diff --git a/test/fake_radio/connector_scenarios_test.dart b/test/fake_radio/connector_scenarios_test.dart index cdd485fb..c6f09a29 100644 --- a/test/fake_radio/connector_scenarios_test.dart +++ b/test/fake_radio/connector_scenarios_test.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:drift/native.dart'; +import 'package:flutter/foundation.dart' show listEquals; import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; @@ -201,10 +202,7 @@ void main() { Future> apply({required bool temporary}) async { final node = nodes[label]!; final target = contact(label); - await connector.sendFrame( - buildSendLoginFrame(target.publicKey, node.adminPassword), - ); - await _until(radio, () => radio.hasAdminSession(node), 'login'); + await _login(connector, radio, target, node.adminPassword); // Built as repeater_settings_screen.dart builds a preset save. final pending = [ temporary @@ -268,10 +266,7 @@ void main() { test('a bad value comes back as the firmware error (#748)', () async { final node = nodes[label]!; final target = contact(label); - await connector.sendFrame( - buildSendLoginFrame(target.publicKey, node.adminPassword), - ); - await _until(radio, () => radio.hasAdminSession(node), 'login'); + await _login(connector, radio, target, node.adminPassword); final service = RepeaterCommandService(connector); addTearDown(service.dispose); final sub = connector.receivedFrames.listen((frame) { @@ -316,6 +311,31 @@ void main() { } } +/// Logs in to [target] the way the app does, and waits until the CLIENT has +/// received LOGIN_SUCCESS for that node, not just until the fake holds a +/// session (MyMesh.cpp:1153: code, permissions, then the 6-byte key prefix). +Future _login( + MeshCoreConnector connector, + FakeRadio radio, + Contact target, + String password, +) async { + var confirmed = false; + final sub = connector.receivedFrames.listen((f) { + if (f.length >= 8 && + f[0] == pushCodeLoginSuccess && + listEquals(f.sublist(2, 8), target.publicKey.sublist(0, 6))) { + confirmed = true; + } + }); + try { + await connector.sendFrame(buildSendLoginFrame(target.publicKey, password)); + await _until(radio, () => confirmed, 'LOGIN_SUCCESS at the client'); + } finally { + await sub.cancel(); + } +} + /// Waits for [done], advancing the fake radio's clock as real time passes so /// ACKs and remote replies arrive. Future _until( diff --git a/test/fake_radio/fake_radio_tcp_test.dart b/test/fake_radio/fake_radio_tcp_test.dart new file mode 100644 index 00000000..4cee65c9 --- /dev/null +++ b/test/fake_radio/fake_radio_tcp_test.dart @@ -0,0 +1,85 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; + +import '../support/fake_radio/fake_radio.dart'; +import '../support/fake_radio/fake_radio_codes.dart'; +import '../support/fake_radio/fake_radio_tcp.dart'; + +// The fake's TCP framing against firmware ArduinoSerialInterface:: +// checkRecvFrame: frames split across reads, a zero length skipped, and a +// frame over MAX_FRAME_SIZE read to its end and cut. + +void main() { + late FakeRadio radio; + late FakeRadioTcpServer server; + late Socket socket; + late StreamController> replies; + late StreamIterator> next; + + setUp(() async { + radio = FakeRadio(); + server = await FakeRadioTcpServer.start(radio); + socket = await Socket.connect(server.host, server.port); + replies = StreamController>(); + next = StreamIterator(replies.stream); + final buf = []; + socket.listen((data) { + buf.addAll(data); + while (buf.length >= 3 && buf.length >= 3 + (buf[1] | buf[2] << 8)) { + final len = buf[1] | buf[2] << 8; + replies.add(buf.sublist(3, 3 + len)); + buf.removeRange(0, 3 + len); + } + }); + }); + + tearDown(() async { + socket.destroy(); + await server.close(); + }); + + List frame(List payload) => [ + 0x3c, + payload.length & 0xFF, + payload.length >> 8, + ...payload, + ]; + + Future> nextReply() async { + expect(await next.moveNext().timeout(const Duration(seconds: 5)), isTrue); + return next.current; + } + + test('a frame split across two writes is put back together', () async { + final f = frame([fwCmdDeviceQuery, 3]); + socket.add(f.sublist(0, 2)); + await socket.flush(); + await Future.delayed(const Duration(milliseconds: 50)); + socket.add(f.sublist(2)); + expect((await nextReply())[0], fwRespDeviceInfo); + }); + + test('a zero-length frame is skipped, and the next one is handled', () async { + socket.add([ + ...frame([]), + ...frame([fwCmdDeviceQuery, 3]), + ]); + expect((await nextReply())[0], fwRespDeviceInfo); + expect(radio.received, hasLength(1)); + }); + + test('a frame over MAX_FRAME_SIZE is read to its end, then cut', () async { + final big = [fwCmdDeviceQuery, 3, ...List.filled(200, 0x41)]; + socket.add([ + ...frame(big), + ...frame([fwCmdGetDeviceTime]), + ]); + expect((await nextReply())[0], fwRespDeviceInfo); + expect((await nextReply())[0], fwRespCurrTime); + expect(radio.received.first, hasLength(maxFrameSize)); + expect(radio.received.first, Uint8List.fromList(big.take(176).toList())); + }); +} diff --git a/test/fake_radio/manifest_contract_test.dart b/test/fake_radio/manifest_contract_test.dart index 66b7501d..080024b1 100644 --- a/test/fake_radio/manifest_contract_test.dart +++ b/test/fake_radio/manifest_contract_test.dart @@ -102,6 +102,26 @@ void main() { expect(_compare(client, offband).unknown, isEmpty); }); + test('no two names reduce to the same comparison key', () { + // `_key` drops case and underscores. If two names collapsed together, + // one of them would never be compared. + List collisions(Iterable names) { + final seen = {}; + return [ + for (final n in names) + if (seen.putIfAbsent(_key(n), () => n) != n) + '$n and ${seen[_key(n)]}', + ]; + } + + expect(collisions(client.keys), isEmpty); + expect( + collisions([for (final s in _sections) ...offband.section(s).keys]), + isEmpty, + ); + expect(collisions(['CMD_FOO_BAR', 'cmdFooBar']), hasLength(1)); + }); + test('a deliberately wrong constant is caught', () { final doctored = Map.of(client) ..['offbandCapCaplog'] = 0x08 diff --git a/test/fake_radio/release_guard_test.dart b/test/fake_radio/release_guard_test.dart index fff2ac15..8ca94e38 100644 --- a/test/fake_radio/release_guard_test.dart +++ b/test/fake_radio/release_guard_test.dart @@ -16,14 +16,18 @@ List forbiddenImports(String source) => [ if (_forbidden(m.group(1)!)) m.group(1)!, ]; -bool _forbidden(String uri) => - uri.contains('fake_radio') || - uri.contains('/test/') || - uri.startsWith('test/') || - uri.contains('../test') || - uri.contains('/tool/') || - uri.startsWith('tool/') || - uri.contains('../tool'); +bool _forbidden(String raw) { + // Windows and macOS resolve paths without regard to case, and a Windows + // path may use backslashes, so compare a folded form. + final uri = raw.toLowerCase().replaceAll(r'\', '/'); + return uri.contains('fake_radio') || + uri.contains('/test/') || + uri.startsWith('test/') || + uri.contains('../test') || + uri.contains('/tool/') || + uri.startsWith('tool/') || + uri.contains('../tool'); +} void main() { test('nothing under lib/ imports the fake radio, test/ or tool/', () { @@ -50,8 +54,10 @@ import 'package:meshcore_open/x/fake_radio_runner.dart'; export '../tool/fake_radio.dart'; part 'test/thing.dart'; import "../services/storage_service.dart"; +import '../../Test/Support/Helpers.dart'; +import '..\\..\\test\\support\\helpers.dart'; '''), - hasLength(4), + hasLength(6), ); }); } diff --git a/test/fake_radio/runner_test.dart b/test/fake_radio/runner_test.dart index b9b59772..12bfaf59 100644 --- a/test/fake_radio/runner_test.dart +++ b/test/fake_radio/runner_test.dart @@ -209,7 +209,7 @@ void main() { addTearDown(proc.kill); final out = proc.stdout.transform(utf8.decoder).asBroadcastStream(); await out - .firstWhere((l) => l.contains('on port $port')) + .firstWhere((l) => l.contains('on 127.0.0.1:$port')) .timeout(const Duration(seconds: 60)); final socket = await Socket.connect(InternetAddress.loopbackIPv4, port); @@ -232,4 +232,30 @@ void main() { }, timeout: const Timeout(Duration(minutes: 2)), ); + + test( + 'a bad seed file stops the runner with a message, not a stack trace', + () async { + final root = Platform.environment['FLUTTER_ROOT']; + if (root == null) { + markTestSkipped('FLUTTER_ROOT not set: not under flutter test'); + return; + } + final bad = + File('${Directory.systemTemp.createTempSync('seed').path}/b.json') + ..writeAsStringSync( + '{"format": "offband-fake-radio-seed", ' + '"format_version": 1, "contacts": [{"name": "A", "key": "11a"}]}', + ); + final result = await Process.run( + '$root/bin/dart${Platform.isWindows ? '.bat' : ''}', + ['run', 'tool/fake_radio.dart', '--seed', bad.path], + runInShell: Platform.isWindows, + ); + expect(result.exitCode, 65, reason: '${result.stdout}${result.stderr}'); + expect('${result.stderr}', contains("can't use ${bad.path}")); + expect('${result.stderr}', isNot(contains('#0 '))); + }, + timeout: const Timeout(Duration(minutes: 2)), + ); } diff --git a/test/support/fake_radio/fake_radio_runner.dart b/test/support/fake_radio/fake_radio_runner.dart index a13809b3..f66b224d 100644 --- a/test/support/fake_radio/fake_radio_runner.dart +++ b/test/support/fake_radio/fake_radio_runner.dart @@ -27,7 +27,9 @@ class FakeRadioRunner { }) async { final server = await FakeRadioTcpServer.start( radio, - address: address ?? InternetAddress.anyIPv4, + // Loopback unless asked: a fake radio need not be reachable from the + // network. + address: address ?? InternetAddress.loopbackIPv4, port: port, ); final ticker = Timer.periodic(tick, (_) => radio.clock.advance(tick)); diff --git a/test/support/fake_radio/fake_radio_tcp.dart b/test/support/fake_radio/fake_radio_tcp.dart index aa6f38fc..72ca1f2b 100644 --- a/test/support/fake_radio/fake_radio_tcp.dart +++ b/test/support/fake_radio/fake_radio_tcp.dart @@ -14,6 +14,10 @@ import 'fake_radio.dart'; const int _appToRadioStart = 0x3c; const int _radioToAppStart = 0x3e; +/// `MAX_FRAME_SIZE` (src/helpers/BaseSerialInterface.h:5 at +/// offband-v1.5.0-beta7). +const int maxFrameSize = 176; + /// The fake radio on a TCP port, for the client's real `connectTcp` path and /// for the desktop app (#768, #780). class FakeRadioTcpServer { @@ -74,8 +78,13 @@ class FakeRadioTcpServer { if (buffer.length < 3) return; final len = buffer[1] | (buffer[2] << 8); if (buffer.length < 3 + len) return; - final payload = Uint8List.fromList(buffer.sublist(3, 3 + len)); + // ArduinoSerialInterface::checkRecvFrame: a zero length is skipped, + // and a frame over MAX_FRAME_SIZE is read to its end, then cut. + final payload = Uint8List.fromList( + buffer.sublist(3, 3 + (len > maxFrameSize ? maxFrameSize : len)), + ); buffer.removeRange(0, 3 + len); + if (len == 0) continue; for (final reply in radio.handle(payload)) { socket.add(_wrap(reply)); } diff --git a/tool/fake_radio.dart b/tool/fake_radio.dart index 213128d6..002c425d 100644 --- a/tool/fake_radio.dart +++ b/tool/fake_radio.dart @@ -5,19 +5,22 @@ // dart run tool/fake_radio.dart --profile stock --seed my-mesh.json // dart run tool/fake_radio.dart --seed test/fake_radio/traces/rak.json // -// Then in the app: connect over TCP to this PC's address, port 5000. Seed -// files and console commands: tool/fake_radio/README.md. Test code only: it -// lives under test/ and tool/ and never ships in the app. +// Then in the app on the same PC: connect over TCP to 127.0.0.1, port 5000. +// For a phone on the network, add --host 0.0.0.0. Seed files and console +// commands: tool/fake_radio/README.md. Test code only: it lives under test/ +// and tool/ and never ships in the app. import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import '../test/support/fake_radio/fake_radio.dart'; import '../test/support/fake_radio/fake_radio_runner.dart'; Future main(List args) async { var profile = 'offband'; var port = 5000; + var host = InternetAddress.loopbackIPv4; String? seed; for (var i = 0; i < args.length; i++) { switch (args[i]) { @@ -25,22 +28,36 @@ Future main(List args) async { profile = args[++i]; case '--port' when i + 1 < args.length: port = int.parse(args[++i]); + case '--host' when i + 1 < args.length: + host = InternetAddress(args[++i]); case '--seed' when i + 1 < args.length: seed = args[++i]; default: stderr.writeln( - 'usage: dart run tool/fake_radio.dart ' - '[--profile offband|stock] [--port 5000] [--seed file.json]', + 'usage: dart run tool/fake_radio.dart [--profile offband|stock] ' + '[--port 5000] [--host 127.0.0.1] [--seed file.json]', ); exit(64); } } - final radio = fakeRadioFromFile(seed, profile: profile); - final runner = await FakeRadioRunner.start(radio: radio, port: port); + final FakeRadio radio; + try { + radio = fakeRadioFromFile(seed, profile: profile); + } on Object catch (e) { + // A bad seed file: say what is wrong, not a stack trace. + stderr.writeln('can\'t use ${seed ?? 'the built-in seed'}: $e'); + exit(65); + } + final runner = await FakeRadioRunner.start( + radio: radio, + address: host, + port: port, + ); stdout.writeln( - 'Fake radio "${radio.name}" (${radio.profile.name}) on port ' - '${runner.server.port}. ${radio.contacts.length} contact(s), ' + 'Fake radio "${radio.name}" (${radio.profile.name}) on ' + '${runner.server.host}:${runner.server.port}. ' + '${radio.contacts.length} contact(s), ' '${radio.channels.length} channel(s). Type "help" for commands.', ); diff --git a/tool/fake_radio/README.md b/tool/fake_radio/README.md index d3096882..72dd57ad 100644 --- a/tool/fake_radio/README.md +++ b/tool/fake_radio/README.md @@ -10,7 +10,7 @@ From the repo root: dart run tool/fake_radio.dart --profile offband --port 5000 ``` -In the app, connect over TCP to this PC's address (`127.0.0.1` on the same machine) and port `5000`. +In the app on the same PC, connect over TCP to `127.0.0.1`, port `5000`. It listens only on this PC unless you add `--host 0.0.0.0`, which lets a phone on the same network connect to this PC's address. Use the Dart that comes with the Flutter SDK this repo builds with. An older Dart fails before the radio starts, with an error about native assets. @@ -18,6 +18,7 @@ Use the Dart that comes with the Flutter SDK this repo builds with. An older Dar |---|---|---| | `--profile` | `offband` | `offband` (pinned to `offband-v1.5.0-beta7`) or `stock` (MeshCore `companion-v1.18.0`) | | `--port` | `5000` | TCP port | +| `--host` | `127.0.0.1` | address to listen on; `0.0.0.0` for every network interface | | `--seed` | built-in | a seed file (below) or a captured trace | The radio's clock follows real time, so ACKs and remote-node replies arrive on their own. diff --git a/tool/fake_radio/gen_protocol_manifest.py b/tool/fake_radio/gen_protocol_manifest.py index d756a128..d26f050a 100644 --- a/tool/fake_radio/gen_protocol_manifest.py +++ b/tool/fake_radio/gen_protocol_manifest.py @@ -39,8 +39,36 @@ def show(repo, ref, path): return out.stdout +PROTOCOL = re.compile(r"(CMD_|RESP_CODE_|PUSH_CODE_|ERR_CODE_|OFFBAND_)") + + +def conditional_definitions(text): + """Protocol definitions inside #if/#ifdef/#ifndef. Reading source with + regexes can't tell which branch a build takes, so the manifest would be + wrong for some build; refuse instead of guessing.""" + depth, found = 0, [] + for n, line in enumerate(text.splitlines(), 1): + s = line.strip() + if re.match(r"#\s*if", s): + depth += 1 + elif re.match(r"#\s*endif", s): + depth -= 1 + elif depth > 0: + m = DEFINE.match(s) or CONSTEXPR.match(s) + if m and PROTOCOL.match(m.group(1)): + found.append(f"line {n}: {m.group(1)}") + return found + + def pick(pairs, prefix): - return {name: int(value, 0) for name, value in pairs if name.startswith(prefix)} + out = {} + for name, value in pairs: + if not name.startswith(prefix): + continue + if name in out and out[name] != int(value, 0): + sys.exit(f"{name} is defined twice with different values") + out[name] = int(value, 0) + return out def main(): @@ -67,6 +95,12 @@ def main(): if offband is None: sys.exit("offband flavor but OffbandConfigProtocol.h is missing") pairs += CONSTEXPR.findall(offband) + DEFINE.findall(offband) + for name, text in [("MyMesh.cpp", source)] + ( + [("OffbandConfigProtocol.h", offband)] if args.flavor == "offband" else [] + ): + found = conditional_definitions(text) + if found: + sys.exit(f"{name} defines protocol codes inside #if: {', '.join(found)}") commands = pick(pairs, "CMD_") responses = pick(pairs, "RESP_CODE_")