From 6848535fc598fe941313fe2e1a9ad8260679e449 Mon Sep 17 00:00:00 2001 From: Losminek Date: Wed, 2 Dec 2026 17:31:37 +0100 Subject: [PATCH] NetKit 2.0.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Widgety a zkratky, SSH na pozadí se SFTP, tunely a ProxyJump, Telnet a USB konzole, iperf3, nové síťové nástroje, sdílení výsledků, zámek SSH a záloha konfigurace. Verze 2.0.0 (versionCode 20000), CHANGELOG. Licence Unicode V3 pro tabulku šířky znaků terminálu (NOTICE, O aplikaci). Čistý export z vývojového repa, strom 5294a26126ddb5d4a5383ac2230fcdf875ca76bd. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EVL2LqxuMXLEZw3WX1KDCm --- .github/workflows/release.yml | 2 + CHANGELOG.md | 44 ++ CLAUDE.md | 4 +- NOTICE | 23 +- README.cs.md | 10 +- README.md | 10 +- androidApp/build.gradle.kts | 102 ++- androidApp/lint.xml | 8 + .../netkit/app/test/AccessibilityEvidence.kt | 224 ++++++ .../cz/netkit/app/test/BackupEvidence.kt | 170 ++++ .../cz/netkit/app/test/CellDetailEvidence.kt | 121 +++ .../netkit/app/test/LanRozsireniEvidence.kt | 331 ++++++++ .../netkit/app/test/LandscapeMloEvidence.kt | 213 +++++ .../cz/netkit/app/test/M1Instrumentation.kt | 202 ++++- .../app/test/NetStatusWidgetEvidence.kt | 264 +++++++ .../netkit/app/test/ShareResultsEvidence.kt | 280 +++++++ .../app/test/SshBackgroundSftpEvidence.kt | 573 ++++++++++++++ .../cz/netkit/app/test/SshLockEvidence.kt | 139 ++++ .../app/test/SshProductivityEvidence.kt | 345 +++++++++ .../netkit/app/test/SshProfilesV2Evidence.kt | 17 +- .../cz/netkit/app/test/SshXtermEvidence.kt | 103 +++ .../netkit/app/test/SystemSettingsEvidence.kt | 524 +++++++++++++ .../cz/netkit/app/test/ToolTargetsEvidence.kt | 222 ++++++ .../netkit/app/test/WifiExtensionsEvidence.kt | 383 +++++++++ .../netkit/app/test/WifiSpectrumEvidence.kt | 202 +++++ .../app/test/WolWidgetIntentEvidence.kt | 130 ++++ androidApp/src/dev/res/xml/shortcuts.xml | 33 + androidApp/src/main/AndroidManifest.xml | 90 ++- .../src/main/assets/licenses/NOTICE.txt | 23 +- .../src/main/assets/licenses/components.json | 67 +- .../main/assets/licenses/protobuf-LICENSE.txt | 32 + .../main/assets/licenses/unicode-LICENSE.txt | 45 ++ .../usb-serial-for-android-LICENSE.txt | 22 + .../usbserial/driver/CdcAcmSerialDriver.java | 451 +++++++++++ .../usbserial/driver/Ch34xSerialDriver.java | 412 ++++++++++ .../usbserial/driver/CommonUsbSerialPort.java | 438 +++++++++++ .../usbserial/driver/Cp21xxSerialDriver.java | 412 ++++++++++ .../usbserial/driver/FtdiSerialDriver.java | 478 ++++++++++++ .../driver/ProlificSerialDriver.java | 605 +++++++++++++++ .../driver/SerialTimeoutException.java | 16 + .../hoho/android/usbserial/driver/UsbId.java | 56 ++ .../usbserial/driver/UsbSerialDriver.java | 38 + .../usbserial/driver/UsbSerialPort.java | 341 ++++++++ .../hoho/android/usbserial/util/HexDump.java | 158 ++++ .../usbserial/util/MonotonicClock.java | 14 + .../hoho/android/usbserial/util/UsbUtils.java | 37 + .../main/kotlin/cz/netkit/app/MainActivity.kt | 251 +++++- .../cz/netkit/app/backup/BackupCrypto.kt | 47 ++ .../cz/netkit/app/backup/BackupRepository.kt | 104 +++ .../cz/netkit/app/backup/BackupScreen.kt | 192 +++++ .../cz/netkit/app/backup/BackupViewModel.kt | 141 ++++ .../cz/netkit/app/backup/RestoreFiles.kt | 162 ++++ .../app/cellular/CellDetailViewModel.kt | 101 +++ .../cz/netkit/app/cellular/CellInfoReader.kt | 125 +++ .../kotlin/cz/netkit/app/lan/DevicesExport.kt | 114 +++ .../kotlin/cz/netkit/app/lan/DevicesScreen.kt | 194 ++++- .../cz/netkit/app/lan/DiagnosticLookup.kt | 94 +++ .../cz/netkit/app/lan/DiagnosticPanel.kt | 128 +++ .../kotlin/cz/netkit/app/lan/DnsLookup.kt | 24 + .../kotlin/cz/netkit/app/lan/LanBackend.kt | 90 ++- .../cz/netkit/app/lan/LanDeviceNetwork.kt | 42 +- .../cz/netkit/app/lan/LanDevicesViewModel.kt | 134 +++- .../kotlin/cz/netkit/app/lan/LanIpv6Tools.kt | 121 +++ .../kotlin/cz/netkit/app/lan/LanScreen.kt | 194 ++++- .../cz/netkit/app/lan/LanToolPreferences.kt | 55 ++ .../kotlin/cz/netkit/app/lan/LanViewModel.kt | 399 ++++++++-- .../cz/netkit/app/lan/MacVendorPanel.kt | 110 +++ .../cz/netkit/app/lan/NetworkInfoCard.kt | 64 ++ .../kotlin/cz/netkit/app/lan/PingOptions.kt | 76 ++ .../kotlin/cz/netkit/app/lan/ServicesPanel.kt | 123 +++ .../kotlin/cz/netkit/app/lan/SubnetPanel.kt | 107 +++ .../kotlin/cz/netkit/app/lan/TargetHistory.kt | 134 ++++ .../kotlin/cz/netkit/app/lan/TracePath.kt | 28 + .../cz/netkit/app/lan/UdpServiceProbe.kt | 91 +++ .../kotlin/cz/netkit/app/lan/WebDiagnostic.kt | 369 +++++++++ .../main/kotlin/cz/netkit/app/lan/WifiIcmp.kt | 87 ++- .../kotlin/cz/netkit/app/lan/WifiIcmp6.kt | 95 +++ .../kotlin/cz/netkit/app/nav/AppShortcuts.kt | 90 +++ .../cz/netkit/app/net/ActiveNetworkMonitor.kt | 11 +- .../netkit/app/netstatus/NetStatusService.kt | 209 +++++ .../netkit/app/netstatus/NetStatusWidget.kt | 311 ++++++++ .../NetStatusWidgetConfigActivity.kt | 161 ++++ .../netkit/app/overview/CellDetailSection.kt | 253 ++++++ .../app/overview/DiagnosticReportDialog.kt | 241 ++++++ .../app/overview/DiagnosticReportViewModel.kt | 189 +++++ .../cz/netkit/app/overview/OverviewCards.kt | 55 +- .../kotlin/cz/netkit/app/overview/PathCard.kt | 14 +- .../netkit/app/publicip/PublicIpRepository.kt | 7 +- .../netkit/app/settings/AppLanguageSystem.kt | 74 ++ .../cz/netkit/app/settings/OwnedOperation.kt | 13 + .../cz/netkit/app/settings/SettingsHost.kt | 42 + .../cz/netkit/app/settings/SettingsScreen.kt | 271 +++++++ .../cz/netkit/app/settings/SettingsStore.kt | 48 ++ .../netkit/app/settings/SettingsViewModel.kt | 60 ++ .../cz/netkit/app/speed/Iperf3Client.kt | 223 ++++++ .../kotlin/cz/netkit/app/speed/Iperf3Form.kt | 59 ++ .../kotlin/cz/netkit/app/speed/SignalHost.kt | 8 +- .../kotlin/cz/netkit/app/speed/SpeedDial.kt | 4 +- .../kotlin/cz/netkit/app/speed/SpeedHttp.kt | 2 +- .../kotlin/cz/netkit/app/speed/SpeedShare.kt | 97 +++ .../cz/netkit/app/speed/SpeedTestScreen.kt | 154 +++- .../cz/netkit/app/speed/SpeedTestViewModel.kt | 189 ++++- .../cz/netkit/app/ssh/ConsoleConnection.kt | 165 ++++ .../cz/netkit/app/ssh/ConsoleProfileUi.kt | 133 ++++ .../cz/netkit/app/ssh/JschConnection.kt | 253 ++++-- .../kotlin/cz/netkit/app/ssh/SftpClient.kt | 201 +++++ .../cz/netkit/app/ssh/SftpController.kt | 264 +++++++ .../main/kotlin/cz/netkit/app/ssh/SftpRun.kt | 94 +++ .../kotlin/cz/netkit/app/ssh/SftpScreen.kt | 211 +++++ .../kotlin/cz/netkit/app/ssh/SshAccess.kt | 72 ++ .../kotlin/cz/netkit/app/ssh/SshForwarders.kt | 254 ++++++ .../kotlin/cz/netkit/app/ssh/SshLockUi.kt | 132 ++++ .../cz/netkit/app/ssh/SshProductivityUi.kt | 316 ++++++++ .../app/ssh/SshProfileImportController.kt | 11 +- .../cz/netkit/app/ssh/SshProfileImportUi.kt | 35 +- .../kotlin/cz/netkit/app/ssh/SshScreen.kt | 580 ++++++++++---- .../kotlin/cz/netkit/app/ssh/SshSessionLog.kt | 165 ++++ .../cz/netkit/app/ssh/SshSessionService.kt | 199 +++++ .../kotlin/cz/netkit/app/ssh/SshStorage.kt | 3 +- .../kotlin/cz/netkit/app/ssh/SshViewModel.kt | 315 ++++++-- .../kotlin/cz/netkit/app/ssh/UsbConsole.kt | 194 +++++ .../cz/netkit/app/tile/SignalTileService.kt | 48 ++ .../kotlin/cz/netkit/app/ui/Components.kt | 137 ++-- .../kotlin/cz/netkit/app/ui/KeepScreenOn.kt | 36 + .../kotlin/cz/netkit/app/ui/NetKitIcons.kt | 14 + .../kotlin/cz/netkit/app/ui/RunSummary.kt | 90 +++ .../kotlin/cz/netkit/app/ui/ShareActions.kt | 95 +++ .../cz/netkit/app/ui/about/AboutScreen.kt | 30 +- .../cz/netkit/app/ui/chart/FullscreenChart.kt | 11 +- .../cz/netkit/app/ui/chart/TimeSeriesChart.kt | 32 +- .../kotlin/cz/netkit/app/ui/theme/Theme.kt | 3 + .../kotlin/cz/netkit/app/update/UpdateCard.kt | 6 +- .../cz/netkit/app/update/UpdateChecker.kt | 3 - .../cz/netkit/app/wifi/ExportSession.kt | 53 ++ .../cz/netkit/app/wifi/SpectrumChart.kt | 159 +++- .../cz/netkit/app/wifi/WifiExportFiles.kt | 135 ++++ .../cz/netkit/app/wifi/WifiScanBudget.kt | 8 +- .../cz/netkit/app/wifi/WifiScanLimitHelp.kt | 3 +- .../kotlin/cz/netkit/app/wifi/WifiScreen.kt | 292 +++++-- .../cz/netkit/app/wifi/WifiViewModel.kt | 50 ++ .../cz/netkit/app/wifi/live/MloReader.kt | 50 ++ .../cz/netkit/app/wifi/live/SignalScreen.kt | 158 +++- .../cz/netkit/app/wifi/live/WalkCard.kt | 180 +++++ .../cz/netkit/app/wifi/live/WifiLiveState.kt | 18 + .../netkit/app/wifi/live/WifiLiveViewModel.kt | 138 +++- .../cz/netkit/app/wol/AndroidNetwork.kt | 4 +- .../kotlin/cz/netkit/app/wol/DeviceStore.kt | 3 +- .../kotlin/cz/netkit/app/wol/UdpTransport.kt | 58 +- .../kotlin/cz/netkit/app/wol/WolScreen.kt | 78 +- .../cz/netkit/app/wol/WolSecureOnStorage.kt | 53 ++ .../kotlin/cz/netkit/app/wol/WolViewModel.kt | 86 +- .../cz/netkit/app/wol/widget/WolWidget.kt | 308 ++++++++ .../app/wol/widget/WolWidgetConfigActivity.kt | 118 +++ .../main/res/drawable/ic_notification_ssh.xml | 11 + .../res/drawable/ic_shortcut_background.xml | 6 + .../main/res/drawable/ic_shortcut_ping.xml | 5 + .../drawable/ic_shortcut_ping_foreground.xml | 17 + .../main/res/drawable/ic_shortcut_signal.xml | 5 + .../ic_shortcut_signal_foreground.xml | 14 + .../res/drawable/ic_shortcut_spectrum.xml | 5 + .../ic_shortcut_spectrum_foreground.xml | 13 + .../src/main/res/drawable/ic_shortcut_ssh.xml | 5 + .../drawable/ic_shortcut_ssh_foreground.xml | 13 + .../main/res/drawable/ic_shortcut_subnet.xml | 5 + .../ic_shortcut_subnet_foreground.xml | 15 + .../src/main/res/drawable/ic_shortcut_wol.xml | 5 + .../drawable/ic_shortcut_wol_foreground.xml | 11 + .../src/main/res/drawable/ic_tile_signal.xml | 12 + .../main/res/drawable/ic_widget_refresh.xml | 9 + .../src/main/res/layout/netstatus_age.xml | 10 + androidApp/src/main/res/resources.properties | 1 + .../src/main/res/values-en/accessibility.xml | 24 + androidApp/src/main/res/values-en/backup.xml | 40 + .../src/main/res/values-en/cellular.xml | 24 + .../src/main/res/values-en/lan_rozsireni.xml | 45 ++ androidApp/src/main/res/values-en/lan_wol.xml | 12 + .../main/res/values-en/netstatus_widget.xml | 42 + .../src/main/res/values-en/settings.xml | 50 ++ androidApp/src/main/res/values-en/sharing.xml | 84 ++ .../src/main/res/values-en/shortcuts.xml | 17 + .../src/main/res/values-en/speedtest.xml | 28 +- .../res/values-en/ssh_background_sftp.xml | 66 ++ .../src/main/res/values-en/ssh_console.xml | 43 + .../src/main/res/values-en/ssh_design.xml | 2 + .../src/main/res/values-en/ssh_import.xml | 6 +- .../main/res/values-en/ssh_productivity.xml | 86 ++ .../src/main/res/values-en/ssh_terminal.xml | 5 + androidApp/src/main/res/values-en/strings.xml | 4 +- .../src/main/res/values-en/strings_lan.xml | 123 ++- .../src/main/res/values-en/strings_ssh.xml | 13 +- .../src/main/res/values-en/strings_wifi.xml | 6 +- .../src/main/res/values-en/tools_targets.xml | 46 ++ .../src/main/res/values-en/wifi_ext.xml | 67 ++ .../src/main/res/values-en/wifi_signal.xml | 8 + .../src/main/res/values-en/wifi_spectrum.xml | 3 + .../src/main/res/values-en/wol_secureon.xml | 13 + .../src/main/res/values-en/wol_widget.xml | 19 + .../values-night/netstatus_widget_colors.xml | 5 + .../src/main/res/values/accessibility.xml | 25 + androidApp/src/main/res/values/backup.xml | 40 + androidApp/src/main/res/values/cellular.xml | 32 + androidApp/src/main/res/values/ids.xml | 2 + .../src/main/res/values/lan_rozsireni.xml | 45 ++ androidApp/src/main/res/values/lan_wol.xml | 13 + .../src/main/res/values/netstatus_widget.xml | 42 + .../res/values/netstatus_widget_colors.xml | 5 + androidApp/src/main/res/values/settings.xml | 62 ++ androidApp/src/main/res/values/sharing.xml | 84 ++ androidApp/src/main/res/values/shortcuts.xml | 20 + androidApp/src/main/res/values/speedtest.xml | 28 +- .../main/res/values/ssh_background_sftp.xml | 72 ++ .../src/main/res/values/ssh_console.xml | 43 + androidApp/src/main/res/values/ssh_design.xml | 2 + androidApp/src/main/res/values/ssh_import.xml | 4 +- .../src/main/res/values/ssh_productivity.xml | 93 +++ .../src/main/res/values/ssh_terminal.xml | 5 + androidApp/src/main/res/values/strings.xml | 4 +- .../src/main/res/values/strings_lan.xml | 125 ++- .../src/main/res/values/strings_ssh.xml | 13 +- .../src/main/res/values/strings_wifi.xml | 15 +- .../src/main/res/values/tools_targets.xml | 46 ++ androidApp/src/main/res/values/wifi_ext.xml | 75 ++ .../src/main/res/values/wifi_signal.xml | 8 + .../src/main/res/values/wifi_spectrum.xml | 3 + .../src/main/res/values/wol_secureon.xml | 13 + androidApp/src/main/res/values/wol_widget.xml | 20 + .../main/res/xml/netstatus_widget_info.xml | 21 + androidApp/src/main/res/xml/shortcuts.xml | 33 + .../src/main/res/xml/wol_widget_info.xml | 20 + .../cz/netkit/app/backup/BackupCryptoTest.kt | 34 + .../netkit/app/backup/BackupRepositoryTest.kt | 66 ++ .../cz/netkit/app/backup/RestoreFilesTest.kt | 78 ++ .../cz/netkit/app/lan/DiagnosticLookupTest.kt | 113 +++ .../kotlin/cz/netkit/app/lan/DnsLookupTest.kt | 40 + .../cz/netkit/app/lan/LanIpv6ToolsTest.kt | 110 +++ .../app/lan/LanNetworkInfoRefreshTest.kt | 22 + .../netkit/app/lan/LanToolPreferencesTest.kt | 88 +++ .../cz/netkit/app/lan/PingOptionsTest.kt | 130 ++++ .../kotlin/cz/netkit/app/lan/TracePathTest.kt | 52 ++ .../netkit/app/lan/UdpServicesFixtureTest.kt | 89 +++ .../cz/netkit/app/lan/WebDiagnosticTest.kt | 516 ++++++++++++ .../cz/netkit/app/nav/ManifestExportsTest.kt | 182 +++++ .../netkit/app/nav/ShortcutResourcesTest.kt | 74 ++ .../app/netstatus/NetStatusWidgetTest.kt | 89 +++ .../app/overview/DiagnosticReportInputTest.kt | 121 +++ .../app/settings/CzechLocaleResourcesTest.kt | 59 ++ .../netkit/app/settings/OwnedOperationTest.kt | 75 ++ .../netkit/app/settings/SettingsStoreTest.kt | 59 ++ .../cz/netkit/app/speed/Iperf3ClientTest.kt | 312 ++++++++ .../cz/netkit/app/ssh/ProfileEditorTest.kt | 42 + .../netkit/app/ssh/SessionNotificationTest.kt | 21 + .../kotlin/cz/netkit/app/ssh/SftpRunTest.kt | 104 +++ .../netkit/app/ssh/SshProductivityJvmTest.kt | 281 +++++++ .../app/ssh/SshProfileImportControllerTest.kt | 33 +- .../netkit/app/ssh/TelnetConsoleWireTest.kt | 37 + .../cz/netkit/app/ssh/UsbConsoleWireTest.kt | 166 ++++ .../cz/netkit/app/ui/AccessibilityTest.kt | 116 +++ .../netkit/app/ui/about/OssComponentsTest.kt | 10 +- .../cz/netkit/app/wifi/ExportSessionTest.kt | 101 +++ .../netkit/app/wifi/SpectrumAxisLabelsTest.kt | 50 ++ .../app/wifi/live/LiveRadioSourceTest.kt | 13 + .../cz/netkit/app/wifi/live/WalkCardTest.kt | 15 + .../cz/netkit/app/wol/UdpTransportTest.kt | 30 +- docs/architektura.md | 45 +- docs/bezpecnost.md | 574 +++++++++++++- docs/design.md | 42 +- docs/funkce/lan-scanner.md | 185 ++++- docs/funkce/mobilni-sit.md | 42 +- docs/funkce/nastaveni.md | 107 +++ docs/funkce/speedtest.md | 61 +- docs/funkce/ssh.md | 202 ++++- docs/funkce/wifi-analyzer.md | 146 +++- docs/funkce/wol.md | 90 ++- docs/licenses/protobuf-LICENSE.txt | 32 + docs/licenses/unicode-LICENSE.txt | 39 + .../usb-serial-for-android-LICENSE.txt | 22 + docs/plan.md | 6 +- docs/project-license-inventory.tsv | 42 + docs/public-license-verification.tsv | 42 + docs/public/data-safety-podklad.md | 38 +- docs/public/data-toky.md | 28 +- docs/public/privacy-cs.md | 132 +++- docs/public/privacy-en.md | 136 +++- docs/publikace-play.md | 26 +- docs/testovani.md | 500 +++++++++++- docs/zavislosti.md | 281 +++++++ gradle/libs.versions.toml | 13 + gradle/verification-metadata.xml | 438 +++++++++++ iosApp/NetKit/Localizable.xcstrings | 16 + iosApp/NetKit/OpenSourceLicenses.txt | 48 ++ iosApp/NetKit/SshView.swift | 1 + iosApp/NetKit/SshViewModel.swift | 4 +- iosApp/NetKitTests/LanTests.swift | 2 +- iosApp/NetKitTests/NetKitTests.swift | 3 +- .../NetKitTests/SshMetadataStoreTests.swift | 16 + .../shared/backup/ConfigurationBackup.kt | 159 ++++ .../cz/netkit/shared/backup/RestorePlan.kt | 111 +++ .../cz/netkit/shared/cellular/CellDetail.kt | 359 +++++++++ .../cz/netkit/shared/lan/ConsentResetGate.kt | 35 + .../kotlin/cz/netkit/shared/lan/DnsMessage.kt | 76 +- .../kotlin/cz/netkit/shared/lan/DnsRcode.kt | 26 + .../kotlin/cz/netkit/shared/lan/DnsRecords.kt | 103 +++ .../kotlin/cz/netkit/shared/lan/IcmpEcho.kt | 28 +- .../kotlin/cz/netkit/shared/lan/Ipv6.kt | 167 ++++ .../cz/netkit/shared/lan/LanDeviceExport.kt | 131 ++++ .../kotlin/cz/netkit/shared/lan/LanDevices.kt | 8 +- .../kotlin/cz/netkit/shared/lan/LanDomain.kt | 26 +- .../cz/netkit/shared/lan/LanNetworkInfo.kt | 81 ++ .../kotlin/cz/netkit/shared/lan/LanPolicy.kt | 4 +- .../kotlin/cz/netkit/shared/lan/LanWol.kt | 52 ++ .../cz/netkit/shared/lan/MacAddressTable.kt | 124 +++ .../cz/netkit/shared/lan/NetBiosParser.kt | 20 +- .../kotlin/cz/netkit/shared/lan/NtpPacket.kt | 51 ++ .../kotlin/cz/netkit/shared/lan/SnmpBer.kt | 180 +++++ .../cz/netkit/shared/lan/SubnetCalculator.kt | 86 ++ .../kotlin/cz/netkit/shared/lan/TcpPing.kt | 33 + .../cz/netkit/shared/lan/ToolTargets.kt | 140 ++++ .../cz/netkit/shared/lan/UdpServices.kt | 121 +++ .../cz/netkit/shared/lan/VersionBind.kt | 29 + .../netkit/shared/nav/AdaptiveNavigation.kt | 9 + .../kotlin/cz/netkit/shared/nav/AppTarget.kt | 130 ++++ .../cz/netkit/shared/netstatus/NetStatus.kt | 222 ++++++ .../shared/netstatus/NetStatusRecorder.kt | 131 ++++ .../shared/netstatus/NetStatusRefresh.kt | 72 ++ .../netkit/shared/netstatus/NetStatusView.kt | 90 +++ .../cz/netkit/shared/publicip/PublicIp.kt | 6 +- .../kotlin/cz/netkit/shared/publicip/Rdap.kt | 108 +++ .../netkit/shared/report/DiagnosticReport.kt | 312 ++++++++ .../cz/netkit/shared/report/ReportText.kt | 182 +++++ .../cz/netkit/shared/settings/AppSettings.kt | 97 +++ .../cz/netkit/shared/speed/Iperf3Protocol.kt | 168 ++++ .../netkit/shared/speed/SpeedDataEstimate.kt | 32 +- .../cz/netkit/shared/speed/SpeedHistory.kt | 37 +- .../cz/netkit/shared/ssh/ConsoleProfile.kt | 38 + .../cz/netkit/shared/ssh/ProfileDirectory.kt | 58 ++ .../kotlin/cz/netkit/shared/ssh/Sftp.kt | 70 ++ .../kotlin/cz/netkit/shared/ssh/Socks5.kt | 144 ++++ .../netkit/shared/ssh/SshBackgroundPolicy.kt | 22 +- .../cz/netkit/shared/ssh/SshForwarding.kt | 69 ++ .../kotlin/cz/netkit/shared/ssh/SshModels.kt | 47 +- .../netkit/shared/ssh/SshProfileExchange.kt | 16 + .../cz/netkit/shared/ssh/SshProfileImport.kt | 195 ++++- .../cz/netkit/shared/ssh/SshSnippets.kt | 73 ++ .../kotlin/cz/netkit/shared/ssh/SshUnlock.kt | 28 + .../cz/netkit/shared/ssh/TelnetCodec.kt | 120 +++ .../cz/netkit/shared/ssh/TerminalBuffer.kt | 733 ++++++++++++++---- .../cz/netkit/shared/ssh/TerminalInput.kt | 16 + .../cz/netkit/shared/ssh/TerminalLog.kt | 133 ++++ .../cz/netkit/shared/ssh/TerminalPalette.kt | 64 ++ .../cz/netkit/shared/ssh/TerminalWidth.kt | 124 +++ .../kotlin/cz/netkit/shared/wifi/EssGroups.kt | 87 +++ .../kotlin/cz/netkit/shared/wifi/Mlo.kt | 47 ++ .../cz/netkit/shared/wifi/RegionalRaster.kt | 45 ++ .../kotlin/cz/netkit/shared/wifi/Spectrum.kt | 109 ++- .../cz/netkit/shared/wifi/SpectrumPins.kt | 86 ++ .../kotlin/cz/netkit/shared/wifi/WalkLog.kt | 317 ++++++++ .../cz/netkit/shared/wifi/WifiDomain.kt | 88 ++- .../cz/netkit/shared/wifi/WifiScanExport.kt | 172 ++++ .../cz/netkit/shared/wol/WolController.kt | 256 +++++- .../kotlin/cz/netkit/shared/wol/WolDomain.kt | 21 + .../kotlin/cz/netkit/shared/wol/WolModels.kt | 33 +- .../cz/netkit/shared/wol/WolSecureOn.kt | 94 +++ .../cz/netkit/shared/wol/WolTransfer.kt | 2 +- .../kotlin/cz/netkit/shared/wol/WolWake.kt | 115 +++ .../cz/netkit/shared/wol/WolWidgetModel.kt | 205 +++++ .../cz/netkit/shared/wol/WolWidgetRun.kt | 136 ++++ .../shared/backup/ConfigurationBackupTest.kt | 173 +++++ .../netkit/shared/cellular/CellDetailTest.kt | 277 +++++++ .../netkit/shared/lan/ConsentResetGateTest.kt | 65 ++ .../cz/netkit/shared/lan/DnsRcodeTest.kt | 13 + .../cz/netkit/shared/lan/DnsRecordsTest.kt | 54 ++ .../cz/netkit/shared/lan/Icmpv6EchoTest.kt | 31 + .../kotlin/cz/netkit/shared/lan/Ipv6Test.kt | 83 ++ .../netkit/shared/lan/LanDeviceExportTest.kt | 57 ++ .../netkit/shared/lan/LanNetworkInfoTest.kt | 56 ++ .../cz/netkit/shared/lan/LanRevisionTest.kt | 10 + .../kotlin/cz/netkit/shared/lan/LanWolTest.kt | 81 ++ .../netkit/shared/lan/MacAddressTableTest.kt | 116 +++ .../netkit/shared/lan/ManagementPortsTest.kt | 14 + .../cz/netkit/shared/lan/NetBiosParserTest.kt | 33 +- .../netkit/shared/lan/SubnetCalculatorTest.kt | 84 ++ .../cz/netkit/shared/lan/TcpPingTest.kt | 42 + .../cz/netkit/shared/lan/ToolTargetsTest.kt | 90 +++ .../netkit/shared/lan/UdpServicesCodecTest.kt | 200 +++++ .../shared/nav/AdaptiveNavigationTest.kt | 21 + .../cz/netkit/shared/nav/AppTargetTest.kt | 89 +++ .../netkit/shared/netstatus/NetStatusTest.kt | 317 ++++++++ .../shared/netstatus/NetStatusViewTest.kt | 97 +++ .../cz/netkit/shared/publicip/RdapTest.kt | 36 + .../shared/report/DiagnosticReportTest.kt | 263 +++++++ .../netkit/shared/settings/AppSettingsTest.kt | 84 ++ .../netkit/shared/speed/Iperf3ProtocolTest.kt | 110 +++ .../shared/speed/SpeedDataEstimateTest.kt | 58 +- .../shared/speed/SpeedHistoryClearTest.kt | 52 ++ .../kotlin/cz/netkit/shared/ssh/SftpTest.kt | 59 ++ .../shared/ssh/SshBackgroundPolicyTest.kt | 32 + .../cz/netkit/shared/ssh/SshDirectoryTest.kt | 102 +++ .../shared/ssh/SshExportProductivityTest.kt | 177 +++++ .../netkit/shared/ssh/SshProductivityTest.kt | 270 +++++++ .../netkit/shared/ssh/SshProfileImportTest.kt | 12 +- .../cz/netkit/shared/ssh/TelnetConsoleTest.kt | 79 ++ .../cz/netkit/shared/ssh/TerminalInputTest.kt | 11 + .../cz/netkit/shared/ssh/TerminalXtermTest.kt | 304 ++++++++ .../netkit/shared/wifi/BondingCenterTest.kt | 125 +++ .../kotlin/cz/netkit/shared/wifi/MloTest.kt | 58 ++ .../cz/netkit/shared/wifi/SpectrumTest.kt | 61 +- .../cz/netkit/shared/wifi/WalkLogTest.kt | 164 ++++ .../netkit/shared/wifi/WifiExtensionsTest.kt | 229 ++++++ .../cz/netkit/shared/wol/WolSecureOnTest.kt | 383 +++++++++ .../cz/netkit/shared/wol/WolWakeTest.kt | 117 +++ .../netkit/shared/wol/WolWidgetModelTest.kt | 180 +++++ .../cz/netkit/shared/wol/WolWidgetRunTest.kt | 239 ++++++ .../shared/wol/WolWidgetSecureOnTest.kt | 118 +++ .../cz/netkit/shared/ios/IosSshDomain.kt | 3 +- tools/m1_provision.py | 22 + tools/netkit_ssh_export.py | 57 +- tools/public_export.manifest | 285 +++++++ tools/public_export.reviewed.tsv | 587 ++++++++++---- tools/run_m1_checks.py | 347 ++++++++- tools/test_check_contrast.py | 15 +- tools/test_m1_fixture_server.py | 77 ++ tools/test_m1_provision.py | 23 +- tools/test_netkit_ssh_export.py | 43 +- tools/test_run_m1_checks.py | 408 ++++++++++ tools/test_update_terminal_width.py | 55 ++ tools/testsrv/iperf3_fixture.py | 155 ++++ tools/testsrv/m1_fixture.py | 526 ++++++++++++- tools/testsrv/telnet_fixture.py | 49 ++ tools/testsrv/test_iperf3_fixture.py | 38 + tools/testsrv/test_m1_fixture.py | 157 ++++ tools/testsrv/test_udp_services.py | 83 ++ tools/testsrv/test_wol_listener.py | 65 ++ tools/testsrv/udp_services.py | 230 ++++++ tools/testsrv/web_diagnostic.py | 70 ++ tools/testsrv/wol_listener.py | 55 +- tools/update_terminal_width.py | 95 +++ 436 files changed, 44621 insertions(+), 1651 deletions(-) create mode 100644 androidApp/lint.xml create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/AccessibilityEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/BackupEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/CellDetailEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/LanRozsireniEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/LandscapeMloEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetStatusWidgetEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/ShareResultsEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshBackgroundSftpEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshLockEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProductivityEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshXtermEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/SystemSettingsEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/ToolTargetsEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiExtensionsEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiSpectrumEvidence.kt create mode 100644 androidApp/src/androidTest/kotlin/cz/netkit/app/test/WolWidgetIntentEvidence.kt create mode 100644 androidApp/src/dev/res/xml/shortcuts.xml create mode 100644 androidApp/src/main/assets/licenses/protobuf-LICENSE.txt create mode 100644 androidApp/src/main/assets/licenses/unicode-LICENSE.txt create mode 100644 androidApp/src/main/assets/licenses/usb-serial-for-android-LICENSE.txt create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/driver/CdcAcmSerialDriver.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/driver/Ch34xSerialDriver.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/driver/Cp21xxSerialDriver.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/driver/FtdiSerialDriver.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/driver/ProlificSerialDriver.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/driver/SerialTimeoutException.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbId.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialPort.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/util/HexDump.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java create mode 100644 androidApp/src/main/java/com/hoho/android/usbserial/util/UsbUtils.java create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/backup/BackupCrypto.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/backup/BackupRepository.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/backup/BackupScreen.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/backup/BackupViewModel.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/backup/RestoreFiles.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/cellular/CellDetailViewModel.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/cellular/CellInfoReader.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesExport.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticLookup.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticPanel.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/DnsLookup.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/LanIpv6Tools.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/LanToolPreferences.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/MacVendorPanel.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/NetworkInfoCard.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/PingOptions.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/ServicesPanel.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/SubnetPanel.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/TargetHistory.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/TracePath.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/UdpServiceProbe.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/WebDiagnostic.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp6.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/nav/AppShortcuts.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusService.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidget.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidgetConfigActivity.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/overview/CellDetailSection.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportDialog.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportViewModel.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/settings/AppLanguageSystem.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/settings/OwnedOperation.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsHost.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsScreen.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsStore.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsViewModel.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Client.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Form.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedShare.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleConnection.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleProfileUi.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpClient.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpController.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpRun.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpScreen.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/SshAccess.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/SshForwarders.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/SshLockUi.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProductivityUi.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionLog.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionService.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ssh/UsbConsole.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/tile/SignalTileService.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ui/KeepScreenOn.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ui/RunSummary.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/ui/ShareActions.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/wifi/ExportSession.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiExportFiles.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/wifi/live/MloReader.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WalkCard.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/wol/WolSecureOnStorage.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidget.kt create mode 100644 androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidgetConfigActivity.kt create mode 100644 androidApp/src/main/res/drawable/ic_notification_ssh.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_background.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_ping.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_ping_foreground.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_signal.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_signal_foreground.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_spectrum.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_spectrum_foreground.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_ssh.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_ssh_foreground.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_subnet.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_subnet_foreground.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_wol.xml create mode 100644 androidApp/src/main/res/drawable/ic_shortcut_wol_foreground.xml create mode 100644 androidApp/src/main/res/drawable/ic_tile_signal.xml create mode 100644 androidApp/src/main/res/drawable/ic_widget_refresh.xml create mode 100644 androidApp/src/main/res/layout/netstatus_age.xml create mode 100644 androidApp/src/main/res/resources.properties create mode 100644 androidApp/src/main/res/values-en/accessibility.xml create mode 100644 androidApp/src/main/res/values-en/backup.xml create mode 100644 androidApp/src/main/res/values-en/lan_rozsireni.xml create mode 100644 androidApp/src/main/res/values-en/lan_wol.xml create mode 100644 androidApp/src/main/res/values-en/netstatus_widget.xml create mode 100644 androidApp/src/main/res/values-en/settings.xml create mode 100644 androidApp/src/main/res/values-en/sharing.xml create mode 100644 androidApp/src/main/res/values-en/shortcuts.xml create mode 100644 androidApp/src/main/res/values-en/ssh_background_sftp.xml create mode 100644 androidApp/src/main/res/values-en/ssh_console.xml create mode 100644 androidApp/src/main/res/values-en/ssh_productivity.xml create mode 100644 androidApp/src/main/res/values-en/ssh_terminal.xml create mode 100644 androidApp/src/main/res/values-en/tools_targets.xml create mode 100644 androidApp/src/main/res/values-en/wifi_ext.xml create mode 100644 androidApp/src/main/res/values-en/wol_secureon.xml create mode 100644 androidApp/src/main/res/values-en/wol_widget.xml create mode 100644 androidApp/src/main/res/values-night/netstatus_widget_colors.xml create mode 100644 androidApp/src/main/res/values/accessibility.xml create mode 100644 androidApp/src/main/res/values/backup.xml create mode 100644 androidApp/src/main/res/values/lan_rozsireni.xml create mode 100644 androidApp/src/main/res/values/lan_wol.xml create mode 100644 androidApp/src/main/res/values/netstatus_widget.xml create mode 100644 androidApp/src/main/res/values/netstatus_widget_colors.xml create mode 100644 androidApp/src/main/res/values/settings.xml create mode 100644 androidApp/src/main/res/values/sharing.xml create mode 100644 androidApp/src/main/res/values/shortcuts.xml create mode 100644 androidApp/src/main/res/values/ssh_background_sftp.xml create mode 100644 androidApp/src/main/res/values/ssh_console.xml create mode 100644 androidApp/src/main/res/values/ssh_productivity.xml create mode 100644 androidApp/src/main/res/values/ssh_terminal.xml create mode 100644 androidApp/src/main/res/values/tools_targets.xml create mode 100644 androidApp/src/main/res/values/wifi_ext.xml create mode 100644 androidApp/src/main/res/values/wol_secureon.xml create mode 100644 androidApp/src/main/res/values/wol_widget.xml create mode 100644 androidApp/src/main/res/xml/netstatus_widget_info.xml create mode 100644 androidApp/src/main/res/xml/shortcuts.xml create mode 100644 androidApp/src/main/res/xml/wol_widget_info.xml create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/backup/BackupCryptoTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/backup/BackupRepositoryTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/backup/RestoreFilesTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/lan/DiagnosticLookupTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/lan/DnsLookupTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/lan/LanIpv6ToolsTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/lan/LanNetworkInfoRefreshTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/lan/LanToolPreferencesTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/lan/PingOptionsTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/lan/TracePathTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/lan/UdpServicesFixtureTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/lan/WebDiagnosticTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/nav/ManifestExportsTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/nav/ShortcutResourcesTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/netstatus/NetStatusWidgetTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/overview/DiagnosticReportInputTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/settings/CzechLocaleResourcesTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/settings/OwnedOperationTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/settings/SettingsStoreTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/speed/Iperf3ClientTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/ssh/ProfileEditorTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/ssh/SessionNotificationTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/ssh/SftpRunTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProductivityJvmTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/ssh/TelnetConsoleWireTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/ssh/UsbConsoleWireTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/ui/AccessibilityTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/wifi/ExportSessionTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/wifi/SpectrumAxisLabelsTest.kt create mode 100644 androidApp/src/test/kotlin/cz/netkit/app/wifi/live/WalkCardTest.kt create mode 100644 docs/funkce/nastaveni.md create mode 100644 docs/licenses/protobuf-LICENSE.txt create mode 100644 docs/licenses/unicode-LICENSE.txt create mode 100644 docs/licenses/usb-serial-for-android-LICENSE.txt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/backup/ConfigurationBackup.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/backup/RestorePlan.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/cellular/CellDetail.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/ConsentResetGate.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRcode.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRecords.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/Ipv6.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDeviceExport.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanNetworkInfo.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanWol.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/MacAddressTable.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/NtpPacket.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/SnmpBer.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/SubnetCalculator.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/TcpPing.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/ToolTargets.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/UdpServices.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/lan/VersionBind.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/nav/AdaptiveNavigation.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/nav/AppTarget.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatus.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRecorder.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRefresh.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusView.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/publicip/Rdap.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/report/DiagnosticReport.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/report/ReportText.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/settings/AppSettings.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/speed/Iperf3Protocol.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ConsoleProfile.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ProfileDirectory.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Sftp.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Socks5.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshForwarding.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshSnippets.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshUnlock.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TelnetCodec.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalLog.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalPalette.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/wifi/EssGroups.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Mlo.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/wifi/RegionalRaster.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/wifi/SpectrumPins.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WalkLog.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiScanExport.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolSecureOn.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWake.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetModel.kt create mode 100644 shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetRun.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/backup/ConfigurationBackupTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/cellular/CellDetailTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/ConsentResetGateTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRcodeTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRecordsTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/Icmpv6EchoTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/Ipv6Test.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDeviceExportTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanNetworkInfoTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanWolTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/MacAddressTableTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/ManagementPortsTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/SubnetCalculatorTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/TcpPingTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/ToolTargetsTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/lan/UdpServicesCodecTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/nav/AdaptiveNavigationTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/nav/AppTargetTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusViewTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/publicip/RdapTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/report/DiagnosticReportTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/settings/AppSettingsTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/speed/Iperf3ProtocolTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedHistoryClearTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SftpTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshDirectoryTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshExportProductivityTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProductivityTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TelnetConsoleTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalXtermTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/wifi/BondingCenterTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/wifi/MloTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WalkLogTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiExtensionsTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolSecureOnTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWakeTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetModelTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetRunTest.kt create mode 100644 shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetSecureOnTest.kt create mode 100644 tools/test_update_terminal_width.py create mode 100644 tools/testsrv/iperf3_fixture.py create mode 100644 tools/testsrv/telnet_fixture.py create mode 100644 tools/testsrv/test_iperf3_fixture.py create mode 100644 tools/testsrv/test_udp_services.py create mode 100644 tools/testsrv/test_wol_listener.py create mode 100644 tools/testsrv/udp_services.py create mode 100644 tools/testsrv/web_diagnostic.py create mode 100644 tools/update_terminal_width.py diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 53512c1..ba72b1c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -65,6 +65,7 @@ jobs: java-version: "21" # No Gradle cache on purpose: a release build must not reuse state written by other runs. + # netkitRequireReleaseManifest: ManifestExportsTest must also check the merged release manifest. # assembleRelease fails by itself (checkReleaseConfig) while netkitWebBase is a placeholder; # -P on the command line wins over every other source of the escape property. Only the # dry run (workflow_dispatch) allows the placeholder; its draft must never be published. @@ -74,6 +75,7 @@ jobs: run: >- ./gradlew --no-daemon --dependency-verification strict "-PnetkitAllowPlaceholderWeb=$ALLOW_PLACEHOLDER" + -PnetkitRequireReleaseManifest=true testDebugUnitTest lintDebug assembleRelease - name: Package and checksum diff --git a/CHANGELOG.md b/CHANGELOG.md index ea687d6..cc150e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,49 @@ # Changelog +## 2.0.0 — síťová diagnostika, SSH a konzole na pozadí (2026-12-02) + +### Česky + +- Velká aktualizace: widgety a zkratky na ploše, SSH na pozadí se SFTP, tunely a ProxyJump, Telnet a USB konzole, iperf3, nové síťové nástroje, sdílení výsledků, zámek SSH a záloha konfigurace. +- Stav sítě i probuzení zařízení přes Wake-on-LAN jsou dostupné přímo z plochy. Dlaždice rychlého nastavení otevře signál Wi-Fi a zkratky vedou na spektrum, ping, SSH profil nebo WoL zařízení. +- Spektrum Wi-Fi zpřesňuje osu 2,4 GHz a polohu širokých kanálů. Přístupové body lze připnout nebo seskupit podle SSID, sken exportovat a při obchůzce zaznamenat signál se značkami míst. +- V LAN lze přepnout na řádkový seznam, zobrazit parametry sítě, předat zařízení do WoL a použít SecureOn. V detailu zařízení lze ručně ověřit služby přes SNMPv2c, NTP a DNS. +- Nástroje přidávají IPv4 kalkulačku podsítí, porty pro správu zařízení, nastavitelný ping s DF a hledáním MTU tam, kde to systém podporuje. Traceroute může pokračovat po pěti tichých hopech. Ping, TCP porty a DNS podporují také jednotlivé IPv6 cíle. +- DNS záznamy ukazují typ, TTL a chyby resolveru. Na vyžádání porovnají odpovědi přes VPN a Wi-Fi. Web/TLS zobrazí přesměrování, časování a certifikát. RDAP vyhledá veřejnou IP nebo ASN. +- SSH přidává uložené příkazy, volitelný záznam výstupu relace do souboru, lokální přesměrování portů, SOCKS5 a připojení přes ProxyJump. +- Rychlost lze měřit proti vlastnímu iperf3 serveru v obou směrech přes TCP, s jedním až osmi paralelními streamy a volitelným limitem na stream. +- V Přehledu lze rozbalit obsluhující a sousední mobilní buňky včetně pásma, kanálu, PCI, Cell ID a TAC podle údajů modemu. Detail se zobrazí jen v telefonu. +- SSH, Telnet a USB sériová konzole mohou s povolenými oznámeními zůstat připojené na pozadí. V oznámení lze všechny relace odpojit. SFTP umožňuje procházet složky, nahrávat a stahovat soubory, přejmenovávat a mazat položky. +- Terminál podporuje 256 barev i truecolor, alternativní obrazovku, rolovací oblasti, bracketed paste a široké či kombinující znaky. K zařízení se lze připojit také nešifrovaným Telnetem nebo přes sériový převodník USB-OTG. +- Přístup k SSH, Telnetu a USB konzoli lze zamknout systémovou biometrií nebo zámkem obrazovky. Profily lze seskupit, vyhledávat a řadit. +- V Nastavení lze změnit jazyk a motiv, ponechat displej zapnutý při měření, obnovit dotazy na souhlas a samostatně vymazat historii speedtestu, iperf3 či cílů nástrojů. Systémové gesto Zpět vrací z ostatních záložek na Přehled. +- V Nastavení lze uložit konfiguraci do jednoho souboru, ve výchozím stavu šifrovaného heslem, a při obnově vybrat sekce podle náhledu. Uložená SSH hesla, privátní klíče a hesla SecureOn se do zálohy nedostanou. +- Diagnostický report z Přehledu lze zkopírovat, sdílet nebo uložit jako text či JSON. Sdílet lze také jednotlivé výsledky měření a exportovat seznam zařízení v LAN. +- Síťové nástroje nabízejí poslední a oblíbené cíle, TCP ping na zvolený port a offline vyhledání výrobce podle MAC adresy. +- TalkBack zpřístupňuje nadpisy, souhrny dokončených měření a hodnoty grafů. Vybrané ovládací prvky mají větší dotykovou plochu a drobné popisky vyšší kontrast. +- Na širším displeji se navigace přesune na bok. V terminálu na šířku lze sbalit ovládání. U Wi-Fi 7 ukazuje Přehled jednotlivé připojené linky MLO podle údajů telefonu. + +### English + +- Major update: home screen widgets and shortcuts, background SSH with SFTP, tunnels and ProxyJump, Telnet and USB console, iperf3, new network tools, result sharing, SSH lock and configuration backup. +- Check network status or wake a device right from the home screen. A Quick Settings tile opens Wi-Fi signal details, and shortcuts open the spectrum, ping, an SSH profile or a Wake-on-LAN device. +- The Wi-Fi spectrum improves the 2.4 GHz axis and wide-channel placement. Pin access points or group them by SSID, export a scan, or record signal levels with location labels during a walk. +- Switch to a compact LAN device list, inspect network settings, send a device to Wake-on-LAN and use SecureOn. Check an individual device for services over SNMPv2c, NTP and DNS. +- The network tools now include an IPv4 subnet calculator, more management ports, configurable ping with DF and MTU discovery where supported. Traceroute can continue after five silent hops. Ping, TCP port checks and DNS also support individual IPv6 targets. +- DNS records show types, TTLs and resolver errors. Compare VPN and Wi-Fi answers on request. Web/TLS shows redirects, timings and the certificate. Look up a public IP address or ASN with RDAP. +- SSH adds saved command snippets, optional session output logging to a file, local port forwarding, SOCKS5 and ProxyJump. +- Measure TCP upload or download speed against your own iperf3 server with one to eight parallel streams and an optional per-stream rate limit. +- Expand the serving and neighbouring mobile cells in Overview to see the band, channel, PCI, cell ID and TAC where available from the modem. Cell details stay on the phone. +- SSH, Telnet and USB serial sessions can stay connected in the background when notifications are enabled. Disconnect all sessions from the notification. Use SFTP to browse directories, upload or download files, and rename or delete items. +- The terminal supports 256 colours and truecolour, the alternate screen, scroll regions, bracketed paste, and wide and combining characters. Connect to devices over unencrypted Telnet or a USB OTG serial adapter. +- Protect access to SSH, Telnet and the USB console with system biometrics or your screen lock. Group, search and sort connection profiles. +- In Settings, change the language and theme, keep the screen on during measurements, reset consent prompts and clear speed test, iperf3 or tool target history separately. The system Back gesture returns to Overview from other tabs. +- Back up your configuration to a single file in Settings, password-encrypted by default, and pick the sections to restore from a preview. Saved SSH passwords, private keys and SecureOn passwords are never included. +- Copy, share or save a diagnostic report from Overview as text or JSON. Share individual speed test results or export the LAN device list. +- Network tools offer recent and favourite targets, TCP ping on a selected port and offline vendor lookup by MAC address. +- TalkBack reads headings, completed measurement summaries and chart values. Selected controls have larger touch targets, and secondary labels have higher contrast. +- Navigation moves to the side on wider screens. Collapse terminal controls in landscape. On Wi-Fi 7, Overview shows individual connected MLO links when the phone reports them. + ## 1.1.0 — upozornění na novou verzi a výrobce Wi-Fi (2026-11-02) - Při spuštění aplikace se zkontroluje nová verze a nabídne se v okně s volbami Stáhnout, Zavřít a Nepřipomínat tuto verzi; bez notifikací na pozadí. diff --git a/CLAUDE.md b/CLAUDE.md index edf5843..f2987cd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,7 +14,9 @@ Rozcestník, struktura a sestavení: [README.md](README.md). - UI texty patří do CS a EN resources; stav přes ViewModel a StateFlow. - Nové závislosti vyžadují ověření oficiální licence a zápis do `docs/zavislosti.md`; povoleny Apache-2.0, MIT a BSD. - Existující výjimky: ISC pouze pro jBCrypt přibalený v JSch a OFL-1.1 pro fonty. + Existující výjimky: ISC pouze pro jBCrypt přibalený v JSch, OFL-1.1 pro fonty a Unicode + License V3 pouze pro tabulku šířek znaků odvozenou z Unicode Character Database (D32; + atribuce v NOTICE, plné znění licence v Android assets a v iOS seznamu licencí). - Nová oprávnění zdůvodnit v `docs/bezpecnost.md`. - Ověřovat kontroly odpovídající změně; výsledek PASS/FAIL/NOT RUN vždy spojit se skutečným během. Emulátor nenahrazuje fyzický test. diff --git a/NOTICE b/NOTICE index da945a1..36951c1 100644 --- a/NOTICE +++ b/NOTICE @@ -21,8 +21,11 @@ Public Suffix List (přibalený v okhttp-android, neupravený) — MPL-2.0, zdrojová podoba https://publicsuffix.org/list/; text licence v aplikaci (O aplikaci → Licence open source) a androidApp/src/main/assets/licenses/MPL-2.0.txt. AndroidX (Compose, Material, Activity, Lifecycle, DataStore, Startup, -ProfileInstaller, Annotation, Collection, Core, Arch, SavedState a další -moduly uvedené v inventáři) — Apache-2.0, Android Open Source Project. +ProfileInstaller, Glance, WorkManager, Room, SQLite, Annotation, Collection, +Core, Arch, SavedState a další moduly uvedené v inventáři) — Apache-2.0, +Android Open Source Project. +Protocol Buffers lite (přebalený v androidx.glance a androidx.datastore) — BSD-3-Clause, +Copyright 2008 Google Inc.; úplný text: docs/licenses/protobuf-LICENSE.txt. Kotlin, kotlinx.coroutines, kotlinx.serialization, JetBrains annotations — Apache-2.0, JetBrains a přispěvatelé. Guava listenablefuture — Apache-2.0, Google a přispěvatelé. @@ -53,3 +56,19 @@ docs/public-license-verification.tsv a docs/zavislosti.md. Cloudflare, Team Cymru, LibreSpeed servery a M-Lab jsou externí služby. Kód LibreSpeed ani GPL kód aplikace ConnectBot se do NetKitu nepřebírá. + +usb-serial-for-android 3.12.0 (MIT), commit 4cb9e82cdcfa095eb2fe0b0bea9605f50bd8e2f2 +https://github.com/mik3y/usb-serial-for-android/tree/3.12.0 +Copyright (c) 2011-2013 Google Inc. and (c) 2013 Mike Wakerly. +Individual driver attribution is retained in the source files. The Ch34x and +Prolific drivers import the app's generated BuildConfig in this distribution. +HexDump.java is Copyright (C) 2006 The Android Open Source Project, Apache-2.0. + +Unicode Character Database 18.0.0 (EastAsianWidth.txt, extracted/DerivedGeneralCategory.txt), +staženo 2026-12-02 z https://www.unicode.org/Public/UCD/latest/ucd/ — Unicode License V3 +(SPDX Unicode-3.0, schválená OSI). Copyright © 1991-2026 Unicode, Inc. +Z dat je odvozena jen tabulka šířek znaků terminálu +(shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt) pro Android i iOS. +Výjimka z projektového pravidla Apache/MIT/BSD platí jen pro tato data (D32). +Úplný text licence: androidApp/src/main/assets/licenses/unicode-LICENSE.txt; v aplikaci +O aplikaci → Licence open source (Android) a v seznamu licencí open source (iOS). diff --git a/README.cs.md b/README.cs.md index bc11cf4..21007b7 100644 --- a/README.cs.md +++ b/README.cs.md @@ -9,10 +9,12 @@ v jedné aplikaci. Kotlin a Jetpack Compose, české a anglické rozhraní, bez - Přehled aktivní sítě, Wi-Fi signálu a mobilního připojení (dual SIM). - Wi-Fi spektrum, kanály, zabezpečení a živé grafy signálu. -- Vyhledání zařízení v LAN, ping, DNS, TCP porty a traceroute. -- SSH profily s ověřením klíče serveru a terminál (omezená podpora VT/ANSI, ne plný xterm). -- Wake-on-LAN s importem a exportem v JSON/CSV. -- Měření rychlosti přes LibreSpeed nebo M-Lab NDT7 s historií. +- Vyhledání zařízení v LAN, ping, DNS záznamy, TCP porty, traceroute, kalkulačka podsítí, Web/TLS a RDAP. +- Společný terminál pro SSH s ověřením klíče serveru, nešifrovaný Telnet a sériovou konzoli přes USB. Podporované převodníky zahrnují FTDI, CP210x, CH34x, PL2303 a CDC-ACM. +- SSH relace na pozadí, SFTP, snippety, lokální a SOCKS5 přesměrování, ProxyJump a volitelný zámek. +- Wake-on-LAN s importem a exportem v JSON/CSV, widgety na ploše, zkratky a dlaždice rychlého nastavení. +- Měření rychlosti přes LibreSpeed, M-Lab NDT7 nebo vlastní server iperf3 s historií. +- Záloha konfigurace do jednoho souboru, ve výchozím stavu šifrovaná heslem. - Volitelné zjištění veřejné IP a poskytovatele (Cloudflare, Team Cymru). **Skenujte jen vlastní nebo výslovně povolené sítě.** Externí služby vidí vaši veřejnou IP adresu; diff --git a/README.md b/README.md index 566a3b3..120793b 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,12 @@ in one app. Kotlin and Jetpack Compose, Czech and English UI, no account, ads or - Overview of the active network, Wi-Fi signal and mobile connection (dual SIM). - Wi-Fi spectrum, channels, security and live signal charts. -- LAN device discovery, ping, DNS, TCP ports and traceroute. -- SSH profiles with host key verification and a terminal (limited VT/ANSI, not a full xterm). -- Wake-on-LAN with JSON/CSV import and export. -- Speed tests via LibreSpeed or M-Lab NDT7, with history. +- LAN device discovery, ping, DNS records, TCP ports, traceroute, subnet calculator, Web/TLS and RDAP. +- SSH profiles with host key verification, cleartext Telnet, and USB serial consoles share a terminal. USB adapters include FTDI, CP210x, CH34x, PL2303 and CDC-ACM. +- SSH sessions in the background, SFTP, snippets, local and SOCKS5 forwarding, ProxyJump and an optional lock. +- Wake-on-LAN with JSON/CSV import and export, home screen widgets, shortcuts and a Quick Settings tile. +- Speed tests via LibreSpeed, M-Lab NDT7 or your own iperf3 server, with history. +- Configuration backup to a single file, password-encrypted by default. - Optional public IP and provider lookup (Cloudflare, Team Cymru). **Scan only networks you own or are explicitly allowed to test.** External services see your diff --git a/androidApp/build.gradle.kts b/androidApp/build.gradle.kts index e802bb8..1de97b1 100644 --- a/androidApp/build.gradle.kts +++ b/androidApp/build.gradle.kts @@ -1,3 +1,4 @@ +import com.android.build.api.artifact.SingleArtifact import java.util.Properties plugins { @@ -7,7 +8,7 @@ plugins { alias(libs.plugins.kotlin.compose) } /** Release version; versionCode = major*10000 + minor*100 + patch (docs/distribuce.md §2). */ -val netkitVersion = "1.1.0" +val netkitVersion = "2.0.0" val netkitVersionCode = netkitVersion.split('.').map(String::toInt).let { (major, minor, patch) -> require(minor in 0..99 && patch in 0..99) { "minor and patch must be 0..99" } major * 10000 + minor * 100 + patch @@ -83,6 +84,10 @@ android { } } buildFeatures { compose = true; buildConfig = true } + // Per-app language (zadání 46 §1, Android 13+): AGP generates the LocaleConfig from the res/values-* + // locales; the default (unqualified) locale is Czech, see src/main/res/resources.properties. + // Czech texts stay in values/; generateCzechLocaleStrings adds a values-cs copy (see below). + androidResources { generateLocaleConfig = true } // The dependency block is encrypted for Google only; an APK from GitHub has no use for it. dependenciesInfo { includeInApk = false; includeInBundle = false } packaging.resources { @@ -97,6 +102,58 @@ android { } kotlin { jvmToolchain(21) } +/** + * Czech is the unqualified default (values/), English is values-en. With a locale list such as + * per-app language cs + system en_US = [cs,en_US], Android 15 resolves every string that has no + * cs-qualified entry from values-en: a recreated activity (language switch, rotation) showed English + * although the app language was Czech (zadání 46, emulator API 35). This task copies every + * translatable string, plural and string array of src/main/res/values into a generated values-cs, so + * Czech has an explicit locale match. values/ stays the only source; non-translatable entries (app_name, + * overridden by the dev build type) are not copied. Checked by CzechLocaleResourcesTest. + */ +@CacheableTask +abstract class CzechLocaleStrings : DefaultTask() { + @get:InputFiles @get:PathSensitive(PathSensitivity.RELATIVE) abstract val sources: ConfigurableFileCollection + @get:OutputDirectory abstract val outputDir: DirectoryProperty + + @TaskAction fun generate() { + val tools = "http://schemas.android.com/tools" + val factory = javax.xml.parsers.DocumentBuilderFactory.newInstance().apply { + isNamespaceAware = true + setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) + } + val out = factory.newDocumentBuilder().newDocument() + val root = out.createElement("resources") + root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:tools", tools) + out.appendChild(root) + root.appendChild(out.createComment(" Generated by generateCzechLocaleStrings from src/main/res/values; do not edit. ")) + for (file in sources.files.sortedBy { it.name }) { + val nodes = factory.newDocumentBuilder().parse(file).documentElement.childNodes + for (index in 0 until nodes.length) { + val node = nodes.item(index) as? org.w3c.dom.Element ?: continue + if (node.tagName in setOf("string", "plurals", "string-array") && node.getAttribute("translatable") != "false") { + root.appendChild(out.importNode(node, true)) + } + } + } + val directory = outputDir.get().asFile + directory.deleteRecursively() + val target = File(directory, "values-cs/netkit_cs_strings.xml").apply { parentFile.mkdirs() } + javax.xml.transform.TransformerFactory.newInstance().newTransformer().apply { + setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, "utf-8") + setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes") + }.transform(javax.xml.transform.dom.DOMSource(out), javax.xml.transform.stream.StreamResult(target)) + } +} +androidComponents { + onVariants { variant -> + val task = tasks.register("generate${variant.name.replaceFirstChar(Char::uppercase)}CzechLocaleStrings") { + sources.from(fileTree("src/main/res/values") { include("*.xml") }) + } + variant.sources.res?.addGeneratedSourceDirectory(task, CzechLocaleStrings::outputDir) + } +} + /** D17: a release must carry the real web base; a placeholder would ship a dead update check. */ val checkReleaseConfig by tasks.registering { val configured = netkitWebConfigured @@ -109,14 +166,53 @@ val checkReleaseConfig by tasks.registering { } } tasks.configureEach { if (name == "preReleaseBuild") dependsOn(checkReleaseConfig) } +/** + * ManifestExportsTest reads the merged manifests (zadání 36, revize kolo 1–2) of every unit test task + * (debug, dev, release). They are declared inputs taken from the AGP artifact `MERGED_MANIFEST`, so + * the producing tasks run first and a changed manifest re-runs the test. Debug and dev are always + * checked. The release manifest needs the real web (checkReleaseConfig) or the local placeholder escape, + * so it is added only with `-PnetkitRequireReleaseManifest=true` (release workflow); then the test + * fails when it is missing instead of skipping it. + */ +val mergedManifests = mutableMapOf>() +androidComponents { + onVariants { variant -> mergedManifests[variant.name] = variant.artifacts.get(SingleArtifact.MERGED_MANIFEST) } +} +val requireReleaseManifest = providers.gradleProperty("netkitRequireReleaseManifest").map { it == "true" }.getOrElse(false) +val checkedManifestVariants = listOf("debug", "dev") + if (requireReleaseManifest) listOf("release") else emptyList() +/** Configuration-cache safe: holds only the variant names, file providers and the flag, no script reference. */ +class MergedManifestArgs( + @get:Input val variants: List, + @get:Internal val files: List>, + @get:Input val requireRelease: Boolean, +) : CommandLineArgumentProvider { + override fun asArguments(): Iterable = listOf( + "-Dnetkit.mergedManifests=" + variants.zip(files).joinToString(",") { (name, file) -> "$name=${file.get().asFile.path}" }, + "-Dnetkit.requireReleaseManifest=$requireRelease") +} +tasks.withType().configureEach { + val variants = checkedManifestVariants.toList() + val artifacts = mergedManifests + val manifests = variants.map { name -> providers.provider { artifacts.getValue(name) }.flatMap { it } } + inputs.files(manifests).withPropertyName("mergedManifests").withPathSensitivity(PathSensitivity.RELATIVE) + // ManifestExportsTest compares the manifest with the permission table of docs/bezpecnost.md (zadání 42). + inputs.file(rootProject.layout.projectDirectory.file("docs/bezpecnost.md")).withPropertyName("securityDoc") + .withPathSensitivity(PathSensitivity.RELATIVE) + jvmArgumentProviders += MergedManifestArgs(variants, manifests, requireReleaseManifest) +} tasks.withType().configureEach { useTestNG() // Reproducible native diagnostics; production classification must not depend on these texts. environment("LC_ALL", "C") + // UdpServicesFixtureTest runs this loopback fixture; a change to it must rerun the tests. + inputs.file(rootProject.file("tools/testsrv/udp_services.py")).withPropertyName("udpServicesFixture") } dependencies { implementation(libs.jsch) + implementation(libs.biometric) + // MainActivity is a FragmentActivity (BiometricPrompt); pinned over biometric's fragment 1.2.5. + implementation(libs.fragment) implementation(libs.bcprov) // Speed test: HTTPS (LibreSpeed) and WebSocket (NDT7) bound to the Wi-Fi Network. implementation(libs.okhttp) @@ -135,4 +231,8 @@ dependencies { implementation(libs.compose.foundation) implementation(libs.activity.compose) implementation(libs.lifecycle.viewmodel) + // WoL home-screen widget (zadání 36 §2.6); WorkManager pinned over Glance's transitive 2.7.1. + implementation(libs.glance.appwidget) + implementation(libs.glance.material3) + implementation(libs.work.runtime.ktx) } diff --git a/androidApp/lint.xml b/androidApp/lint.xml new file mode 100644 index 0000000..ecae711 --- /dev/null +++ b/androidApp/lint.xml @@ -0,0 +1,8 @@ + + + + + + + diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/AccessibilityEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/AccessibilityEvidence.kt new file mode 100644 index 0000000..f014da6 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/AccessibilityEvidence.kt @@ -0,0 +1,224 @@ +package cz.netkit.app.test + +import android.app.Instrumentation +import android.content.res.Configuration +import android.graphics.Rect +import android.os.ParcelFileDescriptor +import android.view.View +import android.view.accessibility.AccessibilityEvent +import android.view.accessibility.AccessibilityNodeInfo +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.compose.ui.unit.dp +import cz.netkit.app.R +import cz.netkit.app.lan.* +import cz.netkit.app.speed.MeasurementCard +import cz.netkit.app.speed.SpeedPhase +import cz.netkit.app.speed.SpeedUiState +import cz.netkit.app.speed.TraceCard +import cz.netkit.app.ui.OffscreenRunSummary +import cz.netkit.app.ui.SectionCard +import cz.netkit.app.ui.SegmentedTabs +import cz.netkit.app.ui.StatusBanner +import cz.netkit.app.ui.chart.ChartLine +import cz.netkit.app.ui.chart.TimeSeriesChart +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.wifi.HeatStrip +import cz.netkit.app.wifi.heatCells +import cz.netkit.app.wifi.SpectrumPanel +import cz.netkit.app.wifi.spectrumDrawnTraces +import cz.netkit.shared.lan.LanAliveMethod +import cz.netkit.shared.lan.LanDevice +import cz.netkit.shared.lan.LanResult +import cz.netkit.shared.lan.LanRunStatus +import cz.netkit.shared.lan.ProbeCounts +import cz.netkit.shared.speed.SpeedEngine +import cz.netkit.shared.speed.ThroughputSummary +import cz.netkit.shared.wifi.* +import kotlinx.coroutines.delay +import java.util.Locale +import kotlin.math.roundToInt + +/** Exercise production composables and the semantics exposed to Android accessibility services. */ +@OptIn(ExperimentalComposeUiApi::class) +internal suspend fun accessibilityEvidence(test: Instrumentation, activity: ComponentActivity, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + val ui = SshEvidenceUi(test) + val polite = View.ACCESSIBILITY_LIVE_REGION_POLITE + val speed = SpeedUiState(phase = SpeedPhase.DONE, engine = SpeedEngine.LIBRESPEED, + download = ThroughputSummary(20.5, 25.0, 0, 1000, 100), upload = ThroughputSummary(8.5, 10.0, 0, 1000, 100), + downloadPoints = listOf(25.0, 16.0, 20.5), uploadPoints = listOf(7.0, 10.0, 8.5)) + val weak = AccessPoint("Lab A", "02:00:00:00:49:01", -80, 2412, channel = 1, band = WifiBand.GHZ_2_4, + widthMhz = 20, security = WifiSecurity.WPA2, standard = null, ageMs = 0, locallyAdministered = true) + val strong = weak.copy(ssid = "Lab B", bssid = "02:00:00:00:49:02", frequencyMhz = 2437, channel = 6, rssiDbm = -48) + val spectrum = requireNotNull(bandSpectrum(listOf(weak, strong), WifiBand.GHZ_2_4)) + + for (language in listOf("cs", "en")) { + val config = Configuration(activity.resources.configuration).apply { setLocale(Locale.forLanguageTag(language)) } + val context = activity.createConfigurationContext(config) + val res = context.resources + fun show(content: @Composable () -> Unit) { + test.runOnMainSync { + activity.setContent { + CompositionLocalProvider(LocalConfiguration provides config, LocalContext provides context) { + NetKitTheme(darkTheme = language == "en") { + Surface(Modifier.fillMaxSize(), color = NetKitTheme.colors.background) { + Column(Modifier.safeDrawingPadding().padding(12.dp).semantics { testTagsAsResourceId = true }, verticalArrangement = Arrangement.spacedBy(8.dp)) { + content() + } + } + } + } + } + } + test.waitForIdleSync() + } + suspend fun capture(scene: String) { + // Accessibility nodes may update before the emulator composites the new scene. + delay(1500) + test.waitForIdleSync() + test.uiAutomation.waitForIdle(200, 4000) + screenshot("accessibility-$language-$scene.png") + } + suspend fun spoken(text: String) = ui.await { + it.isVisibleToUser && it.liveRegion == polite && it.contentDescription?.toString() == text + } + + val header = res.getString(R.string.lan_results_title) + check(header == if (language == "cs") "Výsledky" else "Results") + val note = res.getString(R.string.lan_network_note) + val ping = LanUiState(tool = LanTool.PING, runStatus = LanRunStatus.RUNNING, total = 3) + var state by mutableStateOf(ping) + show { + SectionCard(header) { + StatusBanner(note) + SegmentedTabs(listOf(stringResource(R.string.lan_ping), stringResource(R.string.lan_trace)), 0, {}, + testTags = listOf("accessibility_ping", "accessibility_trace")) + RunStatus(state) + } + SectionCard("192.0.2.1", heading = false) { Text("A") } + } + ui.await { it.isHeading && it.text?.toString() == header } + ui.await { it.isVisibleToUser && it.text?.toString() == "192.0.2.1" && !it.isHeading } + ui.await { it.liveRegion == polite && it.text?.toString() == note } + val tab = ui.await { it.isVisibleToUser && it.isClickable && it.viewIdResourceName == "accessibility_trace" } + val bounds = Rect().also(tab::getBoundsInScreen) + val minimum = (48 * res.displayMetrics.density).roundToInt() + check(bounds.width() >= minimum && bounds.height() >= minimum) + spoken(res.getString(R.string.lan_chip_running_plain)) + test.runOnMainSync { state = ping.copy(runStatus = LanRunStatus.FINISHED, sent = 3, received = 2, + samples = listOf(2.0, null, 4.0), results = List(3) { LanResult("192.0.2.1") }) } + spoken(res.getString(R.string.a11y_ping_done, 2, 3) + " " + res.getString(R.string.a11y_ping_average, 3.0)) + marker("ACCESSIBILITY:$language:HEADING_STATUS_TARGET:PASS") + capture("ping") + + // The user is reading a different item when a run ends. + var running by mutableStateOf(true) + val offscreenResult = res.getString(R.string.a11y_dns_done, 2) + show { + val list = rememberLazyListState() + OffscreenRunSummary(running, if (running) "" else offscreenResult, list, "status") + LazyColumn(Modifier.height(48.dp), state = list) { + item("results") { Text(header, Modifier.height(48.dp)) } + item("status") { Text(offscreenResult) } + } + } + ui.await { it.text?.toString() == header && !it.isHeading && it.isVisibleToUser } + test.uiAutomation.executeAndWaitForEvent( + { test.runOnMainSync { running = false } }, + { it.eventType == AccessibilityEvent.TYPE_ANNOUNCEMENT && offscreenResult in it.text }, + 5000, + ) + marker("ACCESSIBILITY:$language:OFFSCREEN:PASS") + + val done = LanUiState(runStatus = LanRunStatus.FINISHED) + val rows = listOf(LanResult("192.0.2.1"), LanResult("")) + val peer = LanDevice("192.0.2.1", firstSeenElapsedMs = 0, lastSeenElapsedMs = 1, method = LanAliveMethod.ICMP) + val devices = LanDevicesState(scan = LanDeviceScan(LanRunStatus.FINISHED), + devices = listOf(peer, peer.copy(address = "192.0.2.2", stale = true), peer.copy(address = "192.0.2.3", isSelf = true))) + show { + SectionCard(stringResource(R.string.lan_trace)) { RunStatus(done.copy(tool = LanTool.TRACE, results = rows)) } + SectionCard(stringResource(R.string.lan_ports)) { RunStatus(done.copy(tool = LanTool.PORTS, probeCounts = ProbeCounts(open = 1), progress = 3)) } + SectionCard(stringResource(R.string.lan_dns)) { RunStatus(done.copy(tool = LanTool.DNS, results = rows.take(1))) } + SectionCard(stringResource(R.string.lan_discovery)) { DeviceScanTag(devices) } + } + spoken(res.getString(R.string.a11y_trace_done, 2, 1)) + spoken(res.getString(R.string.a11y_ports_done, 1, 3)) + spoken(res.getString(R.string.a11y_dns_done, 1)) + spoken(res.getString(R.string.a11y_scan_done, 3)) + marker("ACCESSIBILITY:$language:LAN_RESULTS:PASS") + capture("lan") + + for (engine in listOf(SpeedEngine.LIBRESPEED, SpeedEngine.IPERF3)) { + val iperf = engine == SpeedEngine.IPERF3 + show { MeasurementCard(speed.copy(engine = engine, download = if (iperf) null else speed.download), {}, {}) } + val expected = listOfNotNull(res.getString(if (iperf) R.string.a11y_iperf_done else R.string.a11y_speed_done), + if (iperf) null else res.getString(R.string.a11y_speed_download, 20.5), res.getString(R.string.a11y_speed_upload, 8.5)) + spoken(expected.joinToString(" ")) + val scene = if (iperf) "iperf" else "speed" + marker("ACCESSIBILITY:$language:$scene:PASS") + capture(scene) + } + show { + TimeSeriesChart(listOf(ChartLine("RSSI", listOf(-70f, -50f, null), Color.Blue)), 3, 1000, null, null, + "dBm", "RSSI", height = 100.dp) + TraceCard(speed) + } + val signal = res.getString(R.string.a11y_series, "RSSI", "-70 dBm", "-50 dBm", res.getString(R.string.a11y_missing)) + ui.await { it.contentDescription?.contains(signal) == true && it.liveRegion == View.ACCESSIBILITY_LIVE_REGION_NONE } + val rate = if (language == "cs") "20,5" else "20.5" + val download = res.getString(R.string.a11y_series, res.getString(R.string.speed_download), "16 Mbit/s", "25 Mbit/s", "$rate Mbit/s") + ui.await { it.contentDescription?.contains(download) == true } + marker("ACCESSIBILITY:$language:CHARTS:PASS") + capture("charts") + + val cells = heatCells(scoreChannelHealth(listOf(weak, strong), WifiBand.GHZ_2_4)) + show { + SpectrumPanel(spectrum, "2.4 GHz", spectrumDrawnTraces(spectrum.traces)) + var selected by remember { mutableIntStateOf(1) } + // Off the left edge: at the 12 dp test margin channel 1 would lie in the system back-gesture zone (24 dp). + Box(Modifier.padding(start = 40.dp).width(300.dp).testTag("accessibility_heat_strip")) { + HeatStrip(cells, setOf(1, 6, 11), selected) { selected = it } + } + } + suspend fun channel(number: Int, selected: Boolean): AccessibilityNodeInfo { + val title = res.getString(R.string.wifi_health_channel_title, number) + return ui.await { it.isVisibleToUser && it.isSelected == selected && + it.contentDescription?.toString()?.substringBefore(" · ") == title } + } + val first = Rect().also(channel(1, true)::getBoundsInScreen) + val lastNumber = cells.filterNotNull().last().channel + val last = Rect().also(channel(lastNumber, false)::getBoundsInScreen) + check(channel(2, false).performAction(AccessibilityNodeInfo.ACTION_CLICK)) + channel(2, true) + /* + * Integrace 2.0 (first emulator run): the swipe used the centres of the accessibility bounds of channels 1 and + * 13, but Compose widens those to the 48 dp minimum touch target, so channel 1's centre lay left of the drawn + * strip and the drag never started on it. Drag between the centres of the drawn end cells instead. + */ + val strip = Rect().also(ui.await { it.viewIdResourceName == "accessibility_heat_strip" }::getBoundsInScreen) + val half = strip.width() / (2 * cells.size) + val swipe = "input swipe ${strip.left + half} ${first.centerY()} ${strip.right - half} ${last.centerY()} 350" + ParcelFileDescriptor.AutoCloseInputStream(test.uiAutomation.executeShellCommand(swipe)).use { it.readBytes() } + channel(lastNumber, true) + val strongest = res.getString(R.string.a11y_strongest, "Lab B", 6, -48) + ui.await { it.contentDescription?.contains(strongest) == true && it.liveRegion == View.ACCESSIBILITY_LIVE_REGION_NONE } + marker("ACCESSIBILITY:$language:SPECTRUM:PASS") + capture("spectrum") + } +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/BackupEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/BackupEvidence.kt new file mode 100644 index 0000000..c220c15 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/BackupEvidence.kt @@ -0,0 +1,170 @@ +package cz.netkit.app.test + +import android.accessibilityservice.AccessibilityService +import android.app.Activity +import android.app.Application +import android.app.Instrumentation +import android.app.LocaleManager +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.os.LocaleList +import android.os.ParcelFileDescriptor +import android.view.accessibility.AccessibilityNodeInfo +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.backup.* +import cz.netkit.shared.backup.encryptedBackup +import cz.netkit.shared.backup.BackupSection +import cz.netkit.shared.ssh.SshAuthentication +import cz.netkit.shared.ssh.SshData +import cz.netkit.shared.ssh.SshKeyInfo +import cz.netkit.shared.ssh.SshProfile +import java.util.UUID +import java.util.concurrent.atomic.AtomicReference +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withTimeout + +/** Exercise the real Settings screen and transfer ViewModel with a per-run file in place of + * the system document picker. Positive process termination is covered by the physical checklist. */ +internal suspend fun backupEvidence(test: Instrumentation, app: M1TestApplication, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + val ui = SshEvidenceUi(test) + val locales = app.getSystemService(LocaleManager::class.java) + val previous = locales.applicationLocales + var current: MainActivity? = null + val file = app.filesDir.resolve("fixture-backup.json") + val corrupt = app.filesDir.resolve("fixture-backup-corrupt.json") + val stored = app.sshStore.read() + // Revize 51, kolo 2: a key profile is exported, removed locally and must be previewed as keyless. + val key = SshKeyInfo(UUID.randomUUID().toString(), "Lab key", "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFixture lab") + val keyed = SshProfile(UUID.randomUUID().toString(), "Lab key host", "192.0.2.30", username = "operator", + authentication = SshAuthentication.KEY, keyRef = key.id) + try { + for (language in listOf("cs", "en")) { + app.sshStore.update { SshData(profiles = listOf(keyed), keys = listOf(key)) } + test.runOnMainSync { locales.applicationLocales = LocaleList.forLanguageTags(language) } + val activity = test.startActivitySync(Intent(app, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)) as MainActivity + current = activity + check(activity.resources.configuration.locales[0].language == language) + ui.clickTag("overview_menu"); ui.clickTag("overview_menu_settings"); ui.clickTag("settings_backup") + ui.await { it.viewIdResourceName == "backup_password" } + screenshot("backup-export-$language.png") + ui.clickText(activity.getString(R.string.backup_encrypt)) + ui.await { it.text?.toString() == activity.getString(R.string.backup_plain_warning) } + screenshot("backup-warning-$language.png") + ui.clickText(activity.getString(R.string.settings_cancel)) + + lateinit var model: BackupViewModel + val pass = UUID.randomUUID().toString() + val ready = CompletableDeferred() + test.runOnMainSync { + model = ViewModelProvider(activity)[BackupViewModel::class.java] + model.prepare(pass.toCharArray()) { ready.complete(Unit) } + } + withTimeout(30_000) { ready.await() } + val uri = Uri.fromFile(file) + test.runOnMainSync { model.write(uri) } + withTimeout(20_000) { model.state.first { it.message == R.string.backup_exported && !it.busy } } + check(encryptedBackup(file.readBytes())) + marker("BACKUP:ENCRYPTED:$language:PASS") + // Build-host verification: a truncated envelope and a JSON nested beyond the json/ limit + // end with the generic error, without a crash and without leaving the export screen. + for (broken in listOf(file.readBytes().copyOf(file.length().toInt() / 2), + ("[".repeat(200) + "]".repeat(200)).encodeToByteArray())) { + corrupt.writeBytes(broken) + test.runOnMainSync { model.read(Uri.fromFile(corrupt)) } + withTimeout(20_000) { model.state.first { it.message == R.string.backup_failed && !it.busy } } + check(!model.state.value.preview && !model.state.value.needsPassword) + } + ui.findText(activity.getString(R.string.backup_failed), scroll = true) + screenshot("backup-corrupt-$language.png") + marker("BACKUP:CORRUPT:$language:PASS") + app.sshStore.update { SshData(keys = listOf(key)) } + test.runOnMainSync { model.read(uri) } + withTimeout(20_000) { model.state.first { it.needsPassword && !it.busy } } + test.runOnMainSync { model.unlock(UUID.randomUUID().toString().toCharArray()) } + withTimeout(30_000) { model.state.first { it.message == R.string.backup_wrong_password && !it.busy } } + ui.findText(activity.getString(R.string.backup_wrong_password), scroll = true) + screenshot("backup-password-error-$language.png") + marker("BACKUP:AUTH_ERROR:$language:PASS") + test.runOnMainSync { model.unlock(pass.toCharArray()) } + withTimeout(30_000) { model.state.first { it.plan != null && !it.busy } } + ui.await { it.viewIdResourceName == "backup_preview" } + withTimeout(8_000) { model.state.first { keyed.name in it.plan?.keyless.orEmpty() } } + ui.findText(activity.getString(R.string.backup_key_missing)) + screenshot("backup-preview-$language.png") + marker("BACKUP:KEYLESS_NOTE:$language:PASS") + ui.clickText(activity.getString(R.string.backup_ssh)) + withTimeout(8_000) { model.state.first { !it.busy && BackupSection.SSH !in it.selected && it.plan != null } } + ui.clickText(activity.getString(R.string.backup_restore), scroll = true) + // Plain AlertDialog: its own window does not inherit testTagsAsResourceId, so find it by text. + ui.findText(activity.getString(R.string.backup_restart)) + screenshot("backup-confirm-$language.png") + ui.clickText(activity.getString(R.string.settings_cancel)) + check(model.state.value.preview && BackupSection.KNOWN_HOSTS !in model.state.value.selected) + marker("BACKUP:SELECT_CONFIRM_CANCEL:$language:PASS") + val last = if (language == "cs") rotatedPicker(test, app, ui, activity, model, screenshot, marker) else activity + current = last + test.runOnMainSync { last.finish() } + withTimeout(8000) { while (!last.isDestroyed) delay(50) } + current = null + } + } finally { + test.runOnMainSync { current?.finish(); locales.applicationLocales = previous } + file.delete() + corrupt.delete() + app.sshStore.update { stored } + } +} + +/** + * Revize 51, kolo 1: the display rotates while PBKDF2 runs. The document picker must start from the + * recreated composition (state flag in the ViewModel), exactly once and without a crash. Cancelling the + * picker writes nothing. Returns the resumed activity to finish. + */ +private suspend fun rotatedPicker(test: Instrumentation, app: M1TestApplication, ui: SshEvidenceUi, activity: MainActivity, + model: BackupViewModel, screenshot: (String) -> Unit, marker: (String) -> Unit): MainActivity { + fun shell(command: String): String = ParcelFileDescriptor.AutoCloseInputStream(test.uiAutomation.executeShellCommand(command)) + .bufferedReader().use { it.readText().trim() } + fun pickerShown() = ui.all().any { it.packageName?.contains("documentsui") == true } + val resumed = AtomicReference(activity) + val tracker = object : Application.ActivityLifecycleCallbacks { + override fun onActivityResumed(activity: Activity) { if (activity is MainActivity) resumed.set(activity) } + override fun onActivityPaused(activity: Activity) {} + override fun onActivityCreated(activity: Activity, state: Bundle?) {} + override fun onActivityStarted(activity: Activity) {} + override fun onActivityStopped(activity: Activity) {} + override fun onActivitySaveInstanceState(activity: Activity, state: Bundle) {} + override fun onActivityDestroyed(activity: Activity) {} + } + val rotation = shell("wm user-rotation") + check(rotation == "free" || Regex("""lock [0-3]""").matches(rotation)) + test.runOnMainSync { model.reset() } + val field = ui.await { it.viewIdResourceName == "backup_password" } + check(field.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, Bundle().apply { + putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, UUID.randomUUID().toString()) + })) + app.registerActivityLifecycleCallbacks(tracker) + try { + ui.clickTag("backup_export") + check(shell("wm user-rotation lock 1").isEmpty()) + withTimeout(30_000) { while (!pickerShown()) delay(200) } + // The composition that started PBKDF2 is gone; the picker came from its successor. + check(activity.isDestroyed) + screenshot("backup-rotated-picker-cs.png") + check(test.uiAutomation.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK)) + ui.await { it.viewIdResourceName == "backup_password" && it.isVisibleToUser } + delay(1000) + check(!pickerShown() && !model.state.value.pickDocument && !model.state.value.busy) + marker("BACKUP:ROTATED_PICKER:cs:PASS") + } finally { + try { shell("wm user-rotation $rotation") } finally { app.unregisterActivityLifecycleCallbacks(tracker) } + } + delay(1000) // The restored rotation recreates the activity once more. + return checkNotNull(resumed.get()) +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/CellDetailEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/CellDetailEvidence.kt new file mode 100644 index 0000000..fd87d7e --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/CellDetailEvidence.kt @@ -0,0 +1,121 @@ +package cz.netkit.app.test + +import android.Manifest +import android.app.Activity +import android.app.Instrumentation +import android.content.Intent +import android.content.pm.PackageManager +import android.os.LocaleList +import android.view.accessibility.AccessibilityNodeInfo +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.cellular.CellDetailStatus +import cz.netkit.app.cellular.CellDetailViewModel +import cz.netkit.shared.cellular.CellTech +import java.util.Locale +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withTimeout + +private val CELL_PERMISSIONS = listOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, + Manifest.permission.READ_PHONE_STATE) + +/** + * Zadání 53, AC-002 on the emulator: the production Overview with the real [CellDetailViewModel] + * and the emulator modem's synthetic LTE cell (`requestCellInfoUpdate`, no fake data). + * + * The runner revokes location and phone permissions before the phase (revoking inside would kill + * this process). 1) Without them the expanded detail explains why, offers both requests and + * requests nothing. 2) After the grant (a recreate = resume) the detail shows the serving LTE + * cell: snapshots in Czech and English. 3) Collapsing forgets the detail of the SIM. + * Markers carry only band / EARFCN / PCI of the synthetic cell, never its cell ID or TAC. + */ +suspend fun cellDetailEvidence(test: Instrumentation, app: M1TestApplication, screenshot: (String) -> Unit, marker: (String) -> Unit) { + val ui = SshEvidenceUi(test) + val localeManager = app.getSystemService(android.app.LocaleManager::class.java) + val beforeLocales = localeManager.applicationLocales + var activity: Activity? = null + suspend fun settle() { + delay(1_500) + test.waitForIdleSync() + test.uiAutomation.waitForIdle(500, 5_000) + } + /** Up first (a restored list may sit below the target), then down, 12 pages each way. */ + suspend fun scrollTo(predicate: (AccessibilityNodeInfo) -> Boolean): AccessibilityNodeInfo { + for (direction in listOf(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD, AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) { + repeat(12) { + ui.all().firstOrNull { predicate(it) && it.isVisibleToUser }?.let { return it } + if (ui.all().firstOrNull { it.isScrollable }?.performAction(direction) != true) return@repeat + delay(300) + } + } + return ui.await { predicate(it) && it.isVisibleToUser } + } + fun recreate(action: () -> Unit) { + val monitor = test.addMonitor(MainActivity::class.java.name, null, false) + try { + test.runOnMainSync(action) + activity = test.waitForMonitorWithTimeout(monitor, 10_000) ?: error("No recreated activity") + } finally { test.removeMonitor(monitor) } + } + try { + check(CELL_PERMISSIONS.none { app.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }) { + "Runner must revoke location and phone permissions before the phase" + } + test.runOnMainSync { localeManager.applicationLocales = LocaleList(Locale.forLanguageTag("cs")) } + activity = test.startActivitySync(Intent(app, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)) + lateinit var model: CellDetailViewModel + test.runOnMainSync { model = ViewModelProvider(activity as MainActivity)[CellDetailViewModel::class.java] } + ui.clickTag("tab_signal") + + // --- 1) Without permissions: explanation, both buttons, no request --------------------------- + val toggle = scrollTo { it.viewIdResourceName?.startsWith("cell_detail_toggle_") == true } + val subId = toggle.viewIdResourceName!!.removePrefix("cell_detail_toggle_").toInt() + ui.click(toggle) + scrollTo { it.viewIdResourceName == "cell_detail_permission" } + scrollTo { it.text?.toString() == app.getString(R.string.cell_detail_permission_why) } + ui.await { it.viewIdResourceName == "cell_detail_allow_location" } + ui.await { it.viewIdResourceName == "cell_detail_allow_phone" } + delay(CELL_REQUEST_GRACE_MS) + check(model.state.value.bySim.isEmpty()) { "Cell info requested without permissions" } + marker("CELL:DETAIL:NO_REQUEST_WITHOUT_PERMISSION:PASS") + settle() + screenshot("cell-detail-permission-cs.png") + marker("CELL:DETAIL:PERMISSION:UI_VERIFIED") + + // --- 2) Granted (emulator only) → recreate = resume → synthetic LTE cell ----------------------- + CELL_PERMISSIONS.forEach { test.uiAutomation.grantRuntimePermission(app.packageName, it) } + recreate { activity!!.recreate() } + check(ViewModelProvider(activity as MainActivity)[CellDetailViewModel::class.java] === model) + val entry = withTimeout(20_000) { + model.state.first { state -> state.bySim[subId]?.status == CellDetailStatus.READY && state.bySim[subId]?.detail != null } + }.bySim.getValue(subId) + val serving = entry.detail!!.serving.firstOrNull { it.tech == CellTech.LTE && it.primary } + ?: error("Emulator returned no primary LTE cell") + marker("CELL:DETAIL:LTE:band=${serving.band?.number}:earfcn=${serving.arfcn}:pci=${serving.pci}:neighbors=${entry.detail!!.neighbors.size}") + for (language in listOf("cs", "en")) { + if (language == "en") recreate { localeManager.applicationLocales = LocaleList(Locale.forLanguageTag("en")) } + val res = activity!!.resources + scrollTo { it.viewIdResourceName == "cell_detail_serving_0" } + scrollTo { it.text?.toString() == res.getString(R.string.cell_detail_eci) } + ui.await { it.text?.toString() == res.getString(R.string.cell_detail_title) } + check(ui.all().none { it.viewIdResourceName == "cell_detail_permission" }) + settle() + screenshot("cell-detail-$language.png") + marker("CELL:DETAIL:LTE:$language:UI_VERIFIED") + } + + // --- 3) Collapse → the detail of the SIM is forgotten --------------------------------------- + ui.clickTag("cell_detail_toggle_$subId") + withTimeout(5_000) { model.state.first { subId !in it.bySim } } + marker("CELL:DETAIL:FORGET_ON_COLLAPSE:PASS") + } finally { + test.runOnMainSync { activity?.finish() } + test.runOnMainSync { localeManager.applicationLocales = beforeLocales } + } +} + +/** Long enough for a request to have reached the ViewModel state if one had been made. */ +private const val CELL_REQUEST_GRACE_MS = 1_500L diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/LanRozsireniEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/LanRozsireniEvidence.kt new file mode 100644 index 0000000..f515f64 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/LanRozsireniEvidence.kt @@ -0,0 +1,331 @@ +package cz.netkit.app.test + +import android.app.Instrumentation +import android.os.Build +import android.os.SystemClock +import android.view.accessibility.AccessibilityNodeInfo +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawWithContent +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.ViewModelStoreOwner +import cz.netkit.app.lan.DeviceRow +import cz.netkit.app.lan.LanBackend +import cz.netkit.app.lan.LanDeviceNetworkReader +import cz.netkit.app.lan.LanTool +import cz.netkit.app.lan.LanViewModel +import cz.netkit.app.lan.NetworkInfoCard +import cz.netkit.app.lan.PingFields +import cz.netkit.app.lan.ToolRoute +import cz.netkit.app.lan.UdpServiceProbe +import cz.netkit.app.lan.deviceRows +import cz.netkit.app.ui.Panel +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.wol.AndroidNetworkInfoProvider +import cz.netkit.app.wol.AndroidPacketSender +import cz.netkit.app.wol.AndroidWolSecureOnStore +import cz.netkit.shared.lan.LanAliveMethod +import cz.netkit.shared.lan.LanDevice +import cz.netkit.shared.lan.LanDeviceName +import cz.netkit.shared.lan.LanNameSource +import cz.netkit.shared.lan.LanRunStatus +import cz.netkit.shared.lan.TargetConfirmationReason +import cz.netkit.shared.lan.UdpProbeOutcome +import cz.netkit.shared.lan.UdpServicePorts +import cz.netkit.shared.wol.TargetMode +import cz.netkit.shared.wol.WolController +import cz.netkit.shared.wol.WolDeviceDraft +import cz.netkit.shared.wol.WolDeviceStore +import cz.netkit.shared.wol.WolDevice +import cz.netkit.shared.wol.encodeWolCsvExport +import cz.netkit.shared.wol.encodeWolExport +import java.net.Inet6Address +import java.net.InetAddress +import java.net.ServerSocket +import java.net.InetSocketAddress +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout + +/* + * Zadání 39 evidence on the emulator (synthetic data, own/loopback/host-fixture targets only). + * Fixture ports for lan-udp are fixed so the runner needs no extra arguments: + * `python3 -I tools/testsrv/udp_services.py --community netkit-fixture-community --snmp-port 18161 --ntp-port 18123 --dns-port 18053` + * and for wol-secureon `python3 -I tools/testsrv/wol_listener.py --count 1 --secureon 112233445566`. + */ +const val LAN39_FIXTURE_COMMUNITY = "netkit-fixture-community" +val LAN39_FIXTURE_PORTS = UdpServicePorts(18161, 18123, 18053) + +private fun syntheticDevices(count: Int, first: Int = 1): List = (first until first + count).map { host -> + val address = "10.0.${host / 256}.${host % 256}" + LanDevice(address, names = if (host % 3 == 0) listOf(LanDeviceName(LanNameSource.PTR, "host-$host.lan")) else emptyList(), + isGateway = host == 1, firstSeenElapsedMs = 0, lastSeenElapsedMs = 0, lastRttMs = host % 50 + 0.5, method = LanAliveMethod.ICMP) +} + +/** AC-001: 254 synthetic rows as lazy items; laziness, scroll, testTags, anchor and composition time vs. the old single panel. */ +@OptIn(ExperimentalComposeUiApi::class) +suspend fun captureLanListEvidence(instrumentation: Instrumentation, activity: ComponentActivity, screenshot: (String) -> Unit, marker: (String) -> Unit) { + val devices = syntheticDevices(254) + val identity = "SYNTHETIC UI · 254 devices (lazy rows)" + + suspend fun firstFrameMs(legacy: Boolean): Double { + // Empty screen first, so every measurement starts from the same state. + instrumentation.runOnMainSync { activity.setContent { Text("reset") } } + instrumentation.waitForIdleSync() + val drawn = CompletableDeferred() + val started = System.nanoTime() + instrumentation.runOnMainSync { + activity.setContent { + NetKitTheme { + LazyColumn(Modifier.fillMaxSize().drawWithContent { drawContent(); if (!drawn.isCompleted) drawn.complete(System.nanoTime()) }, + contentPadding = PaddingValues(Spacing.normal)) { + if (legacy) item(key = "devices") { + // The pre-39 implementation: one item, every row composed in a Column. + Panel(padding = Spacing.normal) { Column { devices.forEachIndexed { index, device -> DeviceRow(device, index > 0) {} } } } + } else deviceRows(devices) {} + } + } + } + } + val end = withTimeout(10_000) { drawn.await() } + instrumentation.waitForIdleSync() + return (end - started) / 1_000_000.0 + } + // Warm-up of both paths (class loading, fonts), then alternating measured runs. + firstFrameMs(true); firstFrameMs(false) + val legacy = mutableListOf(); val lazy = mutableListOf() + repeat(5) { legacy += firstFrameMs(true); lazy += firstFrameMs(false) } + fun median(values: List) = values.sorted()[values.size / 2] + marker("LAN_LIST:FIRST_FRAME_MS:legacy=${"%.1f".format(java.util.Locale.ROOT, median(legacy))};lazy=${"%.1f".format(java.util.Locale.ROOT, median(lazy))};" + + "legacy_runs=${legacy.joinToString("/") { "%.1f".format(java.util.Locale.ROOT, it) }};lazy_runs=${lazy.joinToString("/") { "%.1f".format(java.util.Locale.ROOT, it) }}") + + // Behaviour on the production rows. + val listState = LazyListState() + var shown by mutableStateOf(devices) + instrumentation.runOnMainSync { + activity.setContent { + NetKitTheme { + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + LazyColumn(Modifier.fillMaxSize().safeDrawingPadding().semantics { testTagsAsResourceId = true }, state = listState, + contentPadding = PaddingValues(Spacing.normal)) { + item(key = "identity") { Text(identity, style = MaterialTheme.typography.labelSmall) } + deviceRows(shown) {} + } + } + } + } + } + instrumentation.waitForIdleSync() + awaitNode(instrumentation) { it.text?.toString() == identity } + awaitNode(instrumentation) { it.viewIdResourceName == "devices_row_10.0.0.1" } + check(findNode(instrumentation) { it.viewIdResourceName == "devices_row_10.0.0.254" } == null) { "last row composed before scrolling" } + val composed = withContext(Dispatchers.Main) { listState.layoutInfo.visibleItemsInfo.size } + check(composed in 2..40) { "visible items: $composed" } + marker("LAN_LIST:LAZY_VISIBLE_ITEMS:$composed") + delay(800) + screenshot("lan-list-top.png") + withContext(Dispatchers.Main) { listState.scrollToItem(254) } + instrumentation.waitForIdleSync() + awaitNode(instrumentation) { it.viewIdResourceName == "devices_row_10.0.0.254" } + marker("LAN_LIST:SCROLL_END_ROW_254:PASS") + // Anchor: with row 10.0.0.100 first visible, hosts appearing above it must not move it. + withContext(Dispatchers.Main) { listState.scrollToItem(100) } + instrumentation.waitForIdleSync() + // The first visible item (an item partly inside the top content padding does not count). + fun firstKey() = listState.layoutInfo.visibleItemsInfo.first { it.index == listState.firstVisibleItemIndex }.key + val anchor = withContext(Dispatchers.Main) { firstKey() } + marker("LAN_LIST:ANCHOR_BEFORE:$anchor") + check(anchor == "device:10.0.0.100") { "anchor $anchor" } + val growing = syntheticDevices(253, first = 2) + instrumentation.runOnMainSync { shown = growing.filter { it.address != "10.0.0.50" } } + instrumentation.waitForIdleSync() + instrumentation.runOnMainSync { shown = growing } + instrumentation.waitForIdleSync() + delay(300) + val after = withContext(Dispatchers.Main) { firstKey() } + marker("LAN_LIST:ANCHOR_AFTER:$after") + check(after == anchor) { "anchor moved to $after" } + awaitNode(instrumentation) { it.viewIdResourceName == "devices_row_10.0.0.100" } + marker("LAN_LIST:ANCHOR_KEPT_ON_INSERT:PASS") + delay(800) + screenshot("lan-list-middle.png") + marker("LAN_LIST:254_ROWS_TESTTAGS:PASS") +} + +/** AC-002 + AC-003: Info o síti from the real emulator Wi-Fi, IPv6 ping/AAAA/TCP through production code. */ +@OptIn(ExperimentalComposeUiApi::class) +suspend fun captureLanIpv6Evidence(instrumentation: Instrumentation, activity: ComponentActivity, screenshot: (String) -> Unit, marker: (String) -> Unit) { + val app = instrumentation.targetContext.applicationContext as android.app.Application + val backend = LanBackend(app) + val wifi = withContext(Dispatchers.IO) { backend.wifi() } ?: error("Wi-Fi unavailable") + val info = LanDeviceNetworkReader(app).info(wifi) ?: error("LinkProperties unavailable") + marker("LAN_INFO:SDK:${Build.VERSION.SDK_INT};dhcp=${info.dhcpServer ?: "null"};mtu=${info.mtu};ipv6=${info.ipv6.size};dns=${info.dnsServers.size}") + check(info.dhcpServerSupported == (Build.VERSION.SDK_INT >= 30)) + val identity = "EMULATOR · Info o síti (LinkProperties)" + instrumentation.runOnMainSync { + activity.setContent { + NetKitTheme { + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column(Modifier.safeDrawingPadding().verticalScroll(rememberScrollState()).padding(Spacing.normal) + .semantics { testTagsAsResourceId = true }, verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(identity, style = MaterialTheme.typography.labelSmall) + NetworkInfoCard(info, initiallyExpanded = true) + } + } + } + } + } + instrumentation.waitForIdleSync() + awaitNode(instrumentation) { it.text?.toString() == identity } + awaitNode(instrumentation) { it.text?.toString() == "${wifi.address}/${wifi.prefix}" } + marker("LAN_INFO:CARD:PASS") + delay(1_000) + screenshot("lan-network-info.png") + + // IPv6 ping of ::1 through the real tool ViewModel (confirmation like 127.0.0.1, then replies). + val owner = object : ViewModelStoreOwner { override val viewModelStore = ViewModelStore() } + try { + lateinit var model: LanViewModel + instrumentation.runOnMainSync { + model = ViewModelProvider(owner, ViewModelProvider.AndroidViewModelFactory(app))[LanViewModel::class.java] + } + withTimeout(8_000) { model.state.first { it.wifiAddress != null } } + instrumentation.runOnMainSync { + model.tool(LanTool.PING); model.pingFields(PingFields(count = "3", seconds = "0.3")); model.timeout("1000"); model.host("::1"); model.start() + } + val asked = withTimeout(8_000) { model.state.first { it.confirmation || it.error != null } } + check(asked.confirmation && asked.confirmationReasons == setOf(TargetConfirmationReason.OUTSIDE_WIFI)) { "reasons ${asked.confirmationReasons} error ${asked.error}" } + instrumentation.runOnMainSync { model.start(true) } + val done = withTimeout(15_000) { model.state.first { !it.busy && it.runStatus != LanRunStatus.RUNNING && it.runStatus != LanRunStatus.IDLE } } + check(done.runStatus == LanRunStatus.FINISHED && done.received == 3) { "ping ::1 status ${done.runStatus} received ${done.received} error ${done.error}" } + marker("LAN_IPV6:PING_LOOPBACK_VM:PASS:rtt=${done.samples.filterNotNull().joinToString(";") { "%.2f".format(java.util.Locale.ROOT, it) }}") + // A trace to IPv6 is refused with its own message, not a crash. + instrumentation.runOnMainSync { model.tool(LanTool.TRACE); model.host("::1"); model.start() } + val refused = withTimeout(8_000) { model.state.first { it.error != null || it.confirmation } } + check(refused.error == cz.netkit.app.R.string.lan39_ipv6_trace_unsupported) { "trace error ${refused.error}" } + marker("LAN_IPV6:TRACE_REFUSED:PASS") + } finally { instrumentation.runOnMainSync { owner.viewModelStore.clear() } } + + // Own link-local over the Wi-Fi (needs the interface scope) and TCP to [::1]. + val route = ToolRoute.wifi(wifi) + val ownLinkLocal = info.ipv6.map { it.substringBefore('/').substringBefore('%') }.firstOrNull { it.startsWith("fe80") } + if (ownLinkLocal != null) { + val reply = backend.pingWithOptions(route, ownLinkLocal, 1000, 16, false) + check(reply.milliseconds != null) { "no reply from own link-local" } + marker("LAN_IPV6:PING_OWN_LINK_LOCAL:PASS") + } else marker("LAN_IPV6:PING_OWN_LINK_LOCAL:NOT_POSSIBLE:no-link-local") + withContext(Dispatchers.IO) { + ServerSocket().use { server -> + server.bind(InetSocketAddress(InetAddress.getByName("::1"), 0)) + val open = backend.tcpProbe(route, "::1", server.localPort, 1000) + check(open.status == cz.netkit.shared.lan.ProbeStatus.OPEN && open.result?.port == server.localPort) { "tcp ::1 ${open.status}" } + } + } + marker("LAN_IPV6:TCP_LOOPBACK_OPEN:PASS") + + // AAAA: typed query through the Wi-Fi resolver (emulator forwards DNS to the host). + val answers = try { backend.resolve(route, "localhost") } catch (error: Exception) { marker("LAN_IPV6:AAAA:error=${error.javaClass.simpleName}"); emptyList() } + val v6 = answers.filterIsInstance() + marker("LAN_IPV6:AAAA_LOCALHOST:" + if (v6.isNotEmpty()) "PASS:${v6.first().hostAddress}" else "NOT_POSSIBLE:answers=${answers.size}") +} + +/** AC-004 emulator part: production UDP probe (socket bound to the Wi-Fi) against the host fixture via 10.0.2.2. */ +suspend fun captureLanUdpEvidence(instrumentation: Instrumentation, marker: (String) -> Unit) { + val app = instrumentation.targetContext.applicationContext as android.app.Application + val backend = LanBackend(app) + val wifi = withContext(Dispatchers.IO) { backend.wifi() } ?: error("Wi-Fi unavailable") + val result = UdpServiceProbe.identify(backend, wifi, "10.0.2.2", LAN39_FIXTURE_COMMUNITY.encodeToByteArray(), dnsAllowed = true, ports = LAN39_FIXTURE_PORTS) + marker("LAN_UDP:RESULT:snmp=${result.snmp.outcome};ntp=${result.ntp.outcome};dns=${result.dns.outcome}") + check(result.snmp.outcome == UdpProbeOutcome.OK && result.snmp.sysName == "netkit-fixture") { "snmp ${result.snmp}" } + marker("LAN_UDP:SNMP:PASS") + check(result.ntp.outcome == UdpProbeOutcome.OK && result.ntp.reply?.stratum == 2 && result.ntp.reply?.reference == "192.0.2.1") { "ntp ${result.ntp}" } + marker("LAN_UDP:NTP:PASS") + check(result.dns.outcome == UdpProbeOutcome.OK && result.dns.reply?.version == "netkit-fixture") { "dns ${result.dns}" } + marker("LAN_UDP:DNS_VERSION:PASS") + val wrong = UdpServiceProbe.identify(backend, wifi, "10.0.2.2", "wrong".encodeToByteArray(), dnsAllowed = false, ports = LAN39_FIXTURE_PORTS) + check(wrong.snmp.outcome == UdpProbeOutcome.NO_REPLY && wrong.dns.outcome == UdpProbeOutcome.SKIPPED) { "wrong ${wrong.snmp} ${wrong.dns}" } + marker("LAN_UDP:WRONG_COMMUNITY_SILENT:PASS") +} + +/** AC-005 emulator part: WolController + encrypted SecureOn store + real UDP sender to the host listener (108 B). */ +suspend fun captureWolSecureOnEvidence(instrumentation: Instrumentation, app: M1TestApplication, marker: (String) -> Unit) { + val scope = MainScope() + try { + val memory = object : WolDeviceStore { + var data: List = emptyList() + override suspend fun load() = data + override suspend fun save(devices: List) { data = devices } + } + val secrets = AndroidWolSecureOnStore(app.createWolSecretStore()) + lateinit var controller: WolController + instrumentation.runOnMainSync { + controller = WolController(memory, AndroidNetworkInfoProvider(app), AndroidPacketSender(app), scope, { 1L }, { "secureon-e2e" }, + secureOn = secrets) + } + withTimeout(5_000) { controller.state.first { !it.loading } } + withContext(Dispatchers.Main) { + controller.add() + controller.updateDraft(WolDeviceDraft(name = "SecureOn E2E", mac = "AA:BB:CC:DD:EE:FF", targetMode = TargetMode.CUSTOM, + customTarget = "10.0.2.2", port = "9009", repeatCount = "1", secureOn = "11:22:33:44:55:66")) + controller.save() + } + withTimeout(10_000) { controller.state.first { !it.saving && it.devices.isNotEmpty() } } + check(controller.state.value.secureOnIds == setOf("secureon-e2e")) + // The encrypted store holds it; the device list and both exports do not. + check(secrets.load().getValue("secureon-e2e").password.size == 6) + val exports = listOf(encodeWolExport(memory.data), encodeWolCsvExport(memory.data, { null }, "Default")).map { it.decodeToString() } + check(exports.none { "112233445566" in it.replace(":", "").replace("-", "") || "\"secureOn\":" in it }) { "export carries the password" } + check(memory.data.single().secureOnRequired) { "persistent protection flag" } + marker("WOL_SECUREON:STORED_NOT_EXPORTED:PASS") + withContext(Dispatchers.Main) { controller.wake("secureon-e2e") } + val outcome = withTimeout(10_000) { controller.state.first { it.outcomes["secureon-e2e"] != null && it.sendingDeviceId == null } } + check(outcome.outcomes.getValue("secureon-e2e").sent) { "send ${outcome.outcomes}" } + marker("WOL_SECUREON:SENT_TO_HOST_LISTENER:PASS") + } finally { + scope.cancel() + } +} + +private suspend fun awaitNode(instrumentation: Instrumentation, predicate: (AccessibilityNodeInfo) -> Boolean): AccessibilityNodeInfo = + withTimeout(8_000) { + var found = findNode(instrumentation, predicate) + val started = SystemClock.elapsedRealtime() + while (found == null) { delay(50); found = findNode(instrumentation, predicate); check(SystemClock.elapsedRealtime() - started < 8_000) } + found + } + +private fun findNode(instrumentation: Instrumentation, predicate: (AccessibilityNodeInfo) -> Boolean): AccessibilityNodeInfo? { + fun find(node: AccessibilityNodeInfo): AccessibilityNodeInfo? { + if (predicate(node)) return node + for (index in 0 until node.childCount) node.getChild(index)?.let(::find)?.let { return it } + return null + } + return instrumentation.uiAutomation.rootInActiveWindow?.let(::find) +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/LandscapeMloEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/LandscapeMloEvidence.kt new file mode 100644 index 0000000..bb3a8f2 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/LandscapeMloEvidence.kt @@ -0,0 +1,213 @@ +package cz.netkit.app.test + +import android.app.Instrumentation +import android.app.LocaleManager +import android.content.Intent +import android.content.res.Configuration +import android.graphics.Rect +import android.os.LocaleList +import android.os.ParcelFileDescriptor +import android.view.KeyEvent +import android.view.accessibility.AccessibilityNodeInfo +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.material3.Surface +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.wifi.live.MloCard +import cz.netkit.shared.wifi.AssociatedLink +import cz.netkit.shared.wifi.MloScanWidth +import cz.netkit.shared.wifi.mloConnection +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeout +import kotlin.math.roundToInt + +/** Real destinations and a connected M1 host fixture. Only the MLO card uses synthetic radio readings. */ +@OptIn(ExperimentalComposeUiApi::class) +internal suspend fun landscapeMloEvidence(test: Instrumentation, app: M1TestApplication, language: String, + profileId: String, fingerprint: String, screenshot: (String) -> Unit, marker: (String) -> Unit) { + require(language == "cs" || language == "en") + val ui = SshEvidenceUi(test) + fun shell(command: String): String = ParcelFileDescriptor.AutoCloseInputStream(test.uiAutomation.executeShellCommand(command)) + .bufferedReader().use { it.readText().trim() } + val size = shell("wm size") + check(Regex("""Physical size: \d+x\d+""").containsMatchIn(size)) + val originalSize = Regex("""Override size: (\d+x\d+)""").find(size)?.groupValues?.get(1) ?: "reset" + val rotation = shell("wm user-rotation") + check(rotation == "free" || Regex("""lock [0-3]""").matches(rotation)) + val locales = app.getSystemService(LocaleManager::class.java) + val originalLocales = locales.applicationLocales + val density = app.resources.displayMetrics.density + /* + * Integrace 2.0: Přehled shows the live indicator (an infinite "breathing" animation by design), so the main looper + * is never idle and Instrumentation.waitForIdleSync() can block forever on the emulator. One main-thread pass + * after a short pause is enough to have the verified frame laid out. + */ + suspend fun settle() { delay(150); test.runOnMainSync { } } + // The resumed MainActivity, followed across the recreations caused by `wm size` and rotation. + val resumed = java.util.concurrent.atomic.AtomicReference() + val tracker = object : android.app.Application.ActivityLifecycleCallbacks { + override fun onActivityResumed(activity: android.app.Activity) { if (activity is MainActivity) resumed.set(activity) } + override fun onActivityPaused(activity: android.app.Activity) { resumed.compareAndSet(activity as? MainActivity, null) } + override fun onActivityCreated(activity: android.app.Activity, state: android.os.Bundle?) {} + override fun onActivityStarted(activity: android.app.Activity) {} + override fun onActivityStopped(activity: android.app.Activity) {} + override fun onActivitySaveInstanceState(activity: android.app.Activity, state: android.os.Bundle) {} + override fun onActivityDestroyed(activity: android.app.Activity) {} + } + app.registerActivityLifecycleCallbacks(tracker) + /* + * Integrace 2.0 (first emulator run of this phase): the activity used to be finished between sizes, which left the + * portrait-locked launcher on top, so the locked user rotation was never applied and the wait for landscape timed + * out. NetKit now stays on top while the display changes; the system recreates the activity and the recreated, + * resumed instance (matching orientation and width class) is the one measured. + */ + suspend fun atSize(width: Int, height: Int, body: suspend (MainActivity) -> Unit) { + if (resumed.get() == null) test.startActivitySync(Intent(app, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)) + val pixels = "${(minOf(width, height) * density).roundToInt()}x${(maxOf(width, height) * density).roundToInt()}" + check(shell("wm user-rotation lock ${if (width > height) 1 else 0}").isEmpty()) + check(shell("wm size $pixels").isEmpty()) + val orientation = if (width > height) Configuration.ORIENTATION_LANDSCAPE else Configuration.ORIENTATION_PORTRAIT + fun matches(activity: MainActivity?) = activity != null && !activity.isFinishing && + activity.resources.configuration.let { it.orientation == orientation && (it.screenWidthDp >= 600) == (width >= 600) } + try { + withTimeout(15_000) { while (!matches(resumed.get())) delay(100) } + } catch (e: kotlinx.coroutines.TimeoutCancellationException) { + val current = resumed.get()?.resources?.configuration + marker("LAYOUT:SIZE_WAIT:${width}x$height:orientation=${current?.orientation}:widthDp=${current?.screenWidthDp}:" + + shell("dumpsys window displays").lines().firstOrNull { "mRotation=" in it }?.trim()) + throw e + } + settle() + val activity = checkNotNull(resumed.get()) + check(activity.resources.configuration.locales[0].language == language) + body(activity) + } + suspend fun tag(name: String) = ui.await { it.viewIdResourceName == name && it.isVisibleToUser } + fun bounds(node: AccessibilityNodeInfo) = Rect().apply { node.getBoundsInScreen(this) } + suspend fun save(name: String) { + delay(400) // Allow the tab transition and the frame containing the verified semantics to finish. + settle() + screenshot("$name-$language.png") + } + /* + * Integrace 2.0: right after `wm size`/rotation the system still animates the window, and node bounds read in + * that moment are transformed (e.g. rail at x = -468). Geometry is therefore read only once it is stable. + */ + suspend fun stableBounds(name: String): Rect = withTimeout(8_000) { + var last = bounds(tag(name)) + while (true) { + delay(250) + val now = bounds(tag(name)) + if (now == last && now.left >= 0 && now.top >= 0) break + last = now + } + last + } + suspend fun checkWide(layout: String, activity: MainActivity) { + val rail = stableBounds("nav_rail") + val tabs = listOf("signal" to "signal_screen", "wifi" to "wifi_scan_action", "lan" to "lan_segment_devices", + "ssh" to "ssh_add", "wol" to "wol_add") + for ((tab, content) in tabs) { + val item = "tab_$tab" + // A short landscape window can scroll the rail independently of the current destination. + if (ui.all().none { it.viewIdResourceName == item && it.isVisibleToUser }) { + ui.all().firstOrNull { it.isScrollable && bounds(it).right <= rail.right } + ?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) + } + ui.clickTag(item) + val actual = stableBounds(content) + if (!(actual.width() > 0 && actual.left >= rail.right && actual.right <= activity.window.decorView.width)) { + marker("LAYOUT:BOUNDS:$layout:$tab:content=$actual:rail=$rail:decor=${activity.window.decorView.width}") + } + check(actual.width() > 0 && actual.left >= rail.right && actual.right <= activity.window.decorView.width) + check(ui.all().none { it.viewIdResourceName == "nav_bottom" }) + save("$layout-$tab") + } + marker("LAYOUT:$layout:TABS:PASS") + } + + try { + test.runOnMainSync { locales.applicationLocales = LocaleList.forLanguageTags(language) } + atSize(412, 840) { + tag("nav_bottom") + check(ui.all().none { it.viewIdResourceName == "nav_rail" }) + save("portrait") + } + atSize(840, 412) { activity -> + checkWide("landscape", activity) + ui.clickTag("tab_ssh") + ui.clickTag("ssh_connect_$profileId") + ui.clickTag("ssh_confirm") + // On a 412 dp tall landscape window the fingerprint sits below the fold of the scrollable host-key dialog and + // Compose leaves clipped nodes out of the accessibility tree: scroll it into view, as the user would. + withTimeout(10_000) { + while (ui.all().none { it.text?.contains(fingerprint) == true }) { + ui.all().filter { it.isScrollable }.forEach { it.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) } + delay(250) + } + } + ui.clickTag("ssh_trust") + ui.await { it.text?.contains("NETKIT_FIXTURE_READY") == true } + val grid = bounds(tag("ssh_terminal_output")) + check(grid.height() > 0 && ui.all().none { it.viewIdResourceName in listOf("nav_rail", "nav_bottom", "tab_ssh") }) + save("landscape-terminal") + ui.clickTag("ssh_terminal_options") + ui.clickTag("ssh_toggle_controls") + tag("ssh_options") + check(bounds(tag("ssh_terminal_output")).height() < grid.height()) + ui.clickTag("ssh_terminal_options") + ui.clickTag("ssh_toggle_controls") + ui.await { it.viewIdResourceName == "ssh_terminal_output" && bounds(it).height() == grid.height() } + test.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK) + tag("ssh_options") + val closePrompt = activity.getString(R.string.ssh_close_confirm) + check(ui.all().none { it.text?.toString() == closePrompt }) + test.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK) + ui.await { it.text?.toString() == closePrompt } + ui.click(ui.await { it.text?.toString() == activity.getString(R.string.ssh_cancel) }) + tag("ssh_options") + ui.click(ui.await { it.text?.toString() == activity.getString(R.string.ssh_profiles) }) + tag("nav_rail") + marker("LAYOUT:TERMINAL:PASS") + } + atSize(800, 1000) { activity -> + checkWide("tablet", activity) + val mld = "02:00:00:00:52:01" + val synthetic = checkNotNull(mloConnection(listOf(AssociatedLink(0, 2, 36, 5180, -55, 3), + AssociatedLink(1, 8, 5, 5975, -63, 2)), mld, true, listOf(MloScanWidth(mld, 0, 5180, 1000, 2)), 1100)) + test.runOnMainSync { + activity.setContent { + NetKitTheme { + Surface(Modifier.fillMaxSize()) { + Column(Modifier.safeDrawingPadding().semantics { testTagsAsResourceId = true }) { MloCard(synthetic) } + } + } + } + } + check(tag("mlo_link_0").text.toString().let { it.contains("80 MHz") && it.contains("-55") && it.contains(activity.getString(R.string.wifi_mlo_active)) }) + check(tag("mlo_link_1").text.toString().let { it.contains("—") && it.contains("-63") && it.contains(activity.getString(R.string.wifi_mlo_idle)) }) + ui.await { it.text?.contains(mld) == true } + save("mlo-synthetic") + marker("MLO:SYNTHETIC:PASS") + } + marker("LAYOUT:LANGUAGE:$language") + } finally { + app.unregisterActivityLifecycleCallbacks(tracker) + resumed.get()?.let { activity -> test.runOnMainSync { activity.finish() } } + try { + check(shell("wm size $originalSize").isEmpty()) + } finally { + try { check(shell("wm user-rotation $rotation").isEmpty()) } + finally { test.runOnMainSync { locales.applicationLocales = originalLocales } } + } + } +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt index 130d534..240faf7 100644 --- a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt @@ -3,8 +3,10 @@ package cz.netkit.app.test import android.app.Activity import android.app.Application import android.app.Instrumentation +import android.app.LocaleManager import android.content.Context import android.content.Intent +import android.content.res.Configuration import android.Manifest import android.content.pm.PackageManager import android.location.LocationManager @@ -19,6 +21,7 @@ import cz.netkit.shared.json.jsonNestingDepth import cz.netkit.shared.speed.parseNdt7Measurement import android.graphics.Bitmap import android.os.Bundle +import android.os.LocaleList import android.os.Build import android.os.SystemClock import android.view.accessibility.AccessibilityNodeInfo @@ -89,17 +92,31 @@ class M1Instrumentation : Instrumentation() { phase=arguments.getString("phase").orEmpty() try { check(runId.matches(Regex("[a-f0-9]{32}"))) { "Invalid runId" } - check(phase in listOf("ui","lan","ssh","wifi","wifi-denied","ssh-ui","ssh-rotated","lan-confirm","ssh-lifecycle","ssh-legacy","lan-discovery","lan-icmp-rtt","wifi-freshness","ssh-reconnect","json-limits","ssh-key-editor","ssh-profiles-v2","ssh-profiles-r1","ssh-profiles-p3","update-dialog","wifi-scan-limit")) { "Invalid phase" } + check(phase in listOf("lan-trace-pause","lan-tools","ui","lan","ssh","wifi","wifi-denied","ssh-ui","ssh-rotated","lan-confirm","ssh-lifecycle","ssh-legacy","lan-discovery","lan-icmp-rtt","wifi-freshness","ssh-reconnect","json-limits","ssh-key-editor","ssh-profiles-v2","ssh-profiles-r1","ssh-profiles-p3","update-dialog","wifi-scan-limit","wifi-spectrum","wifi-extensions","wol-widget-intent","ssh-forward","ssh-snippet-log","lan-list","lan-v39","lan-udp","wol-secureon","cell-detail","ssh-background","ssh-background-denied","ssh-sftp","ssh-forwards-panel","netstatus-widget","system-settings","ssh-xterm","accessibility","landscape-mlo","share-results","tools-targets","ssh-lock","config-backup")) { "Invalid phase" } app=targetContext.applicationContext as M1TestApplication + // Zadání 42: the once-only notification question would cover every SSH UI phase; only the + // denied-notification phase starts from "never asked" (it resets this itself). + check(app.getSharedPreferences(cz.netkit.app.ssh.SshSessionKeeper.PREFS, 0).edit() + .putBoolean(cz.netkit.app.ssh.SshSessionKeeper.PREF_ASKED, true).commit()) marker("PHASE:$phase:START") runBlocking { - withTimeout(if (phase == "ssh-lifecycle") 380_000L else 115_000L) { - when(phase) { "wifi-scan-limit" -> wifiScanLimitEvidence(this@M1Instrumentation, app, arguments.getString("language") ?: "cs", ::marker); "update-dialog" -> updateDialogEvidence(this@M1Instrumentation, app, arguments.getString("language") ?: "cs", ::marker); "ssh-profiles-p3" -> sshProfilesP3Evidence(this@M1Instrumentation, app, ::screenshot, ::marker); "ssh-profiles-r1" -> sshProfilesR1Evidence(this@M1Instrumentation, app, ::screenshot, ::marker); "ssh-profiles-v2" -> sshProfilesV2Evidence(this@M1Instrumentation, app, ::screenshot, ::marker); "ssh-key-editor" -> sshKeyEditorEvidence(this@M1Instrumentation, app, arguments.getString("stage") ?: "2", arguments.getString("order") != "import-first", ::screenshot, ::marker); "json-limits" -> jsonLimitsPhase(); "ssh-reconnect" -> sshUiPhase(reconnect = true); "wifi-freshness" -> wifiFreshnessPhase(); "ui" -> uiPhase(); "lan" -> lanPhase(); "lan-icmp-rtt" -> lanIcmpRttPhase(); "lan-confirm" -> lanConfirmPhase(); "lan-discovery" -> lanDiscoveryPhase(); "ssh" -> sshPhase(); "ssh-ui" -> sshUiPhase(); "ssh-lifecycle" -> sshUiPhase(lifecycle = true); "ssh-rotated" -> sshRotatedPhase(); "ssh-legacy" -> sshLegacyPhase(); "wifi" -> wifiPhase(false); "wifi-denied" -> wifiPhase(true) } + withTimeout(if (phase == "ssh-lifecycle") 380_000L else if (phase == "share-results") 300_000L else if (phase == "ssh-sftp") 200_000L else 115_000L) { + when(phase) { + "config-backup" -> backupEvidence(this@M1Instrumentation, app, ::screenshot, ::marker) + "ssh-lock" -> sshLockEvidence(this@M1Instrumentation, app, ::screenshot, ::marker) + "landscape-mlo" -> { + val config = withContext(Dispatchers.IO) { fixture() } + val profile = seedUiProfile(config) + checkpoint = "LANDSCAPE_MLO" + landscapeMloEvidence(this@M1Instrumentation, app, arguments.getString("language") ?: "cs", + profile.id, config.getValue("server").jsonObject.getValue("hostKeyFingerprint").jsonPrimitive.content, + ::screenshot, ::marker) + }; "accessibility" -> withActivity { accessibilityEvidence(this@M1Instrumentation, it, ::screenshot, ::marker) }; "ssh-xterm" -> { checkpoint="SSH_XTERM"; sshXtermEvidence(this@M1Instrumentation, app, withContext(Dispatchers.IO) { fixture() }, ::screenshot, ::marker) }; "ssh-background", "ssh-background-denied" -> { checkpoint="SSH_BACKGROUND"; sshBackgroundEvidence(this@M1Instrumentation, app, withContext(Dispatchers.IO) { fixture() }, phase == "ssh-background", ::screenshot, ::marker) }; "ssh-sftp" -> { checkpoint="SSH_SFTP"; sshSftpEvidence(this@M1Instrumentation, app, withContext(Dispatchers.IO) { fixture() }, runId, ::screenshot, ::marker) }; "ssh-forwards-panel" -> { checkpoint="SSH_FORWARDS_PANEL"; sshForwardsPanelEvidence(this@M1Instrumentation, app, withContext(Dispatchers.IO) { fixture() }, ::screenshot, ::marker) }; "ssh-forward" -> { checkpoint="SSH_FORWARD"; sshForwardEvidence(app, withContext(Dispatchers.IO) { fixture() }, runId, ::marker) }; "ssh-snippet-log" -> { checkpoint="SSH_SNIPPET_LOG"; sshSnippetLogEvidence(this@M1Instrumentation, app, withContext(Dispatchers.IO) { fixture() }, ::screenshot, ::marker) }; "lan-trace-pause" -> lanTracePausePhase(); "lan-tools" -> lanToolsPhase(arguments.getString("language") ?: "cs"); "wifi-scan-limit" -> wifiScanLimitEvidence(this@M1Instrumentation, app, arguments.getString("language") ?: "cs", ::marker); "update-dialog" -> updateDialogEvidence(this@M1Instrumentation, app, arguments.getString("language") ?: "cs", ::marker); "ssh-profiles-p3" -> sshProfilesP3Evidence(this@M1Instrumentation, app, ::screenshot, ::marker); "ssh-profiles-r1" -> sshProfilesR1Evidence(this@M1Instrumentation, app, ::screenshot, ::marker); "ssh-profiles-v2" -> sshProfilesV2Evidence(this@M1Instrumentation, app, ::screenshot, ::marker); "ssh-key-editor" -> sshKeyEditorEvidence(this@M1Instrumentation, app, arguments.getString("stage") ?: "2", arguments.getString("order") != "import-first", ::screenshot, ::marker); "json-limits" -> jsonLimitsPhase(); "ssh-reconnect" -> sshUiPhase(reconnect = true); "wifi-freshness" -> wifiFreshnessPhase(); "wifi-spectrum" -> wifiSpectrumPhase(); "wifi-extensions" -> wifiExtensionsPhase(); "wol-widget-intent" -> wolWidgetIntentEvidence(this@M1Instrumentation, app, ::marker); "lan-list" -> withActivity { captureLanListEvidence(this@M1Instrumentation, it, ::screenshot, ::marker) }; "lan-v39" -> withActivity { captureLanIpv6Evidence(this@M1Instrumentation, it, ::screenshot, ::marker) }; "lan-udp" -> captureLanUdpEvidence(this@M1Instrumentation, ::marker); "wol-secureon" -> captureWolSecureOnEvidence(this@M1Instrumentation, app, ::marker); "cell-detail" -> cellDetailEvidence(this@M1Instrumentation, app, ::screenshot, ::marker); "share-results" -> shareResultsEvidence(this@M1Instrumentation, app, ::screenshot, ::marker); "tools-targets" -> toolTargetsEvidence(this@M1Instrumentation, app, ::screenshot, ::marker); "netstatus-widget" -> netStatusWidgetEvidence(this@M1Instrumentation, app, ::marker); "system-settings" -> systemSettingsEvidence(this@M1Instrumentation, app, arguments.getString("language") ?: "cs", ::screenshot, ::marker); "ui" -> uiPhase(); "lan" -> lanPhase(); "lan-icmp-rtt" -> lanIcmpRttPhase(); "lan-confirm" -> lanConfirmPhase(); "lan-discovery" -> lanDiscoveryPhase(); "ssh" -> sshPhase(); "ssh-ui" -> sshUiPhase(); "ssh-lifecycle" -> sshUiPhase(lifecycle = true); "ssh-rotated" -> sshRotatedPhase(); "ssh-legacy" -> sshLegacyPhase(); "wifi" -> wifiPhase(false); "wifi-denied" -> wifiPhase(true) } } } } catch (failure: Throwable) { // Exception class/step only: provider/library messages may include credentials or key data. - if (phase == "wifi-scan-limit" || phase == "update-dialog" || phase == "ssh-key-editor" || phase == "ssh-profiles-v2" || phase == "ssh-profiles-r1" || phase == "ssh-profiles-p3") { + if (phase == "config-backup" || phase == "cell-detail" || phase == "share-results" || phase == "tools-targets" || phase == "landscape-mlo" || phase == "accessibility" || phase == "ssh-xterm" || phase == "wifi-scan-limit" || phase == "update-dialog" || phase == "ssh-key-editor" || phase == "ssh-profiles-v2" || phase == "ssh-profiles-r1" || phase == "ssh-profiles-p3" || phase == "ssh-forward" || phase == "ssh-snippet-log" || phase.startsWith("ssh-background") || phase == "ssh-sftp" || phase == "ssh-forwards-panel" || phase == "system-settings") { marker("SSH_TEST_STACK:" + failure.stackTrace.take(12).joinToString(";")) try { screenshot("ssh-test-failure.png") } catch (_: Exception) { } } @@ -160,6 +177,27 @@ class M1Instrumentation : Instrumentation() { } finally { runOnMainSync { activity.finish() } } } + /** Zadání 39 phases draw synthetic or emulator content on top of a started MainActivity. */ + private suspend fun withActivity(body: suspend (androidx.activity.ComponentActivity) -> Unit) { + val activity = startActivitySync(Intent(targetContext, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as androidx.activity.ComponentActivity + try { body(activity) } finally { runOnMainSync { activity.finish() } } + } + private suspend fun wifiSpectrumPhase() { + val activity = startActivitySync(Intent(targetContext, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as androidx.activity.ComponentActivity + try { captureWifiSpectrumEvidence(this, activity, ::screenshot, ::marker) } + finally { runOnMainSync { activity.finish() } } + } + private suspend fun wifiExtensionsPhase() { + val activity = startActivitySync(Intent(targetContext, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as androidx.activity.ComponentActivity + try { captureWifiExtensionsEvidence(this, activity, ::screenshot, ::marker) } + finally { runOnMainSync { activity.finish() } } + } private suspend fun uiPhase() { val activity=startActivitySync(Intent(targetContext,MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) @@ -322,6 +360,116 @@ class M1Instrumentation : Instrumentation() { check(server.getValue("sshPort").jsonPrimitive.int == 22222) } } + /** Real ViewModel and pinned route; the TTL backend never sends a packet. */ + private suspend fun lanTracePausePhase() { + val sixthHop = CompletableDeferred() + var hold = false + val ttls = java.util.concurrent.CopyOnWriteArrayList() + lateinit var model: LanViewModel + val owner = ViewModelStore() + runOnMainSync { + val provider = ViewModelProvider.create(owner, object : androidx.lifecycle.ViewModelProvider.Factory { + @Suppress("UNCHECKED_CAST") + override fun create(modelClass: Class): T = + LanViewModel(app, LanBackend(app)) { _, _, _, ttl -> + ttls += ttl + if (ttl == 6 && hold) { sixthHop.complete(Unit); awaitCancellation() } + cz.netkit.shared.lan.PingReply(if (ttl == 6) 1.0 else null) + } as T + }) + model = provider[LanViewModel::class] + } + suspend fun startTrace() { + runOnMainSync { model.tool(LanTool.TRACE); model.host("10.0.2.2"); model.start() } + val ready = model.state.first { it.confirmation || it.awaitingTrace || it.error != null } + check(ready.error == null) + if (ready.confirmation) runOnMainSync { model.start(true) } + val paused = model.state.first { it.awaitingTrace } + check(paused.busy && paused.notice == R.string.lan_trace_paused && ttls.toList() == (1..5).toList()) + runOnMainSync { model.continueTrace() } + } + try { + model.state.first { it.wifiAddress != null } + startTrace() + val done = model.state.first { !it.busy } + check(done.results.last().address == "10.0.2.2" && ttls.toList() == (1..6).toList()) + ttls.clear() + hold = true + startTrace() + sixthHop.await() + runOnMainSync { model.cancelActive() } + check(model.state.value.results.size == 5 && !model.state.value.awaitingTrace) + marker("LAN:TRACE:RESUME_CANCEL:PASS") + } finally { runOnMainSync { owner.clear() } } + } + private suspend fun lanToolsPhase(language: String) { + require(language in setOf("cs", "en")) + check(Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) + val localeManager = app.getSystemService(LocaleManager::class.java) + val beforeLocales = localeManager.applicationLocales + val requestedLocales = LocaleList.forLanguageTags(language) + val expected = app.createConfigurationContext(Configuration().apply { setLocales(requestedLocales) }) + var activity: MainActivity? = null + try { + runOnMainSync { localeManager.applicationLocales = requestedLocales } + val screen = startActivitySync(Intent(targetContext, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as MainActivity + activity = screen + check(screen.resources.configuration.locales[0].language == language) + marker("LAN:LANGUAGE:$language") + + suspend fun setSubnetInput(value: String) { + val field = awaitNode { it.viewIdResourceName == "subnet_input" && it.isEditable } + check(field.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, Bundle().apply { + putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, value) + })) + } + suspend fun awaitSubnetRow(label: Int, value: String) { + val name = expected.getString(label) + awaitNode { row -> + row.isClickable && row.isLongClickable && nodes(row).mapNotNull { it.text }.joinToString(" ").let { + it.contains(name) && value in it.split(' ', '\n', ',') + } + } + } + suspend fun interpretationButton(label: Int, prefix: Int): AccessibilityNodeInfo { + val text = expected.getString(label, prefix) + return awaitNode { button -> + button.isClickable && button.isEnabled && nodes(button).any { it.text?.toString() == text } + } + } + + clickTag("tab_lan") + clickTag("lan_segment_tools") + runOnMainSync { ViewModelProvider(screen)[LanViewModel::class.java].tool(LanTool.SUBNET) } + setSubnetInput("192.0.2.10/27") + awaitSubnetRow(R.string.lan_subnet_network, "192.0.2.0") + awaitSubnetRow(R.string.lan_subnet_broadcast, "192.0.2.31") + awaitSubnetRow(R.string.lan_subnet_wildcard, "0.0.0.31") + screenshot("lan-subnet.png") + marker("LAN:SUBNET:PASS") + + setSubnetInput("192.0.2.10 0.0.0.0") + awaitSubnetRow(R.string.lan_subnet_network, "0.0.0.0") + val toggle = interpretationButton(R.string.lan_using_mask, 0) + marker("LAN:SUBNET:MASK_0:PASS") + check(toggle.performAction(AccessibilityNodeInfo.ACTION_CLICK)) + interpretationButton(R.string.lan_using_wildcard, 32) + awaitSubnetRow(R.string.lan_subnet_network, "192.0.2.10") + screenshot("lan-subnet-wildcard.png") + marker("LAN:SUBNET:WILDCARD_32:PASS") + + runOnMainSync { ViewModelProvider(screen)[LanViewModel::class.java].tool(LanTool.PING) } + clickTag("ping_advanced") + awaitNode { it.text?.toString()?.contains(expected.getString(R.string.lan_ping_count)) == true } + marker("LAN:DF_SUPPORTED:${cz.netkit.app.lan.WifiIcmp.supportsDf()}") + screenshot("lan-ping-advanced.png") + } finally { + runOnMainSync { activity?.finish() } + runOnMainSync { localeManager.applicationLocales = beforeLocales } + } + } private suspend fun lanPhase() = withContext(Dispatchers.IO) { fixture() val backend=LanBackend(app) @@ -440,24 +588,24 @@ class M1Instrumentation : Instrumentation() { marker("LAN_DISCOVERY:LOOPBACK_24_UNDER_20S:PASS") } finally { runOnMainSync { owner.viewModelStore.clear() } } } + private suspend fun seedUiProfile(config: JsonObject, reconnect: Boolean = false): SshProfile { + val server = config.getValue("server").jsonObject + val profile = SshProfile("m1-ui-profile", "M1 UI fixture", "10.0.2.2", 22222, + server.getValue("username").jsonPrimitive.content, secretRef = "ui-password", + startupCommand = if (reconnect) "netkit-check" else "") + checkpoint = "SSH_UI_SEED" + withContext(Dispatchers.IO) { + val bytes = config.getValue("client").jsonObject.getValue("password").jsonPrimitive.content.encodeToByteArray() + try { app.createSshSecretStore().put("ui-password", bytes) } finally { bytes.fill(0) } + app.sshStore.update { cz.netkit.shared.ssh.SshData(profiles = listOf(profile)) } + } + return profile + } + private suspend fun sshUiPhase(lifecycle: Boolean = false, reconnect: Boolean = false) { - val config=withContext(Dispatchers.IO) { fixture() } - val server=config.getValue("server").jsonObject - val client=config.getValue("client").jsonObject - val profile=SshProfile("m1-ui-profile","M1 UI fixture","10.0.2.2",22222, - server.getValue("username").jsonPrimitive.content,secretRef="ui-password", startupCommand=if (reconnect) "netkit-check" else "") - val seedScope=CoroutineScope(SupervisorJob()+Dispatchers.IO) - checkpoint="SSH_UI_SEED" - try { - withContext(Dispatchers.IO) { - val credentialBytes=client.getValue("password").jsonPrimitive.content.encodeToByteArray() - try { app.createSshSecretStore().put("ui-password",credentialBytes) } finally { credentialBytes.fill(0) } - val file=File(app.filesDir,"datastore/ssh.json") - check(file.canonicalPath.startsWith(app.filesDir.canonicalPath+File.separator)) - val store=SshStore(app,seedScope,file) - store.update { cz.netkit.shared.ssh.SshData(profiles=listOf(profile)) } - } - } finally { withContext(NonCancellable) { seedScope.coroutineContext[Job]!!.cancelAndJoin() } } + val config = withContext(Dispatchers.IO) { fixture() } + val server = config.getValue("server").jsonObject + val profile = seedUiProfile(config, reconnect) val activity=startActivitySync(Intent(targetContext,MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) }) @@ -934,7 +1082,8 @@ class M1TestApplication : NetKitApplication() { private fun isolated(base: File): File { // Framework/content-provider initialization may read files before Instrumentation.onCreate. val id=runId.takeIf { it.matches(Regex("[a-f0-9]{32}")) } ?: bootstrapId - return File(base,"m1-data/$id").apply { check(isDirectory || mkdirs()) } + // mkdirs() is false when a concurrent caller (e.g. WorkManager ForceStopRunnable) created it first. + return File(base,"m1-data/$id").apply { mkdirs(); check(isDirectory) } } override fun getFilesDir(): File=isolated(super.getFilesDir()) override fun getNoBackupFilesDir(): File=isolated(super.getNoBackupFilesDir()) @@ -943,6 +1092,11 @@ class M1TestApplication : NetKitApplication() { check(runId.matches(Regex("[a-f0-9]{32}"))) return AndroidSecretStore(this,"test-ui-$runId") } + /** SecureOn evidence (zadání 39) shares the per-run namespace, so cleanupUiSecrets removes it too. */ + override fun createWolSecretStore(): AndroidSecretStore { + check(runId.matches(Regex("[a-f0-9]{32}"))) + return AndroidSecretStore(this,"test-ui-$runId") + } fun cleanupUiSecrets() { check(runId.matches(Regex("[a-f0-9]{32}"))) val namespace="test-ui-$runId" @@ -955,5 +1109,7 @@ class M1TestApplication : NetKitApplication() { } } fun closeStore() { wolStore?.let { runBlocking { it.close() } }; wolStore=null } - companion object { @Volatile var runId="" } + /** Zadání 42 AC-001: a phase shortens the 5-minute background limit before the activity creates the ViewModel. */ + override val sshBackgroundGraceMillis: Long get()=backgroundGraceMillis.takeIf { it > 0 } ?: super.sshBackgroundGraceMillis + companion object { @Volatile var runId=""; @Volatile var backgroundGraceMillis=0L } } diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetStatusWidgetEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetStatusWidgetEvidence.kt new file mode 100644 index 0000000..6beb7ff --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetStatusWidgetEvidence.kt @@ -0,0 +1,264 @@ +package cz.netkit.app.test + +import android.Manifest +import android.app.AppOpsManager +import android.app.AsyncNotedAppOp +import android.app.Instrumentation +import android.app.SyncNotedAppOp +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetProviderInfo +import android.graphics.Bitmap +import android.graphics.Canvas +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.net.TrafficStats +import android.net.wifi.WifiManager +import android.os.Bundle +import android.os.Process +import android.os.SystemClock +import android.view.View +import android.view.ViewGroup +import android.widget.Chronometer +import android.widget.FrameLayout +import android.widget.RemoteViews +import android.widget.TextView +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import androidx.glance.appwidget.compose +import cz.netkit.app.R +import cz.netkit.app.netstatus.NET_STATUS_MEDIUM +import cz.netkit.app.netstatus.NET_STATUS_SMALL +import cz.netkit.app.netstatus.NetStatusWidget +import cz.netkit.shared.netstatus.NetStatusData +import cz.netkit.shared.netstatus.NetStatusGateway +import cz.netkit.shared.netstatus.NetStatusLabel +import cz.netkit.shared.netstatus.NetStatusRadioSource +import cz.netkit.shared.netstatus.NetStatusRefreshResult +import cz.netkit.shared.netstatus.NetStatusSettings +import cz.netkit.shared.netstatus.NetStatusSpeed +import cz.netkit.shared.netstatus.NetStatusWidth +import cz.netkit.shared.netstatus.netStatusRadio +import java.io.File +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetAddress +import java.util.Collections +import java.util.concurrent.Executor +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext + +/** + * Zadání 37 on the emulator (phase `netstatus-widget`). + * + * AC-002: the widget refresh path ([cz.netkit.app.netstatus.NetStatusService.refresh], the code the refresh + * receiver runs) while an [AppOpsManager.OnOpNotedCallback] records every app op noted for this process and the + * per-UID traffic counters are watched. Positive controls prove both detectors: `WifiManager.connectionInfo` + * notes the location op, one UDP datagram to the emulator host (10.0.2.2, discard port) moves the counters. + * The refresh must note no location op, move no packet, finish under 10 s, update RSSI/channel and keep the SSID. + * + * AC-003: the real [NetStatusWidget] composed by Glance (RemoteViews) for small and medium sizes and the states + * fresh, stale (> 24 h), no data, SSID on/off and lock screen; texts are checked in the inflated views and each + * drawing is saved as a PNG (m1-evidence). Synthetic SSID and documentation addresses only. + */ +suspend fun netStatusWidgetEvidence(test: Instrumentation, app: M1TestApplication, marker: (String) -> Unit) { + // The location op is only noted (and its absence meaningful) with the permission granted. + test.uiAutomation.grantRuntimePermission(app.packageName, Manifest.permission.ACCESS_FINE_LOCATION) + try { + refreshEvidence(test, app, marker) + renderEvidence(test, app, marker) + } catch (failure: IllegalStateException) { + // Only this file's own check messages (synthetic data, no secrets); one line for the runner log. + marker("NETSTATUS:CHECK_FAILED:" + failure.message.orEmpty().replace('\n', ' ').take(600)) + throw failure + } +} + +/** FINE/COARSE_LOCATION access and rejection entries of this app (`dumpsys appops`), without the relative age. */ +private fun locationOpEvents(test: Instrumentation, app: M1TestApplication): Set { + val output = test.uiAutomation.executeShellCommand("dumpsys appops --package ${app.packageName}").let { fd -> + android.os.ParcelFileDescriptor.AutoCloseInputStream(fd).use { it.readBytes().decodeToString() } + } + val events = mutableSetOf() + var op: String? = null + val opLine = Regex("""^\s+([A-Z_]+) \((?:allow|ignore|deny|default|foreground)\):""") + val event = Regex("""(Access|Reject): \[[^]]*][0-9-]+ [0-9:.]+""") + for (line in output.lineSequence()) { + opLine.find(line)?.let { op = it.groupValues[1] } + if (op == "FINE_LOCATION" || op == "COARSE_LOCATION") event.find(line)?.let { events += "$op ${it.value}" } + } + return events +} + +private suspend fun refreshEvidence(test: Instrumentation, app: M1TestApplication, marker: (String) -> Unit) { + val connectivity = app.getSystemService(ConnectivityManager::class.java) + @Suppress("DEPRECATION") + check(connectivity.allNetworks.any { connectivity.getNetworkCapabilities(it)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true }) { "No Wi-Fi" } + val old = System.currentTimeMillis() - 3_600_000 + app.netStatus.replaceForEvidence(NetStatusData( + settings = NetStatusSettings(showSsid = true), + radio = netStatusRadio(old, 5180, -90, 6, 6, NetStatusRadioSource.FOREGROUND), + ssid = NetStatusLabel(old, "EvidenceNet"), + )) + check(app.netStatus.load().ssid?.value == "EvidenceNet") { "seed" } + + val ops = Collections.synchronizedList(mutableListOf()) + val appOps = app.getSystemService(AppOpsManager::class.java) + appOps.setOnOpNotedCallback(Executor { it.run() }, object : AppOpsManager.OnOpNotedCallback() { + override fun onNoted(op: SyncNotedAppOp) { ops += op.op } + override fun onSelfNoted(op: SyncNotedAppOp) { ops += op.op } + override fun onAsyncNoted(op: AsyncNotedAppOp) { ops += op.op } + }) + try { + // Positive control 1: the legacy Wi-Fi read runs the system's location check for this app. Without a visible + // activity the check is rejected (mode "foreground"), so it is not a noted op but an AppOps "Reject" entry; + // both an access and a rejection count as a location check. + val beforeControl = locationOpEvents(test, app) + withContext(Dispatchers.IO) { + @Suppress("DEPRECATION") app.getSystemService(WifiManager::class.java).connectionInfo + } + delay(300) + val control = (locationOpEvents(test, app) - beforeControl) + ops.filter { it.contains("location") } + check(control.isNotEmpty()) { "location control not recorded" } + marker("NETSTATUS:LOCATION_CONTROL_EVENTS:${control.joinToString(";")}") + marker("NETSTATUS:LOCATION_CONTROL_NOTED:PASS") + ops.clear() + val beforeRefresh = locationOpEvents(test, app) + + val uid = Process.myUid() + val txBefore = TrafficStats.getUidTxPackets(uid) + val rxBefore = TrafficStats.getUidRxPackets(uid) + val started = SystemClock.elapsedRealtime() + val result = app.netStatus.refresh() + val took = SystemClock.elapsedRealtime() - started + delay(1_500) + val txAfter = TrafficStats.getUidTxPackets(uid) + val rxAfter = TrafficStats.getUidRxPackets(uid) + marker("NETSTATUS:REFRESH:result=$result:ms=$took:tx=${txAfter - txBefore}:rx=${rxAfter - rxBefore}:ops=${ops.toList()}") + check(result == NetStatusRefreshResult.UPDATED) { "refresh $result" } + check(took < 10_000) { "refresh took $took ms" } + marker("NETSTATUS:REFRESH_UNDER_10S:PASS") + val refreshChecks = (locationOpEvents(test, app) - beforeRefresh) + ops.filter { it.contains("location") } + check(refreshChecks.isEmpty()) { "refresh ran a location check: $refreshChecks" } + marker("NETSTATUS:REFRESH_NO_LOCATION_OP:PASS") + check(txBefore >= 0 && txAfter == txBefore && rxAfter == rxBefore) { "traffic during refresh" } + marker("NETSTATUS:REFRESH_NO_TRAFFIC:PASS") + + // Positive control 2: one datagram to the emulator host moves the same counters. + withContext(Dispatchers.IO) { + DatagramSocket().use { it.send(DatagramPacket(ByteArray(1), 1, InetAddress.getByName("10.0.2.2"), 9)) } + } + var moved = false + repeat(20) { if (!moved) { delay(100); moved = TrafficStats.getUidTxPackets(uid) > txAfter } } + check(moved) { "traffic control not counted" } + marker("NETSTATUS:TRAFFIC_CONTROL_COUNTED:PASS") + + val after = app.netStatus.load() + val radio = checkNotNull(after.radio) + check(radio.source == NetStatusRadioSource.WIDGET_REFRESH && radio.atMs > old && radio.rssiDbm != null && radio.rssiDbm != -90) { "radio $radio" } + check(radio.frequencyMhz != null && radio.frequencyMhz != 5180) { "channel not updated: $radio" } + check(after.ssid == NetStatusLabel(old, "EvidenceNet")) { "SSID changed: ${after.ssid}" } + marker("NETSTATUS:REFRESH_RADIO_UPDATED_SSID_KEPT:PASS") + } finally { + appOps.setOnOpNotedCallback(null, null) + } +} + +private data class RenderCase(val name: String, val size: DpSize, val host: DpSize, val data: NetStatusData, val lockscreen: Boolean = false, + val expect: List, val absent: List = emptyList()) + +private suspend fun renderEvidence(test: Instrumentation, app: M1TestApplication, marker: (String) -> Unit) { + val now = System.currentTimeMillis() + val minute = 60_000L + val fresh = NetStatusData( + settings = NetStatusSettings(showSsid = true, showPublicIp = true), + radio = netStatusRadio(now - 12 * minute, 5180, -58, 866, 780, NetStatusRadioSource.FOREGROUND), + width = NetStatusWidth(now - 13 * minute, 5180, 80), + gateway = NetStatusGateway(now - 12 * minute, 2.4), + speed = NetStatusSpeed(now - 120 * minute, 412.0, 98.0, 11.0), + ssid = NetStatusLabel(now - 12 * minute, "TestNet-5G"), + publicIp = NetStatusLabel(now - 12 * minute, "203.0.113.7"), + ) + val s = { id: Int -> app.getString(id) } + val small = DpSize(150.dp, 64.dp) + val medium = DpSize(300.dp, 150.dp) + val cases = listOf( + RenderCase("fresh-small", NET_STATUS_SMALL, small, fresh, expect = listOf("-58 dBm", app.getString(R.string.netstatus_channel_short, 36) + " ·", age(app, R.string.netstatus_age_format))), + RenderCase("fresh-medium-ssid", NET_STATUS_MEDIUM, medium, fresh, expect = listOf("TestNet-5G", "-58 dBm", app.getString(R.string.netstatus_channel, 36), + "80 MHz", "866", "412", "203.0.113.7", age(app, R.string.netstatus_signal_age_format))), + RenderCase("fresh-medium-no-ssid", NET_STATUS_MEDIUM, medium, fresh.copy(settings = NetStatusSettings()), + expect = listOf(s(R.string.netstatus_title), "-58 dBm"), absent = listOf("TestNet-5G", "203.0.113.7")), + RenderCase("lockscreen-medium", NET_STATUS_MEDIUM, medium, fresh, lockscreen = true, expect = listOf("-58 dBm"), absent = listOf("TestNet-5G", "203.0.113.7")), + RenderCase("stale-small", NET_STATUS_SMALL, small, fresh.copy(radio = fresh.radio!!.copy(atMs = now - 26 * 60 * minute), + gateway = null, speed = fresh.speed!!.copy(atMs = now - 27 * 60 * minute)), expect = listOf(s(R.string.netstatus_open_app)), absent = listOf("-58 dBm")), + RenderCase("stale-medium", NET_STATUS_MEDIUM, medium, fresh.copy(radio = fresh.radio!!.copy(atMs = now - 26 * 60 * minute), + gateway = null, speed = fresh.speed!!.copy(atMs = now - 27 * 60 * minute)), + expect = listOf(s(R.string.netstatus_open_app)), absent = listOf("-58 dBm", "TestNet-5G", "412")), + RenderCase("nodata-small", NET_STATUS_SMALL, small, NetStatusData(), expect = listOf(s(R.string.netstatus_no_data))), + RenderCase("nodata-medium", NET_STATUS_MEDIUM, medium, NetStatusData(), expect = listOf(s(R.string.netstatus_no_data), s(R.string.netstatus_open_app))), + ) + for (case in cases) { + app.netStatus.replaceForEvidence(case.data) + val options = Bundle().apply { + putInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY, + if (case.lockscreen) AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD else AppWidgetProviderInfo.WIDGET_CATEGORY_HOME_SCREEN) + } + val views = NetStatusWidget().compose(app, options = options, size = case.size) + val texts = mutableListOf() + var chronometers = 0 + val file = File(app.filesDir, "m1-evidence/netstatus-${case.name}.png") + check(file.parentFile!!.isDirectory || file.parentFile!!.mkdirs()) + test.runOnMainSync { + val root = inflate(app, views, case.host) + fun walk(view: View) { + if (view is Chronometer) { + chronometers++ + // Detached from a window the Chronometer has not ticked yet: its text lacks the format that the + // launcher shows from the first tick on. Apply the format once, as that tick would. + view.format?.let { format -> view.text = String.format(format, view.text) } + } + if (view is TextView && view.visibility == View.VISIBLE) view.text?.toString()?.takeIf { it.isNotBlank() }?.let(texts::add) + if (view is ViewGroup) for (i in 0 until view.childCount) walk(view.getChildAt(i)) + } + walk(root) + // Lay out again with the formatted Chronometer text, as the launcher does after the first tick. + root.measure(View.MeasureSpec.makeMeasureSpec(root.width, View.MeasureSpec.EXACTLY), + View.MeasureSpec.makeMeasureSpec(root.height, View.MeasureSpec.EXACTLY)) + root.layout(0, 0, root.measuredWidth, root.measuredHeight) + val bitmap = Bitmap.createBitmap(root.width, root.height, Bitmap.Config.ARGB_8888) + root.draw(Canvas(bitmap)) + file.outputStream().use { check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)) } + bitmap.recycle() + } + val joined = texts.joinToString(" | ") + marker("NETSTATUS:RENDER:${case.name}:TEXTS:${joined.replace('\n', ' ')}") + for (expected in case.expect) check(joined.contains(expected) || (expected.startsWith(AGE) && Regex(expected.removePrefix(AGE)).containsMatchIn(joined))) { + "${case.name}: missing '$expected' in $joined" } + for (absent in case.absent) check(!joined.contains(absent)) { "${case.name}: unexpected '$absent'" } + if (case.name.startsWith("fresh")) check(chronometers == 1) { "${case.name}: live age missing" } + marker("NETSTATUS:RENDER:${case.name}:PASS") + marker("SCREENSHOT:files/m1-data/${M1TestApplication.runId}/m1-evidence/netstatus-${case.name}.png") + } + // Leave an honest state for a widget placed on the emulator: the last refresh-free snapshot. + app.netStatus.replaceForEvidence(fresh) +} + +/** Marks an expectation that is a regex: the age format of [id] (any locale) around "12:0x" (12 min, maybe a tick later). */ +private const val AGE = "regex:" +private fun age(app: M1TestApplication, id: Int): String { + val format = app.getString(id) + return AGE + Regex.escape(format.substringBefore("%s")) + "12:0\\d" + Regex.escape(format.substringAfter("%s")) +} + +/** Inflates [views] like a launcher at [size] (dp) and lays it out. */ +private fun inflate(app: M1TestApplication, views: RemoteViews, size: DpSize): View { + val density = app.resources.displayMetrics.density + val width = (size.width.value * density).toInt() + val height = (size.height.value * density).toInt() + val parent = FrameLayout(app) + val root = views.apply(app, parent) + parent.addView(root, FrameLayout.LayoutParams(width, height)) + parent.measure(View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY)) + parent.layout(0, 0, width, height) + return parent +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/ShareResultsEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/ShareResultsEvidence.kt new file mode 100644 index 0000000..6c2d6b4 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/ShareResultsEvidence.kt @@ -0,0 +1,280 @@ +package cz.netkit.app.test + +import android.Manifest +import android.app.Activity +import android.app.Instrumentation +import android.content.ClipDescription +import android.content.ClipboardManager +import android.content.Intent +import android.graphics.Rect +import android.net.Uri +import android.os.LocaleList +import android.os.SystemClock +import android.view.InputDevice +import android.view.MotionEvent +import android.view.accessibility.AccessibilityNodeInfo +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.ui.Modifier +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.lan.LanDevicesViewModel +import cz.netkit.app.speed.SpeedShareDialog +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.wifi.live.WifiLiveViewModel +import cz.netkit.shared.net.NetKind +import cz.netkit.shared.report.DIAGNOSTIC_REPORT_FORMAT +import cz.netkit.shared.report.DiagnosticReport +import cz.netkit.shared.speed.SpeedEngine +import cz.netkit.shared.speed.SpeedRecord +import java.io.File +import java.util.Locale +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.Json + +private val SHARE_LOCATION = listOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION) + +/** + * Zadání 47, AC-001 on the emulator (phase `share-results`), Czech then English: + * 1) Přehled: a real long press copies the IPv4 (plain clip) and the BSSID (clip marked + * `EXTRA_IS_SENSITIVE`). 2) Diagnostický report: SSID/BSSID/public IP off by default, the + * shared `text/plain` equals what is saved through SAF, opting in adds the SSID, the JSON file + * parses. 3) Zařízení: discovery of the emulator's own virtual network, export dialog, CSV + * written through the SAF result path. 4) Rychlost: the share dialog of a synthetic, labelled + * record, SSID off by default. The share sheet and the document picker are replaced by an + * ActivityMonitor (the app code path up to `startActivity` and the ContentResolver write is real). + */ +suspend fun shareResultsEvidence(test: Instrumentation, app: M1TestApplication, screenshot: (String) -> Unit, marker: (String) -> Unit) { + val ui = SshEvidenceUi(test) + val localeManager = app.getSystemService(android.app.LocaleManager::class.java) + val beforeLocales = localeManager.applicationLocales + var activity: Activity? = null + val evidence = File(app.filesDir, "m1-evidence").apply { mkdirs() } + val shared = mutableListOf() + var nextDocument: File? = null + val monitor = object : Instrumentation.ActivityMonitor() { + override fun onStartActivity(intent: Intent): Instrumentation.ActivityResult? { + when (intent.action) { + Intent.ACTION_CHOOSER -> { + synchronized(shared) { shared += intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)!! } + return Instrumentation.ActivityResult(Activity.RESULT_CANCELED, null) + } + Intent.ACTION_CREATE_DOCUMENT -> { + val file = nextDocument ?: return Instrumentation.ActivityResult(Activity.RESULT_CANCELED, null) + return Instrumentation.ActivityResult(Activity.RESULT_OK, Intent().setData(Uri.fromFile(file))) + } + } + return null + } + } + suspend fun settle() { + delay(1_200) + test.waitForIdleSync() + try { test.uiAutomation.waitForIdle(500, 5_000) } catch (_: java.util.concurrent.TimeoutException) { } + } + suspend fun scrollTo(predicate: (AccessibilityNodeInfo) -> Boolean): AccessibilityNodeInfo { + for (direction in listOf(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD, AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) { + repeat(12) { + ui.all().firstOrNull { predicate(it) && it.isVisibleToUser }?.let { return it } + if (ui.all().firstOrNull { it.isScrollable }?.performAction(direction) != true) return@repeat + delay(300) + } + } + return ui.await { predicate(it) && it.isVisibleToUser } + } + suspend fun longPress(node: AccessibilityNodeInfo) { + val bounds = Rect(); node.getBoundsInScreen(bounds) + val down = SystemClock.uptimeMillis() + fun inject(action: Int) { + val event = MotionEvent.obtain(down, SystemClock.uptimeMillis(), action, bounds.exactCenterX(), bounds.exactCenterY(), 0) + event.source = InputDevice.SOURCE_TOUCHSCREEN + try { check(test.uiAutomation.injectInputEvent(event, true)) } finally { event.recycle() } + } + inject(MotionEvent.ACTION_DOWN) + delay(900) + inject(MotionEvent.ACTION_UP) + delay(400) + } + /** Clipboard read on the main thread (the focused app may read it); polled, never throws there. */ + suspend fun clip(expected: String): Pair? = withTimeout(5_000) { + var result: Pair? = null + while (result?.first != expected) { + test.runOnMainSync { + result = try { + app.getSystemService(ClipboardManager::class.java).primaryClip?.let { clip -> + clip.getItemAt(0).text?.toString().orEmpty() to (clip.description.extras?.getBoolean(ClipDescription.EXTRA_IS_SENSITIVE) == true) + } + } catch (_: RuntimeException) { null } + } + if (result?.first != expected) delay(200) + } + result + } + fun clearClip() = test.runOnMainSync { app.getSystemService(ClipboardManager::class.java).clearPrimaryClip() } + suspend fun awaitShared(count: Int): Intent = withTimeout(8_000) { + while (synchronized(shared) { shared.size } < count) delay(50) + synchronized(shared) { shared[count - 1] } + } + suspend fun awaitFile(file: File): String = withTimeout(8_000) { + while (!file.isFile || file.length() == 0L) delay(50) + delay(200) + file.readText() + } + fun recreate(action: () -> Unit) { + val m = test.addMonitor(MainActivity::class.java.name, null, false) + try { + test.runOnMainSync(action) + activity = test.waitForMonitorWithTimeout(m, 10_000) ?: error("No recreated activity") + } finally { test.removeMonitor(m) } + } + + var restoreLookup: () -> Unit = {} + test.addMonitor(monitor) + try { + SHARE_LOCATION.forEach { test.uiAutomation.grantRuntimePermission(app.packageName, it) } + test.runOnMainSync { localeManager.applicationLocales = LocaleList(Locale.forLanguageTag("cs")) } + activity = test.startActivitySync(Intent(app, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)) + lateinit var live: WifiLiveViewModel + test.runOnMainSync { live = ViewModelProvider(activity as MainActivity)[WifiLiveViewModel::class.java] } + // No real public IP of the build host in screenshots or files: the lookup is switched off (isolated store). + val lookupWas = withTimeout(10_000) { live.state.first { it.publicIp.settingLoaded } }.publicIp.enabled + restoreLookup = { if (lookupWas) test.runOnMainSync { live.setPublicIpLookup(true) } } + test.runOnMainSync { live.setPublicIpLookup(false) } + withTimeout(10_000) { live.state.first { it.publicIp.settingLoaded && !it.publicIp.enabled && it.publicIp.info == null } } + ui.clickTag("tab_signal") + val link = withTimeout(20_000) { live.state.first { it.link?.ipv4Address != null && it.link?.bssid != null && it.link?.ssid != null } }.link!! + val ssid = link.ssid!! + val bssid = link.bssid!!.uppercase(Locale.ROOT) + + for (language in listOf("cs", "en")) { + if (language == "en") recreate { localeManager.applicationLocales = LocaleList(Locale.forLanguageTag("en")) } + val res = activity!!.resources + + // --- 1) Long press copies (IPv4 plain, BSSID sensitive) -------------------------------- + clearClip() + longPress(scrollTo { it.viewIdResourceName == "overview_copy_ipv4" }) + check(clip(link.ipv4Address!!) == (link.ipv4Address!! to false)) { "IPv4 clip" } + clearClip() + longPress(scrollTo { it.viewIdResourceName == "overview_copy_bssid" }) + check(clip(bssid) == (bssid to true)) { "BSSID clip must be marked sensitive" } + settle() + screenshot("share-copy-$language.png") + if (language == "cs") { marker("SHARE:COPY:IPV4:PASS"); marker("SHARE:COPY:BSSID_SENSITIVE:PASS") } + marker("SHARE:COPY:$language:UI_VERIFIED") + + // --- 2) Diagnostic report ----------------------------------------------------------- + scrollTo { it.viewIdResourceName == "overview_menu" } + ui.clickTag("overview_menu") + ui.clickTag("overview_menu_report") + ui.await { it.viewIdResourceName == "report_dialog" || it.viewIdResourceName == "report_preview" } + val title = res.getString(R.string.report_label_title) + ui.await { it.text?.toString()?.startsWith(title) == true } + for (tag in listOf("report_include_ssid", "report_include_bssid", "report_include_public_ip")) { + check(!ui.await { it.viewIdResourceName == tag }.isChecked) { "$tag must default to off" } + } + settle() + screenshot("share-report-$language.png") + val before = synchronized(shared) { shared.size } + ui.clickTag("report_share") + val sent = awaitShared(before + 1) + val text = sent.getStringExtra(Intent.EXTRA_TEXT)!! + check(sent.type == "text/plain" && text.startsWith(title)) { "share intent" } + check(ssid !in text && bssid !in text && bssid.lowercase(Locale.ROOT) !in text) { "identifier in default report" } + live.state.value.publicIp.info?.v4?.address?.let { check(it !in text) { "public IP in default report" } } + check(res.getString(R.string.report_label_section_latency) in text) { "latency section" } + if (language == "cs") { + marker("SHARE:REPORT:DEFAULTS_OFF:PASS") + marker("SHARE:REPORT:SHARE_INTENT:bytes=${text.encodeToByteArray().size}") + // Save the same text through the SAF result path. + val txt = File(evidence, "share-report.txt").apply { delete() } + nextDocument = txt + ui.clickTag("report_save") + check(awaitFile(txt) == text) { "saved text differs from shared text" } + ui.await { it.text?.toString() == res.getString(R.string.report_saved) } + marker("SHARE:REPORT:SAF_TEXT:PASS") + // JSON form. + ui.clickTag("report_format_json") + val json = File(evidence, "share-report.json").apply { delete() } + nextDocument = json + ui.clickTag("report_save") + val report = Json.decodeFromString(DiagnosticReport.serializer(), awaitFile(json)) + check(report.format == DIAGNOSTIC_REPORT_FORMAT && report.wifi?.ssid == null && report.wifi?.bssid == null && report.publicIp == null) + check(report.network.type == "wifi" && report.network.ipv4 == link.ipv4Address) { "JSON network" } + marker("SHARE:REPORT:SAF_JSON:PASS:mtu=${report.network.mtu}:dhcp=${report.network.dhcpServer != null}:width=${report.wifi?.widthMhz}") + // Opt-in: the SSID appears only after the switch. + ui.clickTag("report_format_txt") + ui.click(ui.await { it.viewIdResourceName == "report_include_ssid" }) + ui.clickTag("report_share") + val withSsid = awaitShared(before + 2).getStringExtra(Intent.EXTRA_TEXT)!! + check("SSID: $ssid" in withSsid) { "opt-in SSID missing" } + marker("SHARE:REPORT:SSID_OPT_IN:PASS") + nextDocument = null + } + ui.clickTag("report_close") + marker("SHARE:REPORT:$language:UI_VERIFIED") + + // --- 3) Device list export ------------------------------------------------------------ + ui.clickTag("tab_lan") + lateinit var devices: LanDevicesViewModel + test.runOnMainSync { devices = ViewModelProvider(activity as MainActivity)[LanDevicesViewModel::class.java] } + // A remembered consent starts an automatic scan on entry; export is enabled only after it ends. + if (devices.state.value.devices.isEmpty() && !devices.state.value.scan.running) { + delay(1_500) + if (!devices.state.value.scan.running) ui.all().firstOrNull { it.viewIdResourceName == "devices_consent_allow" }?.let { ui.click(it) } + ?: ui.clickTag("devices_refresh") + } + withTimeout(90_000) { devices.state.first { s -> s.devices.isNotEmpty() && !s.scan.running } } + ui.clickTag("devices_export") + ui.await { it.viewIdResourceName == "devices_export_dialog" || it.viewIdResourceName == "devices_export_confirm" } + ui.await { it.text?.toString() == res.getString(R.string.devices_export_warning) } + settle() + screenshot("share-devices-$language.png") + val csv = File(evidence, "share-devices-$language.csv").apply { delete() } + nextDocument = csv + ui.clickTag("devices_export_format_csv") + ui.clickTag("devices_export_confirm") + val rows = awaitFile(csv).trimEnd().lines() + check(rows.first().startsWith("address,name,nameSource") && rows.size == devices.state.value.devices.size + 1) { "CSV rows" } + ui.await { it.viewIdResourceName == "devices_export_notice" } + nextDocument = null + if (language == "cs") marker("SHARE:DEVICES:CSV:SAF_FILE_VERIFIED:rows=${rows.size - 1}") + marker("SHARE:DEVICES:$language:UI_VERIFIED") + + // --- 4) Speed result share (synthetic record, production dialog) ------------------------ + val record = SpeedRecord(timestampMs = 1_764_665_103_042, engine = SpeedEngine.IPERF3, serverName = "192.0.2.10:5201 (SYNTHETIC)", + downloadMbps = 941.2, retransmits = 3, ssid = ssid, networkKind = NetKind.WIFI) + test.runOnMainSync { + (activity as MainActivity).setContent { + NetKitTheme { Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { SpeedShareDialog(record) {} } } + } + } + ui.await { it.viewIdResourceName == "speed_share_preview" } + check(!ui.await { it.viewIdResourceName == "speed_share_include_ssid" }.isChecked) { "SSID must default to off" } + settle() + screenshot("share-speed-$language.png") + val count = synchronized(shared) { shared.size } + ui.clickTag("speed_share_confirm") + val speedText = awaitShared(count + 1).getStringExtra(Intent.EXTRA_TEXT)!! + check(speedText.startsWith(res.getString(R.string.report_label_speed_title)) && "941.2 Mb/s" in speedText && ssid !in speedText) + if (language == "cs") marker("SHARE:SPEED:SHARE_INTENT:PASS") + marker("SHARE:SPEED:$language:UI_VERIFIED") + // Back to the production content for the next language. + recreate { activity!!.recreate() } + ui.clickTag("tab_signal") + } + } catch (failure: Throwable) { + try { screenshot("share-results-failure.png") } catch (_: Throwable) { } + throw failure + } finally { + test.removeMonitor(monitor) + try { restoreLookup() } catch (_: Throwable) { } + test.runOnMainSync { activity?.finish() } + test.runOnMainSync { localeManager.applicationLocales = beforeLocales } + } +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshBackgroundSftpEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshBackgroundSftpEvidence.kt new file mode 100644 index 0000000..f615abb --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshBackgroundSftpEvidence.kt @@ -0,0 +1,573 @@ +package cz.netkit.app.test + +import android.accessibilityservice.AccessibilityService +import android.app.Activity +import android.app.ActivityManager +import android.app.Instrumentation +import android.app.Notification +import android.app.NotificationManager +import android.content.Intent +import android.graphics.Rect +import android.net.Uri +import android.view.accessibility.AccessibilityNodeInfo +import android.view.accessibility.AccessibilityWindowInfo +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.ssh.AndroidSecretStore +import cz.netkit.app.ssh.JschConnection +import cz.netkit.app.ssh.SftpClient +import cz.netkit.app.ssh.SftpOperationException +import cz.netkit.app.ssh.SshInteraction +import cz.netkit.app.ssh.SshSessionService +import cz.netkit.app.ssh.SshStore +import cz.netkit.app.ssh.SshViewModel +import cz.netkit.shared.ssh.* +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.File +import java.security.KeyStore +import java.security.MessageDigest +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.selects.select +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/* Zadání 42: SSH session foreground service (AC-001), SFTP against the loopback fixture (AC-003) and the + * review-of-41 tunnel panel with the keyboard open. Everything targets 10.0.2.2 fixture ports only. */ + +private const val GRACE_MS = 3000L + +private fun hex(bytes: ByteArray) = bytes.joinToString("") { "%02x".format(it.toInt() and 0xff) } +private fun sha256(bytes: ByteArray) = hex(MessageDigest.getInstance("SHA-256").digest(bytes)) + +private fun sessionServiceRunning(app: M1TestApplication, foreground: Boolean? = null): Boolean = + @Suppress("DEPRECATION") // For the caller's own services getRunningServices is still supported. + app.getSystemService(ActivityManager::class.java).getRunningServices(50).any { + it.service.className == SshSessionService::class.java.name && it.service.packageName == app.packageName && + (foreground == null || it.foreground == foreground) + } + +private fun sessionNotification(app: M1TestApplication): Notification? = + app.getSystemService(NotificationManager::class.java).activeNotifications + .firstOrNull { it.id == SshSessionService.NOTIFICATION_ID }?.notification + +private fun shell(test: Instrumentation, command: String) { + test.uiAutomation.executeShellCommand(command).close() +} + +private suspend fun seedProfile(app: M1TestApplication, config: JsonObject, profile: SshProfile) = withContext(Dispatchers.IO) { + val credential = config.getValue("client").jsonObject.getValue("password").jsonPrimitive.content + val bytes = credential.encodeToByteArray() + try { app.createSshSecretStore().put("ui-password", bytes) } finally { bytes.fill(0) } + // One DataStore per file: seed through the application singleton (zadání 36). + app.sshStore.update { SshData(profiles = listOf(profile)) } +} + +private fun fixtureProfile(config: JsonObject, id: String, name: String) = SshProfile(id, name, "10.0.2.2", 22222, + config.getValue("server").jsonObject.getValue("username").jsonPrimitive.content, secretRef = "ui-password") + +private suspend fun launch(test: Instrumentation, app: M1TestApplication): Pair { + val activity = test.startActivitySync(Intent(app, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as MainActivity + lateinit var model: SshViewModel + test.runOnMainSync { model = ViewModelProvider(activity)[SshViewModel::class.java] } + withTimeout(8000) { model.state.first { it.loaded } } + return activity to model +} + +private suspend fun finishActivity(test: Instrumentation, activity: Activity) = withContext(NonCancellable) { + test.runOnMainSync { activity.finish() } + withTimeout(5000) { while (!activity.isDestroyed) delay(50) } +} + +private suspend fun connectFromUi(ui: SshEvidenceUi, model: SshViewModel, profile: SshProfile, beforeTrust: suspend () -> Unit = {}) { + ui.clickTag("tab_ssh") + ui.clickTag("ssh_connect_${profile.id}") + ui.clickTag("ssh_confirm") + beforeTrust() + ui.clickTag("ssh_trust") + withTimeout(15000) { model.state.first { s -> s.sessions.any { it.connected } } } + withTimeout(8000) { model.state.first { s -> s.sessions.single().terminal.screen.any { it.text.contains("NETKIT_FIXTURE_READY") } } } +} + +/** LazyColumn composes only visible rows: scroll the SFTP list until the row is there. */ +private suspend fun SshEvidenceUi.sftpRow(tag: String): AccessibilityNodeInfo { + // To the top first, then down: the row may be above or below the current position. + for (action in listOf(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD, AccessibilityNodeInfo.ACTION_SCROLL_FORWARD)) { + repeat(10) { + all().firstOrNull { it.viewIdResourceName == tag }?.let { return it } + val moved = all().firstOrNull { it.viewIdResourceName == "sftp_list" }?.performAction(action) == true + delay(300) + if (!moved) return@repeat + } + } + return await { it.viewIdResourceName == tag } +} + +private suspend fun lifecycle(test: Instrumentation, activity: MainActivity): Lifecycle.State { + var state = Lifecycle.State.INITIALIZED + test.runOnMainSync { state = activity.lifecycle.currentState } + return state +} + +/** + * AC-001. With notifications granted: the service is foreground with a private notification, the session + * outlives the (shortened) background limit, and "Odpojit vše" ends the sessions and the service. + * Denied: the connection asks once, the limit banner is shown, no service runs and the limit closes the session. + */ +suspend fun sshBackgroundEvidence(test: Instrumentation, app: M1TestApplication, config: JsonObject, granted: Boolean, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + M1TestApplication.backgroundGraceMillis = GRACE_MS + marker("SSH_BG:GRACE_MS:$GRACE_MS") + // The once-only question is remembered in app preferences, which outlive a run: start from "never asked". + check(app.getSharedPreferences(cz.netkit.app.ssh.SshSessionKeeper.PREFS, 0).edit().clear().commit()) + val profile = fixtureProfile(config, "m1-bg-profile", "M1 background fixture") + seedProfile(app, config, profile) + val ui = SshEvidenceUi(test) + val (activity, model) = launch(test, app) + try { + check(app.sshKeeper.notificationsAllowed() == granted) { "POST_NOTIFICATIONS state does not match the phase" } + marker("SSH_BG:PERMISSION_STATE:" + if (granted) "granted" else "denied") + if (granted) { + connectFromUi(ui, model, profile) + withTimeout(8000) { app.sshKeeper.serviceForeground.first { it } } + withTimeout(8000) { while (!sessionServiceRunning(app, foreground = true)) delay(100) } + marker("SSH_BG:SERVICE_FOREGROUND:PASS") + val notification = withTimeout(8000) { var n: Notification? = null; while (n == null) { n = sessionNotification(app); if (n == null) delay(100) }; n!! } + val host = "10.0.2.2" + val username = config.getValue("server").jsonObject.getValue("username").jsonPrimitive.content + fun Notification.texts() = listOfNotNull(extras.getCharSequence(Notification.EXTRA_TITLE), extras.getCharSequence(Notification.EXTRA_TEXT), + extras.getCharSequence(Notification.EXTRA_BIG_TEXT), tickerText).joinToString("|") + check(notification.visibility == Notification.VISIBILITY_PRIVATE) { "visibility" } + val public = checkNotNull(notification.publicVersion) { "public version" } + check(host !in public.texts() && username !in public.texts() && profile.name !in public.texts()) { "public version leaks details" } + check(host !in notification.texts() && username !in notification.texts()) { "private version shows host or user" } + check(notification.contentIntent != null) { "tap target" } + val action = checkNotNull(notification.actions?.singleOrNull()) { "one action" } + check(action.title.toString() == app.getString(R.string.ssh_notification_disconnect_all)) { "Odpojit vše action" } + check(notification.flags and Notification.FLAG_FOREGROUND_SERVICE != 0) { "FGS notification" } + marker("SSH_BG:NOTIFICATION_PRIVATE:PASS") + + check(test.uiAutomation.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME)) + withTimeout(8000) { while (lifecycle(test, activity).isAtLeast(Lifecycle.State.STARTED)) delay(100) } + delay(GRACE_MS * 3) // well past the shortened 5-minute limit + val session = model.state.value.sessions.single() + check(session.connected && !session.ended) { "session closed in background despite the service" } + check(sessionServiceRunning(app, foreground = true)) { "service left the foreground" } + val before = session.terminal.let { (it.history + it.screen).count { line -> line.text.contains("NETKIT_TEST_OK") } } + test.runOnMainSync { model.send(session.id, "netkit-check\r") } + withTimeout(8000) { + model.state.first { s -> s.sessions.single().terminal.let { t -> (t.history + t.screen).count { it.text.contains("NETKIT_TEST_OK") } > before } } + } + marker("SSH_BG:SESSION_SURVIVES_BACKGROUND:PASS") + + // "Odpojit vše" from the notification shade as a user would; the PendingIntent is the fallback. + check(test.uiAutomation.performGlobalAction(AccessibilityService.GLOBAL_ACTION_NOTIFICATIONS)) + delay(1500) + screenshot("ssh-bg-notification.png") + val label = app.getString(R.string.ssh_notification_disconnect_all) + fun shade() = test.uiAutomation.windows.mapNotNull { it.root }.flatMap { root -> + buildList { fun visit(n: AccessibilityNodeInfo) { add(n); for (i in 0 until n.childCount) n.getChild(i)?.let(::visit) }; visit(root) } + } + // A silent notification below another one is collapsed: expand ours (the chevron in its row) first. + val title = notification.extras.getCharSequence(Notification.EXTRA_TITLE).toString() + shade().firstOrNull { it.text?.toString() == title }?.let { node -> + generateSequence(node) { it.parent }.take(6).firstNotNullOfOrNull { row -> + buildList { fun visit(n: AccessibilityNodeInfo) { add(n); for (i in 0 until n.childCount) n.getChild(i)?.let(::visit) }; visit(row) } + .firstOrNull { it.contentDescription?.toString()?.contains("xpand") == true && it.isClickable } + }?.performAction(AccessibilityNodeInfo.ACTION_CLICK) + delay(800) + } + val button = withTimeoutOrNull(5000) { + var found: AccessibilityNodeInfo? = null + while (found == null) { + found = test.uiAutomation.windows.mapNotNull { it.root }.flatMap { root -> + buildList { fun visit(n: AccessibilityNodeInfo) { add(n); for (i in 0 until n.childCount) n.getChild(i)?.let(::visit) }; visit(root) } + }.firstOrNull { it.text?.toString().equals(label, ignoreCase = true) && it.isVisibleToUser } + if (found == null) delay(200) + } + found + } + val via = if (button != null && generateSequence(button) { it.parent }.firstOrNull { it.isClickable }?.performAction(AccessibilityNodeInfo.ACTION_CLICK) == true) "ui" + else { action.actionIntent.send(); "pendingintent" } + marker("SSH_BG:DISCONNECT_ALL_VIA:$via") + withTimeout(10000) { model.state.first { it.sessions.isEmpty() } } + withTimeout(10000) { app.sshKeeper.serviceForeground.first { !it } } + withTimeout(10000) { while (sessionServiceRunning(app) || sessionNotification(app) != null) delay(100) } + marker("SSH_BG:DISCONNECT_ALL_STOPS_SERVICE:PASS") + test.uiAutomation.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK) + } else { + connectFromUi(ui, model, profile, beforeTrust = { + // The runtime question comes with the first connection; the user refuses it. + val deny = withTimeout(10000) { + var node: AccessibilityNodeInfo? = null + while (node == null) { + node = test.uiAutomation.windows.mapNotNull { it.root }.flatMap { root -> + buildList { fun visit(n: AccessibilityNodeInfo) { add(n); for (i in 0 until n.childCount) n.getChild(i)?.let(::visit) }; visit(root) } + }.firstOrNull { it.viewIdResourceName == "com.android.permissioncontroller:id/permission_deny_button" } + if (node == null) delay(200) + } + node!! + } + screenshot("ssh-bg-permission.png") + check(deny.performAction(AccessibilityNodeInfo.ACTION_CLICK)) + marker("SSH_BG:PERMISSION_ASKED_AT_CONNECT:PASS") + }) + ui.await { it.viewIdResourceName == "ssh_background_limited" } + screenshot("ssh-bg-limited.png") + marker("SSH_BG:LIMIT_BANNER:PASS") + delay(2000) + check(!app.sshKeeper.serviceForeground.value && !sessionServiceRunning(app)) { "service without notifications" } + check(!app.sshKeeper.notificationsAllowed()) + marker("SSH_BG:NO_SERVICE_WITHOUT_NOTIFICATIONS:PASS") + check(test.uiAutomation.performGlobalAction(AccessibilityService.GLOBAL_ACTION_HOME)) + withTimeout(8000) { while (lifecycle(test, activity).isAtLeast(Lifecycle.State.STARTED)) delay(100) } + withTimeout(GRACE_MS + 12000) { model.state.first { s -> s.sessions.all { it.ended } } } + marker("SSH_BG:FALLBACK_LIMIT_CLOSES:PASS") + } + } finally { + withContext(NonCancellable) { + try { test.runOnMainSync { model.closeAllSessions() } } catch (_: Throwable) { } + finishActivity(test, activity) + } + } +} + +private fun testConnection(app: M1TestApplication, profile: SshProfile, store: SshStore, secrets: AndroidSecretStore, + scope: CoroutineScope, connected: CompletableDeferred, failed: CompletableDeferred) = + JschConnection(profile, store, secrets, object : SshInteraction { + override suspend fun confirmHost(offered: TrustedHostKey, previous: TrustedHostKey?): Boolean = true + override suspend fun authenticate(name: String, instruction: String, prompts: List, echo: List): List? = null + }, scope, onText = { }, onConnected = { connected.complete(Unit) }, onEnd = { }, onFailure = { failed.complete(it) }) + +private inline fun expectFailure(reason: SftpFailure, block: () -> Unit) { + val error = try { block(); null } catch (e: SftpOperationException) { e } + check(error?.reason == reason) { "expected $reason, got ${error?.reason}" } +} + +/** AC-003: SftpClient over a real JSch session against the sandboxed fixture, then the browser on screen. */ +suspend fun sshSftpEvidence(test: Instrumentation, app: M1TestApplication, config: JsonObject, runId: String, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + val sftpConfig = config.getValue("sftp").jsonObject + val home = sftpConfig.getValue("home").jsonPrimitive.content + val hello = sftpConfig.getValue("helloText").jsonPrimitive.content.encodeToByteArray() + val dataSha = sftpConfig.getValue("dataSha256").jsonPrimitive.content + val dataSize = sftpConfig.getValue("dataSize").jsonPrimitive.int + val profile = fixtureProfile(config, "m1-sftp-profile", "M1 SFTP fixture") + withContext(Dispatchers.IO) { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + val namespace = "test-sftp-$runId" + val secrets = AndroidSecretStore(app, namespace) + val credential = config.getValue("client").jsonObject.getValue("password").jsonPrimitive.content.encodeToByteArray() + try { secrets.put("ui-password", credential) } finally { credential.fill(0) } + val store = SshStore(app, scope, File(File(app.filesDir, "ssh-sftp").apply { check(isDirectory || mkdirs()) }, "store.json")) + val connected = CompletableDeferred(); val failed = CompletableDeferred() + val connection = testConnection(app, profile, store, secrets, scope, connected, failed) + try { + connection.start() + withTimeout(20000) { select { connected.onAwait { }; failed.onAwait { error("SSH failed: $it") } } } + val client = SftpClient(connection.openSftp(), connection::releaseSftp) + check(client.home() == home) + marker("SFTP:HOME_REALPATH:PASS") + + val listing = client.list(home) + val byName = listing.entries.associateBy { it.name } + check(byName.getValue("docs").kind == SftpEntryKind.DIRECTORY && byName.getValue("hello.txt").kind == SftpEntryKind.FILE) + check(byName.getValue("hello.txt").size == hello.size.toLong() && byName.getValue("data.bin").size == dataSize.toLong()) + check(byName.getValue("link-docs").kind == SftpEntryKind.LINK && byName.getValue("escape").kind == SftpEntryKind.LINK) + check(listing.hidden == 1 && "bad\nname" !in byName) { "invalid server name must be hidden" } + check(listing.entries.first().kind == SftpEntryKind.DIRECTORY) + marker("SFTP:LIST:PASS") + + check(client.parent(home) == "/home" && client.parent("/") == "/") + check(client.resolve("$home/docs/../..") == "/home" && client.resolve("/../../..") == "/") + check(runCatching { sftpChild(home, "..") }.isFailure && runCatching { sftpChild(home, "../etc") }.isFailure) + marker("SFTP:DOTDOT_NORMALIZED_BY_SERVER:PASS") + + check(client.follow(home, "link-docs") == ("$home/docs" to SftpEntryKind.DIRECTORY)) + check(client.follow(home, "link-hello") == ("$home/hello.txt" to SftpEntryKind.FILE)) + expectFailure(SftpFailure.PERMISSION) { client.follow(home, "escape") } + marker("SFTP:SYMLINKS_RESOLVED_IN_SANDBOX:PASS") + + val download = ByteArrayOutputStream(); var progress = 0L + check(client.download("$home/data.bin", download, { progress = it }, { false }) == dataSize.toLong()) + check(sha256(download.toByteArray()) == dataSha && progress == dataSize.toLong()) + marker("SFTP:DOWNLOAD_SHA256:PASS") + var chunks = 0 + expectFailure(SftpFailure.CANCELLED) { client.download("$home/data.bin", ByteArrayOutputStream(), { chunks++ }, { chunks > 0 }) } + val again = SftpClient(connection.openSftp(), connection::releaseSftp) // a cancelled transfer leaves the channel unusable by design (controller reopens) + marker("SFTP:DOWNLOAD_CANCEL:PASS") + + val payload = ByteArray(200_000) { (it * 31 + 7).toByte() } + val uploaded = "up-${runId.take(8)}.bin" + check(again.upload(home, uploaded, ByteArrayInputStream(payload), { }, { false }) == payload.size.toLong()) + ByteArrayOutputStream().also { again.download("$home/$uploaded", it, { }, { false }); check(it.toByteArray().contentEquals(payload)) } + fun temps(client: SftpClient) = client.list(home).entries.filter { it.name.startsWith(".netkit-upload-") } + check(temps(again).isEmpty()) + marker("SFTP:UPLOAD_ROUNDTRIP:PASS") + + expectFailure(SftpFailure.EXISTS) { again.upload(home, "hello.txt", ByteArrayInputStream(byteArrayOf(1, 2, 3)), { }, { false }) } + ByteArrayOutputStream().also { again.download("$home/hello.txt", it, { }, { false }); check(it.toByteArray().contentEquals(hello)) } + check(temps(again).isEmpty()) + marker("SFTP:UPLOAD_EXISTING_TARGET_UNTOUCHED:PASS") + + var written = 0 + expectFailure(SftpFailure.CANCELLED) { again.upload(home, "cancelled.bin", ByteArrayInputStream(payload), { written++ }, { written > 0 }) } + val third = SftpClient(connection.openSftp(), connection::releaseSftp) + check(temps(third).isEmpty() && third.list(home).entries.none { it.name == "cancelled.bin" }) { "temporary file left after cancel" } + marker("SFTP:UPLOAD_CANCEL_REMOVES_TEMP:PASS") + + // The final step itself never replaces: a target that appears meanwhile stays as it was. + third.upload(home, "race-a.txt", ByteArrayInputStream("A".encodeToByteArray()), { }, { false }) + third.upload(home, "race-b.txt", ByteArrayInputStream("B".encodeToByteArray()), { }, { false }) + expectFailure(SftpFailure.EXISTS) { third.publish("$home/race-a.txt", "$home/race-b.txt") } + ByteArrayOutputStream().also { third.download("$home/race-b.txt", it, { }, { false }); check(it.toString() == "B") } + marker("SFTP:PUBLISH_NEVER_OVERWRITES:PASS") + + third.rename(home, uploaded, "renamed.bin") + expectFailure(SftpFailure.EXISTS) { third.rename(home, "renamed.bin", "hello.txt") } + expectFailure(SftpFailure.EXISTS) { third.rename(home, "empty", "docs") } + third.rename(home, "empty", "empty2") + ByteArrayOutputStream().also { third.download("$home/hello.txt", it, { }, { false }); check(it.toByteArray().contentEquals(hello)) } + check(third.list(home).entries.map { it.name }.containsAll(listOf("renamed.bin", "empty2", "docs"))) + marker("SFTP:RENAME_NO_OVERWRITE:PASS") + + third.mkdir(home, "newdir") + check(runCatching { third.mkdir(home, "newdir") }.isFailure) + expectFailure(SftpFailure.INVALID_NAME) { third.mkdir(home, "../x") } + expectFailure(SftpFailure.INVALID_NAME) { third.upload(home, "a/b", ByteArrayInputStream(byteArrayOf()), { }, { false }) } + marker("SFTP:MKDIR_AND_NAMES:PASS") + + fun entry(name: String) = third.list(home).entries.single { it.name == name } + third.delete(home, entry("renamed.bin")) + third.delete(home, entry("star*.txt")) // escaped: must not expand to starfish.txt + third.delete(home, entry("link-hello")) // the link only + expectFailure(SftpFailure.FAILURE) { third.delete(home, entry("docs")) } // not empty + third.delete(home, entry("newdir")) + val names = third.list(home).entries.map { it.name }.toSet() + check("starfish.txt" in names && "hello.txt" in names && "docs" in names) + check(names.none { it in setOf("renamed.bin", "star*.txt", "link-hello", "newdir") }) + marker("SFTP:DELETE_EXACT_ENTRY:PASS") + third.close(); again.close(); client.close() + withTimeout(5000) { while (connection.sftpChannelCount != 0) delay(50) } + repeat(5) { SftpClient(connection.openSftp(), connection::releaseSftp).apply { home(); close() } } + check(connection.sftpChannelCount == 0) { "closed SFTP channels stay registered" } + marker("SFTP:CHANNELS_RELEASED:PASS") + + // --- Review round 1: a hanging peer, cancel, I/O timeout, close during open ------------------ + val hang = "hang.bin" + suspend fun controller(io: Long, grace: Long, open: () -> com.jcraft.jsch.ChannelSftp = connection::openSftp) = + cz.netkit.app.ssh.SftpController(scope, "review", app.contentResolver, open = open, + release = connection::releaseSftp, ioTimeoutMs = io, cancelGraceMs = grace).also { c -> + c.start(); withTimeout(10000) { c.state.first { it.path == home && !it.loading } } + } + val sink = File(app.filesDir, "m1-evidence/sftp-hang.bin").apply { parentFile!!.mkdirs(); delete() } + val cancelling = controller(io = 60_000, grace = 1000) + val hangEntry = cancelling.state.value.entries.single { it.name == hang } + cancelling.download(hangEntry, Uri.fromFile(sink)) + withTimeout(8000) { cancelling.state.first { it.transfer != null } } + delay(500) + val pressed = System.nanoTime() + cancelling.cancelTransfer() + val cancelled = withTimeout(8000) { cancelling.state.first { it.transfer == null && !it.loading } } + val tookMs = (System.nanoTime() - pressed) / 1_000_000 + check(cancelled.failure == SftpFailure.CANCELLED) { "cancel ended with ${cancelled.failure}" } + withTimeout(5000) { while (sink.exists()) delay(50) } // the half-written document is removed + check(!cancelling.hasClient) + cancelling.refresh() // usable at once, on a new channel, although the old thread still hangs + withTimeout(10000) { cancelling.state.first { !it.loading && it.failure == null && it.entries.any { e -> e.name == "hello.txt" } } } + marker("SFTP:CANCEL_HANGING_PEER:PASS") + marker("SFTP:CANCEL_MS:$tookMs") + cancelling.close() + + val timing = controller(io = 1500, grace = 60_000) + timing.download(timing.state.value.entries.single { it.name == hang }, Uri.fromFile(sink)) + val timedOut = withTimeout(10000) { timing.state.first { it.failure != null && !it.loading } } + check(timedOut.failure == SftpFailure.CONNECTION && timedOut.transfer == null) { "timeout ended with ${timedOut.failure}" } + withTimeout(5000) { while (sink.exists()) delay(50) } + marker("SFTP:IO_TIMEOUT_HANGING_PEER:PASS") + timing.close() + withTimeout(8000) { while (connection.sftpChannelCount != 0) delay(50) } + + val gate = java.util.concurrent.CountDownLatch(1) + val entered = java.util.concurrent.CountDownLatch(1) + val blocked = cz.netkit.app.ssh.SftpController(scope, "review", app.contentResolver, + open = { entered.countDown(); gate.await(); connection.openSftp() }, release = connection::releaseSftp) + blocked.start() + check(entered.await(5, java.util.concurrent.TimeUnit.SECONDS)) + blocked.close() // while open() is still blocking + gate.countDown() + delay(1500) + withTimeout(8000) { while (connection.sftpChannelCount != 0) delay(50) } + check(!blocked.hasClient) { "a channel opened after close() was kept" } + marker("SFTP:CLOSE_DURING_OPEN_RELEASES:PASS") + } finally { + // Closing the session right after a hung SFTP peer must not block (it runs on the main thread in the app). + val closer = Thread { connection.close() }.apply { start() } + val closeStarted = System.nanoTime() + closer.join(3000) + if (closer.isAlive) { + Thread.getAllStackTraces().filter { (t, st) -> st.any { "jcraft" in it.className || "netkit" in it.className } } + .forEach { (t, st) -> marker("SFTP:CLOSE_BLOCKED:${t.name}:" + st.take(10).joinToString(";")) } + closer.join() + } + marker("SFTP:CONNECTION_CLOSE_MS:${(System.nanoTime() - closeStarted) / 1_000_000}") + scope.cancel() + withContext(NonCancellable) { + val encrypted = File(app.noBackupFilesDir, "$namespace-secrets") + check(!encrypted.exists() || encrypted.deleteRecursively()) + KeyStore.getInstance("AndroidKeyStore").apply { load(null); deleteEntry("netkit.$namespace.aes.v1"); check(!containsAlias("netkit.$namespace.aes.v1")) } + } + } + } + + // --- Browser on screen ------------------------------------------------------------------------ + marker("SFTP:INTEGRATION_CLOSED") + seedProfile(app, config, profile) + val ui = SshEvidenceUi(test) + val (activity, model) = launch(test, app) + marker("SFTP_UI:LAUNCHED") + val target = File(app.filesDir, "m1-evidence/sftp-download.txt").apply { parentFile!!.mkdirs(); delete() } + var requested: Intent? = null + val monitor = object : Instrumentation.ActivityMonitor() { + override fun onStartActivity(intent: Intent): Instrumentation.ActivityResult? { + if (intent.action != Intent.ACTION_CREATE_DOCUMENT) return null + requested = intent + // Stands in for the document picker: the app writes through ContentResolver as with a SAF Uri. + return Instrumentation.ActivityResult(Activity.RESULT_OK, Intent().setData(Uri.fromFile(target))) + } + } + test.addMonitor(monitor) + var step = "start" + try { + step = "1:connectFromUi(ui, model, profile)" + connectFromUi(ui, model, profile) + step = "2:ui.clickTag(ssh_options)" + ui.clickTag("ssh_options") + step = "3:ui.clickTag(ssh_sftp_open)" + ui.clickTag("ssh_sftp_open") + step = "4:ui.await { it.viewIdResourceName == sft" + ui.sftpRow("sftp_entry_hello.txt") + step = "5:ui.await { it.viewIdResourceName == sft" + ui.sftpRow("sftp_entry_link-docs") + screenshot("sftp-browser.png") + marker("SFTP_UI:BROWSER_LISTED:PASS") + step = "6:ui.clickTag(sftp_entry_link-docs)" + ui.click(ui.sftpRow("sftp_entry_link-docs")) + step = "7:ui.await { it.viewIdResourceName == sft" + ui.await { it.viewIdResourceName == "sftp_path" && it.text?.toString() == "$home/docs" } + step = "8:ui.await { it.viewIdResourceName == sft" + ui.sftpRow("sftp_entry_readme.md") + step = "9:ui.clickTag(sftp_up)" + ui.clickTag("sftp_up") + step = "10:ui.await { it.viewIdResourceName == sft" + ui.await { it.viewIdResourceName == "sftp_path" && it.text?.toString() == home } + marker("SFTP_UI:NAVIGATE_LINK_AND_UP:PASS") + step = "11:ui.clickTag(sftp_entry_menu_hello.txt)" + ui.click(ui.sftpRow("sftp_entry_menu_hello.txt")) + step = "12:ui.clickTag(sftp_download)" + ui.clickTag("sftp_download") + withTimeout(8000) { while (requested == null) delay(25) } + check(requested!!.getStringExtra(Intent.EXTRA_TITLE) == "hello.txt") + step = "13:ui.await { it.viewIdResourceName == sft" + ui.await { it.viewIdResourceName == "sftp_notice" } + check(target.readBytes().contentEquals(hello)) + marker("SFTP_UI:SAF_DOWNLOAD:PASS") + step = "14:ui.clickTag(sftp_entry_menu_starfish.tx" + ui.click(ui.sftpRow("sftp_entry_menu_starfish.txt")) + step = "15:ui.clickTag(sftp_delete)" + ui.clickTag("sftp_delete") + step = "16:ui.await { it.viewIdResourceName == ssh" + ui.await { it.viewIdResourceName == "ssh_confirm" } + screenshot("sftp-delete-confirm.png") + step = "17:ui.clickTag(ssh_confirm)" + ui.clickTag("ssh_confirm") + step = "18:ui.await { it.viewIdResourceName == sft" + ui.await { it.viewIdResourceName == "sftp_notice" } + withTimeout(8000) { while (ui.all().any { it.viewIdResourceName == "sftp_entry_starfish.txt" }) delay(100) } + marker("SFTP_UI:DELETE_CONFIRMED:PASS") + step = "19:test.runOnMainSync { model.closeSftp() }" + test.runOnMainSync { model.closeSftp() } + step = "20:ui.await { it.viewIdResourceName == ssh" + ui.await { it.viewIdResourceName == "ssh_options" } + } catch (failure: Throwable) { + marker("SFTP_UI:FAILED_AT:$step") + try { screenshot("sftp-ui-failure.png") } catch (_: Throwable) { } + throw failure + } finally { + test.removeMonitor(monitor) + withContext(NonCancellable) { + try { test.runOnMainSync { model.closeAllSessions() } } catch (_: Throwable) { } + finishActivity(test, activity) + } + } +} + +/** Review of 41: eight -L and a -D above the terminal; with the keyboard open the terminal keeps its height. */ +suspend fun sshForwardsPanelEvidence(test: Instrumentation, app: M1TestApplication, config: JsonObject, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + val echo = config.getValue("server").jsonObject.getValue("tcpEchoPort").jsonPrimitive.int + val profile = fixtureProfile(config, "m1-fwd-panel", "M1 forwards panel").copy( + localForwards = (0 until SSH_MAX_LOCAL_FORWARDS).map { SshLocalForward(28091 + it, "127.0.0.1", echo) }, + dynamicForwardPort = 21081) + check(profile.valid()) + seedProfile(app, config, profile) + val ui = SshEvidenceUi(test) + val (activity, model) = launch(test, app) + try { + connectFromUi(ui, model, profile) + withTimeout(10000) { model.state.first { s -> s.sessions.single().forwards.size == SSH_MAX_LOCAL_FORWARDS + 1 } } + ui.await { it.viewIdResourceName == "ssh_forwards_toggle" } + check(ui.all().none { it.viewIdResourceName == "ssh_forwards_details" }) { "details collapsed by default" } + val input = ui.await { it.viewIdResourceName == "cz.netkit.app:id/ssh_direct_input" && it.isVisibleToUser } + val bounds = Rect().also(input::getBoundsInScreen) + shell(test, "input tap ${bounds.centerX()} ${bounds.centerY()}") + val keyboard = withTimeout(8000) { + var window: AccessibilityWindowInfo? = null + while (window == null) { window = test.uiAutomation.windows.firstOrNull { it.type == AccessibilityWindowInfo.TYPE_INPUT_METHOD }; if (window == null) delay(100) } + Rect().also(window!!::getBoundsInScreen) + } + delay(500) + val density = app.resources.displayMetrics.density + fun terminal() = Rect().also { ui.all().first { n -> n.viewIdResourceName == "ssh_terminal_output" }.getBoundsInScreen(it) } + val collapsed = terminal() + val summary = Rect().also { ui.all().first { n -> n.viewIdResourceName == "ssh_forwards" }.getBoundsInScreen(it) } + marker("SSH_FWD_UI:MEASURE:terminal=${collapsed.toShortString()};ime=${keyboard.toShortString()};forwards=${summary.toShortString()};density=$density") + screenshot("ssh-forwards-ime.png") + // Collapsed, nine tunnels take one summary row; the terminal keeps several text rows above the IME + // (before the fix the full list was taller than the space left by the keyboard). + check(summary.height() <= 48 * density) { "collapsed tunnels ${summary.height()} px" } + check(!Rect.intersects(collapsed, keyboard) && collapsed.height() >= 56 * density) { "terminal height ${collapsed.height()} px with IME" } + marker("SSH_FWD_UI:TERMINAL_VISIBLE_WITH_IME:PASS") + fun imeShown() = test.uiAutomation.windows.any { it.type == AccessibilityWindowInfo.TYPE_INPUT_METHOD } + ui.clickTag("ssh_forwards_toggle") // opening the details closes the keyboard + val details = ui.await { it.viewIdResourceName == "ssh_forwards_details" } + withTimeout(8000) { while (imeShown()) delay(100) } + delay(500) + val panel = Rect().also(ui.await { it.viewIdResourceName == "ssh_forwards_details" }::getBoundsInScreen) + check(panel.height() <= (120 + 2) * density) { "details panel ${panel.height()} px" } + check(details.isScrollable || panel.height() >= 112 * density) { "nine tunnels must overflow into the panel's own scroll" } + val expanded = terminal() + marker("SSH_FWD_UI:MEASURE_EXPANDED:terminal=${expanded.toShortString()};panel=${panel.toShortString()}") + check(expanded.height() >= 56 * density) { "terminal ${expanded.height()} px with details open" } + screenshot("ssh-forwards-expanded.png") + // Typing again collapses the details, so the keyboard never squeezes the terminal to nothing. + val again = Rect().also(ui.await { it.viewIdResourceName == "cz.netkit.app:id/ssh_direct_input" && it.isVisibleToUser }::getBoundsInScreen) + shell(test, "input tap ${again.centerX()} ${again.centerY()}") + withTimeout(8000) { while (!imeShown()) delay(100) } + withTimeout(8000) { while (ui.all().any { it.viewIdResourceName == "ssh_forwards_details" }) delay(100) } + marker("SSH_FWD_UI:DETAILS_BOUNDED_SCROLLED:PASS") + shell(test, "input keyevent KEYCODE_BACK") + } finally { + withContext(NonCancellable) { + try { test.runOnMainSync { model.closeAllSessions() } } catch (_: Throwable) { } + finishActivity(test, activity) + } + } +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshLockEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshLockEvidence.kt new file mode 100644 index 0000000..d1c6326 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshLockEvidence.kt @@ -0,0 +1,139 @@ +package cz.netkit.app.test + +import android.accessibilityservice.AccessibilityService +import android.app.Instrumentation +import android.app.LocaleManager +import android.content.Intent +import android.net.Uri +import android.os.Bundle +import android.os.LocaleList +import android.view.accessibility.AccessibilityNodeInfo +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.nav.AppShortcuts +import cz.netkit.app.ssh.SshViewModel +import cz.netkit.shared.nav.AppTarget +import cz.netkit.shared.ssh.* +import java.io.File +import java.util.Locale +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withTimeout + +/** Real shortcut, UI and protected entry points. System authentication is a separate device check. */ +internal suspend fun sshLockEvidence(test: Instrumentation, app: M1TestApplication, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + val ui = SshEvidenceUi(test) + val locale = app.getSystemService(LocaleManager::class.java) + val sortPrefs = app.getSharedPreferences("ssh_list", 0) + val previousSort = sortPrefs.getString("sort", null) + val previousLocale = locale.applicationLocales + val prefs = app.getSharedPreferences("ssh_access", 0) + val previousEnabled = prefs.getBoolean("enabled", false) + val previousMinutes = prefs.getInt("minutes", 5) + val stored = app.sshStore.read() + val ssh = SshProfile("one", "Lab SSH", "192.0.2.1", username = "operator", group = "Rack", authentication = SshAuthentication.KEY) + val telnet = ConsoleProfile("two", "Lab Telnet", ConsoleKind.TELNET, "192.0.2.2", group = "Rack") + val serial = ConsoleProfile("three", "Lab USB", ConsoleKind.SERIAL, group = "Cabinet") + var current: MainActivity? = null + try { + app.sshStore.update { SshData(profiles = listOf(ssh), consoles = listOf(telnet, serial), recentProfiles = listOf(telnet.listKey)) } + check(prefs.edit().putBoolean("enabled", true).putInt("minutes", 0).commit()) + for (language in listOf("cs", "en")) { + test.runOnMainSync { locale.applicationLocales = LocaleList(Locale.forLanguageTag(language)) } + val activity = test.startActivitySync(AppShortcuts.openIntent(app, AppTarget.SshProfile(ssh.id)) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)) as MainActivity + current = activity + check(activity.resources.configuration.locales[0].language == language) + lateinit var model: SshViewModel + test.runOnMainSync { model = ViewModelProvider(activity)[SshViewModel::class.java] } + model.state.first { it.loaded } + ui.await { it.viewIdResourceName == "ssh_unlock" } + check(ui.all().none { it.text?.contains(ssh.host) == true || it.viewIdResourceName == "ssh_add" }) + screenshot("ssh-locked-$language.png") + marker("SSH_LOCK:SHORTCUT:$language:PASS") + + // API 35 evidence AVD must already have a screen lock. Exercise the real system + // prompt and Back without reading, changing or entering the emulator credential. + ui.clickTag("ssh_unlock") + // The SystemUI prompt is an overlay window: rootInActiveWindow keeps returning the app, + // so look for it among the interactive windows (FLAG_RETRIEVE_INTERACTIVE_WINDOWS is set). + fun systemPrompt() = test.uiAutomation.windows.any { window -> + val root = window.root + window.title?.toString() == "BiometricPrompt" || root?.packageName?.toString() == "com.android.settings" || + root?.findAccessibilityNodeInfosByViewId("com.android.systemui:id/lockPassword")?.isNotEmpty() == true + } + withTimeout(8_000) { while (!systemPrompt()) delay(100) } + // On API 35 the PIN view of the prompt may consume the first Back; repeat until it closes. + withTimeout(8_000) { + while (systemPrompt()) { check(test.uiAutomation.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK)); delay(1_000) } + } + ui.await { it.viewIdResourceName == "ssh_unlock" } + check(ui.all().none { it.viewIdResourceName == "ssh_confirm" }) + marker("SSH_LOCK:SYSTEM_CANCEL:$language:PASS") + + // No callbacks are granted. A denied operation must not even prepare the SAF destination. + var requests = 0 + val out = File(app.cacheDir, "lock-evidence-$language.json") + check(!out.exists()) + test.runOnMainSync { + model.access.prompt = { requests++ } + model.connect(ssh) + model.connectConsole(telnet, null, warningAccepted = false, remember = false) + model.connectConsole(serial, null, warningAccepted = false, remember = false) + model.openSftp("absent") + model.prepareExport { error("Opened SAF while locked") } + model.export(Uri.fromFile(out)) + } + check(requests == 6 && !out.exists() && model.state.value.sessions.isEmpty() && model.sftp.value == null) + check(model.state.value.keySelectionRequired == null) + marker("SSH_LOCK:DENIED:$language:PASS") + + // Inject only the result in this instrumentation activity. Keep device credentials untouched. + test.runOnMainSync { model.access.prompt = { success -> success() } } + ui.clickTag("ssh_unlock") + ui.await { it.text?.contains(ssh.endpoint) == true } + check(model.state.value.sessions.isEmpty()) + ui.clickText(activity.getString(R.string.ssh_cancel)) + suspend fun search(term: String) { + val field = ui.await { it.viewIdResourceName == "ssh_search" && it.isEditable } + check(field.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, Bundle().apply { + putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, term) + })) + } + for ((term, name) in listOf("cabinet" to serial.name, telnet.host to telnet.name, ssh.username to ssh.name)) { + search(term) + withTimeout(5_000) { + val names = listOf(serial.name, telnet.name, ssh.name) + while (ui.all().mapNotNull { it.text?.toString() }.filter { it in names }.toSet() != setOf(name)) delay(100) + } + } + ui.await { it.text?.toString() == "Rack" } + screenshot("ssh-groups-$language.png") + marker("SSH_LOCK:DIRECTORY:$language:PASS") + search("Rack") + for ((order, title, first) in listOf( + Triple(ProfileSort.ALPHABETICAL, R.string.ssh_sort_alpha, ssh.name), + Triple(ProfileSort.RECENT, R.string.ssh_sort_recent, telnet.name), + Triple(ProfileSort.MANUAL, R.string.ssh_sort_manual, telnet.name))) { + ui.clickTag("ssh_sort") + ui.clickText(activity.getString(title)) + ui.await { it.text?.toString() == first && it.isVisibleToUser } + check(sortPrefs.getString("sort", null) == order.name) + val names = ui.all().filter { it.isVisibleToUser && it.text?.toString() in listOf(ssh.name, telnet.name) } + check(names.first().text.toString() == first) + if (order == ProfileSort.RECENT) screenshot("ssh-sort-$language.png") + } + marker("SSH_LOCK:SORT:$language:PASS") + test.runOnMainSync { activity.finish() } + withTimeout(5_000) { while (!activity.isDestroyed) delay(50) } + current = null + } + } finally { + test.runOnMainSync { current?.finish(); locale.applicationLocales = previousLocale } + check(prefs.edit().putBoolean("enabled", previousEnabled).putInt("minutes", previousMinutes).commit()) + check(sortPrefs.edit().putString("sort", previousSort).commit()) + app.sshStore.update { stored } + } +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProductivityEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProductivityEvidence.kt new file mode 100644 index 0000000..e88241e --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProductivityEvidence.kt @@ -0,0 +1,345 @@ +package cz.netkit.app.test + +import android.app.Activity +import android.app.Instrumentation +import android.content.Intent +import android.net.Uri +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.ssh.AndroidSecretStore +import cz.netkit.app.ssh.JschConnection +import cz.netkit.app.ssh.SshInteraction +import cz.netkit.app.ssh.SshLogStop +import cz.netkit.app.ssh.SshStore +import cz.netkit.app.ssh.SshViewModel +import cz.netkit.shared.ssh.* +import java.io.File +import java.io.InputStream +import java.net.Inet4Address +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.NetworkInterface +import java.net.ServerSocket +import java.net.Socket +import java.security.KeyStore +import java.util.Base64 +import java.util.concurrent.CopyOnWriteArrayList +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.update +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +private val LOOPBACK: InetAddress = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)) + +private fun InputStream.readExactly(count: Int): ByteArray { + val bytes = ByteArray(count); var read = 0 + while (read < count) { val n = read(bytes, read, count - read); check(n >= 0) { "EOF" }; read += n } + return bytes +} + +private fun echoThrough(socket: Socket, payload: String) { + socket.soTimeout = 8000 + socket.getOutputStream().apply { write(payload.encodeToByteArray()); flush() } + check(socket.getInputStream().readExactly(payload.length).decodeToString() == payload) +} + +/** RFC 1929 login, then SOCKS5 CONNECT by hand; returns the reply code and leaves the socket open on success. */ +private fun socksConnect(socket: Socket, request: ByteArray, login: SshSocksCredentials): Int { + socket.soTimeout = 15000 + val output = socket.getOutputStream(); val input = socket.getInputStream() + output.write(byteArrayOf(5, 1, 2)); output.flush() + check(input.readExactly(2).contentEquals(byteArrayOf(5, 2))) + val user = login.username.encodeToByteArray(); val secretBytes = login.password.encodeToByteArray() + output.write(byteArrayOf(1, user.size.toByte()) + user + byteArrayOf(secretBytes.size.toByte()) + secretBytes); output.flush() + check(input.readExactly(2).contentEquals(byteArrayOf(1, 0))) + output.write(request); output.flush() + val reply = input.readExactly(10) + check(reply[0].toInt() == 5) + return reply[1].toInt() +} + +private fun port(value: Int) = byteArrayOf((value shr 8).toByte(), value.toByte()) + +/** + * AC-003/004/005 against the loopback fixture: -L and -D carry data to the fixture echo through the SSH + * session, listeners are loopback-only, and ProxyJump verifies each hop's key before reaching the second server. + */ +suspend fun sshForwardEvidence(app: M1TestApplication, config: JsonObject, runId: String, marker: (String) -> Unit) = withContext(Dispatchers.IO) { + val server = config.getValue("server").jsonObject + val username = server.getValue("username").jsonPrimitive.content + val credential = config.getValue("client").jsonObject.getValue("password").jsonPrimitive.content + val echoPort = server.getValue("tcpEchoPort").jsonPrimitive.int + val jumpTargetPort = server.getValue("jumpTargetSshPort").jsonPrimitive.int + check(echoPort == 18084 && jumpTargetPort == 22223) + val namespace = "test-fwd-$runId" + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + val secrets = AndroidSecretStore(app, namespace) + val directory = File(app.filesDir, "ssh-forward").apply { check(isDirectory || mkdirs()) } + val connections = mutableListOf() + val occupied = ServerSocket(28085, 1, LOOPBACK) + try { + val bytes = credential.encodeToByteArray() + try { secrets.put("pw", bytes) } finally { bytes.fill(0) } + class Run(val store: SshStore) { + lateinit var connection: JschConnection + val output = MutableStateFlow("") + val connected = CompletableDeferred() + val ended = CompletableDeferred() + val failure = CompletableDeferred() + val forwards = CompletableDeferred>() + val offered = CopyOnWriteArrayList>() + val hopsAuthenticated = CopyOnWriteArrayList() + } + suspend fun open(name: String, profile: SshProfile, jumps: List = emptyList(), known: List = emptyList()): Run { + val store = SshStore(app, scope, File(directory, "$name.json")) + known.forEach { store.trustNew(it) } + val run = Run(store) + run.connection = JschConnection(profile, store, secrets, object : SshInteraction { + override suspend fun confirmHost(offered: TrustedHostKey, previous: TrustedHostKey?): Boolean { + run.offered += offered to previous; return true + } + override suspend fun authenticate(name: String, instruction: String, prompts: List, echo: List): List? = null + override suspend fun authenticateHop(hop: SshProfile, name: String, instruction: String, prompts: List, echo: List): List? { + run.hopsAuthenticated += hop.id; return null // Stored passwords must suffice; a prompt here is a failure. + } + }, scope, onText = { text -> run.output.update { (it + text).takeLast(65536) } }, + onConnected = { run.connected.complete(Unit) }, onEnd = { run.ended.complete(it) }, + onFailure = { run.failure.complete(it) }, jumps = jumps, onForwards = { run.forwards.complete(it) }) + connections += run.connection + run.connection.start() + return run + } + + // --- -L and -D ------------------------------------------------------------------------ + val profile = SshProfile("fwd", "Forward fixture", "10.0.2.2", 22222, username, secretRef = "pw", + localForwards = listOf(SshLocalForward(28084, "127.0.0.1", echoPort), SshLocalForward(28085, "127.0.0.1", echoPort)), + dynamicForwardPort = 21080) + check(profile.valid()) + val forward = open("forward", profile) + withTimeout(15000) { forward.connected.await() } + val statuses = withTimeout(5000) { forward.forwards.await() } + val login = checkNotNull(statuses.single { it.kind == SshForwardKind.DYNAMIC }.credentials) { "SOCKS login must be on by default" } + check(login.password.length == 20) + check(statuses.map { it.kind to it.localPort to it.state } == listOf( + SshForwardKind.LOCAL to 28084 to SshForwardState.ACTIVE, + SshForwardKind.LOCAL to 28085 to SshForwardState.PORT_IN_USE, + SshForwardKind.DYNAMIC to 21080 to SshForwardState.ACTIVE)) { "statuses $statuses" } + marker("SSH_FWD:FORWARDS_STATUS:PASS") + marker("SSH_FWD:PORT_IN_USE_REPORTED:PASS") + val listening = forward.connection.listeningAddresses + check(listening.map { it.port }.sorted() == listOf(21080, 28084) && listening.all { it.address.isLoopbackAddress }) { "listening $listening" } + val external = NetworkInterface.getNetworkInterfaces().toList().filter { it.isUp && !it.isLoopback } + .flatMap { it.inetAddresses.toList() }.filterIsInstance() + check(external.isNotEmpty()) { "emulator has no external IPv4 to probe" } + for (address in external) for (localPort in listOf(28084, 21080)) { + var refused = false + try { Socket().use { it.connect(InetSocketAddress(address, localPort), 1500) } } catch (_: java.io.IOException) { refused = true } + check(refused) { "forward reachable on ${address.hostAddress}:$localPort" } + } + marker("SSH_FWD:LISTEN_LOOPBACK_ONLY:PASS") + Socket().use { socket -> socket.connect(InetSocketAddress(LOOPBACK, 28084), 3000); echoThrough(socket, "netkit-local-forward") } + marker("SSH_FWD:LOCAL_ECHO:PASS") + Socket().use { socket -> + // Request then EOF of the sending side: the reply must still arrive (revize P2 half-close). + socket.connect(InetSocketAddress(LOOPBACK, 28084), 3000); socket.soTimeout = 8000 + socket.getOutputStream().apply { write("netkit-half-close".encodeToByteArray()); flush() } + socket.shutdownOutput() + check(socket.getInputStream().readBytes().decodeToString() == "netkit-half-close") + } + marker("SSH_FWD:HALF_CLOSE_REPLY:PASS") + Socket().use { socket -> + socket.connect(InetSocketAddress(LOOPBACK, 21080), 3000); socket.soTimeout = 8000 + socket.getOutputStream().apply { write(byteArrayOf(5, 1, 0)); flush() } + check(socket.getInputStream().readExactly(2).contentEquals(byteArrayOf(5, 0xFF.toByte()))) + } + Socket().use { socket -> + socket.connect(InetSocketAddress(LOOPBACK, 21080), 3000); socket.soTimeout = 8000 + val output = socket.getOutputStream(); val input = socket.getInputStream() + output.write(byteArrayOf(5, 1, 2)); output.flush() + check(input.readExactly(2).contentEquals(byteArrayOf(5, 2))) + val wrong = (login.password.dropLast(1) + if (login.password.last() == 'a') "b" else "a").encodeToByteArray() + output.write(byteArrayOf(1, 6) + "netkit".encodeToByteArray() + byteArrayOf(wrong.size.toByte()) + wrong); output.flush() + check(input.readExactly(2).contentEquals(byteArrayOf(1, 1)) && input.read() == -1) + } + marker("SSH_FWD:SOCKS_AUTH_REQUIRED:PASS") + Socket().use { socket -> + socket.connect(InetSocketAddress(LOOPBACK, 21080), 3000) + check(socksConnect(socket, byteArrayOf(5, 1, 0, 1, 127, 0, 0, 1) + port(echoPort), login) == 0) + echoThrough(socket, "netkit-socks-ipv4") + } + marker("SSH_FWD:SOCKS_CONNECT_ECHO:PASS") + Socket().use { socket -> + socket.connect(InetSocketAddress(LOOPBACK, 21080), 3000) + val name = "localhost".encodeToByteArray() + check(socksConnect(socket, byteArrayOf(5, 1, 0, 3, name.size.toByte()) + name + port(echoPort), login) == 0) + echoThrough(socket, "netkit-socks-domain") + } + marker("SSH_FWD:SOCKS_DOMAIN_ECHO:PASS") + Socket().use { socket -> + socket.connect(InetSocketAddress(LOOPBACK, 21080), 3000) + check(socksConnect(socket, byteArrayOf(5, 2, 0, 1, 127, 0, 0, 1) + port(echoPort), login) == Socks5Reply.COMMAND_NOT_SUPPORTED.code) + } + marker("SSH_FWD:SOCKS_BIND_REJECTED:PASS") + Socket().use { socket -> + socket.connect(InetSocketAddress(LOOPBACK, 21080), 3000) + // The fixture refuses direct-tcpip outside its own echo/jump ports; the client gets a refusal, no data. + check(socksConnect(socket, byteArrayOf(5, 1, 0, 1, 127, 0, 0, 1) + port(22), login) == Socks5Reply.CONNECTION_REFUSED.code) + } + marker("SSH_FWD:SOCKS_DENIED_TARGET:PASS") + forward.connection.close() + withTimeout(5000) { forward.ended.await() } + for (localPort in listOf(28084, 21080)) { + var refused = false + withTimeout(5000) { + while (!refused) { + try { Socket().use { it.connect(InetSocketAddress(LOOPBACK, localPort), 500) }; delay(100) } catch (_: java.io.IOException) { refused = true } + } + } + } + marker("SSH_FWD:CLOSE_RELEASES_PORTS:PASS") + + // --- ProxyJump ------------------------------------------------------------------------ + val jump = SshProfile("jump", "Jump fixture", "10.0.2.2", 22222, username, secretRef = "pw") + val target = SshProfile("target", "Jump target", "127.0.0.1", jumpTargetPort, username, secretRef = "pw", jumpProfileId = "jump") + val chain = resolveSshJumpChain(listOf(jump, target), target) + check(chain == SshJumpResolution.Chain(listOf(jump))) + val jumped = open("jump", target, (chain as SshJumpResolution.Chain).hops) + withTimeout(20000) { jumped.connected.await() } + val endpoints = jumped.offered.map { it.first.endpoint to it.first.fingerprint } + check(endpoints == listOf("[10.0.2.2]:22222" to server.getValue("hostKeyFingerprint").jsonPrimitive.content, + "[127.0.0.1]:22223" to server.getValue("jumpTargetHostKeyFingerprint").jsonPrimitive.content)) { "offered $endpoints" } + check(jumped.offered.all { it.second == null } && jumped.hopsAuthenticated.isEmpty()) + check(jumped.store.read().hostKeys.map { it.endpoint }.toSet() == setOf("[10.0.2.2]:22222", "[127.0.0.1]:22223")) + marker("SSH_JUMP:PER_HOP_TOFU:PASS") + withTimeout(5000) { jumped.output.first { it.contains("NETKIT_FIXTURE_READY") } } + check(jumped.connection.send("netkit-check\r")) + withTimeout(5000) { jumped.output.first { it.contains("NETKIT_TEST_OK") } } + jumped.connection.close(); withTimeout(5000) { jumped.ended.await() } + marker("SSH_JUMP:TARGET_SHELL:PASS") + + // The jump host is known; the target's saved key differs: the chain stops at the target, before its login. + val primary = TrustedHostKey("[10.0.2.2]:22222", server.getValue("hostKeyAlgorithm").jsonPrimitive.content, + server.getValue("hostKeyPublicKey").jsonPrimitive.content, server.getValue("hostKeyFingerprint").jsonPrimitive.content) + val realTarget = server.getValue("jumpTargetHostKeyPublicKey").jsonPrimitive.content + val tampered = Base64.getDecoder().decode(realTarget).also { it[it.lastIndex] = (it.last().toInt() xor 1).toByte() } + val wrongTarget = TrustedHostKey("[127.0.0.1]:22223", server.getValue("jumpTargetHostKeyAlgorithm").jsonPrimitive.content, + Base64.getEncoder().encodeToString(tampered), "SHA256:tampered") + val changed = open("jump-changed", target, listOf(jump), known = listOf(primary, wrongTarget)) + check(withTimeout(20000) { changed.ended.await() }) + check(!changed.connected.isCompleted) + check(withTimeout(2000) { changed.failure.await() } == SshFailure.HOST_KEY_CHANGED) + check(changed.offered.map { it.first.endpoint } == listOf("[127.0.0.1]:22223") && changed.offered.single().second == wrongTarget) + check(changed.store.read().hostKeys.single { it.endpoint == "[127.0.0.1]:22223" } == wrongTarget) + marker("SSH_JUMP:TARGET_CHANGED_KEY_REJECTED:PASS") + + val cyclic = listOf(jump.copy(jumpProfileId = "target"), target) + check(resolveSshJumpChain(cyclic, target) == SshJumpResolution.Cycle) + check(resolveSshJumpChain(listOf(target), target) == SshJumpResolution.Missing("jump")) + marker("SSH_JUMP:CYCLE_REJECTED:PASS") + } finally { + connections.forEach { it.close() } + occupied.close() + withContext(NonCancellable) { + scope.coroutineContext[Job]!!.cancelAndJoin() + val encrypted = File(app.noBackupFilesDir, "$namespace-secrets") + try { + check(!encrypted.exists() || encrypted.deleteRecursively()) + check(!directory.exists() || directory.deleteRecursively()) + } finally { + KeyStore.getInstance("AndroidKeyStore").apply { load(null); deleteEntry("netkit.$namespace.aes.v1"); check(!containsAlias("netkit.$namespace.aes.v1")) } + } + } + } +} + +/** AC-001 (UI send of a snippet) and AC-002 (session log through the SAF result path) on the real screen. */ +suspend fun sshSnippetLogEvidence(test: Instrumentation, app: M1TestApplication, config: JsonObject, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + val server = config.getValue("server").jsonObject + val credential = config.getValue("client").jsonObject.getValue("password").jsonPrimitive.content + val profile = SshProfile("m1-snippet-profile", "M1 snippet fixture", "10.0.2.2", 22222, + server.getValue("username").jsonPrimitive.content, secretRef = "ui-password") + val snippet = SshSnippet("snip-check", "check", "netkit-check", sendEnter = true) + val own = SshSnippet("snip-own", "own", "uptime", sendEnter = false, profileId = profile.id) + withContext(Dispatchers.IO) { + val bytes = credential.encodeToByteArray() + try { app.createSshSecretStore().put("ui-password", bytes) } finally { bytes.fill(0) } + // Zadání 36: one DataStore per file — seed through the application singleton, never a second instance. + app.sshStore.update { SshData(profiles = listOf(profile), snippets = listOf(snippet, own)) } + } + val ui = SshEvidenceUi(test) + val activity = test.startActivitySync(Intent(app, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as MainActivity + lateinit var model: SshViewModel + test.runOnMainSync { model = ViewModelProvider(activity)[SshViewModel::class.java] } + val logFile = File(app.filesDir, "m1-evidence/ssh-session-log.txt").apply { parentFile!!.mkdirs(); delete() } + var requested: Intent? = null + val monitor = object : Instrumentation.ActivityMonitor() { + override fun onStartActivity(intent: Intent): Instrumentation.ActivityResult? { + if (intent.action != Intent.ACTION_CREATE_DOCUMENT) return null + requested = intent + // Stands in for the document picker: the app writes through ContentResolver exactly as with a SAF Uri. + return Instrumentation.ActivityResult(Activity.RESULT_OK, Intent().setData(Uri.fromFile(logFile))) + } + } + test.addMonitor(monitor) + try { + withTimeout(8000) { model.state.first { it.loaded } } + ui.clickTag("tab_ssh") + ui.clickTag("ssh_connect_${profile.id}") + ui.clickTag("ssh_confirm") + ui.clickTag("ssh_trust") + withTimeout(15000) { model.state.first { s -> s.sessions.any { it.connected } } } + val sessionId = model.state.value.sessions.single().id + withTimeout(8000) { model.state.first { s -> s.sessions.single().terminal.screen.any { it.text.contains("NETKIT_FIXTURE_READY") } } } + ui.await { it.viewIdResourceName == "ssh_snippet_${snippet.id}" } + ui.await { it.viewIdResourceName == "ssh_snippet_${own.id}" } + marker("SSH_SNIPPET:BAR_VISIBLE:PASS") + + ui.clickTag("ssh_options") + ui.clickTag("ssh_log_start") + ui.await { it.viewIdResourceName == "ssh_log_warning" } + screenshot("ssh-log-warning.png") + marker("SSH_LOG:WARNING_SHOWN:PASS") + ui.clickTag("ssh_log_confirm") + withTimeout(8000) { while (requested == null) delay(25) } + check(requested!!.type == "text/plain" && requested!!.getStringExtra(Intent.EXTRA_TITLE)?.startsWith("netkit-ssh-") == true) + withTimeout(8000) { model.state.first { s -> s.sessions.single().logging } } + ui.await { it.viewIdResourceName == "ssh_log_active" } + marker("SSH_LOG:SAF_DESTINATION:PASS") + + screenshot("ssh-snippet-bar.png") + ui.clickTag("ssh_snippet_${snippet.id}") + withTimeout(8000) { model.state.first { s -> s.sessions.single().terminal.let { t -> (t.history + t.screen).any { it.text.contains("NETKIT_TEST_OK") } } } } + screenshot("ssh-snippet-sent.png") + marker("SSH_SNIPPET:SENT_FROM_BAR:PASS") + + ui.clickTag("ssh_options") + ui.clickTag("ssh_log_stop") + withTimeout(8000) { model.state.first { s -> s.sessions.single().let { !it.logging && it.logStop == SshLogStop.USER } } } + val text = logFile.readText() + check(text.startsWith("# NetKit SSH log: M1 snippet fixture\n# start: ")) { "header" } + check("netkit-check" in text && "NETKIT_TEST_OK" in text) { "content" } + check(text.trimEnd().lines().last().startsWith("# end: ")) { "footer" } + check(text.none { it == '\u001b' || it == '\r' || it.code in 0x80..0x9f }) { "escape sequences in log" } + marker("SSH_LOG:SAF_FILE_PLAIN_TEXT:PASS") + check(model.state.value.sessions.single().id == sessionId) + ui.clickTag("ssh_close") + ui.clickTag("ssh_confirm") + ui.await { it.viewIdResourceName == "ssh_connect_${profile.id}" && it.isEnabled } + } catch (failure: Throwable) { + try { screenshot("ssh-snippet-log-failure.png") } catch (_: Throwable) { } + throw failure + } finally { + test.removeMonitor(monitor) + withContext(NonCancellable) { + test.runOnMainSync { activity.finish() } + withTimeout(3000) { while (!activity.isDestroyed) delay(50) } + } + } +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt index d121443..c2ec4fa 100644 --- a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt @@ -29,9 +29,8 @@ suspend fun sshProfilesV2Evidence(test: Instrumentation, app: M1TestApplication, SshProfile("a", "Alpha", "192.0.2.1", username = "tester", authentication = SshAuthentication.KEY), SshProfile("b", "Beta", "192.0.2.2", username = "tester", authentication = SshAuthentication.KEY, keyRef = "absent"), SshProfile("c", "Gamma", "192.0.2.3", username = "tester", authentication = SshAuthentication.KEY, keyRef = "metadata-only")) - val seedScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - try { SshStore(app, seedScope).update { SshData(profiles = profiles, keys = listOf(SshKeyInfo("metadata-only", "Other key", "public-fixture"))) } } - finally { seedScope.coroutineContext[Job]!!.cancelAndJoin() } + // The app-wide store: a second DataStore over the same file would fail (zadání 36 §2.8). + app.sshStore.update { SshData(profiles = profiles, keys = listOf(SshKeyInfo("metadata-only", "Other key", "public-fixture"))) } val ui = SshEvidenceUi(test) fun start() = test.startActivitySync(Intent(app, MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) @@ -44,7 +43,19 @@ suspend fun sshProfilesV2Evidence(test: Instrumentation, app: M1TestApplication, withTimeout(8000) { model.state.first { it.loaded } } ui.clickTag("tab_ssh") check(!ui.await { it.viewIdResourceName == "ssh_up_a" }.isEnabled) + withTimeout(5_000) { + while (ui.all().none { it.viewIdResourceName == "ssh_down_c" && it.isVisibleToUser }) { + ui.all().firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) + delay(150) + } + } check(!ui.await { it.viewIdResourceName == "ssh_down_c" }.isEnabled) + withTimeout(5_000) { + while (ui.all().none { it.viewIdResourceName == "ssh_down_a" && it.isVisibleToUser }) { + ui.all().firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD) + delay(150) + } + } ui.clickTag("ssh_down_a") withTimeout(8000) { model.state.first { !it.busy && it.data.profiles.map { p -> p.id } == listOf("b", "a", "c") } } screenshot("ssh-profile-order.png") diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshXtermEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshXtermEvidence.kt new file mode 100644 index 0000000..6b9325f --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshXtermEvidence.kt @@ -0,0 +1,103 @@ +package cz.netkit.app.test + +import android.app.Instrumentation +import android.content.Intent +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.ssh.SshViewModel +import cz.netkit.shared.ssh.* +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.first +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** Background colour of [column] in [row]: runs cover the row cell by cell (wide characters count twice). */ +private fun TerminalRow.backgroundAt(column: Int): Int { + var start = 0 + for (run in runs) { if (column < start + run.columns) return run.background; start += run.columns } + error("column $column outside row") +} + +/** + * Zadání 43, AC-002: real SSH session (app UI, JSch, PTY xterm-256color) against the loopback fixture. The fixture + * sends canned printf-equivalent output (256 SGR 48;5 swatches, truecolor, attributes) and a full-screen demo + * (alternate screen, OSC 2 title, DEC line drawing, scroll region, wide characters); the app's terminal snapshot + * must match cell by cell and the primary screen must come back after leaving the alternate screen. + */ +suspend fun sshXtermEvidence(test: Instrumentation, app: M1TestApplication, config: JsonObject, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + val server = config.getValue("server").jsonObject + val credential = config.getValue("client").jsonObject.getValue("password").jsonPrimitive.content + val profile = SshProfile("m1-xterm-profile", "M1 xterm fixture", "10.0.2.2", 22222, + server.getValue("username").jsonPrimitive.content, secretRef = "ui-password") + val snippets = listOf("colors", "alt", "main").map { SshSnippet("xterm-$it", it, "netkit-xterm-$it", sendEnter = true) } + withContext(Dispatchers.IO) { + val bytes = credential.encodeToByteArray() + try { app.createSshSecretStore().put("ui-password", bytes) } finally { bytes.fill(0) } + app.sshStore.update { SshData(profiles = listOf(profile), snippets = snippets) } + } + val ui = SshEvidenceUi(test) + val activity = test.startActivitySync(Intent(app, MainActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) + }) as MainActivity + lateinit var model: SshViewModel + test.runOnMainSync { model = ViewModelProvider(activity)[SshViewModel::class.java] } + fun terminal() = model.state.value.sessions.single().terminal + fun all(snapshot: TerminalSnapshot) = snapshot.history + snapshot.screen + try { + withTimeout(8000) { model.state.first { it.loaded } } + ui.clickTag("tab_ssh") + ui.clickTag("ssh_connect_${profile.id}") + ui.clickTag("ssh_confirm") + ui.clickTag("ssh_trust") + withTimeout(15000) { model.state.first { s -> s.sessions.any { it.connected } } } + withTimeout(8000) { model.state.first { s -> s.sessions.single().terminal.screen.any { it.text.contains("NETKIT_FIXTURE_READY") } } } + check(terminal().screen.first().columns >= 32) { "grid narrower than the 32-column swatch table" } + + ui.clickTag("ssh_snippet_xterm-colors") + withTimeout(10000) { model.state.first { s -> all(s.sessions.single().terminal).any { it.text.startsWith("NETKIT_XTERM_COLORS_OK") } } } + val rows = all(terminal()) + val header = rows.indexOfLast { it.text.startsWith("256 colors") } + check(header >= 0) { "header" } + for (line in 0 until 16) for (column in 0 until 16) + check(rows[header + 1 + line].backgroundAt(column * 2) == line * 16 + column) { "swatch $line/$column" } + val styles = rows[header + 17].runs + check(styles.first().foreground == (0x1000000 or 0xFF6400) && styles.any { it.bold && it.text.contains("BOLD") } && + styles.any { it.dim } && styles.any { it.italic } && styles.any { it.underline } && rows[header + 17].text.contains("中文")) { "styles" } + marker("SSH_XTERM:COLORS_256:PASS") + screenshot("ssh-xterm-colors.png") + + ui.clickTag("ssh_snippet_xterm-alt") + withTimeout(10000) { model.state.first { s -> s.sessions.single().terminal.let { t -> t.alternateScreen && t.screen.any { it.text.startsWith("NETKIT_XTERM_ALT_OK") } } } } + val alt = terminal() + check(alt.history.isEmpty()) { "alternate screen hides scrollback" } + check(alt.screen[0].text.startsWith("┌────────────────┐")) { "line drawing" } + check(alt.screen[2].text.startsWith("│ 宽字符 😀")) { "wide characters" } + check(alt.screen.subList(5, 8).map { it.text.trim() } == listOf("region-2", "region-3", "region-4")) { "scroll region" } + marker("SSH_XTERM:ALT_SCREEN:PASS") + check(alt.title == "NetKit alt") { "title" } + ui.await { it.text?.toString()?.contains("NetKit alt") == true } + marker("SSH_XTERM:TITLE_SHOWN:PASS") + screenshot("ssh-xterm-alt.png") + + ui.clickTag("ssh_snippet_xterm-main") + withTimeout(10000) { model.state.first { s -> s.sessions.single().terminal.let { t -> !t.alternateScreen && all(t).any { it.text.startsWith("NETKIT_XTERM_MAIN_OK") } } } } + val main = all(terminal()) + check(main.any { it.text.startsWith("256 colors") } && main.none { it.text.startsWith("NETKIT_XTERM_ALT_OK") }) { "primary restored" } + marker("SSH_XTERM:ALT_RESTORED:PASS") + screenshot("ssh-xterm-main.png") + + ui.clickTag("ssh_close") + ui.clickTag("ssh_confirm") + ui.await { it.viewIdResourceName == "ssh_connect_${profile.id}" && it.isEnabled } + } catch (failure: Throwable) { + try { screenshot("ssh-xterm-failure.png") } catch (_: Throwable) { } + throw failure + } finally { + withContext(NonCancellable) { + test.runOnMainSync { activity.finish() } + withTimeout(3000) { while (!activity.isDestroyed) delay(50) } + } + } +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SystemSettingsEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SystemSettingsEvidence.kt new file mode 100644 index 0000000..02c3ed6 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/SystemSettingsEvidence.kt @@ -0,0 +1,524 @@ +package cz.netkit.app.test + +import android.app.Activity +import android.app.Instrumentation +import android.app.NotificationManager +import android.app.LocaleManager +import android.content.Context +import android.content.Intent +import android.content.res.Configuration +import android.os.Bundle +import android.os.LocaleList +import android.view.KeyEvent +import android.view.View +import android.view.WindowInsets +import android.view.accessibility.AccessibilityNodeInfo +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.SideEffect +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.toArgb +import androidx.compose.ui.platform.LocalView +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.lan.LanDevicesViewModel +import cz.netkit.app.lan.LanPreferencesSerializer +import cz.netkit.app.lan.LanTool +import cz.netkit.app.lan.LanToolStore +import cz.netkit.app.lan.LanUiState +import cz.netkit.app.lan.keepsScreenOn +import cz.netkit.app.ssh.SshSessionService +import cz.netkit.app.settings.SettingsHost +import cz.netkit.app.settings.SettingsViewModel +import cz.netkit.app.speed.SpeedTestViewModel +import cz.netkit.app.ui.KeepScreenOn +import cz.netkit.app.ui.theme.DarkNetKitColors +import cz.netkit.app.ui.theme.LightNetKitColors +import cz.netkit.shared.lan.LanRunStatus +import cz.netkit.shared.lan.FavoriteTarget +import cz.netkit.shared.lan.ToolTargets +import cz.netkit.shared.lan.DiscoveryConsent +import cz.netkit.shared.settings.ThemeMode +import cz.netkit.shared.speed.SpeedEngine +import cz.netkit.shared.speed.SpeedRecord +import cz.netkit.shared.speed.SpeedStoreCodec +import cz.netkit.shared.speed.SpeedStoreData +import java.io.File +import kotlin.math.abs +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeout + +/** + * Zadání 46 on the real MainActivity, CS or EN app locale: predictive back (tab → Přehled, editors, + * About/licences, leaving the app from Přehled), the Settings screen (theme with rendered background, + * consent resets and history deletion against the real stores, online-query switch, update card, + * About link, app language switched from the UI) and the KeepScreenOn helper under the production + * SettingsHost (view flag and the window's KEEP_SCREEN_ON in WindowManager). Only synthetic data: + * documentation addresses, a fake LAN consent key; the shared SharedPreferences and the app locale + * are restored afterwards. + */ +suspend fun systemSettingsEvidence(test: Instrumentation, app: M1TestApplication, language: String, + screenshot: (String) -> Unit, marker: (String) -> Unit) { + require(language in setOf("cs", "en")) + // One small suspend method per stage: a single coroutine body with every step overflowed the + // ART verifier (VerifyError on the spilled state-machine registers). + val run = SystemSettingsRun(test, app, language, screenshot, marker) + try { + run.seed() + run.predictiveBack() + val main = run.settingsScreen() + run.updatesAndAbout(main) + val switched = run.languageFromUi() + run.keepScreenOn(switched) + } finally { + run.restore() + } +} + +private class SystemSettingsRun( + private val test: Instrumentation, + private val app: M1TestApplication, + private val language: String, + private val screenshot: (String) -> Unit, + private val marker: (String) -> Unit, +) { + private val other = if (language == "cs") "en" else "cs" + private val expected = localized(language) + private val localeManager: LocaleManager = app.getSystemService(LocaleManager::class.java) + private val beforeLocales: LocaleList = localeManager.applicationLocales + private val lanPrefs = app.getSharedPreferences("lan-devices", Context.MODE_PRIVATE) + private val overviewPrefs = app.getSharedPreferences("overview", Context.MODE_PRIVATE) + private val lanBefore: Map = lanPrefs.all.toMap() + private val overviewBefore: Map = overviewPrefs.all.toMap() + private val speedFile = File(app.noBackupFilesDir, "speedtest.json") + private val settingsFile = File(app.filesDir, "datastore/settings.json") + private val ui = SshEvidenceUi(test) + private val activities = mutableListOf() + + private fun localized(tag: String): Context = + app.createConfigurationContext(Configuration().apply { setLocales(LocaleList.forLanguageTags(tag)) }) + + private fun start(): MainActivity = (test.startActivitySync(Intent(app, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)) as MainActivity).also { activities += it } + + private suspend fun settle() { + delay(800) + test.waitForIdleSync() + try { test.uiAutomation.waitForIdle(300, 5_000) } catch (_: java.util.concurrent.TimeoutException) { } + } + + private suspend fun visible(tag: String) = ui.await { it.viewIdResourceName == tag && it.isVisibleToUser } + + private suspend fun gone(tag: String) = + withTimeout(8_000) { while (ui.all().any { it.viewIdResourceName == tag && it.isVisibleToUser }) delay(100) } + + private suspend fun scrollTo(tag: String): AccessibilityNodeInfo { + repeat(12) { + val found = ui.all().firstOrNull { it.viewIdResourceName == tag && it.isVisibleToUser } + if (found != null) return found + ui.all().firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) + delay(300) + } + return visible(tag) + } + + /** Like [scrollTo], but upwards: a row above the current viewport is not in the semantics tree. */ + private suspend fun scrollBackTo(tag: String): AccessibilityNodeInfo { + repeat(12) { + val found = ui.all().firstOrNull { it.viewIdResourceName == tag && it.isVisibleToUser } + if (found != null) return found + ui.all().firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD) + delay(300) + } + return visible(tag) + } + + private fun imeVisible(activity: Activity): Boolean { + var shown = false + test.runOnMainSync { shown = activity.window.decorView.rootWindowInsets?.isVisible(WindowInsets.Type.ime()) == true } + return shown + } + + /** System back as a key event; an open soft keyboard is closed first (that back belongs to the IME). */ + private suspend fun back(activity: Activity) { + if (imeVisible(activity)) { + test.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK) + withTimeout(5_000) { while (imeVisible(activity)) delay(100) } + } + test.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK) + delay(400) + } + + private suspend fun overview(activity: Activity) { + visible("signal_screen") + check(ui.await { it.viewIdResourceName == "tab_signal" }.isSelected) { "Přehled tab selected" } + check(!activity.isFinishing) + } + + private fun pixel(name: String): Int { + val image = test.uiAutomation.takeScreenshot() ?: error("screenshot $name") + try { + // Left gutter (16 dp) in the middle of the screen: the screen background, outside any card. + return image.getPixel(8, image.height / 2) + } finally { image.recycle() } + } + + private fun near(color: Int, expected: Int) = + listOf(16, 8, 0).all { shift -> abs((color shr shift and 0xFF) - (expected shr shift and 0xFF)) <= 6 } + + private fun speedData(): SpeedStoreData = SpeedStoreCodec.decode(speedFile.readText()) + + private fun windowKeepsScreenOn(): Boolean { + val dump = test.uiAutomation.executeShellCommand("dumpsys window windows").let { descriptor -> + android.os.ParcelFileDescriptor.AutoCloseInputStream(descriptor).use { it.readBytes().decodeToString() } + } + // The section of NetKit's main window up to the next window entry. + val start = dump.indexOf("cz.netkit.app/cz.netkit.app.MainActivity}:") + check(start >= 0) { "main window not in dumpsys" } + val end = dump.indexOf("Window #", start).let { if (it < 0) dump.length else it } + return Regex("""\bfl=[^\n]*\bKEEP_SCREEN_ON\b""").containsMatchIn(dump.substring(start, end)) + } + + /** Synthetic history, NDT7 consent, iperf3 target and one fake LAN consent; app locale under test. */ + fun seed() { + val now = System.currentTimeMillis() + speedFile.parentFile?.mkdirs() + speedFile.writeText(SpeedStoreCodec.encode(SpeedStoreData(ndt7ConsentMs = now - 60_000, + records = listOf(SpeedRecord(now - 3_000, SpeedEngine.IPERF3, "192.0.2.10:5202", downloadMbps = 90.0), + SpeedRecord(now - 2_000, SpeedEngine.LIBRESPEED, "Test LibreSpeed", downloadMbps = 100.0), + SpeedRecord(now - 1_000, SpeedEngine.NDT7, "M-Lab NDT7", downloadMbps = 110.0)), + iperfHost = "192.0.2.10", iperfPort = 5202))) + check(lanPrefs.edit().putString("consent.netkit-test-46", "ALLOWED").commit()) + check(overviewPrefs.edit().putBoolean("public_ip.enabled", true).commit()) + test.runOnMainSync { localeManager.applicationLocales = LocaleList.forLanguageTags(language) } + } + + suspend fun predictiveBack() { + val first = start() + check(first.resources.configuration.locales[0].language == language) + marker("SYSTEM:LANGUAGE:$language") + overview(first) + ui.clickTag("tab_wol"); visible("wol_add") + back(first); overview(first) + ui.clickTag("tab_lan"); visible("lan_segment_tools") + back(first); overview(first) + marker("SYSTEM:BACK:TAB_TO_OVERVIEW:PASS") + ui.clickTag("tab_wol"); ui.clickTag("wol_add"); visible("device_form") + back(first); visible("wol_add") + check(ui.await { it.viewIdResourceName == "tab_wol" }.isSelected) { "WoL form closes to the WoL list" } + back(first); overview(first) + marker("SYSTEM:BACK:WOL_EDITOR:PASS") + ui.clickTag("tab_ssh"); ui.clickTag("ssh_add"); gone("ssh_add") + back(first); visible("ssh_add") + check(ui.await { it.viewIdResourceName == "tab_ssh" }.isSelected) { "Untouched editor closes directly to the SSH list" } + ui.clickTag("ssh_add") + val name = ui.await { it.isEditable && it.isVisibleToUser } + check(name.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, Bundle().apply { + putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, "Lab") + })) + back(first); visible("ssh_confirm") + ui.clickTag("ssh_confirm"); visible("ssh_add") + back(first); overview(first) + marker("SYSTEM:BACK:SSH_EDITOR:PASS") + ui.clickTag("overview_menu"); ui.clickTag("overview_menu_about"); visible("about_screen") + scrollTo("about_oss_licenses"); ui.clickTag("about_oss_licenses"); visible("oss_licenses_screen") + back(first); visible("about_screen") + back(first); overview(first) + marker("SYSTEM:BACK:ABOUT_LICENSES:PASS") + ui.clickTag("overview_menu"); ui.clickTag("overview_menu_settings"); visible("settings_screen") + back(first); overview(first) + marker("SYSTEM:BACK:SETTINGS:PASS") + // On Přehled back belongs to the system: the app leaves the foreground (Android 12+: moved back, not finished). + test.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK) + withTimeout(8_000) { while (first.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) delay(100) } + marker("SYSTEM:BACK:OVERVIEW_LEAVES_APP:PASS") + } + + /** Settings on a fresh start: theme, keep-screen switch, consents, histories. Returns the activity. */ + suspend fun settingsScreen(): MainActivity { + val main = start() + val settings = ViewModelProvider(main)[SettingsViewModel::class.java] + overview(main) + ui.clickTag("overview_menu") + ui.await { it.viewIdResourceName == "overview_menu_settings" && it.isVisibleToUser } + settle(); screenshot("settings-menu.png") + ui.clickTag("overview_menu_settings"); visible("settings_screen") + ui.findText(expected.getString(R.string.settings_title)) + check(ui.await { it.viewIdResourceName == "settings_theme_system" }.isSelected) + check(ui.await { it.viewIdResourceName == "settings_language_$language" }.isSelected) { "language segment shows $language" } + check(ui.await { it.viewIdResourceName == "settings_language_open" }.isVisibleToUser) + marker("SYSTEM:SETTINGS:OPENED:UI_VERIFIED") + settle(); screenshot("settings-top.png") + theme(settings) + keepScreenSwitch(settings) + consents() + lanCancelledCaller(main) + histories(main) + targetHistory() + return main + } + + /** Theme: rendered background follows the choice, and the file keeps it. */ + private suspend fun theme(settings: SettingsViewModel) { + ui.clickTag("settings_theme_dark") + withTimeout(5_000) { while (settings.settings.value?.theme != ThemeMode.DARK) delay(50) } + settle() + check(near(pixel("dark"), DarkNetKitColors.background.toArgb())) { "dark background" } + withTimeout(5_000) { while (!(settingsFile.isFile && settingsFile.readText().contains("\"DARK\""))) delay(100) } + screenshot("settings-dark.png") + marker("SYSTEM:THEME:DARK:PIXEL_AND_STORE_VERIFIED") + ui.clickTag("settings_theme_light") + withTimeout(5_000) { while (settings.settings.value?.theme != ThemeMode.LIGHT) delay(50) } + settle() + check(near(pixel("light"), LightNetKitColors.background.toArgb())) { "light background" } + marker("SYSTEM:THEME:LIGHT:PIXEL_VERIFIED") + ui.clickTag("settings_theme_system") + withTimeout(5_000) { while (settings.settings.value?.theme != ThemeMode.SYSTEM) delay(50) } + marker("SYSTEM:THEME:SYSTEM:RESTORED") + } + + /** Keep the display on: the switch changes the stored setting. */ + private suspend fun keepScreenSwitch(settings: SettingsViewModel) { + val keep = scrollTo("settings_keep_screen") + check(keep.isChecked) { "keep screen on defaults to on" } + ui.clickTag("settings_keep_screen") + withTimeout(5_000) { while (settings.settings.value?.keepScreenOn != false) delay(50) } + withTimeout(5_000) { while (!settingsFile.readText().contains("\"keepScreenOn\":false")) delay(100) } + check(!scrollTo("settings_keep_screen").isChecked) + ui.clickTag("settings_keep_screen") + withTimeout(5_000) { while (settings.settings.value?.keepScreenOn != true) delay(50) } + marker("SYSTEM:KEEP_SCREEN:SWITCH:STORE_VERIFIED") + } + + /** Consents and online queries. */ + private suspend fun consents() { + val online = scrollTo("settings_online") + check(online.isChecked) + ui.clickTag("settings_online") + withTimeout(5_000) { while (overviewPrefs.getBoolean("public_ip.enabled", true)) delay(50) } + check(!scrollTo("settings_online").isChecked) + ui.clickTag("settings_online") + withTimeout(5_000) { while (!overviewPrefs.getBoolean("public_ip.enabled", false)) delay(50) } + marker("SYSTEM:ONLINE:TOGGLE:PREFS_VERIFIED") + scrollTo("settings_ndt7_consent") + ui.findText(expected.getString(R.string.settings_ndt7_acknowledged)) + settle(); screenshot("settings-privacy.png") + // Since the target-history row (#51) the NDT7 row can push the LAN consent row above the viewport. + scrollBackTo("settings_lan_consent") + ui.clickTag("settings_lan_consent") + visible("settings_confirm") + ui.findText(expected.getString(R.string.settings_confirm_lan_title)) + settle(); screenshot("settings-confirm-lan.png") + ui.clickTag("settings_confirm") + visible("settings_lan_consent_result") + withTimeout(5_000) { while (lanPrefs.all.keys.any { it.startsWith("consent.") }) delay(50) } + marker("SYSTEM:RESET:LAN_CONSENT:PREFS_VERIFIED") + scrollTo("settings_ndt7_consent") + ui.clickTag("settings_ndt7_consent") + visible("settings_ndt7_consent_result") + withTimeout(5_000) { while (speedData().ndt7ConsentMs != null) delay(50) } + ui.findText(expected.getString(R.string.settings_ndt7_pending)) + marker("SYSTEM:RESET:NDT7_CONSENT:STORE_VERIFIED") + } + + /** + * Revize kolo 1: the consent reset finishes in the ViewModel scope although its caller (Settings' + * composition scope) is cancelled right away; the current network must not stay ALLOWED in memory. + */ + private suspend fun lanCancelledCaller(main: MainActivity) { + val devices = ViewModelProvider(main)[LanDevicesViewModel::class.java] + withTimeout(10_000) { while (devices.state.value.let { it.loadingNetwork || it.network == null }) delay(100) } + test.runOnMainSync { devices.allowAutoDiscovery() } + withTimeout(5_000) { while (devices.state.value.consent != DiscoveryConsent.ALLOWED) delay(50) } + cancelledCaller { devices.forgetAllConsents() } + withTimeout(5_000) { while (devices.state.value.consent != DiscoveryConsent.UNKNOWN) delay(50) } + withTimeout(5_000) { while (lanPrefs.all.keys.any { it.startsWith("consent.") }) delay(50) } + marker("SYSTEM:CANCELLED_CALLER:LAN_CONSENT:STATE_AND_PREFS_VERIFIED") + } + + /** Starts [action] on the main thread and cancels its caller before the store write can answer. */ + private fun cancelledCaller(action: suspend () -> Unit) { + val caller = CoroutineScope(SupervisorJob() + Dispatchers.Main) + var pending = false + test.runOnMainSync { + val job = caller.launch(start = CoroutineStart.UNDISPATCHED) { action() } + pending = job.isActive + job.cancel() + } + caller.cancel() + check(pending) { "the action must still be waiting for its write when the caller is cancelled" } + } + + /** Histories and the iperf3 target. */ + private suspend fun histories(main: MainActivity) { + scrollTo("settings_speed_history") + ui.findText(expected.resources.getQuantityString(R.plurals.settings_history_count, 2, 2)) + ui.findText("192.0.2.10:5202", scroll = true) + settle(); screenshot("settings-data.png") + ui.clickTag("settings_speed_history") + visible("settings_confirm") + settle(); screenshot("settings-confirm-delete.png") + ui.clickTag("settings_confirm") + withTimeout(5_000) { while (speedData().records.map { it.engine } != listOf(SpeedEngine.IPERF3)) delay(50) } + marker("SYSTEM:DELETE:SPEED_HISTORY:STORE_VERIFIED") + scrollTo("settings_iperf_history"); ui.clickTag("settings_iperf_history") + visible("settings_confirm"); ui.clickTag("settings_confirm") + withTimeout(5_000) { while (speedData().records.isNotEmpty()) delay(50) } + marker("SYSTEM:DELETE:IPERF_HISTORY:STORE_VERIFIED") + // Revize kolo 1: the row shows the stored server even when the iperf3 form is emptied. + val speed = ViewModelProvider(main)[SpeedTestViewModel::class.java] + test.runOnMainSync { speed.setIperfForm(speed.state.value.iperf.copy(host = "")) } + withTimeout(5_000) { while (speed.state.value.iperf.host.isNotEmpty()) delay(50) } + check(scrollTo("settings_iperf_target").isEnabled) { "Forget stays enabled for the stored server" } + ui.findText("192.0.2.10:5202", scroll = true) + check(speedData().iperfHost == "192.0.2.10") + marker("SYSTEM:IPERF_TARGET:STORED_NOT_FORM:UI_VERIFIED") + // Forget with a caller cancelled at once: store, saved target and form are still cleared. + test.runOnMainSync { speed.setIperfForm(speed.state.value.iperf.copy(host = "192.0.2.10", port = "5202")) } + cancelledCaller { speed.forgetIperfTarget() } + withTimeout(5_000) { while (speedData().iperfHost.isNotEmpty() || speedData().iperfPort != 5201) delay(50) } + withTimeout(5_000) { while (speed.state.value.let { it.savedIperfTarget != null || it.iperf.host.isNotEmpty() }) delay(50) } + marker("SYSTEM:CANCELLED_CALLER:IPERF_TARGET:STATE_AND_STORE_VERIFIED") + ui.findText(expected.getString(R.string.settings_iperf_target_none), scroll = true) + check(!ui.await { it.viewIdResourceName == "settings_iperf_target" }.isEnabled) { "nothing stored to forget" } + check(!ui.await { it.viewIdResourceName == "settings_speed_history" }.isEnabled) { "nothing left to delete" } + settle(); screenshot("settings-data-cleared.png") + marker("SYSTEM:FORGET:IPERF_TARGET:STORE_VERIFIED") + } + + private suspend fun targetHistory() { + val store = LanToolStore.get(app) + val before = store.data.first().targets + val seeded = ToolTargets(listOf("192.0.2.10", "192.0.2.11"), listOf(FavoriteTarget("192.0.2.10", "Lab"))) + try { + store.updateData { it.copy(targets = seeded) } + scrollTo("settings_tool_targets") + ui.await { it.viewIdResourceName == "settings_tool_targets" && it.isEnabled } + ui.clickTag("settings_tool_targets") + visible("settings_confirm_cancel"); ui.clickTag("settings_confirm_cancel") + gone("settings_confirm") + check(store.data.first().targets == seeded) + ui.clickTag("settings_tool_targets") + visible("settings_confirm"); ui.clickTag("settings_confirm") + withTimeout(5_000) { store.data.first { it.targets.recent.isEmpty() } } + val saved = app.filesDir.resolve("datastore/lan-tools.json").inputStream().use { + LanPreferencesSerializer.readFrom(it) + } + check(saved.targets == seeded.copy(recent = emptyList())) + marker("SYSTEM:DELETE:TARGET_HISTORY:FAVORITES_PRESERVED") + } finally { store.updateData { it.copy(targets = before) } } + } + + /** Update check moved to Settings; About keeps a link back. */ + suspend fun updatesAndAbout(main: MainActivity) { + scrollTo("about_check_now"); scrollTo("about_update_toggle") + settle(); screenshot("settings-updates.png") + marker("SYSTEM:UPDATES:IN_SETTINGS:UI_VERIFIED") + back(main); overview(main) + ui.clickTag("overview_menu"); ui.clickTag("overview_menu_about"); visible("about_screen") + check(ui.all().none { it.viewIdResourceName == "about_check_now" }) { "About no longer has the check button" } + ui.clickTag("about_open_settings"); visible("settings_screen") + back(main); visible("about_screen") + settle(); screenshot("about-settings-link.png") + marker("SYSTEM:ABOUT:SETTINGS_LINK:UI_VERIFIED") + back(main); overview(main) + } + + /** App language from the UI: LocaleManager recreates the activity, the subscreen stays open. */ + suspend fun languageFromUi(): MainActivity { + ui.clickTag("overview_menu"); ui.clickTag("overview_menu_settings"); visible("settings_screen") + SshSessionService.createChannel(app) + val recreated = test.addMonitor(MainActivity::class.java.name, null, false) + ui.clickTag("settings_language_$other") + val switched = test.waitForMonitorWithTimeout(recreated, 8_000) as? MainActivity ?: error("no recreated activity") + test.removeMonitor(recreated) + activities += switched + check(switched.resources.configuration.locales[0].language == other) + check(localeManager.applicationLocales.toLanguageTags().startsWith(other)) + ui.findText(localized(other).getString(R.string.settings_title)) + check(ui.await { it.viewIdResourceName == "settings_language_$other" }.isSelected) + settle(); screenshot("settings-language-$other.png") + val notifications = app.getSystemService(NotificationManager::class.java) + val channelName = localized(other).getString(R.string.ssh_notification_channel) + withTimeout(8_000) { + while (notifications.getNotificationChannel(SshSessionService.CHANNEL_ID)?.name?.toString() != channelName) delay(100) + } + marker("SYSTEM:LANGUAGE:SSH_CHANNEL:VERIFIED") + marker("SYSTEM:LANGUAGE:UI_SWITCH:PASS") + return switched + } + + /** KeepScreenOn under the production SettingsHost: view flag and the window's KEEP_SCREEN_ON. */ + suspend fun keepScreenOn(switched: MainActivity) { + val tcpPing = mutableStateOf(LanUiState(tool = LanTool.TCP_PING)) + val second = mutableStateOf(false) + val holder = arrayOfNulls(1) + val switchedSettings = ViewModelProvider(switched)[SettingsViewModel::class.java] + test.runOnMainSync { + switched.setContent { + SettingsHost(switchedSettings, switched) { + val current = LocalView.current + SideEffect { holder[0] = current } + KeepScreenOn(tcpPing.value.keepsScreenOn) + KeepScreenOn(second.value) + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column { Text("SYNTHETIC UI · KeepScreenOn TCP ping=${tcpPing.value.runStatus} second=${second.value}") } + } + } + } + } + expectKeep(holder, false, "IDLE") + test.runOnMainSync { tcpPing.value = tcpPing.value.copy(runStatus = LanRunStatus.RUNNING) } + expectKeep(holder, true, "RUNNING") + test.runOnMainSync { switchedSettings.setKeepScreenOn(false) } + expectKeep(holder, false, "SETTING_OFF") + test.runOnMainSync { switchedSettings.setKeepScreenOn(true) } + expectKeep(holder, true, "SETTING_ON") + test.runOnMainSync { second.value = true } + test.runOnMainSync { tcpPing.value = tcpPing.value.copy(runStatus = LanRunStatus.FINISHED) } + expectKeep(holder, true, "OVERLAP") + test.runOnMainSync { second.value = false } + expectKeep(holder, false, "RELEASED") + marker("SYSTEM:KEEP_SCREEN:WINDOW_FLAG:VERIFIED") + } + + private suspend fun expectKeep(holder: Array, on: Boolean, step: String) { + withTimeout(5_000) { while (holder[0]?.keepScreenOn != on) delay(50) } + withTimeout(8_000) { while (windowKeepsScreenOn() != on) delay(200) } + marker("SYSTEM:KEEP_SCREEN:$step:${if (on) "ON" else "OFF"}") + } + + /** Finish the test's activities and put back the app locale and the shared SharedPreferences. */ + fun restore() { + test.runOnMainSync { activities.forEach { if (!it.isFinishing) it.finish() } } + test.runOnMainSync { localeManager.applicationLocales = beforeLocales } + restorePrefs(lanPrefs, lanBefore) + restorePrefs(overviewPrefs, overviewBefore) + } + + private fun restorePrefs(prefs: android.content.SharedPreferences, before: Map) { + prefs.edit().clear().apply { + before.forEach { (key, value) -> when (value) { + is Boolean -> putBoolean(key, value) + is Int -> putInt(key, value) + is Long -> putLong(key, value) + is Float -> putFloat(key, value) + is String -> putString(key, value) + } } + }.commit() + } +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/ToolTargetsEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/ToolTargetsEvidence.kt new file mode 100644 index 0000000..17d70e7 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/ToolTargetsEvidence.kt @@ -0,0 +1,222 @@ +package cz.netkit.app.test + +import android.app.Activity +import android.app.Instrumentation +import android.app.LocaleManager +import android.content.Intent +import android.os.Bundle +import android.os.LocaleList +import android.view.accessibility.AccessibilityNodeInfo +import androidx.lifecycle.ViewModelProvider +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.app.lan.LanTool +import cz.netkit.app.lan.LanToolStore +import cz.netkit.app.lan.LanViewModel +import cz.netkit.shared.lan.FavoriteChange +import cz.netkit.shared.lan.LanRunStatus +import cz.netkit.shared.lan.TargetConfirmationReason +import cz.netkit.shared.lan.ToolTargets +import java.net.InetAddress +import java.net.ServerSocket +import java.util.Locale +import java.util.concurrent.atomic.AtomicInteger +import kotlin.concurrent.thread +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout + +/** Synthetic Cisco `show mac address-table` with RFC 7042 documentation MACs plus one LAA and one multicast. */ +private val MAC_TABLE_SAMPLE = """ + |Vlan Mac Address Type Ports + |---- ----------- -------- ----- + | 10 0000.5e00.5301 DYNAMIC Gi1/0/1 + | 10 0200.5e00.5302 DYNAMIC Gi1/0/2 + | 20 0000.5e00.5301 DYNAMIC Po1 + | All 0100.5e00.0001 STATIC CPU +""".trimMargin() + +private fun seedTargets(): ToolTargets { + val recent = ToolTargets().remember("192.0.2.20").remember("https://example.com/").remember("example.com") + return (recent.star("198.51.100.1", "Lab switch") as FavoriteChange.Updated).targets +} + +/** + * Zadání 48 on the emulator, production MainActivity and [LanViewModel] in Czech and English: + * 1) shared history and favourites at the target field (filtered per tool, choose, star with a + * label, clear history keeps favourites); 2) TCP ping to a loopback listener in this process + * (statistics, one connection at a time, RST counted as loss, target remembered on start); + * 3) MAC → vendor over a synthetic MAC table with the bundled IEEE OUI list. + * The tool DataStore is restored afterwards. + */ +suspend fun toolTargetsEvidence(test: Instrumentation, app: M1TestApplication, screenshot: (String) -> Unit, marker: (String) -> Unit) { + val ui = SshEvidenceUi(test) + val localeManager = app.getSystemService(LocaleManager::class.java) + val beforeLocales = localeManager.applicationLocales + val store = LanToolStore.get(app) + val beforeTargets = store.data.first().targets + var activity: Activity? = null + // Loopback listener: counts connections that are open at the same time. + val server = withContext(Dispatchers.IO) { ServerSocket(0, 16, InetAddress.getByName("127.0.0.1")) } + val open = AtomicInteger(); val maximum = AtomicInteger(); val accepted = AtomicInteger() + val acceptor = thread(name = "tools48-tcp-ping", isDaemon = true) { + while (!server.isClosed) { + val socket = try { server.accept() } catch (_: java.io.IOException) { break } + accepted.incrementAndGet() + maximum.accumulateAndGet(open.incrementAndGet()) { a, b -> maxOf(a, b) } + thread(isDaemon = true) { try { socket.use { it.getInputStream().read() } } catch (_: java.io.IOException) { } finally { open.decrementAndGet() } } + } + } + val closedPort = withContext(Dispatchers.IO) { ServerSocket(0, 1, InetAddress.getByName("127.0.0.1")).use { it.localPort } } + + suspend fun settle() { delay(1_000); test.waitForIdleSync(); test.uiAutomation.waitForIdle(300, 5_000) } + suspend fun setText(tag: String, value: String) { + val field = ui.await { it.viewIdResourceName == tag && it.isEditable } + check(field.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, Bundle().apply { + putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, value) + })) + } + suspend fun scrollTo(predicate: (AccessibilityNodeInfo) -> Boolean): AccessibilityNodeInfo { + repeat(10) { + ui.all().firstOrNull { predicate(it) && it.isVisibleToUser }?.let { return it } + ui.all().firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) + delay(300) + } + return ui.await { predicate(it) && it.isVisibleToUser } + } + suspend fun closeMenu() { test.uiAutomation.performGlobalAction(android.accessibilityservice.AccessibilityService.GLOBAL_ACTION_BACK); delay(400) } + suspend fun runToEnd(model: LanViewModel) { + // busy is true while the target resolves, then the confirmation (loopback is outside the Wi-Fi) or the end. + val terminal = setOf(LanRunStatus.FINISHED, LanRunStatus.FAILED, LanRunStatus.CANCELLED) + val asked = withTimeout(10_000) { model.state.first { it.confirmation || it.error != null || (!it.busy && it.runStatus in terminal) } } + check(asked.error == null) { "error ${asked.error}" } + if (asked.confirmation) { + check(TargetConfirmationReason.OUTSIDE_WIFI in asked.confirmationReasons) { "reasons ${asked.confirmationReasons}" } + test.runOnMainSync { model.start(true) } + } + withTimeout(20_000) { model.state.first { !it.busy && !it.confirmation && it.runStatus != LanRunStatus.RUNNING && it.runStatus != LanRunStatus.IDLE } } + } + + try { + for (language in listOf("cs", "en")) { + store.updateData { it.copy(targets = seedTargets()) } + test.runOnMainSync { localeManager.applicationLocales = LocaleList(Locale.forLanguageTag(language)) } + activity = test.startActivitySync(Intent(app, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)) + val res = activity!!.resources + check(res.configuration.locales[0].language == language) + lateinit var model: LanViewModel + test.runOnMainSync { model = ViewModelProvider(activity as MainActivity)[LanViewModel::class.java] } + ui.clickTag("tab_lan") + ui.clickTag("lan_segment_tools") + test.runOnMainSync { model.tool(LanTool.PING); model.host("") } + withTimeout(5_000) { model.state.first { it.targets == seedTargets() } } + + // --- 1) History and favourites --------------------------------------------------------- + ui.clickTag("target_history") + ui.await { it.text?.toString() == "Lab switch" } + ui.await { it.text?.toString() == "example.com" } + ui.await { it.text?.toString() == res.getString(R.string.tools48_clear_history) } + check(ui.all().none { it.text?.toString() == "https://example.com/" }) { "URL offered to ping" } + settle() + screenshot("tools-targets-menu-$language.png") + marker("TARGETS:MENU_FILTERED:$language:UI_VERIFIED") + ui.click(ui.await { it.text?.toString() == "example.com" }) + withTimeout(5_000) { model.state.first { it.host == "example.com" } } + marker("TARGETS:CHOOSE:$language:PASS") + + // The same list in Web/TLS offers only the URL. + test.runOnMainSync { model.tool(LanTool.WEB) } + ui.clickTag("target_history") + ui.await { it.text?.toString() == "https://example.com/" } + check(ui.all().none { it.text?.toString() == "example.com" || it.text?.toString() == "192.0.2.20" }) { "host offered to Web/TLS" } + closeMenu() + marker("TARGETS:WEB_URL_ONLY:$language:PASS") + + // Star the current target with a label. + test.runOnMainSync { model.tool(LanTool.PING); model.host("198.51.100.7") } + ui.clickTag("target_history") + ui.clickTag("target_star") + setText("target_favorite_label", "Core $language") + ui.await { it.text?.toString() == "Core $language" } + settle() + screenshot("tools-targets-star-$language.png") + ui.clickTag("target_favorite_save") + withTimeout(5_000) { model.state.first { state -> state.targets.favorites.any { it.value == "198.51.100.7" && it.label == "Core $language" } } } + marker("TARGETS:STAR_LABEL:$language:PASS") + + // Clear history: recent entries go, both favourites stay. + ui.clickTag("target_history") + ui.clickTag("target_clear_history") + withTimeout(5_000) { model.state.first { it.targets.recent.isEmpty() } } + check(model.state.value.targets.favorites.map { it.value } == listOf("198.51.100.1", "198.51.100.7")) + marker("TARGETS:CLEAR_KEEPS_FAVORITES:$language:PASS") + + // --- 2) TCP ping to the loopback listener ------------------------------------------------ + val before = accepted.get() + test.runOnMainSync { + model.tool(LanTool.TCP_PING); model.host("127.0.0.1"); model.tcpPort(server.localPort.toString()) + model.tcpCount("4"); model.timeout("1000"); model.start() + } + val done = run { runToEnd(model); model.state.value } + check(done.runStatus == LanRunStatus.FINISHED && done.sent == 4 && done.received == 4) { + "tcp ping ${done.runStatus} sent ${done.sent} received ${done.received} error ${done.error}" + } + check(accepted.get() - before == 4) { "accepted ${accepted.get() - before}" } + check(done.results.all { it.method == "TCP" && it.port == server.localPort }) + marker("TCP_PING:LOOPBACK:$language:sent=${done.sent};received=${done.received};rtt=" + + done.samples.filterNotNull().joinToString("/") { "%.2f".format(Locale.ROOT, it) }) + check(done.targets.recent.firstOrNull() == "127.0.0.1" || model.state.value.targets.recent.firstOrNull() == "127.0.0.1") + marker("TARGETS:REMEMBERED_ON_START:$language:PASS") + scrollTo { it.text?.toString() == res.getString(R.string.lan_ping_statistics) } + settle() + screenshot("tools-tcp-ping-$language.png") + marker("TCP_PING:$language:UI_VERIFIED") + + if (language == "cs") { + // RST from a closed port is a lost sample, not a reply. + test.runOnMainSync { model.tcpPort(closedPort.toString()); model.tcpCount("2"); model.start() } + val refused = run { runToEnd(model); model.state.value } + check(refused.sent == 2 && refused.received == 0 && refused.results.all { it.detail == "REFUSED" && it.milliseconds == null }) { + "refused ${refused.sent}/${refused.received} ${refused.results.map { it.detail }}" + } + marker("TCP_PING:REFUSED_IS_LOSS:PASS") + } + + // --- 3) MAC → vendor --------------------------------------------------------------------- + test.runOnMainSync { model.tool(LanTool.MAC_VENDOR); model.macInput(MAC_TABLE_SAMPLE) } + ui.clickTag("mac_lookup") + val macs = withTimeout(10_000) { model.state.first { !it.busy && it.macRows.isNotEmpty() } } + val byMac = macs.macRows.associateBy { it.mac.text } + check(byMac.keys.toList() == listOf("00:00:5E:00:53:01", "02:00:5E:00:53:02", "01:00:5E:00:00:01")) { "macs ${byMac.keys}" } + check(byMac.getValue("00:00:5E:00:53:01").vendor == "ICANN, IANA Department" && byMac.getValue("00:00:5E:00:53:01").mac.occurrences == 2) + check(byMac.getValue("02:00:5E:00:53:02").let { it.vendor == null && it.mac.locallyAdministered }) + check(byMac.getValue("01:00:5E:00:00:01").let { it.vendor == null && it.mac.multicast }) + check(macs.results.size == 3 && !macs.ouiMissing) + if (language == "cs") marker("MAC_VENDOR:TABLE:PASS") + scrollTo { it.viewIdResourceName == "mac_row_02:00:5E:00:53:02" } + ui.await { it.text?.toString() == res.getString(R.string.tools48_mac_no_vendor_local) } + settle() + screenshot("tools-mac-$language.png") + marker("MAC_VENDOR:$language:UI_VERIFIED") + // Revize kolo 1: a failed export of the MAC table is visible in this panel (not only in the sheet). + test.runOnMainSync { model.exportFailed() } + repeat(6) { ui.all().firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); delay(200) } + scrollTo { it.text?.toString() == res.getString(R.string.lan_export_failed) } + check(macs.macRows.isNotEmpty() && model.state.value.macRows == macs.macRows) { "rows lost on export error" } + marker("MAC_VENDOR:EXPORT_ERROR_VISIBLE:$language:PASS") + test.runOnMainSync { activity?.finish() } + activity = null + } + } finally { + test.runOnMainSync { activity?.finish() } + withContext(Dispatchers.IO) { server.close() } + acceptor.join(2_000) + check(maximum.get() <= 1) { "concurrent TCP ping connections ${maximum.get()}" } + store.updateData { it.copy(targets = beforeTargets) } + test.runOnMainSync { localeManager.applicationLocales = beforeLocales } + } + marker("TCP_PING:ONE_CONNECTION_AT_A_TIME:PASS:max=${maximum.get()}") +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiExtensionsEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiExtensionsEvidence.kt new file mode 100644 index 0000000..047de40 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiExtensionsEvidence.kt @@ -0,0 +1,383 @@ +package cz.netkit.app.test + +import android.app.Instrumentation +import android.net.Uri +import android.os.Bundle +import android.provider.DocumentsContract +import android.view.accessibility.AccessibilityNodeInfo +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.MutableState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import cz.netkit.app.R +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.wifi.AccessPointRow +import cz.netkit.app.wifi.ExportDialog +import cz.netkit.app.wifi.NetworkListOptions +import cz.netkit.app.wifi.RegionalRasterNote +import cz.netkit.app.wifi.SpectrumPanel +import cz.netkit.app.wifi.live.WalkCard +import cz.netkit.app.wifi.live.WalkUiState +import cz.netkit.app.wifi.networksCard +import cz.netkit.app.wifi.rememberExportLauncher +import cz.netkit.app.wifi.writeExportDocument +import cz.netkit.shared.wifi.* +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeout +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** + * Zadání 38, UI only with synthetic, locally administered BSSIDs (not an RF scan): + * AC-001 spectrum with the connected AP, pinned APs and a pin missing from the scan; AC-002 the + * networks card grouped by SSID; AC-003 scan export through the real system picker (SAF) into a + * file that is read back and deleted; AC-004 the walk card (mark dialog, summary); AC-005 note. + */ +@OptIn(ExperimentalComposeUiApi::class) +suspend fun captureWifiExtensionsEvidence( + instrumentation: Instrumentation, + activity: ComponentActivity, + screenshot: (String) -> Unit, + marker: (String) -> Unit, +) { + val context = instrumentation.targetContext + val ui = SshEvidenceUi(instrumentation) + fun point(ssid: String?, id: Int, frequency: Int, rssi: Int, current: Boolean = false, selected: Boolean = false) = AccessPoint( + ssid, "02:00:00:00:38:${id.toString(16).padStart(2, '0')}", rssi, frequency, channel = channelForFrequency(frequency), + band = bandForFrequency(frequency), widthMhz = 20, security = WifiSecurity.WPA2, standard = "ax", ageMs = 0, + locallyAdministered = true, isCurrent = current, isSelected = selected) + suspend fun settle() { + // The accessibility tree can be ahead of the composited frame (see WifiSpectrumEvidence). + delay(1_500) + instrumentation.waitForIdleSync() + instrumentation.uiAutomation.waitForIdle(500, 5_000) + } + + // --- AC-001 pins + AC-005 regional note -------------------------------------------------- + val connected = point("Moje síť", 1, 2437, -72, current = true) + val strong = (2..5).map { point("Soused $it", it, 2412 + it * 10, -40 - it) } + val weak6 = point("Sklep AP", 6, 2462, -86, selected = true) + val weak7 = point("Garáž AP", 7, 2472, -88) + val gone = point("Půda AP", 9, 2412, -80) // pinned in an earlier scan, absent now + val points = listOf(connected) + strong + listOf(weak6, weak7) + var pins = emptyList() + for (ap in listOf(gone, weak6, weak7)) pins = togglePinnedAccessPoint(pins, ap).pins + check(togglePinnedAccessPoint(pins, strong[0]).change == PinChange.LIMIT_REACHED) + pins = refreshPinnedAccessPoints(pins, points) + val spectrum = bandSpectrum(points, WifiBand.GHZ_2_4)!! + val selection = spectrumSelection(spectrum.traces, pins, WifiBand.GHZ_2_4, points) + check(selection.drawn.map { it.accessPoint } == listOf(connected, weak6, weak7, strong[0], strong[1], strong[2])) { "drawn order" } + check(selection.missingPins.map { it.ssid } == listOf("Půda AP")) + val state = WifiAnalyzerState(accessPoints = points, status = WifiScanStatus.READY, selectedBssid = weak6.bssid) + val raster = regional24Raster("cz")!! + val pinsState = mutableStateOf(pins) + val pinsIdentity = "SYNTHETIC UI · pins (connected → pinned → strongest)" + instrumentation.runOnMainSync { + activity.setContent { + NetKitTheme { + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column(Modifier.safeDrawingPadding().verticalScroll(rememberScrollState()).padding(Spacing.normal) + .semantics { testTagsAsResourceId = true }, verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(pinsIdentity, style = MaterialTheme.typography.labelSmall) + // Same selection as WifiScreen, recomputed from the pins state; the unpin button uses unpinAccessPoint. + val current = spectrumSelection(spectrum.traces, pinsState.value, WifiBand.GHZ_2_4, points) + SpectrumPanel(spectrum, "2,4 GHz", current.drawn, current.pinnedKeys, current.missingPins, + onUnpin = { bssid -> pinsState.value = unpinAccessPoint(pinsState.value, bssid) }) + AccessPointRow(weak6, null, showDivider = false, state = state, history = emptyList(), elapsedNow = 0, + onOwn = {}, onSelect = {}, pinned = true, onPin = {}) + RegionalRasterNote(raster, 14) + } + } + } + } + } + instrumentation.waitForIdleSync() + ui.await { it.text?.toString() == pinsIdentity } + val pinnedTag = context.getString(R.string.wifi_pinned_tag) + val missingLine = context.getString(R.string.wifi_pin_missing, "Půda AP") + val chart = ui.await { it.contentDescription?.contains(missingLine) == true } + val lines = chart.contentDescription.toString().lines() + val traceLines = lines.filter { line -> line.substringBefore(". ").toIntOrNull() != null } + check(traceLines.size == 6) { "six drawn traces: $traceLines" } + check(traceLines[0].contains("Moje síť") && traceLines[1].contains("Sklep AP") && traceLines[2].contains("Garáž AP")) { "order $traceLines" } + check(traceLines.count { it.contains(pinnedTag) } == 2 && traceLines[1].contains(pinnedTag) && traceLines[2].contains(pinnedTag)) + marker("WIFI:PIN:ORDER:UI_VERIFIED") + check(lines.last() == missingLine) + marker("WIFI:PIN:MISSING:UI_VERIFIED") + settle() + screenshot("wifi-pins.png") + // The row is clickable, so Compose merges its texts (and the "pinned" tag) into one node. + val rowTexts = withTimeout(8_000) { + var texts = emptyList() + while (pinnedTag !in texts) { + // Texts of the AP row's node tree (merged or not): the row holding "Sklep AP" must show the tag. + val row = ui.all().firstOrNull { node -> node.isClickable && treeTexts(node).any { it.contains("Sklep AP") } } + texts = row?.let(::treeTexts).orEmpty().flatMap { it.split(", ") } + if (pinnedTag !in texts) delay(100) + } + texts + } + marker("WIFI:PIN:ROW_TEXTS:" + rowTexts.take(4).joinToString("|")) + // Compose leaves off-screen nodes out of the tree: scroll the evidence column to reach them. + check(scrollTo(ui) { it.viewIdResourceName == "wifi_pin_toggle" }.isChecked) { "pin toggle of a pinned AP is checked" } + marker("WIFI:PIN:DETAIL:UI_VERIFIED") + scrollTo(ui) { it.text?.toString() == context.getString(R.string.wifi_region_raster, "CZ", context.getString(R.string.wifi_region_eu), 1, 13) } + scrollTo(ui) { it.text?.toString() == context.getString(R.string.wifi_region_outside, 14) } + marker("WIFI:REGION:NOTE:UI_VERIFIED") + settle() + screenshot("wifi-pins-detail.png") + // Codex revize kolo 1: a pin missing from the scan has no list row; its legend row unpins it. + repeat(8) { + ui.all().firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD) + delay(200) + } + ui.clickTag("wifi_pin_missing_unpin") + withTimeout(5_000) { while (pinsState.value.size != 2) delay(50) } + check(pinsState.value.none { it.ssid == "Půda AP" }) + withTimeout(5_000) { + while (ui.all().any { it.contentDescription?.contains(missingLine) == true || it.viewIdResourceName == "wifi_pin_missing" }) delay(100) + } + check(togglePinnedAccessPoint(pinsState.value, strong[0]).change == PinChange.PINNED) { "limit freed" } + marker("WIFI:PIN:MISSING_UNPIN:UI_VERIFIED") + + // --- AC-002 groups + AC-003 export through SAF -------------------------------------------- + val tricky = "Kavárna, \"U Lípy\"\nPatro 2" + val scan = listOf( + point("Home", 0x11, 2412, -61, current = true), point("Home", 0x12, 5180, -52), point("Home", 0x13, 5975, -70), + point("Office", 0x14, 5500, -58), point(tricky, 0x15, 2437, -66).copy(vendor = "Acme, Inc."), + point(null, 0x16, 2462, -75), point(null, 0x17, 2462, -77), + ) + val visible = sortedAccessPoints(scan, null, WifiSort.SIGNAL) + val entries = essListEntries(visible, WifiSort.SIGNAL) + val home = entries.filterIsInstance().single { it.ssid == "Home" } + check(home.apCount == 3 && home.bands.size == 3 && entries.filterIsInstance().size == 2) + val scanState = WifiAnalyzerState(accessPoints = scan, status = WifiScanStatus.READY) + val exportOpen = mutableStateOf(false) + var pickedUri: CompletableDeferred = CompletableDeferred() + var pickedFormat: WifiExportFormat? = null + val groupsIdentity = "SYNTHETIC UI · ESS groups" + instrumentation.runOnMainSync { + activity.setContent { + NetKitTheme { + val launch = rememberExportLauncher { pickedUri.complete(it) } + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + LazyColumn(Modifier.safeDrawingPadding().semantics { testTagsAsResourceId = true }, + contentPadding = PaddingValues(Spacing.normal)) { + item { Text(groupsIdentity, style = MaterialTheme.typography.labelSmall) } + networksCard(visible, emptyMap(), scanState, emptyList(), 0, WifiSort.SIGNAL, {}, "", {}, {}, { _, _ -> }, + {}, NetworkListOptions(grouped = true, entries = entries, expandedGroups = setOf(home.key), + onExport = { exportOpen.value = true }, exportEnabled = true)) + } + } + if (exportOpen.value) ExportDialog(context.getString(R.string.wifi_export_title), + context.getString(R.string.wifi_export_warning), context.getString(R.string.wifi_export_note), + onDismiss = { exportOpen.value = false }) { format -> + pickedFormat = format + check(launch(format, "netkit-wifi-scan-evidence")) + } + } + } + } + instrumentation.waitForIdleSync() + ui.await { it.text?.toString() == groupsIdentity } + val homeSubtitle = (listOf(context.getString(R.string.wifi_group_ap_count, 3)) + + listOf(R.string.wifi_band_24 to 1, R.string.wifi_band_5 to 36, R.string.wifi_band_6 to 5).map { (band, channel) -> + context.getString(band) + " " + context.getString(R.string.wifi_group_channels, channel.toString()) + }).joinToString(" · ") + ui.await { it.text?.toString() == homeSubtitle } + // Expanded Home: the group row and its three APs (top of the list, on screen). + check(ui.all().count { it.text?.toString() == "Home" } == 4) { "group row + 3 AP rows" } + settle() + screenshot("wifi-ess-groups.png") + // The lazy list composes only what is on screen: collect the rest while scrolling down. + val hiddenName = context.getString(R.string.wifi_hidden_network) + val groupTitles = mutableSetOf() + val hiddenBssids = mutableSetOf() + repeat(6) { + val nodes = ui.all() + nodes.filter { it.viewIdResourceName == "wifi_ess_group" }.forEach { group -> + fun texts(node: AccessibilityNodeInfo): List = listOfNotNull(node.text?.toString()) + + (0 until node.childCount).mapNotNull { node.getChild(it) }.flatMap(::texts) + texts(group).firstOrNull { it in setOf("Home", "Office", tricky) }?.let { groupTitles += it } + } + if (nodes.any { it.text?.toString() == hiddenName }) hiddenBssids += nodes.count { it.text?.toString() == hiddenName }.toString() + nodes.firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) + delay(400) + } + check(groupTitles == setOf("Home", "Office", tricky)) { "groups $groupTitles" } + check("2" in hiddenBssids) { "two hidden single rows, saw $hiddenBssids" } + marker("WIFI:ESS_GROUPS:UI_VERIFIED") + repeat(8) { + ui.all().firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD) + delay(250) + } + + for (format in WifiExportFormat.entries) try { + pickedUri = CompletableDeferred() + marker("WIFI:EXPORT:STEP:${format.name}:OPEN") + ui.clickTag("wifi_export_open") + ui.await { it.text?.toString() == context.getString(R.string.wifi_export_warning) } + // The dialog is its own window/composition: no test tags as resource ids there, click by text. + ui.clickText(context.getString(if (format == WifiExportFormat.CSV) R.string.lan_format_csv else R.string.lan_format_json)) + if (format == WifiExportFormat.CSV) { settle(); screenshot("wifi-export-dialog.png") } + marker("WIFI:EXPORT:STEP:${format.name}:CONFIRM") + ui.clickText(context.getString(R.string.wifi_export_confirm)) + saveInDocumentsUi(ui, marker) + marker("WIFI:EXPORT:STEP:${format.name}:SAVED_IN_PICKER") + val uri = withTimeout(20_000) { pickedUri.await() } ?: error("picker returned no document") + check(pickedFormat == format) + val now = System.currentTimeMillis() + val text = exportWifiScan(scan, format, now, android.os.SystemClock.elapsedRealtime(), null) + check(writeExportDocument(context, uri, text)) { "write failed" } + val read = context.contentResolver.openInputStream(uri)!!.use { it.readBytes().decodeToString() } + check(read == text) { "read-back differs" } + val name = context.contentResolver.query(uri, arrayOf(DocumentsContract.Document.COLUMN_DISPLAY_NAME), null, null, null) + ?.use { if (it.moveToFirst()) it.getString(0) else null } + check(name?.endsWith(".${format.extension}") == true) { "name $name" } + when (format) { + WifiExportFormat.CSV -> check(read.contains("\"Kavárna, \"\"U Lípy\"\"\nPatro 2\"") && read.contains("\"Acme, Inc.\"") && + read.lines().first().startsWith("time,ssid,bssid,vendor,band,channel,width_mhz,center_mhz")) + WifiExportFormat.JSON -> { + val rows = Json.parseToJsonElement(read).jsonObject.getValue("accessPoints").jsonArray + check(rows.size == scan.size && rows.any { it.jsonObject["ssid"]?.jsonPrimitive?.content == tricky }) + } + } + marker("WIFI:EXPORT:${format.name}:SAF_FILE_VERIFIED:bytes=${read.encodeToByteArray().size}:name=$name") + // Leave no synthetic file behind in the emulator's storage. + check(DocumentsContract.deleteDocument(context.contentResolver, uri)) { "cleanup" } + withTimeout(10_000) { while (ui.all().none { it.text?.toString() == groupsIdentity }) delay(100) } + } catch (error: Throwable) { + marker("WIFI:DIAG:NODES:" + ui.all().mapNotNull { node -> + listOfNotNull(node.packageName?.toString()?.substringAfterLast('.'), node.viewIdResourceName, node.text?.toString()?.take(20), + node.contentDescription?.toString()?.take(20), if (node.isEnabled) null else "disabled").joinToString("/").ifEmpty { null } + }.joinToString("|").take(1500)) + screenshot("wifi-export-failure.png") + throw error + } + + // --- AC-004 walk card ------------------------------------------------------------------------ + val recorder = WalkRecorder() + val roaming = RoamingDetector() + val start = 1_000_000L + recorder.start(start, System.currentTimeMillis()) + for (second in 0 until 30) { + val t = start + second * 1_000L + val lost = second in 12..13 + recorder.observeGateway(t, if (lost) null else 3.0, lost) + val bssid = if (second < 15) "02:00:00:00:38:21" else "02:00:00:00:38:22" + recorder.sample(t, -48 - second, bssid, if (second < 15) 1 else 36, 300, 280, roaming.observe(t, bssid, if (second < 15) 2412 else 5180)) + } + val now = start + 30_000L + val walkState: MutableState = mutableStateOf(WalkUiState(WalkStatus.RECORDING, start, recorder.summary(now))) + val walkIdentity = "SYNTHETIC UI · walk log" + instrumentation.runOnMainSync { + activity.setContent { + NetKitTheme { + val walk by walkState + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column(Modifier.safeDrawingPadding().verticalScroll(rememberScrollState()).padding(Spacing.normal) + .semantics { testTagsAsResourceId = true }, verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(walkIdentity, style = MaterialTheme.typography.labelSmall) + WalkCard(walk, onStart = {}, onStop = {}, onMark = { recorder.mark(now, it) }, onExport = {}, onDiscard = {}) + } + } + } + } + } + instrumentation.waitForIdleSync() + ui.await { it.text?.toString() == walkIdentity } + ui.await { it.text?.toString() == context.resources.getQuantityString(R.plurals.walk_recording, 30, "0:30", 30) } + ui.clickTag("walk_mark") + val editable = ui.await { it.isEditable } + check(editable.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, Bundle().apply { + putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, "Chodba 2. patro, sever") + })) + delay(300) + settle() + screenshot("walk-mark-dialog.png") + ui.clickText(context.getString(R.string.walk_mark_add)) + ui.await { it.text?.toString() == context.getString(R.string.walk_mark_added) } + check(recorder.snapshot(now).events.any { it.kind == WalkEventKind.MARK && it.detail == "Chodba 2. patro, sever" }) + marker("WIFI:WALK:MARK:UI_VERIFIED") + settle() + screenshot("walk-recording.png") + recorder.stop(now, WalkStopReason.USER) + val summary = recorder.summary(now)!! + check(summary.roamings == 1 && summary.gatewayLost == 2 && summary.gatewaySent == 30 && summary.marks == 1 && summary.minRssiDbm == -77) + instrumentation.runOnMainSync { walkState.value = WalkUiState(WalkStatus.STOPPED, start, summary) } + ui.await { it.text?.toString() == context.getString(R.string.walk_stopped_user) } + scrollTo(ui) { it.text?.toString() == context.getString(R.string.walk_summary_ping_loss_value, 2, 30) } + scrollTo(ui) { it.viewIdResourceName == "walk_export" } + scrollTo(ui) { it.text?.toString() == context.getString(R.string.walk_precision) } + marker("WIFI:WALK:SUMMARY:UI_VERIFIED") + settle() + screenshot("walk-summary.png") +} + +/** Finds a node, scrolling the first scrollable container forward (up to 12 pages) until it appears. */ +private suspend fun scrollTo(ui: SshEvidenceUi, predicate: (AccessibilityNodeInfo) -> Boolean): AccessibilityNodeInfo { + repeat(12) { + ui.all().firstOrNull(predicate)?.let { return it } + ui.all().firstOrNull { it.isScrollable }?.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD) + delay(300) + } + return ui.await(predicate) +} + +private fun treeTexts(node: AccessibilityNodeInfo): List = listOfNotNull(node.text?.toString(), + node.contentDescription?.toString()) + (0 until node.childCount).mapNotNull { node.getChild(it) }.flatMap(::treeTexts) + +/** + * Drives the system DocumentsUI "create document" screen: presses Save (switching to Downloads + * when the opened root does not accept new documents). Only the emulator's own storage is used. + */ +private suspend fun saveInDocumentsUi(ui: SshEvidenceUi, marker: (String) -> Unit) { + fun isSave(node: AccessibilityNodeInfo) = node.text?.toString()?.equals("save", ignoreCase = true) == true || + node.viewIdResourceName?.endsWith(":id/button1") == true && node.packageName?.contains("documentsui") == true + val save = withTimeout(20_000) { + var found: AccessibilityNodeInfo? = null + while (found == null) { + found = ui.all().firstOrNull { isSave(it) && it.packageName?.contains("documentsui") == true } + if (found == null) delay(200) + } + found + } + if (!save.isEnabled) { + marker("WIFI:EXPORT:PICKER:SWITCH_TO_DOWNLOADS") + ui.all().firstOrNull { it.contentDescription?.toString().equals("Show roots", ignoreCase = true) }?.let { ui.click(it) } + delay(500) + ui.all().firstOrNull { it.text?.toString() == "Downloads" }?.let { ui.click(it) } + delay(800) + } + val enabled = withTimeout(10_000) { + var found: AccessibilityNodeInfo? = null + while (found == null) { + found = ui.all().firstOrNull { isSave(it) && it.isEnabled && it.packageName?.contains("documentsui") == true } + if (found == null) delay(200) + } + found + } + ui.click(enabled) +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiSpectrumEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiSpectrumEvidence.kt new file mode 100644 index 0000000..eab2524 --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiSpectrumEvidence.kt @@ -0,0 +1,202 @@ +package cz.netkit.app.test + +import android.app.Instrumentation +import android.graphics.Rect +import android.view.accessibility.AccessibilityNodeInfo +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.Density +import androidx.compose.ui.unit.dp +import cz.netkit.app.R +import cz.netkit.app.ui.SectionCard +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.wifi.AccessPointRow +import cz.netkit.app.wifi.SpectrumLegendItem +import cz.netkit.app.wifi.SpectrumPanel +import cz.netkit.app.wifi.spectrumDrawnTraces +import cz.netkit.shared.wifi.* +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeout + +/** + * Zadání 34 (AC-004), UI only: the production 2.4 GHz spectrum card over synthetic APs on + * channel 1 and 13 (20 MHz), 13 (40 MHz without centre, HT40− from the raster) and 6 (40 MHz + * without centre, ambiguous → "centre unknown"), plus the expanded detail of the last one. + * Synthetic, locally administered BSSIDs; not an RF scan. + */ +suspend fun captureWifiSpectrumEvidence( + instrumentation: Instrumentation, + activity: ComponentActivity, + screenshot: (String) -> Unit, + marker: (String) -> Unit, +) { + fun point(ssid: String, id: Int, frequency: Int, width: Int, rssi: Int, selected: Boolean = false) = AccessPoint(ssid, + "02:00:00:00:34:0$id", rssi, frequency, centerFrequencyMhz = null, channel = channelForFrequency(frequency), + band = WifiBand.GHZ_2_4, widthMhz = width, security = WifiSecurity.WPA2, standard = "n", ageMs = 0, + locallyAdministered = true, isSelected = selected) + val ch1 = point("Ch1 20 MHz", 1, 2412, 20, -48) + val ch13 = point("Ch13 20 MHz", 2, 2472, 20, -58) + val ch13Bonded = point("Ch13 40 MHz", 3, 2472, 40, -66) + val ch6Bonded = point("Ch6 40 MHz", 4, 2437, 40, -74, selected = true) + val points = listOf(ch1, ch13, ch13Bonded, ch6Bonded) + val spectrum = bandSpectrum(points, WifiBand.GHZ_2_4)!! + val axis = spectrum.axis + + // Model behind the picture: axis 1–14 with margin, shaded range above 2483.5 MHz, both skirts inside. + check(axis.minMhz == 2397.0 && axis.maxMhz == 2499.0) { "2.4 GHz axis range" } + check(axis.ticks.first().let { it.channel == 1 && it.labelled } && axis.ticks.last().let { it.channel == 14 && it.labelled && it.outOfBand }) + check(axis.outOfBand == listOf(SpectrumGap(2483.5, 2499.0))) + for (trace in spectrum.traces) for (shape in trace.shapes) + check(axis.fraction(shape.lowerMhz) > 0.0 && axis.fraction(shape.upperMhz) < 1.0) { "${trace.key} skirt on the edge" } + val bonded13 = spectrum.traces.single { it.accessPoint === ch13Bonded } + check(bonded13.centerSource == BondingCenterSource.RASTER && bonded13.shapes.single().let { it.lowerMhz == 2442.0 && it.upperMhz == 2482.0 }) + val bonded6 = spectrum.traces.single { it.accessPoint === ch6Bonded } + check(bonded6.centerUnknown && bonded6.shapes.single().let { it.lowerMhz == 2427.0 && it.upperMhz == 2447.0 }) + + val context = instrumentation.targetContext + val identity = "SYNTHETIC UI · spectrum 2.4 GHz axis" + val state = WifiAnalyzerState(accessPoints = points, status = WifiScanStatus.READY) + instrumentation.runOnMainSync { + activity.setContent { + NetKitTheme { + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column(Modifier.safeDrawingPadding().verticalScroll(rememberScrollState()).padding(Spacing.normal), + verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(identity, style = MaterialTheme.typography.labelSmall) + SpectrumPanel(spectrum, "2,4 GHz", spectrumDrawnTraces(spectrum.traces)) + AccessPointRow(ch6Bonded, null, showDivider = false, state = state, history = emptyList(), + elapsedNow = 0, onOwn = {}, onSelect = {}) + } + } + } + } + } + instrumentation.waitForIdleSync() + awaitSpectrumNode(instrumentation) { it.text?.toString() == identity } + // Chart description: channel 14 sentence and the centre-unknown width of the channel 6 trace. + val outOfBand = context.getString(R.string.wifi_spectrum_channel14_out_of_band) + val unknownWidth = context.getString(R.string.wifi_width_center_unknown, 40) + val chart = awaitSpectrumNode(instrumentation) { it.contentDescription?.contains(outOfBand) == true } + check(chart.contentDescription.toString().lines().count { unknownWidth in it } == 1) { "exactly one trace has an unknown centre" } + marker("WIFI:SPECTRUM:AXIS24:UI_VERIFIED") + // AP detail note. + awaitSpectrumNode(instrumentation) { it.text?.toString() == context.getString(R.string.wifi_width_center_unknown_detail, 40) } + marker("WIFI:SPECTRUM:CENTER_UNKNOWN:UI_VERIFIED") + // The accessibility tree can be ahead of the composited frame (swiftshader): on warm runs the + // screenshot otherwise caught the production screen MainActivity drew first. + delay(1_500) + instrumentation.waitForIdleSync() + instrumentation.uiAutomation.waitForIdle(500, 5_000) + screenshot("wifi-spectrum-axis24.png") + + // Codex review P2: a 32-character SSID at font scale 1.3 must not squeeze the note to zero width. + // The production legend clears its semantics (the chart description carries it), so the same + // SpectrumLegendItem is also shown in a card without that, where its text nodes can be measured. + val longSsid = "W".repeat(32) + val long = point(longSsid, 5, 2437, 40, -60) + val longSpectrum = bandSpectrum(listOf(ch1, long), WifiBand.GHZ_2_4)!! + val longTraces = spectrumDrawnTraces(longSpectrum.traces) + check(longTraces.single { it.accessPoint === long }.centerUnknown) + val longIdentity = "SYNTHETIC UI · legend 32-char SSID, font 1.3" + val hidden = context.getString(R.string.wifi_hidden_network) + instrumentation.runOnMainSync { + activity.setContent { + val density = LocalDensity.current + CompositionLocalProvider(LocalDensity provides Density(density.density, 1.3f)) { + NetKitTheme { + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Column(Modifier.safeDrawingPadding().verticalScroll(rememberScrollState()).padding(Spacing.normal), + verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(longIdentity, style = MaterialTheme.typography.labelSmall) + SectionCard("legend") { + longTraces.forEachIndexed { index, trace -> + SpectrumLegendItem(index, trace, Color.Blue, hidden) + } + } + SpectrumPanel(longSpectrum, "2,4 GHz", longTraces) + } + } + } + } + } + } + instrumentation.waitForIdleSync() + awaitSpectrumNode(instrumentation) { it.text?.toString() == longIdentity } + val ssidBounds = Rect().also(awaitSpectrumNode(instrumentation) { it.text?.toString() == longSsid }::getBoundsInScreen) + val noteBounds = Rect().also(awaitSpectrumNode(instrumentation) { it.text?.toString() == unknownWidth }::getBoundsInScreen) + val screen = Rect().also { instrumentation.uiAutomation.rootInActiveWindow!!.getBoundsInScreen(it) } + check(noteBounds.width() > 0 && noteBounds.height() > 0) { "note has no size: $noteBounds" } + check(noteBounds.top >= ssidBounds.bottom - 1 && noteBounds.left == ssidBounds.left) { "note is not under the SSID: $ssidBounds / $noteBounds" } + check(ssidBounds.right <= screen.right && noteBounds.right <= screen.right) { "legend runs off screen: $ssidBounds / $noteBounds" } + marker("WIFI:SPECTRUM:LEGEND_LONG_SSID_FONT_1_3:UI_VERIFIED") + delay(1_500) + instrumentation.waitForIdleSync() + instrumentation.uiAutomation.waitForIdle(500, 5_000) + screenshot("wifi-spectrum-legend-long-ssid.png") + + // Reproduce the compact AP list separately from the chart legend, with both status badges. + val connected = ch1.copy(ssid = "AndroidWifi", isCurrent = true) + instrumentation.runOnMainSync { + activity.setContent { + val density = LocalDensity.current + CompositionLocalProvider(LocalDensity provides Density(density.density, 1.3f)) { + NetKitTheme { + Surface(Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { + Box(Modifier.safeDrawingPadding()) { + Column(Modifier.width(248.dp)) { + AccessPointRow(connected, null, false, state, emptyList(), 0, {}, {}, pinned = true) + } + } + } + } + } + } + } + instrumentation.waitForIdleSync() + suspend fun bounds(text: String) = Rect().also(awaitSpectrumNode(instrumentation) { it.text?.toString() == text }::getBoundsInScreen) + val nameBounds = bounds("AndroidWifi") + val connectedBounds = bounds(context.getString(R.string.wifi_spectrum_connected)) + val pinBounds = bounds(context.getString(R.string.wifi_pinned_tag)) + val rssiBounds = bounds(connected.rssiDbm.toString()) + val density = activity.resources.displayMetrics.density + check(nameBounds.width() > 70 * density && nameBounds.height() in 1..(32 * density).toInt()) { + "Expected a readable single-line SSID at font scale 1.3: $nameBounds" + } + check(listOf(connectedBounds, pinBounds, rssiBounds).all { it.top >= nameBounds.bottom - 1 }) { + "Status and RSSI must flow below the SSID in the narrow row" + } + screenshot("wifi-spectrum-connected-pinned-font13.png") +} + +private suspend fun awaitSpectrumNode(instrumentation: Instrumentation, predicate: (AccessibilityNodeInfo) -> Boolean): AccessibilityNodeInfo = + withTimeout(5_000) { + var found = findSpectrumNode(instrumentation, predicate) + while (found == null) { delay(50); found = findSpectrumNode(instrumentation, predicate) } + found + } + +private fun findSpectrumNode(instrumentation: Instrumentation, predicate: (AccessibilityNodeInfo) -> Boolean): AccessibilityNodeInfo? { + fun find(node: AccessibilityNodeInfo): AccessibilityNodeInfo? { + if (node.isVisibleToUser && predicate(node)) return node + for (index in 0 until node.childCount) node.getChild(index)?.let(::find)?.let { return it } + return null + } + return instrumentation.uiAutomation.rootInActiveWindow?.let(::find) +} diff --git a/androidApp/src/androidTest/kotlin/cz/netkit/app/test/WolWidgetIntentEvidence.kt b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/WolWidgetIntentEvidence.kt new file mode 100644 index 0000000..04da4dc --- /dev/null +++ b/androidApp/src/androidTest/kotlin/cz/netkit/app/test/WolWidgetIntentEvidence.kt @@ -0,0 +1,130 @@ +package cz.netkit.app.test + +import android.app.Instrumentation +import android.view.View +import android.view.ViewGroup +import android.widget.FrameLayout +import android.widget.RemoteViews +import android.widget.TextView +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import androidx.datastore.preferences.core.Preferences +import androidx.glance.appwidget.compose +import androidx.glance.appwidget.state.getAppWidgetState +import cz.netkit.app.R +import cz.netkit.app.wol.widget.WolWidget +import android.appwidget.AppWidgetManager +import android.content.ComponentName +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import cz.netkit.app.wol.widget.WolWidgetReceiver +import cz.netkit.app.wol.widget.WolWidgets +import cz.netkit.app.wol.widget.transactWolWidget +import cz.netkit.shared.wol.TargetMode +import cz.netkit.shared.wol.WolDevice +import cz.netkit.shared.wol.WolWidgetStatus +import androidx.glance.appwidget.GlanceAppWidgetManager +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.Inet4Address +import java.net.InetAddress +import java.net.SocketTimeoutException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext + +/** + * Revize kolo 3–4 (zadání 36): the widget is rendered by Glance (RemoteViews with the real PendingIntents) + * for device A and held; after the widget was redrawn for device B, tapping "Wake" in the held drawing + * must send nothing, while the current drawing for B sends B's series. + * Precondition: one WoL widget placed on the emulator home screen (any state). Devices use synthetic + * locally administered MACs and target the emulator's own Wi-Fi address, where this test listens. + * The app's stores are the isolated M1 test stores, so the user's widget state is not touched + * (the home-screen widget is only redrawn from them). + */ +suspend fun wolWidgetIntentEvidence(test: Instrumentation, app: M1TestApplication, marker: (String) -> Unit) { + val manager = AppWidgetManager.getInstance(app) + val appWidgetId = manager.getAppWidgetIds(ComponentName(app, WolWidgetReceiver::class.java)).firstOrNull() + ?: error("No WoL widget placed on the home screen") + marker("WOL_WIDGET:PLACED_WIDGET:PASS") + val connectivity = app.getSystemService(ConnectivityManager::class.java) + val wifi = connectivity.allNetworks.firstOrNull { connectivity.getNetworkCapabilities(it)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true } + ?: error("No Wi-Fi network") + val own = connectivity.getLinkProperties(wifi)?.linkAddresses?.map { it.address }?.firstOrNull { it is Inet4Address } + ?: error("No IPv4 on Wi-Fi") + DatagramSocket(0, InetAddress.getByName("0.0.0.0")).use { socketA -> + DatagramSocket(0, InetAddress.getByName("0.0.0.0")).use { socketB -> + val a = WolDevice("intent-a", "Intent A", "02:00:5E:36:00:0A", TargetMode.CUSTOM, own.hostAddress, socketA.localPort, + createdAt = 1, updatedAt = 1, repeatCount = 3, repeatIntervalMs = 100) + val b = WolDevice("intent-b", "Intent B", "02:00:5E:36:00:0B", TargetMode.CUSTOM, own.hostAddress, socketB.localPort, + createdAt = 2, updatedAt = 2, repeatCount = 3, repeatIntervalMs = 100) + app.devices.save(listOf(a, b)) + val glanceId = GlanceAppWidgetManager(app).getGlanceIdBy(appWidgetId) + WolWidgets.configure(app, appWidgetId, a) + // The real Glance rendering of the widget for A (RemoteViews with its PendingIntents), held. + val drawnA = render(app, glanceId) + WolWidgets.configure(app, appWidgetId, b) + val stateB = transactWolWidget(app, glanceId) { it } + check(stateB.deviceId == "intent-b") + val drawnB = render(app, glanceId) + // Tapping "Wake" on the old drawing for A after the widget was redrawn for B must not wake anything. + clickWake(test, app, drawnA) + val staleA = receive(socketA, 4_000); val staleB = receive(socketB, 100) + val afterStale = transactWolWidget(app, glanceId) { it } + check(staleA.isEmpty() && staleB.isEmpty()) { "stale intent sent ${staleA.size}+${staleB.size} packets" } + check(afterStale == stateB) { "stale intent changed the widget state" } + marker("WOL_WIDGET:STALE_INTENT_REFUSED:PASS") + // Positive control: the current drawing for B wakes B (and only B) over the same path. + clickWake(test, app, drawnB) + val currentB = receive(socketB, 6_000, expected = 3); val currentA = receive(socketA, 100) + check(currentB.size == 3 && currentA.isEmpty()) { "current intent: B=${currentB.size} A=${currentA.size}" } + check(currentB.all { it.copyOfRange(6, 12).contentEquals(byteArrayOf(2, 0, 0x5E, 0x36, 0, 0x0B)) }) { "wrong MAC" } + var final = afterStale + repeat(30) { if (final.status != WolWidgetStatus.SENT) { delay(100); final = transactWolWidget(app, glanceId) { it } } } + check(final.status == WolWidgetStatus.SENT && final.deviceId == "intent-b") { "state ${final.status}" } + marker("WOL_WIDGET:CURRENT_INTENT_SENT:PASS") + } + } +} + +/** What the launcher would show: Glance composes the widget's RemoteViews from its current state. */ +private suspend fun render(app: M1TestApplication, glanceId: androidx.glance.GlanceId): RemoteViews { + val widget = WolWidget() + return widget.compose(app, glanceId, size = DpSize(300.dp, 80.dp), state = widget.getAppWidgetState(app, glanceId)) +} + +/** Inflates [views] like a host and clicks the "Wake" button, which sends its PendingIntent. */ +private fun clickWake(test: Instrumentation, app: M1TestApplication, views: RemoteViews) { + val label = app.getString(R.string.wol_widget_wake) + var clicked = false + test.runOnMainSync { + val parent = FrameLayout(app) + val root = views.apply(app, parent) + parent.addView(root) + fun find(view: View): View? = when { + view is TextView && view.text?.toString() == label -> view + view is ViewGroup -> (0 until view.childCount).firstNotNullOfOrNull { find(view.getChildAt(it)) } + else -> null + } + var target: View? = find(root) + while (target != null && !target.hasOnClickListeners()) target = target.parent as? View + clicked = target?.performClick() == true + } + check(clicked) { "Wake button not found or not clickable in the rendered widget" } +} + +private suspend fun receive(socket: DatagramSocket, windowMillis: Long, expected: Int = Int.MAX_VALUE): List = + withContext(Dispatchers.IO) { + val packets = mutableListOf() + val end = System.currentTimeMillis() + windowMillis + while (packets.size < expected) { + val left = end - System.currentTimeMillis() + if (left <= 0) break + socket.soTimeout = left.toInt().coerceAtLeast(1) + val buffer = ByteArray(256) + val packet = DatagramPacket(buffer, buffer.size) + try { socket.receive(packet) } catch (_: SocketTimeoutException) { break } + packets += buffer.copyOf(packet.length) + } + packets + } diff --git a/androidApp/src/dev/res/xml/shortcuts.xml b/androidApp/src/dev/res/xml/shortcuts.xml new file mode 100644 index 0000000..3e34c99 --- /dev/null +++ b/androidApp/src/dev/res/xml/shortcuts.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/androidApp/src/main/AndroidManifest.xml b/androidApp/src/main/AndroidManifest.xml index fd250c8..fbeeac6 100644 --- a/androidApp/src/main/AndroidManifest.xml +++ b/androidApp/src/main/AndroidManifest.xml @@ -7,33 +7,119 @@ + + + + + + + + + + + + + + android:usesCleartextTraffic="false" + tools:targetApi="tiramisu"> - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/androidApp/src/main/assets/licenses/NOTICE.txt b/androidApp/src/main/assets/licenses/NOTICE.txt index da945a1..36951c1 100644 --- a/androidApp/src/main/assets/licenses/NOTICE.txt +++ b/androidApp/src/main/assets/licenses/NOTICE.txt @@ -21,8 +21,11 @@ Public Suffix List (přibalený v okhttp-android, neupravený) — MPL-2.0, zdrojová podoba https://publicsuffix.org/list/; text licence v aplikaci (O aplikaci → Licence open source) a androidApp/src/main/assets/licenses/MPL-2.0.txt. AndroidX (Compose, Material, Activity, Lifecycle, DataStore, Startup, -ProfileInstaller, Annotation, Collection, Core, Arch, SavedState a další -moduly uvedené v inventáři) — Apache-2.0, Android Open Source Project. +ProfileInstaller, Glance, WorkManager, Room, SQLite, Annotation, Collection, +Core, Arch, SavedState a další moduly uvedené v inventáři) — Apache-2.0, +Android Open Source Project. +Protocol Buffers lite (přebalený v androidx.glance a androidx.datastore) — BSD-3-Clause, +Copyright 2008 Google Inc.; úplný text: docs/licenses/protobuf-LICENSE.txt. Kotlin, kotlinx.coroutines, kotlinx.serialization, JetBrains annotations — Apache-2.0, JetBrains a přispěvatelé. Guava listenablefuture — Apache-2.0, Google a přispěvatelé. @@ -53,3 +56,19 @@ docs/public-license-verification.tsv a docs/zavislosti.md. Cloudflare, Team Cymru, LibreSpeed servery a M-Lab jsou externí služby. Kód LibreSpeed ani GPL kód aplikace ConnectBot se do NetKitu nepřebírá. + +usb-serial-for-android 3.12.0 (MIT), commit 4cb9e82cdcfa095eb2fe0b0bea9605f50bd8e2f2 +https://github.com/mik3y/usb-serial-for-android/tree/3.12.0 +Copyright (c) 2011-2013 Google Inc. and (c) 2013 Mike Wakerly. +Individual driver attribution is retained in the source files. The Ch34x and +Prolific drivers import the app's generated BuildConfig in this distribution. +HexDump.java is Copyright (C) 2006 The Android Open Source Project, Apache-2.0. + +Unicode Character Database 18.0.0 (EastAsianWidth.txt, extracted/DerivedGeneralCategory.txt), +staženo 2026-12-02 z https://www.unicode.org/Public/UCD/latest/ucd/ — Unicode License V3 +(SPDX Unicode-3.0, schválená OSI). Copyright © 1991-2026 Unicode, Inc. +Z dat je odvozena jen tabulka šířek znaků terminálu +(shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt) pro Android i iOS. +Výjimka z projektového pravidla Apache/MIT/BSD platí jen pro tato data (D32). +Úplný text licence: androidApp/src/main/assets/licenses/unicode-LICENSE.txt; v aplikaci +O aplikaci → Licence open source (Android) a v seznamu licencí open source (iOS). diff --git a/androidApp/src/main/assets/licenses/components.json b/androidApp/src/main/assets/licenses/components.json index f62e9bb..5ddaaf8 100644 --- a/androidApp/src/main/assets/licenses/components.json +++ b/androidApp/src/main/assets/licenses/components.json @@ -49,6 +49,26 @@ "catalog": ["datastore-core"], "artifacts": ["androidx.datastore:*"] }, + { + "id": "androidx-biometric", + "name": "AndroidX Biometric", + "version": "1.1.0", + "license": "Apache-2.0", + "copyright": "Copyright The Android Open Source Project", + "texts": ["Apache-2.0.txt"], + "catalog": ["biometric"], + "artifacts": ["androidx.biometric:*"] + }, + { + "id": "androidx-fragment", + "name": "AndroidX Fragment", + "version": "1.8.9", + "license": "Apache-2.0", + "copyright": "Copyright The Android Open Source Project", + "texts": ["Apache-2.0.txt"], + "catalog": ["fragment"], + "artifacts": ["androidx.fragment:*"] + }, { "id": "androidx-profileinstaller", "name": "AndroidX ProfileInstaller", @@ -59,10 +79,30 @@ "catalog": ["profileinstaller"], "artifacts": ["androidx.profileinstaller:*"] }, + { + "id": "androidx-glance", + "name": "AndroidX Glance (App Widget, Material 3)", + "version": "1.2.0", + "license": "Apache-2.0", + "copyright": "Copyright The Android Open Source Project", + "texts": ["Apache-2.0.txt"], + "catalog": ["glance-appwidget", "glance-material3"], + "artifacts": ["androidx.glance:glance", "androidx.glance:glance-appwidget", "androidx.glance:glance-appwidget-proto", "androidx.glance:glance-material3"] + }, + { + "id": "androidx-work", + "name": "AndroidX WorkManager", + "version": "2.12.0", + "license": "Apache-2.0", + "copyright": "Copyright The Android Open Source Project", + "texts": ["Apache-2.0.txt"], + "catalog": ["work-runtime-ktx"], + "artifacts": ["androidx.work:*"] + }, { "id": "androidx", "name": "AndroidX", - "version": "Core 1.15.0, Annotation 1.9.1, Collection 1.5.0, SavedState 1.3.1, Startup 1.2.0, Emoji2 1.4.0, Arch Core 2.2.0, Tracing 1.2.0, Graphics Path 1.0.1, Autofill, Concurrent, CustomView, Interpolator, VersionedParcelable", + "version": "Core 1.15.0, Annotation 1.9.1, Collection 1.5.0, SavedState 1.3.1, Startup 1.2.0, Emoji2 1.4.0, Arch Core 2.2.0, Tracing 1.2.0, Room 2.7.0, SQLite 2.5.0, Core RemoteViews 1.1.0, Graphics Path 1.0.1, Autofill, Concurrent, CustomView, Interpolator, VersionedParcelable", "license": "Apache-2.0", "copyright": "Copyright The Android Open Source Project", "texts": ["Apache-2.0.txt"], @@ -133,6 +173,15 @@ "texts": ["Apache-2.0.txt"], "artifacts": ["com.squareup.okio:*"] }, + { + "id": "protobuf-lite", + "name": "Protocol Buffers lite (repackaged in Glance and DataStore)", + "version": "Glance 1.2.0, DataStore 1.1.7", + "license": "BSD-3-Clause", + "copyright": "Copyright 2008 Google Inc.", + "texts": ["protobuf-LICENSE.txt"], + "artifacts": ["androidx.glance:glance-appwidget-external-protobuf", "androidx.datastore:datastore-preferences-external-protobuf"] + }, { "id": "guava-listenablefuture", "name": "Guava ListenableFuture", @@ -195,6 +244,22 @@ "copyright": "IEEE Registration Authority, https://standards-oui.ieee.org/. Statement attributed to IEEE (quoted by Debian ieee-data): IEEE does not assert any copyright in the OUI Public Listing or attempt to restrict distribution of the listing in any way.", "texts": ["ieee-oui-NOTICE.txt"] }, + { + "id": "usb-serial-for-android", + "name": "usb-serial-for-android", + "version": "3.12.0 (4cb9e82cdcfa095eb2fe0b0bea9605f50bd8e2f2)", + "license": "MIT, Apache-2.0 (HexDump)", + "copyright": "Copyright (c) 2011-2013 Google Inc., 2013 Mike Wakerly and individual driver authors. HexDump © 2006 The Android Open Source Project.", + "texts": ["usb-serial-for-android-LICENSE.txt", "Apache-2.0.txt"] + }, + { + "id": "unicode-data", + "name": "Unicode Character Database", + "version": "18.0.0 (EastAsianWidth, DerivedGeneralCategory; terminal cell widths only), downloaded 2026-12-02", + "license": "Unicode-3.0", + "copyright": "Copyright © 1991-2026 Unicode, Inc.", + "texts": ["unicode-LICENSE.txt"] + }, { "id": "manrope", "name": "Manrope (font)", diff --git a/androidApp/src/main/assets/licenses/protobuf-LICENSE.txt b/androidApp/src/main/assets/licenses/protobuf-LICENSE.txt new file mode 100644 index 0000000..19b305b --- /dev/null +++ b/androidApp/src/main/assets/licenses/protobuf-LICENSE.txt @@ -0,0 +1,32 @@ +Copyright 2008 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. diff --git a/androidApp/src/main/assets/licenses/unicode-LICENSE.txt b/androidApp/src/main/assets/licenses/unicode-LICENSE.txt new file mode 100644 index 0000000..193d1c0 --- /dev/null +++ b/androidApp/src/main/assets/licenses/unicode-LICENSE.txt @@ -0,0 +1,45 @@ +Unicode Character Database (UCD) 18.0.0 + +NetKit derives the terminal cell width table (shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt) +from EastAsianWidth.txt and extracted/DerivedGeneralCategory.txt, downloaded on 2026-12-02 from +https://www.unicode.org/Public/UCD/latest/ucd/. License text from https://www.unicode.org/license.txt: + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2026 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. diff --git a/androidApp/src/main/assets/licenses/usb-serial-for-android-LICENSE.txt b/androidApp/src/main/assets/licenses/usb-serial-for-android-LICENSE.txt new file mode 100644 index 0000000..98e65da --- /dev/null +++ b/androidApp/src/main/assets/licenses/usb-serial-for-android-LICENSE.txt @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2011-2013 Google Inc. +Copyright (c) 2013 Mike Wakerly + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/driver/CdcAcmSerialDriver.java b/androidApp/src/main/java/com/hoho/android/usbserial/driver/CdcAcmSerialDriver.java new file mode 100644 index 0000000..02ae7a5 --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/driver/CdcAcmSerialDriver.java @@ -0,0 +1,451 @@ +/* Copyright 2011-2013 Google Inc. + * Copyright 2013 mike wakerly + * + * Project home page: https://github.com/mik3y/usb-serial-for-android + */ + +package com.hoho.android.usbserial.driver; + +import android.hardware.usb.UsbConstants; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbEndpoint; +import android.hardware.usb.UsbInterface; +import android.util.Log; + +import com.hoho.android.usbserial.util.HexDump; +import com.hoho.android.usbserial.util.MonotonicClock; +import com.hoho.android.usbserial.util.UsbUtils; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * USB CDC/ACM serial driver implementation. + * + * @author mike wakerly (opensource@hoho.com) + * @see Universal + * Serial Bus Class Definitions for Communication Devices, v1.1 + */ +public class CdcAcmSerialDriver implements UsbSerialDriver { + + public static final int USB_SUBCLASS_ACM = 2; + + private final String TAG = CdcAcmSerialDriver.class.getSimpleName(); + + private final UsbDevice mDevice; + private final List mPorts; + + public CdcAcmSerialDriver(UsbDevice device) { + mDevice = device; + mPorts = new ArrayList<>(); + int ports = countPorts(device); + for (int port = 0; port < ports; port++) { + mPorts.add(new CdcAcmSerialPort(mDevice, port)); + } + if (mPorts.size() == 0) { + mPorts.add(new CdcAcmSerialPort(mDevice, -1)); + } + } + + @SuppressWarnings({"unused"}) + public static boolean probe(UsbDevice device) { + return countPorts(device) > 0; + } + + private static int countPorts(UsbDevice device) { + int controlInterfaceCount = 0; + int dataInterfaceCount = 0; + for (int i = 0; i < device.getInterfaceCount(); i++) { + if (device.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_COMM && + device.getInterface(i).getInterfaceSubclass() == USB_SUBCLASS_ACM) + controlInterfaceCount++; + if (device.getInterface(i).getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) + dataInterfaceCount++; + } + return Math.min(controlInterfaceCount, dataInterfaceCount); + } + + @Override + public UsbDevice getDevice() { + return mDevice; + } + + @Override + public List getPorts() { + return mPorts; + } + + public class CdcAcmSerialPort extends CommonUsbSerialPort { + + private UsbInterface mControlInterface; + private UsbInterface mDataInterface; + + private UsbEndpoint mControlEndpoint; + + private int mControlIndex; + + private boolean mRts = false; + private boolean mDtr = false; + + private static final int USB_RECIP_INTERFACE = 0x01; + private static final int USB_RT_ACM = UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE; + + private static final int SET_LINE_CODING = 0x20; // USB CDC 1.1 section 6.2 + private static final int GET_LINE_CODING = 0x21; + private static final int SET_CONTROL_LINE_STATE = 0x22; + private static final int SEND_BREAK = 0x23; + + private static final int NOTIFICATION_REQUEST_TYPE = 0xA1; + private static final int SERIAL_STATE = 0x20; + private static final int SERIAL_STATE_PACKET_SIZE = 10; + private static final int SERIAL_STATE_FLAG_CD = 0x01; + private static final int SERIAL_STATE_FLAG_DSR = 0x02; + private static final int SERIAL_STATE_FLAG_RI = 0x08; + + private volatile int mSerialState = 0; + private volatile Thread mReadControlLinesThread = null; + private final Object mReadControlLinesThreadLock = new Object(); + private boolean mStopReadControlLinesThread = false; + private Exception mReadControlLinesException = null; + + public CdcAcmSerialPort(UsbDevice device, int portNumber) { + super(device, portNumber); + } + + @Override + public UsbSerialDriver getDriver() { + return CdcAcmSerialDriver.this; + } + + @Override + protected void openInt() throws IOException { + Log.d(TAG, "interfaces:"); + for (int i = 0; i < mDevice.getInterfaceCount(); i++) { + Log.d(TAG, mDevice.getInterface(i).toString()); + } + if (mPortNumber == -1) { + Log.d(TAG,"device might be castrated ACM device, trying single interface logic"); + openSingleInterface(); + } else { + Log.d(TAG,"trying default interface logic"); + openInterface(); + } + } + + private void openSingleInterface() throws IOException { + // the following code is inspired by the cdc-acm driver in the linux kernel + + mControlIndex = 0; + mControlInterface = mDevice.getInterface(0); + mDataInterface = mDevice.getInterface(0); + if (!mConnection.claimInterface(mControlInterface, true)) { + throw new IOException("Could not claim shared control/data interface"); + } + + for (int i = 0; i < mControlInterface.getEndpointCount(); ++i) { + UsbEndpoint ep = mControlInterface.getEndpoint(i); + if ((ep.getDirection() == UsbConstants.USB_DIR_IN) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_INT)) { + mControlEndpoint = ep; + } else if ((ep.getDirection() == UsbConstants.USB_DIR_IN) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) { + mReadEndpoint = ep; + } else if ((ep.getDirection() == UsbConstants.USB_DIR_OUT) && (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK)) { + mWriteEndpoint = ep; + } + } + if (mControlEndpoint == null) { + throw new IOException("No control endpoint"); + } + } + + private void openInterface() throws IOException { + + mControlInterface = null; + mDataInterface = null; + int j = getInterfaceIdFromDescriptors(); + Log.d(TAG, "interface count=" + mDevice.getInterfaceCount() + ", IAD=" + j); + if (j >= 0) { + for (int i = 0; i < mDevice.getInterfaceCount(); i++) { + UsbInterface usbInterface = mDevice.getInterface(i); + if (usbInterface.getId() == j || usbInterface.getId() == j+1) { + if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_COMM && + usbInterface.getInterfaceSubclass() == USB_SUBCLASS_ACM) { + mControlIndex = usbInterface.getId(); + mControlInterface = usbInterface; + } + if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) { + mDataInterface = usbInterface; + } + } + } + } + if (mControlInterface == null || mDataInterface == null) { + Log.d(TAG, "no IAD fallback"); + int controlInterfaceCount = 0; + int dataInterfaceCount = 0; + for (int i = 0; i < mDevice.getInterfaceCount(); i++) { + UsbInterface usbInterface = mDevice.getInterface(i); + if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_COMM && + usbInterface.getInterfaceSubclass() == USB_SUBCLASS_ACM) { + if (controlInterfaceCount == mPortNumber) { + mControlIndex = usbInterface.getId(); + mControlInterface = usbInterface; + } + controlInterfaceCount++; + } + if (usbInterface.getInterfaceClass() == UsbConstants.USB_CLASS_CDC_DATA) { + if (dataInterfaceCount == mPortNumber) { + mDataInterface = usbInterface; + } + dataInterfaceCount++; + } + } + } + + if(mControlInterface == null) { + throw new IOException("No control interface"); + } + Log.d(TAG, "Control interface id " + mControlInterface.getId()); + + if (!mConnection.claimInterface(mControlInterface, true)) { + throw new IOException("Could not claim control interface"); + } + mControlEndpoint = mControlInterface.getEndpoint(0); + if (mControlEndpoint.getDirection() != UsbConstants.USB_DIR_IN || mControlEndpoint.getType() != UsbConstants.USB_ENDPOINT_XFER_INT) { + throw new IOException("Invalid control endpoint"); + } + + if(mDataInterface == null) { + throw new IOException("No data interface"); + } + Log.d(TAG, "data interface id " + mDataInterface.getId()); + if (!mConnection.claimInterface(mDataInterface, true)) { + throw new IOException("Could not claim data interface"); + } + for (int i = 0; i < mDataInterface.getEndpointCount(); i++) { + UsbEndpoint ep = mDataInterface.getEndpoint(i); + if (ep.getDirection() == UsbConstants.USB_DIR_IN && ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) + mReadEndpoint = ep; + if (ep.getDirection() == UsbConstants.USB_DIR_OUT && ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) + mWriteEndpoint = ep; + } + } + + private int getInterfaceIdFromDescriptors() { + ArrayList descriptors = UsbUtils.getDescriptors(mConnection); + Log.d(TAG, "USB descriptor:"); + for(byte[] descriptor : descriptors) + Log.d(TAG, HexDump.toHexString(descriptor)); + + if (descriptors.size() > 0 && + descriptors.get(0).length == 18 && + descriptors.get(0)[1] == 1 && // bDescriptorType + descriptors.get(0)[4] == (byte)(UsbConstants.USB_CLASS_MISC) && //bDeviceClass + descriptors.get(0)[5] == 2 && // bDeviceSubClass + descriptors.get(0)[6] == 1) { // bDeviceProtocol + // is IAD device, see https://www.usb.org/sites/default/files/iadclasscode_r10.pdf + int port = -1; + for (int d = 1; d < descriptors.size(); d++) { + if (descriptors.get(d).length == 8 && + descriptors.get(d)[1] == 0x0b && // bDescriptorType == IAD + descriptors.get(d)[4] == UsbConstants.USB_CLASS_COMM && // bFunctionClass == CDC + descriptors.get(d)[5] == USB_SUBCLASS_ACM) { // bFunctionSubClass == ACM + port++; + if (port == mPortNumber && + descriptors.get(d)[3] == 2) { // bInterfaceCount + return descriptors.get(d)[2]; // bFirstInterface + } + } + } + } + return -1; + } + + private int sendAcmControlMessage(int request, int value, byte[] buf) throws IOException { + int len = mConnection.controlTransfer( + USB_RT_ACM, request, value, mControlIndex, buf, buf != null ? buf.length : 0, 5000); + if(len < 0) { + throw new IOException("controlTransfer failed"); + } + return len; + } + + private void readControlLinesThreadFunction() { + try { + byte[] buffer = new byte[Math.max(SERIAL_STATE_PACKET_SIZE, mControlEndpoint.getMaxPacketSize())]; + while (!mStopReadControlLinesThread && mConnection!=null) { + long endTime = MonotonicClock.millis() + 500; + int readBytesCount = mConnection.bulkTransfer(mControlEndpoint, buffer, buffer.length, 500); + if (readBytesCount == -1) { + testConnection(MonotonicClock.millis() < endTime); + continue; + } + if (readBytesCount != SERIAL_STATE_PACKET_SIZE) continue; + if (buffer[0] != (byte)NOTIFICATION_REQUEST_TYPE) continue; + if (buffer[1] != SERIAL_STATE) continue; + int index = ((buffer[5] & 0xff) << 8) | (buffer[4] & 0xff); + if (index != mControlIndex) continue; + int payloadLength = ((buffer[7] & 0xff) << 8) | (buffer[6] & 0xff); + if (payloadLength < 2) continue; + mSerialState = ((buffer[9] & 0xff) << 8) | (buffer[8] & 0xff); + Log.d(TAG, "control line state " + Arrays.toString(buffer)); + } + } catch (Exception e) { + mReadControlLinesException = e; + } + } + + private int getSerialState() throws IOException { + if(mConnection == null) + throw new IOException("connection closed"); + if (mReadControlLinesThread == null) { + synchronized (mReadControlLinesThreadLock) { + if (mReadControlLinesThread == null) { + mSerialState = 0; + mReadControlLinesThread = new Thread(this::readControlLinesThreadFunction); + mReadControlLinesThread.setDaemon(true); + mReadControlLinesThread.start(); + } + } + } + if (mReadControlLinesException != null) { + throw new IOException(mReadControlLinesException); + } + return mSerialState; + } + + @Override + protected void closeInt() { + try { + synchronized (mReadControlLinesThreadLock) { + if (mReadControlLinesThread != null) { + try { + mStopReadControlLinesThread = true; + mReadControlLinesThread.join(); + } catch (Exception e) { + Log.w(TAG, "An error occurred while waiting for control line read thread", e); + } + mStopReadControlLinesThread = false; + mReadControlLinesThread = null; + mReadControlLinesException = null; + } + } + mConnection.releaseInterface(mControlInterface); + mConnection.releaseInterface(mDataInterface); + } catch(Exception ignored) {} + } + + @Override + public void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException { + if(baudRate <= 0) { + throw new IllegalArgumentException("Invalid baud rate: " + baudRate); + } + if(dataBits < DATABITS_5 || dataBits > DATABITS_8) { + throw new IllegalArgumentException("Invalid data bits: " + dataBits); + } + byte stopBitsByte; + switch (stopBits) { + case STOPBITS_1: stopBitsByte = 0; break; + case STOPBITS_1_5: stopBitsByte = 1; break; + case STOPBITS_2: stopBitsByte = 2; break; + default: throw new IllegalArgumentException("Invalid stop bits: " + stopBits); + } + + byte parityBitesByte; + switch (parity) { + case PARITY_NONE: parityBitesByte = 0; break; + case PARITY_ODD: parityBitesByte = 1; break; + case PARITY_EVEN: parityBitesByte = 2; break; + case PARITY_MARK: parityBitesByte = 3; break; + case PARITY_SPACE: parityBitesByte = 4; break; + default: throw new IllegalArgumentException("Invalid parity: " + parity); + } + byte[] msg = { + (byte) ( baudRate & 0xff), + (byte) ((baudRate >> 8 ) & 0xff), + (byte) ((baudRate >> 16) & 0xff), + (byte) ((baudRate >> 24) & 0xff), + stopBitsByte, + parityBitesByte, + (byte) dataBits}; + sendAcmControlMessage(SET_LINE_CODING, 0, msg); + } + + @Override + public boolean getDTR() throws IOException { + return mDtr; + } + + @Override + public void setDTR(boolean value) throws IOException { + mDtr = value; + setDtrRts(); + } + + @Override + public boolean getRTS() throws IOException { + return mRts; + } + + @Override + public boolean getCD() throws IOException { + return (getSerialState() & SERIAL_STATE_FLAG_CD) != 0; + } + + @Override + public boolean getDSR() throws IOException { + return (getSerialState() & SERIAL_STATE_FLAG_DSR) != 0; + } + + @Override + public boolean getRI() throws IOException { + return (getSerialState() & SERIAL_STATE_FLAG_RI) != 0; + } + + @Override + public void setRTS(boolean value) throws IOException { + mRts = value; + setDtrRts(); + } + + private void setDtrRts() throws IOException { + int value = (mRts ? 0x2 : 0) | (mDtr ? 0x1 : 0); + sendAcmControlMessage(SET_CONTROL_LINE_STATE, value, null); + } + + @Override + public EnumSet getControlLines() throws IOException { + int serialState = getSerialState(); + EnumSet set = EnumSet.noneOf(ControlLine.class); + if(mRts) set.add(ControlLine.RTS); + // no CTS + if(mDtr) set.add(ControlLine.DTR); + if((serialState & SERIAL_STATE_FLAG_DSR) != 0) set.add(ControlLine.DSR); + if((serialState & SERIAL_STATE_FLAG_CD) != 0) set.add(ControlLine.CD); + if((serialState & SERIAL_STATE_FLAG_RI) != 0) set.add(ControlLine.RI); + return set; + } + + @Override + public EnumSet getSupportedControlLines() throws IOException { + return EnumSet.of(ControlLine.RTS, ControlLine.DTR, ControlLine.DSR, ControlLine.CD, ControlLine.RI); + } + + @Override + public void setBreak(boolean value) throws IOException { + sendAcmControlMessage(SEND_BREAK, value ? 0xffff : 0, null); + } + + } + + @SuppressWarnings({"unused"}) + public static Map getSupportedDevices() { + return new LinkedHashMap<>(); + } + +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/driver/Ch34xSerialDriver.java b/androidApp/src/main/java/com/hoho/android/usbserial/driver/Ch34xSerialDriver.java new file mode 100644 index 0000000..527fb89 --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/driver/Ch34xSerialDriver.java @@ -0,0 +1,412 @@ +/* Copyright 2014 Andreas Butti + * + * Project home page: https://github.com/mik3y/usb-serial-for-android + */ + +package com.hoho.android.usbserial.driver; + +import android.hardware.usb.UsbConstants; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbEndpoint; +import android.hardware.usb.UsbInterface; +import android.util.Log; + +import cz.netkit.app.BuildConfig; + +import java.io.IOException; +import java.util.Collections; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Ch34xSerialDriver implements UsbSerialDriver { + + private static final String TAG = Ch34xSerialDriver.class.getSimpleName(); + + private final UsbDevice mDevice; + private final UsbSerialPort mPort; + + private static final int LCR_ENABLE_RX = 0x80; + private static final int LCR_ENABLE_TX = 0x40; + private static final int LCR_MARK_SPACE = 0x20; + private static final int LCR_PAR_EVEN = 0x10; + private static final int LCR_ENABLE_PAR = 0x08; + private static final int LCR_STOP_BITS_2 = 0x04; + private static final int LCR_CS8 = 0x03; + private static final int LCR_CS7 = 0x02; + private static final int LCR_CS6 = 0x01; + private static final int LCR_CS5 = 0x00; + + private static final int GCL_CTS = 0x01; + private static final int GCL_DSR = 0x02; + private static final int GCL_RI = 0x04; + private static final int GCL_CD = 0x08; + private static final int SCL_DTR = 0x20; + private static final int SCL_RTS = 0x40; + + public Ch34xSerialDriver(UsbDevice device) { + mDevice = device; + mPort = new Ch340SerialPort(mDevice, 0); + } + + @Override + public UsbDevice getDevice() { + return mDevice; + } + + @Override + public List getPorts() { + return Collections.singletonList(mPort); + } + + public class Ch340SerialPort extends CommonUsbSerialPort { + + private static final int USB_TIMEOUT_MILLIS = 5000; + + private final int DEFAULT_BAUD_RATE = 9600; + + private boolean dtr = false; + private boolean rts = false; + + public Ch340SerialPort(UsbDevice device, int portNumber) { + super(device, portNumber); + } + + @Override + public UsbSerialDriver getDriver() { + return Ch34xSerialDriver.this; + } + + @Override + protected void openInt() throws IOException { + for (int i = 0; i < mDevice.getInterfaceCount(); i++) { + UsbInterface usbIface = mDevice.getInterface(i); + if (!mConnection.claimInterface(usbIface, true)) { + throw new IOException("Could not claim data interface"); + } + } + + UsbInterface dataIface = mDevice.getInterface(mDevice.getInterfaceCount() - 1); + for (int i = 0; i < dataIface.getEndpointCount(); i++) { + UsbEndpoint ep = dataIface.getEndpoint(i); + if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { + if (ep.getDirection() == UsbConstants.USB_DIR_IN) { + mReadEndpoint = ep; + } else { + mWriteEndpoint = ep; + } + } + } + + initialize(); + setBaudRate(DEFAULT_BAUD_RATE); + setFlowControl(mFlowControl); + } + + @Override + protected void closeInt() { + try { + for (int i = 0; i < mDevice.getInterfaceCount(); i++) + mConnection.releaseInterface(mDevice.getInterface(i)); + } catch(Exception ignored) {} + } + + private int controlOut(int request, int value, int index) { + final int REQTYPE_HOST_TO_DEVICE = UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_DIR_OUT; + return mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request, + value, index, null, 0, USB_TIMEOUT_MILLIS); + } + + + private int controlIn(int request, int value, int index, byte[] buffer) { + final int REQTYPE_DEVICE_TO_HOST = UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_DIR_IN; + return mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, request, + value, index, buffer, buffer.length, USB_TIMEOUT_MILLIS); + } + + + private void checkState(String msg, int request, int value, int[] expected) throws IOException { + byte[] buffer = new byte[expected.length]; + int ret = controlIn(request, value, 0, buffer); + + if (ret < 0) { + throw new IOException("Failed send cmd [" + msg + "]"); + } + + if (ret != expected.length) { + throw new IOException("Expected " + expected.length + " bytes, but get " + ret + " [" + msg + "]"); + } + + for (int i = 0; i < expected.length; i++) { + if (expected[i] == -1) { + continue; + } + + int current = buffer[i] & 0xff; + if (expected[i] != current) { + throw new IOException("Expected 0x" + Integer.toHexString(expected[i]) + " byte, but get 0x" + Integer.toHexString(current) + " [" + msg + "]"); + } + } + } + + private void setControlLines() throws IOException { + if (controlOut(0xa4, ~((dtr ? SCL_DTR : 0) | (rts ? SCL_RTS : 0)), 0) < 0) { + throw new IOException("Failed to set control lines"); + } + } + + private byte getStatus() throws IOException { + byte[] buffer = new byte[2]; + int ret = controlIn(0x95, 0x0706, 0, buffer); + if (ret < 0) + throw new IOException("Error getting control lines"); + return buffer[0]; + } + + private void initialize() throws IOException { + checkState("init #1", 0x5f, 0, new int[]{-1 /* 0x27, 0x30 */, 0x00}); + + if (controlOut(0xa1, 0, 0) < 0) { + throw new IOException("Init failed: #2"); + } + + setBaudRate(DEFAULT_BAUD_RATE); + + checkState("init #4", 0x95, 0x2518, new int[]{-1 /* 0x56, c3*/, 0x00}); + + if (controlOut(0x9a, 0x2518, LCR_ENABLE_RX | LCR_ENABLE_TX | LCR_CS8) < 0) { + throw new IOException("Init failed: #5"); + } + + checkState("init #6", 0x95, 0x0706, new int[]{-1/*0xf?*/, -1/*0xec,0xee*/}); + + if (controlOut(0xa1, 0x501f, 0xd90a) < 0) { + throw new IOException("Init failed: #7"); + } + + setBaudRate(DEFAULT_BAUD_RATE); + + setControlLines(); + + checkState("init #10", 0x95, 0x0706, new int[]{-1/* 0x9f, 0xff*/, -1/*0xec,0xee*/}); + } + + + private void setBaudRate(int baudRate) throws IOException { + long factor; + long divisor; + + if (baudRate == 921600) { + divisor = 7; + factor = 0xf300; + } else if (baudRate == 307200) { + divisor = 7; + factor = 0xd900; + } else { + final long BAUDBASE_FACTOR = 1532620800; + final int BAUDBASE_DIVMAX = 3; + + if(BuildConfig.DEBUG && (baudRate & (3<<29)) == (1<<29)) + baudRate &= ~(1<<29); // for testing purpose bypass dedicated baud rate handling + factor = BAUDBASE_FACTOR / baudRate; + divisor = BAUDBASE_DIVMAX; + while ((factor > 0xfff0) && divisor > 0) { + factor >>= 3; + divisor--; + } + if (factor > 0xfff0) { + throw new UnsupportedOperationException("Unsupported baud rate: " + baudRate); + } + factor = 0x10000 - factor; + } + + divisor |= 0x0080; // else ch341a waits until buffer full + int val1 = (int) ((factor & 0xff00) | divisor); + int val2 = (int) (factor & 0xff); + Log.d(TAG, String.format("baud rate=%d, 0x1312=0x%04x, 0x0f2c=0x%04x", baudRate, val1, val2)); + int ret = controlOut(0x9a, 0x1312, val1); + if (ret < 0) { + throw new IOException("Error setting baud rate: #1)"); + } + ret = controlOut(0x9a, 0x0f2c, val2); + if (ret < 0) { + throw new IOException("Error setting baud rate: #2"); + } + } + + @Override + public void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException { + if(baudRate <= 0) { + throw new IllegalArgumentException("Invalid baud rate: " + baudRate); + } + setBaudRate(baudRate); + + int lcr = LCR_ENABLE_RX | LCR_ENABLE_TX; + + switch (dataBits) { + case DATABITS_5: + lcr |= LCR_CS5; + break; + case DATABITS_6: + lcr |= LCR_CS6; + break; + case DATABITS_7: + lcr |= LCR_CS7; + break; + case DATABITS_8: + lcr |= LCR_CS8; + break; + default: + throw new IllegalArgumentException("Invalid data bits: " + dataBits); + } + + switch (parity) { + case PARITY_NONE: + break; + case PARITY_ODD: + lcr |= LCR_ENABLE_PAR; + break; + case PARITY_EVEN: + lcr |= LCR_ENABLE_PAR | LCR_PAR_EVEN; + break; + case PARITY_MARK: + lcr |= LCR_ENABLE_PAR | LCR_MARK_SPACE; + break; + case PARITY_SPACE: + lcr |= LCR_ENABLE_PAR | LCR_MARK_SPACE | LCR_PAR_EVEN; + break; + default: + throw new IllegalArgumentException("Invalid parity: " + parity); + } + + switch (stopBits) { + case STOPBITS_1: + break; + case STOPBITS_1_5: + throw new UnsupportedOperationException("Unsupported stop bits: 1.5"); + case STOPBITS_2: + lcr |= LCR_STOP_BITS_2; + break; + default: + throw new IllegalArgumentException("Invalid stop bits: " + stopBits); + } + + int ret = controlOut(0x9a, 0x2518, lcr); + if (ret < 0) { + throw new IOException("Error setting control byte"); + } + } + + @Override + public boolean getCD() throws IOException { + return (getStatus() & GCL_CD) == 0; + } + + @Override + public boolean getCTS() throws IOException { + return (getStatus() & GCL_CTS) == 0; + } + + @Override + public boolean getDSR() throws IOException { + return (getStatus() & GCL_DSR) == 0; + } + + @Override + public boolean getDTR() throws IOException { + return dtr; + } + + @Override + public void setDTR(boolean value) throws IOException { + dtr = value; + setControlLines(); + } + + @Override + public boolean getRI() throws IOException { + return (getStatus() & GCL_RI) == 0; + } + + @Override + public boolean getRTS() throws IOException { + return rts; + } + + @Override + public void setRTS(boolean value) throws IOException { + rts = value; + setControlLines(); + } + + @Override + public EnumSet getControlLines() throws IOException { + int status = getStatus(); + EnumSet set = EnumSet.noneOf(ControlLine.class); + if(rts) set.add(ControlLine.RTS); + if((status & GCL_CTS) == 0) set.add(ControlLine.CTS); + if(dtr) set.add(ControlLine.DTR); + if((status & GCL_DSR) == 0) set.add(ControlLine.DSR); + if((status & GCL_CD) == 0) set.add(ControlLine.CD); + if((status & GCL_RI) == 0) set.add(ControlLine.RI); + return set; + } + + @Override + public EnumSet getSupportedControlLines() throws IOException { + return EnumSet.allOf(ControlLine.class); + } + + @Override + public void setFlowControl(FlowControl flowControl) throws IOException { + if (flowControl == FlowControl.RTS_CTS) { + if (controlOut(0x9a, 0x2727, 0x0101) < 0) { + throw new IOException("Error setting flow control"); + } + } else if (flowControl == FlowControl.NONE) { + if (controlOut(0x9a, 0x2727, 0x0000) < 0) { + throw new IOException("Error setting flow control"); + } + } else { + throw new UnsupportedOperationException("Unsupported flow control: " + flowControl); + } + mFlowControl = flowControl; + } + + @Override + public EnumSet getSupportedFlowControl() { + return EnumSet.of(FlowControl.NONE, FlowControl.RTS_CTS); + } + + @Override + public void setBreak(boolean value) throws IOException { + byte[] req = new byte[2]; + if(controlIn(0x95, 0x1805, 0, req) < 0) { + throw new IOException("Error getting BREAK condition"); + } + if(value) { + req[0] &= ~1; + req[1] &= ~0x40; + } else { + req[0] |= 1; + req[1] |= 0x40; + } + int val = (req[1] & 0xff) << 8 | (req[0] & 0xff); + if(controlOut(0x9a, 0x1805, val) < 0) { + throw new IOException("Error setting BREAK condition"); + } + } + } + + @SuppressWarnings({"unused"}) + public static Map getSupportedDevices() { + final Map supportedDevices = new LinkedHashMap<>(); + supportedDevices.put(UsbId.VENDOR_QINHENG, new int[]{ + UsbId.QINHENG_CH340, + UsbId.QINHENG_CH341A, + }); + return supportedDevices; + } + +} \ No newline at end of file diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java b/androidApp/src/main/java/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java new file mode 100644 index 0000000..cda94e2 --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java @@ -0,0 +1,438 @@ +/* Copyright 2011-2013 Google Inc. + * Copyright 2013 mike wakerly + * + * Project home page: https://github.com/mik3y/usb-serial-for-android + */ + +package com.hoho.android.usbserial.driver; + +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbDeviceConnection; +import android.hardware.usb.UsbEndpoint; +import android.hardware.usb.UsbRequest; +import android.os.Build; +import android.util.Log; + +import com.hoho.android.usbserial.util.MonotonicClock; +import com.hoho.android.usbserial.util.UsbUtils; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.EnumSet; +import java.util.LinkedList; +import java.util.Objects; + +/** + * A base class shared by several driver implementations. + * + * @author mike wakerly (opensource@hoho.com) + */ +public abstract class CommonUsbSerialPort implements UsbSerialPort { + + public static boolean DEBUG = false; + + private static final String TAG = CommonUsbSerialPort.class.getSimpleName(); + private static final int MAX_READ_SIZE = 16 * 1024; // = old bulkTransfer limit prior to Android 9 + + protected final UsbDevice mDevice; + protected final int mPortNumber; + + // non-null when open() + protected UsbDeviceConnection mConnection; + protected UsbEndpoint mReadEndpoint; + protected UsbEndpoint mWriteEndpoint; + protected UsbRequest mReadRequest; + protected LinkedList mReadQueueRequests; + private int mReadQueueBufferCount; + private int mReadQueueBufferSize; + protected FlowControl mFlowControl = FlowControl.NONE; + protected UsbUtils.Supplier mUsbRequestSupplier = UsbRequest::new; // override for testing + + /** + * Internal write buffer. + * Guarded by {@link #mWriteBufferLock}. + * Default length = mReadEndpoint.getMaxPacketSize() + **/ + protected byte[] mWriteBuffer; + protected final Object mWriteBufferLock = new Object(); + + + public CommonUsbSerialPort(UsbDevice device, int portNumber) { + mDevice = device; + mPortNumber = portNumber; + } + + @Override + public String toString() { + return String.format("<%s device_name=%s device_id=%s port_number=%s>", + getClass().getSimpleName(), mDevice.getDeviceName(), + mDevice.getDeviceId(), mPortNumber); + } + + @Override + public UsbDevice getDevice() { + return mDevice; + } + + @Override + public int getPortNumber() { + return mPortNumber; + } + + @Override + public UsbEndpoint getWriteEndpoint() { return mWriteEndpoint; } + + @Override + public UsbEndpoint getReadEndpoint() { return mReadEndpoint; } + + /** + * Returns the device serial number + * @return serial number + */ + @Override + public String getSerial() { + return mConnection.getSerial(); + } + + /** + * Sets the size of the internal buffer used to exchange data with the USB + * stack for write operations. Most users should not need to change this. + * + * @param bufferSize the size in bytes, <= 0 resets original size + */ + public final void setWriteBufferSize(int bufferSize) { + synchronized (mWriteBufferLock) { + if (bufferSize <= 0) { + if (mWriteEndpoint != null) { + bufferSize = mWriteEndpoint.getMaxPacketSize(); + } else { + mWriteBuffer = null; + return; + } + } + if (mWriteBuffer != null && bufferSize == mWriteBuffer.length) { + return; + } + mWriteBuffer = new byte[bufferSize]; + } + } + + @Override + public void setReadQueue(int bufferCount, int bufferSize) { + if (bufferCount < 0) { + throw new IllegalArgumentException("Invalid bufferCount"); + } + if (bufferSize < 0) { + throw new IllegalArgumentException("Invalid bufferSize"); + } + if(isOpen()) { + if (bufferCount < mReadQueueBufferCount) { + throw new IllegalStateException("Cannot reduce bufferCount when port is open"); + } + if (bufferSize == 0) { + bufferSize = mReadEndpoint.getMaxPacketSize(); + } + if (mReadQueueBufferSize == 0) { + mReadQueueBufferSize = mReadEndpoint.getMaxPacketSize(); + } + if (mReadQueueBufferCount != 0 && bufferSize != mReadQueueBufferSize) { + throw new IllegalStateException("Cannot change bufferSize when port is open"); + } + if (bufferCount > 0) { + if (mReadQueueRequests == null) { + mReadQueueRequests = new LinkedList<>(); + } + for (int i = mReadQueueRequests.size(); i < bufferCount; i++) { + ByteBuffer buffer = ByteBuffer.allocate(bufferSize); + UsbRequest request = mUsbRequestSupplier.get(); + request.initialize(mConnection, mReadEndpoint); + request.setClientData(buffer); + request.queue(buffer, bufferSize); + mReadQueueRequests.add(request); + } + } + } + mReadQueueBufferCount = bufferCount; + mReadQueueBufferSize = bufferSize; + } + + @Override + public int getReadQueueBufferCount() { return mReadQueueBufferCount; } + @Override + public int getReadQueueBufferSize() { return mReadQueueBufferSize; } + + private boolean useReadQueue() { return mReadQueueBufferCount != 0; } + + @Override + public void open(UsbDeviceConnection connection) throws IOException { + if (mConnection != null) { + throw new IOException("Already open"); + } + if(connection == null) { + throw new IllegalArgumentException("Connection is null"); + } + mConnection = connection; + boolean ok = false; + try { + openInt(); + if (mReadEndpoint == null || mWriteEndpoint == null) { + throw new IOException("Could not get read & write endpoints"); + } + mReadRequest = mUsbRequestSupplier.get(); + mReadRequest.initialize(mConnection, mReadEndpoint); + setReadQueue(mReadQueueBufferCount, mReadQueueBufferSize); // fill mReadQueueRequests + ok = true; + } finally { + if (!ok) { + try { + close(); + } catch (Exception ignored) {} + } + } + } + + protected abstract void openInt() throws IOException; + + @Override + public void close() throws IOException { + if (mConnection == null) { + throw new IOException("Already closed"); + } + UsbRequest readRequest = mReadRequest; + mReadRequest = null; + try { + readRequest.cancel(); + } catch(Exception ignored) {} + if(mReadQueueRequests != null) { + for(UsbRequest readQueueRequest : mReadQueueRequests) { + try { + readQueueRequest.cancel(); + } catch(Exception ignored) {} + } + mReadQueueRequests = null; + } + try { + closeInt(); + } catch(Exception ignored) {} + try { + mConnection.close(); + } catch(Exception ignored) {} + mConnection = null; + } + + protected abstract void closeInt(); + + /** + * use simple USB request supported by all devices to test if connection is still valid + */ + protected void testConnection(boolean full) throws IOException { + testConnection(full, "USB get_status request failed"); + } + + protected void testConnection(boolean full, String msg) throws IOException { + if(mReadRequest == null) { + throw new IOException("Connection closed"); + } + if(!full) { + return; + } + byte[] buf = new byte[2]; + int len = mConnection.controlTransfer(0x80 /*DEVICE*/, 0 /*GET_STATUS*/, 0, 0, buf, buf.length, 200); + if(len < 0) + throw new IOException(msg); + } + + @Override + public int read(final byte[] dest, final int timeout) throws IOException { + if(dest.length == 0) { + throw new IllegalArgumentException("Read buffer too small"); + } + return read(dest, dest.length, timeout); + } + + @Override + public int read(final byte[] dest, final int length, final int timeout) throws IOException {return read(dest, length, timeout, true);} + + protected int read(final byte[] dest, int length, final int timeout, boolean testConnection) throws IOException { + testConnection(false); + if(length <= 0) { + throw new IllegalArgumentException("Read length too small"); + } + length = Math.min(length, dest.length); + final int nread; + if (timeout != 0) { + if(useReadQueue()) { + throw new IllegalStateException("Cannot use timeout!=0 if readQueue is enabled"); + } + // bulkTransfer will cause data loss with short timeout + high baud rates + continuous transfer + // https://stackoverflow.com/questions/9108548/android-usb-host-bulktransfer-is-losing-data + // but mConnection.requestWait(timeout) available since Android 8.0 es even worse, + // as it crashes with short timeout, e.g. + // A/libc: Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x276a in tid 29846 (pool-2-thread-1), pid 29618 (.usbserial.test) + // /system/lib64/libusbhost.so (usb_request_wait+192) + // /system/lib64/libandroid_runtime.so (android_hardware_UsbDeviceConnection_request_wait(_JNIEnv*, _jobject*, long)+84) + // data loss / crashes were observed with timeout up to 200 msec + long endTime = testConnection ? MonotonicClock.millis() + timeout : 0; + int readMax = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) ? length : Math.min(length, MAX_READ_SIZE); + nread = mConnection.bulkTransfer(mReadEndpoint, dest, readMax, timeout); + // Android error propagation is improvable: + // nread == -1 can be: timeout, connection lost, buffer too small, ??? + if(nread == -1 && testConnection) + testConnection(MonotonicClock.millis() < endTime); + + } else { + ByteBuffer buf = null; + if(useReadQueue()) { + if (length != mReadQueueBufferSize) { + throw new IllegalStateException("Cannot use different length if readQueue is enabled"); + } + } else { + buf = ByteBuffer.wrap(dest, 0, length); + if (!mReadRequest.queue(buf, length)) { + throw new IOException("Queueing USB request failed"); + } + } + final UsbRequest response = mConnection.requestWait(); + if (response == null) { + throw new IOException("Waiting for USB request failed"); + } + if(useReadQueue()) { + buf = (ByteBuffer) response.getClientData(); + System.arraycopy(buf.array(), 0, dest, 0, buf.position()); + if(mReadRequest != null) { // re-queue if connection not closed + if (!response.queue(buf, buf.capacity())) { + throw new IOException("Queueing USB request failed"); + } + } + } + nread = Objects.requireNonNull(buf).position(); + // Android error propagation is improvable: + // response != null & nread == 0 can be: connection lost, buffer too small, ??? + if(nread == 0) { + testConnection(true); + } + } + return Math.max(nread, 0); + } + + @Override + public void write(byte[] src, int timeout) throws IOException {write(src, src.length, timeout);} + + @Override + public void write(final byte[] src, int length, final int timeout) throws IOException { + int offset = 0; + long startTime = MonotonicClock.millis(); + length = Math.min(length, src.length); + + testConnection(false); + while (offset < length) { + int requestTimeout; + final int requestLength; + final int actualLength; + + synchronized (mWriteBufferLock) { + final byte[] writeBuffer; + + if (mWriteBuffer == null) { + mWriteBuffer = new byte[mWriteEndpoint.getMaxPacketSize()]; + } + requestLength = Math.min(length - offset, mWriteBuffer.length); + if (offset == 0) { + writeBuffer = src; + } else { + // bulkTransfer does not support offsets, make a copy. + System.arraycopy(src, offset, mWriteBuffer, 0, requestLength); + writeBuffer = mWriteBuffer; + } + if (timeout == 0 || offset == 0) { + requestTimeout = timeout; + } else { + requestTimeout = (int)(startTime + timeout - MonotonicClock.millis()); + if(requestTimeout == 0) + requestTimeout = -1; + } + if (requestTimeout < 0) { + actualLength = -2; + } else { + actualLength = mConnection.bulkTransfer(mWriteEndpoint, writeBuffer, requestLength, requestTimeout); + } + } + long elapsed = MonotonicClock.millis() - startTime; + if (DEBUG) { + Log.d(TAG, "Wrote " + actualLength + "/" + requestLength + " offset " + offset + "/" + length + " time " + elapsed + "/" + requestTimeout); + } + if (actualLength <= 0) { + String msg = "Error writing " + requestLength + " bytes at offset " + offset + " of total " + src.length + " after " + elapsed + "msec, rc=" + actualLength; + if (timeout != 0) { + // could be buffer full because: writing too fast, stopped by flow control + testConnection(elapsed < timeout, msg); + throw new SerialTimeoutException(msg, offset); + } else { + throw new IOException(msg); + + } + } + offset += actualLength; + } + } + + @Override + public boolean isOpen() { + return mReadRequest != null; + } + + @Override + public abstract void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException; + + @Override + public boolean getCD() throws IOException { throw new UnsupportedOperationException(); } + + @Override + public boolean getCTS() throws IOException { throw new UnsupportedOperationException(); } + + @Override + public boolean getDSR() throws IOException { throw new UnsupportedOperationException(); } + + @Override + public boolean getDTR() throws IOException { throw new UnsupportedOperationException(); } + + @Override + public void setDTR(boolean value) throws IOException { throw new UnsupportedOperationException(); } + + @Override + public boolean getRI() throws IOException { throw new UnsupportedOperationException(); } + + @Override + public boolean getRTS() throws IOException { throw new UnsupportedOperationException(); } + + @Override + public void setRTS(boolean value) throws IOException { throw new UnsupportedOperationException(); } + + @Override + public EnumSet getControlLines() throws IOException { throw new UnsupportedOperationException(); } + + @Override + public EnumSet getSupportedControlLines() throws IOException { return EnumSet.noneOf(ControlLine.class); } + + @Override + public void setFlowControl(FlowControl flowcontrol) throws IOException { + if (flowcontrol != FlowControl.NONE) + throw new UnsupportedOperationException(); + } + + @Override + public FlowControl getFlowControl() { return mFlowControl; } + + @Override + public EnumSet getSupportedFlowControl() { return EnumSet.of(FlowControl.NONE); } + + @Override + public boolean getXON() throws IOException { throw new UnsupportedOperationException(); } + + @Override + public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException { throw new UnsupportedOperationException(); } + + @Override + public void setBreak(boolean value) throws IOException { throw new UnsupportedOperationException(); } + +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/driver/Cp21xxSerialDriver.java b/androidApp/src/main/java/com/hoho/android/usbserial/driver/Cp21xxSerialDriver.java new file mode 100644 index 0000000..492bd6c --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/driver/Cp21xxSerialDriver.java @@ -0,0 +1,412 @@ +/* Copyright 2011-2013 Google Inc. + * Copyright 2013 mike wakerly + * + * Project home page: https://github.com/mik3y/usb-serial-for-android + */ + +package com.hoho.android.usbserial.driver; + +import android.hardware.usb.UsbConstants; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbEndpoint; +import android.hardware.usb.UsbInterface; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class Cp21xxSerialDriver implements UsbSerialDriver { + + private static final String TAG = Cp21xxSerialDriver.class.getSimpleName(); + + private final UsbDevice mDevice; + private final List mPorts; + + public Cp21xxSerialDriver(UsbDevice device) { + mDevice = device; + mPorts = new ArrayList<>(); + for( int port = 0; port < device.getInterfaceCount(); port++) { + mPorts.add(new Cp21xxSerialPort(mDevice, port)); + } + } + + @Override + public UsbDevice getDevice() { + return mDevice; + } + + @Override + public List getPorts() { + return mPorts; + } + + public class Cp21xxSerialPort extends CommonUsbSerialPort { + + private static final int USB_WRITE_TIMEOUT_MILLIS = 5000; + + /* + * Configuration Request Types + */ + private static final int REQTYPE_HOST_TO_DEVICE = 0x41; + private static final int REQTYPE_DEVICE_TO_HOST = 0xc1; + + /* + * Configuration Request Codes + */ + private static final int SILABSER_IFC_ENABLE_REQUEST_CODE = 0x00; + private static final int SILABSER_SET_LINE_CTL_REQUEST_CODE = 0x03; + private static final int SILABSER_SET_BREAK_REQUEST_CODE = 0x05; + private static final int SILABSER_SET_MHS_REQUEST_CODE = 0x07; + private static final int SILABSER_GET_MDMSTS_REQUEST_CODE = 0x08; + private static final int SILABSER_SET_XON_REQUEST_CODE = 0x09; + private static final int SILABSER_SET_XOFF_REQUEST_CODE = 0x0A; + private static final int SILABSER_GET_COMM_STATUS_REQUEST_CODE = 0x10; + private static final int SILABSER_FLUSH_REQUEST_CODE = 0x12; + private static final int SILABSER_SET_FLOW_REQUEST_CODE = 0x13; + private static final int SILABSER_SET_CHARS_REQUEST_CODE = 0x19; + private static final int SILABSER_SET_BAUDRATE_REQUEST_CODE = 0x1E; + + private static final int FLUSH_READ_CODE = 0x0a; + private static final int FLUSH_WRITE_CODE = 0x05; + + /* + * SILABSER_IFC_ENABLE_REQUEST_CODE + */ + private static final int UART_ENABLE = 0x0001; + private static final int UART_DISABLE = 0x0000; + + /* + * SILABSER_SET_MHS_REQUEST_CODE + */ + private static final int DTR_ENABLE = 0x101; + private static final int DTR_DISABLE = 0x100; + private static final int RTS_ENABLE = 0x202; + private static final int RTS_DISABLE = 0x200; + + /* + * SILABSER_GET_MDMSTS_REQUEST_CODE + */ + private static final int STATUS_DTR = 0x01; + private static final int STATUS_RTS = 0x02; + private static final int STATUS_CTS = 0x10; + private static final int STATUS_DSR = 0x20; + private static final int STATUS_RI = 0x40; + private static final int STATUS_CD = 0x80; + + + private boolean dtr = false; + private boolean rts = false; + + // second port of Cp2105 has limited baudRate, dataBits, stopBits, parity + // unsupported baudrate returns error at controlTransfer(), other parameters are silently ignored + private boolean mIsRestrictedPort; + + public Cp21xxSerialPort(UsbDevice device, int portNumber) { + super(device, portNumber); + } + + @Override + public UsbSerialDriver getDriver() { + return Cp21xxSerialDriver.this; + } + + private void setConfigSingle(int request, int value) throws IOException { + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, request, value, + mPortNumber, null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Control transfer failed: " + request + " / " + value + " -> " + result); + } + } + + private byte getStatus() throws IOException { + byte[] buffer = new byte[1]; + int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, SILABSER_GET_MDMSTS_REQUEST_CODE, 0, + mPortNumber, buffer, buffer.length, USB_WRITE_TIMEOUT_MILLIS); + if (result != buffer.length) { + throw new IOException("Control transfer failed: " + SILABSER_GET_MDMSTS_REQUEST_CODE + " / " + 0 + " -> " + result); + } + return buffer[0]; + } + + @Override + protected void openInt() throws IOException { + mIsRestrictedPort = mDevice.getInterfaceCount() == 2 && mPortNumber == 1; + if(mPortNumber >= mDevice.getInterfaceCount()) { + throw new IOException("Unknown port number"); + } + UsbInterface dataIface = mDevice.getInterface(mPortNumber); + if (!mConnection.claimInterface(dataIface, true)) { + throw new IOException("Could not claim interface " + mPortNumber); + } + for (int i = 0; i < dataIface.getEndpointCount(); i++) { + UsbEndpoint ep = dataIface.getEndpoint(i); + if (ep.getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) { + if (ep.getDirection() == UsbConstants.USB_DIR_IN) { + mReadEndpoint = ep; + } else { + mWriteEndpoint = ep; + } + } + } + + setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_ENABLE); + setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, (dtr ? DTR_ENABLE : DTR_DISABLE) | (rts ? RTS_ENABLE : RTS_DISABLE)); + setFlowControl(mFlowControl); + } + + @Override + protected void closeInt() { + try { + setConfigSingle(SILABSER_IFC_ENABLE_REQUEST_CODE, UART_DISABLE); + } catch (Exception ignored) {} + try { + mConnection.releaseInterface(mDevice.getInterface(mPortNumber)); + } catch(Exception ignored) {} + } + + private void setBaudRate(int baudRate) throws IOException { + byte[] data = new byte[] { + (byte) ( baudRate & 0xff), + (byte) ((baudRate >> 8 ) & 0xff), + (byte) ((baudRate >> 16) & 0xff), + (byte) ((baudRate >> 24) & 0xff) + }; + int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_BAUDRATE_REQUEST_CODE, + 0, mPortNumber, data, 4, USB_WRITE_TIMEOUT_MILLIS); + if (ret < 0) { + throw new IOException("Error setting baud rate"); + } + } + + @Override + public void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException { + if(baudRate <= 0) { + throw new IllegalArgumentException("Invalid baud rate: " + baudRate); + } + setBaudRate(baudRate); + + int configDataBits = 0; + switch (dataBits) { + case DATABITS_5: + if(mIsRestrictedPort) + throw new UnsupportedOperationException("Unsupported data bits: " + dataBits); + configDataBits |= 0x0500; + break; + case DATABITS_6: + if(mIsRestrictedPort) + throw new UnsupportedOperationException("Unsupported data bits: " + dataBits); + configDataBits |= 0x0600; + break; + case DATABITS_7: + if(mIsRestrictedPort) + throw new UnsupportedOperationException("Unsupported data bits: " + dataBits); + configDataBits |= 0x0700; + break; + case DATABITS_8: + configDataBits |= 0x0800; + break; + default: + throw new IllegalArgumentException("Invalid data bits: " + dataBits); + } + + switch (parity) { + case PARITY_NONE: + break; + case PARITY_ODD: + configDataBits |= 0x0010; + break; + case PARITY_EVEN: + configDataBits |= 0x0020; + break; + case PARITY_MARK: + if(mIsRestrictedPort) + throw new UnsupportedOperationException("Unsupported parity: mark"); + configDataBits |= 0x0030; + break; + case PARITY_SPACE: + if(mIsRestrictedPort) + throw new UnsupportedOperationException("Unsupported parity: space"); + configDataBits |= 0x0040; + break; + default: + throw new IllegalArgumentException("Invalid parity: " + parity); + } + + switch (stopBits) { + case STOPBITS_1: + break; + case STOPBITS_1_5: + throw new UnsupportedOperationException("Unsupported stop bits: 1.5"); + case STOPBITS_2: + if(mIsRestrictedPort) + throw new UnsupportedOperationException("Unsupported stop bits: 2"); + configDataBits |= 2; + break; + default: + throw new IllegalArgumentException("Invalid stop bits: " + stopBits); + } + setConfigSingle(SILABSER_SET_LINE_CTL_REQUEST_CODE, configDataBits); + } + + @Override + public boolean getCD() throws IOException { + return (getStatus() & STATUS_CD) != 0; + } + + @Override + public boolean getCTS() throws IOException { + return (getStatus() & STATUS_CTS) != 0; + } + + @Override + public boolean getDSR() throws IOException { + return (getStatus() & STATUS_DSR) != 0; + } + + @Override + public boolean getDTR() throws IOException { + return dtr; + } + + @Override + public void setDTR(boolean value) throws IOException { + dtr = value; + setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, dtr ? DTR_ENABLE : DTR_DISABLE); + } + + @Override + public boolean getRI() throws IOException { + return (getStatus() & STATUS_RI) != 0; + } + + @Override + public boolean getRTS() throws IOException { + return rts; + } + + @Override + public void setRTS(boolean value) throws IOException { + rts = value; + setConfigSingle(SILABSER_SET_MHS_REQUEST_CODE, rts ? RTS_ENABLE : RTS_DISABLE); + } + + @Override + public EnumSet getControlLines() throws IOException { + byte status = getStatus(); + EnumSet set = EnumSet.noneOf(ControlLine.class); + //if(rts) set.add(ControlLine.RTS); // configured value + if((status & STATUS_RTS) != 0) set.add(ControlLine.RTS); // actual value + if((status & STATUS_CTS) != 0) set.add(ControlLine.CTS); + //if(dtr) set.add(ControlLine.DTR); // configured value + if((status & STATUS_DTR) != 0) set.add(ControlLine.DTR); // actual value + if((status & STATUS_DSR) != 0) set.add(ControlLine.DSR); + if((status & STATUS_CD) != 0) set.add(ControlLine.CD); + if((status & STATUS_RI) != 0) set.add(ControlLine.RI); + return set; + } + + @Override + public EnumSet getSupportedControlLines() throws IOException { + return EnumSet.allOf(ControlLine.class); + } + + @Override + public boolean getXON() throws IOException { + byte[] buffer = new byte[0x13]; + int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, SILABSER_GET_COMM_STATUS_REQUEST_CODE, 0, + mPortNumber, buffer, buffer.length, USB_WRITE_TIMEOUT_MILLIS); + if (result != buffer.length) { + throw new IOException("Control transfer failed: " + SILABSER_GET_COMM_STATUS_REQUEST_CODE + " -> " + result); + } + return (buffer[4] & 8) == 0; + } + + /** + * emulate external XON/OFF + * @throws IOException + */ + public void setXON(boolean value) throws IOException { + setConfigSingle(value ? SILABSER_SET_XON_REQUEST_CODE : SILABSER_SET_XOFF_REQUEST_CODE, 0); + } + + @Override + public void setFlowControl(FlowControl flowControl) throws IOException { + byte[] data = new byte[16]; + if(flowControl == FlowControl.RTS_CTS) { + data[4] |= 0b1000_0000; // RTS + data[0] |= 0b0000_1000; // CTS + } else { + if(rts) + data[4] |= 0b0100_0000; + } + if(flowControl == FlowControl.DTR_DSR) { + data[0] |= 0b0000_0010; // DTR + data[0] |= 0b0001_0000; // DSR + } else { + if(dtr) + data[0] |= 0b0000_0001; + } + if(flowControl == FlowControl.XON_XOFF) { + byte[] chars = new byte[]{0, 0, 0, 0, CHAR_XON, CHAR_XOFF}; + int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_CHARS_REQUEST_CODE, + 0, mPortNumber, chars, chars.length, USB_WRITE_TIMEOUT_MILLIS); + if (ret != chars.length) { + throw new IOException("Error setting XON/XOFF chars"); + } + data[4] |= 0b0000_0011; + data[7] |= 0b1000_0000; + data[8] = (byte)128; + data[12] = (byte)128; + } + if(flowControl == FlowControl.XON_XOFF_INLINE) { + throw new UnsupportedOperationException(); + } + int ret = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SILABSER_SET_FLOW_REQUEST_CODE, + 0, mPortNumber, data, data.length, USB_WRITE_TIMEOUT_MILLIS); + if (ret != data.length) { + throw new IOException("Error setting flow control"); + } + if(flowControl == FlowControl.XON_XOFF) { + setXON(true); + } + mFlowControl = flowControl; + } + + @Override + public EnumSet getSupportedFlowControl() { + return EnumSet.of(FlowControl.NONE, FlowControl.RTS_CTS, FlowControl.DTR_DSR, FlowControl.XON_XOFF); + } + + @Override + // note: only working on some devices, on other devices ignored w/o error + public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException { + int value = (purgeReadBuffers ? FLUSH_READ_CODE : 0) + | (purgeWriteBuffers ? FLUSH_WRITE_CODE : 0); + + if (value != 0) { + setConfigSingle(SILABSER_FLUSH_REQUEST_CODE, value); + } + } + + @Override + public void setBreak(boolean value) throws IOException { + setConfigSingle(SILABSER_SET_BREAK_REQUEST_CODE, value ? 1 : 0); + } + } + + @SuppressWarnings({"unused"}) + public static Map getSupportedDevices() { + final Map supportedDevices = new LinkedHashMap<>(); + supportedDevices.put(UsbId.VENDOR_SILABS, + new int[] { + UsbId.SILABS_CP2102, // same ID for CP2101, CP2103, CP2104, CP2109 + UsbId.SILABS_CP2105, + UsbId.SILABS_CP2108, + }); + return supportedDevices; + } + +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/driver/FtdiSerialDriver.java b/androidApp/src/main/java/com/hoho/android/usbserial/driver/FtdiSerialDriver.java new file mode 100644 index 0000000..9344bdf --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/driver/FtdiSerialDriver.java @@ -0,0 +1,478 @@ +/* Copyright 2011-2013 Google Inc. + * Copyright 2013 mike wakerly + * Copyright 2020 kai morich + * + * Project home page: https://github.com/mik3y/usb-serial-for-android + */ + +package com.hoho.android.usbserial.driver; + +import android.hardware.usb.UsbConstants; +import android.hardware.usb.UsbDevice; +import android.util.Log; + +import com.hoho.android.usbserial.util.MonotonicClock; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/* + * driver is implemented from various information scattered over FTDI documentation + * + * baud rate calculation https://www.ftdichip.com/Support/Documents/AppNotes/AN232B-05_BaudRates.pdf + * control bits https://www.ftdichip.com/Firmware/Precompiled/UM_VinculumFirmware_V205.pdf + * device type https://www.ftdichip.com/Support/Documents/AppNotes/AN_233_Java_D2XX_for_Android_API_User_Manual.pdf -> bvdDevice + * + */ + +public class FtdiSerialDriver implements UsbSerialDriver { + + private static final String TAG = FtdiSerialPort.class.getSimpleName(); + + private final UsbDevice mDevice; + private final List mPorts; + + public FtdiSerialDriver(UsbDevice device) { + mDevice = device; + mPorts = new ArrayList<>(); + for( int port = 0; port < device.getInterfaceCount(); port++) { + mPorts.add(new FtdiSerialPort(mDevice, port)); + } + } + + @Override + public UsbDevice getDevice() { + return mDevice; + } + + @Override + public List getPorts() { + return mPorts; + } + + public class FtdiSerialPort extends CommonUsbSerialPort { + + private static final int USB_WRITE_TIMEOUT_MILLIS = 5000; + private static final int READ_HEADER_LENGTH = 2; // contains MODEM_STATUS + + private static final int REQTYPE_HOST_TO_DEVICE = UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_DIR_OUT; + private static final int REQTYPE_DEVICE_TO_HOST = UsbConstants.USB_TYPE_VENDOR | UsbConstants.USB_DIR_IN; + + private static final int RESET_REQUEST = 0; + private static final int MODEM_CONTROL_REQUEST = 1; + private static final int SET_FLOW_CONTROL_REQUEST = 2; + private static final int SET_BAUD_RATE_REQUEST = 3; + private static final int SET_DATA_REQUEST = 4; + private static final int GET_MODEM_STATUS_REQUEST = 5; + private static final int SET_LATENCY_TIMER_REQUEST = 9; + private static final int GET_LATENCY_TIMER_REQUEST = 10; + + private static final int MODEM_CONTROL_DTR_ENABLE = 0x0101; + private static final int MODEM_CONTROL_DTR_DISABLE = 0x0100; + private static final int MODEM_CONTROL_RTS_ENABLE = 0x0202; + private static final int MODEM_CONTROL_RTS_DISABLE = 0x0200; + private static final int MODEM_STATUS_CTS = 0x10; + private static final int MODEM_STATUS_DSR = 0x20; + private static final int MODEM_STATUS_RI = 0x40; + private static final int MODEM_STATUS_CD = 0x80; + private static final int RESET_ALL = 0; + private static final int RESET_PURGE_RX = 1; + private static final int RESET_PURGE_TX = 2; + + private boolean baudRateWithPort = false; + private boolean dtr = false; + private boolean rts = false; + private int breakConfig = 0; + + public FtdiSerialPort(UsbDevice device, int portNumber) { + super(device, portNumber); + } + + @Override + public UsbSerialDriver getDriver() { + return FtdiSerialDriver.this; + } + + + @Override + protected void openInt() throws IOException { + if (!mConnection.claimInterface(mDevice.getInterface(mPortNumber), true)) { + throw new IOException("Could not claim interface " + mPortNumber); + } + if (mDevice.getInterface(mPortNumber).getEndpointCount() < 2) { + throw new IOException("Not enough endpoints"); + } + mReadEndpoint = mDevice.getInterface(mPortNumber).getEndpoint(0); + mWriteEndpoint = mDevice.getInterface(mPortNumber).getEndpoint(1); + + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, RESET_REQUEST, + RESET_ALL, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Reset failed: result=" + result); + } + result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, MODEM_CONTROL_REQUEST, + (dtr ? MODEM_CONTROL_DTR_ENABLE : MODEM_CONTROL_DTR_DISABLE) | + (rts ? MODEM_CONTROL_RTS_ENABLE : MODEM_CONTROL_RTS_DISABLE), + mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Init RTS,DTR failed: result=" + result); + } + setFlowControl(mFlowControl); + + // mDevice.getVersion() would require API 23 + byte[] rawDescriptors = mConnection.getRawDescriptors(); + if(rawDescriptors == null || rawDescriptors.length < 14) { + throw new IOException("Could not get device descriptors"); + } + int deviceType = rawDescriptors[13]; + baudRateWithPort = deviceType == 7 || deviceType == 8 || deviceType == 9 // ...H devices + || mDevice.getInterfaceCount() > 1; // FT2232C + } + + @Override + protected void closeInt() { + try { + mConnection.releaseInterface(mDevice.getInterface(mPortNumber)); + } catch(Exception ignored) {} + } + + @Override + public int read(final byte[] dest, final int timeout) throws IOException + { + if(dest.length <= READ_HEADER_LENGTH) { + throw new IllegalArgumentException("Read buffer too small"); + // could allocate larger buffer, including space for 2 header bytes, but this would + // result in buffers not being 64 byte aligned any more, causing data loss at continuous + // data transfer at high baud rates when buffers are fully filled. + } + return read(dest, dest.length, timeout); + } + + @Override + public int read(final byte[] dest, int length, final int timeout) throws IOException { + if(length <= READ_HEADER_LENGTH) { + throw new IllegalArgumentException("Read length too small"); + // could allocate larger buffer, including space for 2 header bytes, but this would + // result in buffers not being 64 byte aligned any more, causing data loss at continuous + // data transfer at high baud rates when buffers are fully filled. + } + length = Math.min(length, dest.length); + int nread; + if (timeout != 0) { + long endTime = MonotonicClock.millis() + timeout; + do { + nread = super.read(dest, length, Math.max(1, (int)(endTime - MonotonicClock.millis())), false); + } while (nread == READ_HEADER_LENGTH && MonotonicClock.millis() < endTime); + if(nread <= 0) + testConnection(MonotonicClock.millis() < endTime); + } else { + do { + nread = super.read(dest, length, timeout); + } while (nread == READ_HEADER_LENGTH); + } + return readFilter(dest, nread); + } + + protected int readFilter(byte[] buffer, int totalBytesRead) throws IOException { + final int maxPacketSize = mReadEndpoint.getMaxPacketSize(); + int destPos = 0; + for(int srcPos = 0; srcPos < totalBytesRead; srcPos += maxPacketSize) { + int length = Math.min(srcPos + maxPacketSize, totalBytesRead) - (srcPos + READ_HEADER_LENGTH); + if (length < 0) + throw new IOException("Expected at least " + READ_HEADER_LENGTH + " bytes"); + System.arraycopy(buffer, srcPos + READ_HEADER_LENGTH, buffer, destPos, length); + destPos += length; + } + //Log.d(TAG, "read filter " + totalBytesRead + " -> " + destPos); + return destPos; + } + + private void setBaudrate(int baudRate) throws IOException { + int divisor, subdivisor, effectiveBaudRate; + if (baudRate > 3500000) { + throw new UnsupportedOperationException("Baud rate too high"); + } else if(baudRate >= 2500000) { + divisor = 0; + subdivisor = 0; + effectiveBaudRate = 3000000; + } else if(baudRate >= 1750000) { + divisor = 1; + subdivisor = 0; + effectiveBaudRate = 2000000; + } else { + divisor = (24000000 << 1) / baudRate; + divisor = (divisor + 1) >> 1; // round + subdivisor = divisor & 0x07; + divisor >>= 3; + if (divisor > 0x3fff) // exceeds bit 13 at 183 baud + throw new UnsupportedOperationException("Baud rate too low"); + effectiveBaudRate = (24000000 << 1) / ((divisor << 3) + subdivisor); + effectiveBaudRate = (effectiveBaudRate +1) >> 1; + } + double baudRateError = Math.abs(1.0 - (effectiveBaudRate / (double)baudRate)); + if(baudRateError >= 0.031) // can happen only > 1.5Mbaud + throw new UnsupportedOperationException(String.format("Baud rate deviation %.1f%% is higher than allowed 3%%", baudRateError*100)); + int value = divisor; + int index = 0; + switch(subdivisor) { + case 0: break; // 16,15,14 = 000 - sub-integer divisor = 0 + case 4: value |= 0x4000; break; // 16,15,14 = 001 - sub-integer divisor = 0.5 + case 2: value |= 0x8000; break; // 16,15,14 = 010 - sub-integer divisor = 0.25 + case 1: value |= 0xc000; break; // 16,15,14 = 011 - sub-integer divisor = 0.125 + case 3: value |= 0x0000; index |= 1; break; // 16,15,14 = 100 - sub-integer divisor = 0.375 + case 5: value |= 0x4000; index |= 1; break; // 16,15,14 = 101 - sub-integer divisor = 0.625 + case 6: value |= 0x8000; index |= 1; break; // 16,15,14 = 110 - sub-integer divisor = 0.75 + case 7: value |= 0xc000; index |= 1; break; // 16,15,14 = 111 - sub-integer divisor = 0.875 + } + if(baudRateWithPort) { + index <<= 8; + index |= mPortNumber+1; + } + Log.d(TAG, String.format("baud rate=%d, effective=%d, error=%.1f%%, value=0x%04x, index=0x%04x, divisor=%d, subdivisor=%d", + baudRate, effectiveBaudRate, baudRateError*100, value, index, divisor, subdivisor)); + + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SET_BAUD_RATE_REQUEST, + value, index, null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Setting baudrate failed: result=" + result); + } + } + + @Override + public void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException { + if(baudRate <= 0) { + throw new IllegalArgumentException("Invalid baud rate: " + baudRate); + } + setBaudrate(baudRate); + + int config = 0; + switch (dataBits) { + case DATABITS_5: + case DATABITS_6: + throw new UnsupportedOperationException("Unsupported data bits: " + dataBits); + case DATABITS_7: + case DATABITS_8: + config |= dataBits; + break; + default: + throw new IllegalArgumentException("Invalid data bits: " + dataBits); + } + + switch (parity) { + case PARITY_NONE: + break; + case PARITY_ODD: + config |= 0x100; + break; + case PARITY_EVEN: + config |= 0x200; + break; + case PARITY_MARK: + config |= 0x300; + break; + case PARITY_SPACE: + config |= 0x400; + break; + default: + throw new IllegalArgumentException("Invalid parity: " + parity); + } + + switch (stopBits) { + case STOPBITS_1: + break; + case STOPBITS_1_5: + throw new UnsupportedOperationException("Unsupported stop bits: 1.5"); + case STOPBITS_2: + config |= 0x1000; + break; + default: + throw new IllegalArgumentException("Invalid stop bits: " + stopBits); + } + + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SET_DATA_REQUEST, + config, mPortNumber+1,null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Setting parameters failed: result=" + result); + } + breakConfig = config; + } + + private int getStatus() throws IOException { + byte[] data = new byte[2]; + int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, GET_MODEM_STATUS_REQUEST, + 0, mPortNumber+1, data, data.length, USB_WRITE_TIMEOUT_MILLIS); + if (result != data.length) { + throw new IOException("Get modem status failed: result=" + result); + } + return data[0]; + } + + @Override + public boolean getCD() throws IOException { + return (getStatus() & MODEM_STATUS_CD) != 0; + } + + @Override + public boolean getCTS() throws IOException { + return (getStatus() & MODEM_STATUS_CTS) != 0; + } + + @Override + public boolean getDSR() throws IOException { + return (getStatus() & MODEM_STATUS_DSR) != 0; + } + + @Override + public boolean getDTR() throws IOException { + return dtr; + } + + @Override + public void setDTR(boolean value) throws IOException { + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, MODEM_CONTROL_REQUEST, + value ? MODEM_CONTROL_DTR_ENABLE : MODEM_CONTROL_DTR_DISABLE, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Set DTR failed: result=" + result); + } + dtr = value; + } + + @Override + public boolean getRI() throws IOException { + return (getStatus() & MODEM_STATUS_RI) != 0; + } + + @Override + public boolean getRTS() throws IOException { + return rts; + } + + @Override + public void setRTS(boolean value) throws IOException { + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, MODEM_CONTROL_REQUEST, + value ? MODEM_CONTROL_RTS_ENABLE : MODEM_CONTROL_RTS_DISABLE, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Set RTS failed: result=" + result); + } + rts = value; + } + + @Override + public EnumSet getControlLines() throws IOException { + int status = getStatus(); + EnumSet set = EnumSet.noneOf(ControlLine.class); + if(rts) set.add(ControlLine.RTS); + if((status & MODEM_STATUS_CTS) != 0) set.add(ControlLine.CTS); + if(dtr) set.add(ControlLine.DTR); + if((status & MODEM_STATUS_DSR) != 0) set.add(ControlLine.DSR); + if((status & MODEM_STATUS_CD) != 0) set.add(ControlLine.CD); + if((status & MODEM_STATUS_RI) != 0) set.add(ControlLine.RI); + return set; + } + + @Override + public EnumSet getSupportedControlLines() throws IOException { + return EnumSet.allOf(ControlLine.class); + } + + @Override + public void setFlowControl(FlowControl flowControl) throws IOException { + int value = 0; + int index = mPortNumber+1; + switch (flowControl) { + case NONE: + break; + case RTS_CTS: + index |= 0x100; + break; + case DTR_DSR: + index |= 0x200; + break; + case XON_XOFF_INLINE: + value = CHAR_XON + (CHAR_XOFF << 8); + index |= 0x400; + break; + default: + throw new UnsupportedOperationException(); + } + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SET_FLOW_CONTROL_REQUEST, + value, index, null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) + throw new IOException("Set flow control failed: result=" + result); + mFlowControl = flowControl; + } + + @Override + public EnumSet getSupportedFlowControl() { + return EnumSet.of(FlowControl.NONE, FlowControl.RTS_CTS, FlowControl.DTR_DSR, FlowControl.XON_XOFF_INLINE); + } + + @Override + public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException { + if (purgeWriteBuffers) { + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, RESET_REQUEST, + RESET_PURGE_RX, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Purge write buffer failed: result=" + result); + } + } + + if (purgeReadBuffers) { + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, RESET_REQUEST, + RESET_PURGE_TX, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Purge read buffer failed: result=" + result); + } + } + } + + @Override + public void setBreak(boolean value) throws IOException { + int config = breakConfig; + if(value) config |= 0x4000; + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SET_DATA_REQUEST, + config, mPortNumber+1,null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Setting BREAK failed: result=" + result); + } + } + + public void setLatencyTimer(int latencyTime) throws IOException { + int result = mConnection.controlTransfer(REQTYPE_HOST_TO_DEVICE, SET_LATENCY_TIMER_REQUEST, + latencyTime, mPortNumber+1, null, 0, USB_WRITE_TIMEOUT_MILLIS); + if (result != 0) { + throw new IOException("Set latency timer failed: result=" + result); + } + } + + public int getLatencyTimer() throws IOException { + byte[] data = new byte[1]; + int result = mConnection.controlTransfer(REQTYPE_DEVICE_TO_HOST, GET_LATENCY_TIMER_REQUEST, + 0, mPortNumber+1, data, data.length, USB_WRITE_TIMEOUT_MILLIS); + if (result != data.length) { + throw new IOException("Get latency timer failed: result=" + result); + } + return data[0]; + } + + } + + @SuppressWarnings({"unused"}) + public static Map getSupportedDevices() { + final Map supportedDevices = new LinkedHashMap<>(); + supportedDevices.put(UsbId.VENDOR_FTDI, + new int[] { + UsbId.FTDI_FT232R, + UsbId.FTDI_FT232H, + UsbId.FTDI_FT2232H, + UsbId.FTDI_FT4232H, + UsbId.FTDI_FT231X, // same ID for FT230X, FT231X, FT234XD + }); + return supportedDevices; + } + +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/driver/ProlificSerialDriver.java b/androidApp/src/main/java/com/hoho/android/usbserial/driver/ProlificSerialDriver.java new file mode 100644 index 0000000..0f01ad3 --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/driver/ProlificSerialDriver.java @@ -0,0 +1,605 @@ +/* + * Ported to usb-serial-for-android by Felix Hädicke + * + * Based on the pyprolific driver written by Emmanuel Blot + * See https://github.com/eblot/pyftdi + * + * Project home page: https://github.com/mik3y/usb-serial-for-android + */ + +package com.hoho.android.usbserial.driver; + +import android.hardware.usb.UsbConstants; +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbEndpoint; +import android.hardware.usb.UsbInterface; +import android.util.Log; + +import cz.netkit.app.BuildConfig; +import com.hoho.android.usbserial.util.MonotonicClock; + +import java.io.IOException; +import java.util.Collections; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class ProlificSerialDriver implements UsbSerialDriver { + + private final String TAG = ProlificSerialDriver.class.getSimpleName(); + + private final static int[] standardBaudRates = { + 75, 150, 300, 600, 1200, 1800, 2400, 3600, 4800, 7200, 9600, + 14400, 19200, 28800, 38400, 57600, 115200, 230400, 460800, + 614400, 921600, 1228800, 2457600, 3000000, 6000000 + }; + protected enum DeviceType { DEVICE_TYPE_01, DEVICE_TYPE_T, DEVICE_TYPE_HX, DEVICE_TYPE_HXN } + + private final UsbDevice mDevice; + private final UsbSerialPort mPort; + + public ProlificSerialDriver(UsbDevice device) { + mDevice = device; + mPort = new ProlificSerialPort(mDevice, 0); + } + + @Override + public List getPorts() { + return Collections.singletonList(mPort); + } + + @Override + public UsbDevice getDevice() { + return mDevice; + } + + class ProlificSerialPort extends CommonUsbSerialPort { + + private static final int USB_READ_TIMEOUT_MILLIS = 1000; + private static final int USB_WRITE_TIMEOUT_MILLIS = 5000; + + private static final int USB_RECIP_INTERFACE = 0x01; + + private static final int VENDOR_READ_REQUEST = 0x01; + private static final int VENDOR_WRITE_REQUEST = 0x01; + private static final int VENDOR_READ_HXN_REQUEST = 0x81; + private static final int VENDOR_WRITE_HXN_REQUEST = 0x80; + + private static final int VENDOR_OUT_REQTYPE = UsbConstants.USB_DIR_OUT | UsbConstants.USB_TYPE_VENDOR; + private static final int VENDOR_IN_REQTYPE = UsbConstants.USB_DIR_IN | UsbConstants.USB_TYPE_VENDOR; + private static final int CTRL_OUT_REQTYPE = UsbConstants.USB_DIR_OUT | UsbConstants.USB_TYPE_CLASS | USB_RECIP_INTERFACE; + + private static final int WRITE_ENDPOINT = 0x02; + private static final int READ_ENDPOINT = 0x83; + private static final int INTERRUPT_ENDPOINT = 0x81; + + private static final int RESET_HXN_REQUEST = 0x07; + private static final int FLUSH_RX_REQUEST = 0x08; + private static final int FLUSH_TX_REQUEST = 0x09; + private static final int SET_LINE_REQUEST = 0x20; // same as CDC SET_LINE_CODING + private static final int SET_CONTROL_REQUEST = 0x22; // same as CDC SET_CONTROL_LINE_STATE + private static final int SEND_BREAK_REQUEST = 0x23; // same as CDC SEND_BREAK + private static final int GET_CONTROL_HXN_REQUEST = 0x80; + private static final int GET_CONTROL_REQUEST = 0x87; + private static final int STATUS_NOTIFICATION = 0xa1; // similar to CDC SERIAL_STATE but different length + + /* RESET_HXN_REQUEST */ + private static final int RESET_HXN_RX_PIPE = 1; + private static final int RESET_HXN_TX_PIPE = 2; + + /* SET_CONTROL_REQUEST */ + private static final int CONTROL_DTR = 0x01; + private static final int CONTROL_RTS = 0x02; + + /* GET_CONTROL_REQUEST */ + private static final int GET_CONTROL_FLAG_CD = 0x02; + private static final int GET_CONTROL_FLAG_DSR = 0x04; + private static final int GET_CONTROL_FLAG_RI = 0x01; + private static final int GET_CONTROL_FLAG_CTS = 0x08; + + /* GET_CONTROL_HXN_REQUEST */ + private static final int GET_CONTROL_HXN_FLAG_CD = 0x40; + private static final int GET_CONTROL_HXN_FLAG_DSR = 0x20; + private static final int GET_CONTROL_HXN_FLAG_RI = 0x80; + private static final int GET_CONTROL_HXN_FLAG_CTS = 0x08; + + /* interrupt endpoint read */ + private static final int STATUS_FLAG_CD = 0x01; + private static final int STATUS_FLAG_DSR = 0x02; + private static final int STATUS_FLAG_RI = 0x08; + private static final int STATUS_FLAG_CTS = 0x80; + + private static final int STATUS_BUFFER_SIZE = 10; + private static final int STATUS_BYTE_IDX = 8; + + protected DeviceType mDeviceType = DeviceType.DEVICE_TYPE_HX; + private UsbEndpoint mInterruptEndpoint; + private int mControlLinesValue = 0; + private int mBaudRate = -1, mDataBits = -1, mStopBits = -1, mParity = -1; + + private int mStatus = 0; + private volatile Thread mReadStatusThread = null; + private final Object mReadStatusThreadLock = new Object(); + private boolean mStopReadStatusThread = false; + private Exception mReadStatusException = null; + + + public ProlificSerialPort(UsbDevice device, int portNumber) { + super(device, portNumber); + } + + @Override + public UsbSerialDriver getDriver() { + return ProlificSerialDriver.this; + } + + private byte[] inControlTransfer(int requestType, int request, int value, int index, int length) throws IOException { + byte[] buffer = new byte[length]; + int result = mConnection.controlTransfer(requestType, request, value, index, buffer, length, USB_READ_TIMEOUT_MILLIS); + if (result != length) { + throw new IOException(String.format("ControlTransfer %s 0x%x failed: %d",mDeviceType.name(), value, result)); + } + return buffer; + } + + private void outControlTransfer(int requestType, int request, int value, int index, byte[] data) throws IOException { + int length = (data == null) ? 0 : data.length; + int result = mConnection.controlTransfer(requestType, request, value, index, data, length, USB_WRITE_TIMEOUT_MILLIS); + if (result != length) { + throw new IOException( String.format("ControlTransfer %s 0x%x failed: %d", mDeviceType.name(), value, result)); + } + } + + private byte[] vendorIn(int value, int index, int length) throws IOException { + int request = (mDeviceType == DeviceType.DEVICE_TYPE_HXN) ? VENDOR_READ_HXN_REQUEST : VENDOR_READ_REQUEST; + return inControlTransfer(VENDOR_IN_REQTYPE, request, value, index, length); + } + + private void vendorOut(int value, int index, byte[] data) throws IOException { + int request = (mDeviceType == DeviceType.DEVICE_TYPE_HXN) ? VENDOR_WRITE_HXN_REQUEST : VENDOR_WRITE_REQUEST; + outControlTransfer(VENDOR_OUT_REQTYPE, request, value, index, data); + } + + private void resetDevice() throws IOException { + purgeHwBuffers(true, true); + } + + private void ctrlOut(int request, int value, int index, byte[] data) throws IOException { + outControlTransfer(CTRL_OUT_REQTYPE, request, value, index, data); + } + + private boolean testHxStatus() { + try { + inControlTransfer(VENDOR_IN_REQTYPE, VENDOR_READ_REQUEST, 0x8080, 0, 1); + return true; + } catch(IOException ignored) { + return false; + } + } + + private void doBlackMagic() throws IOException { + if (mDeviceType == DeviceType.DEVICE_TYPE_HXN) + return; + vendorIn(0x8484, 0, 1); + vendorOut(0x0404, 0, null); + vendorIn(0x8484, 0, 1); + vendorIn(0x8383, 0, 1); + vendorIn(0x8484, 0, 1); + vendorOut(0x0404, 1, null); + vendorIn(0x8484, 0, 1); + vendorIn(0x8383, 0, 1); + vendorOut(0, 1, null); + vendorOut(1, 0, null); + vendorOut(2, (mDeviceType == DeviceType.DEVICE_TYPE_01) ? 0x24 : 0x44, null); + } + + private void setControlLines(int newControlLinesValue) throws IOException { + ctrlOut(SET_CONTROL_REQUEST, newControlLinesValue, 0, null); + mControlLinesValue = newControlLinesValue; + } + + private void readStatusThreadFunction() { + try { + byte[] buffer = new byte[STATUS_BUFFER_SIZE]; + while (!mStopReadStatusThread) { + long endTime = MonotonicClock.millis() + 500; + int readBytesCount = mConnection.bulkTransfer(mInterruptEndpoint, buffer, STATUS_BUFFER_SIZE, 500); + if(readBytesCount == -1) + testConnection(MonotonicClock.millis() < endTime); + if (readBytesCount > 0) { + if (readBytesCount != STATUS_BUFFER_SIZE) { + throw new IOException("Invalid status notification, expected " + STATUS_BUFFER_SIZE + " bytes, got " + readBytesCount); + } else if(buffer[0] != (byte)STATUS_NOTIFICATION ) { + throw new IOException("Invalid status notification, expected " + STATUS_NOTIFICATION + " request, got " + buffer[0]); + } else { + mStatus = buffer[STATUS_BYTE_IDX] & 0xff; + } + } + } + } catch (Exception e) { + mReadStatusException = e; + } + //Log.d(TAG, "end control line status thread " + mStopReadStatusThread + " " + (mReadStatusException == null ? "-" : mReadStatusException.getMessage())); + } + + private int getStatus() throws IOException { + if (mReadStatusThread == null) { + synchronized (mReadStatusThreadLock) { + if (mReadStatusThread == null) { + mStatus = 0; + if(mDeviceType == DeviceType.DEVICE_TYPE_HXN) { + byte[] data = vendorIn(GET_CONTROL_HXN_REQUEST, 0, 1); + if ((data[0] & GET_CONTROL_HXN_FLAG_CTS) == 0) mStatus |= STATUS_FLAG_CTS; + if ((data[0] & GET_CONTROL_HXN_FLAG_DSR) == 0) mStatus |= STATUS_FLAG_DSR; + if ((data[0] & GET_CONTROL_HXN_FLAG_CD) == 0) mStatus |= STATUS_FLAG_CD; + if ((data[0] & GET_CONTROL_HXN_FLAG_RI) == 0) mStatus |= STATUS_FLAG_RI; + } else { + byte[] data = vendorIn(GET_CONTROL_REQUEST, 0, 1); + if ((data[0] & GET_CONTROL_FLAG_CTS) == 0) mStatus |= STATUS_FLAG_CTS; + if ((data[0] & GET_CONTROL_FLAG_DSR) == 0) mStatus |= STATUS_FLAG_DSR; + if ((data[0] & GET_CONTROL_FLAG_CD) == 0) mStatus |= STATUS_FLAG_CD; + if ((data[0] & GET_CONTROL_FLAG_RI) == 0) mStatus |= STATUS_FLAG_RI; + } + //Log.d(TAG, "start control line status thread " + mStatus); + mReadStatusThread = new Thread(this::readStatusThreadFunction); + mReadStatusThread.setDaemon(true); + mReadStatusThread.start(); + } + } + } + if (mReadStatusException != null) { + throw new IOException(mReadStatusException); + } + return mStatus; + } + + @Override + public void openInt() throws IOException { + UsbInterface usbInterface = mDevice.getInterface(0); + + if (!mConnection.claimInterface(usbInterface, true)) { + throw new IOException("Error claiming Prolific interface 0"); + } + + for (int i = 0; i < usbInterface.getEndpointCount(); ++i) { + UsbEndpoint currentEndpoint = usbInterface.getEndpoint(i); + + switch (currentEndpoint.getAddress()) { + case READ_ENDPOINT: + mReadEndpoint = currentEndpoint; + break; + + case WRITE_ENDPOINT: + mWriteEndpoint = currentEndpoint; + break; + + case INTERRUPT_ENDPOINT: + mInterruptEndpoint = currentEndpoint; + break; + } + } + + byte[] rawDescriptors = mConnection.getRawDescriptors(); + if(rawDescriptors == null || rawDescriptors.length < 14) { + throw new IOException("Could not get device descriptors"); + } + int usbVersion = (rawDescriptors[3] << 8) + rawDescriptors[2]; + int deviceVersion = (rawDescriptors[13] << 8) + rawDescriptors[12]; + byte maxPacketSize0 = rawDescriptors[7]; + if (mDevice.getDeviceClass() == 0x02 || maxPacketSize0 != 64) { + mDeviceType = DeviceType.DEVICE_TYPE_01; + } else if(usbVersion == 0x200) { + if(deviceVersion == 0x300 && testHxStatus()) { + mDeviceType = DeviceType.DEVICE_TYPE_T; // TA + } else if(deviceVersion == 0x500 && testHxStatus()) { + mDeviceType = DeviceType.DEVICE_TYPE_T; // TB + } else { + mDeviceType = DeviceType.DEVICE_TYPE_HXN; + } + } else { + mDeviceType = DeviceType.DEVICE_TYPE_HX; + } + Log.d(TAG, String.format("usbVersion=%x, deviceVersion=%x, deviceClass=%d, packetSize=%d => deviceType=%s", + usbVersion, deviceVersion, mDevice.getDeviceClass(), maxPacketSize0, mDeviceType.name())); + resetDevice(); + doBlackMagic(); + setControlLines(mControlLinesValue); + setFlowControl(mFlowControl); + } + + @Override + public void closeInt() { + try { + synchronized (mReadStatusThreadLock) { + if (mReadStatusThread != null) { + try { + mStopReadStatusThread = true; + mReadStatusThread.join(); + } catch (Exception e) { + Log.w(TAG, "An error occurred while waiting for status read thread", e); + } + mStopReadStatusThread = false; + mReadStatusThread = null; + mReadStatusException = null; + } + } + resetDevice(); + } catch(Exception ignored) {} + try { + mConnection.releaseInterface(mDevice.getInterface(0)); + } catch(Exception ignored) {} + } + + private int filterBaudRate(int baudRate) { + if (baudRate <= 0) { + throw new IllegalArgumentException("Invalid baud rate: " + baudRate); + } + if (mDeviceType == DeviceType.DEVICE_TYPE_HXN) { + return baudRate; + } + for(int br : standardBaudRates) { + if (br == baudRate) { + return baudRate; + } + } + /* + * Formula taken from Linux + FreeBSD. + * + * For TA+TB devices + * baudrate = baseline / (mantissa * 2^exponent) + * where + * mantissa = buf[10:0] + * exponent = buf[15:13 16] + * + * For other devices + * baudrate = baseline / (mantissa * 4^exponent) + * where + * mantissa = buf[8:0] + * exponent = buf[11:9] + * + */ + int baseline, mantissa, exponent, buf, effectiveBaudRate; + baseline = 12000000 * 32; + mantissa = baseline / baudRate; + if (mantissa == 0) { // > unrealistic 384 MBaud + throw new UnsupportedOperationException("Baud rate too high"); + } + exponent = 0; + if (mDeviceType == DeviceType.DEVICE_TYPE_T) { + while (mantissa >= 2048) { + if (exponent < 15) { + mantissa >>= 1; /* divide by 2 */ + exponent++; + } else { // < 7 baud + throw new UnsupportedOperationException("Baud rate too low"); + } + } + buf = mantissa + ((exponent & ~1) << 12) + ((exponent & 1) << 16) + (1 << 31); + effectiveBaudRate = (baseline / mantissa) >> exponent; + } else { + while (mantissa >= 512) { + if (exponent < 7) { + mantissa >>= 2; /* divide by 4 */ + exponent++; + } else { // < 45.8 baud + throw new UnsupportedOperationException("Baud rate too low"); + } + } + buf = mantissa + (exponent << 9) + (1 << 31); + effectiveBaudRate = (baseline / mantissa) >> (exponent << 1); + } + double baudRateError = Math.abs(1.0 - (effectiveBaudRate / (double)baudRate)); + if(baudRateError >= 0.031) // > unrealistic 11.6 Mbaud + throw new UnsupportedOperationException(String.format("Baud rate deviation %.1f%% is higher than allowed 3%%", baudRateError*100)); + + Log.d(TAG, String.format("baud rate=%d, effective=%d, error=%.1f%%, value=0x%08x, mantissa=%d, exponent=%d", + baudRate, effectiveBaudRate, baudRateError*100, buf, mantissa, exponent)); + return buf; + } + + @Override + public void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException { + baudRate = filterBaudRate(baudRate); + if ((mBaudRate == baudRate) && (mDataBits == dataBits) + && (mStopBits == stopBits) && (mParity == parity)) { + // Make sure no action is performed if there is nothing to change + return; + } + + byte[] lineRequestData = new byte[7]; + lineRequestData[0] = (byte) (baudRate & 0xff); + lineRequestData[1] = (byte) ((baudRate >> 8) & 0xff); + lineRequestData[2] = (byte) ((baudRate >> 16) & 0xff); + lineRequestData[3] = (byte) ((baudRate >> 24) & 0xff); + + switch (stopBits) { + case STOPBITS_1: + lineRequestData[4] = 0; + break; + case STOPBITS_1_5: + lineRequestData[4] = 1; + break; + case STOPBITS_2: + lineRequestData[4] = 2; + break; + default: + throw new IllegalArgumentException("Invalid stop bits: " + stopBits); + } + + switch (parity) { + case PARITY_NONE: + lineRequestData[5] = 0; + break; + case PARITY_ODD: + lineRequestData[5] = 1; + break; + case PARITY_EVEN: + lineRequestData[5] = 2; + break; + case PARITY_MARK: + lineRequestData[5] = 3; + break; + case PARITY_SPACE: + lineRequestData[5] = 4; + break; + default: + throw new IllegalArgumentException("Invalid parity: " + parity); + } + + if(dataBits < DATABITS_5 || dataBits > DATABITS_8) { + throw new IllegalArgumentException("Invalid data bits: " + dataBits); + } + lineRequestData[6] = (byte) dataBits; + + ctrlOut(SET_LINE_REQUEST, 0, 0, lineRequestData); + + resetDevice(); + + mBaudRate = baudRate; + mDataBits = dataBits; + mStopBits = stopBits; + mParity = parity; + } + + @Override + public boolean getCD() throws IOException { + return (getStatus() & STATUS_FLAG_CD) != 0; + } + + @Override + public boolean getCTS() throws IOException { + return (getStatus() & STATUS_FLAG_CTS) != 0; + } + + @Override + public boolean getDSR() throws IOException { + return (getStatus() & STATUS_FLAG_DSR) != 0; + } + + @Override + public boolean getDTR() throws IOException { + return (mControlLinesValue & CONTROL_DTR) != 0; + } + + @Override + public void setDTR(boolean value) throws IOException { + int newControlLinesValue; + if (value) { + newControlLinesValue = mControlLinesValue | CONTROL_DTR; + } else { + newControlLinesValue = mControlLinesValue & ~CONTROL_DTR; + } + setControlLines(newControlLinesValue); + } + + @Override + public boolean getRI() throws IOException { + return (getStatus() & STATUS_FLAG_RI) != 0; + } + + @Override + public boolean getRTS() throws IOException { + return (mControlLinesValue & CONTROL_RTS) != 0; + } + + @Override + public void setRTS(boolean value) throws IOException { + int newControlLinesValue; + if (value) { + newControlLinesValue = mControlLinesValue | CONTROL_RTS; + } else { + newControlLinesValue = mControlLinesValue & ~CONTROL_RTS; + } + setControlLines(newControlLinesValue); + } + + @Override + public EnumSet getControlLines() throws IOException { + int status = getStatus(); + EnumSet set = EnumSet.noneOf(ControlLine.class); + if((mControlLinesValue & CONTROL_RTS) != 0) set.add(ControlLine.RTS); + if((status & STATUS_FLAG_CTS) != 0) set.add(ControlLine.CTS); + if((mControlLinesValue & CONTROL_DTR) != 0) set.add(ControlLine.DTR); + if((status & STATUS_FLAG_DSR) != 0) set.add(ControlLine.DSR); + if((status & STATUS_FLAG_CD) != 0) set.add(ControlLine.CD); + if((status & STATUS_FLAG_RI) != 0) set.add(ControlLine.RI); + return set; + } + + @Override + public EnumSet getSupportedControlLines() throws IOException { + return EnumSet.allOf(ControlLine.class); + } + + @Override + public void setFlowControl(FlowControl flowControl) throws IOException { + // vendorOut values from https://www.mail-archive.com/linux-usb@vger.kernel.org/msg110968.html + switch (flowControl) { + case NONE: + if (mDeviceType == DeviceType.DEVICE_TYPE_HXN) + vendorOut(0x0a, 0xff, null); + else + vendorOut(0, 0, null); + break; + case RTS_CTS: + if (mDeviceType == DeviceType.DEVICE_TYPE_HXN) + vendorOut(0x0a, 0xfa, null); + else + vendorOut(0, 0x61, null); + break; + case XON_XOFF_INLINE: + if (mDeviceType == DeviceType.DEVICE_TYPE_HXN) + vendorOut(0x0a, 0xee, null); + else + vendorOut(0, 0xc1, null); + break; + default: + throw new UnsupportedOperationException(); + } + mFlowControl = flowControl; + } + + @Override + public EnumSet getSupportedFlowControl() { + return EnumSet.of(FlowControl.NONE, FlowControl.RTS_CTS, FlowControl.XON_XOFF_INLINE); + } + + @Override + public void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException { + if (mDeviceType == DeviceType.DEVICE_TYPE_HXN) { + int index = 0; + if(purgeWriteBuffers) index |= RESET_HXN_RX_PIPE; + if(purgeReadBuffers) index |= RESET_HXN_TX_PIPE; + if(index != 0) + vendorOut(RESET_HXN_REQUEST, index, null); + } else { + if (purgeWriteBuffers) + vendorOut(FLUSH_RX_REQUEST, 0, null); + if (purgeReadBuffers) + vendorOut(FLUSH_TX_REQUEST, 0, null); + } + } + + @Override + public void setBreak(boolean value) throws IOException { + ctrlOut(SEND_BREAK_REQUEST, value ? 0xffff : 0, 0, null); + } + } + + @SuppressWarnings({"unused"}) + public static Map getSupportedDevices() { + final Map supportedDevices = new LinkedHashMap<>(); + supportedDevices.put(UsbId.VENDOR_PROLIFIC, + new int[] { + UsbId.PROLIFIC_PL2303, + UsbId.PROLIFIC_PL2303GC, + UsbId.PROLIFIC_PL2303GB, + UsbId.PROLIFIC_PL2303GT, + UsbId.PROLIFIC_PL2303GL, + UsbId.PROLIFIC_PL2303GE, + UsbId.PROLIFIC_PL2303GS, + }); + return supportedDevices; + } +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/driver/SerialTimeoutException.java b/androidApp/src/main/java/com/hoho/android/usbserial/driver/SerialTimeoutException.java new file mode 100644 index 0000000..53304bc --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/driver/SerialTimeoutException.java @@ -0,0 +1,16 @@ +package com.hoho.android.usbserial.driver; + +import java.io.InterruptedIOException; + +/** + * Signals that a timeout has occurred on serial write. + * Similar to SocketTimeoutException. + * + * {@see InterruptedIOException#bytesTransferred} may contain bytes transferred + */ +public class SerialTimeoutException extends InterruptedIOException { + public SerialTimeoutException(String s, int bytesTransferred) { + super(s); + this.bytesTransferred = bytesTransferred; + } +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbId.java b/androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbId.java new file mode 100644 index 0000000..b265628 --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbId.java @@ -0,0 +1,56 @@ +/* Copyright 2011-2013 Google Inc. + * Copyright 2013 mike wakerly + * + * Project home page: https://github.com/mik3y/usb-serial-for-android + */ + +package com.hoho.android.usbserial.driver; + +/** + * Registry of USB vendor/product ID constants. + * + * Culled from various sources; see + * usb.ids for one listing. + * + * @author mike wakerly (opensource@hoho.com) + */ +public final class UsbId { + + public static final int VENDOR_FTDI = 0x0403; + public static final int FTDI_FT232R = 0x6001; + public static final int FTDI_FT2232H = 0x6010; + public static final int FTDI_FT4232H = 0x6011; + public static final int FTDI_FT232H = 0x6014; + public static final int FTDI_FT231X = 0x6015; // same ID for FT230X, FT231X, FT234XD + + public static final int VENDOR_SILABS = 0x10c4; + public static final int SILABS_CP2102 = 0xea60; // same ID for CP2101, CP2103, CP2104, CP2109 + public static final int SILABS_CP2105 = 0xea70; + public static final int SILABS_CP2108 = 0xea71; + + public static final int VENDOR_PROLIFIC = 0x067b; + public static final int PROLIFIC_PL2303 = 0x2303; // device type 01, T, HX + public static final int PROLIFIC_PL2303GC = 0x23a3; // device type HXN + public static final int PROLIFIC_PL2303GB = 0x23b3; // " + public static final int PROLIFIC_PL2303GT = 0x23c3; // " + public static final int PROLIFIC_PL2303GL = 0x23d3; // " + public static final int PROLIFIC_PL2303GE = 0x23e3; // " + public static final int PROLIFIC_PL2303GS = 0x23f3; // " + + public static final int VENDOR_GOOGLE = 0x18d1; + public static final int GOOGLE_CR50 = 0x5014; + + public static final int VENDOR_QINHENG = 0x1a86; + public static final int QINHENG_CH340 = 0x7523; + public static final int QINHENG_CH341A = 0x5523; + + public static final int VENDOR_UNISOC = 0x1782; + public static final int FIBOCOM_L610 = 0x4D10; + public static final int FIBOCOM_L612 = 0x4D12; + + + private UsbId() { + throw new IllegalAccessError("Non-instantiable class"); + } + +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java b/androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java new file mode 100644 index 0000000..78c1665 --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java @@ -0,0 +1,38 @@ +/* Copyright 2011-2013 Google Inc. + * Copyright 2013 mike wakerly + * + * Project home page: https://github.com/mik3y/usb-serial-for-android + */ + +package com.hoho.android.usbserial.driver; + +import android.hardware.usb.UsbDevice; + +import java.util.List; + +public interface UsbSerialDriver { + + /* + * Additional interface properties. Invoked thru reflection. + * + UsbSerialDriver(UsbDevice device); // constructor with device + static Map getSupportedDevices(); + static boolean probe(UsbDevice device); // optional + */ + + + /** + * Returns the raw {@link UsbDevice} backing this port. + * + * @return the device + */ + UsbDevice getDevice(); + + /** + * Returns all available ports for this device. This list must have at least + * one entry. + * + * @return the ports + */ + List getPorts(); +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialPort.java b/androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialPort.java new file mode 100644 index 0000000..567e45a --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialPort.java @@ -0,0 +1,341 @@ +/* Copyright 2011-2013 Google Inc. + * Copyright 2013 mike wakerly + * + * Project home page: https://github.com/mik3y/usb-serial-for-android + */ + +package com.hoho.android.usbserial.driver; + +import android.hardware.usb.UsbDevice; +import android.hardware.usb.UsbDeviceConnection; +import android.hardware.usb.UsbEndpoint; +import android.hardware.usb.UsbManager; + +import androidx.annotation.IntDef; + +import java.io.Closeable; +import java.io.IOException; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.util.EnumSet; + +/** + * Interface for a single serial port. + * + * @author mike wakerly (opensource@hoho.com) + */ +public interface UsbSerialPort extends Closeable { + + /** 5 data bits. */ + int DATABITS_5 = 5; + /** 6 data bits. */ + int DATABITS_6 = 6; + /** 7 data bits. */ + int DATABITS_7 = 7; + /** 8 data bits. */ + int DATABITS_8 = 8; + + /** Values for setParameters(..., parity) */ + @Retention(RetentionPolicy.SOURCE) + @IntDef({PARITY_NONE, PARITY_ODD, PARITY_EVEN, PARITY_MARK, PARITY_SPACE}) + @interface Parity {} + /** No parity. */ + int PARITY_NONE = 0; + /** Odd parity. */ + int PARITY_ODD = 1; + /** Even parity. */ + int PARITY_EVEN = 2; + /** Mark parity. */ + int PARITY_MARK = 3; + /** Space parity. */ + int PARITY_SPACE = 4; + + /** 1 stop bit. */ + int STOPBITS_1 = 1; + /** 1.5 stop bits. */ + int STOPBITS_1_5 = 3; + /** 2 stop bits. */ + int STOPBITS_2 = 2; + + /** Values for get[Supported]ControlLines() */ + enum ControlLine { RTS, CTS, DTR, DSR, CD, RI } + + /** Values for (set|get|getSupported)FlowControl() */ + enum FlowControl { NONE, RTS_CTS, DTR_DSR, XON_XOFF, XON_XOFF_INLINE } + + /** XON character used with flow control XON/XOFF */ + char CHAR_XON = 17; + /** XOFF character used with flow control XON/XOFF */ + char CHAR_XOFF = 19; + + + /** + * Returns the driver used by this port. + */ + UsbSerialDriver getDriver(); + + /** + * Returns the currently-bound USB device. + */ + UsbDevice getDevice(); + + /** + * Port number within driver. + */ + int getPortNumber(); + + /** + * Returns the write endpoint. + * @return write endpoint + */ + UsbEndpoint getWriteEndpoint(); + + /** + * Returns the read endpoint. + * @return read endpoint + */ + UsbEndpoint getReadEndpoint(); + + /** + * The serial number of the underlying UsbDeviceConnection, or {@code null}. + * + * @return value from {@link UsbDeviceConnection#getSerial()} + * @throws SecurityException starting with target SDK 29 (Android 10) if permission for USB device is not granted + */ + String getSerial(); + + /** + * Applications doing permanent {@link #read} with timeout=0 can reduce data loss likelihood + * at high baud rate and continuous data transfer by using multiple buffers to copy next data + * from Linux kernel, while the current data is processed. + * When enabled, {@link #read} can not be called with timeout!=0 or different buffer size. + * + * @param bufferCount number of buffers to use for readQueue. + * Use 0 to disable. + * @param bufferSize size of each buffer. + * Use 0 for optimal size (= getReadEndpoint().getMaxPacketSize()). + * @throws IllegalStateException if port is open and buffer count should be lowered or + * buffer size should be changed. + */ + void setReadQueue(int bufferCount, int bufferSize); + int getReadQueueBufferCount(); + int getReadQueueBufferSize(); + + /** + * Opens and initializes the port. Upon success, caller must ensure that + * {@link #close()} is eventually called. + * + * @param connection an open device connection, acquired with + * {@link UsbManager#openDevice(android.hardware.usb.UsbDevice)} + * @throws IOException on error opening or initializing the port. + */ + void open(UsbDeviceConnection connection) throws IOException; + + /** + * Closes the port and {@link UsbDeviceConnection} + * + * @throws IOException on error closing the port. + */ + void close() throws IOException; + + /** + * Reads as many bytes as possible into the destination buffer. + * + * @param dest the destination byte buffer + * @param timeout the timeout for reading in milliseconds, 0 is infinite + * @return the actual number of bytes read + * @throws IOException if an error occurred during reading + */ + int read(final byte[] dest, final int timeout) throws IOException; + + /** + * Reads bytes with specified length into the destination buffer. + * + * @param dest the destination byte buffer + * @param length the maximum length of the data to read + * @param timeout the timeout for reading in milliseconds, 0 is infinite + * @return the actual number of bytes read + * @throws IOException if an error occurred during reading + */ + int read(final byte[] dest, int length, final int timeout) throws IOException; + + /** + * Writes as many bytes as possible from the source buffer. + * + * @param src the source byte buffer + * @param timeout the timeout for writing in milliseconds, 0 is infinite + * @throws SerialTimeoutException if timeout reached before sending all data. + * ex.bytesTransferred may contain bytes transferred + * @throws IOException if an error occurred during writing + */ + void write(final byte[] src, final int timeout) throws IOException; + + /** + * Writes bytes with specified length from the source buffer. + * + * @param src the source byte buffer + * @param length the length of the data to write + * @param timeout the timeout for writing in milliseconds, 0 is infinite + * @throws SerialTimeoutException if timeout reached before sending all data. + * ex.bytesTransferred may contain bytes transferred + * @throws IOException if an error occurred during writing + */ + void write(final byte[] src, int length, final int timeout) throws IOException; + + /** + * Sets various serial port parameters. + * + * @param baudRate baud rate as an integer, for example {@code 115200}. + * @param dataBits one of {@link #DATABITS_5}, {@link #DATABITS_6}, + * {@link #DATABITS_7}, or {@link #DATABITS_8}. + * @param stopBits one of {@link #STOPBITS_1}, {@link #STOPBITS_1_5}, or {@link #STOPBITS_2}. + * @param parity one of {@link #PARITY_NONE}, {@link #PARITY_ODD}, + * {@link #PARITY_EVEN}, {@link #PARITY_MARK}, or {@link #PARITY_SPACE}. + * @throws IOException on error setting the port parameters + * @throws UnsupportedOperationException if not supported or values are not supported by a specific device + */ + void setParameters(int baudRate, int dataBits, int stopBits, @Parity int parity) throws IOException; + + /** + * Gets the CD (Carrier Detect) bit from the underlying UART. + * + * @return the current state + * @throws IOException if an error occurred during reading + * @throws UnsupportedOperationException if not supported + */ + boolean getCD() throws IOException; + + /** + * Gets the CTS (Clear To Send) bit from the underlying UART. + * + * @return the current state + * @throws IOException if an error occurred during reading + * @throws UnsupportedOperationException if not supported + */ + boolean getCTS() throws IOException; + + /** + * Gets the DSR (Data Set Ready) bit from the underlying UART. + * + * @return the current state + * @throws IOException if an error occurred during reading + * @throws UnsupportedOperationException if not supported + */ + boolean getDSR() throws IOException; + + /** + * Gets the DTR (Data Terminal Ready) bit from the underlying UART. + * + * @return the current state + * @throws IOException if an error occurred during reading + * @throws UnsupportedOperationException if not supported + */ + boolean getDTR() throws IOException; + + /** + * Sets the DTR (Data Terminal Ready) bit on the underlying UART, if supported. + * + * @param value the value to set + * @throws IOException if an error occurred during writing + * @throws UnsupportedOperationException if not supported + */ + void setDTR(boolean value) throws IOException; + + /** + * Gets the RI (Ring Indicator) bit from the underlying UART. + * + * @return the current state + * @throws IOException if an error occurred during reading + * @throws UnsupportedOperationException if not supported + */ + boolean getRI() throws IOException; + + /** + * Gets the RTS (Request To Send) bit from the underlying UART. + * + * @return the current state + * @throws IOException if an error occurred during reading + * @throws UnsupportedOperationException if not supported + */ + boolean getRTS() throws IOException; + + /** + * Sets the RTS (Request To Send) bit on the underlying UART, if supported. + * + * @param value the value to set + * @throws IOException if an error occurred during writing + * @throws UnsupportedOperationException if not supported + */ + void setRTS(boolean value) throws IOException; + + /** + * Gets all control line values from the underlying UART, if supported. + * Requires less USB calls than calling getRTS() + ... + getRI() individually. + * + * @return EnumSet.contains(...) is {@code true} if set, else {@code false} + * @throws IOException if an error occurred during reading + * @throws UnsupportedOperationException if not supported + */ + EnumSet getControlLines() throws IOException; + + /** + * Gets all control line supported flags. + * + * @return EnumSet.contains(...) is {@code true} if supported, else {@code false} + * @throws IOException if an error occurred during reading + */ + EnumSet getSupportedControlLines() throws IOException; + + /** + * Set flow control mode, if supported + * @param flowControl @FlowControl + * @throws IOException if an error occurred during writing + * @throws UnsupportedOperationException if not supported + */ + void setFlowControl(FlowControl flowControl) throws IOException; + + /** + * Get flow control mode. + * @return FlowControl + */ + FlowControl getFlowControl(); + + /** + * Get supported flow control modes + * @return EnumSet.contains(...) is {@code true} if supported, else {@code false} + */ + EnumSet getSupportedFlowControl(); + + /** + * If flow control = XON_XOFF, indicates that send is enabled by XON. + * Devices supporting flow control = XON_XOFF_INLINE return CHAR_XON/CHAR_XOFF in read() data. + * + * @return the current state + * @throws IOException if an error occurred during reading + * @throws UnsupportedOperationException if not supported + */ + boolean getXON() throws IOException; + + /** + * Purge non-transmitted output data and / or non-read input data. + * + * @param purgeWriteBuffers {@code true} to discard non-transmitted output data + * @param purgeReadBuffers {@code true} to discard non-read input data + * @throws IOException if an error occurred during flush + * @throws UnsupportedOperationException if not supported + */ + void purgeHwBuffers(boolean purgeWriteBuffers, boolean purgeReadBuffers) throws IOException; + + /** + * send BREAK condition. + * + * @param value set/reset + */ + void setBreak(boolean value) throws IOException; + + /** + * Returns the current state of the connection. + */ + boolean isOpen(); + +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/util/HexDump.java b/androidApp/src/main/java/com/hoho/android/usbserial/util/HexDump.java new file mode 100644 index 0000000..ddf8f0f --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/util/HexDump.java @@ -0,0 +1,158 @@ +/* + * Copyright (C) 2006 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.hoho.android.usbserial.util; + +import java.security.InvalidParameterException; + +/** + * Clone of Android's /core/java/com/android/internal/util/HexDump class, for use in debugging. + * Changes: space separated hex strings + */ +public class HexDump { + private final static char[] HEX_DIGITS = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' + }; + + private HexDump() { + } + + public static String dumpHexString(byte[] array) { + return dumpHexString(array, 0, array.length); + } + + public static String dumpHexString(byte[] array, int offset, int length) { + StringBuilder result = new StringBuilder(); + + byte[] line = new byte[8]; + int lineIndex = 0; + + for (int i = offset; i < offset + length; i++) { + if (lineIndex == line.length) { + for (int j = 0; j < line.length; j++) { + if (line[j] > ' ' && line[j] < '~') { + result.append(new String(line, j, 1)); + } else { + result.append("."); + } + } + + result.append("\n"); + lineIndex = 0; + } + + byte b = array[i]; + result.append(HEX_DIGITS[(b >>> 4) & 0x0F]); + result.append(HEX_DIGITS[b & 0x0F]); + result.append(" "); + + line[lineIndex++] = b; + } + + for (int i = 0; i < (line.length - lineIndex); i++) { + result.append(" "); + } + for (int i = 0; i < lineIndex; i++) { + if (line[i] > ' ' && line[i] < '~') { + result.append(new String(line, i, 1)); + } else { + result.append("."); + } + } + + return result.toString(); + } + + public static String toHexString(byte b) { + return toHexString(toByteArray(b)); + } + + public static String toHexString(byte[] array) { + return toHexString(array, 0, array.length); + } + + public static String toHexString(byte[] array, int offset, int length) { + char[] buf = new char[length > 0 ? length * 3 - 1 : 0]; + + int bufIndex = 0; + for (int i = offset; i < offset + length; i++) { + if (i > offset) + buf[bufIndex++] = ' '; + byte b = array[i]; + buf[bufIndex++] = HEX_DIGITS[(b >>> 4) & 0x0F]; + buf[bufIndex++] = HEX_DIGITS[b & 0x0F]; + } + + return new String(buf); + } + + public static String toHexString(int i) { + return toHexString(toByteArray(i)); + } + + public static String toHexString(short i) { + return toHexString(toByteArray(i)); + } + + public static byte[] toByteArray(byte b) { + byte[] array = new byte[1]; + array[0] = b; + return array; + } + + public static byte[] toByteArray(int i) { + byte[] array = new byte[4]; + + array[3] = (byte) (i & 0xFF); + array[2] = (byte) ((i >> 8) & 0xFF); + array[1] = (byte) ((i >> 16) & 0xFF); + array[0] = (byte) ((i >> 24) & 0xFF); + + return array; + } + + public static byte[] toByteArray(short i) { + byte[] array = new byte[2]; + + array[1] = (byte) (i & 0xFF); + array[0] = (byte) ((i >> 8) & 0xFF); + + return array; + } + + private static int toByte(char c) { + if (c >= '0' && c <= '9') + return (c - '0'); + if (c >= 'A' && c <= 'F') + return (c - 'A' + 10); + if (c >= 'a' && c <= 'f') + return (c - 'a' + 10); + + throw new InvalidParameterException("Invalid hex char '" + c + "'"); + } + + /** accepts any separator, e.g. space or newline */ + public static byte[] hexStringToByteArray(String hexString) { + int length = hexString.length(); + byte[] buffer = new byte[(length + 1) / 3]; + + for (int i = 0; i < length; i += 3) { + buffer[i / 3] = (byte) ((toByte(hexString.charAt(i)) << 4) | toByte(hexString.charAt(i + 1))); + } + + return buffer; + } +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java b/androidApp/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java new file mode 100644 index 0000000..befc3dc --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java @@ -0,0 +1,14 @@ +package com.hoho.android.usbserial.util; + +public final class MonotonicClock { + + private static final long NS_PER_MS = 1_000_000; + + private MonotonicClock() { + } + + public static long millis() { + return System.nanoTime() / NS_PER_MS; + } + +} diff --git a/androidApp/src/main/java/com/hoho/android/usbserial/util/UsbUtils.java b/androidApp/src/main/java/com/hoho/android/usbserial/util/UsbUtils.java new file mode 100644 index 0000000..e019ef1 --- /dev/null +++ b/androidApp/src/main/java/com/hoho/android/usbserial/util/UsbUtils.java @@ -0,0 +1,37 @@ +package com.hoho.android.usbserial.util; + +import android.hardware.usb.UsbDeviceConnection; + +import java.util.ArrayList; + +public class UsbUtils { + + // copied from java.util.function.Supplier which is not available < API 24 + public interface Supplier { + T get(); + } + + private UsbUtils() { + } + + public static ArrayList getDescriptors(UsbDeviceConnection connection) { + ArrayList descriptors = new ArrayList<>(); + byte[] rawDescriptors = connection.getRawDescriptors(); + if (rawDescriptors != null) { + int pos = 0; + while (pos < rawDescriptors.length) { + int len = rawDescriptors[pos] & 0xFF; + if (len == 0) + break; + if (pos + len > rawDescriptors.length) + len = rawDescriptors.length - pos; + byte[] descriptor = new byte[len]; + System.arraycopy(rawDescriptors, pos, descriptor, 0, len); + descriptors.add(descriptor); + pos += len; + } + } + return descriptors; + } + +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/MainActivity.kt b/androidApp/src/main/kotlin/cz/netkit/app/MainActivity.kt index 118f25b..ffdfbbc 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/MainActivity.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/MainActivity.kt @@ -12,8 +12,38 @@ import androidx.compose.ui.geometry.Offset import androidx.compose.ui.draw.drawBehind import androidx.compose.animation.togetherWith import androidx.compose.animation.AnimatedContent +import android.widget.Toast +import androidx.compose.ui.platform.LocalContext +import android.content.res.Configuration +import androidx.compose.material3.NavigationRail +import androidx.compose.material3.NavigationRailItem +import androidx.compose.material3.NavigationRailItemDefaults +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalWindowInfo +import androidx.compose.ui.graphics.vector.ImageVector +import cz.netkit.shared.nav.navigationPlacement +import cz.netkit.shared.nav.NavigationPlacement +import android.content.Intent import android.os.Bundle -import androidx.activity.ComponentActivity +import androidx.compose.runtime.LaunchedEffect +import androidx.lifecycle.lifecycleScope +import cz.netkit.app.wol.NetKitApplication +import cz.netkit.app.cellular.CellDetailViewModel +import cz.netkit.shared.nav.APP_TARGET_ACTION +import cz.netkit.shared.nav.APP_TARGET_EXTRA +import cz.netkit.shared.nav.AppTarget +import cz.netkit.shared.nav.parseAppTarget +import cz.netkit.shared.nav.resolveAppTarget +import cz.netkit.shared.wol.wolDeviceByKey +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.launch +import androidx.fragment.app.FragmentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.annotation.StringRes @@ -54,6 +84,7 @@ import cz.netkit.app.wifi.live.WifiLiveViewModel import cz.netkit.app.lan.DevicesScreen import cz.netkit.app.lan.LanDevicesViewModel import cz.netkit.app.lan.LanTool +import cz.netkit.app.lan.LanWolBridge import cz.netkit.app.ui.SegmentedTabs import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.platform.testTag @@ -68,8 +99,13 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import cz.netkit.app.ui.theme.NetKitTheme +import androidx.activity.compose.BackHandler +import cz.netkit.app.settings.SettingsHost +import cz.netkit.app.settings.SettingsScreen +import cz.netkit.app.settings.SettingsViewModel +import cz.netkit.shared.settings.tabBackTarget -class MainActivity : ComponentActivity() { +class MainActivity : FragmentActivity() { private val wol by lazy { ViewModelProvider(this)[WolViewModel::class.java] } private val lan by lazy { ViewModelProvider(this)[LanViewModel::class.java] } @@ -77,9 +113,11 @@ class MainActivity : ComponentActivity() { private val live by lazy { ViewModelProvider(this)[WifiLiveViewModel::class.java] } private val devices by lazy { ViewModelProvider(this)[LanDevicesViewModel::class.java] } private val speed by lazy { ViewModelProvider(this)[SpeedTestViewModel::class.java] } + private val cellDetail by lazy { ViewModelProvider(this)[CellDetailViewModel::class.java] } private val ssh by lazy { ViewModelProvider(this)[SshViewModel::class.java] } private val update by lazy { ViewModelProvider(this)[UpdateViewModel::class.java] } + private val settings by lazy { ViewModelProvider(this)[SettingsViewModel::class.java] } override fun onStop() { wifi.setScreenActive(false) @@ -109,13 +147,62 @@ class MainActivity : ComponentActivity() { super.onDestroy() } + /** Pending external navigation (zadání 36 §2.1); consumed by [NetKitApp] once applied. */ + private val navRequest = mutableStateOf(null) + private var navSequence = 0L + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() - setContent { NetKitTheme { NetKitApp(wol, lan, wifi, live, devices, ssh, speed, update) } } + // A recreated activity (rotation, restored process) keeps its saved tab instead of replaying the intent. + if (savedInstanceState == null) handleNavigation(intent) + setContent { SettingsHost(settings, this) { NetKitApp(wol, lan, wifi, live, devices, ssh, speed, update, + navRequest = navRequest.value, onNavigationConsumed = { navRequest.value = null }, settings = settings, + cellDetail = cellDetail) } } + } + + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handleNavigation(intent) + } + + /** + * MainActivity is exported: any app may send [APP_TARGET_ACTION]. Only whitelisted targets are + * accepted, record IDs must exist locally, and nothing runs without a further tap by the user. + * Anything else (unknown target, missing record) opens the default tab. + */ + private fun handleNavigation(intent: Intent?) { + if (intent?.action != APP_TARGET_ACTION) return + val raw = try { intent.getStringExtra(APP_TARGET_EXTRA) } catch (_: RuntimeException) { null } // malformed extras + val target = parseAppTarget(raw) + val sequence = ++navSequence + lifecycleScope.launch { + val app = application as NetKitApplication + var wolDeviceId: String? = null + val resolved = when (target) { + is AppTarget.SshProfile -> resolveAppTarget(target, recordIds { app.sshStore.read().profiles.map { it.id } }, null) + // The target carries the opaque device key; the local ID never leaves the app. + // An ambiguous key (two devices) opens nothing specific: default tab. + is AppTarget.WolDevice -> recordIds { listOfNotNull(wolDeviceByKey(app.devices.load(), target.key)?.id) } + ?.singleOrNull()?.let { id -> wolDeviceId = id; target } + else -> target + } + if (sequence == navSequence) navRequest.value = NavRequest(resolved, sequence, wolDeviceId) + } } + + /** Unreadable store (corrupt, I/O) counts as "no such record". */ + private suspend fun recordIds(read: suspend () -> List): List? = + try { read() } catch (e: CancellationException) { throw e } catch (_: Exception) { null } } +/** + * One external navigation request; null [target] means the default tab. [sequence] makes repeats distinct. + * [wolDeviceId] is the local ID resolved from the opaque key of a WoL target. + */ +data class NavRequest(val target: AppTarget?, val sequence: Long, val wolDeviceId: String? = null) + /** Test tags keep the M1 names: Spektrum is the former Wi-Fi tab, Zařízení the former LAN tab. */ private enum class Destination(@param:StringRes val label: Int, val tag: String) { SIGNAL(R.string.tab_signal, "tab_signal"), @@ -125,17 +212,53 @@ private enum class Destination(@param:StringRes val label: Int, val tag: String) WOL(R.string.tab_wol, "tab_wol"), } +private val Destination.icon: ImageVector get() = when (this) { + Destination.SIGNAL -> NetKitIcons.Signal + Destination.SPECTRUM -> NetKitIcons.Spectrum + Destination.DEVICES -> NetKitIcons.Devices + Destination.SSH -> NetKitIcons.Terminal + Destination.WOL -> NetKitIcons.Power +} + +@Composable +private fun SideNavigation(destination: Destination, onOpen: (Destination) -> Unit) { + val colors = NetKitTheme.colors + // Scaffold already applied system bar insets. Keep all destinations reachable on short windows. + NavigationRail(modifier = Modifier.testTag("nav_rail"), containerColor = colors.navBackground, + windowInsets = WindowInsets(0, 0, 0, 0)) { + Column(Modifier.verticalScroll(rememberScrollState())) { + Destination.entries.forEach { item -> + NavigationRailItem(selected = destination == item, onClick = { onOpen(item) }, + modifier = Modifier.testTag(item.tag), icon = { Icon(item.icon, null) }, + label = { NavLabel(stringResource(item.label)) }, + colors = NavigationRailItemDefaults.colors(selectedIconColor = colors.accent, + selectedTextColor = colors.text, indicatorColor = colors.accentSoft, + unselectedIconColor = colors.dim, unselectedTextColor = colors.dim)) + } + } + } +} + @OptIn(ExperimentalComposeUiApi::class) @Composable fun NetKitApp(wol: WolViewModel, lan: LanViewModel, wifi: WifiViewModel, live: WifiLiveViewModel, - devices: LanDevicesViewModel, ssh: SshViewModel, speed: SpeedTestViewModel, update: UpdateViewModel) { + devices: LanDevicesViewModel, ssh: SshViewModel, speed: SpeedTestViewModel, update: UpdateViewModel, + navRequest: NavRequest? = null, onNavigationConsumed: () -> Unit = {}, settings: SettingsViewModel? = null, + cellDetail: CellDetailViewModel? = null) { var selectedTab by rememberSaveable { mutableIntStateOf(0) } var lanSegment by rememberSaveable { mutableIntStateOf(0) } var sshPrefillHost by rememberSaveable { mutableStateOf(null) } + // From a pinned shortcut: the profile whose connect confirmation is shown (never connects by itself). + var sshConnectId by rememberSaveable { mutableStateOf(null) } + // From a pinned shortcut or the widget: the WoL device to highlight with its "Wake" button. + var wolHighlightId by rememberSaveable { mutableStateOf(null) } // About is a subscreen of Přehled (zadání 21): any tab tap, Přehled included, closes it. var aboutOpen by rememberSaveable { mutableStateOf(false) } // Open-source licences, a subscreen of About; closed together with About. var licensesOpen by rememberSaveable { mutableStateOf(false) } + // Settings (zadání 46), a subscreen of Přehled like About; back returns to where it was opened from. + var backupOpen by rememberSaveable { mutableStateOf(false) } + var settingsOpen by rememberSaveable { mutableStateOf(false) } val updateState by update.state.collectAsStateWithLifecycle() updateState.dialog?.let { info -> UpdateDialog(info, onClose = update::closeDialog, onDismissVersion = { update.dismiss(info) }) @@ -143,13 +266,42 @@ fun NetKitApp(wol: WolViewModel, lan: LanViewModel, wifi: WifiViewModel, live: W val destination = Destination.entries[selectedTab] val savedTabs = rememberSaveableStateHolder() val sshState by ssh.state.collectAsStateWithLifecycle() + val context = LocalContext.current + val wolState by wol.controller.state.collectAsStateWithLifecycle() val divider = NetKitTheme.colors.divider fun open(target: Destination) { if (selectedTab != target.ordinal) { lan.cancelActive(); wifi.cancelActive() } selectedTab = target.ordinal aboutOpen = false licensesOpen = false + backupOpen = false + settingsOpen = false + if (target != Destination.WOL) wolHighlightId = null + } + LaunchedEffect(navRequest) { + val request = navRequest ?: return@LaunchedEffect + when (val target = request.target) { + null, AppTarget.Signal -> open(Destination.SIGNAL) + AppTarget.Spectrum -> open(Destination.SPECTRUM) + // SSH session notification (zadání 42): the tab only, never a session action. + AppTarget.Ssh -> open(Destination.SSH) + is AppTarget.LanTools -> { + open(Destination.DEVICES) + lan.tool(LanTool.valueOf(target.tool.name)) + lanSegment = 1 + } + is AppTarget.SshProfile -> { ssh.access.leave(); open(Destination.SSH); sshConnectId = target.id } + is AppTarget.WolDevice -> { open(Destination.WOL); wolHighlightId = request.wolDeviceId } + } + onNavigationConsumed() } + // Predictive back (zadání 46 §2): another tab goes back to Přehled. Registered before the screens, + // so their own handlers (subscreens, editors, details, dialogs) take precedence. + BackHandler(enabled = tabBackTarget(selectedTab) != null) { tabBackTarget(selectedTab)?.let { open(Destination.entries[it]) } } + var terminalVisible by remember { mutableStateOf(false) } + val landscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE + val windowWidthDp = with(LocalDensity.current) { LocalWindowInfo.current.containerSize.width.toDp().value.toInt() } + val placement = navigationPlacement(windowWidthDp, landscape, destination == Destination.SSH && terminalVisible) Scaffold( modifier = Modifier.semantics { testTagsAsResourceId = BuildConfig.DEBUG }, containerColor = NetKitTheme.colors.background, @@ -164,9 +316,9 @@ fun NetKitApp(wol: WolViewModel, lan: LanViewModel, wifi: WifiViewModel, live: W } }, bottomBar = { - NavigationBar( + if (placement == NavigationPlacement.BOTTOM) NavigationBar( // A hairline instead of elevation keeps the flat M3 layers (docs/design.md §5). - Modifier.drawBehind { drawLine(divider, Offset.Zero, Offset(size.width, 0f), 1.dp.toPx()) }, + Modifier.testTag("nav_bottom").drawBehind { drawLine(divider, Offset.Zero, Offset(size.width, 0f), 1.dp.toPx()) }, containerColor = NetKitTheme.colors.navBackground, tonalElevation = 0.dp, ) { Destination.entries.forEach { item -> @@ -174,52 +326,73 @@ fun NetKitApp(wol: WolViewModel, lan: LanViewModel, wifi: WifiViewModel, live: W modifier = Modifier.testTag(item.tag), selected = destination == item, onClick = { open(item) }, - icon = { Icon(when(item) { - Destination.SIGNAL -> NetKitIcons.Signal - Destination.SPECTRUM -> NetKitIcons.Spectrum - Destination.DEVICES -> NetKitIcons.Devices - Destination.SSH -> NetKitIcons.Terminal - Destination.WOL -> NetKitIcons.Power - }, contentDescription = null) }, + icon = { Icon(item.icon, contentDescription = null) }, label = { NavLabel(stringResource(item.label)) }, colors = NavigationBarItemDefaults.colors( selectedIconColor = NetKitTheme.colors.accent, selectedTextColor = NetKitTheme.colors.text, indicatorColor = NetKitTheme.colors.accentSoft, - unselectedIconColor = NetKitTheme.colors.dim, unselectedTextColor = NetKitTheme.colors.dim, + unselectedIconColor = NetKitTheme.colors.dim, unselectedTextColor = NetKitTheme.colors.muted, ), ) } } }, ) { padding -> - val screen = Modifier.padding(padding).consumeWindowInsets(padding) - val enter = rememberNetKitEnter(); val exit = rememberNetKitExit() - AnimatedContent(destination, transitionSpec = { enter togetherWith exit }, label = "tab") { shown -> - savedTabs.SaveableStateProvider(shown.name) { - when (shown) { - Destination.SIGNAL -> if (aboutOpen && licensesOpen) OssLicensesScreen(onBack = { licensesOpen = false }, screen) - else if (aboutOpen) AboutScreen(update, onBack = { aboutOpen = false }, onOpenLicenses = { licensesOpen = true }, screen) - else SignalHost(live, speed, screen, - updateCard = updateState.card?.let { info -> { UpdateCard(info, onDismiss = { update.dismiss(info) }) } }, - onOpenAbout = { aboutOpen = true }) - Destination.SPECTRUM -> WifiScreen(wifi, screen) - Destination.DEVICES -> Column(screen) { - SegmentedTabs(listOf(stringResource(R.string.lan_segment_devices), stringResource(R.string.lan_segment_tools)), - // Leaving Tools stops its run, as leaving the tab does, so the two scanners never overlap. - lanSegment, { if (it != lanSegment && lanSegment == 1) lan.cancelActive(); lanSegment = it }, - Modifier.padding(horizontal = Spacing.normal, vertical = Spacing.small), - testTags = listOf("lan_segment_devices", "lan_segment_tools")) - if (lanSegment == 0) DevicesScreen(devices, - onTrace = { address -> lan.host(address); lan.tool(LanTool.TRACE); lanSegment = 1 }, - onSsh = { address -> sshPrefillHost = address; open(Destination.SSH) }, - modifier = Modifier.weight(1f)) - else LanScreen(lan, Modifier.weight(1f)) + Row(Modifier.fillMaxSize().padding(padding).consumeWindowInsets(padding)) { + if (placement == NavigationPlacement.RAIL) SideNavigation(destination, ::open) + val screen = Modifier.fillMaxSize() + val enter = rememberNetKitEnter(); val exit = rememberNetKitExit() + AnimatedContent(destination, transitionSpec = { enter togetherWith exit }, label = "tab") { shown -> + savedTabs.SaveableStateProvider(shown.name) { + when (shown) { + Destination.SIGNAL -> if (settingsOpen && backupOpen) + cz.netkit.app.backup.BackupScreen(ssh, canClose = { + ssh.canCloseForRestore() && !speed.state.value.running && !devices.state.value.scan.running && + !lan.state.value.busy && live.state.value.walk.status != cz.netkit.shared.wifi.WalkStatus.RECORDING && + with(wol.controller.state.value) { !saving && sendingDeviceId == null && draft == null } + }, onBack = { backupOpen = false }, screen) + else if (settingsOpen && settings != null) + SettingsScreen(settings, update, live, speed, devices, lan, onBack = { settingsOpen = false }, screen, onBackup = { backupOpen = true }) + else if (aboutOpen && licensesOpen) OssLicensesScreen(onBack = { licensesOpen = false }, screen) + else if (aboutOpen) AboutScreen(update, onBack = { aboutOpen = false }, onOpenLicenses = { licensesOpen = true }, + onOpenSettings = { settingsOpen = true }, screen) + else SignalHost(live, speed, screen, + updateCard = updateState.card?.let { info -> { UpdateCard(info, onDismiss = { update.dismiss(info) }) } }, + onOpenAbout = { aboutOpen = true }, onOpenSettings = { settingsOpen = true }.takeIf { settings != null }, + cellDetail = cellDetail, onRdap = { target -> + if (lan.state.value.busy) { + Toast.makeText(context, R.string.diag_rdap_busy, Toast.LENGTH_SHORT).show() + } else { + open(Destination.DEVICES) + lanSegment = 1 + lan.tool(LanTool.RDAP) + lan.diagnosticInput(target) + } + }) + Destination.SPECTRUM -> WifiScreen(wifi, screen) + Destination.DEVICES -> Column(screen) { + SegmentedTabs(listOf(stringResource(R.string.lan_segment_devices), stringResource(R.string.lan_segment_tools)), + // Leaving Tools stops its run, as leaving the tab does, so the two scanners never overlap. + lanSegment, { if (it != lanSegment && lanSegment == 1) lan.cancelActive(); lanSegment = it }, + Modifier.padding(horizontal = Spacing.normal, vertical = Spacing.small), + testTags = listOf("lan_segment_devices", "lan_segment_tools")) + if (lanSegment == 0) DevicesScreen(devices, + onTrace = { address -> lan.host(address); lan.tool(LanTool.TRACE); lanSegment = 1 }, + onSsh = { address -> sshPrefillHost = address; open(Destination.SSH) }, + modifier = Modifier.weight(1f), + // WoL from the device detail (zadání 36 §2.7): wake a saved device or open a prefilled form. + wol = LanWolBridge(wolState, onWake = wol.controller::wake, + onAdd = { draft -> wol.add(draft); if (wol.controller.state.value.draft != null) open(Destination.WOL) })) + else LanScreen(lan, Modifier.weight(1f)) + } + Destination.SSH -> SshScreen(ssh, screen, prefillHost = sshPrefillHost, onPrefillConsumed = { sshPrefillHost = null }, + connectProfileId = sshConnectId, onConnectRequestConsumed = { sshConnectId = null }, + landscape = landscape, onTerminalVisible = { terminalVisible = it }) + Destination.WOL -> WolScreen(wol, screen, highlightId = wolHighlightId) + } } - Destination.SSH -> SshScreen(ssh, screen, prefillHost = sshPrefillHost, onPrefillConsumed = { sshPrefillHost = null }) - Destination.WOL -> WolScreen(wol, screen) } } - } } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupCrypto.kt b/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupCrypto.kt new file mode 100644 index 0000000..d9aad83 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupCrypto.kt @@ -0,0 +1,47 @@ +package cz.netkit.app.backup + +import cz.netkit.shared.backup.* +import java.security.SecureRandom +import java.util.Base64 +import javax.crypto.BadPaddingException +import javax.crypto.Cipher +import javax.crypto.SecretKeyFactory +import javax.crypto.spec.GCMParameterSpec +import javax.crypto.spec.PBEKeySpec +import javax.crypto.spec.SecretKeySpec + +internal class BackupAuthenticationFailed : Exception() +internal object BackupCrypto { + private val random = SecureRandom() + + private fun crypt(mode: Int, input: ByteArray, password: CharArray, salt: ByteArray, iv: ByteArray): ByteArray { + require(salt.size == 16 && iv.size == 12 && password.size in 1..1024) + val spec = PBEKeySpec(password, salt, BACKUP_ROUNDS, 256) + val key = try { SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).encoded } + finally { spec.clearPassword() } + return try { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(mode, SecretKeySpec(key, "AES"), GCMParameterSpec(128, iv)) + cipher.updateAAD("$BACKUP_ENCRYPTED_FORMAT|$BACKUP_KDF|$BACKUP_ROUNDS|$BACKUP_CIPHER".encodeToByteArray()) + cipher.doFinal(input) + } catch (_: BadPaddingException) { throw BackupAuthenticationFailed() } + finally { key.fill(0) } + } + + fun seal(plain: ByteArray, password: CharArray): ByteArray { + require(plain.size <= BACKUP_BYTES) + val salt = ByteArray(16).also(random::nextBytes) + val iv = ByteArray(12).also(random::nextBytes) + val b64 = Base64.getEncoder() + return encodeEnvelope(b64.encodeToString(salt), b64.encodeToString(iv), + b64.encodeToString(crypt(Cipher.ENCRYPT_MODE, plain, password, salt, iv))) + } + + fun open(bytes: ByteArray, password: CharArray): ByteArray { + val header = decodeEnvelope(bytes) + val b64 = Base64.getDecoder() + val cipher = b64.decode(header.ciphertext) + require(cipher.size in 16..BACKUP_BYTES + 16) + return crypt(Cipher.DECRYPT_MODE, cipher, password, b64.decode(header.salt), b64.decode(header.iv)) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupRepository.kt b/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupRepository.kt new file mode 100644 index 0000000..06d9816 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupRepository.kt @@ -0,0 +1,104 @@ +package cz.netkit.app.backup + +import android.content.Context +import androidx.datastore.core.Serializer +import cz.netkit.app.lan.* +import cz.netkit.app.settings.AppLanguageSystem +import cz.netkit.app.settings.AppSettingsSerializer +import cz.netkit.app.ssh.SshCrypto +import cz.netkit.app.ssh.SshDataSerializer +import cz.netkit.app.wol.DeviceEnvelope +import cz.netkit.app.wol.DeviceSerializer +import cz.netkit.shared.backup.* +import cz.netkit.shared.settings.* +import cz.netkit.shared.speed.* +import java.io.ByteArrayOutputStream +import java.util.Base64 +import java.util.UUID +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +internal class BackupSnapshot(val state: ConfigurationState, val stamps: Map, + val lan: LanToolPreferences, val speed: SpeedStoreData, val language: AppLanguage?) { + fun export() = with(state) { encodeBackup(configurationBackup(ssh, devices, tools, favorites, servers, settings)) } +} + +internal class BackupRepository(private val files: RestoreFiles, private val currentLanguage: () -> AppLanguage?) { + constructor(app: Context) : this(RestoreFiles(app), { AppLanguageSystem.current(app) }) + + suspend fun snapshot(): BackupSnapshot = withContext(Dispatchers.IO) { + // Hash and decode the same bytes. Each existing writer publishes its file by atomic move. + val bytes = ConfigFile.entries.associateWith(files::contents) + suspend fun read(key: ConfigFile, codec: Serializer) = + bytes[key]?.inputStream()?.use { codec.readFrom(it) } ?: codec.defaultValue + val ssh = read(ConfigFile.SSH, SshDataSerializer) + val devices = read(ConfigFile.WOL, DeviceSerializer).devices + val lan = read(ConfigFile.LAN, LanPreferencesSerializer) + val speed = bytes[ConfigFile.SPEED]?.let { SpeedStoreCodec.decode(it.decodeToString(throwOnInvalidSequence = true)) } ?: SpeedStoreData() + val settings = read(ConfigFile.SETTINGS, AppSettingsSerializer) + val language = currentLanguage() + BackupSnapshot(ConfigurationState(ssh, devices, + with(lan) { BackupTools(ping.count, ping.seconds, ping.payload, ping.df, subnetInput, ports, maskInterpretation) }, + lan.targets.favorites, BackupServers(speed.customUrl, speed.iperfHost, speed.iperfPort), + BackupSettings(settings.theme, language ?: AppLanguage.SYSTEM, settings.keepScreenOn)), + bytes.mapValues { files.stamp(it.value) }, lan, speed, language) + } + + fun validate(bytes: ByteArray): ValidatedBackup = decodeBackup(bytes).also { backup -> + for (host in backup.file.knownHosts) { + val blob = Base64.getDecoder().decode(host.publicKey) + require(host.fingerprint == SshCrypto.fingerprint(blob)) + require(blob.size >= 5) + val length = java.nio.ByteBuffer.wrap(blob).int + require(length in 1..64 && blob.size > 4 + length && blob.decodeToString(4, 4 + length) == host.algorithm) + } + } + + fun plan(snapshot: BackupSnapshot, incoming: ValidatedBackup, selected: Set): RestorePlan = + planRestore(snapshot.state, incoming, selected) { UUID.randomUUID().toString() } + + suspend fun stage(snapshot: BackupSnapshot, plan: RestorePlan) = withContext(Dispatchers.IO) { + require(plan.changes.isNotEmpty()) + val after = plan.state + val before = snapshot.state + val filesAfter = mutableMapOf() + suspend fun encode(key: ConfigFile, codec: Serializer, value: T) { + val buffer = ByteArrayOutputStream() + codec.writeTo(value, buffer) + filesAfter[key] = buffer.toByteArray() + } + if (after.ssh != before.ssh) encode(ConfigFile.SSH, SshDataSerializer, after.ssh) + if (after.devices != before.devices || plan.forgetSecureOn.isNotEmpty()) encode(ConfigFile.WOL, DeviceSerializer, DeviceEnvelope(2, after.devices)) + if (after.tools != before.tools || after.favorites != before.favorites) with(after.tools) { + encode(ConfigFile.LAN, LanPreferencesSerializer, snapshot.lan.copy( + ping = PingFields(count, seconds, payload, df), subnetInput = subnetInput, ports = ports, maskInterpretation = mask, + targets = snapshot.lan.targets.copy(favorites = after.favorites))) + } + if (after.servers != before.servers) with(after.servers) { + filesAfter[ConfigFile.SPEED] = SpeedStoreCodec.encode(snapshot.speed.copy(customUrl = libreSpeed, + iperfHost = iperfHost, iperfPort = iperfPort)).encodeToByteArray() + } + if (after.settings.theme != before.settings.theme || after.settings.keepScreenOn != before.settings.keepScreenOn) { + encode(ConfigFile.SETTINGS, AppSettingsSerializer, AppSettings(theme = after.settings.theme, keepScreenOn = after.settings.keepScreenOn)) + } + val sections = plan.changes.keys + val touched = buildSet { + if (sections.any { it in sshSections }) add(ConfigFile.SSH) + if (BackupSection.WOL in sections) add(ConfigFile.WOL) + if (BackupSection.TOOLS in sections || BackupSection.FAVORITES in sections) add(ConfigFile.LAN) + if (BackupSection.SERVERS in sections) add(ConfigFile.SPEED) + if (BackupSection.SETTINGS in sections) add(ConfigFile.SETTINGS) + } + if (BackupSection.SETTINGS in sections && currentLanguage() != snapshot.language) throw StaleBackupPreview() + val detachedRefs = before.ssh.profiles.mapNotNull { it.secretRef }.toSet() - + after.ssh.profiles.mapNotNull { it.secretRef }.toSet() - after.ssh.keys.map { it.id }.toSet() - + after.ssh.profiles.mapNotNull { it.keyRef }.toSet() + files.stage(snapshot.stamps.filterKeys { it in touched }, filesAfter, snapshot.language, + after.settings.language.takeIf { BackupSection.SETTINGS in sections && snapshot.language != null }, plan.forgetSecureOn, detachedRefs) + } + + private companion object { + val sshSections = setOf(BackupSection.SSH, BackupSection.SERIAL, BackupSection.TELNET, BackupSection.SNIPPETS, + BackupSection.FORWARDS, BackupSection.KNOWN_HOSTS) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupScreen.kt new file mode 100644 index 0000000..d525a3c --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupScreen.kt @@ -0,0 +1,192 @@ +package cz.netkit.app.backup + +import androidx.activity.compose.BackHandler +import androidx.activity.compose.LocalActivity +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.fragment.app.FragmentActivity +import cz.netkit.app.R +import cz.netkit.app.ssh.* +import cz.netkit.app.ui.* +import cz.netkit.app.ui.about.SubscreenHeader +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.shared.backup.BackupSection + +internal val BackupSection.title: Int get() = when (this) { + BackupSection.SSH -> R.string.backup_ssh + BackupSection.TELNET -> R.string.backup_telnet + BackupSection.SERIAL -> R.string.backup_serial + BackupSection.SNIPPETS -> R.string.backup_snippets + BackupSection.FORWARDS -> R.string.backup_forwards + BackupSection.KNOWN_HOSTS -> R.string.backup_known_hosts + BackupSection.WOL -> R.string.backup_wol + BackupSection.TOOLS -> R.string.backup_tools + BackupSection.FAVORITES -> R.string.backup_favorites + BackupSection.SERVERS -> R.string.backup_servers + BackupSection.SETTINGS -> R.string.settings_title +} + +@Composable +internal fun BackupScreen(ssh: SshViewModel, canClose: () -> Boolean, onBack: () -> Unit, modifier: Modifier) { + BackHandler(onBack = onBack) + val activity = LocalActivity.current as FragmentActivity + val model = remember(activity) { ViewModelProvider(activity)[BackupViewModel::class.java] } + DisposableEffect(model) { onDispose { if (!activity.isChangingConfigurations) model.reset() } } + SshLockHost(ssh.access, modifier) { + BackupContent(model, ssh.access, canClose, onBack, modifier) { + activity.finishAndRemoveTask() + // Explicitly confirmed cold restart: all DataStore owners release the previous generation. + kotlin.system.exitProcess(0) + } + } +} + +@Composable +private fun BackupContent(model: BackupViewModel, access: SshAccess, canClose: () -> Boolean, onBack: () -> Unit, + modifier: Modifier, close: () -> Unit) { + val state by model.state.collectAsStateWithLifecycle() + var encrypt by remember { mutableStateOf(true) } + var password by remember { mutableStateOf("") } // Never save to a Bundle, logs or preferences. + var warning by remember { mutableStateOf(false) } + var confirm by remember { mutableStateOf(false) } + var blocked by remember { mutableStateOf(false) } + var pickerFailed by remember { mutableStateOf(false) } + val create = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri -> + if (uri == null) model.reset() else access.protect { model.write(uri) } + } + val open = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + if (uri != null) access.protect { model.read(uri) } + } + // The picker starts from the composition that is current when the export is ready (revize 51, kolo 1). + LaunchedEffect(state.pickDocument) { + if (!state.pickDocument) return@LaunchedEffect + model.documentPickerShown() + password = "" + try { create.launch("netkit-backup-v1.json") } catch (_: android.content.ActivityNotFoundException) { + model.reset(); pickerFailed = true + } + } + val scroll = rememberLazyListState() + LaunchedEffect(state.preview, state.needsPassword) { scroll.scrollToItem(0) } + LazyColumn(modifier.fillMaxSize().testTag("backup_screen"), state = scroll, contentPadding = PaddingValues(Spacing.normal), + verticalArrangement = Arrangement.spacedBy(Spacing.normal)) { + item { SubscreenHeader(stringResource(R.string.backup_title), "backup_back", onBack) } + if (state.preview) { + item { + if (!state.authenticatedFile) StatusBanner(stringResource(R.string.backup_plain_warning), StatusKind.WARNING) + Text(stringResource(R.string.backup_preview), Modifier.testTag("backup_preview")) + } + for (section in BackupSection.entries) { + val selected = section in state.selected + val changes = state.plan?.changes?.get(section) + item(key = section.name) { + Column { + CheckRow(selected, stringResource(section.title)) { model.select(section, it) } + changes?.let { Text(stringResource(R.string.backup_changes, it.added, it.changed, it.skipped)) } + if (section == BackupSection.KNOWN_HOSTS) Text(stringResource(R.string.backup_trust_note)) + if (selected && section == BackupSection.WOL) Text(stringResource(R.string.backup_wol_note)) + } + } + if (!selected) continue + // Each record is lazy, including large known_hosts and snippet lists. + when (section) { + BackupSection.KNOWN_HOSTS -> model.document?.knownHosts?.let { rows -> items(rows.size) { i -> + Text("${rows[i].endpoint} ${rows[i].fingerprint}") + } } + BackupSection.SSH -> model.importedProfiles?.profiles?.let { rows -> items(rows.size) { i -> + val row = rows[i] + Column { + Text("${row.alias} · ${row.username}@${row.host}:${row.port} ${row.startupCommand}") + // Revize 51, kolo 2: keys are local, a restored key profile must get its key again. + if (row.alias in state.plan?.keyless.orEmpty()) + Text(stringResource(R.string.backup_key_missing), color = NetKitTheme.colors.warn) + } + } } + BackupSection.SNIPPETS -> model.importedProfiles?.snippets?.let { rows -> items(rows.size) { i -> + Text("${rows[i].name} · ${rows[i].text}") + } } + BackupSection.TELNET, BackupSection.SERIAL -> { + val kind = if (section == BackupSection.SERIAL) cz.netkit.shared.ssh.ConsoleKind.SERIAL else cz.netkit.shared.ssh.ConsoleKind.TELNET + val rows = model.document?.consoles.orEmpty().filter { it.kind == kind } + items(rows.size) { i -> val row = rows[i] + Text(if (kind == cz.netkit.shared.ssh.ConsoleKind.SERIAL) "${row.name} · ${row.serial.baud}" else "${row.name} · ${row.host}:${row.port}") + } + } + BackupSection.WOL -> model.importedDevices.let { rows -> items(rows.size) { i -> + Text("${rows[i].name} · ${rows[i].mac}") + } } + BackupSection.FAVORITES -> model.document?.favorites?.let { rows -> items(rows.size) { i -> + Text(listOf(rows[i].label, rows[i].value).filter(String::isNotBlank).joinToString(" · ")) + } } + BackupSection.SERVERS -> model.document?.servers?.let { servers -> item { + servers.libreSpeed?.let { Text(it) } + if (servers.iperfHost.isNotEmpty()) Text("iperf3 · ${servers.iperfHost} · ${servers.iperfPort}") + } } + BackupSection.FORWARDS -> model.document?.forwards?.filter { it.local.isNotEmpty() || it.dynamicPort != null }?.let { rows -> + items(rows.size) { i -> Column { + val row = rows[i] + for (rule in row.local) Text("${row.profile} · ${rule.localPort} → ${rule.target}") + row.dynamicPort?.let { Text("${row.profile} · SOCKS5 · $it") } + } } + } + BackupSection.TOOLS, BackupSection.SETTINGS -> Unit + } + } + item { PrimaryButton(stringResource(R.string.backup_restore), { confirm = true }, + Modifier.testTag("backup_apply"), enabled = !state.busy && state.plan != null && state.selected.isNotEmpty()) } + } else { + if (!state.needsPassword) item { + Text(stringResource(R.string.backup_contents)) + CheckRow(encrypt, stringResource(R.string.backup_encrypt)) { if (!it) warning = true else encrypt = true } + if (!encrypt) StatusBanner(stringResource(R.string.backup_plain_warning), StatusKind.WARNING) + } + if (encrypt || state.needsPassword) item { + OutlinedTextField(password, { if (it.length <= 1024) password = it }, singleLine = true, + modifier = Modifier.fillMaxWidth().testTag("backup_password"), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), + visualTransformation = PasswordVisualTransformation(), label = { Text(stringResource(R.string.backup_password)) }) + } + if (state.needsPassword) item { + PrimaryButton(stringResource(R.string.backup_unlock), { + model.unlock(password.toCharArray()); password = "" + }, enabled = !state.busy && password.isNotEmpty()) + } else item { + PrimaryButton(stringResource(R.string.backup_export), { access.protect { + model.prepare(if (encrypt) password.toCharArray() else null) + } }, Modifier.testTag("backup_export"), enabled = !state.busy && (!encrypt || password.isNotEmpty())) + NeutralButton(stringResource(R.string.backup_open), { + password = "" + try { open.launch(arrayOf("application/json", "application/octet-stream", "text/*")) } + catch (_: android.content.ActivityNotFoundException) { pickerFailed = true } + }, Modifier.testTag("backup_open"), enabled = !state.busy) + } + } + if (state.preview || state.needsPassword) item { + NeutralButton(stringResource(R.string.settings_cancel), { model.reset(); password = "" }, enabled = !state.busy) + } + state.message?.let { item { StatusBanner(stringResource(it), if (it == R.string.backup_exported) StatusKind.INFO else StatusKind.ERROR) } } + if (state.busy) item { LinearProgressIndicator(Modifier.fillMaxWidth()) } + if (blocked || pickerFailed) item { StatusBanner(stringResource(if (blocked) R.string.backup_blocked else R.string.backup_failed), StatusKind.WARNING) } + } + if (warning || confirm) AlertDialog(onDismissRequest = { warning = false; confirm = false }, + title = { Text(stringResource(if (warning) R.string.backup_plain_title else R.string.backup_restore)) }, + text = { Text(stringResource(if (warning) R.string.backup_plain_warning else R.string.backup_restart_note)) }, + confirmButton = { TextButton({ if (warning) { encrypt = false; password = ""; warning = false } else { + confirm = false + access.protect { if (canClose()) model.apply(close) else blocked = true } + } }, Modifier.testTag("backup_confirm")) { Text(stringResource(if (warning) R.string.backup_plain_button else R.string.backup_restart)) } }, + dismissButton = { TextButton({ warning = false; confirm = false }) { Text(stringResource(R.string.settings_cancel)) } }) +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupViewModel.kt new file mode 100644 index 0000000..1dd88fe --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/backup/BackupViewModel.kt @@ -0,0 +1,141 @@ +package cz.netkit.app.backup + +import android.app.Application +import android.net.Uri +import android.os.CancellationSignal +import android.os.ParcelFileDescriptor +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import cz.netkit.app.R +import cz.netkit.app.wol.BoundedStreamIo +import cz.netkit.shared.backup.* +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow + +internal data class BackupUiState(val busy: Boolean = false, val needsPassword: Boolean = false, + val preview: Boolean = false, val authenticatedFile: Boolean = false, val selected: Set = emptySet(), val plan: RestorePlan? = null, + val message: Int? = null, + /** A prepared export waits for the document picker of the CURRENT composition (revize 51, kolo 1). */ + val pickDocument: Boolean = false) + +class BackupViewModel(application: Application) : AndroidViewModel(application) { + private val repo = BackupRepository(application) + private val resolver = application.contentResolver + private val mutable = MutableStateFlow(BackupUiState()) + internal val state = mutable.asStateFlow() + private var encrypted: ByteArray? = null + private var authenticatedFile = false + private var export: ByteArray? = null + private var snapshot: BackupSnapshot? = null + private var incoming: ValidatedBackup? = null + private var work: Job? = null + + internal fun reset() { + work?.cancel() + encrypted = null + authenticatedFile = false + export?.fill(0) + export = null + snapshot = null + incoming = null + mutable.value = BackupUiState() + } + + private fun run(action: suspend () -> Unit) { + if (state.value.busy) return + mutable.value = state.value.copy(busy = true, message = null) + work = viewModelScope.launch { + try { action() } + catch (e: CancellationException) { + currentCoroutineContext().ensureActive() + mutable.value = state.value.copy(message = R.string.backup_failed) + } + catch (_: BackupContainsCredential) { mutable.value = state.value.copy(message = R.string.backup_credential_text) } + catch (_: cz.netkit.shared.ssh.SshProfileExportException) { mutable.value = state.value.copy(message = R.string.backup_profile_error) } + catch (_: BackupAuthenticationFailed) { mutable.value = state.value.copy(message = R.string.backup_wrong_password) } + catch (_: StaleBackupPreview) { mutable.value = BackupUiState(message = R.string.backup_stale) } + catch (_: Exception) { mutable.value = state.value.copy(message = R.string.backup_failed) } + finally { if (isActive) mutable.value = state.value.copy(busy = false) } + } + } + + /** + * Without [ready] the result is a state flag, never a callback: PBKDF2 can outlive a rotation, and a + * launcher captured by the old composition is unregistered by then. + */ + internal fun prepare(password: CharArray?, ready: (() -> Unit)? = null) = run { + try { + val portable = repo.snapshot() + export = withContext(Dispatchers.Default) { + val plain = portable.export() + if (password == null) plain else try { BackupCrypto.seal(plain, password) } finally { plain.fill(0) } + } + if (ready != null) ready() else mutable.value = state.value.copy(pickDocument = true) + } finally { password?.fill('\u0000') } + } + + /** Consume the request before launching, so a recomposition or rotation never opens a second picker. */ + internal fun documentPickerShown() { mutable.value = state.value.copy(pickDocument = false) } + + internal fun write(uri: Uri?) = run { + val bytes = export ?: error("No prepared export") + export = null + try { + if (uri != null) { + val signal = CancellationSignal() + BoundedStreamIo.write({ ParcelFileDescriptor.AutoCloseOutputStream( + requireNotNull(resolver.openFileDescriptor(uri, "wt", signal))) }, signal::cancel, bytes) + mutable.value = state.value.copy(message = R.string.backup_exported) + } + } finally { bytes.fill(0) } + } + + internal fun read(uri: Uri) = run { + val signal = CancellationSignal() + val bytes = BoundedStreamIo.read({ ParcelFileDescriptor.AutoCloseInputStream( + requireNotNull(resolver.openFileDescriptor(uri, "r", signal))) }, signal::cancel, BACKUP_FILE_BYTES) + receive(bytes) + } + + private suspend fun receive(bytes: ByteArray) { + if (withContext(Dispatchers.Default) { encryptedBackup(bytes) }) { + encrypted = bytes + mutable.value = BackupUiState(needsPassword = true) + } else { authenticatedFile = false; preview(bytes) } + } + + internal fun unlock(password: CharArray) = run { + try { + val plain = withContext(Dispatchers.Default) { BackupCrypto.open(requireNotNull(encrypted), password) } + authenticatedFile = true + try { preview(plain) } finally { plain.fill(0) } + encrypted = null + } finally { password.fill('\u0000') } + } + + private suspend fun preview(plain: ByteArray) { + incoming = withContext(Dispatchers.Default) { repo.validate(plain) } + snapshot = repo.snapshot() + replan(BackupSection.entries.toSet() - BackupSection.KNOWN_HOSTS) + } + + private suspend fun replan(sections: Set) { + mutable.value = BackupUiState(preview = true, authenticatedFile = authenticatedFile, selected = sections, busy = true) + val plan = withContext(Dispatchers.Default) { repo.plan(requireNotNull(snapshot), requireNotNull(incoming), sections) } + mutable.value = state.value.copy(plan = plan, busy = false) + } + internal fun select(section: BackupSection, enabled: Boolean) = run { + replan(if (enabled) state.value.selected + section else state.value.selected - section) + } + + internal val importedDevices get() = incoming?.devices.orEmpty() + internal val document get() = incoming?.file + internal val importedProfiles get() = incoming?.profiles + internal fun apply(closed: () -> Unit) = run { + val current = requireNotNull(snapshot) + repo.stage(current, requireNotNull(state.value.plan)) + closed() + } + override fun onCleared() = reset() +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/backup/RestoreFiles.kt b/androidApp/src/main/kotlin/cz/netkit/app/backup/RestoreFiles.kt new file mode 100644 index 0000000..09a956e --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/backup/RestoreFiles.kt @@ -0,0 +1,162 @@ +package cz.netkit.app.backup + +import android.content.Context +import cz.netkit.app.ssh.readBytesBounded +import cz.netkit.shared.settings.AppLanguage +import java.io.File +import java.io.FileOutputStream +import java.nio.channels.FileChannel +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.nio.file.StandardOpenOption +import java.security.MessageDigest +import java.util.UUID +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +internal enum class ConfigFile(val filename: String) { + SSH("ssh.json"), WOL("wol-devices.json"), LAN("lan-tools.json"), SPEED("speedtest.json"), SETTINGS("settings.json"); + + fun resolve(context: Context): File = RestoreFiles(context).resolve(this) +} + +internal class StaleBackupPreview : Exception() + +/** + * DataStore instances own their paths for the life of a process. Stage new files beside the + * stores, then switch a single map at cold start, before creating any DataStore or ViewModel. + * Each generation contains only the stores that changed. Old paths stay usable until activation. + */ +internal class RestoreFiles(private val files: File, private val privateDir: File) { + constructor(context: Context) : this(context.filesDir, context.noBackupFilesDir) + + private val root = privateDir.resolve("configuration-restore") + private val active = root.resolve("active.json") + private val pending = root.resolve("pending.json") + private val mapReset = root.resolve("map-reset.flag") + + @Serializable private data class Active(val id: String, val locations: Map) + @Serializable private data class Pending(val id: String, val before: Map, + val after: Map, val oldLanguage: AppLanguage?, val language: AppLanguage?, + val detachedRefs: Set) + + /** + * Every store resolves its path here, so a damaged map must never stop the app (revize 51, kolo 2): + * set it aside, fall back to the default store paths and leave a one-time flag for Settings. + * Generation directories stay on disk until the next confirmed restore cleans them up. + */ + private fun locations(): Active = synchronized(lock) { + if (!active.exists()) return Active("", emptyMap()) + try { + Json.decodeFromString(active.readBytes().decodeToString(throwOnInvalidSequence = true)).also { map -> + (map.locations.values + map.id.takeIf { it.isNotEmpty() }).filterNotNull().forEach(::generation) + } + } catch (_: Exception) { + val aside = root.resolve("active.corrupt-${System.currentTimeMillis()}.json") + if (!active.renameTo(aside)) active.delete() + try { mapReset.createNewFile() } catch (_: java.io.IOException) { } + Active("", emptyMap()) + } + } + + /** Check the map before any store exists; true once after a damaged map was set aside. */ + fun recoverDamagedMap(): Boolean = synchronized(lock) { + locations() + mapReset.exists().also { if (it) mapReset.delete() } + } + + private fun generation(id: String): File { + require(UUID.fromString(id).toString() == id) + return root.resolve(id) + } + + private fun legacy(key: ConfigFile) = if (key == ConfigFile.SPEED) privateDir.resolve(key.filename) + else files.resolve("datastore").resolve(key.filename) + + fun resolve(key: ConfigFile): File = + locations().locations[key]?.let { generation(it).resolve(key.filename) } ?: legacy(key) + + private fun digest(bytes: ByteArray) = java.util.Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(bytes)) + // A restore invalidates the vault entries of imported IDs, even when the binding matches. + // The sidecar becomes visible in the very same switch as the restored device list. + fun wolRevocations(): File? = locations().locations[ConfigFile.WOL]?.let { generation(it).resolve("forget-wol.json") } + + fun stamp(bytes: ByteArray?) = bytes?.let(::digest) ?: "absent" + fun contents(key: ConfigFile): ByteArray? = resolve(key).let { file -> + if (!file.exists()) null else file.inputStream().use { it.readBoundedConfig() } + } + + private fun syncDirectory(dir: File) = FileChannel.open(dir.toPath(), StandardOpenOption.READ).use { it.force(true) } + private fun write(file: File, bytes: ByteArray) = FileOutputStream(file).use { it.write(bytes); it.fd.sync() } + private fun publish(file: File, text: String) { + val temp = File.createTempFile("publish", ".tmp", root) + try { + write(temp, text.encodeToByteArray()) + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING) + syncDirectory(root) + } finally { temp.delete() } + } + + fun stage(before: Map, replacements: Map, + oldLanguage: AppLanguage?, language: AppLanguage?, importedWolIds: Set = emptySet(), + detachedRefs: Set = emptySet()) = synchronized(lock) { + check(!pending.exists()) + require(replacements.keys.all { it in before }) + if (before.any { (key, hash) -> stamp(contents(key)) != hash }) throw StaleBackupPreview() + check(root.isDirectory || root.mkdirs()) + val id = UUID.randomUUID().toString() + val dir = generation(id) + check(dir.mkdir()) + try { + replacements.forEach { (key, data) -> write(dir.resolve(key.filename), data) } + if (ConfigFile.WOL in replacements) { + val outstanding = wolRevocations()?.takeIf { it.exists() }?.let { Json.decodeFromString>(it.readText()) }.orEmpty() + val ids = importedWolIds + outstanding + if (ids.isNotEmpty()) write(dir.resolve("forget-wol.json"), Json.encodeToString(ids).encodeToByteArray()) + } + syncDirectory(dir) + publish(pending, Json.encodeToString(Pending(id, before, replacements.mapValues { digest(it.value) }, oldLanguage, language, detachedRefs))) + } finally { + // A failed prepare has no committed owner. Never remove a published generation. + if (!pending.exists()) dir.deleteRecursively() + } + } + + /** Idempotent after interruption on either side of the atomic move or the Android locale setter. */ + fun activate(currentLanguage: () -> AppLanguage?, forgetSsh: (Set) -> Unit = {}, setLanguage: (AppLanguage) -> Unit): Boolean? = synchronized(lock) { + if (!pending.exists()) return null + val request = Json.decodeFromString(pending.readText()) + val previous = locations() + if (previous.id != request.id) { + val fresh = request.before.all { (key, hash) -> stamp(contents(key)) == hash } && + (request.language == null || request.oldLanguage == currentLanguage()) && + request.after.all { (key, hash) -> generation(request.id).resolve(key.filename).let { file -> + file.isFile && file.inputStream().use { digest(it.readBoundedConfig()) } == hash + } } + if (!fresh) { + Files.delete(pending.toPath()) + generation(request.id).deleteRecursively() + return false + } + val locations = previous.locations + request.after.keys.associateWith { request.id } + publish(active, Json.encodeToString(Active(request.id, locations))) + } + request.language?.takeIf { it != currentLanguage() }?.let(setLanguage) + if (request.detachedRefs.isNotEmpty()) forgetSsh(request.detachedRefs) + Files.delete(pending.toPath()) + syncDirectory(root) + // The atomic switch is durable. Discard retired copies of private configuration. + val current = locations().locations + current.keys.forEach { legacy(it).delete() } + root.listFiles()?.filter { it.isDirectory && runCatching { UUID.fromString(it.name) }.isSuccess }?.forEach { dir -> + ConfigFile.entries.filter { current[it] != dir.name }.forEach { dir.resolve(it.filename).delete() } + if (current[ConfigFile.WOL] != dir.name) dir.resolve("forget-wol.json").delete() + dir.delete() // Only empty directories are removed. + } + true + } + + private companion object { val lock = Any() } +} + +private fun java.io.InputStream.readBoundedConfig() = readBytesBounded(4 * 1024 * 1024) diff --git a/androidApp/src/main/kotlin/cz/netkit/app/cellular/CellDetailViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/cellular/CellDetailViewModel.kt new file mode 100644 index 0000000..c01ebd2 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/cellular/CellDetailViewModel.kt @@ -0,0 +1,101 @@ +package cz.netkit.app.cellular + +import android.app.Application +import android.os.SystemClock +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import cz.netkit.shared.cellular.CellDetail +import cz.netkit.shared.cellular.cellDetailOf +import cz.netkit.shared.cellular.cellDetailRefreshPass +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull + +enum class CellDetailStatus { LOADING, READY, FAILED, NO_PERMISSION } + +/** Detail of one SIM; [detail] is null until the first answer (and after a permission loss). */ +data class CellDetailEntry(val status: CellDetailStatus, val detail: CellDetail? = null) + +/** Subscription id → detail of every SIM whose expanded "Detail buňky" is on screen. */ +data class CellDetailUiState(val bySim: Map = emptyMap()) + +/** + * Zadání 53 (D31): cell detail **only in memory, only while visible**. + * + * - The UI calls [show] when an expanded "Detail buňky" of a SIM is composed and the app is + * resumed, and [hide] when it collapses, scrolls away or the app pauses. Only shown SIMs are + * requested, each at most once per 5 s ([cellDetailRefreshPass]); without any shown SIM the loop + * ends (cancelled, no request in flight is awaited). + * - [hide] also forgets the detail of that SIM: cell ID and TAC are a location hint, nothing is + * stored, exported, shared or sent, and the diagnostic report never reads this ViewModel. + */ +class CellDetailViewModel(application: Application) : AndroidViewModel(application) { + private val reader = CellInfoReader(application) + private val visible = linkedMapOf() + private val lastRequestMs = mutableMapOf() + private val wake = Channel(Channel.CONFLATED) + private var loop: Job? = null + private val _state = MutableStateFlow(CellDetailUiState()) + val state: StateFlow = _state.asStateFlow() + + /** An expanded detail of [subscriptionId] became visible (reference counted). */ + fun show(subscriptionId: Int) { + visible[subscriptionId] = (visible[subscriptionId] ?: 0) + 1 + _state.update { s -> + if (subscriptionId in s.bySim) s else s.copy(bySim = s.bySim + (subscriptionId to CellDetailEntry(CellDetailStatus.LOADING))) + } + if (loop?.isActive == true) wake.trySend(Unit) else loop = viewModelScope.launch { run() } + } + + /** The detail of [subscriptionId] left the screen: forget it, stop when nothing is shown. */ + fun hide(subscriptionId: Int) { + val count = (visible[subscriptionId] ?: return) - 1 + if (count > 0) { + visible[subscriptionId] = count + return + } + visible.remove(subscriptionId) + _state.update { it.copy(bySim = it.bySim - subscriptionId) } + if (visible.isEmpty()) { + loop?.cancel() + loop = null + } + } + + private suspend fun run() { + while (visible.isNotEmpty()) { + // Each SIM's request time is read right before its own request (cellDetailRefreshPass). + val nextMs = cellDetailRefreshPass({ visible.keys.toSet() }, lastRequestMs, SystemClock::elapsedRealtime) { id -> + // Binder calls stay off the main thread (as CellularMonitor); cancellable. + val result = withContext(Dispatchers.IO) { reader.read(id) } + if (id in visible) apply(id, result) + } + // A newly shown SIM wakes the loop; the schedule still keeps 5 s per SIM. + withTimeoutOrNull(nextMs.coerceAtLeast(MIN_WAIT_MS)) { wake.receive() } + } + } + + private fun apply(id: Int, result: CellInfoResult) { + _state.update { s -> + val previous = s.bySim[id] + val entry = when (result) { + is CellInfoResult.Cells -> CellDetailEntry(CellDetailStatus.READY, cellDetailOf(result.readings)) + // A failed refresh keeps the last answer on screen; without one it says so. + CellInfoResult.Failed -> previous?.takeIf { it.detail != null } ?: CellDetailEntry(CellDetailStatus.FAILED) + CellInfoResult.NoPermission -> CellDetailEntry(CellDetailStatus.NO_PERMISSION) + } + s.copy(bySim = s.bySim + (id to entry)) + } + } + + private companion object { + const val MIN_WAIT_MS = 250L + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/cellular/CellInfoReader.kt b/androidApp/src/main/kotlin/cz/netkit/app/cellular/CellInfoReader.kt new file mode 100644 index 0000000..5377eff --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/cellular/CellInfoReader.kt @@ -0,0 +1,125 @@ +package cz.netkit.app.cellular + +import android.Manifest +import android.annotation.SuppressLint +import android.content.Context +import android.content.pm.PackageManager +import android.os.Build +import android.telephony.CellIdentityNr +import android.telephony.CellInfo +import android.telephony.CellInfoGsm +import android.telephony.CellInfoLte +import android.telephony.CellInfoNr +import android.telephony.CellInfoTdscdma +import android.telephony.CellInfoWcdma +import android.telephony.CellSignalStrengthNr +import android.telephony.TelephonyManager +import cz.netkit.shared.cellular.CELL_UNAVAILABLE +import cz.netkit.shared.cellular.CellInfoReading +import cz.netkit.shared.cellular.CellRat +import cz.netkit.shared.cellular.CellStrengthReading +import java.util.concurrent.Executor +import kotlin.coroutines.resume +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeoutOrNull + +/** Outcome of one `requestCellInfoUpdate` of one SIM. */ +internal sealed interface CellInfoResult { + data class Cells(val readings: List) : CellInfoResult + /** Modem error, timeout, binder failure or a missing telephony feature. */ + data object Failed : CellInfoResult + /** ACCESS_FINE_LOCATION or READ_PHONE_STATE is missing (or was revoked meanwhile). */ + data object NoPermission : CellInfoResult +} + +/** + * Zadání 53 (D31): the cell detail needs an already granted ACCESS_FINE_LOCATION (required by + * `requestCellInfoUpdate`) and READ_PHONE_STATE (decision 53 §2: both SIMs, never asked for here + * on its own). Neither is a new permission. + */ +internal fun cellDetailPermissionsGranted(context: Context): Boolean = + context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && + context.checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED + +/** + * Reads the cells of one subscription with `TelephonyManager.requestCellInfoUpdate` (API 29+, + * "from the current subscription", so a `createForSubscriptionId` manager gives one SIM). + * `getAllCellInfo` is not used: it mixes all radios and, for apps targeting API 29+, returns a + * possibly stale cache. The answer is mapped to raw readings at once; validation is in `shared`. + * Nothing is kept here: the caller holds the result only in memory. + */ +internal class CellInfoReader(context: Context) { + private val app = context.applicationContext + + suspend fun read(subscriptionId: Int, timeoutMs: Long = REQUEST_TIMEOUT_MS): CellInfoResult { + if (!cellDetailPermissionsGranted(app)) return CellInfoResult.NoPermission + if (!app.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) return CellInfoResult.Failed + val telephony = app.getSystemService(TelephonyManager::class.java) ?: return CellInfoResult.Failed + val tm = try { + telephony.createForSubscriptionId(subscriptionId) + } catch (_: RuntimeException) { + return CellInfoResult.Failed + } + return withTimeoutOrNull(timeoutMs) { request(tm) } ?: CellInfoResult.Failed + } + + @SuppressLint("MissingPermission") // checked by cellDetailPermissionsGranted; SecurityException is mapped + private suspend fun request(tm: TelephonyManager): CellInfoResult = suspendCancellableCoroutine { cont -> + // The callback is light (mapping only); a direct executor avoids a thread hop. + val direct = Executor { it.run() } + val callback = object : TelephonyManager.CellInfoCallback() { + override fun onCellInfo(cellInfo: MutableList) { + if (cont.isActive) cont.resume(CellInfoResult.Cells(cellInfo.mapNotNull { it.toReading() })) + } + + override fun onError(errorCode: Int, detail: Throwable?) { + if (cont.isActive) cont.resume(CellInfoResult.Failed) + } + } + try { + tm.requestCellInfoUpdate(direct, callback) + } catch (_: SecurityException) { + if (cont.isActive) cont.resume(CellInfoResult.NoPermission) + } catch (_: RuntimeException) { + // UnsupportedOperationException (no radio access feature) or a binder failure. + if (cont.isActive) cont.resume(CellInfoResult.Failed) + } + } + + private companion object { + const val REQUEST_TIMEOUT_MS = 4_000L + } +} + +/** Raw getters of one `CellInfo`; CDMA (deprecated, no network in scope) is dropped. */ +internal fun CellInfo.toReading(): CellInfoReading? { + val status = cellConnectionStatus + return when (this) { + is CellInfoLte -> { + val id = cellIdentity + val s = cellSignalStrength + CellInfoReading.Lte( + registered = isRegistered, connectionStatus = status, + earfcn = id.earfcn, pci = id.pci, ci = id.ci, tac = id.tac, bandwidthKhz = id.bandwidth, + bands = if (Build.VERSION.SDK_INT >= 30) id.bands.toList() else emptyList(), + signal = CellStrengthReading.Lte(s.rsrp, s.rsrq, s.rssnr, s.rssi, s.level), + timingAdvance = s.timingAdvance, + ) + } + is CellInfoNr -> { + // API 29 declares the base types; the objects are always the NR subclasses. + val id = cellIdentity as? CellIdentityNr ?: return null + val s = cellSignalStrength as? CellSignalStrengthNr ?: return null + CellInfoReading.Nr( + registered = isRegistered, connectionStatus = status, + nrarfcn = id.nrarfcn, pci = id.pci, nci = id.nci, tac = id.tac, + bands = if (Build.VERSION.SDK_INT >= 30) id.bands.toList() else emptyList(), + signal = CellStrengthReading.Nr(s.ssRsrp, s.ssRsrq, s.ssSinr, s.csiRsrp, s.csiRsrq, s.csiSinr, s.level), + timingAdvance = if (Build.VERSION.SDK_INT >= 34) s.timingAdvanceMicros else CELL_UNAVAILABLE, + ) + } + is CellInfoWcdma, is CellInfoTdscdma -> CellInfoReading.Other(isRegistered, status, CellRat.UMTS) + is CellInfoGsm -> CellInfoReading.Other(isRegistered, status, CellRat.GSM) + else -> null + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesExport.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesExport.kt new file mode 100644 index 0000000..400ebcb --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesExport.kt @@ -0,0 +1,114 @@ +package cz.netkit.app.lan + +import android.app.Application +import android.net.Uri +import android.os.SystemClock +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import cz.netkit.app.BuildConfig +import cz.netkit.app.R +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.StatusBanner +import cz.netkit.app.ui.StatusKind +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.app.wifi.ExportNotice +import cz.netkit.app.wifi.ExportSession +import cz.netkit.app.wifi.SmallChip +import cz.netkit.app.wifi.writeExportDocument +import cz.netkit.shared.lan.LanDevice +import cz.netkit.shared.lan.LanExport +import cz.netkit.shared.lan.exportLanDevices +import cz.netkit.shared.wifi.isoUtc +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.launch + +/** + * Zadání 47 §3: export of the device list through SAF. The text is built when the picker opens + * and exactly that snapshot is written ([ExportSession]); nothing is kept after the write. A + * separate ViewModel so the discovery ViewModel stays unchanged. + */ +class DevicesExportViewModel(application: Application) : AndroidViewModel(application) { + private val app = application + private val export = ExportSession { uri, text -> writeExportDocument(app, uri, text) } + val notice: StateFlow = export.notice + + /** [network] is the scanned range label (e.g. `192.168.1.0/24`), never the SSID. */ + fun prepare(devices: List, format: LanExport, network: String?): Boolean = + export.prepare(devices.takeIf { it.isNotEmpty() }?.let { + exportLanDevices(it, format, SystemClock.elapsedRealtime(), isoUtc(System.currentTimeMillis()), network) + }) + + fun launchFailed() = export.launchFailed() + fun dismiss() = export.dismiss() + fun save(uri: Uri?) { viewModelScope.launch { export.save(uri) } } +} + +private fun LanExport.mime() = when (this) { LanExport.TEXT -> "text/plain"; LanExport.CSV -> "text/csv"; LanExport.JSON -> "application/json" } +private fun LanExport.extension() = when (this) { LanExport.TEXT -> "txt"; LanExport.CSV -> "csv"; LanExport.JSON -> "json" } + +/** Three SAF launchers at the caller's scope; returns "open the picker for this format", false on failure. */ +@Composable +internal fun rememberDevicesExportLauncher(onResult: (Uri?) -> Unit): (LanExport) -> Boolean { + val callback by rememberUpdatedState(onResult) + val launchers = LanExport.entries.associateWith { format -> + rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument(format.mime())) { callback(it) } + } + return { format -> + try { launchers.getValue(format).launch("netkit-devices.${format.extension()}"); true } catch (_: Exception) { false } + } +} + +/** Warning that the file describes devices of the user's network, and the format choice. */ +@Composable +internal fun DevicesExportDialog(onDismiss: () -> Unit, onExport: (LanExport) -> Unit) { + val colors = NetKitTheme.colors + var format by rememberSaveable { mutableStateOf(LanExport.CSV) } + AlertDialog( + onDismissRequest = onDismiss, + containerColor = colors.surface, + modifier = Modifier.testTag("devices_export_dialog").semantics { testTagsAsResourceId = BuildConfig.DEBUG }, + title = { Text(stringResource(R.string.devices_export_title), style = NetKitType.panelTitle, color = colors.text) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { + StatusBanner(stringResource(R.string.devices_export_warning), StatusKind.WARNING) + Text(stringResource(R.string.devices_export_note), style = NetKitType.label, color = colors.muted) + Row(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + LanExport.entries.forEach { entry -> + SmallChip(stringResource(when (entry) { + LanExport.TEXT -> R.string.lan_format_text + LanExport.CSV -> R.string.lan_format_csv + LanExport.JSON -> R.string.lan_format_json + }), entry == format, Modifier.testTag("devices_export_format_${entry.extension()}")) { format = entry } + } + } + } + }, + confirmButton = { + TextButton({ onExport(format); onDismiss() }, Modifier.testTag("devices_export_confirm")) { + Text(stringResource(R.string.devices_export_confirm), color = colors.accent) + } + }, + dismissButton = { TextButton(onDismiss) { Text(stringResource(R.string.devices_export_cancel), color = colors.muted) } }, + ) +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesScreen.kt index d646421..a35c180 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesScreen.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesScreen.kt @@ -28,7 +28,9 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.Icon import androidx.compose.material3.Text @@ -36,6 +38,7 @@ import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -75,12 +78,19 @@ import cz.netkit.app.ui.KeyValueRows import cz.netkit.app.ui.NetKitIcons import cz.netkit.app.ui.NeutralButton import cz.netkit.app.ui.Panel +import cz.netkit.app.ui.PanelSegment import cz.netkit.app.ui.PrimaryButton import cz.netkit.app.ui.SectionCard import cz.netkit.app.ui.AdaptiveHeader import cz.netkit.app.ui.Spacing import cz.netkit.app.ui.StatTile import cz.netkit.app.ui.StatTiles +import cz.netkit.app.ui.deviceScanSummary +import cz.netkit.app.ui.pingSummary +import cz.netkit.app.ui.spoken +import cz.netkit.app.ui.spokenStatus +import androidx.compose.ui.semantics.heading +import cz.netkit.app.ui.OffscreenRunSummary import cz.netkit.app.ui.StatusBanner import cz.netkit.app.ui.StatusKind import cz.netkit.app.ui.Tag @@ -101,6 +111,11 @@ import cz.netkit.shared.lan.LanUpnpInfo import cz.netkit.shared.lan.OpenPort import cz.netkit.shared.lan.commonPorts import cz.netkit.shared.lan.lanDeviceDisplayName +import cz.netkit.shared.lan.LanWolAction +import cz.netkit.shared.lan.lanWolAction +import cz.netkit.shared.wol.SendFailure +import cz.netkit.shared.wol.WolDeviceDraft +import cz.netkit.shared.wol.WolUiState import java.util.Locale /** @@ -109,7 +124,8 @@ import java.util.Locale * The screen is active (automatic discovery allowed, running work kept) only while resumed. */ @Composable -fun DevicesScreen(viewModel: LanDevicesViewModel, onTrace: (String) -> Unit, onSsh: (String) -> Unit, modifier: Modifier = Modifier) { +fun DevicesScreen(viewModel: LanDevicesViewModel, onTrace: (String) -> Unit, onSsh: (String) -> Unit, modifier: Modifier = Modifier, + wol: LanWolBridge? = null) { val state by viewModel.state.collectAsStateWithLifecycle() val activity = androidx.activity.compose.LocalActivity.current LifecycleResumeEffect(Unit) { @@ -125,7 +141,7 @@ fun DevicesScreen(viewModel: LanDevicesViewModel, onTrace: (String) -> Unit, onS if (state.selectedAddress != null && device == null) viewModel.closeDevice() } BackHandler(enabled = device != null) { viewModel.closeDevice() } - if (device != null) DeviceDetail(state, device, viewModel, onTrace, onSsh, modifier) + if (device != null) DeviceDetail(state, device, viewModel, onTrace, onSsh, modifier, wol) else DeviceList(state, viewModel, listState, modifier) } @@ -135,23 +151,44 @@ fun DevicesScreen(viewModel: LanDevicesViewModel, onTrace: (String) -> Unit, onS @Composable private fun DeviceList(state: LanDevicesState, viewModel: LanDevicesViewModel, listState: LazyListState, modifier: Modifier) { val scan = state.scan + OffscreenRunSummary(scan.running, deviceScanSummary(state).spoken(), listState, "summary") val canRefresh = !state.loadingNetwork && !scan.running && state.network?.range != null - LazyColumn(modifier.testTag("devices_screen"), state = listState, contentPadding = PaddingValues(Spacing.normal), - verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { - item(key = "header") { + // Zadání 47 §3: export of the list; own ViewModel, SAF launchers at list scope. + val activity = androidx.activity.compose.LocalActivity.current + val exportModel = androidx.compose.runtime.remember(activity) { + (activity as? androidx.activity.ComponentActivity)?.let { androidx.lifecycle.ViewModelProvider(it)[DevicesExportViewModel::class.java] } + } + val exportNotice = exportModel?.notice?.collectAsStateWithLifecycle()?.value + val launchExport = rememberDevicesExportLauncher { uri -> exportModel?.save(uri) } + var exportOpen by androidx.compose.runtime.saveable.rememberSaveable { androidx.compose.runtime.mutableStateOf(false) } + val canExport = exportModel != null && state.devices.isNotEmpty() && !scan.running + // No list-wide spacing: device rows are adjacent slices of one panel; every other block adds its own gap. + LazyColumn(modifier.testTag("devices_screen"), state = listState, contentPadding = PaddingValues(Spacing.normal)) { + block("header") { LanHeader(stringResource(R.string.lan_devices_ui_title), networkSubtitle(state)) { + HeaderIconButton(NetKitIcons.Download, stringResource(R.string.devices_export), { exportOpen = true }, + Modifier.testTag("devices_export"), enabled = canExport) HeaderIconButton(NetKitIcons.Refresh, stringResource(R.string.lan_devices_ui_refresh_cd), viewModel::refresh, Modifier.testTag("devices_refresh"), enabled = canRefresh) } } - if (state.askConsent) item(key = "consent") { ConsentCard(state, viewModel) } - item(key = "summary") { Summary(state, viewModel) } - if (scan.running) item(key = "progress") { LanProgress(progressOf(scan.done, scan.total)) } - else if (state.identification == LanRunStatus.RUNNING) item(key = "progress") { LanProgress(null) } - if (state.icmpUnavailable) item(key = "icmp") { StatusBanner(stringResource(R.string.lan_devices_icmp_fallback), StatusKind.WARNING) } - if (state.error != null) item(key = "error") { ErrorBanner(state, viewModel) } - if (state.devices.isNotEmpty()) item(key = "devices") { DevicePanel(state.devices, viewModel::openDevice) } - else if (!scan.running && !state.loadingNetwork) item(key = "empty") { + exportNotice?.let { notice -> + block("export_notice") { + Column(Modifier.testTag("devices_export_notice")) { + StatusBanner(stringResource(if (notice == cz.netkit.app.wifi.ExportNotice.SAVED) R.string.devices_export_saved + else R.string.devices_export_failed), if (notice == cz.netkit.app.wifi.ExportNotice.SAVED) StatusKind.INFO else StatusKind.ERROR) + } + } + } + if (state.askConsent) block("consent") { ConsentCard(state, viewModel) } + block("summary") { Summary(state, viewModel) } + if (scan.running) block("progress") { LanProgress(progressOf(scan.done, scan.total)) } + else if (state.identification == LanRunStatus.RUNNING) block("progress") { LanProgress(null) } + if (state.icmpUnavailable) block("icmp") { StatusBanner(stringResource(R.string.lan_devices_icmp_fallback), StatusKind.WARNING) } + if (state.error != null) block("error") { ErrorBanner(state, viewModel) } + state.network?.info?.let { info -> block("network_info") { NetworkInfoCard(info) } } + if (state.devices.isNotEmpty()) deviceRows(state.devices, viewModel::openDevice) + else if (!scan.running && !state.loadingNetwork) block("empty") { EmptyState(stringResource(R.string.lan_devices_empty), NetKitIcons.Devices) { PrimaryButton(stringResource(R.string.lan_devices_refresh), viewModel::refresh, Modifier.testTag("devices_empty_refresh"), icon = NetKitIcons.Refresh, enabled = canRefresh) @@ -159,6 +196,31 @@ private fun DeviceList(state: LanDevicesState, viewModel: LanDevicesViewModel, l } item(key = "info") { InfoNote(stringResource(R.string.lan_devices_ui_info_summary), stringResource(R.string.lan_devid_info_detail)) } } + if (exportOpen && exportModel != null) { + DevicesExportDialog(onDismiss = { exportOpen = false }) { format -> + if (exportModel.prepare(state.devices, format, state.network?.range) && !launchExport(format)) exportModel.launchFailed() + } + } +} + +/** A list block followed by the screen's standard gap. */ +private fun LazyListScope.block(key: String, content: @Composable () -> Unit) = + item(key = key) { Box(Modifier.padding(bottom = Spacing.medium)) { content() } } + +/** + * One lazy item per device (zadání 39 §2.1), keyed by address: only visible rows compose, a row + * keeps its state while devices are inserted around it, and the list keeps its scroll anchor + * (the first visible key) while discovery adds hosts above it. Consecutive [PanelSegment]s draw + * the former single panel. + */ +internal fun LazyListScope.deviceRows(devices: List, onOpen: (String) -> Unit) { + itemsIndexed(devices, key = { _, device -> "device:" + device.address }, contentType = { _, _ -> "device" }) { index, device -> + val last = index == devices.lastIndex + PanelSegment(first = index == 0, last = last, modifier = if (last) Modifier.padding(bottom = Spacing.medium) else Modifier, + padding = Spacing.normal) { + DeviceRow(device, showDivider = index > 0, onOpen = onOpen) + } + } } /** "192.168.0.0/24 · SSID": the range in mono; the SSID stays as broadcast (it is case-sensitive). */ @@ -180,7 +242,7 @@ private fun ConsentCard(state: LanDevicesState, viewModel: LanDevicesViewModel) val range = network.range ?: return val where = network.ssid?.let { stringResource(R.string.lan_devices_ui_network_ssid, it, range) } ?: range Panel(Modifier.testTag("devices_consent")) { - Text(stringResource(R.string.lan_devices_consent_title), style = NetKitType.panelTitle, color = colors.text) + Text(stringResource(R.string.lan_devices_consent_title), Modifier.semantics { heading() }, style = NetKitType.panelTitle, color = colors.text) Text(stringResource(R.string.lan_devices_consent_body, where), style = NetKitType.body, color = colors.text) Text(stringResource(R.string.lan_devices_ui_consent_legal), style = NetKitType.label, color = colors.muted) if (network.ssid == null) Text(stringResource(R.string.lan_devices_consent_session), style = NetKitType.label, color = colors.muted) @@ -190,7 +252,7 @@ private fun ConsentCard(state: LanDevicesState, viewModel: LanDevicesViewModel) NeutralButton(stringResource(R.string.lan_devices_consent_deny), viewModel::denyAutoDiscovery, Modifier.fillMaxWidth().testTag("devices_consent_deny")) } - Text(stringResource(R.string.lan_devices_ui_consent_manual), style = NetKitType.label, color = colors.dim) + Text(stringResource(R.string.lan_devices_ui_consent_manual), style = NetKitType.label, color = colors.muted) } } @@ -216,10 +278,11 @@ private fun Summary(state: LanDevicesState, viewModel: LanDevicesViewModel) { Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { val middle = Modifier.align(Alignment.CenterVertically) - if (scan.running) Tag(stringResource(R.string.lan_devices_ui_scan_running, scan.done, scan.total), Tone.ACCENT, dot = true, - modifier = middle.testTag("devices_scan_running")) - else if (showCount) Tag(pluralStringResource(R.plurals.lan_devices_ui_scan_found, count, count), Tone.ACCENT, dot = true, modifier = middle) - if (cancelled) Tag(stringResource(R.string.lan_devices_ui_scan_cancelled), Tone.WARN, modifier = middle) + if (scan.running || showCount) DeviceScanTag(state, middle) + if (cancelled) { + val label = stringResource(R.string.lan_devices_ui_scan_cancelled) + Tag(label, Tone.WARN, modifier = middle.spokenStatus(label)) + } consent?.let { Tag(it, modifier = middle) } if (identifying) Text(stringResource(R.string.lan_devid_identifying), middle.testTag("devices_identifying"), style = NetKitType.label, color = colors.muted) @@ -230,8 +293,22 @@ private fun Summary(state: LanDevicesState, viewModel: LanDevicesViewModel) { middle.testTag("devices_consent_change"), small = true) } if (state.consent == DiscoveryConsent.ALLOWED && !state.consentRemembered && state.network?.ssid == null) - Text(stringResource(R.string.lan_devices_consent_session), style = NetKitType.label, color = colors.dim) + Text(stringResource(R.string.lan_devices_consent_session), style = NetKitType.label, color = colors.muted) + } +} + +@Composable +internal fun DeviceScanTag(state: LanDevicesState, modifier: Modifier = Modifier) { + val scan = state.scan + val count = state.devices.size + val label = if (scan.running) stringResource(R.string.lan_devices_ui_scan_running, scan.done, scan.total) + else pluralStringResource(R.plurals.lan_devices_ui_scan_found, count, count) + val status = when { + scan.running -> modifier.testTag("devices_scan_running").spokenStatus(stringResource(R.string.a11y_scanning)) + scan.status == LanRunStatus.FINISHED -> modifier.spokenStatus(deviceScanSummary(state).spoken()) + else -> modifier } + Tag(label, Tone.ACCENT, dot = true, modifier = status) } @Composable @@ -244,17 +321,7 @@ private fun ErrorBanner(state: LanDevicesState, viewModel: LanDevicesViewModel) } @Composable -private fun DevicePanel(devices: List, onOpen: (String) -> Unit) { - // A /24 caps the list at 254 hosts, so one non-lazy panel stays cheap; rows skip when unchanged. - Panel(padding = Spacing.normal) { - Column { - devices.forEachIndexed { index, device -> DeviceRow(device, showDivider = index > 0, onOpen = onOpen) } - } - } -} - -@Composable -private fun DeviceRow(device: LanDevice, showDivider: Boolean, onOpen: (String) -> Unit) { +internal fun DeviceRow(device: LanDevice, showDivider: Boolean, onOpen: (String) -> Unit) { val name = lanDeviceDisplayName(device) val parts = listOfNotNull( name.source?.let { stringResource(nameSourceChip(it)) }, @@ -283,7 +350,7 @@ private fun DeviceRow(device: LanDevice, showDivider: Boolean, onOpen: (String) @Composable private fun DeviceDetail( state: LanDevicesState, device: LanDevice, viewModel: LanDevicesViewModel, - onTrace: (String) -> Unit, onSsh: (String) -> Unit, modifier: Modifier, + onTrace: (String) -> Unit, onSsh: (String) -> Unit, modifier: Modifier, wol: LanWolBridge?, ) { val address = device.address LazyColumn(modifier.testTag("device_detail"), contentPadding = PaddingValues(Spacing.normal), @@ -298,6 +365,7 @@ private fun DeviceDetail( if (state.error != null) item(key = "error") { ErrorBanner(state, viewModel) } if (!device.isSelf || device.names.isNotEmpty()) item(key = "identity") { IdentityPanel(state, device) } item(key = "ports") { PortsPanel(state, device, viewModel) } + if (!device.isSelf) item(key = "services") { ServicesPanel(state, device, viewModel) } if (!device.isSelf) item(key = "actions") { Row(horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { PrimaryButton(stringResource(R.string.lan_trace), { onTrace(address) }, Modifier.weight(1f).testTag("device_trace"), @@ -306,6 +374,44 @@ private fun DeviceDetail( icon = NetKitIcons.Terminal) } } + if (wol != null) lanWolAction(device, wol.state.devices)?.let { action -> item(key = "wol") { WolAction(action, wol) } } + } +} + +/** What the device detail needs from the WoL tab (zadání 36 §2.7); waking still needs a tap here. */ +class LanWolBridge(val state: WolUiState, val onWake: (String) -> Unit, val onAdd: (WolDeviceDraft) -> Unit) + +@Composable +private fun WolAction(action: LanWolAction, wol: LanWolBridge) { + val colors = NetKitTheme.colors + val ready = !wol.state.loading && !wol.state.loadFailed + Column(verticalArrangement = Arrangement.spacedBy(Spacing.tiny)) { + when (action) { + is LanWolAction.Wake -> action.candidates.forEach { candidate -> + // Each button names its real target, so a name collision cannot hide which device wakes. + val sending = wol.state.sendingDeviceId == candidate.deviceId + TonalButton(stringResource(R.string.lan_wol_wake_named, candidate.name), { wol.onWake(candidate.deviceId) }, + Modifier.fillMaxWidth().testTag("device_wol_wake_${candidate.deviceId}"), + icon = NetKitIcons.Power, enabled = ready && wol.state.sendingDeviceId == null && !wol.state.saving) + val outcome = wol.state.outcomes[candidate.deviceId] + val text = when { + sending -> stringResource(R.string.lan_wol_sending) + outcome == null -> null + outcome.sent -> stringResource(R.string.lan_wol_sent) + outcome.reason == SendFailure.NO_WIFI -> stringResource(R.string.lan_wol_no_wifi) + outcome.reason == SendFailure.CANCELLED -> null + else -> stringResource(R.string.lan_wol_failed) + } + text?.let { Text(it, Modifier.testTag("device_wol_status_${candidate.deviceId}"), style = NetKitType.label, + color = if (outcome?.sent == false) colors.err else colors.muted) } + } + is LanWolAction.Add -> { + NeutralButton(stringResource(R.string.lan_wol_add), { wol.onAdd(action.draft) }, Modifier.fillMaxWidth().testTag("device_wol_add"), + icon = NetKitIcons.Power, enabled = ready && wol.state.draft == null) + Text(if (action.draft.mac.isNotEmpty()) stringResource(R.string.lan_wol_mac_netbios, action.draft.mac) + else stringResource(R.string.lan_wol_mac_manual), Modifier.testTag("device_wol_mac_hint"), style = NetKitType.label, color = colors.muted) + } + } } } @@ -382,7 +488,12 @@ private fun PingStats(state: LanDevicesState, device: LanDevice, viewModel: LanD Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { StatTiles(listOf(pingTile, lossTile, methodTile)) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { - Text(detail, Modifier.weight(1f), style = NetKitType.label, color = if (icmpFailed) colors.warn else colors.muted) + val status = when (ping?.status) { + LanRunStatus.RUNNING -> Modifier.spokenStatus(stringResource(R.string.a11y_ping_running)) + LanRunStatus.FINISHED -> Modifier.spokenStatus((pingSummary(samples.size, stats?.received ?: 0, samples).spoken() + " " + detail).trim()) + else -> Modifier + } + Text(detail, Modifier.weight(1f).then(status), style = NetKitType.label, color = if (icmpFailed) colors.warn else colors.muted) NeutralButton(stringResource(R.string.lan_devices_ping_again), { viewModel.openDevice(device.address) }, Modifier.testTag("device_ping_again"), icon = NetKitIcons.Refresh, enabled = !running, small = true) } @@ -390,7 +501,7 @@ private fun PingStats(state: LanDevicesState, device: LanDevice, viewModel: LanD } /** - * Only the names and fields that were found, then one dim line for what was not: NetBIOS and + * Only the names and fields that were found, then one muted line for what was not: NetBIOS and * reverse DNS come from discovery, mDNS and UPnP count as "not found" only after a finished * identification pass that queried this device; before that the line says why they are unknown. * A presentation URL is opened only on tap and only if [LanUpnpInfo.openUrl] passed the @@ -402,7 +513,8 @@ private fun IdentityPanel(state: LanDevicesState, device: LanDevice) { val running = !device.isSelf && state.identification == LanRunStatus.RUNNING val known = LanNameSource.entries.mapNotNull { source -> device.names.firstOrNull { it.source == source }?.let { KeyValue(stringResource(nameSourceLabel(source)), it.value) } - } + listOfNotNull(device.netBiosGroup?.let { KeyValue(stringResource(R.string.lan_devices_netbios_group), it) }) + } + listOfNotNull(device.netBiosGroup?.let { KeyValue(stringResource(R.string.lan_devices_netbios_group), it) }, + device.netBiosMac?.let { KeyValue(stringResource(R.string.lan_devices_netbios_mac), it) }) val line = if (device.isSelf) null else identityLine(state, device, running) Box(Modifier.testTag("device_identity")) { SectionCard(stringResource(R.string.lan_devid_section), trailing = if (running) ({ @@ -415,7 +527,7 @@ private fun IdentityPanel(state: LanDevicesState, device: LanDevice) { } } device.upnp?.let { UpnpRows(it) } - line?.let { Text(it, Modifier.testTag("device_identity_missing"), style = NetKitType.label, color = colors.dim) } + line?.let { Text(it, Modifier.testTag("device_identity_missing"), style = NetKitType.label, color = colors.muted) } } } } @@ -457,7 +569,7 @@ private fun UpnpRows(info: LanUpnpInfo) { Column(Modifier.testTag("device_upnp"), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { Eyebrow(stringResource(R.string.lan_devid_upnp)) if (rows.isNotEmpty()) KeyValueRows(rows) - if (!info.hasDescription) Text(stringResource(R.string.lan_devid_upnp_no_description), style = NetKitType.label, color = colors.dim) + if (!info.hasDescription) Text(stringResource(R.string.lan_devid_upnp_no_description), style = NetKitType.label, color = colors.muted) info.openUrl?.let { url -> TonalButton(stringResource(R.string.lan_devid_upnp_open), { openInBrowser(context, url) }, Modifier.testTag("device_upnp_open"), icon = NetKitIcons.Globe, small = true) @@ -484,12 +596,14 @@ private fun PortsPanel(state: LanDevicesState, device: LanDevice, viewModel: Lan val meta = if (!running && (scanned || device.openPorts.isNotEmpty())) stringResource(R.string.lan_devices_ui_ports_meta, device.openPorts.size, total) else null Box(Modifier.testTag("device_ports")) { - SectionCard(stringResource(R.string.lan_devices_ui_section_ports), meta = meta) { + SectionCard(stringResource(R.string.lan_devices_ui_section_ports), meta = meta, + metaModifier = if (scan?.status == LanRunStatus.FINISHED) + Modifier.spokenStatus(stringResource(R.string.a11y_ports_done, scan.counts.open, scan.done)) else Modifier) { when { runningScan != null -> Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { Text(stringResource(R.string.lan_devices_ports_progress, runningScan.done, runningScan.total, device.openPorts.size), - Modifier.weight(1f), style = NetKitType.label, color = colors.muted) + Modifier.weight(1f).spokenStatus(stringResource(R.string.a11y_ports_running)), style = NetKitType.label, color = colors.muted) NeutralButton(stringResource(R.string.lan_cancel), viewModel::cancelPortScan, Modifier.testTag("device_ports_cancel"), small = true) } LanProgress(progressOf(runningScan.done, runningScan.total)) @@ -503,7 +617,7 @@ private fun PortsPanel(state: LanDevicesState, device: LanDevice, viewModel: Lan else if (!running && scanned) Text(stringResource(R.string.lan_devices_no_open_ports), style = NetKitType.label, color = colors.muted) if (!running && (scan != null || scanned || device.openPorts.isNotEmpty())) { if (scan?.status == LanRunStatus.CANCELLED || (!scanned && device.openPorts.isNotEmpty())) - Text(stringResource(R.string.lan_devices_ui_ports_cancelled), style = NetKitType.label, color = colors.dim) + Text(stringResource(R.string.lan_devices_ui_ports_cancelled), style = NetKitType.label, color = colors.muted) TonalButton(stringResource(R.string.lan_devices_ui_ports_again), { viewModel.scanPorts(address) }, Modifier.testTag("device_scan_ports_again"), icon = NetKitIcons.Refresh, small = true) } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticLookup.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticLookup.kt new file mode 100644 index 0000000..f39ce5f --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticLookup.kt @@ -0,0 +1,94 @@ +package cz.netkit.app.lan + +import android.net.DnsResolver +import android.net.Network +import android.os.CancellationSignal +import cz.netkit.app.R +import cz.netkit.app.speed.readBounded +import cz.netkit.shared.lan.* +import cz.netkit.shared.net.NetKind +import cz.netkit.shared.publicip.* +import kotlinx.coroutines.suspendCancellableCoroutine +import kotlinx.coroutines.withTimeout +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import java.io.IOException +import java.util.concurrent.Executor + +/** No implicit fallback. A missing participant invalidates a requested comparison. */ +internal fun recordRoutes(active: T, kind: NetKind, wifi: T?, compare: Boolean): List> = + when { + !compare -> listOf(kind to active) + kind == NetKind.VPN && wifi != null && wifi != active -> listOf(kind to active, NetKind.WIFI to wifi) + else -> emptyList() + } + +internal class RecordCallback(private val complete: (Result) -> Unit) : DnsResolver.Callback { + override fun onAnswer(answer: ByteArray, rcode: Int) { + val reply = parseRecordReply(answer) + complete(if (reply != null && (reply.rcode and 15) == (rcode and 15)) Result.success(reply) + else Result.failure(DnsFailure(R.string.diag_bad_dns))) + } + override fun onError(error: DnsResolver.DnsException) { + complete(Result.failure(DnsFailure(R.string.lan_dns_resolver, cause = error))) + } +} + +internal suspend fun queryRecords(network: Network, name: String, type: RecordType): RecordReply = withTimeout(5000) { + suspendCancellableCoroutine { continuation -> + val signal = CancellationSignal() + continuation.invokeOnCancellation { signal.cancel() } + DnsResolver.getInstance().rawQuery(network, name, DnsResolver.CLASS_IN, type.code, DnsResolver.FLAG_NO_CACHE_LOOKUP, + Executor { it.run() }, signal, RecordCallback { continuation.resumeWith(it) }) + } +} + +internal class DiagnosticFailure(val label: Int, val retryAfterSeconds: Long? = null) : IOException() + +internal suspend fun lookupRdap(input: String, enabled: () -> Boolean, request: suspend (String) -> RdapInfo): RdapInfo { + if (!enabled()) throw DiagnosticFailure(R.string.diag_rdap_disabled) + val path = rdapPath(input) ?: throw DiagnosticFailure(R.string.diag_rdap_invalid) + return request(path) +} + +private val rirHosts = setOf("rdap.arin.net", "rdap.db.ripe.net", "rdap.apnic.net", "rdap.lacnic.net", "rdap.afrinic.net") + +internal suspend fun fetchRdap(path: String, client: OkHttpClient, enabled: () -> Boolean): RdapInfo { + var url = "https://rdap.org/$path".toHttpUrl() + repeat(6) { hop -> + if (!enabled()) throw DiagnosticFailure(R.string.diag_rdap_disabled) + val call = client.newCall(Request.Builder().url(url).header("Accept", "application/rdap+json, application/json") + .header("User-Agent", diagnosticUserAgent).build()) + var location: String? = null + val result = diagnosticIo(call::cancel) { + call.execute().use { response -> + if (response.isRedirect) { + location = response.header("Location") + null + } else { + when (response.code) { + 403 -> throw DiagnosticFailure(R.string.diag_rdap_blocked) + 404 -> throw DiagnosticFailure(R.string.diag_rdap_unknown) + 429 -> { + val delay = response.header("Retry-After")?.takeIf { it.all { c -> c in '0'..'9' } }?.toLongOrNull() + ?: response.headers.getDate("Retry-After")?.let { + (it.toInstant().epochSecond - java.time.Instant.now().epochSecond).coerceAtLeast(0) + } + val label = if (url.host == "rdap.org") R.string.diag_rdap_bootstrap_limited else R.string.diag_rdap_limited + throw DiagnosticFailure(label, delay) + } + } + if (!response.isSuccessful) throw DiagnosticFailure(R.string.diag_rdap_response) + val body = readBounded(response.body, RDAP_MAX_BYTES) ?: throw DiagnosticFailure(R.string.diag_rdap_response) + parseRdap(body) ?: throw DiagnosticFailure(R.string.diag_rdap_response) + } + } + } + if (result != null) return result + url = location?.let(url::resolve)?.takeIf { + hop < 5 && it.isHttps && it.port == 443 && it.username.isEmpty() && it.password.isEmpty() && it.host in rirHosts + } ?: throw DiagnosticFailure(R.string.diag_rdap_redirect) + } + throw DiagnosticFailure(R.string.diag_rdap_redirect) +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticPanel.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticPanel.kt new file mode 100644 index 0000000..cee224e --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticPanel.kt @@ -0,0 +1,128 @@ +package cz.netkit.app.lan + +import android.content.Context +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import cz.netkit.app.R +import cz.netkit.app.net.netKindLabel +import cz.netkit.app.ui.* +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.shared.lan.* +import cz.netkit.shared.publicip.RdapInfo + +@Composable +internal fun DiagnosticPanel(state: LanUiState, model: LanViewModel) { + val label = when (state.tool) { + LanTool.RECORDS -> R.string.diag_dns_input + LanTool.WEB -> R.string.diag_url + else -> R.string.diag_ip_asn + } + val tool = when (state.tool) { + LanTool.RECORDS -> R.string.diag_records + LanTool.WEB -> R.string.diag_web + else -> R.string.diag_rdap + } + SectionCard(stringResource(tool), meta = stringResource(state.routeKind?.let(::netKindLabel) ?: R.string.net_kind_none)) { + TargetInput(state.diagnosticInput, model::diagnosticInput, label, !state.busy, requireNotNull(state.tool.targetField), + state.targets, model, Modifier.fillMaxWidth()) + if (state.tool == LanTool.RECORDS && !state.busy) { + Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + RecordType.entries.forEach { type -> ChoiceChip(type.name, state.recordType == type) { model.recordType(type) } } + } + } + when (state.tool) { + LanTool.RDAP -> Text(stringResource(R.string.diag_rdap_note)) + LanTool.WEB -> Text(stringResource(R.string.diag_web_note)) + else -> Unit + } + if (state.busy) NeutralButton(stringResource(R.string.lan_stop), model::cancelActive) + else if (state.webConfirmation != null) { + val target = state.webConfirmation + val source = target.redirectFromHost + val address = target.address.hostAddress + Text(when { + source != null && target.route == WebRoute.FAKE_IP -> + stringResource(R.string.diag_fake_ip_redirect_confirmation, source, target.url.toString(), address) + target.route == WebRoute.FAKE_IP -> stringResource(R.string.diag_fake_ip_confirmation, target.url.host, address) + else -> stringResource(R.string.diag_local_confirmation, target.url.host, address) + }) + PrimaryButton(stringResource(R.string.diag_local_continue), { model.confirmWeb(target) }) + NeutralButton(stringResource(R.string.lan_cancel), model::cancelActive) + } else { + PrimaryButton(stringResource(R.string.lan_start), { model.startDiagnostic() }, enabled = state.diagnosticInput.isNotBlank()) + state.redirectPrefill?.let { target -> + NeutralButton(stringResource(R.string.diag_prefill_redirect), { model.diagnosticInput(target) }) + } + if (state.tool == LanTool.RECORDS && state.canCompare) { + Text(stringResource(R.string.diag_split_warning), color = NetKitTheme.colors.muted) + NeutralButton(stringResource(R.string.diag_split), { model.startDiagnostic(compare = true) }, + enabled = state.diagnosticInput.isNotBlank()) + } + } + } +} + +internal fun RecordReply.rows(query: String, type: RecordType, route: String): List { + val bits = listOf("AA" to 0x0400, "TC" to 0x0200, "RD" to 0x0100, "RA" to 0x0080) + val header = "RCODE=$rcode ${dnsRcodeName(rcode).orEmpty()} · " + bits.joinToString(" ") { (name, mask) -> + "$name=${if (flags and mask != 0) 1 else 0}" + } + return listOf(LanResult(query, type.name, method = route, detail = header)) + records.map { rr -> + val type = RecordType.entries.firstOrNull { it.code == rr.type }?.name ?: "TYPE${rr.type}" + LanResult(rr.owner, "$type · TTL=${rr.ttl}", route, detail = rr.value) + } +} + +internal fun WebError.label() = when (this) { + WebError.URL -> R.string.diag_invalid_url + WebError.REDIRECT_LIMIT -> R.string.diag_redirect_limit + WebError.REDIRECT_PORT -> R.string.diag_redirect_port + WebError.ROUTE_CHANGED -> R.string.diag_web_route_changed + WebError.LOCAL_REDIRECT -> R.string.diag_redirect_local + WebError.TLS_NAME -> R.string.diag_tls_name + WebError.TLS_TRUST -> R.string.diag_tls_trust + WebError.TLS_VALIDITY -> R.string.diag_tls_validity + WebError.TLS_HANDSHAKE -> R.string.diag_tls_handshake + WebError.DNS -> R.string.diag_dns_failed + WebError.CONNECT -> R.string.diag_connect_failed + WebError.TIMEOUT -> R.string.lan_operation_timeout + WebError.TLS -> R.string.diag_tls_error + WebError.TRANSPORT -> R.string.lan_operation_failed +} + +internal fun Context.webLines(report: WebReport): List> = buildList { + val missing = getString(R.string.lan_missing_value) + for (hop in report.hops) { + fun title(label: String) = if (hop.fromPreviousRun) getString(R.string.diag_previous_measurement, label) else label + val times = hop.times + add(title("${hop.method} ${hop.status}") to buildString { + append(hop.url) + append('\n').append(getString(R.string.diag_peer_ip, hop.peer.hostAddress)) + hop.location?.let { append("\nLocation: ").append(sanitizeLanText(it, 8192)) } + hop.server?.let { append("\nServer: ").append(sanitizeLanText(it)) } + hop.hsts?.let { append("\nStrict-Transport-Security: ").append(sanitizeLanText(it)) } + append('\n').append(getString(R.string.diag_times, times.dns ?: missing, times.tcp ?: missing, + times.tls ?: missing, times.ttfb ?: missing)) + }) + hop.tls?.let { tls -> + add(title(getString(R.string.diag_tls_valid)) to "${tls.version} · ${tls.cipher}") + tls.certificates.forEachIndexed { index, c -> + add(title(getString(R.string.diag_cert, index + 1)) to + getString(R.string.diag_cert_fields, c.subject, c.issuer, c.from, c.until, c.san.ifEmpty { missing }, c.fingerprint)) + } + } + } + report.skippedGet?.let { add(getString(R.string.diag_get_skipped) to it.toString()) } + report.failedUrl?.let { add(getString(R.string.diag_url) to it.toString()) } + report.reason?.takeIf { it.isNotBlank() }?.let { add(getString(R.string.diag_technical_detail) to it) } +} + +internal fun Context.rdapLines(info: RdapInfo) = listOf( + R.string.diag_network to info.network, R.string.diag_name to info.name, R.string.diag_country to info.country, + R.string.diag_org to info.organization, R.string.diag_abuse to info.abuseEmail, R.string.diag_asn to info.asn, +).map { (label, value) -> getString(label) to (value ?: getString(R.string.lan_missing_value)) } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/DnsLookup.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/DnsLookup.kt new file mode 100644 index 0000000..c140589 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/DnsLookup.kt @@ -0,0 +1,24 @@ +package cz.netkit.app.lan + +import android.net.DnsResolver +import cz.netkit.app.R +import java.io.IOException +import java.net.InetAddress + +internal class DnsFailure(val resource: Int, val rcode: Int? = null, cause: Throwable? = null) : IOException(cause) + +/** The resolver can fail without receiving a DNS response. Only onAnswer carries a wire RCODE. */ +internal class LookupCallback(private val complete: (Result>) -> Unit) : DnsResolver.Callback> { + override fun onAnswer(answer: List, rcode: Int) { + val error = when { + rcode == 3 -> DnsFailure(R.string.lan_dns_nxdomain) + rcode != 0 -> DnsFailure(R.string.lan_dns_rcode, rcode) + answer.isEmpty() -> DnsFailure(R.string.lan_dns_no_record) + else -> null + } + complete(if (error == null) Result.success(answer) else Result.failure(error)) + } + override fun onError(error: DnsResolver.DnsException) { + complete(Result.failure(DnsFailure(R.string.lan_dns_resolver, cause = error))) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt index 75df8ac..727717a 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt @@ -11,6 +11,7 @@ import android.net.nsd.NsdManager import android.net.nsd.NsdServiceInfo import android.os.Build import android.os.CancellationSignal +import cz.netkit.app.R import cz.netkit.app.net.ActiveNetworkInfo import cz.netkit.app.net.readActiveNetworkInfo import cz.netkit.shared.lan.* @@ -28,6 +29,7 @@ import kotlin.coroutines.resumeWithException import kotlinx.coroutines.* import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow +import kotlinx.coroutines.flow.conflate import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map @@ -67,7 +69,16 @@ internal class LanBackend(context: Context) { LanWifi(network, address.address.hostAddress ?: return@firstNotNullOfOrNull null, address.prefixLength, link.interfaceName ?: return@firstNotNullOfOrNull null) } } - fun observeWifi() = callbackFlow { + @Suppress("DEPRECATION") + fun diagnosticWifi(): Network? = connectivity.allNetworks.firstOrNull { network -> + val caps = connectivity.getNetworkCapabilities(network) + caps?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true && + caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN) + } + + fun observeWifi() = wifiChanges().map { withContext(Dispatchers.IO) { wifi() } }.distinctUntilChanged() + + fun wifiChanges() = callbackFlow { val callback = object : ConnectivityManager.NetworkCallback() { override fun onAvailable(network: Network) { trySend(Unit) } override fun onLost(network: Network) { trySend(Unit) } @@ -79,7 +90,21 @@ internal class LanBackend(context: Context) { connectivity.registerNetworkCallback(request, callback) trySend(Unit) awaitClose { connectivity.unregisterNetworkCallback(callback) } - }.map { withContext(Dispatchers.IO) { wifi() } }.distinctUntilChanged() + } + + /** + * Every LinkProperties change of a non-VPN Wi-Fi, also when [observeWifi] stays the same (same + * address/prefix/interface): new IPv6 address, DNS or domain from DHCP/RA (revize 39/1). + */ + fun linkPropertiesChanges() = callbackFlow { + val callback = object : ConnectivityManager.NetworkCallback() { + override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) { trySend(network) } + } + val request = NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI) + .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build() + connectivity.registerNetworkCallback(request, callback) + awaitClose { connectivity.unregisterNetworkCallback(callback) } + }.conflate() fun checkWifi(wifi: LanWifi) { val caps = connectivity.getNetworkCapabilities(wifi.network) @@ -110,12 +135,12 @@ internal class LanBackend(context: Context) { } /** Forward lookup on [route]'s network, A and AAAA, without falling back to another network. */ - suspend fun resolve(route: ToolRoute, host: String): List = withTimeout(4000) { + suspend fun resolve(route: ToolRoute, host: String): List = withTimeoutOrNull(4000) { checkRoute(route) - ipv4Number(host)?.let { return@withTimeout listOf(numericAddress(host)) } + lanNumericAddress(host)?.let { return@withTimeoutOrNull listOf(toolInetAddress(it.text, route.interfaceName)) } require(validLanHost(host)) lookup(route.network, host) - } + } ?: throw DnsFailure(R.string.lan_dns_timeout) suspend fun reverse(route: ToolRoute, address: String): String { // An active-network route over Wi-Fi keeps checkRoute(), so a later VPN still stops the run. route.wifi?.takeUnless { route.followsDefault }?.let { return reverse(it, address) } @@ -126,6 +151,13 @@ internal class LanBackend(context: Context) { ptr(route.network, address) } } + suspend fun pingWithOptions(route: ToolRoute, address: String, timeoutMs: Int, payload: Int, df: Boolean): PingReply { + checkRoute(route) + // IPv6 (zadání 39): ICMPv6 ping socket; DF does not exist there, the MTU sweep stays IPv4 (ipv6Refusal). + if (isIpv6Target(address)) return WifiIcmp6.echo(route.network, toolInetAddress(address, route.interfaceName) as java.net.Inet6Address, + timeoutMs, payload.coerceAtMost(1452)) + return WifiIcmp.echo(route.network, address, timeoutMs, payload, df) + } suspend fun ping(route: ToolRoute, address: String, timeoutMs: Int, ttl: Int? = null): PingReply { route.wifi?.takeUnless { route.followsDefault }?.let { return ping(it, address, timeoutMs, ttl) } require(ipv4Number(address) != null) @@ -135,26 +167,27 @@ internal class LanBackend(context: Context) { } suspend fun tcpProbe(route: ToolRoute, address: String, port: Int, timeoutMs: Int, banner: Boolean = false): TcpProbeResult { route.wifi?.takeUnless { route.followsDefault }?.let { return tcpProbe(it, address, port, timeoutMs, banner) } - return boundTcpProbe(route.network, address, port, timeoutMs, banner, {}) { checkRoute(route) } + return boundTcpProbe(route.network, route.interfaceName, address, port, timeoutMs, banner, {}) { checkRoute(route) } } - suspend fun resolve(wifi: LanWifi, host: String): List = withTimeout(4000) { + suspend fun resolve(wifi: LanWifi, host: String): List = withTimeoutOrNull(4000) { checkWifi(wifi) - ipv4Number(host)?.let { return@withTimeout listOf(numericAddress(host)) } + lanNumericAddress(host)?.let { return@withTimeoutOrNull listOf(toolInetAddress(it.text, wifi.interfaceName)) } require(validLanHost(host)) lookup(wifi.network, host) - } - private suspend fun lookup(network: Network, host: String): List = suspendCancellableCoroutine { cont -> + } ?: throw DnsFailure(R.string.lan_dns_timeout) + /** + * A and AAAA as two typed queries (zadání 39 §2.3): the untyped query asks for AAAA only when + * the network has IPv6, so an IPv4-only Wi-Fi would never show an AAAA record. IPv4 answers + * come first; a failure of one type is reported only when the other has no address either. + */ + private suspend fun lookup(network: Network, host: String): List = + lookupBoth({ typedLookup(network, host, DnsResolver.TYPE_A) }, { typedLookup(network, host, DnsResolver.TYPE_AAAA) }) + private suspend fun typedLookup(network: Network, host: String, type: Int): List = suspendCancellableCoroutine { cont -> val signal = CancellationSignal() cont.invokeOnCancellation { signal.cancel() } - DnsResolver.getInstance().query(network, host, DnsResolver.FLAG_EMPTY, direct, signal, - object : DnsResolver.Callback> { - override fun onAnswer(answer: List, rcode: Int) { - if (!cont.isActive) return - if (rcode == 0 && answer.isNotEmpty()) cont.resume(answer) else cont.resumeWithException(IOException("DNS")) - } - override fun onError(error: DnsResolver.DnsException) { if (cont.isActive) cont.resumeWithException(error) } - }) + DnsResolver.getInstance().query(network, host, type, DnsResolver.FLAG_EMPTY, direct, signal, + LookupCallback { result -> if (cont.isActive) cont.resumeWith(result) }) } suspend fun reverse(wifi: LanWifi, address: String): String = withTimeout(1500) { require(ipv4Number(address) != null) @@ -215,24 +248,27 @@ internal class LanBackend(context: Context) { tcpProbe(wifi, address, port, timeoutMs, banner, onConnected).result suspend fun tcpProbe(wifi: LanWifi, address: String, port: Int, timeoutMs: Int, banner: Boolean = false, onConnected: () -> Unit = {}): TcpProbeResult = - boundTcpProbe(wifi.network, address, port, timeoutMs, banner, onConnected) { checkWifi(wifi) } + boundTcpProbe(wifi.network, wifi.interfaceName, address, port, timeoutMs, banner, onConnected) { checkWifi(wifi) } - private suspend fun boundTcpProbe(network: Network, address: String, port: Int, timeoutMs: Int, banner: Boolean, + private suspend fun boundTcpProbe(network: Network, interfaceName: String?, address: String, port: Int, timeoutMs: Int, banner: Boolean, onConnected: () -> Unit, check: () -> Unit): TcpProbeResult = withContext(probes) { - require(ipv4Number(address) != null && port in 1..65535) + require(lanNumericAddress(address) != null && port in 1..65535) check() suspendCancellableCoroutine { cont -> val socket = Socket() cont.invokeOnCancellation { try { socket.close() } catch (_: IOException) { } } try { if (cont.isActive) { - val result = probeTcpSocket(socket, numericAddress(address), port, timeoutMs, banner, network::bindSocket, onConnected) + val result = probeTcpSocket(socket, toolInetAddress(address, interfaceName), port, timeoutMs, banner, network::bindSocket, onConnected) if (cont.isActive) cont.resume(result) } } finally { try { socket.close() } catch (_: IOException) { /* A completed connect remains OPEN. */ } } } } + /** On-link IPv6 prefixes of [network] (global/ULA), for the IPv6 target confirmation. */ + fun ipv6Prefixes(network: Network): List = ipv6Prefixes(connectivity.getLinkProperties(network)) + /** Older APIs cannot guarantee both network scoping and cancellation of service resolution. */ fun services(wifi: LanWifi, type: String) = callbackFlow { if (Build.VERSION.SDK_INT < 34) throw UnsupportedOperationException("NSD_API") @@ -288,7 +324,15 @@ internal class LanBackend(context: Context) { } } -private fun numericAddress(address: String): InetAddress = InetAddress.getByAddress(address.split('.').map { it.toInt().toByte() }.toByteArray()) + +/** Typed A/AAAA results: addresses of both in order A, AAAA; with none, the A failure (else the AAAA one). */ +internal fun mergeLookups(v4: Result>, v6: Result>): List { + (v4.exceptionOrNull() as? kotlinx.coroutines.CancellationException)?.let { throw it } + (v6.exceptionOrNull() as? kotlinx.coroutines.CancellationException)?.let { throw it } + val found = v4.getOrDefault(emptyList()) + v6.getOrDefault(emptyList()) + if (found.isNotEmpty()) return found + throw (v4.exceptionOrNull() ?: v6.exceptionOrNull() ?: DnsFailure(R.string.lan_dns_no_record)) +} /** Bounded RFC1035 compression parser; only PTR answer records are returned. */ internal fun dnsPtrName(packet: ByteArray): String? = runCatching { diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanDeviceNetwork.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanDeviceNetwork.kt index 39195a0..0c9ece6 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanDeviceNetwork.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanDeviceNetwork.kt @@ -1,7 +1,9 @@ package cz.netkit.app.lan +import android.annotation.SuppressLint import android.content.Context import android.net.ConnectivityManager +import android.net.LinkProperties import android.net.Network import android.net.NetworkCapabilities import android.net.NetworkRequest @@ -9,12 +11,15 @@ import android.net.wifi.WifiInfo import android.net.wifi.WifiManager import android.os.Build import androidx.annotation.RequiresApi +import androidx.core.content.edit import cz.netkit.shared.lan.DiscoveryConsent import cz.netkit.shared.lan.LanNetworkIdentity +import cz.netkit.shared.lan.LanNetworkInfo import cz.netkit.shared.lan.lanNetworkConsentKey import cz.netkit.shared.lan.normalizeWifiSsid import java.io.IOException import java.net.Inet4Address +import java.net.Inet6Address import java.security.SecureRandom import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.atomic.AtomicBoolean @@ -25,7 +30,7 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withTimeoutOrNull -internal data class LanDeviceNetworkFacts(val gateway: String?, val ssid: String?) +internal data class LanDeviceNetworkFacts(val gateway: String?, val ssid: String?, val info: LanNetworkInfo? = null) /** * Reads the default IPv4 gateway (must lie in the Wi-Fi subnet) and the SSID of the selected @@ -36,7 +41,25 @@ internal class LanDeviceNetworkReader(context: Context) { private val connectivity = context.getSystemService(ConnectivityManager::class.java) private val wifiManager = context.applicationContext.getSystemService(WifiManager::class.java) - suspend fun read(wifi: LanWifi): LanDeviceNetworkFacts = LanDeviceNetworkFacts(gateway(wifi), ssid(wifi)) + suspend fun read(wifi: LanWifi): LanDeviceNetworkFacts = LanDeviceNetworkFacts(gateway(wifi), ssid(wifi), info(wifi)) + + /** "Info o síti" (zadání 39 §2.2): LinkProperties only, no packet is sent. */ + fun info(wifi: LanWifi): LanNetworkInfo? { + val link = connectivity.getLinkProperties(wifi.network) ?: return null + val gateways = link.routes.filter { it.isDefaultRoute }.mapNotNull { route -> + route.gateway?.takeUnless { it.isAnyLocalAddress }?.hostAddress + } + val ipv6 = link.linkAddresses.filter { it.address is Inet6Address }.mapNotNull { address -> + address.address.hostAddress?.let { "$it/${address.prefixLength}" } + } + val dhcpSupported = Build.VERSION.SDK_INT >= 30 + val dhcp = if (dhcpSupported) dhcpServer(link) else null + return LanNetworkInfo(link.interfaceName, wifi.address, wifi.prefix, gateways, link.dnsServers.mapNotNull { it.hostAddress }, + link.domains, dhcpSupported, dhcp, link.mtu, ipv6) + } + + @RequiresApi(30) + private fun dhcpServer(link: LinkProperties): String? = link.dhcpServerAddress?.hostAddress private fun gateway(wifi: LanWifi): String? = connectivity.getLinkProperties(wifi.network)?.routes.orEmpty() .filter { it.isDefaultRoute } @@ -119,9 +142,22 @@ internal class LanDeviceConsentStore(context: Context) { return written } + /** + * Settings (zadání 46 §3): forgets the consent of every network, stored and session-only. + * The install key and the last-discovery times stay. Returns false when the disk write failed. + */ + @Synchronized + @SuppressLint("UseKtx") // The commit() result is the return value; the KTX edit {} hides it. + fun forgetAllConsents(): Boolean { + session.clear() + val editor = preferences.edit() + preferences.all.keys.filter { it.startsWith(CONSENT) }.forEach(editor::remove) + return editor.commit() + } + fun lastDiscovery(key: String): Long? = preferences.getLong(LAST + key, -1L).takeIf { it >= 0 } - fun markDiscovery(key: String, elapsedMs: Long) { preferences.edit().putLong(LAST + key, elapsedMs).apply() } + fun markDiscovery(key: String, elapsedMs: Long) { preferences.edit { putLong(LAST + key, elapsedMs) } } private fun fromHex(text: String): ByteArray? = if (text.length % 2 != 0) null else runCatching { ByteArray(text.length / 2) { text.substring(it * 2, it * 2 + 2).toInt(16).toByte() } }.getOrNull() diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt index 3143949..9301001 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt @@ -6,6 +6,8 @@ import androidx.annotation.StringRes import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import cz.netkit.app.R +import cz.netkit.app.settings.awaitInOwner +import cz.netkit.shared.lan.ConsentResetGate import cz.netkit.shared.lan.DiscoveryConsent import cz.netkit.shared.lan.Ipv4Subnet import cz.netkit.shared.lan.LanAliveMethod @@ -14,6 +16,7 @@ import cz.netkit.shared.lan.LanDeviceName import cz.netkit.shared.lan.LanDeviceObservation import cz.netkit.shared.lan.LanNameSource import cz.netkit.shared.lan.LanNetworkIdentity +import cz.netkit.shared.lan.LanNetworkInfo import cz.netkit.shared.lan.LanRunStatus import cz.netkit.shared.lan.MDNS_MAX_HOSTS import cz.netkit.shared.lan.MdnsFindings @@ -41,6 +44,8 @@ import cz.netkit.shared.lan.updateLanDeviceUpnp import cz.netkit.shared.lan.upnpDescriptionTarget import cz.netkit.shared.lan.upsertLanDevice import cz.netkit.shared.lan.withOpenPorts +import cz.netkit.shared.lan.UdpServicesResult +import cz.netkit.shared.lan.lanDnsProbeAllowed import java.io.IOException import java.util.concurrent.atomic.AtomicBoolean import kotlinx.coroutines.CancellationException @@ -77,10 +82,13 @@ enum class LanDevicesError(@param:StringRes @get:StringRes val message: Int) { * The current Wi-Fi as the Devices screen sees it. * @property range CIDR that discovery probes (own subnet narrowed to at most /24), or null when * discovery is not allowed here (e.g. non-private address); then only [LanDevicesError.RANGE_NOT_ALLOWED]. + * @property info link facts for the "Info o síti" card, read from LinkProperties only. * @property ssid sanitized SSID for the consent question only; null when Android redacts it * (no location permission). Never logged or stored. */ -data class LanDevicesNetwork(val address: String, val prefix: Int, val range: String?, val gateway: String?, val ssid: String?) +data class LanDevicesNetwork(val address: String, val prefix: Int, val range: String?, val gateway: String?, val ssid: String?, + /** "Info o síti" card (zadání 39 §2.2); null when LinkProperties were unavailable. */ + val info: LanNetworkInfo? = null) /** Discovery progress; [automatic] distinguishes consent-driven runs from [LanDevicesViewModel.refresh]. */ data class LanDeviceScan( @@ -94,6 +102,20 @@ data class LanDevicePing(val address: String, val status: LanRunStatus, val samp val statistics: PingStatistics get() = pingStatistics(samples) } +/** + * "Identifikovat služby" (zadání 39 §2.4) of one device: SNMP/NTP/DNS over UDP. [dnsAllowed] says + * whether the DNS probe was sent (the host is a DNS server of the Wi-Fi or TCP 53 was found open). + * The SNMP community is never part of the state. + */ +data class LanDeviceServices(val address: String, val status: LanRunStatus, val dnsAllowed: Boolean, val result: UdpServicesResult? = null) + +/** The "Info o síti" snapshot of the shown Wi-Fi replaced by [info]; any other state is left as is. */ +internal fun refreshedNetworkInfo(state: LanDevicesState, wifiAddress: String, info: LanNetworkInfo): LanDevicesState { + val network = state.network ?: return state + if (network.address != wifiAddress || network.info == info) return state + return state.copy(network = network.copy(info = info)) +} + /** Quick TCP scan of the preset ports; open ports go into [LanDevice.openPorts]. */ data class LanDevicePortScan(val address: String, val status: LanRunStatus, val done: Int = 0, val total: Int = 0, val counts: ProbeCounts = ProbeCounts()) @@ -127,6 +149,7 @@ data class LanDevicesState( val selectedAddress: String? = null, val ping: LanDevicePing? = null, val portScan: LanDevicePortScan? = null, + val services: LanDeviceServices? = null, val icmpUnavailable: Boolean = false, val identification: LanRunStatus = LanRunStatus.IDLE, val identificationHosts: Set = emptySet(), @@ -178,11 +201,15 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati private val ping = Slot() private val ports = Slot() private val identify = Slot() + private val serviceProbe = Slot() /** Whether the running identification belongs to an automatic (consent-driven) discovery. */ private var identifyAutomatic = false - private data class Current(val wifi: LanWifi, val identity: LanNetworkIdentity, val range: Ipv4Subnet?, val key: String?) + private data class Current(val wifi: LanWifi, val identity: LanNetworkIdentity, val range: Ipv4Subnet?, val key: String?, + val info: LanNetworkInfo? = null) private var current: Current? = null + /** Keeps a network load that overlapped "forget all consents" from restoring the old answer (revize kolo 2). */ + private val consentReset = ConsentResetGate() init { viewModelScope.launch { @@ -190,6 +217,20 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati catch (error: CancellationException) { throw error } catch (_: Exception) { onWifi(null) } } + // Same Wi-Fi, new link facts (IPv6 address, DNS, domain): only the info snapshot changes. + viewModelScope.launch { + try { + backend.linkPropertiesChanges().collect { network -> + val c = current ?: return@collect + if (c.wifi.network != network) return@collect + val info = withContext(Dispatchers.IO) { + try { reader.info(c.wifi) } catch (error: CancellationException) { throw error } catch (_: Exception) { null } + } ?: return@collect + if (current === c) mutable.update { refreshedNetworkInfo(it, c.wifi.address, info) } + } + } catch (error: CancellationException) { throw error + } catch (_: Exception) { /* Best effort: the snapshot from onWifi stays. */ } + } } private suspend fun onWifi(wifi: LanWifi?) { @@ -201,13 +242,15 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati return } mutable.update { LanDevicesState(active = it.active, loadingNetwork = true) } - val loaded = withContext(Dispatchers.IO) { load(wifi) } + val stamp = consentReset.loadStarted() + val read = withContext(Dispatchers.IO) { load(wifi) } + val loaded = read.copy(second = consentReset.publishable(stamp, read.second)) current = loaded.first val c = loaded.first mutable.update { it.copy(loadingNetwork = false, network = LanDevicesNetwork(wifi.address, wifi.prefix, c.range?.toString(), c.identity.gateway, - c.identity.ssid?.let { ssid -> sanitizeLanText(ssid, 64) }), + c.identity.ssid?.let { ssid -> sanitizeLanText(ssid, 64) }, c.info), consent = loaded.second, consentRemembered = loaded.second != DiscoveryConsent.UNKNOWN && c.key != null && lanConsentIsPersistable(loaded.second, c.identity), scan = LanDeviceScan(lastCompletedElapsedMs = loaded.third), @@ -217,12 +260,12 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati } private suspend fun load(wifi: LanWifi): Triple { - val facts = try { reader.read(wifi) } catch (error: CancellationException) { throw error } catch (_: Exception) { LanDeviceNetworkFacts(null, null) } + val facts = try { reader.read(wifi) } catch (error: CancellationException) { throw error } catch (_: Exception) { LanDeviceNetworkFacts(null, null, null) } val identity = LanNetworkIdentity(facts.ssid, facts.gateway, wifi.subnet) val key = try { withContext(storage) { store.key(identity) } } catch (error: CancellationException) { throw error } catch (_: Exception) { null } val consent = key?.let { runCatching { store.consent(it, wifi.network.networkHandle) }.getOrNull() } ?: DiscoveryConsent.UNKNOWN val last = key?.let { runCatching { store.lastDiscovery(it) }.getOrNull() } - return Triple(Current(wifi, identity, lanDevicesRange(wifi.address, wifi.prefix), key), consent, last) + return Triple(Current(wifi, identity, lanDevicesRange(wifi.address, wifi.prefix), key, facts.info), consent, last) } fun setActive(active: Boolean) { @@ -252,6 +295,34 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati maybeAutoDiscover() } + /** + * Settings (zadání 46 §3): forgets the auto-discovery consent of all networks. The current + * network asks again; a running automatic discovery stops. False when the store failed. + * Everything runs in the ViewModel scope (revize kolo 1): a cancelled caller (leaving Settings, + * rotation) cannot leave the network ALLOWED in memory. The in-memory state changes first, so + * nothing starts automatically while the write is pending; a failed write reports false and the + * next start asks or not according to the stored answer. + */ + suspend fun forgetAllConsents(): Boolean = awaitInOwner(viewModelScope) { + // Revize kolo 2: a network still loading may have read the old answer; the gate makes it + // publish UNKNOWN, and the state is cleared again after the write (both before and after). + consentReset.begin() + try { + clearConsentInMemory() + withContext(storage) { runCatching { store.forgetAllConsents() }.getOrDefault(false) } + } finally { + consentReset.end() + clearConsentInMemory() + } + } + + /** Main thread: stops consent-driven work and shows the question again for the current network. */ + private fun clearConsentInMemory() { + if (state.value.scan.let { it.running && it.automatic }) cancelDiscovery() + if (identifyAutomatic) cancelIdentification() + if (current != null) mutable.update { it.copy(consent = DiscoveryConsent.UNKNOWN, consentRemembered = false) } + } + /** Manual discovery: allowed with any consent state, still only inside [LanDevicesNetwork.range]. Ignored while running. */ fun refresh() { val snapshot = state.value @@ -301,8 +372,9 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati val alive = probeAlive(wifi, ip, icmpUnavailable, runId) if (alive != null) { publish(discovery, runId) { it.copy(devices = upsertLanDevice(it.devices, alive, now(), gateway, wifi.address)) } - val (found, group) = resolveNames(wifi, ip, names) - if (found.isNotEmpty() || group != null) publish(discovery, runId) { it.copy(devices = updateLanDeviceNames(it.devices, ip, found, group)) } + val (found, group, mac) = resolveNames(wifi, ip, names) + if (found.isNotEmpty() || group != null || mac != null) + publish(discovery, runId) { it.copy(devices = updateLanDeviceNames(it.devices, ip, found, group, mac)) } } publish(discovery, runId) { it.copy(scan = it.scan.copy(done = it.scan.done + 1)) } } @@ -342,7 +414,7 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati } /** PTR (existing backend, 1.5 s) in parallel with NetBIOS (≤ 800 ms, at most [NETBIOS_PARALLEL] at once). */ - private suspend fun resolveNames(wifi: LanWifi, ip: String, limiter: Semaphore): Pair, String?> = coroutineScope { + private suspend fun resolveNames(wifi: LanWifi, ip: String, limiter: Semaphore): Triple, String?, String?> = coroutineScope { val ptr = async { val name = try { backend.reverse(wifi, ip) } catch (error: CancellationException) { currentCoroutineContext().ensureActive(); "" } @@ -354,7 +426,7 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati catch (error: CancellationException) { currentCoroutineContext().ensureActive(); null } catch (_: Exception) { null } } - listOfNotNull(lanDeviceName(LanNameSource.NETBIOS, netBios?.name), ptr.await()) to netBios?.group + Triple(listOfNotNull(lanDeviceName(LanNameSource.NETBIOS, netBios?.name), ptr.await()), netBios?.group, netBios?.mac) } /** @@ -455,6 +527,7 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati fun closeDevice() { cancelPing() + cancelServices() mutable.update { it.copy(selectedAddress = null, ping = null) } } @@ -500,6 +573,41 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati } } + /** + * UDP service identification of one listed device of the current range (never another + * network, never more than one host). [community] lives only in this call: empty skips SNMP. + */ + fun identifyServices(address: String, community: String) { + val c = current ?: return fail(LanDevicesError.NO_WIFI) + val device = state.value.devices.firstOrNull { it.address == address } + if (device == null || device.isSelf || c.range?.contains(address) != true) return fail(LanDevicesError.UNKNOWN_DEVICE) + val target = Ipv4Subnet.parse("$address/32") ?: return fail(LanDevicesError.UNKNOWN_DEVICE) + if (targetConfirmationReasons(target, c.wifi.subnet).isNotEmpty()) return fail(LanDevicesError.RANGE_NOT_ALLOWED) + cancelServices() + val runId = serviceProbe.runId + val dnsAllowed = lanDnsProbeAllowed(address, state.value.network?.info, device.openPorts) + val communityBytes = community.takeIf { it.isNotEmpty() }?.encodeToByteArray() + mutable.update { it.copy(services = LanDeviceServices(address, LanRunStatus.RUNNING, dnsAllowed), error = null) } + serviceProbe.job = viewModelScope.launch(Dispatchers.IO) { + var outcome = LanRunStatus.CANCELLED + try { + val result = UdpServiceProbe.identify(backend, c.wifi, address, communityBytes, dnsAllowed) + publish(serviceProbe, runId) { s -> s.copy(services = s.services?.takeIf { it.address == address }?.copy(status = LanRunStatus.FINISHED, result = result)) } + outcome = LanRunStatus.FINISHED + } catch (error: CancellationException) { throw error + } catch (error: Exception) { + outcome = LanRunStatus.FAILED + currentCoroutineContext().ensureActive() + publish(serviceProbe, runId) { it.copy(error = classify(error)) } + } finally { + communityBytes?.fill(0) + finish(serviceProbe, runId) { s -> s.services?.takeIf { it.status == LanRunStatus.RUNNING }?.let { s.copy(services = it.copy(status = outcome)) } ?: s } + } + } + } + + fun cancelServiceProbe() = cancelServices() + /** Cancels discovery, ping and port scan; results gathered so far stay visible. */ fun cancel() = cancelAll() @@ -513,7 +621,7 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati private fun portsOf(state: LanDevicesState, address: String): List = state.devices.firstOrNull { it.address == address }?.openPorts.orEmpty() - private fun cancelAll() { cancelDiscovery(); cancelIdentification(); cancelPing(); cancelPorts() } + private fun cancelAll() { cancelDiscovery(); cancelIdentification(); cancelPing(); cancelPorts(); cancelServices() } private fun cancelDiscovery() { stop(discovery) @@ -533,6 +641,10 @@ class LanDevicesViewModel(application: Application) : AndroidViewModel(applicati stop(ports) mutable.update { s -> s.portScan?.takeIf { it.status == LanRunStatus.RUNNING }?.let { s.copy(portScan = it.copy(status = LanRunStatus.CANCELLED)) } ?: s } } + private fun cancelServices() { + stop(serviceProbe) + mutable.update { s -> s.services?.takeIf { it.status == LanRunStatus.RUNNING }?.let { s.copy(services = it.copy(status = LanRunStatus.CANCELLED)) } ?: s } + } private fun stop(slot: Slot) { slot.runId++; slot.job?.cancel(); slot.job = null } private fun fail(error: LanDevicesError) { mutable.update { it.copy(error = error) } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanIpv6Tools.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanIpv6Tools.kt new file mode 100644 index 0000000..07884e5 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanIpv6Tools.kt @@ -0,0 +1,121 @@ +package cz.netkit.app.lan + +import android.net.LinkProperties +import android.system.Os +import cz.netkit.app.R +import cz.netkit.shared.lan.Ipv6Prefix +import cz.netkit.shared.lan.Ipv6Scope +import cz.netkit.shared.lan.LanNumericAddress +import cz.netkit.shared.lan.TargetConfirmationReason +import cz.netkit.shared.lan.ipv4Number +import cz.netkit.shared.lan.ipv6TargetConfirmationReasons +import cz.netkit.shared.lan.lanNumericAddress +import cz.netkit.shared.lan.targetConfirmationReasons +import cz.netkit.shared.lan.Ipv4Subnet +import java.io.IOException +import java.net.Inet4Address +import java.net.Inet6Address +import java.net.InetAddress +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.withTimeoutOrNull + +/* + * IPv6 for single-target LAN tools (zadání 39 §2.3): ping, TCP port check and DNS AAAA. Kept + * apart from LanViewModel so the tool state machine changes only where an address is parsed. + * No IPv6 subnet discovery exists anywhere. + */ + +/** A typed `%zone` that does not name the interface of the selected route. */ +internal class Ipv6ZoneMismatchException : IOException("ZONE_MISMATCH") + +/** + * Numeric literal → [InetAddress] without DNS. A link-local IPv6 address gets the scope of + * [interfaceName] (Android binds sockets by network mark, not by device, so the kernel needs the + * scope); a typed zone must be that interface. + */ +internal fun toolInetAddress(address: String, interfaceName: String?): InetAddress = when (val numeric = lanNumericAddress(address)) { + is LanNumericAddress.V4 -> InetAddress.getByAddress(numeric.text.split('.').map { it.toInt().toByte() }.toByteArray()) + is LanNumericAddress.V6 -> { + val v6 = numeric.address + val index by lazy { interfaceName?.let { Os.if_nametoindex(it) } ?: 0 } + if (!zoneMatches(v6.zone, interfaceName) { index }) throw Ipv6ZoneMismatchException() + if (v6.scope == Ipv6Scope.LINK_LOCAL) { + if (interfaceName == null || index <= 0) throw Ipv6ZoneMismatchException() + Inet6Address.getByAddress(null, v6.bytes, index) + } else InetAddress.getByAddress(v6.bytes) + } + null -> throw IllegalArgumentException("NUMERIC") +} + +/** + * A typed or stored zone names the route's interface: by name (`%wlan0`) or by its numeric index + * (`%12`, how `Inet6Address.getHostAddress` prints a scope set by index, e.g. in our own results). + */ +internal fun zoneMatches(zone: String?, interfaceName: String?, index: () -> Int): Boolean = when { + zone == null -> true + interfaceName == null -> false + zone == interfaceName -> true + zone.all { it in '0'..'9' } -> zone.toIntOrNull()?.let { it > 0 && it == index() } == true + else -> false +} + +/** Per-type limit of the A/AAAA lookup, inside the 4 s limit of the whole resolution. */ +internal const val LOOKUP_TYPE_TIMEOUT_MS = 3_000L + +/** + * A and AAAA concurrently, each bounded by [timeoutMs]: a resolver that drops AAAA (IPv4-only + * network) cannot hold back the A answer. A timed-out or failed type counts as a failure for + * [mergeLookups]; cancellation of the caller is never turned into a result. + */ +internal suspend fun lookupBoth(a: suspend () -> List, aaaa: suspend () -> List, + timeoutMs: Long = LOOKUP_TYPE_TIMEOUT_MS): List = coroutineScope { + suspend fun bounded(query: suspend () -> List): Result> = try { + withTimeoutOrNull(timeoutMs) { query() }?.let { Result.success(it) } ?: Result.failure(DnsFailure(R.string.lan_dns_timeout)) + } catch (error: CancellationException) { throw error + } catch (error: Exception) { Result.failure(error) } + val v4 = async { bounded(a) } + val v6 = async { bounded(aaaa) } + mergeLookups(v4.await(), v6.await()) +} + +/** On-link IPv6 prefixes of a link (global and ULA; link-local is on-link by definition). */ +internal fun ipv6Prefixes(link: LinkProperties?): List = link?.linkAddresses.orEmpty().mapNotNull { address -> + (address.address as? Inet6Address)?.let { Ipv6Prefix.parse("${it.hostAddress.orEmpty().substringBefore('%')}/${address.prefixLength}") } +} + +/** DNS answer → tool target: the first IPv4, else the first IPv6 (canonical, zone dropped). */ +internal fun pickToolAddress(addresses: List): String? = + addresses.firstOrNull { it is Inet4Address }?.hostAddress + ?: addresses.firstOrNull { it is Inet6Address }?.hostAddress?.substringBefore('%') + ?.let { (lanNumericAddress(it) as? LanNumericAddress.V6)?.address?.canonical } + +internal fun isIpv6Target(address: String): Boolean = lanNumericAddress(address) is LanNumericAddress.V6 + +/** + * The same questions as before for IPv4 (own subnet, private range, port count); for IPv6 see + * [ipv6TargetConfirmationReasons]. [wifiSubnet] / [wifiPrefixes] null = no Wi-Fi on this route. + */ +internal fun toolTargetReasons(address: String, wifiSubnet: Ipv4Subnet?, wifiPrefixes: List?, portCount: Int): Set = + when (val numeric = lanNumericAddress(address)) { + is LanNumericAddress.V4 -> targetConfirmationReasons(Ipv4Subnet.parse("${numeric.text}/32")!!, wifiSubnet, portCount) + is LanNumericAddress.V6 -> ipv6TargetConfirmationReasons(numeric.address, wifiPrefixes, portCount) + null -> throw IllegalArgumentException("NUMERIC") + } + +/** Whether a numeric target lies on the Wi-Fi link: IPv4 subnet, IPv6 link-local or an on-link prefix. */ +internal fun onWifiLink(address: String, wifiSubnet: Ipv4Subnet?, wifiPrefixes: () -> List): Boolean = + when (val numeric = lanNumericAddress(address)) { + is LanNumericAddress.V4 -> wifiSubnet?.contains(numeric.text) == true + is LanNumericAddress.V6 -> numeric.address.scope == Ipv6Scope.LINK_LOCAL || wifiPrefixes().any { it.contains(numeric.address) } + null -> false + } + +/** Tools that stay IPv4-only; null when [tool] works with [address]. */ +internal fun ipv6Refusal(tool: LanTool, address: String, mtuSweep: Boolean): Int? = when { + !isIpv6Target(address) || ipv4Number(address) != null -> null + tool == LanTool.TRACE -> R.string.lan39_ipv6_trace_unsupported + tool == LanTool.PING && mtuSweep -> R.string.lan39_ipv6_mtu_unsupported + else -> null +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanScreen.kt index 62799dc..51e773f 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanScreen.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanScreen.kt @@ -26,6 +26,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.selectable @@ -93,6 +94,7 @@ import cz.netkit.app.net.netKindLabel import cz.netkit.app.ui.EmptyState import cz.netkit.app.ui.Eyebrow import cz.netkit.app.ui.InfoNote +import cz.netkit.app.ui.KeepScreenOn import cz.netkit.app.ui.NetKitIcons import cz.netkit.app.ui.NeutralButton import cz.netkit.app.ui.Panel @@ -101,6 +103,11 @@ import cz.netkit.app.ui.SectionCard import cz.netkit.app.ui.Spacing import cz.netkit.app.ui.StatTile import cz.netkit.app.ui.StatTiles +import cz.netkit.app.ui.lanSummary +import cz.netkit.app.ui.spoken +import cz.netkit.app.ui.spokenStatus +import cz.netkit.app.ui.chart.seriesDescription +import cz.netkit.app.ui.OffscreenRunSummary import cz.netkit.app.ui.StatusBanner import cz.netkit.app.ui.StatusKind import cz.netkit.app.ui.Tag @@ -117,8 +124,9 @@ import cz.netkit.shared.lan.LanExport import cz.netkit.shared.lan.LanResult import cz.netkit.shared.lan.LanRunStatus import cz.netkit.shared.lan.TargetConfirmationReason +import cz.netkit.shared.lan.TargetField import cz.netkit.shared.lan.exportLan -import cz.netkit.shared.lan.ipv4Number +import cz.netkit.shared.lan.lanNumericAddress import cz.netkit.shared.lan.lanTextFitsIpc import cz.netkit.shared.lan.pingStatistics import cz.netkit.shared.net.NetKind @@ -138,6 +146,8 @@ private const val PING_VISIBLE = 120 @Composable fun LanScreen(viewModel: LanViewModel, modifier: Modifier = Modifier) { val state by viewModel.state.collectAsStateWithLifecycle() + // Zadání 46 §4: a running ping (with a count or continuous) keeps the display on. + KeepScreenOn(state.keepsScreenOn) val colors = NetKitTheme.colors // Register at screen scope: closing the export sheet must not dispose its SAF result callback. val saveText=rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/plain"),viewModel::saveExport) @@ -151,9 +161,9 @@ fun LanScreen(viewModel: LanViewModel, modifier: Modifier = Modifier) { LanExport.JSON -> saveJson.launch("netkit-lan.json") } } catch(_: Exception) { viewModel.cancelExport(); viewModel.exportFailed() } } - val labels = listOf(R.string.lan_discovery,R.string.lan_ping,R.string.lan_trace,R.string.lan_ports,R.string.lan_dns,R.string.lan_mdns) var menuOpen by remember { mutableStateOf(false) } var exportOpen by rememberSaveable { mutableStateOf(false) } + var splitPrefix by rememberSaveable { mutableStateOf("") } val hasResults = state.results.isNotEmpty() // Export exists only for a non-empty snapshot; a tool switch or a new run closes the sheet. LaunchedEffect(hasResults) { if (!hasResults) exportOpen = false } @@ -167,7 +177,9 @@ fun LanScreen(viewModel: LanViewModel, modifier: Modifier = Modifier) { LanExportSheet(state.results,state.exportFormat,state.error,viewModel) { launchSave(); closeExport() } } - LazyColumn(modifier.fillMaxSize().imePadding(),contentPadding=PaddingValues(Spacing.normal), + val listState = rememberLazyListState() + OffscreenRunSummary(state.runStatus == LanRunStatus.RUNNING, lanSummary(state).spoken(), listState, "status") + LazyColumn(modifier.fillMaxSize().imePadding(),state=listState,contentPadding=PaddingValues(Spacing.normal), verticalArrangement=Arrangement.spacedBy(Spacing.medium)) { item(key="header") { LanHeader(stringResource(R.string.lan_header),wifiSubtitle(state.wifiAddress)) { @@ -186,19 +198,52 @@ fun LanScreen(viewModel: LanViewModel, modifier: Modifier = Modifier) { item(key="safety") { SafetyLine() } item(key="tools") { Row(Modifier.horizontalScroll(rememberScrollState()),horizontalArrangement=Arrangement.spacedBy(Spacing.small)) { - LanTool.entries.forEach { tool -> ChoiceChip(stringResource(labels[tool.ordinal]),state.tool==tool) { viewModel.tool(tool) } } + LanTool.entries.forEach { tool -> ChoiceChip(stringResource(toolLabel(tool)),state.tool==tool) { viewModel.tool(tool) } } } } + if (state.tool == LanTool.SUBNET) { + subnetCalculator(state.subnetInput ?: state.wifiCidr, state.maskInterpretation, viewModel::subnetInput, splitPrefix) { splitPrefix = it } + return@LazyColumn + } + if (state.tool == LanTool.MAC_VENDOR) { + macVendorTool(state, viewModel) + return@LazyColumn + } + if (state.tool.diagnostic) { + item("diagnostic") { DiagnosticPanel(state, viewModel) } + if (state.tool == LanTool.RECORDS && state.runStatus != LanRunStatus.IDLE) item("status") { RunStatus(state) } + state.error?.let { item("error") { StatusBanner(stringResource(it), StatusKind.ERROR) } } + state.notice?.let { item("notice") { StatusBanner(stringResource(it)) } } + items(state.results.size) { i -> + val row = state.results[i] + SectionCard(row.address, meta = row.method, heading = false) { Text(listOf(row.name, row.detail).filter(String::isNotEmpty).joinToString(" · ")) } + } + items(state.diagnosticLines.size) { i -> + val (label, value) = state.diagnosticLines[i] + SectionCard(label, heading = false) { Text(value, style = NetKitType.body, color = colors.text) } + } + return@LazyColumn + } item(key="target") { TargetPanel(state,viewModel) } if (state.runStatus!=LanRunStatus.IDLE || state.busy) item(key="status") { RunStatus(state) } - state.error?.let { resource -> item(key="error") { StatusBanner(stringResource(resource),StatusKind.ERROR) } } + state.error?.let { resource -> item(key="error") { val message = if (resource == R.string.lan_dns_rcode) { + val code = requireNotNull(state.dnsRcode) + stringResource(resource, code, cz.netkit.shared.lan.dnsRcodeName(code) ?: stringResource(R.string.lan_dns_unknown)) + } else stringResource(resource) + StatusBanner(message, StatusKind.ERROR) } } state.notice?.let { resource -> item(key="notice") { StatusBanner(stringResource(resource)) } } + if (state.awaitingTrace) item("continue_trace") { + PrimaryButton(stringResource(R.string.lan_trace_continue), viewModel::continueTrace) + } if (state.traceRouteWarning) item(key="route") { StatusBanner(stringResource(R.string.lan_trace_outside_wifi),StatusKind.WARNING) } - if (state.tool==LanTool.PING && state.samples.isNotEmpty()) item(key="ping") { PingSummary(state) } + state.mtuPayload?.let { size -> item("mtu_payload") { + StatusBanner(stringResource(R.string.lan_mtu_result, size, size + 28)) + } } + if (state.tool.pingLike && state.samples.isNotEmpty()) item(key="ping") { PingSummary(state) } if (hasResults) { if (state.tool==LanTool.TRACE) item(key="trace") { TracePanel(state.results) } else item(key="results") { ResultsPanel(state.results,state.tool,viewModel) } - } else if(!state.busy && state.error==null) item(key="empty") { + } else if(!state.busy && state.error==null && !state.mtuSweep) item(key="empty") { EmptyState(stringResource(R.string.lan_empty),if(state.tool==LanTool.TRACE) NetKitIcons.Route else NetKitIcons.Devices) } item(key="info") { @@ -208,6 +253,34 @@ fun LanScreen(viewModel: LanViewModel, modifier: Modifier = Modifier) { } } +/** Ping and TCP ping share statistics, graph and the newest-first sample rows. */ +internal val LanUiState.keepsScreenOn get() = runStatus == LanRunStatus.RUNNING && + (tool.pingLike || tool == LanTool.TRACE || tool == LanTool.PORTS) + +internal val LanTool.pingLike get() = this == LanTool.PING || this == LanTool.TCP_PING + +internal fun toolLabel(tool: LanTool): Int = when (tool) { + LanTool.DISCOVERY -> R.string.lan_discovery + LanTool.PING -> R.string.lan_ping + LanTool.TCP_PING -> R.string.tools48_tcp_ping + LanTool.TRACE -> R.string.lan_trace + LanTool.PORTS -> R.string.lan_ports + LanTool.DNS -> R.string.lan_dns + LanTool.MDNS -> R.string.lan_mdns + LanTool.SUBNET -> R.string.lan_subnet + LanTool.MAC_VENDOR -> R.string.tools48_mac_vendor + LanTool.RECORDS -> R.string.diag_records + LanTool.WEB -> R.string.diag_web + LanTool.RDAP -> R.string.diag_rdap +} + +/** Short reason of a lost TCP ping sample; the row keeps the stable status name for exports. */ +internal fun tcpLossLabel(status: String): Int = when (status) { + "REFUSED" -> R.string.tools48_tcp_refused + "TIMEOUT" -> R.string.tools48_tcp_timeout + else -> R.string.tools48_tcp_error +} + /** "Wi-Fi · 192.168.0.30" (address in mono); the run binds to this network. */ @Composable private fun wifiSubtitle(address: String?): AnnotatedString = buildAnnotatedString { @@ -254,7 +327,7 @@ private fun ConfirmationDialog(state: LanUiState, viewModel: LanViewModel) { /** Tool or format choice: pill on `surface2`, the selected one in accent tint; 48 dp touch target. */ @Composable -private fun ChoiceChip(label: String, selected: Boolean, onClick: () -> Unit) { +internal fun ChoiceChip(label: String, selected: Boolean, onClick: () -> Unit) { val colors = NetKitTheme.colors val fill by animateColorAsState(if(selected) colors.accentSoft else colors.surface2,rememberNetKitTween(MotionToken.FAST),label="chip-fill") val ink by animateColorAsState(if(selected) colors.accent else colors.muted,rememberNetKitTween(MotionToken.FAST),label="chip-ink") @@ -273,9 +346,11 @@ private fun TargetPanel(state: LanUiState, viewModel: LanViewModel) { Row(verticalAlignment=Alignment.Bottom,horizontalArrangement=Arrangement.spacedBy(Spacing.small)) { val field=Modifier.weight(1f) when(state.tool) { + LanTool.SUBNET, LanTool.MAC_VENDOR, LanTool.RECORDS, LanTool.WEB, LanTool.RDAP -> Unit LanTool.DISCOVERY -> Field(state.cidr,viewModel::cidr,R.string.lan_cidr,!state.busy,field,mono=true) LanTool.MDNS -> Field(state.serviceType,viewModel::serviceType,R.string.lan_service_type,!state.busy,field,mono=true) - LanTool.PING,LanTool.TRACE,LanTool.PORTS,LanTool.DNS -> Field(state.host,viewModel::host,R.string.lan_host,!state.busy,field,mono=true) + LanTool.PING,LanTool.TCP_PING,LanTool.TRACE,LanTool.PORTS,LanTool.DNS -> + TargetInput(state.host,viewModel::host,R.string.lan_host,!state.busy,TargetField.HOST,state.targets,viewModel,field) } // Same height as the outlined field next to it. val action=Modifier.heightIn(min=56.dp) @@ -294,11 +369,44 @@ private fun TargetPanel(state: LanUiState, viewModel: LanViewModel) { NeutralButton(stringResource(R.string.lan_preset),viewModel::preset,enabled=!state.busy,small=true) } } + if (state.tool==LanTool.TCP_PING) { + Row(horizontalArrangement=Arrangement.spacedBy(Spacing.small)) { + Field(state.tcpPort,viewModel::tcpPort,R.string.tools48_tcp_port,!state.busy,Modifier.weight(1f).testTag("tcp_port"),number=true,mono=true) + Field(state.tcpCount,viewModel::tcpCount,R.string.tools48_tcp_count,!state.busy,Modifier.weight(1f).testTag("tcp_count"),number=true) + } + Text(stringResource(R.string.tools48_tcp_help),style=NetKitType.label,color=colors.muted) + } if (state.tool !in listOf(LanTool.DNS,LanTool.MDNS)) Field(state.timeout,viewModel::timeout,R.string.lan_timeout,!state.busy,number=true) + if (state.tool == LanTool.PING) PingAdvanced(state, viewModel) if (state.tool in listOf(LanTool.DISCOVERY,LanTool.PORTS)) Field(state.concurrency,viewModel::concurrency,R.string.lan_concurrency,!state.busy,number=true) } } +@Composable +private fun PingAdvanced(state: LanUiState, viewModel: LanViewModel) { + var expanded by rememberSaveable { mutableStateOf(false) } + NeutralButton(stringResource(if (expanded) R.string.lan_ping_collapse else R.string.lan_ping_advanced), + { expanded = !expanded }, Modifier.testTag("ping_advanced"), small = true) + if (!expanded) return + val colors = NetKitTheme.colors + val fields = state.pingFields + val enabled = !state.busy + Field(fields.count, { viewModel.pingFields(fields.copy(count = it)) }, R.string.lan_ping_count, enabled, number = true) + Field(fields.seconds, { viewModel.pingFields(fields.copy(seconds = it)) }, R.string.lan_ping_seconds, enabled, decimal = true) + Text(stringResource(R.string.lan_ping_interval_help), style = NetKitType.label, color = colors.muted) + Field(fields.payload, { viewModel.pingFields(fields.copy(payload = it)) }, R.string.lan_ping_payload, enabled, number = true) + if (state.dfSupported) { + Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(NetKitShape.nested).toggleable(fields.df, enabled, Role.Checkbox) { + viewModel.pingFields(fields.copy(df = it)) + }, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + Checkbox(fields.df, null, enabled = enabled, colors = CheckboxDefaults.colors( + checkedColor = colors.accent, uncheckedColor = colors.muted, checkmarkColor = colors.accentInk)) + Text(stringResource(R.string.lan_ping_df), style = NetKitType.body) + } + NeutralButton(stringResource(R.string.lan_mtu_sweep), { viewModel.start(mtuSweep = true) }, enabled = enabled) + } +} + /** "Měří se přes [Wi-Fi]": the network of the next or current run; warning tone when it is missing. */ @Composable private fun RouteLine(state: LanUiState) { @@ -313,24 +421,29 @@ private fun RouteLine(state: LanUiState) { } @Composable -private fun RunStatus(state: LanUiState) { +internal fun RunStatus(state: LanUiState) { val colors = NetKitTheme.colors - val count = state.results.size + val count = if (state.mtuSweep) state.progress else state.results.size Column(verticalArrangement=Arrangement.spacedBy(Spacing.small)) { - when(state.runStatus) { - LanRunStatus.RUNNING -> Tag(when { - state.total>0 -> stringResource(R.string.lan_chip_running_total,state.progress,state.total) - state.progress>0 -> stringResource(R.string.lan_chip_running,state.progress) + val status = when (state.runStatus) { + LanRunStatus.RUNNING -> when { + state.total > 0 -> stringResource(R.string.lan_chip_running_total, state.progress, state.total) + state.progress > 0 -> stringResource(R.string.lan_chip_running, state.progress) else -> stringResource(R.string.lan_chip_running_plain) - },Tone.ACCENT,dot=true) - LanRunStatus.FINISHED -> Tag(pluralStringResource(R.plurals.lan_chip_finished,count,count),Tone.OK,dot=true) - LanRunStatus.CANCELLED -> Tag(pluralStringResource(R.plurals.lan_chip_cancelled,count,count),Tone.WARN,dot=true) - LanRunStatus.FAILED -> Tag(stringResource(R.string.lan_chip_failed),Tone.ERR,dot=true) - LanRunStatus.IDLE -> Unit + } to Tone.ACCENT + LanRunStatus.FINISHED -> pluralStringResource(R.plurals.lan_chip_finished, count, count) to Tone.OK + LanRunStatus.CANCELLED -> pluralStringResource(R.plurals.lan_chip_cancelled, count, count) to Tone.WARN + LanRunStatus.FAILED -> stringResource(R.string.lan_chip_failed) to Tone.ERR + LanRunStatus.IDLE -> null + } + status?.let { (label, tone) -> + val spoken = if (state.runStatus == LanRunStatus.RUNNING) stringResource(R.string.lan_chip_running_plain) + else lanSummary(state).spoken().ifEmpty { label } + Tag(label, tone, dot = true, modifier = Modifier.spokenStatus(spoken)) } - if (state.tool in listOf(LanTool.DISCOVERY,LanTool.PORTS) && state.runStatus!=LanRunStatus.IDLE) + if (state.tool in listOf(LanTool.DISCOVERY,LanTool.PORTS,LanTool.TCP_PING) && state.runStatus!=LanRunStatus.IDLE) Text(stringResource(R.string.lan_probe_counts,state.probeCounts.open,state.probeCounts.refused,state.probeCounts.timeout,state.probeCounts.error), - style=NetKitType.label,color=colors.dim) + style=NetKitType.label,color=colors.muted) if (state.busy) LanProgress(if(state.total>0) (state.progress.toFloat()/state.total).coerceIn(0f,1f) else null) } } @@ -357,8 +470,8 @@ private fun PingSummary(state: LanUiState) { @Composable private fun ResultsPanel(results: List, tool: LanTool, viewModel: LanViewModel) { - val displayed = if(tool==LanTool.PING) results.takeLast(PING_VISIBLE).asReversed() else results - SectionCard(stringResource(R.string.lan_results_title),meta=if(tool==LanTool.PING) stringResource(R.string.lan_ping_visible_window) else null) { + val displayed = if(tool.pingLike) results.takeLast(PING_VISIBLE).asReversed() else results + SectionCard(stringResource(R.string.lan_results_title),meta=if(tool.pingLike) stringResource(R.string.lan_ping_visible_window) else null) { Column { displayed.forEachIndexed { index, result -> // Keyed so a row's open menu stays with its result while new ping samples arrive on top. @@ -374,7 +487,7 @@ private fun ResultRow(result: LanResult, tool: LanTool, viewModel: LanViewModel, val colors = NetKitTheme.colors val mono = NetKitType.addressFor(NetKitType.label).toSpanStyle() val address = result.address.ifEmpty { stringResource(R.string.lan_unknown_hop) }+result.port?.let { ":$it" }.orEmpty() - val actions = ipv4Number(result.address)!=null + val actions = lanNumericAddress(result.address)!=null fun line(first: String?, rest: List): AnnotatedString? { val tail = rest.filter(String::isNotEmpty) if (first==null && tail.isEmpty()) return null @@ -385,7 +498,7 @@ private fun ResultRow(result: LanResult, tool: LanTool, viewModel: LanViewModel, } // The address is the title wherever there is no better one; it is mono and never cut. val (title,titleMono,subtitle) = when(tool) { - LanTool.PING -> result.sequence?.let { Triple(stringResource(R.string.lan_ping_sample,it,result.elapsedMs ?: 0),false,line(address,listOf(result.method))) } + LanTool.PING, LanTool.TCP_PING -> result.sequence?.let { Triple(stringResource(R.string.lan_ping_sample,it,result.elapsedMs ?: 0),false,line(address,listOf(result.method))) } ?: Triple(address,true,line(null,listOf(result.method))) LanTool.MDNS -> if (result.name.isNotEmpty()) Triple(result.name,false,line(address,listOf(result.detail,result.method))) else Triple(address,true,line(null,listOf(result.detail,result.method))) @@ -395,7 +508,8 @@ private fun ResultRow(result: LanResult, tool: LanTool, viewModel: LanViewModel, LanRow(AnnotatedString(title),subtitle,titleStyle=if(titleMono) NetKitType.addressFor(LanRowTitle) else LanRowTitle,showDivider=showDivider) { val rtt = result.milliseconds if (rtt!=null) Text(stringResource(R.string.lan_rtt,decimal(rtt)),style=LanRowValue,color=colors.text,maxLines=1,softWrap=false) - else if (tool==LanTool.PING) Text(stringResource(R.string.lan_missing_value),style=LanRowValue,color=colors.err) + else if (tool==LanTool.PING) Text(stringResource(if (result.dfTooLarge) R.string.lan_ping_too_large else R.string.lan_missing_value),style=LanRowValue,color=colors.err) + else if (tool==LanTool.TCP_PING) Text(stringResource(tcpLossLabel(result.detail)),style=LanRowValue,color=colors.err,maxLines=1,softWrap=false) if (actions) { var open by remember { mutableStateOf(false) } Box { @@ -405,7 +519,7 @@ private fun ResultRow(result: LanResult, tool: LanTool, viewModel: LanViewModel, open = false if(!copy(context,result.address)) viewModel.exportIpcFailed() }) - if(tool!=LanTool.PING) DropdownMenuItem(text={ Text(stringResource(R.string.lan_ping),style=NetKitType.body) },onClick={ + if(!tool.pingLike) DropdownMenuItem(text={ Text(stringResource(R.string.lan_ping),style=NetKitType.body) },onClick={ open = false viewModel.selectHost(result.address) }) @@ -477,7 +591,7 @@ private fun TraceTimelineRow(item: TraceItem, first: Boolean, last: Boolean, max val fill = when { item.destination -> colors.accent; responded -> colors.surface3; else -> colors.surface2 } Box(Modifier.padding(top=HopTop).size(HopColumn).clip(CircleShape).background(fill),contentAlignment=Alignment.Center) { Text(item.result.detail,style=NetKitType.tag,maxLines=1,softWrap=false, - color=when { item.destination -> colors.accentInk; responded -> colors.text; else -> colors.dim }) + color=when { item.destination -> colors.accentInk; responded -> colors.text; else -> colors.muted }) } } is TraceItem.Silent -> Box(Modifier.padding(top=HopTop+HopColumn/2-Spacing.tiny).size(Spacing.small).clip(CircleShape).background(colors.dim)) @@ -492,7 +606,7 @@ private fun TraceTimelineRow(item: TraceItem, first: Boolean, last: Boolean, max } is TraceItem.Silent -> { Text(pluralStringResource(R.plurals.lan_trace_silent,item.count,item.count),style=NetKitType.body,color=colors.muted) - Text(stringResource(R.string.lan_trace_silent_range,item.firstHop,item.lastHop),style=NetKitType.label,color=colors.dim) + Text(stringResource(R.string.lan_trace_silent_range,item.firstHop,item.lastHop),style=NetKitType.label,color=colors.muted) } } } @@ -500,9 +614,9 @@ private fun TraceTimelineRow(item: TraceItem, first: Boolean, last: Boolean, max horizontalAlignment=Alignment.End,verticalArrangement=Arrangement.spacedBy(Spacing.small)) { val rtt = item.result.milliseconds Row(verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(Spacing.tiny)) { - if (rtt!=null && item.result.method==TRACE_ECHO_METHOD) Text(stringResource(R.string.lan_trace_echo),style=NetKitType.tag,color=colors.dim) + if (rtt!=null && item.result.method==TRACE_ECHO_METHOD) Text(stringResource(R.string.lan_trace_echo),style=NetKitType.tag,color=colors.muted) Text(rtt?.let { stringResource(R.string.lan_rtt,compact(it)) } ?: stringResource(R.string.lan_missing_value), - style=LanRowValue,color=if(rtt!=null) colors.text else colors.dim,maxLines=1,softWrap=false) + style=LanRowValue,color=if(rtt!=null) colors.text else colors.muted,maxLines=1,softWrap=false) } if (rtt!=null && maximum!=null && maximum>0.0) ValueBar((rtt/maximum).toFloat(),modifier=Modifier.fillMaxWidth()) } @@ -548,16 +662,17 @@ private fun LanExportSheet(results: List, format: LanExport, error: I } @Composable -private fun Field(value:String,onChange:(String)->Unit,label:Int,enabled:Boolean,modifier:Modifier=Modifier,number:Boolean=false,mono:Boolean=false) { +internal fun Field(value:String,onChange:(String)->Unit,label:Int,enabled:Boolean,modifier:Modifier=Modifier,number:Boolean=false,mono:Boolean=false,decimal:Boolean=false, + trailing:(@Composable () -> Unit)?=null) { val colors=NetKitTheme.colors - OutlinedTextField(value=value,onValueChange=onChange,label={Text(stringResource(label),maxLines=1,overflow=TextOverflow.Ellipsis)},enabled=enabled, + OutlinedTextField(value=value,onValueChange=onChange,label={Text(stringResource(label),maxLines=1,overflow=TextOverflow.Ellipsis)},enabled=enabled,trailingIcon=trailing, singleLine=true,modifier=modifier.fillMaxWidth(),shape=NetKitShape.nested, textStyle=if(mono) NetKitType.addressFor(NetKitType.value) else NetKitType.value, colors=OutlinedTextFieldDefaults.colors( focusedTextColor=colors.text,unfocusedTextColor=colors.text,disabledTextColor=colors.muted, focusedBorderColor=colors.accent,unfocusedBorderColor=colors.border,disabledBorderColor=colors.borderSoft, focusedLabelColor=colors.accent,unfocusedLabelColor=colors.muted,disabledLabelColor=colors.dim,cursorColor=colors.accent), - keyboardOptions=KeyboardOptions(keyboardType=if(number)KeyboardType.Number else KeyboardType.Ascii)) + keyboardOptions=KeyboardOptions(keyboardType=if(decimal) KeyboardType.Decimal else if(number) KeyboardType.Number else KeyboardType.Ascii)) } /** @@ -568,11 +683,12 @@ private fun Field(value:String,onChange:(String)->Unit,label:Int,enabled:Boolean @Composable private fun PingGraph(samples:List) { val colors=NetKitTheme.colors - val description=stringResource(R.string.lan_graph) + val values = samples.map { it.milliseconds?.toFloat() } + val description = seriesDescription(stringResource(R.string.lan_graph), values, values.indices, stringResource(R.string.lan_unit_ms)) val measurer=rememberTextMeasurer() val locale=LocalConfiguration.current.locales[0] val format=remember(locale) { NumberFormat.getNumberInstance(locale).apply { isGroupingUsed=false; maximumFractionDigits=2 } } - val tick=NetKitType.valueSmall.copy(fontSize=11.sp,lineHeight=14.sp,color=colors.dim) + val tick=NetKitType.valueSmall.copy(fontSize=11.sp,lineHeight=14.sp,color=colors.muted) val top=niceMax(((samples.mapNotNull { it.milliseconds }.maxOrNull() ?: 1.0)*1.15).toFloat()) val ticks=listOf(0f,top/2f,top) val startMs=samples.firstOrNull()?.elapsedMs ?: 0L @@ -619,13 +735,13 @@ private fun PingGraph(samples:List) { drawText(first,topLeft=Offset(left,labelY)) drawText(lastLabel,topLeft=Offset(size.width-lastLabel.size.width,labelY)) } - Text(description,style=NetKitType.label,color=colors.dim) + Text(description,style=NetKitType.label,color=colors.muted) } } private fun decimal(value:Double):String=String.format(Locale.getDefault(),"%.3f",value) /** Short RTT for tiles and the hop timeline; full precision stays in rows and exports. */ private fun compact(value:Double):String=String.format(Locale.getDefault(),when { value<10.0 -> "%.2f"; value<100.0 -> "%.1f"; else -> "%.0f" },value) -private fun copy(context:Context,text:String):Boolean { +internal fun copy(context:Context,text:String):Boolean { if(!lanTextFitsIpc(text))return false return try {context.getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText(context.getString(R.string.lan_title),text));true} catch(_:Exception){false} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanToolPreferences.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanToolPreferences.kt new file mode 100644 index 0000000..3b2a8b8 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanToolPreferences.kt @@ -0,0 +1,55 @@ +package cz.netkit.app.lan + +import cz.netkit.app.backup.ConfigFile +import android.content.Context +import androidx.datastore.core.CorruptionException +import androidx.datastore.core.DataStore +import androidx.datastore.core.DataStoreFactory +import androidx.datastore.core.Serializer +import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler +import cz.netkit.shared.lan.MaskInterpretation +import cz.netkit.shared.lan.ToolTargets +import java.io.InputStream +import java.io.OutputStream +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json + +@Serializable +internal data class LanToolPreferences( + val ping: PingFields = PingFields(), + val subnetInput: String? = null, + val ports: String = "22,80,443,445,3389,8080", + val maskInterpretation: MaskInterpretation = MaskInterpretation.NETMASK, + /** Zadání 48: shared history and favourite targets of the single-target tools (only on this device). */ + val targets: ToolTargets = ToolTargets(), +) + +internal object LanPreferencesSerializer : Serializer { + override val defaultValue = LanToolPreferences() + override suspend fun readFrom(input: InputStream): LanToolPreferences = try { + Json.decodeFromString(input.bufferedReader().readText()) + } catch (error: SerializationException) { + throw CorruptionException("Invalid LAN preferences", error) + } + override suspend fun writeTo(t: LanToolPreferences, output: OutputStream) { + output.write(Json.encodeToString(t).encodeToByteArray()) + } +} + +internal object LanToolStore { + val corruptionHandler = ReplaceFileCorruptionHandler { LanPreferencesSerializer.defaultValue } + private var instance: DataStore? = null + + @Synchronized fun get(context: Context): DataStore = + instance ?: DataStoreFactory.create( + serializer = LanPreferencesSerializer, + corruptionHandler = corruptionHandler, + produceFile = { ConfigFile.LAN.resolve(context) }, + ).also { instance = it } + + /** "Vymazat historii" outside the tools screen (e.g. Settings): favourites stay. */ + suspend fun clearTargetHistory(store: DataStore) { + store.updateData { it.copy(targets = it.targets.clearHistory()) } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt index 022669a..478876c 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt @@ -2,14 +2,19 @@ package cz.netkit.app.lan import android.app.Application import android.net.ConnectivityManager +import android.net.Network import android.net.Uri +import android.os.Build import android.provider.DocumentsContract import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import cz.netkit.app.R import cz.netkit.app.net.ActiveNetworkInfo import cz.netkit.app.net.ActiveNetworkMonitor +import cz.netkit.app.publicip.PublicIpRepository +import cz.netkit.app.speed.boundTo import cz.netkit.app.net.netKindLabel +import cz.netkit.app.wifi.OuiAssets import cz.netkit.shared.lan.* import cz.netkit.shared.net.NetKind import cz.netkit.shared.net.ToolRouteDecision @@ -18,11 +23,24 @@ import java.net.Inet4Address import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference -enum class LanTool { DISCOVERY, PING, TRACE, PORTS, DNS, MDNS } +enum class LanTool { DISCOVERY, PING, TCP_PING, TRACE, PORTS, DNS, MDNS, SUBNET, MAC_VENDOR, RECORDS, WEB, RDAP; + val diagnostic get() = this == RECORDS || this == WEB || this == RDAP + /** Zadání 48: the single-target tools share history and favourites; null = no target field. */ + val targetField: TargetField? get() = when (this) { + PING, TCP_PING, TRACE, PORTS, DNS -> TargetField.HOST + RECORDS -> TargetField.DNS_NAME + WEB -> TargetField.URL + RDAP -> TargetField.RDAP + DISCOVERY, MDNS, SUBNET, MAC_VENDOR -> null + } +} internal data class LanProbeSettings(val timeout: Int = 1000, val parallel: Int = 1, val error: Int? = null) internal fun validatedProbeSettings(tool: LanTool, timeoutText: String, parallelText: String): LanProbeSettings { val timeout = if(tool in listOf(LanTool.DNS,LanTool.MDNS)) 1000 else @@ -33,27 +51,45 @@ internal fun validatedProbeSettings(tool: LanTool, timeoutText: String, parallel } data class LanUiState( val runStatus: LanRunStatus = LanRunStatus.IDLE, val confirmationReasons: Set = emptySet(), + val pingFields: PingFields = PingFields(), val dfSupported: Boolean = false, + val mtuSweep: Boolean = false, val mtuPayload: Int? = null, + val maskInterpretation: MaskInterpretation = MaskInterpretation.NETMASK, + val diagnosticInput: String = "", val recordType: RecordType = RecordType.A, val canCompare: Boolean = false, + val redirectPrefill: String? = null, val webConfirmation: WebLocalTarget? = null, + val diagnosticLines: List> = emptyList(), + val subnetInput: String? = null, val wifiCidr: String = "", val exportFormat: LanExport = LanExport.TEXT, val tool: LanTool = LanTool.DISCOVERY, val cidr: String = "", val host: String = "", val ports: String = "22,80,443,445,3389,8080", val timeout: String = "1000", val concurrency: String = "32", val serviceType: String = "_http._tcp.", - val probeCounts: ProbeCounts = ProbeCounts(), val traceRouteWarning: Boolean = false, + val awaitingTrace: Boolean = false, val probeCounts: ProbeCounts = ProbeCounts(), val traceRouteWarning: Boolean = false, val readBanner: Boolean = false, val busy: Boolean = false, val progress: Int = 0, val total: Int = 0, val results: List = emptyList(), val samples: List = emptyList(), - val sent: Int = 0, val received: Int = 0, val error: Int? = null, val notice: Int? = null, + val dnsRcode: Int? = null, val sent: Int = 0, val received: Int = 0, val error: Int? = null, val notice: Int? = null, val confirmation: Boolean = false, val confirmationTarget: String = "", val wifiAddress: String? = null, /** Network the next run of the visible tool would use (`null` = no usable network). */ val predictedRoute: NetKind? = null, /** Network of the current or last run; cleared when the target or tool changes. */ val runRoute: NetKind? = null, + /** Zadání 48: shared target history and favourites (DataStore of the tools). */ + val targets: ToolTargets = ToolTargets(), + val tcpPort: String = TCP_PING_DEFAULT_PORT.toString(), val tcpCount: String = "10", + val macInput: String = "", val macRows: List = emptyList(), val macError: MacInputError? = null, + /** The bundled OUI list could not be read: every vendor shows as unknown. */ + val ouiMissing: Boolean = false, ) { val routeKind: NetKind? get() = runRoute ?: predictedRoute } /** A run that cannot start on the current networks; [resource] explains why. */ private class ToolRefused(val resource: Int) : Exception() -class LanViewModel(application: Application) : AndroidViewModel(application) { - private val backend = LanBackend(application) +class LanViewModel internal constructor( + application: Application, + private val backend: LanBackend, + private val traceProbe: suspend (ToolRoute, String, Int, Int) -> PingReply, +) : AndroidViewModel(application) { + private constructor(application: Application, backend: LanBackend) : this(application, backend, backend::ping) + constructor(application: Application) : this(application, LanBackend(application)) private val mutable = MutableStateFlow(LanUiState()) val state = mutable.asStateFlow() private var active: Job? = null @@ -67,17 +103,58 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { private val pending = AtomicReference() private var networkSnapshot: LanWifi? = null @Volatile private var activeSnapshot: ActiveNetworkInfo? = null + private var physicalWifi: Network? = null + private val online by lazy { PublicIpRepository(getApplication()) } private var networkInitialized = false private var pendingExport: Pair>? = null + private val preferences = LanToolStore.get(application) + private var pingEdited = false + private var portsEdited = false + + private fun savePreference(transform: (LanToolPreferences) -> LanToolPreferences) { + // UNDISPATCHED starts immediately. NonCancellable protects the bounded write when the ViewModel is cleared. + viewModelScope.launch(start = CoroutineStart.UNDISPATCHED) { + val saved = withContext(NonCancellable) { + try { withTimeoutOrNull(3000) { preferences.updateData { transform(it) } } } + catch (_: java.io.IOException) { null } + } + if (saved == null) mutable.update { it.copy(notice = R.string.lan_settings_io) } + } + } + init { + viewModelScope.launch { + val supported = withContext(Dispatchers.IO) { WifiIcmp.supportsDf() } + mutable.update { it.copy(dfSupported = supported) } + } viewModelScope.launch { try { - backend.observeWifi().collect { wifi -> networkChanged(wifi) } + val saved = preferences.data.first() + mutable.update { it.copy(subnetInput = it.subnetInput ?: saved.subnetInput, + maskInterpretation = if (it.subnetInput == null) saved.maskInterpretation else it.maskInterpretation, + pingFields = if (pingEdited) it.pingFields else saved.ping, + ports = if (portsEdited) it.ports else saved.ports) } + } catch (_: java.io.IOException) { mutable.update { it.copy(notice = R.string.lan_settings_io) } } + } + viewModelScope.launch { + // Follows every write (this screen, another ViewModel or "Vymazat historii" in Settings). + try { preferences.data.map { it.targets.normalized() }.distinctUntilChanged().collect { targets -> mutable.update { it.copy(targets = targets) } } } + catch (_: java.io.IOException) { /* The load above already reported the storage problem. */ } + } + viewModelScope.launch { + try { + backend.wifiChanges().collect { + val (wifi, physical) = withContext(Dispatchers.IO) { backend.wifi() to backend.diagnosticWifi() } + physicalWifi = physical + networkChanged(wifi) + predictRoute() + } } catch (error: CancellationException) { throw error } catch (_: Exception) { fail(R.string.lan_no_wifi) } } viewModelScope.launch { ActiveNetworkMonitor(application.getSystemService(ConnectivityManager::class.java)).observe().collect { active -> + if (state.value.tool.diagnostic && (state.value.busy || state.value.webConfirmation != null) && activeSnapshot?.network != active?.network) cancelActive() activeSnapshot = active predictRoute() } @@ -92,11 +169,12 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { val kind = when (current.tool) { // Wi-Fi-only tools always name Wi-Fi; the screen marks it when Wi-Fi is missing. LanTool.DISCOVERY, LanTool.MDNS -> NetKind.WIFI + LanTool.RECORDS, LanTool.WEB, LanTool.RDAP -> active?.kind LanTool.DNS -> if (wifi != null) NetKind.WIFI else active?.kind - else -> if (ipv4Number(host) != null) (routeFor(host, wifi, active) as? RouteChoice.Selected)?.route?.kind ?: active?.kind + else -> if (lanNumericAddress(host) != null) (routeFor(host, wifi, active) as? RouteChoice.Selected)?.route?.kind ?: active?.kind else active?.kind ?: if (wifi != null) NetKind.WIFI else null } - current.copy(predictedRoute = kind) + current.copy(predictedRoute = kind, canCompare = active?.kind == NetKind.VPN && physicalWifi != null && physicalWifi != active.network) } } private sealed interface RouteChoice { @@ -105,7 +183,8 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { } /** See [chooseToolRoute]: public targets over the active network, local ones over Wi-Fi or VPN. */ private fun routeFor(address: String, wifi: LanWifi?, active: ActiveNetworkInfo?): RouteChoice = - when (chooseToolRoute(address, wifi != null, active?.kind, active?.viaVpn == true, wifi?.subnet?.contains(address) == true)) { + when (chooseToolRoute(address, wifi != null, active?.kind, active?.viaVpn == true, + wifi != null && onWifiLink(address, wifi.subnet) { backend.ipv6Prefixes(wifi.network) })) { ToolRouteDecision.WIFI -> wifi?.let { RouteChoice.Selected(ToolRoute.wifi(it)) } ?: RouteChoice.Refused(R.string.lan_no_network) ToolRouteDecision.ACTIVE -> active?.let { RouteChoice.Selected(ToolRoute.active(it, wifi)) } ?: RouteChoice.Refused(R.string.lan_no_network) ToolRouteDecision.LOCAL_NEEDS_WIFI_OR_VPN -> RouteChoice.Refused(R.string.lan_local_needs_wifi) @@ -121,6 +200,7 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { } private fun networkChanged(wifi: LanWifi?) { if (networkInitialized && networkSnapshot == wifi) return + mutable.update { it.copy(wifiCidr = wifi?.let { w -> "${w.address}/${w.prefix}" }.orEmpty()) } if (!networkInitialized) { networkInitialized = true networkSnapshot = wifi @@ -140,10 +220,75 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { networkChanged(wifi) } } - fun tool(tool: LanTool) { cancelActive(); mutable.update { it.copy(tool=tool,runStatus=LanRunStatus.IDLE,results=emptyList(),samples=emptyList(),error=null,notice=null,confirmation=false,progress=0,total=0,runRoute=null) }; predictRoute() } + fun tool(tool: LanTool) { cancelActive(); mutable.update { it.copy(tool=tool,diagnosticInput="",macRows=emptyList(),macError=null,ouiMissing=false,redirectPrefill=null,diagnosticLines=emptyList(),mtuSweep=false,mtuPayload=null,traceRouteWarning=false,runStatus=LanRunStatus.IDLE,results=emptyList(),samples=emptyList(),error=null,notice=null,confirmation=false,progress=0,total=0,runRoute=null) }; predictRoute() } fun cidr(value: String) { pending.set(null); mutable.update { it.copy(cidr=value,confirmation=false) } } fun host(value: String) { pending.set(null); mutable.update { it.copy(host=value,confirmation=false,runRoute=if(it.busy) it.runRoute else null) }; predictRoute() } - fun ports(value: String) { pending.set(null); mutable.update { it.copy(ports=value,confirmation=false) } } + fun pingFields(fields: PingFields) { + pending.set(null) + pingEdited = true + mutable.update { it.copy(pingFields = fields, confirmation = false) } + savePreference { it.copy(ping = fields) } + } + fun subnetInput(value: String, interpretation: MaskInterpretation = MaskInterpretation.NETMASK) { + mutable.update { it.copy(subnetInput = value, maskInterpretation = interpretation) } + savePreference { it.copy(subnetInput = value, maskInterpretation = interpretation) } + } + fun ports(value: String) { + pending.set(null) + portsEdited = true + mutable.update { it.copy(ports=value,confirmation=false) } + savePreference { it.copy(ports = value) } + } + fun tcpPort(value: String) { pending.set(null); mutable.update { it.copy(tcpPort=value,confirmation=false) } } + fun tcpCount(value: String) { pending.set(null); mutable.update { it.copy(tcpCount=value,confirmation=false) } } + + /** A started run moves its target to the top of the shared history (only local). */ + private fun rememberTarget(value: String) { savePreference { it.copy(targets = it.targets.normalized().remember(value)) } } + fun starTarget(value: String, label: String) { + when (state.value.targets.star(value, label)) { + FavoriteChange.Limit -> mutable.update { it.copy(error = R.string.tools48_favorite_limit) } + FavoriteChange.Invalid -> mutable.update { it.copy(error = R.string.tools48_favorite_invalid) } + is FavoriteChange.Updated -> savePreference { saved -> + (saved.targets.normalized().star(value, label) as? FavoriteChange.Updated)?.let { saved.copy(targets = it.targets) } ?: saved + } + } + } + fun unstarTarget(value: String) { savePreference { it.copy(targets = it.targets.normalized().unstar(value)) } } + fun clearTargetHistory(): Deferred = viewModelScope.async(start = CoroutineStart.UNDISPATCHED) { + val cleared = withContext(NonCancellable) { + try { withTimeoutOrNull(3_000) { LanToolStore.clearTargetHistory(preferences) } != null } + catch (_: java.io.IOException) { false } + } + if (!cleared) mutable.update { it.copy(notice = R.string.lan_settings_io) } + cleared + } + + fun macInput(value: String) { + // Anything longer than the limit is refused as a whole; holding a larger paste is pointless. + if (!state.value.busy) mutable.update { it.copy(macInput = value.take(MAC_INPUT_MAX_BYTES + 1), macRows = emptyList(), macError = null, + results = emptyList(), error = null, notice = null, runStatus = LanRunStatus.IDLE) } + } + /** Offline: the parser in commonMain and the bundled IEEE OUI list; nothing leaves the phone. */ + fun lookupMacs() { + val form = state.value + if (form.tool != LanTool.MAC_VENDOR || form.busy) return + val id = generation.incrementAndGet() + mutable.update { it.copy(busy = true, macRows = emptyList(), macError = null, results = emptyList(), error = null, notice = null, + ouiMissing = false, runStatus = LanRunStatus.RUNNING) } + active = viewModelScope.launch(Dispatchers.Default) { + try { + val extraction = extractMacAddresses(form.macInput) + if (extraction.error != null) { + publish(id) { it.copy(macError = extraction.error, runStatus = LanRunStatus.FAILED) } + return@launch + } + val database = withContext(Dispatchers.IO) { OuiAssets.loadedOnIo(getApplication()) } + val rows = macVendorRows(extraction.macs, database) + publish(id) { it.copy(macRows = rows, results = macExportRows(rows), ouiMissing = database.size == 0, + notice = if (rows.isEmpty()) R.string.tools48_mac_none else null) } + } finally { finishRun(id) } + } + } fun timeout(value: String) { pending.set(null); mutable.update { it.copy(timeout=value,confirmation=false) } } fun concurrency(value: String) { pending.set(null); mutable.update { it.copy(concurrency=value,confirmation=false) } } fun serviceType(value: String) { pending.set(null); mutable.update { it.copy(serviceType=value,confirmation=false) } } @@ -151,7 +296,11 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { fun preset() { ports(commonPorts.joinToString(",")) } fun dismissConfirmation() { pending.set(null); mutable.update { it.copy(confirmation=false) } } fun selectHost(address: String) { host(address); tool(LanTool.PING) } - fun cancelActive() { pending.set(null); generation.incrementAndGet(); active?.cancel(); active=null; mutable.update { it.copy(busy=false,confirmation=false,runStatus=if(it.busy) LanRunStatus.CANCELLED else it.runStatus) } } + fun continueTrace() { + mutable.update { if (it.awaitingTrace) it.copy(awaitingTrace = false, notice = null) else it } + } + fun cancelActive() { pending.set(null); generation.incrementAndGet(); active?.cancel(); active=null; mutable.update { it.copy(busy=false,webConfirmation=null,confirmation=false,awaitingTrace=false, + notice=if(it.awaitingTrace) null else it.notice,runStatus=if(it.busy) LanRunStatus.CANCELLED else it.runStatus) } } private fun fail(resource: Int) { mutable.update { it.copy(error=resource,busy=false,confirmation=false,runStatus=LanRunStatus.FAILED) } } private suspend fun publish(runId: Int, change: (LanUiState)->LanUiState) = withContext(Dispatchers.Main.immediate) { currentCoroutineContext().ensureActive() @@ -193,25 +342,131 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { } } - fun start(confirmed: Boolean = false) { - if (state.value.busy) return + fun diagnosticInput(value: String) { + if (!state.value.busy) mutable.update { it.copy(diagnosticInput = value, redirectPrefill = null, webConfirmation = null, results = emptyList(), + diagnosticLines = emptyList(), error = null, runStatus = LanRunStatus.IDLE) } + } + fun recordType(type: RecordType) { + if (!state.value.busy) { + diagnosticInput(state.value.diagnosticInput) + mutable.update { it.copy(recordType = type) } + } + } + + fun startDiagnostic(compare: Boolean = false) = runDiagnostic(compare, null) + + internal fun confirmWeb(target: WebLocalTarget) { + if (state.value.webConfirmation == target) runDiagnostic(false, target) + } + + private fun runDiagnostic(compare: Boolean, confirmed: WebLocalTarget?) { + val form = state.value + if (!form.tool.diagnostic || form.busy) return + val network = activeSnapshot ?: return fail(R.string.lan_no_network) + val field = form.tool.targetField + if (field != null && targetFits(field, form.diagnosticInput)) rememberTarget(form.diagnosticInput.trim()) + val wifi = physicalWifi + val id = generation.incrementAndGet() + val app = getApplication() + mutable.update { it.copy(busy = true, redirectPrefill = null, webConfirmation = null, results = emptyList(), diagnosticLines = emptyList(), error = null, + notice = null, runRoute = network.kind, runStatus = LanRunStatus.RUNNING) } + active = viewModelScope.launch(Dispatchers.IO) { + try { + withTimeout(45000) { + fun checkDefault() { + if (backend.activeNetwork()?.network != network.network) throw DiagnosticFailure(R.string.lan_network_changed) + } + checkDefault() + when (form.tool) { + LanTool.RECORDS -> { + val name = recordQueryName(form.diagnosticInput, form.recordType) + ?: throw DiagnosticFailure(R.string.diag_bad_name) + val routes = recordRoutes(network.network, network.kind, wifi, compare) + if (routes.isEmpty()) throw DiagnosticFailure(R.string.lan_network_changed) + for ((kind, target) in routes) { + ensureActive() + checkDefault() + if (compare && wifi != backend.diagnosticWifi()) throw DiagnosticFailure(R.string.lan_network_changed) + val route = app.getString(netKindLabel(kind)) + val rows = try { + val reply = queryRecords(target, name, form.recordType) + reply.rows(name, form.recordType, route) + } catch (e: TimeoutCancellationException) { + ensureActive() + listOf(LanResult(name, method = route, detail = app.getString(R.string.lan_dns_timeout))) + } catch (e: DnsFailure) { + listOf(LanResult(name, method = route, detail = app.getString(e.resource))) + } + publish(id) { it.copy(results = it.results + rows) } + } + } + LanTool.WEB -> { + val client = diagnosticClient().boundTo(network.network) + val report = inspectWeb(form.diagnosticInput, client, confirmed) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + app.getSystemService(ConnectivityManager::class.java).getLinkProperties(network.network) + ?.nat64Prefix?.let { WebNat64Prefix(it.address, it.prefixLength) } + } else null + } + val lines = app.webLines(report) + publish(id) { it.copy(diagnosticLines = lines, error = report.error?.label(), + redirectPrefill = report.prefillUrl?.toString(), webConfirmation = report.confirmation, + runStatus = when { + report.confirmation != null -> LanRunStatus.IDLE + report.error != null -> LanRunStatus.FAILED + else -> LanRunStatus.FINISHED + }) } + } + LanTool.RDAP -> { + val result = lookupRdap(form.diagnosticInput, online::isLookupEnabled) { path -> + fetchRdap(path, diagnosticClient().boundTo(network.network), online::isLookupEnabled) + } + publish(id) { it.copy(diagnosticLines = app.rdapLines(result)) } + } + else -> return@withTimeout + } + } + } catch (e: TimeoutCancellationException) { failFor(id, R.string.lan_operation_timeout) + } catch (e: CancellationException) { throw e + } catch (e: DiagnosticFailure) { + val retry = e.retryAfterSeconds?.let { seconds -> + listOf("Retry-After" to app.getString(R.string.diag_rdap_wait, seconds)) + }.orEmpty() + publish(id) { it.copy(error = e.label, diagnosticLines = retry, runStatus = LanRunStatus.FAILED) } + } catch (e: Exception) { failFor(id, failure(e)) + } finally { finishRun(id) } + } + } + + fun start(confirmed: Boolean = false, mtuSweep: Boolean = false) { + if (state.value.busy || state.value.tool.diagnostic || state.value.tool == LanTool.SUBNET || state.value.tool == LanTool.MAC_VENDOR) return if (confirmed) { acceptPending(); return } pending.set(null) - val snapshot = state.value + val snapshot = state.value.copy(mtuSweep = mtuSweep) + if (mtuSweep && (snapshot.tool != LanTool.PING || !snapshot.dfSupported)) return + if (snapshot.tool == LanTool.PING && !mtuSweep && snapshot.pingFields.options(snapshot.dfSupported) == null) + return fail(R.string.lan_ping_invalid) val settings = validatedProbeSettings(snapshot.tool,snapshot.timeout,snapshot.concurrency) settings.error?.let { return fail(it) } val timeout=settings.timeout val parallel=settings.parallel val subnet = if (snapshot.tool == LanTool.DISCOVERY) Ipv4Subnet.parse(snapshot.cidr) ?: return fail(R.string.lan_invalid_cidr) else null if (subnet != null && subnet.hostCount > 4096) return fail(R.string.lan_host_limit) - val portList = if (snapshot.tool == LanTool.PORTS) parsePorts(snapshot.ports) ?: return fail(R.string.lan_invalid_ports) else emptyList() + val portList = when (snapshot.tool) { + LanTool.PORTS -> parsePorts(snapshot.ports) ?: return fail(R.string.lan_invalid_ports) + // One port; it also counts in the confirmation ("portů: 1"). + LanTool.TCP_PING -> listOf((tcpPingOptions(snapshot.tcpPort, snapshot.tcpCount) ?: return fail(R.string.tools48_tcp_invalid)).port) + else -> emptyList() + } val host = snapshot.host.trim() - if (snapshot.tool in listOf(LanTool.PING,LanTool.TRACE,LanTool.PORTS,LanTool.DNS) && - !validLanHost(host)) return fail(R.string.lan_invalid_host) + if (snapshot.tool.targetField == TargetField.HOST) { + if (!validLanTarget(host)) return fail(R.string.lan_invalid_host) + rememberTarget(host) + } if (snapshot.tool == LanTool.MDNS && !Regex("_[A-Za-z0-9-]{1,62}\\._(?:tcp|udp)\\.?").matches(snapshot.serviceType)) return fail(R.string.lan_invalid_service) // Hostnames are resolved before the final address confirmation below; no probe yet. val runGeneration = generation.incrementAndGet() - mutable.update { it.copy(busy=true,runStatus=LanRunStatus.RUNNING,error=null,notice=null,confirmation=false,results=emptyList(),samples=emptyList(),sent=0,received=0,progress=0,total=0,probeCounts=ProbeCounts(),traceRouteWarning=false,runRoute=null) } + mutable.update { it.copy(busy=true,mtuSweep=mtuSweep,mtuPayload=null,runStatus=LanRunStatus.RUNNING,error=null,notice=null,confirmation=false,results=emptyList(),samples=emptyList(),sent=0,received=0,progress=0,total=0,probeCounts=ProbeCounts(),traceRouteWarning=false,runRoute=null) } active = viewModelScope.launch(Dispatchers.IO) { try { val wifi = backend.wifi() @@ -220,8 +475,9 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { publish(runGeneration) { it.copy(wifiAddress=wifi?.address) } val wifiOnly = snapshot.tool in listOf(LanTool.DISCOVERY,LanTool.MDNS) if (wifiOnly && wifi == null) { failFor(runGeneration,R.string.lan_no_wifi); return@launch } - val target = if (snapshot.tool in listOf(LanTool.PING,LanTool.TRACE,LanTool.PORTS)) { + val target = if (snapshot.tool in listOf(LanTool.PING,LanTool.TCP_PING,LanTool.TRACE,LanTool.PORTS)) { val address = resolveTarget(host,wifi,activeNetwork) + ipv6Refusal(snapshot.tool,address,mtuSweep)?.let { throw ToolRefused(it) } when (val choice = routeFor(address,wifi,activeNetwork)) { is RouteChoice.Selected -> PinnedLanHost(choice.route,address) is RouteChoice.Refused -> throw ToolRefused(choice.resource) @@ -237,7 +493,7 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { val request = PreparedRequest(snapshot,if (wifiOnly) wifi else null,route,timeout,parallel,subnet,portList,target,runGeneration,routeWarning) val reasons = when { subnet != null -> targetConfirmationReasons(subnet,wifi?.subnet,portList.size) - target != null -> targetConfirmationReasons(Ipv4Subnet.parse("${target.address}/32")!!,target.network.wifi?.subnet,portList.size) + target != null -> toolTargetReasons(target.address,target.network.wifi?.subnet,target.network.wifi?.let { backend.ipv6Prefixes(it.network) },portList.size) // Without Wi-Fi there is no own subnet to be outside of; the address class still counts. .let { found -> if (target.network.wifi == null) found - TargetConfirmationReason.OUTSIDE_WIFI else found } else -> emptySet() @@ -256,7 +512,10 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { } catch (error: TimeoutCancellationException) { currentCoroutineContext().ensureActive(); failFor(runGeneration,R.string.lan_operation_timeout) } catch (error: CancellationException) { throw error } catch (error: ToolRefused) { currentCoroutineContext().ensureActive(); failFor(runGeneration,error.resource) + } catch (_: Ipv6ZoneMismatchException) { currentCoroutineContext().ensureActive(); failFor(runGeneration,R.string.lan39_ipv6_zone_mismatch) } catch (error: UnsupportedOperationException) { currentCoroutineContext().ensureActive(); failFor(runGeneration,R.string.lan_mdns_unsupported) + } catch (error: DnsFailure) { + publish(runGeneration) { it.copy(error = error.resource, dnsRcode = error.rcode, busy = false, runStatus = LanRunStatus.FAILED) } } catch (error: Exception) { currentCoroutineContext().ensureActive(); failFor(runGeneration,failure(error)) } finally { finishRun(runGeneration) } } @@ -266,13 +525,13 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { * network (public names when the Wi-Fi resolver fails, e.g. Wi-Fi without internet). */ private suspend fun resolveTarget(host: String, wifi: LanWifi?, active: ActiveNetworkInfo?): String { - if (ipv4Number(host) != null) return host + lanNumericAddress(host)?.let { return it.text } val routes = listOfNotNull(wifi?.let(ToolRoute::wifi), active?.let { ToolRoute.active(it,wifi) }).distinct() if (routes.isEmpty()) throw ToolRefused(R.string.lan_no_network) var last: Exception? = null for (route in routes) { try { - return backend.resolve(route,host).firstOrNull { it is Inet4Address }?.hostAddress ?: throw IllegalArgumentException("IPV4") + return pickToolAddress(backend.resolve(route,host)) ?: throw IllegalArgumentException("ADDRESS") } catch (error: TimeoutCancellationException) { last = error } catch (error: CancellationException) { throw error } catch (error: Exception) { last = error } @@ -313,6 +572,8 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { execute(request.copy(generation=runGeneration)) } catch (error: TimeoutCancellationException) { currentCoroutineContext().ensureActive(); failFor(runGeneration,R.string.lan_operation_timeout) } catch (error: CancellationException) { throw error + } catch (error: DnsFailure) { + publish(runGeneration) { it.copy(error = error.resource, dnsRcode = error.rcode, busy = false, runStatus = LanRunStatus.FAILED) } } catch (error: Exception) { currentCoroutineContext().ensureActive(); failFor(runGeneration,failure(error)) } finally { finishRun(runGeneration) } } @@ -339,7 +600,7 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { val route=request.route!! for (address in backend.resolve(route,snapshot.host.trim())) { val ip=address.hostAddress.orEmpty() - append(LanResult(ip,if (address is Inet4Address) reverseOrEmpty(route,ip) else "","DNS"),runId) + append(LanResult(ip,if (address is Inet4Address) reverseOrEmpty(route,ip) else "",if (address is Inet4Address) "A" else "AAAA"),runId) } } else -> { @@ -348,9 +609,11 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { if (current != target.network) throw java.io.IOException("NETWORK_LOST") probePinnedHost(target,current) { selected,ip -> when(snapshot.tool) { - LanTool.PING -> ping(selected,ip,request.timeout,runId) + LanTool.PING -> if (snapshot.mtuSweep) sweep(selected, ip, request.timeout, runId) + else ping(selected, ip, request.timeout, runId, requireNotNull(snapshot.pingFields.options(snapshot.dfSupported))) LanTool.TRACE -> trace(selected,ip,request.timeout,runId,request.traceRouteWarning) LanTool.PORTS -> scanPorts(selected,ip,request.ports,request.timeout,request.parallel,snapshot.readBanner,runId) + LanTool.TCP_PING -> tcpPing(selected,ip,request.ports.single(),requireNotNull(tcpPingOptions(snapshot.tcpPort,snapshot.tcpCount)).count,request.timeout,runId) else -> Unit } } @@ -386,30 +649,73 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { publish(runId) { it.copy(progress=it.progress+1) } } } - private suspend fun ping(route: ToolRoute,ip: String,timeout: Int,runId: Int) { + private suspend fun ping(route: ToolRoute, ip: String, timeout: Int, runId: Int, options: PingOptions) { val start = System.nanoTime() - while (currentCoroutineContext().isActive) { - backend.checkRoute(route) - val reply = try { backend.ping(route,ip,timeout) } - catch (_: TimeoutCancellationException) { PingReply(null) } - catch (_: IcmpUnavailableException) { failFor(runId,R.string.lan_icmp_unavailable); return } - val elapsed=(System.nanoTime()-start)/1_000_000 - publish(runId) { old -> old.copy(samples=(old.samples+reply.milliseconds).takeLast(600), - sent=old.sent+1,received=old.received+if(reply.milliseconds != null) 1 else 0, - results=appendPingResult(old.results,ip,old.sent.toLong()+1,elapsed,reply.milliseconds),progress=old.sent+1) } - delay(1000) + fun elapsedMs() = (System.nanoTime() - start) / 1_000_000 + options.count?.let { count -> publish(runId) { it.copy(total = count) } } + try { + runPingSeries(options, ::elapsedMs) { + var tooLarge = false + val rtt = try { + backend.pingWithOptions(route, ip, timeout, options.payload, options.df).milliseconds + } catch (_: DfTooLargeException) { tooLarge = true; null } + val elapsed = elapsedMs() + publish(runId) { old -> + val rows = appendPingResult(old.results, ip, old.sent.toLong() + 1, elapsed, rtt, + dfTooLarge = tooLarge) + old.copy(samples = (old.samples + rtt).takeLast(600), sent = old.sent + 1, + received = old.received + if (rtt == null) 0 else 1, results = rows, progress = old.sent + 1) + } + } + } catch (_: IcmpUnavailableException) { failFor(runId, R.string.lan_icmp_unavailable) } + } + + /** Zadání 48: one TCP connect per second, never two at once (the next starts after the previous closed). */ + private suspend fun tcpPing(route: ToolRoute, ip: String, port: Int, count: Int?, timeout: Int, runId: Int) { + val start = System.nanoTime() + fun elapsedMs() = (System.nanoTime() - start) / 1_000_000 + count?.let { total -> publish(runId) { it.copy(total = total) } } + runPingSeries(PingOptions(count, TCP_PING_INTERVAL_MS, 0, false), ::elapsedMs) { + val probe = backend.tcpProbe(route, ip, port, timeout) + val rtt = probe.result?.milliseconds + val elapsed = elapsedMs() + publish(runId) { old -> + val rows = appendTcpPingResult(old.results, ip, port, old.sent.toLong() + 1, elapsed, rtt, probe.status) + val reply = rows.last().milliseconds + old.copy(samples = (old.samples + reply).takeLast(600), sent = old.sent + 1, received = old.received + if (reply == null) 0 else 1, + probeCounts = old.probeCounts.add(probe.status), results = rows, progress = old.sent + 1) + } } } + + private suspend fun sweep(route: ToolRoute, ip: String, timeout: Int, runId: Int) { + var probes = 0 + val result = try { + findMtuPayload { size -> + if (probes > 0) delay(200) + val response = try { + val rtt = backend.pingWithOptions(route, ip, timeout, size, df = true).milliseconds + if (rtt == null) DfProbe.NO_REPLY else DfProbe.REPLY + } catch (_: DfTooLargeException) { DfProbe.TOO_LARGE } + probes++ + publish(runId) { it.copy(progress = probes) } + response + } + } catch (_: IcmpUnavailableException) { failFor(runId, R.string.lan_icmp_unavailable); return } + publish(runId) { it.copy(mtuPayload = result.bestPayload, notice = when { + result.limit == SweepLimit.SOFT_TIMEOUT -> R.string.lan_mtu_soft_limit + result.limit == SweepLimit.NO_BASELINE -> R.string.lan_mtu_inconclusive + result.bestPayload == null -> R.string.lan_mtu_below + else -> R.string.lan_mtu_complete + }) } + } private suspend fun trace(route: ToolRoute,ip: String,timeout: Int,runId: Int,routeWarning: Boolean) { publish(runId) { it.copy(total=30) } - var knownHop=false - for (ttl in 1..30) { + val reached = tracePath(ip, route.localAddress, probe = { ttl -> backend.checkRoute(route) if (backend.traceNeedsConfirmation(route) && !routeWarning) throw java.io.IOException("ROUTE_CHANGED") - val reply = try { backend.ping(route,ip,timeout,ttl) } catch (_: TimeoutCancellationException) { PingReply(null) } - currentCoroutineContext().ensureActive() - val address=if (reply.milliseconds != null) ip else reply.hop?.takeUnless { it == route.localAddress }.orEmpty() - if (address.isNotEmpty()) knownHop=true + try { traceProbe(route, ip, timeout, ttl) } catch (_: TimeoutCancellationException) { PingReply(null) } + }, record = { ttl, address, reply -> val measureHop = address.isNotEmpty() && address != ip val milliseconds = if (measureHop) { val echoTimeout = minOf(timeout,1000) @@ -425,10 +731,11 @@ class LanViewModel(application: Application) : AndroidViewModel(application) { } else reply.milliseconds append(LanResult(address,method=if (measureHop) "TTL+ICMP" else "TTL",milliseconds=milliseconds,detail=ttl.toString(),routeMayBeOutsideWifi=routeWarning),runId) publish(runId) { it.copy(progress=ttl) } - if (reply.milliseconds != null) return - if (ttl == 5 && !knownHop) { publish(runId) { it.copy(notice=R.string.lan_trace_limited) }; return } - } - publish(runId) { it.copy(notice=R.string.lan_trace_limited) } + }, awaitContinue = { + publish(runId) { it.copy(awaitingTrace = true, notice = R.string.lan_trace_paused) } + state.first { !it.awaitingTrace } + }) + if (!reached) publish(runId) { it.copy(notice = R.string.lan_trace_limited) } } override fun onCleared() { cancelActive(); super.onCleared() } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/MacVendorPanel.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/MacVendorPanel.kt new file mode 100644 index 0000000..ade9f43 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/MacVendorPanel.kt @@ -0,0 +1,110 @@ +package cz.netkit.app.lan + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import cz.netkit.app.R +import cz.netkit.app.ui.NeutralButton +import cz.netkit.app.ui.Panel +import cz.netkit.app.ui.PrimaryButton +import cz.netkit.app.ui.SectionCard +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.StatusBanner +import cz.netkit.app.ui.StatusKind +import cz.netkit.app.ui.Tag +import cz.netkit.app.ui.Tone +import cz.netkit.app.ui.theme.NetKitShape +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.lan.MacInputError +import cz.netkit.shared.lan.MacVendorRow + +/** Rows per lazy item: a pasted table with thousands of addresses is never composed at once. */ +private const val MAC_ROWS_PER_ITEM = 25 + +/** Zadání 48: "MAC → výrobce" — one MAC or a pasted MAC table, vendor from the bundled IEEE OUI list. */ +internal fun LazyListScope.macVendorTool(state: LanUiState, viewModel: LanViewModel) { + item(key = "mac_input") { MacInputPanel(state, viewModel) } + state.macError?.let { error -> item(key = "mac_error") { + StatusBanner(when (error) { + MacInputError.TOO_LARGE -> stringResource(R.string.tools48_mac_too_large) + MacInputError.TOO_MANY_LINES -> stringResource(R.string.tools48_mac_too_many_lines) + }, StatusKind.ERROR) + } } + // Export (SAF/clipboard/share) failures land in state.error; without this the user would not see them here. + state.error?.let { error -> item(key = "mac_state_error") { Box(Modifier.testTag("mac_state_error")) { StatusBanner(stringResource(error), StatusKind.ERROR) } } } + state.notice?.let { notice -> item(key = "mac_notice") { StatusBanner(stringResource(notice)) } } + if (state.ouiMissing) item(key = "mac_oui_missing") { StatusBanner(stringResource(R.string.tools48_mac_oui_missing), StatusKind.WARNING) } + if (state.macRows.isEmpty()) return + item(key = "mac_summary") { + val count = state.macRows.size + val known = state.macRows.count { it.vendor != null } + SectionCard(stringResource(R.string.tools48_mac_results), meta = stringResource(R.string.tools48_mac_count, count)) { + Text(stringResource(R.string.tools48_mac_summary, known, count - known), style = NetKitType.label, color = NetKitTheme.colors.muted) + } + } + val chunks = state.macRows.chunked(MAC_ROWS_PER_ITEM) + chunks.forEachIndexed { index, chunk -> + item(key = "mac_rows_$index") { + Panel(padding = Spacing.normal) { + Column { chunk.forEachIndexed { row, entry -> MacVendorLine(entry, showDivider = row > 0) } } + } + } + } +} + +@Composable +private fun MacInputPanel(state: LanUiState, viewModel: LanViewModel) { + val colors = NetKitTheme.colors + Panel { + OutlinedTextField(value = state.macInput, onValueChange = viewModel::macInput, enabled = !state.busy, + label = { Text(stringResource(R.string.tools48_mac_input)) }, + modifier = Modifier.fillMaxWidth().heightIn(min = 120.dp).testTag("mac_input"), minLines = 4, maxLines = 10, + shape = NetKitShape.nested, textStyle = NetKitType.addressFor(NetKitType.label), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Ascii, autoCorrectEnabled = false), + colors = OutlinedTextFieldDefaults.colors( + focusedTextColor = colors.text, unfocusedTextColor = colors.text, disabledTextColor = colors.muted, + focusedBorderColor = colors.accent, unfocusedBorderColor = colors.border, disabledBorderColor = colors.borderSoft, + focusedLabelColor = colors.accent, unfocusedLabelColor = colors.muted, disabledLabelColor = colors.dim, cursorColor = colors.accent)) + Text(stringResource(R.string.tools48_mac_help), style = NetKitType.label, color = colors.muted) + Row(horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + PrimaryButton(stringResource(R.string.tools48_mac_lookup), viewModel::lookupMacs, Modifier.weight(1f).testTag("mac_lookup"), + enabled = !state.busy && state.macInput.isNotBlank()) + NeutralButton(stringResource(R.string.tools48_mac_clear), { viewModel.macInput("") }, enabled = !state.busy && state.macInput.isNotEmpty()) + } + } +} + +@Composable +private fun MacVendorLine(entry: MacVendorRow, showDivider: Boolean) { + val colors = NetKitTheme.colors + val mac = entry.mac + val vendor = entry.vendor ?: stringResource(when { + mac.multicast -> R.string.tools48_mac_no_vendor_multicast + mac.locallyAdministered -> R.string.tools48_mac_no_vendor_local + else -> R.string.tools48_mac_unknown_vendor + }) + LanRow(AnnotatedString(mac.text), AnnotatedString(vendor), Modifier.testTag("mac_row_${mac.text}"), + titleStyle = NetKitType.addressFor(LanRowTitle), showDivider = showDivider) { + Row(horizontalArrangement = Arrangement.spacedBy(Spacing.tiny)) { + if (mac.locallyAdministered) Tag(stringResource(R.string.tools48_mac_flag_local), Tone.INFO) + if (mac.multicast) Tag(stringResource(R.string.tools48_mac_flag_multicast), Tone.WARN) + if (mac.occurrences > 1) Tag(stringResource(R.string.tools48_mac_occurrences, mac.occurrences)) + } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/NetworkInfoCard.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/NetworkInfoCard.kt new file mode 100644 index 0000000..5b0a21c --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/NetworkInfoCard.kt @@ -0,0 +1,64 @@ +package cz.netkit.app.lan + +import androidx.compose.foundation.layout.Box +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import cz.netkit.app.R +import cz.netkit.app.ui.KeyValue +import cz.netkit.app.ui.KeyValueRows +import cz.netkit.app.ui.NeutralButton +import cz.netkit.app.ui.SectionCard +import cz.netkit.shared.lan.LanNetworkInfo +import cz.netkit.shared.lan.LanNetworkInfoField +import cz.netkit.shared.lan.LanNetworkInfoValue +import cz.netkit.shared.lan.lanNetworkInfoRows + +/** + * "Info o síti" (zadání 39 §2.2): the Wi-Fi link as Android reports it (LinkProperties), no + * probe. Collapsed by default so the device list stays first; the IPv4 row is always visible. + */ +@Composable +internal fun NetworkInfoCard(info: LanNetworkInfo, initiallyExpanded: Boolean = false) { + var expanded by rememberSaveable { mutableStateOf(initiallyExpanded) } + val rows = lanNetworkInfoRows(info) + val shown = if (expanded) rows else rows.filter { it.field == LanNetworkInfoField.IPV4 } + val none = stringResource(R.string.lan39_info_none) + val unknown = stringResource(R.string.lan39_info_unknown) + val unavailable = stringResource(R.string.lan39_info_dhcp_unavailable) + val values = shown.map { row -> + val text = when (row.state) { + LanNetworkInfoValue.VALUES -> row.values.joinToString("\n") + LanNetworkInfoValue.NONE -> none + LanNetworkInfoValue.UNKNOWN -> unknown + LanNetworkInfoValue.UNAVAILABLE -> unavailable + } + KeyValue(stringResource(infoLabel(row.field)), text, monospace = row.state == LanNetworkInfoValue.VALUES && row.field != LanNetworkInfoField.DOMAINS) + } + Box(Modifier.testTag("network_info")) { + SectionCard(stringResource(R.string.lan39_info_title), trailing = { + NeutralButton(stringResource(if (expanded) R.string.lan39_info_collapse else R.string.lan39_info_expand), { expanded = !expanded }, + Modifier.testTag("network_info_toggle"), small = true) + }) { + KeyValueRows(values) + } + } +} + +private fun infoLabel(field: LanNetworkInfoField): Int = when (field) { + LanNetworkInfoField.INTERFACE -> R.string.lan39_info_interface + LanNetworkInfoField.IPV4 -> R.string.lan39_info_ipv4 + LanNetworkInfoField.GATEWAY -> R.string.lan39_info_gateway + LanNetworkInfoField.DNS -> R.string.lan39_info_dns + LanNetworkInfoField.DOMAINS -> R.string.lan39_info_domains + LanNetworkInfoField.DHCP -> R.string.lan39_info_dhcp + LanNetworkInfoField.MTU -> R.string.lan39_info_mtu + LanNetworkInfoField.IPV6_GLOBAL -> R.string.lan39_info_ipv6_global + LanNetworkInfoField.IPV6_ULA -> R.string.lan39_info_ipv6_ula + LanNetworkInfoField.IPV6_LINK_LOCAL -> R.string.lan39_info_ipv6_link_local +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/PingOptions.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/PingOptions.kt new file mode 100644 index 0000000..afbfa51 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/PingOptions.kt @@ -0,0 +1,76 @@ +package cz.netkit.app.lan + +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive +import kotlinx.serialization.Serializable +import kotlin.math.roundToLong + +@Serializable +data class PingFields( + val count: String = "", + val seconds: String = "1", + val payload: String = "16", + val df: Boolean = false, +) { + internal fun options(dfSupported: Boolean): PingOptions? { + val countLimit = if (count.isBlank()) null else count.toIntOrNull()?.takeIf { it in 1..1000 } ?: return null + val interval = seconds.replace(',', '.').toDoubleOrNull()?.takeIf { it in 0.2..10.0 } ?: return null + val bytes = payload.toIntOrNull()?.takeIf { it in 0..1472 } ?: return null + return PingOptions(countLimit, (interval * 1000).roundToLong(), bytes, df && dfSupported) + } +} + +internal data class PingOptions(val count: Int?, val intervalMs: Long, val payload: Int, val df: Boolean) +internal suspend fun runPingSeries(options: PingOptions, nowMs: () -> Long, probe: suspend () -> Unit) { + var sent = 0L + while (options.count == null || sent < options.count) { + currentCoroutineContext().ensureActive() + val started = nowMs() + probe() + sent++ + if (sent == options.count?.toLong()) break + delay((options.intervalMs - (nowMs() - started)).coerceAtLeast(0)) + } +} + +internal enum class DfProbe { REPLY, TOO_LARGE, NO_REPLY } +internal enum class SweepLimit { SIZE_OR_MAXIMUM, NO_BASELINE, SOFT_TIMEOUT } +internal data class SweepResult(val bestPayload: Int?, val limit: SweepLimit) + +internal suspend fun findMtuPayload(probe: suspend (Int) -> DfProbe): SweepResult { + suspend fun probeWithRetry(size: Int): DfProbe { + currentCoroutineContext().ensureActive() + val first = probe(size) + if (first != DfProbe.NO_REPLY) return first + currentCoroutineContext().ensureActive() + return probe(size) + } + + var best = 548 + when (probeWithRetry(best)) { + DfProbe.NO_REPLY -> return SweepResult(null, SweepLimit.NO_BASELINE) + DfProbe.TOO_LARGE -> return SweepResult(null, SweepLimit.SIZE_OR_MAXIMUM) + DfProbe.REPLY -> Unit + } + + var high = 1472 + var limit = SweepLimit.SIZE_OR_MAXIMUM + while (best < high) { + val payload = (best + high + 1) / 2 + when (probeWithRetry(payload)) { + DfProbe.REPLY -> best = payload + DfProbe.TOO_LARGE -> { + high = payload - 1 + limit = SweepLimit.SIZE_OR_MAXIMUM + } + DfProbe.NO_REPLY -> { + currentCoroutineContext().ensureActive() + if (probe(best) != DfProbe.REPLY) return SweepResult(null, SweepLimit.NO_BASELINE) + high = payload - 1 + limit = SweepLimit.SOFT_TIMEOUT + } + } + } + return SweepResult(best, limit) +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/ServicesPanel.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/ServicesPanel.kt new file mode 100644 index 0000000..f465f71 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/ServicesPanel.kt @@ -0,0 +1,123 @@ +package cz.netkit.app.lan + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.OutlinedTextFieldDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import cz.netkit.app.R +import cz.netkit.app.ui.KeyValue +import cz.netkit.app.ui.KeyValueRows +import cz.netkit.app.ui.NeutralButton +import cz.netkit.app.ui.SectionCard +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.TonalButton +import cz.netkit.app.ui.Tone +import cz.netkit.app.ui.theme.NetKitShape +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.lan.LanDevice +import cz.netkit.shared.lan.LanRunStatus +import cz.netkit.shared.lan.NtpReferenceKind +import cz.netkit.shared.lan.UdpProbeOutcome +import cz.netkit.shared.lan.UdpServicesResult + +/** + * "Služby (UDP)" in the device detail (zadání 39 §2.4). The SNMP community is a masked field kept + * only in this composition (`remember`, not saveable: it never reaches the saved-state bundle, + * the ViewModel state or storage); empty skips SNMP. + */ +@Composable +internal fun ServicesPanel(state: LanDevicesState, device: LanDevice, viewModel: LanDevicesViewModel) { + val colors = NetKitTheme.colors + var community by remember(device.address) { mutableStateOf("") } + val services = state.services?.takeIf { it.address == device.address } + val running = services?.status == LanRunStatus.RUNNING + Box(Modifier.testTag("device_services")) { + SectionCard(stringResource(R.string.lan39_services_title)) { + Text(stringResource(R.string.lan39_services_hint), style = NetKitType.label, color = colors.muted) + OutlinedTextField(community, { community = it.take(64) }, Modifier.fillMaxWidth().testTag("device_snmp_community"), + enabled = !running, singleLine = true, label = { Text(stringResource(R.string.lan39_snmp_community)) }, + visualTransformation = PasswordVisualTransformation(), shape = NetKitShape.nested, textStyle = NetKitType.value, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, autoCorrectEnabled = false), + colors = OutlinedTextFieldDefaults.colors(focusedTextColor = colors.text, unfocusedTextColor = colors.text, + focusedBorderColor = colors.accent, unfocusedBorderColor = colors.border, focusedLabelColor = colors.accent, + unfocusedLabelColor = colors.muted, cursorColor = colors.accent)) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + if (running) { + Text(stringResource(R.string.lan39_services_running), Modifier.weight(1f), style = NetKitType.label, color = colors.muted) + NeutralButton(stringResource(R.string.lan_cancel), viewModel::cancelServiceProbe, Modifier.testTag("device_services_cancel"), small = true) + } else TonalButton(stringResource(R.string.lan39_services_identify), { viewModel.identifyServices(device.address, community) }, + Modifier.testTag("device_services_identify"), small = true) + } + services?.result?.let { ServiceRows(it, services.dnsAllowed) } + if (services?.status == LanRunStatus.CANCELLED) Text(stringResource(R.string.lan39_services_cancelled), style = NetKitType.label, color = colors.muted) + } + } +} + +@Composable +private fun ServiceRows(result: UdpServicesResult, dnsAllowed: Boolean) { + val rows = buildList { + val snmp = result.snmp + if (snmp.outcome == UdpProbeOutcome.OK) { + add(KeyValue(stringResource(R.string.lan39_snmp_name), snmp.sysName ?: stringResource(R.string.lan39_value_missing))) + add(KeyValue(stringResource(R.string.lan39_snmp_descr), snmp.sysDescr ?: stringResource(R.string.lan39_value_missing))) + } else add(KeyValue(stringResource(R.string.lan39_snmp), outcomeText(snmp.outcome, snmp.errorStatus, skipped = R.string.lan39_snmp_skipped), + tone = outcomeTone(snmp.outcome))) + val ntp = result.ntp + val reply = ntp.reply + add(if (ntp.outcome == UdpProbeOutcome.OK && reply != null) KeyValue(stringResource(R.string.lan39_ntp), ntpText(reply.stratum, reply.referenceKind, reply.reference, reply.leapUnsynchronized), monospace = true) + else KeyValue(stringResource(R.string.lan39_ntp), outcomeText(ntp.outcome, null, skipped = R.string.lan39_value_missing), tone = outcomeTone(ntp.outcome))) + val dns = result.dns + val version = dns.reply + add(when { + dns.outcome == UdpProbeOutcome.OK && version != null -> KeyValue(stringResource(R.string.lan39_dns_version), + version.version ?: stringResource(R.string.lan39_dns_hidden, version.rcode)) + else -> KeyValue(stringResource(R.string.lan39_dns_version), outcomeText(dns.outcome, null, + skipped = if (dnsAllowed) R.string.lan39_value_missing else R.string.lan39_dns_skipped), tone = outcomeTone(dns.outcome)) + }) + } + Column(Modifier.testTag("device_services_result")) { KeyValueRows(rows) } +} + +@Composable +private fun ntpText(stratum: Int, kind: NtpReferenceKind, reference: String?, unsynchronized: Boolean): String { + val ref = when (kind) { + NtpReferenceKind.KISS_CODE -> stringResource(R.string.lan39_ntp_kiss, reference ?: "?") + NtpReferenceKind.SOURCE -> reference ?: stringResource(R.string.lan39_value_missing) + NtpReferenceKind.UPSTREAM_ADDRESS -> reference ?: stringResource(R.string.lan39_value_missing) + NtpReferenceKind.NONE -> stringResource(R.string.lan39_ntp_unsynchronized) + } + val base = stringResource(R.string.lan39_ntp_value, stratum, ref) + return if (unsynchronized && kind != NtpReferenceKind.NONE) base + SEPARATOR + stringResource(R.string.lan39_ntp_unsynchronized) else base +} + +@Composable +private fun outcomeText(outcome: UdpProbeOutcome, errorStatus: Int?, skipped: Int): String = when (outcome) { + UdpProbeOutcome.OK -> stringResource(R.string.lan39_value_missing) + UdpProbeOutcome.ERROR -> errorStatus?.let { stringResource(R.string.lan39_snmp_error, it) } ?: stringResource(R.string.lan39_probe_invalid) + UdpProbeOutcome.NO_REPLY -> stringResource(R.string.lan39_probe_no_reply) + UdpProbeOutcome.CLOSED -> stringResource(R.string.lan39_probe_closed) + UdpProbeOutcome.SKIPPED -> stringResource(skipped) +} + +private fun outcomeTone(outcome: UdpProbeOutcome): Tone = when (outcome) { + UdpProbeOutcome.ERROR -> Tone.WARN + else -> Tone.NEUTRAL +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/SubnetPanel.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/SubnetPanel.kt new file mode 100644 index 0000000..2affb06 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/SubnetPanel.kt @@ -0,0 +1,107 @@ +package cz.netkit.app.lan + +import android.os.Build +import android.widget.Toast +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.lazy.LazyListScope +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.semantics +import cz.netkit.app.R +import cz.netkit.app.ui.KeyValueRow +import cz.netkit.app.ui.NeutralButton +import cz.netkit.app.ui.Panel +import cz.netkit.app.ui.StatusBanner +import cz.netkit.app.ui.StatusKind +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.lan.* + +internal fun LazyListScope.subnetCalculator( + input: String, interpretation: MaskInterpretation, onInput: (String, MaskInterpretation) -> Unit, + splitPrefix: String, onSplit: (String) -> Unit, +) { + val result = calculateSubnet(input, interpretation) + item("subnet_fields") { + Panel { + Field(input, { onInput(it, MaskInterpretation.NETMASK) }, R.string.lan_subnet_input, true, Modifier.testTag("subnet_input"), mono = true) + result?.ambiguousInterpretation?.let { current -> + val isMask = current == MaskInterpretation.NETMASK + NeutralButton(stringResource(if (isMask) R.string.lan_using_mask else R.string.lan_using_wildcard, result.subnet.prefix), { + onInput(input, if (isMask) MaskInterpretation.WILDCARD else MaskInterpretation.NETMASK) + }) + } + if (result == null && input.isNotBlank()) StatusBanner(stringResource(R.string.lan_subnet_invalid), StatusKind.ERROR) + } + } + if (result == null) return + item("subnet_details") { + Panel { + val rangeLabel = when (result.range) { + AddressRange.PRIVATE -> R.string.lan_range_private + AddressRange.CGNAT -> R.string.lan_range_cgnat + AddressRange.LINK_LOCAL -> R.string.lan_range_link_local + AddressRange.LOOPBACK -> R.string.lan_range_loopback + AddressRange.MULTICAST -> R.string.lan_range_multicast + AddressRange.DOCUMENTATION -> R.string.lan_range_documentation + AddressRange.MIXED -> R.string.lan_range_mixed + AddressRange.OTHER -> R.string.lan_range_other + } + Column { + CopyValue(ipv4Text(result.subnet.network), R.string.lan_subnet_network, showDivider = false) + CopyValue(result.mask, R.string.lan_subnet_mask) + CopyValue(result.wildcard, R.string.lan_subnet_wildcard) + CopyValue(result.broadcast ?: stringResource(R.string.lan_subnet_no_broadcast), + R.string.lan_subnet_broadcast, monospace = result.broadcast != null) + CopyValue(result.firstHost, R.string.lan_subnet_first) + CopyValue(result.lastHost, R.string.lan_subnet_last) + CopyValue(result.subnet.hostCount.toString(), R.string.lan_subnet_hosts, monospace = false) + CopyValue(stringResource(rangeLabel), R.string.lan_subnet_range, monospace = false) + CopyValue(result.addressClass.name, R.string.lan_subnet_class, monospace = false) + } + } + } + val split = splitPrefix.toIntOrNull()?.let(result::split) + item("subnet_split") { + Panel { + Field(splitPrefix, onSplit, R.string.lan_subnet_split, true, number = true) + if (splitPrefix.isNotBlank() && split == null) + StatusBanner(stringResource(R.string.lan_subnet_split_invalid, result.subnet.prefix), StatusKind.ERROR) + } + } + if (split != null) { + items(split.rows, key = { "subnet_$it" }) { CopyValue(it.toString()) } + if (split.remaining > 0) item { + // A /0 split into /32s exceeds Int.MAX_VALUE. Keep the full count for display. + val quantity = split.remaining.coerceAtMost(Int.MAX_VALUE.toLong()).toInt() + Text(pluralStringResource(R.plurals.lan_subnet_remaining, quantity, split.remaining)) + } + } +} + +@Composable +private fun CopyValue(value: String, label: Int? = null, monospace: Boolean = true, showDivider: Boolean = true) { + val context = LocalContext.current + val action = stringResource(R.string.lan_copy_value) + val onCopy = { + val copied = copy(context, value) + if (!copied || Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + Toast.makeText(context, if (copied) R.string.lan_value_copied else R.string.lan_copy_failed, Toast.LENGTH_SHORT).show() + } + } + Box( + Modifier.fillMaxWidth().combinedClickable(onClickLabel = action, onLongClickLabel = action, + onClick = onCopy, onLongClick = onCopy).semantics(mergeDescendants = true) {}, + ) { + if (label == null) Text(value, style = NetKitType.address) + else KeyValueRow(stringResource(label), value, monospace = monospace, showDivider = showDivider) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/TargetHistory.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/TargetHistory.kt new file mode 100644 index 0000000..19a6bd4 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/TargetHistory.kt @@ -0,0 +1,134 @@ +package cz.netkit.app.lan + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.widthIn +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import cz.netkit.app.BuildConfig +import cz.netkit.app.R +import cz.netkit.app.ui.Eyebrow +import cz.netkit.app.ui.NetKitIcons +import cz.netkit.app.ui.NeutralButton +import cz.netkit.app.ui.PrimaryButton +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.theme.NetKitShape +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.lan.TARGET_LABEL_LIMIT +import cz.netkit.shared.lan.TargetField +import cz.netkit.shared.lan.ToolTargets +import cz.netkit.shared.lan.targetFits + +/** + * Zadání 48: a tool's target field with the shared history and favourites behind the clock icon. + * The menu offers only entries the tool accepts; starring asks for an optional label. + */ +@OptIn(ExperimentalComposeUiApi::class) +@Composable +internal fun TargetInput(value: String, onChange: (String) -> Unit, label: Int, enabled: Boolean, field: TargetField, + targets: ToolTargets, viewModel: LanViewModel, modifier: Modifier = Modifier) { + val colors = NetKitTheme.colors + var open by remember { mutableStateOf(false) } + var starring by rememberSaveable { mutableStateOf(null) } + val suggestions = remember(targets, field) { targets.suggestions(field) } + val current = value.trim() + val canStar = remember(current, field) { targetFits(field, current) } + val starred = remember(targets, current) { targets.isFavorite(current) } + Field(value, onChange, label, enabled, modifier, mono = true, trailing = { + Box { + IconButton(onClick = { open = true }, enabled = enabled, modifier = Modifier.testTag("target_history")) { + Icon(NetKitIcons.History, stringResource(R.string.tools48_history_open), tint = colors.muted) + } + DropdownMenu(expanded = open, onDismissRequest = { open = false }, containerColor = colors.surface2, + modifier = Modifier.widthIn(max = 360.dp).semantics { testTagsAsResourceId = BuildConfig.DEBUG }) { + if (canStar) DropdownMenuItem( + text = { Text(stringResource(if (starred) R.string.tools48_unstar else R.string.tools48_star), style = NetKitType.body) }, + leadingIcon = { Icon(if (starred) NetKitIcons.StarFilled else NetKitIcons.Star, null, tint = colors.accent) }, + modifier = Modifier.testTag("target_star"), + onClick = { open = false; if (starred) viewModel.unstarTarget(current) else starring = current }) + val favorites = suggestions.filter { it.favorite } + val recent = suggestions.filterNot { it.favorite } + if (suggestions.isEmpty()) DropdownMenuItem(text = { Text(stringResource(R.string.tools48_history_empty), style = NetKitType.body, + color = colors.muted) }, enabled = false, onClick = {}) + if (favorites.isNotEmpty()) Eyebrow(stringResource(R.string.tools48_favorites), Modifier.padding(horizontal = Spacing.medium, vertical = Spacing.small)) + favorites.forEach { item -> + DropdownMenuItem( + text = { TargetText(item.label.ifEmpty { item.value }, item.value.takeIf { item.label.isNotEmpty() }) }, + leadingIcon = { Icon(NetKitIcons.StarFilled, null, tint = colors.accent) }, + trailingIcon = { + IconButton(onClick = { viewModel.unstarTarget(item.value) }) { + Icon(NetKitIcons.Close, stringResource(R.string.tools48_unstar_item, item.label.ifEmpty { item.value }), tint = colors.muted) + } + }, + modifier = Modifier.testTag("target_item_${item.value}"), + onClick = { open = false; onChange(item.value) }) + } + if (recent.isNotEmpty()) Eyebrow(stringResource(R.string.tools48_recent), Modifier.padding(horizontal = Spacing.medium, vertical = Spacing.small)) + recent.forEach { item -> + DropdownMenuItem(text = { TargetText(item.value, null) }, + leadingIcon = { Icon(NetKitIcons.History, null, tint = colors.muted) }, + modifier = Modifier.testTag("target_item_${item.value}"), + onClick = { open = false; onChange(item.value) }) + } + HorizontalDivider(color = colors.divider) + DropdownMenuItem(text = { Text(stringResource(R.string.tools48_clear_history), style = NetKitType.body) }, + enabled = targets.recent.isNotEmpty(), modifier = Modifier.testTag("target_clear_history"), + onClick = { open = false; viewModel.clearTargetHistory() }) + } + } + }) + starring?.let { target -> FavoriteDialog(target, { starring = null }) { name -> starring = null; viewModel.starTarget(target, name) } } +} + +@Composable +private fun TargetText(title: String, subtitle: String?) { + val colors = NetKitTheme.colors + Column { + Text(title, style = if (subtitle == null) NetKitType.addressFor(NetKitType.body) else NetKitType.body, color = colors.text, + maxLines = 1, overflow = TextOverflow.Ellipsis) + subtitle?.let { Text(it, style = NetKitType.addressFor(NetKitType.label), color = colors.muted, maxLines = 1, overflow = TextOverflow.Ellipsis) } + } +} + +@OptIn(ExperimentalComposeUiApi::class) +@Composable +private fun FavoriteDialog(target: String, onDismiss: () -> Unit, onSave: (String) -> Unit) { + val colors = NetKitTheme.colors + var name by rememberSaveable { mutableStateOf("") } + AlertDialog(onDismissRequest = onDismiss, containerColor = colors.surface, shape = NetKitShape.card, + titleContentColor = colors.text, textContentColor = colors.text, + modifier = Modifier.semantics { testTagsAsResourceId = BuildConfig.DEBUG }, + title = { Text(stringResource(R.string.tools48_star_title), style = NetKitType.panelTitle) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { + Text(target, style = NetKitType.addressFor(NetKitType.value), color = colors.text, maxLines = 3, overflow = TextOverflow.Ellipsis) + Field(name, { name = it.take(TARGET_LABEL_LIMIT) }, R.string.tools48_star_label, true, Modifier.testTag("target_favorite_label")) + Text(stringResource(R.string.tools48_local_only), style = NetKitType.label, color = colors.muted) + } + }, + confirmButton = { PrimaryButton(stringResource(R.string.tools48_star_save), { onSave(name) }, Modifier.testTag("target_favorite_save"), small = true) }, + dismissButton = { NeutralButton(stringResource(R.string.lan_cancel), onDismiss, small = true) }, + ) +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/TracePath.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/TracePath.kt new file mode 100644 index 0000000..5d3f5de --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/TracePath.kt @@ -0,0 +1,28 @@ +package cz.netkit.app.lan + +import cz.netkit.shared.lan.PingReply +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive + +/** One cancellable sequence. The caller captures its confirmed route and target once. */ +internal suspend fun tracePath( + target: String, + localAddress: String?, + probe: suspend (Int) -> PingReply, + record: suspend (Int, String, PingReply) -> Unit, + awaitContinue: suspend () -> Unit, +): Boolean { + var knownHop = false + for (ttl in 1..30) { + currentCoroutineContext().ensureActive() + val reply = probe(ttl) + currentCoroutineContext().ensureActive() + val reached = reply.milliseconds != null + val address = if (reached) target else reply.hop?.takeUnless { it == localAddress }.orEmpty() + if (address.isNotEmpty()) knownHop = true + record(ttl, address, reply) + if (reached) return true + if (ttl == 5 && !knownHop) awaitContinue() + } + return false +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/UdpServiceProbe.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/UdpServiceProbe.kt new file mode 100644 index 0000000..418f339 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/UdpServiceProbe.kt @@ -0,0 +1,91 @@ +package cz.netkit.app.lan + +import cz.netkit.shared.lan.UdpExchange +import cz.netkit.shared.lan.UdpReply +import cz.netkit.shared.lan.UdpServicePorts +import cz.netkit.shared.lan.UdpServicesResult +import cz.netkit.shared.lan.probeUdpServices +import java.net.DatagramPacket +import java.net.DatagramSocket +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.PortUnreachableException +import java.net.SocketAddress +import java.net.SocketTimeoutException +import java.security.SecureRandom +import kotlin.coroutines.EmptyCoroutineContext +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.suspendCancellableCoroutine + +/** Largest datagram read; the parsers apply their own, smaller limits (SNMP 4096, NTP 1024, DNS 9000). */ +private const val UDP_RECEIVE_BYTES = 9_001 + +/** + * One connected UDP socket per attempt to the fixed [target] (zadání 39 §2.4). [bind] attaches + * it to the Wi-Fi network before connect; [check] runs before sending (Wi-Fi still the same). + * A connected socket only receives from the target and reports ICMP port unreachable as + * [PortUnreachableException]. The blocking work runs on an IO thread; cancellation closes the + * socket at once (revize 39/1), which wakes a blocked `receive` instead of waiting for its timeout. + */ +internal class DatagramUdpExchange( + private val target: InetAddress, + private val bind: (DatagramSocket) -> Unit = {}, + private val check: () -> Unit = {}, + private val now: () -> Long = System::nanoTime, +) : UdpExchange { + override suspend fun exchange(port: Int, payload: ByteArray, timeoutMs: Long, accept: (ByteArray, Int) -> Boolean): UdpReply { + require(port in 1..65535 && timeoutMs in 1..5_000) + return suspendCancellableCoroutine { cont -> + val socket = DatagramSocket(null as SocketAddress?) + cont.invokeOnCancellation { socket.close() } + Dispatchers.IO.dispatch(EmptyCoroutineContext) { + val result = try { + if (!cont.isActive) throw CancellationException() + Result.success(run(socket, port, payload, timeoutMs, accept)) + } catch (error: Throwable) { Result.failure(error) + } finally { socket.close() } + // After cancellation the closed socket's SocketException is not a result; resume is then ignored. + if (cont.isActive) cont.resumeWith(result) + } + } + } + + private fun run(socket: DatagramSocket, port: Int, payload: ByteArray, timeoutMs: Long, accept: (ByteArray, Int) -> Boolean): UdpReply { + try { + bind(socket) + if (!socket.isBound) socket.bind(null) + socket.connect(InetSocketAddress(target, port)) + check() + socket.send(DatagramPacket(payload, payload.size)) + val deadline = now() + timeoutMs * 1_000_000L + val buffer = ByteArray(UDP_RECEIVE_BYTES) + while (true) { + val remainingMs = (deadline - now()) / 1_000_000L + if (remainingMs <= 0) return UdpReply.Timeout + socket.soTimeout = remainingMs.toInt().coerceAtLeast(1) + val packet = DatagramPacket(buffer, buffer.size) + try { socket.receive(packet) } catch (_: SocketTimeoutException) { return UdpReply.Timeout } + val length = packet.length + if (length >= UDP_RECEIVE_BYTES) continue // possibly truncated: never parse a partial datagram + val bytes = buffer.copyOf(length) + if (accept(bytes, length)) return UdpReply.Data(bytes) + } + } catch (_: PortUnreachableException) { + return UdpReply.Refused + } + } +} + +/** Android side of "Identifikovat služby": sockets bound to [wifi], target already checked by the caller. */ +internal object UdpServiceProbe { + private val random = SecureRandom() + + suspend fun identify(backend: LanBackend, wifi: LanWifi, address: String, community: ByteArray?, dnsAllowed: Boolean, + ports: UdpServicePorts = UdpServicePorts()): UdpServicesResult { + backend.checkWifi(wifi) + val exchange = DatagramUdpExchange(toolInetAddress(address, wifi.interfaceName), bind = { wifi.network.bindSocket(it) }, + check = { backend.checkWifi(wifi) }) + return probeUdpServices(exchange, community, dnsAllowed, { size -> ByteArray(size).also(random::nextBytes) }, ports) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/WebDiagnostic.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/WebDiagnostic.kt new file mode 100644 index 0000000..5f6e66f --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/WebDiagnostic.kt @@ -0,0 +1,369 @@ +package cz.netkit.app.lan + +import cz.netkit.app.BuildConfig +import cz.netkit.shared.lan.ipv4Number +import cz.netkit.shared.publicip.isPublicDiagnosticAddress +import cz.netkit.shared.lan.sanitizeLanText +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.InterruptedIOException +import java.io.InputStream +import java.net.ConnectException +import java.net.UnknownHostException +import java.net.URISyntaxException +import java.net.URI +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.Proxy +import java.security.MessageDigest +import java.security.cert.CertificateException +import java.security.cert.CertificateExpiredException +import java.security.cert.CertificateNotYetValidException +import java.security.cert.CertPathValidatorException +import java.security.cert.X509Certificate +import java.util.concurrent.TimeUnit +import javax.net.ssl.SSLHandshakeException +import javax.net.ssl.SSLPeerUnverifiedException +import javax.net.ssl.SSLException +import okhttp3.* +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import kotlinx.coroutines.* + +internal val diagnosticUserAgent = "NetKit/${BuildConfig.VERSION_NAME}" + +internal data class WebTimings(var dns: Long? = null, var tcp: Long? = null, var tls: Long? = null, var ttfb: Long? = null) + +private fun now() = System.nanoTime() +private fun elapsed(start: Long) = (now() - start) / 1_000_000 + +/** Separate listener per exchange. TLS is excluded from TCP; absent phases stay absent. */ +private class WebEvents(val times: WebTimings) : EventListener() { + lateinit var peer: InetAddress + private set + override fun connectionAcquired(call: Call, connection: Connection) { + peer = connection.route().socketAddress.address + } + private var startTcp = 0L + private var startTls = 0L + private var sent = 0L + override fun connectStart(call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy) { startTcp = now() } + override fun secureConnectStart(call: Call) { times.tcp = elapsed(startTcp); startTls = now() } + override fun secureConnectEnd(call: Call, handshake: Handshake?) { times.tls = elapsed(startTls) } + override fun connectEnd(call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy, protocol: Protocol?) { + if (times.tcp == null) times.tcp = elapsed(startTcp) + } + override fun requestHeadersEnd(call: Call, request: Request) { sent = now() } + override fun responseHeadersStart(call: Call) { times.ttfb = elapsed(sent) } +} + +internal data class WebCertificate(val subject: String, val issuer: String, val from: String, val until: String, + val san: String, val fingerprint: String) +internal data class WebTls(val version: String, val cipher: String, val certificates: List) +internal data class WebHop(val url: HttpUrl, val method: String, val status: Int, val times: WebTimings, + val server: String?, val hsts: String?, val location: String?, val tls: WebTls?, val peer: InetAddress, + val fromPreviousRun: Boolean = false) +internal enum class WebError { URL, REDIRECT_LIMIT, REDIRECT_PORT, LOCAL_REDIRECT, ROUTE_CHANGED, TLS_NAME, TLS_TRUST, TLS_VALIDITY, TLS_HANDSHAKE, TLS, DNS, CONNECT, TIMEOUT, TRANSPORT } +class WebLocalTarget internal constructor( + val url: HttpUrl, val address: InetAddress, internal val prefix: WebNat64Prefix?, + internal val hops: List, internal val redirects: Int, internal val allowGet: Boolean, +) { + internal val route = address.webRoute(prefix) + internal val redirectFromHost get() = hops.lastOrNull()?.url?.host +} + +internal data class WebReport(val hops: List, val error: WebError? = null, val failedUrl: HttpUrl? = null, + val reason: String? = null, val confirmation: WebLocalTarget? = null, val skippedGet: HttpUrl? = null) { + val prefillUrl: HttpUrl? get() = skippedGet ?: failedUrl?.takeIf { error == WebError.LOCAL_REDIRECT || error == WebError.REDIRECT_PORT } +} + +private fun certificate(cert: X509Certificate) = WebCertificate( + sanitizeLanText(cert.subjectX500Principal.name, 1024), sanitizeLanText(cert.issuerX500Principal.name, 1024), + cert.notBefore.toInstant().toString(), cert.notAfter.toInstant().toString(), + cert.subjectAlternativeNames.orEmpty().mapNotNull { entry -> + val type = entry.firstOrNull() as? Int ?: return@mapNotNull null + val value = when (val raw = entry.getOrNull(1)) { + is String -> sanitizeLanText(raw) + is ByteArray -> raw.joinToString("") { "%02X".format(it) } + else -> return@mapNotNull null + } + val label = listOf("otherName", "email", "DNS", "x400Address", "directoryName", "ediPartyName", + "URI", "IP", "registeredID").getOrNull(type) ?: type.toString() + "$label=$value" + }.joinToString(", "), + MessageDigest.getInstance("SHA-256").digest(cert.encoded).joinToString(":") { "%02X".format(it) }, +) + +internal fun diagnosticUrl(input: String): HttpUrl? { + if (input.length > 8192 || input.any { it.code < 32 }) return null + return input.trim().toHttpUrlOrNull()?.takeIf { it.username.isEmpty() && it.password.isEmpty() } + ?.newBuilder()?.fragment(null)?.build() +} + +internal fun diagnosticClient() = OkHttpClient.Builder() + .proxy(Proxy.NO_PROXY) + .connectTimeout(5, TimeUnit.SECONDS) + .readTimeout(5, TimeUnit.SECONDS) + .callTimeout(10, TimeUnit.SECONDS) + .connectionPool(ConnectionPool(0, 1, TimeUnit.SECONDS)) + .fastFallback(false) + .retryOnConnectionFailure(false) + .followRedirects(false) + .followSslRedirects(false) + .build() + +/** Byte-aligned IPv4 embedding layouts from RFC 6052 section 2.2. */ +internal data class WebNat64Prefix(private val address: InetAddress, private val length: Int) { + private val bytes = address.address + private val size = length / 8 + + init { require(bytes.size == 16 && length in setOf(32, 40, 48, 56, 64, 96)) } + + fun route(ip: ByteArray): WebRoute? { + if (ip.size != 16 || (0 until size).any { ip[it] != bytes[it] }) return null + // At lengths below /96 the reserved octet at offset 8 interrupts the IPv4 bits. + if (ip[8] != 0.toByte()) return WebRoute.NON_PUBLIC + return InetAddress.getByAddress(ByteArray(4) { i -> + val offset = size + i + ip[if (size < 12 && offset >= 8) offset + 1 else offset] + }).nativeWebRoute() + } +} + +private val wellKnownNat64 = WebNat64Prefix(InetAddress.getByName("64:ff9b::"), 96) +internal enum class WebRoute { PUBLIC, FAKE_IP, NON_PUBLIC } + +private fun InetAddress.webRoute(prefix: WebNat64Prefix?): WebRoute = + prefix?.route(address) ?: wellKnownNat64.route(address) ?: nativeWebRoute() + +private fun InetAddress.nativeWebRoute(): WebRoute { + val bytes = address + return when { + bytes.size == 4 && bytes[0] == 198.toByte() && bytes[1].toInt() in 18..19 -> WebRoute.FAKE_IP + isPublicDiagnosticAddress(hostAddress.orEmpty().substringBefore('%')) -> WebRoute.PUBLIC + else -> WebRoute.NON_PUBLIC + } +} + +private class LocalRedirect : IOException() +private class RouteChanged : IOException() +private class ConfirmLocal(val address: InetAddress, val prefix: WebNat64Prefix?) : IOException() + +private fun selectWebAddresses(url: HttpUrl, answers: List, literal: Boolean, previous: WebHop?, + confirmed: WebLocalTarget?, prefix: WebNat64Prefix?): List { + if (answers.isEmpty()) throw UnknownHostException(url.host) + val routes = answers.groupBy { it.webRoute(prefix) } + if (confirmed != null) { + // Consent covers one URL, one scoped address and the same translation prefix. + if (url != confirmed.url || prefix != confirmed.prefix) throw RouteChanged() + val candidates = routes[confirmed.route] ?: throw RouteChanged() + // Only the first hop can offer a fake-IP from a mixture of fake and other non-public answers. + val mixedFirstHop = previous == null && confirmed.route == WebRoute.FAKE_IP && WebRoute.PUBLIC !in routes + if (routes.size > 1 && !mixedFirstHop) throw RouteChanged() + val pinned = candidates.find { it.hostAddress == confirmed.address.hostAddress } + ?: throw ConfirmLocal(candidates.first(), prefix) + return listOf(pinned) + } + if (previous != null) { + // Pin a LAN/fake peer across same-host retries. hostAddress includes the IPv6 interface scope. + if (url.host == previous.url.host && previous.peer.webRoute(prefix) != WebRoute.PUBLIC) { + answers.find { it.hostAddress == previous.peer.hostAddress }?.let { return listOf(it) } + } + if (!literal && url.host != previous.url.host && routes.keys == setOf(WebRoute.FAKE_IP)) { + throw ConfirmLocal(answers.first(), prefix) + } + if (routes.keys != setOf(WebRoute.PUBLIC)) throw LocalRedirect() + return answers + } + routes[WebRoute.PUBLIC]?.let { return it } + routes[WebRoute.FAKE_IP]?.let { throw ConfirmLocal(it.first(), prefix) } + if (literal) return answers + throw ConfirmLocal(answers.first(), prefix) +} + +private fun HttpUrl.sameOrigin(other: HttpUrl) = scheme == other.scheme && host == other.host && port == other.port + +/** OkHttp can skip DNS for a literal and canonicalize mapped IPv6 to IPv4. Check its source spelling too. */ +private fun unambiguousLiteral(base: HttpUrl, reference: String, target: HttpUrl): Boolean { + val host = target.host + if (':' !in host && !host.all { it in '0'..'9' || it == '.' }) return true + return try { + val rawHost = base.toUri().resolve(URI(reference)).host + if (':' in host) rawHost?.startsWith('[') == true else ipv4Number(host) != null && rawHost == host + } catch (_: URISyntaxException) { false } +} + +private fun webError(error: IOException): WebError { + val causes = generateSequence(error) { it.cause }.take(32).toList() + val path = causes.filterIsInstance().firstOrNull() + return when { + causes.any { it is RouteChanged } -> WebError.ROUTE_CHANGED + causes.any { it is LocalRedirect } -> WebError.LOCAL_REDIRECT + causes.any { it is CertificateExpiredException || it is CertificateNotYetValidException } || + path?.reason == CertPathValidatorException.BasicReason.EXPIRED || + path?.reason == CertPathValidatorException.BasicReason.NOT_YET_VALID -> WebError.TLS_VALIDITY + causes.any { it is SSLPeerUnverifiedException } -> WebError.TLS_NAME + path != null || causes.any { it is CertificateException } -> WebError.TLS_TRUST + causes.any { it is UnknownHostException } -> WebError.DNS + causes.any { it is InterruptedIOException } -> WebError.TIMEOUT + causes.any { it is ConnectException } -> WebError.CONNECT + error is SSLHandshakeException -> WebError.TLS_HANDSHAKE + error is SSLException -> WebError.TLS + else -> WebError.TRANSPORT + } +} + +internal suspend fun inspectWeb(input: String, client: OkHttpClient, confirmed: WebLocalTarget? = null, + nat64Prefix: () -> WebNat64Prefix? = { null }): WebReport { + var initialPrefix = confirmed?.prefix + return inspectWeb(input, confirmed) { url, method, previous, grant -> + val literal = ':' in url.host || ipv4Number(url.host) != null + val times = WebTimings() + val answers = if (literal) listOf(InetAddress.getByName(url.host)) else withContext(Dispatchers.IO) { + val start = now() + client.dns.lookup(url.host).also { times.dns = elapsed(start) } + } + val prefix = nat64Prefix() + if (previous != null && initialPrefix != prefix) throw RouteChanged() + initialPrefix = prefix + val addresses = selectWebAddresses(url, answers, literal, previous, grant, prefix) + if (url.isHttps) { + // Keep the hostname for SNI and certificate verification. OkHttp receives only approved routes. + val pinned = object : Dns { + override fun lookup(hostname: String): List { + if (hostname != url.host) throw UnknownHostException(hostname) + return addresses + } + } + tlsExchange(client.newBuilder().dns(pinned).build(), url, method, times) + } else plainExchange(client, url, method, addresses, times) + } +} + +internal suspend fun inspectWeb(input: String, confirmed: WebLocalTarget? = null, + exchange: suspend (HttpUrl, String, WebHop?, WebLocalTarget?) -> WebHop): WebReport { + val initialUrl = diagnosticUrl(input) ?: return WebReport(emptyList(), WebError.URL) + if (!unambiguousLiteral(initialUrl, input.trim(), initialUrl)) return WebReport(emptyList(), WebError.URL) + var grant = confirmed?.takeIf { (it.hops.firstOrNull()?.url ?: it.url) == initialUrl } + var url = grant?.url ?: initialUrl + val hops = grant?.hops.orEmpty().mapTo(mutableListOf()) { it.copy(fromPreviousRun = true) } + var method = "HEAD" + var redirects = grant?.redirects ?: 0 + var allowGet = grant?.allowGet ?: true + while (true) { + currentCoroutineContext().ensureActive() + val hop = try { + exchange(url, method, hops.lastOrNull(), grant) + } catch (e: ConfirmLocal) { + return WebReport(hops, confirmation = WebLocalTarget(url, e.address, e.prefix, hops, redirects, allowGet)) + } catch (e: IOException) { + currentCoroutineContext().ensureActive() + return WebReport(hops, webError(e), url, e.message?.let { sanitizeLanText(it, 512) }) + } + grant = null + hops += hop + if (method == "HEAD" && hop.status in setOf(405, 501)) { + if (!allowGet) return WebReport(hops, skippedGet = url) + method = "GET" + continue + } + if (hop.status !in setOf(300, 301, 302, 303, 307, 308) || hop.location == null) return WebReport(hops) + if (redirects++ == 5) return WebReport(hops, WebError.REDIRECT_LIMIT) + val next = url.resolve(hop.location)?.let { diagnosticUrl(it.toString()) } ?: return WebReport(hops, WebError.URL) + if (next.port != url.port && next.port != 80 && next.port != 443) return WebReport(hops, WebError.REDIRECT_PORT, next) + if (!unambiguousLiteral(url, hop.location, next)) return WebReport(hops, WebError.LOCAL_REDIRECT, next) + allowGet = allowGet && url.sameOrigin(next) + url = next + method = "HEAD" + } +} + +/** Close the active call/socket from the cancelling coroutine, even while the IO worker is blocked. */ +internal suspend fun diagnosticIo(close: () -> Unit, block: () -> T): T = coroutineScope { + val work = async(Dispatchers.IO) { block() } + try { work.await() } finally { close() } +} + +private suspend fun tlsExchange(client: OkHttpClient, url: HttpUrl, method: String, times: WebTimings): WebHop { + val events = WebEvents(times) + val request = Request.Builder().url(url).method(method, null).header("Accept-Encoding", "identity") + .header("User-Agent", diagnosticUserAgent).build() + val call = client.newBuilder().eventListener(events).build().newCall(request) + return diagnosticIo(call::cancel) { + call.execute().use { response -> + val tls = response.handshake?.let { hs -> + WebTls(hs.tlsVersion.javaName, hs.cipherSuite.javaName, hs.peerCertificates.filterIsInstance().map(::certificate)) + } + // Only metadata is needed. Cancel before close so OkHttp will not drain an unbounded GET body for reuse. + if (method == "GET") call.cancel() + WebHop(url, method, response.code, events.times, response.header("Server"), response.header("Strict-Transport-Security"), + response.header("Location"), tls, events.peer) + } + } +} + +/** + * Android denies cleartext to high-level clients app-wide. The explicit HTTP/1.x probe uses + * only the selected network's resolver/socket factory. Stream through the header terminator, + * without downloading a GET body or relaxing network_security_config. + */ +private suspend fun plainExchange(client: OkHttpClient, url: HttpUrl, method: String, addresses: List, times: WebTimings): WebHop { + val events = WebEvents(times) + val request = Request.Builder().url(url).method(method, null).build() + val call = client.newCall(request) + var failure: IOException? = null + for (address in addresses) { + val socket = client.socketFactory.createSocket() + val endpoint = InetSocketAddress(address, url.port) + var connected = false + try { + return diagnosticIo(socket::close) { + socket.soTimeout = 5000 + events.connectStart(call, endpoint, Proxy.NO_PROXY) + socket.connect(endpoint, 5000) + connected = true + events.connectEnd(call, endpoint, Proxy.NO_PROXY, Protocol.HTTP_1_1) + val path = url.encodedPath + (url.encodedQuery?.let { "?$it" } ?: "") + val literal = if (':' in url.host) "[${url.host}]" else url.host + val host = if (url.port == 80) literal else "$literal:${url.port}" + val wire = "$method $path HTTP/1.1\r\nHost: $host\r\nConnection: close\r\nUser-Agent: $diagnosticUserAgent\r\nAccept-Encoding: identity\r\n\r\n" + socket.getOutputStream().write(wire.toByteArray(Charsets.US_ASCII)) + events.requestHeadersEnd(call, request) + val input = socket.getInputStream().buffered(1024) + readPlainHeaders(input, url, method, events.times, address) { events.responseHeadersStart(call) } + } + } catch (e: IOException) { + currentCoroutineContext().ensureActive() + if (connected) throw e + failure = e + } + } + throw failure ?: IOException("No address") +} + +internal fun readPlainHeaders(input: InputStream, url: HttpUrl, method: String, times: WebTimings, peer: InetAddress, + firstByte: () -> Unit): WebHop { + var remaining = 65536 + var first = true + // A server can precede its final response with informational headers (e.g. 103). + while (true) { + val bytes = ByteArrayOutputStream() + var tail = 0 + while (tail != 0x0d0a0d0a) { + if (remaining-- == 0) throw IOException("HTTP header limit") + val byte = input.read() + if (byte < 0) throw IOException("Incomplete HTTP headers") + if (first) { firstByte(); first = false } + bytes.write(byte) + tail = (tail shl 8) or byte + } + val lines = bytes.toString("ISO-8859-1").split("\r\n") + val status = Regex("""HTTP/1\.[01] ([1-5][0-9]{2})(?: .*)?""").matchEntire(lines.first()) + ?.groupValues?.get(1)?.toInt() ?: throw IOException("Invalid HTTP status") + if (status in 100..199 && status != 101) continue + fun header(name: String) = lines.drop(1).firstOrNull { + ':' in it && it.substringBefore(':').equals(name, true) + }?.substringAfter(':')?.trim() + return WebHop(url, method, status, times, header("Server"), + header("Strict-Transport-Security"), header("Location"), null, peer) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp.kt index 51179dc..d7da0f5 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp.kt @@ -8,6 +8,7 @@ import android.system.StructPollfd import cz.netkit.shared.lan.PingReply import cz.netkit.shared.lan.ipv4Number import cz.netkit.shared.lan.matchesIcmpEchoReply +import java.io.FileDescriptor import java.io.IOException import java.net.InetAddress import java.security.SecureRandom @@ -18,26 +19,95 @@ import kotlinx.coroutines.withContext internal class IcmpUnavailableException(cause: Throwable) : IOException("ICMP_UNAVAILABLE", cause) +internal class DfTooLargeException : IOException("EMSGSIZE") + +// Linux UAPI include/uapi/linux/in.h (https://github.com/torvalds/linux/blob/master/include/uapi/linux/in.h). +private const val IP_MTU_DISCOVER = 10 +private const val IP_PMTUDISC_DONT = 0 +private const val IP_PMTUDISC_DO = 2 +private const val DEFAULT_ECHO_PAYLOAD = 16 + +internal fun configureDf(df: Boolean, payload: Int, setOption: (Int, Int) -> Unit) { + if (df) { + setOption(IP_MTU_DISCOVER, IP_PMTUDISC_DO) + } else if (payload > DEFAULT_ECHO_PAYLOAD) { + // Prefer fragmentation for larger pings, but keep the socket default if the option is unavailable. + try { + setOption(IP_MTU_DISCOVER, IP_PMTUDISC_DONT) + } catch (_: ErrnoException) { + } catch (_: SecurityException) { + } + } +} + +internal enum class IcmpError { TOO_LARGE, NO_REPLY, UNAVAILABLE } + +/** Terminal I/O errors, after read-side readiness and transient errors have been handled. */ +internal class IcmpErrnos(private val messageTooLarge: Int, private val unreachable: Set) { + fun classify(errno: Int, df: Boolean): IcmpError = when (errno) { + messageTooLarge -> if (df) IcmpError.TOO_LARGE else IcmpError.NO_REPLY + in unreachable -> IcmpError.NO_REPLY + else -> IcmpError.UNAVAILABLE + } +} + +private val echoRandom = SecureRandom() +internal fun echoRequest(payload: Int): ByteArray { + require(payload in 0..1472) + return ByteArray(8 + payload).also { + echoRandom.nextBytes(it) + it[0] = 8 + it[1] = 0 + it[2] = 0 + it[3] = 0 + } +} + /** Unprivileged IPv4 echo socket, explicitly bound before connect. Never falls back to another network. */ internal object WifiIcmp { - suspend fun echo(network: Network, address: String, timeoutMs: Int): PingReply = withContext(Dispatchers.IO) { + private val socketErrors = IcmpErrnos(OsConstants.EMSGSIZE, + setOf(OsConstants.ECONNREFUSED, OsConstants.EHOSTUNREACH, OsConstants.ENETUNREACH)) + + private fun failedEcho(error: ErrnoException, df: Boolean): PingReply = when (socketErrors.classify(error.errno, df)) { + IcmpError.TOO_LARGE -> throw DfTooLargeException() + IcmpError.NO_REPLY -> PingReply(null) + IcmpError.UNAVAILABLE -> throw IcmpUnavailableException(error) + } + + private fun socket(): FileDescriptor = Os.socket(OsConstants.AF_INET, + OsConstants.SOCK_DGRAM or OsConstants.SOCK_NONBLOCK or OsConstants.SOCK_CLOEXEC, OsConstants.IPPROTO_ICMP) + + private fun configureDf(fd: FileDescriptor, df: Boolean, payload: Int = DEFAULT_ECHO_PAYLOAD) = configureDf(df, payload) { option, value -> + Os.setsockoptInt(fd, OsConstants.IPPROTO_IP, option, value) + } + + /** Test the real socket option without transmitting any packets. */ + fun supportsDf(): Boolean = try { + val fd = socket() + try { configureDf(fd, true); true } finally { Os.close(fd) } + } catch (_: ErrnoException) { false } catch (_: SecurityException) { false } + + suspend fun echo(network: Network, address: String, timeoutMs: Int, payload: Int = DEFAULT_ECHO_PAYLOAD, df: Boolean = false): PingReply = withContext(Dispatchers.IO) { require(ipv4Number(address) != null && timeoutMs in 100..5000) currentCoroutineContext().ensureActive() - val fd = try { Os.socket(OsConstants.AF_INET, OsConstants.SOCK_DGRAM or OsConstants.SOCK_NONBLOCK or OsConstants.SOCK_CLOEXEC, OsConstants.IPPROTO_ICMP) } + val fd = try { socket() } catch (error: ErrnoException) { throw IcmpUnavailableException(error) } try { try { + configureDf(fd, df, payload) network.bindSocket(fd) Os.connect(fd, InetAddress.getByAddress(address.split('.').map { it.toInt().toByte() }.toByteArray()), 0) } catch (error: Exception) { throw IcmpUnavailableException(error) } - val request = ByteArray(24).also { SecureRandom().nextBytes(it) } - request[0] = 8; request[1] = 0; request[2] = 0; request[3] = 0 + val request = echoRequest(payload) // Kernel ping sockets set the identifier and checksum; sequence + nonce identify our reply. val start = System.nanoTime() val deadline = start + timeoutMs * 1_000_000L try { Os.write(fd, request, 0, request.size) } - catch (error: ErrnoException) { throw IcmpUnavailableException(error) } - val reply = ByteArray(512) + catch (error: ErrnoException) { + return@withContext failedEcho(error, df) + } + // One spare byte distinguishes an oversized datagram from an exact echo. + val reply = ByteArray(request.size + 1) val pollFd = StructPollfd() pollFd.fd = fd pollFd.events = OsConstants.POLLIN.toShort() @@ -64,13 +134,12 @@ internal object WifiIcmp { } val count = Os.read(fd, reply, 0, reply.size) val receivedAt = System.nanoTime() - if (receivedAt <= deadline && matchesIcmpEchoReply(request, reply, count)) { + if (receivedAt <= deadline && matchesIcmpEchoReply(request, reply, count, allowEmptyPayload = payload == 0)) { return@withContext PingReply((receivedAt - start) / 1_000_000.0) } } catch (error: ErrnoException) { if (error.errno != OsConstants.EAGAIN && error.errno != OsConstants.EINTR) { - if (error.errno == OsConstants.ECONNREFUSED || error.errno == OsConstants.EHOSTUNREACH || error.errno == OsConstants.ENETUNREACH) return@withContext PingReply(null) - throw IcmpUnavailableException(error) + return@withContext failedEcho(error, df) } } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp6.kt b/androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp6.kt new file mode 100644 index 0000000..89641ec --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp6.kt @@ -0,0 +1,95 @@ +package cz.netkit.app.lan + +import android.net.Network +import android.system.ErrnoException +import android.system.Os +import android.system.OsConstants +import android.system.StructPollfd +import cz.netkit.shared.lan.ICMPV6_ECHO_REQUEST +import cz.netkit.shared.lan.PingReply +import cz.netkit.shared.lan.matchesIcmpv6EchoReply +import java.io.FileDescriptor +import java.io.IOException +import java.net.Inet6Address +import java.security.SecureRandom +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.withContext + +private val echo6Random = SecureRandom() + +internal fun echo6Request(payload: Int): ByteArray { + require(payload in 0..1452) + return ByteArray(8 + payload).also { + echo6Random.nextBytes(it) + it[0] = ICMPV6_ECHO_REQUEST.toByte() + it[1] = 0 + it[2] = 0 + it[3] = 0 + } +} + +/** + * Unprivileged ICMPv6 echo (zadání 39 §2.3): an `IPPROTO_ICMPV6` datagram ("ping") socket, the + * IPv6 twin of [WifiIcmp]. Android exposes the constant since API 21 (OsConstants); the kernel + * sets identifier and checksum and filters by the connected peer. Bound to [network] before + * connect; a link-local target carries its scope in [address]. No DF/MTU options: IPv6 routers + * never fragment, and the payload is capped at 1452 B (1500 − 40 − 8). + */ +internal object WifiIcmp6 { + private val socketErrors = IcmpErrnos(OsConstants.EMSGSIZE, + setOf(OsConstants.ECONNREFUSED, OsConstants.EHOSTUNREACH, OsConstants.ENETUNREACH)) + + private fun failed(error: ErrnoException): PingReply = when (socketErrors.classify(error.errno, df = false)) { + IcmpError.TOO_LARGE, IcmpError.NO_REPLY -> PingReply(null) + IcmpError.UNAVAILABLE -> throw IcmpUnavailableException(error) + } + + private fun socket(): FileDescriptor = Os.socket(OsConstants.AF_INET6, + OsConstants.SOCK_DGRAM or OsConstants.SOCK_NONBLOCK or OsConstants.SOCK_CLOEXEC, OsConstants.IPPROTO_ICMPV6) + + suspend fun echo(network: Network, address: Inet6Address, timeoutMs: Int, payload: Int = 16): PingReply = withContext(Dispatchers.IO) { + require(timeoutMs in 100..5000) + currentCoroutineContext().ensureActive() + val fd = try { socket() } catch (error: ErrnoException) { throw IcmpUnavailableException(error) } + try { + try { + network.bindSocket(fd) + Os.connect(fd, address, 0) + } catch (error: Exception) { throw IcmpUnavailableException(error) } + val request = echo6Request(payload) + val start = System.nanoTime() + val deadline = start + timeoutMs * 1_000_000L + try { Os.write(fd, request, 0, request.size) } catch (error: ErrnoException) { return@withContext failed(error) } + val reply = ByteArray(request.size + 1) + val pollFd = StructPollfd().apply { this.fd = fd; events = OsConstants.POLLIN.toShort() } + val pollFds = arrayOf(pollFd) + while (true) { + currentCoroutineContext().ensureActive() + val remainingNanos = deadline - System.nanoTime() + if (remainingNanos <= 0) break + val waitMs = ((remainingNanos + 999_999L) / 1_000_000L).coerceAtMost(10).toInt() + try { + pollFd.revents = 0 + if (Os.poll(pollFds, waitMs) == 0) continue + currentCoroutineContext().ensureActive() + val events = pollFd.revents.toInt() + if (events and OsConstants.POLLNVAL != 0) throw IcmpUnavailableException(IOException("ICMP6_SOCKET_INVALID")) + if (events and (OsConstants.POLLIN or OsConstants.POLLERR) == 0) { + if (events and OsConstants.POLLHUP != 0) return@withContext PingReply(null) + continue + } + val count = Os.read(fd, reply, 0, reply.size) + val receivedAt = System.nanoTime() + if (receivedAt <= deadline && matchesIcmpv6EchoReply(request, reply, count, allowEmptyPayload = payload == 0)) { + return@withContext PingReply((receivedAt - start) / 1_000_000.0) + } + } catch (error: ErrnoException) { + if (error.errno != OsConstants.EAGAIN && error.errno != OsConstants.EINTR) return@withContext failed(error) + } + } + PingReply(null) + } finally { try { Os.close(fd) } catch (_: ErrnoException) { /* Already invalid. */ } } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/nav/AppShortcuts.kt b/androidApp/src/main/kotlin/cz/netkit/app/nav/AppShortcuts.kt new file mode 100644 index 0000000..4eff854 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/nav/AppShortcuts.kt @@ -0,0 +1,90 @@ +package cz.netkit.app.nav + +import android.content.Context +import android.content.Intent +import androidx.annotation.DrawableRes +import androidx.core.content.pm.ShortcutInfoCompat +import androidx.core.content.pm.ShortcutManagerCompat +import androidx.core.graphics.drawable.IconCompat +import cz.netkit.app.MainActivity +import cz.netkit.app.R +import cz.netkit.shared.nav.APP_TARGET_ACTION +import cz.netkit.shared.nav.AppTarget +import cz.netkit.shared.nav.PinnedShortcut +import cz.netkit.shared.nav.appTargetExtras +import cz.netkit.shared.nav.AppRecordKind +import cz.netkit.shared.nav.parseAppTarget +import cz.netkit.shared.nav.planPinnedShortcutSync +import cz.netkit.shared.nav.shortcutId + +/** + * Intents and pinned shortcuts for external navigation (zadání 36 §2.1–2.3). Every intent is + * explicit (MainActivity of this package) and carries only the whitelisted target extra. + */ +object AppShortcuts { + /** Longest label put on the home screen; launchers ellipsize anything longer anyway. */ + private const val LABEL_MAX = 25 + + fun openIntent(context: Context, target: AppTarget): Intent = + Intent(APP_TARGET_ACTION).setClass(context, MainActivity::class.java).apply { + appTargetExtras(target).forEach { (key, value) -> putExtra(key, value) } + } + + /** The home-screen label: the record name, shortened; never the host, MAC or user name. */ + fun label(name: String): String = name.trim().take(LABEL_MAX).ifEmpty { "NetKit" } + + /** The pin menu item is shown only when the launcher supports it and the record fits the whitelist. */ + fun canPin(context: Context, kind: AppRecordKind, value: String): Boolean = + kind.target(value) != null && ShortcutManagerCompat.isRequestPinShortcutSupported(context) + + /** Asks the launcher to pin; the launcher shows its own confirmation. False if it refused. */ + fun requestPin(context: Context, target: AppTarget, name: String): Boolean { + val info = shortcut(context, target, label(name)) + return try { ShortcutManagerCompat.requestPinShortcut(context, info, null) } + catch (_: IllegalStateException) { false } // app not in foreground or launcher refused + } + + private fun shortcut(context: Context, target: AppTarget, label: String): ShortcutInfoCompat { + @DrawableRes val icon = when (target) { + is AppTarget.SshProfile -> R.drawable.ic_shortcut_ssh + is AppTarget.WolDevice -> R.drawable.ic_shortcut_wol + else -> R.drawable.ic_shortcut_signal + } + return ShortcutInfoCompat.Builder(context, target.shortcutId()) + .setShortLabel(label).setLongLabel(label) + .setIcon(IconCompat.createWithResource(context, icon)) + .setIntent(openIntent(context, target)) + .build() + } + + /** + * Matches pinned shortcuts of one kind to a successfully loaded record list: deleted records + * get their shortcut disabled with [disabledMessage], restored ones enabled, renamed ones relabelled. + * Call only with a complete, successfully read list (never after a load failure). + */ + fun sync(context: Context, kind: AppRecordKind, records: Map, disabledMessage: CharSequence) { + try { + val pinned = ShortcutManagerCompat.getShortcuts(context, ShortcutManagerCompat.FLAG_MATCH_PINNED) + .map { PinnedShortcut(it.id, it.isEnabled, it.shortLabel.toString()) } + val plan = planPinnedShortcutSync(kind, pinned, records.mapValues { (_, name) -> label(name) }) + if (plan.isEmpty) return + if (plan.disable.isNotEmpty()) ShortcutManagerCompat.disableShortcuts(context, plan.disable, disabledMessage) + if (plan.enable.isNotEmpty()) ShortcutManagerCompat.enableShortcuts(context, plan.enable.mapNotNull { id -> + parseAppTarget(id)?.let { shortcut(context, it, label(records.getValue(it.recordId()))) } + }) + if (plan.relabel.isNotEmpty()) ShortcutManagerCompat.updateShortcuts(context, plan.relabel.mapNotNull { (id, label) -> + parseAppTarget(id)?.let { shortcut(context, it, label) } + }) + } catch (_: IllegalStateException) { + // Rate limit or launcher state; the next record change retries. + } catch (_: IllegalArgumentException) { + // A shortcut changed concurrently (e.g. unpinned); the next record change retries. + } + } + + private fun AppTarget.recordId(): String = when (this) { + is AppTarget.SshProfile -> id + is AppTarget.WolDevice -> key + else -> "" + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/net/ActiveNetworkMonitor.kt b/androidApp/src/main/kotlin/cz/netkit/app/net/ActiveNetworkMonitor.kt index 1e38174..49bca31 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/net/ActiveNetworkMonitor.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/net/ActiveNetworkMonitor.kt @@ -4,6 +4,7 @@ import android.net.ConnectivityManager import android.net.LinkProperties import android.net.Network import android.net.NetworkCapabilities +import android.os.Build import cz.netkit.shared.net.NetKind import java.net.Inet4Address import java.net.Inet6Address @@ -18,7 +19,8 @@ import kotlinx.coroutines.flow.distinctUntilChanged * covers the app). [metered] = `NET_CAPABILITY_NOT_METERED` missing (mobile data, hotspot marked * as metered). [localIpv6] is the first non-link-local IPv6 address. [dnsServers] are numeric * addresses; with [privateDnsActive] the queries go to [privateDnsServerName] over TLS instead - * (the name is `null` in opportunistic mode). + * (the name is `null` in opportunistic mode). [mtu] 0 = not set by the network; [dhcpServer] is + * known on API 30+ for a DHCP lease only; [gateway] is the IPv4 default gateway (diagnostic report, zadání 47). */ internal data class ActiveNetworkInfo( val network: Network, @@ -31,6 +33,9 @@ internal data class ActiveNetworkInfo( val privateDnsActive: Boolean, val privateDnsServerName: String?, val viaVpn: Boolean, + val mtu: Int = 0, + val dhcpServer: String? = null, + val gateway: String? = null, ) /** @@ -121,5 +126,9 @@ internal fun activeNetworkInfo(network: Network, capabilities: NetworkCapabiliti privateDnsActive = links.isPrivateDnsActive, privateDnsServerName = links.privateDnsServerName, viaVpn = vpn, + mtu = links.mtu, + gateway = links.routes.firstOrNull { it.isDefaultRoute && it.gateway is Inet4Address && !it.gateway!!.isAnyLocalAddress } + ?.gateway?.hostAddress, + dhcpServer = if (Build.VERSION.SDK_INT >= 30) links.dhcpServerAddress?.hostAddress else null, ) } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusService.kt b/androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusService.kt new file mode 100644 index 0000000..173d8c0 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusService.kt @@ -0,0 +1,209 @@ +package cz.netkit.app.netstatus + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import android.net.ConnectivityManager +import android.net.NetworkCapabilities +import android.net.wifi.WifiInfo +import android.net.wifi.WifiManager +import android.os.Build +import android.os.SystemClock +import androidx.core.content.ContextCompat +import cz.netkit.app.publicip.publicIpLookupEnabled +import cz.netkit.shared.netstatus.NET_STATUS_MAX_BYTES +import cz.netkit.shared.netstatus.NetStatusCodec +import cz.netkit.shared.netstatus.NetStatusCorrupt +import cz.netkit.shared.netstatus.NetStatusData +import cz.netkit.shared.netstatus.NetStatusLabel +import cz.netkit.shared.netstatus.NetStatusPatch +import cz.netkit.shared.netstatus.NetStatusPrivacy +import cz.netkit.shared.netstatus.NetStatusRadioReader +import cz.netkit.shared.netstatus.NetStatusRadioReading +import cz.netkit.shared.netstatus.NetStatusRadioSource +import cz.netkit.shared.netstatus.NetStatusRecorder +import cz.netkit.shared.netstatus.NetStatusRefreshResult +import cz.netkit.shared.netstatus.NetStatusSettings +import cz.netkit.shared.netstatus.NetStatusSpeed +import cz.netkit.shared.netstatus.NetStatusSsidReport +import cz.netkit.shared.netstatus.NetStatusStore +import cz.netkit.shared.netstatus.NetStatusWidth +import cz.netkit.shared.netstatus.NetStatusGateway +import cz.netkit.shared.netstatus.netStatusRadio +import cz.netkit.shared.netstatus.refreshNetStatus +import java.io.File +import java.io.IOException +import java.nio.file.Files +import java.nio.file.StandardCopyOption +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +/** File of the widget snapshot: app-private, outside backups (`noBackupFilesDir`, plus `allowBackup=false`). */ +internal const val NET_STATUS_FILE = "netstatus_widget.json" + +/** + * Snapshot file with an atomic replace (temp file + move), serialized by a mutex. [data] is the last read or + * written state for the widget composition. An unreadable file counts as empty (both options off). + */ +internal class FileNetStatusStore(private val file: File) : NetStatusStore { + private val mutex = Mutex() + private val state = MutableStateFlow(null) + val data: StateFlow = state.asStateFlow() + + override suspend fun read(): NetStatusData = withContext(Dispatchers.IO) { mutex.withLock { readLocked().also { state.value = it } } } + + override suspend fun update(transform: (NetStatusData) -> NetStatusData): NetStatusData = withContext(Dispatchers.IO) { + mutex.withLock { + val before = readLocked() + val next = transform(before) + if (next != before || !file.exists()) writeLocked(next) + state.value = next + next + } + } + + private fun readLocked(): NetStatusData { + if (!file.exists()) return NetStatusData() + return try { + if (file.length() > NET_STATUS_MAX_BYTES) throw NetStatusCorrupt("size") + NetStatusCodec.decode(file.readText(Charsets.UTF_8)) + } catch (_: NetStatusCorrupt) { + NetStatusData() + } catch (_: IOException) { + NetStatusData() + } + } + + private fun writeLocked(data: NetStatusData) { + file.parentFile?.mkdirs() + val temp = File(file.parentFile, file.name + ".tmp") + temp.writeText(NetStatusCodec.encode(data), Charsets.UTF_8) + Files.move(temp.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE) + } +} + +/** What may be kept now: SSID needs fine location (as reading it does), public IP its enabled lookup. Disk read. */ +internal fun netStatusPrivacy(context: Context) = NetStatusPrivacy( + locationGranted = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED, + publicIpLookupEnabled = publicIpLookupEnabled(context), +) + +/** + * The only owner of the network status widget snapshot (zadání 37), one per process in + * `NetKitApplication.netStatus`. Screens offer foreground measurements; the widget reads [data] and + * refreshes the radio values. Nothing here runs periodically or opens a socket. + */ +class NetStatusService internal constructor( + private val context: Context, + scope: CoroutineScope, + private val store: FileNetStatusStore = FileNetStatusStore(File(context.noBackupFilesDir, NET_STATUS_FILE)), + private val reader: NetStatusRadioReader = AndroidNetStatusRadioReader(context, scope), +) { + private val refreshing = AtomicBoolean(false) + private val recorder = NetStatusRecorder( + scope = scope, store = store, + privacy = { withContext(Dispatchers.IO) { netStatusPrivacy(context) } }, + elapsedMs = SystemClock::elapsedRealtime, + nowMs = System::currentTimeMillis, + onChanged = { NetStatusWidgets.redraw(context) }, + ) + + /** Last known snapshot (`null` before the first read). */ + val data: StateFlow get() = store.data + + suspend fun load(): NetStatusData = store.read() + + /** Přehled, 1 Hz: link values and optional SSID (written at most every 30 s). */ + fun offerLink(atMs: Long, frequencyMhz: Int?, rssiDbm: Int?, rxLinkMbps: Int?, txLinkMbps: Int?, ssid: String?) = + recorder.offer(NetStatusPatch( + radio = netStatusRadio(atMs, frequencyMhz, rssiDbm, rxLinkMbps, txLinkMbps, NetStatusRadioSource.FOREGROUND), + ssid = NetStatusSsidReport(atMs, ssid), + )) + + /** Přehled without a Wi-Fi network: the widget says "Bez Wi-Fi" from now on. */ + fun offerNoWifi(atMs: Long) = recorder.offer(NetStatusPatch( + radio = cz.netkit.shared.netstatus.NetStatusRadio(atMs, wifi = false), ssid = NetStatusSsidReport(atMs, null))) + + fun offerGateway(atMs: Long, latencyMs: Double) = recorder.offer(NetStatusPatch(gateway = NetStatusGateway(atMs, latencyMs))) + + /** A finished speed test; its Wi-Fi context (if it ran on Wi-Fi) is a radio reading of the same time. */ + fun offerSpeed(atMs: Long, downloadMbps: Double?, uploadMbps: Double?, pingMs: Double?, + wifi: NetStatusRadioReading?, ssid: String?) = recorder.offer(NetStatusPatch( + speed = NetStatusSpeed(atMs, downloadMbps, uploadMbps, pingMs), + radio = wifi?.let { netStatusRadio(atMs, it.frequencyMhz, it.rssiDbm, it.rxLinkMbps, it.txLinkMbps, NetStatusRadioSource.FOREGROUND) }, + ssid = wifi?.let { NetStatusSsidReport(atMs, ssid) }, + )) + + /** Wi-Fi analyzer: channel width of the connected AP on [frequencyMhz]. */ + fun offerWidth(atMs: Long, frequencyMhz: Int, widthMhz: Int) = recorder.offer(NetStatusPatch(width = NetStatusWidth(atMs, frequencyMhz, widthMhz))) + + /** Public IP shown in Přehled (only while its lookup is enabled; the widget never looks it up). */ + fun offerPublicIp(atMs: Long, address: String) = recorder.offer(NetStatusPatch(publicIp = NetStatusLabel(atMs, address))) + + /** The lookup was switched off in Přehled: the stored copy goes at once. */ + suspend fun clearPublicIp() { recorder.update { it.copy(publicIp = null) } } + + suspend fun setSettings(settings: NetStatusSettings): NetStatusData = recorder.update { it.copy(settings = settings) } + + /** App start and every widget update: removes SSID / public IP no longer allowed. */ + suspend fun enforcePrivacy(): NetStatusData = recorder.enforcePrivacy() + + /** Instrumentation evidence only (zadání 37 AC-002/003): replaces the snapshot; the privacy rules still apply. */ + @androidx.annotation.VisibleForTesting + internal suspend fun replaceForEvidence(data: NetStatusData): NetStatusData = recorder.update { data } + + /** The widget's refresh tap; a second tap while one runs is ignored. */ + suspend fun refresh(): NetStatusRefreshResult? { + if (!refreshing.compareAndSet(false, true)) return null + return try { refreshNetStatus(reader, recorder, System::currentTimeMillis) } finally { refreshing.set(false) } + } +} + +/** + * Radio values for the refresh tap without location and without traffic (zadání 37 §2.2). + * + * - API 31+: a one-shot `ConnectivityManager.getNetworkCapabilities` — no `NetworkCallback`, so no + * `FLAG_INCLUDE_LOCATION_INFO`. The platform redacts SSID/BSSID without any location check; RSSI, + * frequency and link rates stay. They are as fresh as the last capabilities update of the Wi-Fi stack. + * - API 29–30: `NetworkCapabilities` carry no `WifiInfo`; the legacy `WifiManager.connectionInfo` is the + * only source. Only radio values are taken from it (the system may still run its location check there). + * + * Binder calls are blocking, so they run in [scope] and the caller only awaits (cancellable deadline). + */ +internal class AndroidNetStatusRadioReader(context: Context, private val scope: CoroutineScope) : NetStatusRadioReader { + private val connectivity = context.getSystemService(ConnectivityManager::class.java) + private val wifi = context.applicationContext.getSystemService(WifiManager::class.java) + + override suspend fun read(): NetStatusRadioReading? = scope.async(Dispatchers.IO) { readBlocking() }.await() + + private fun readBlocking(): NetStatusRadioReading? { + val info = if (Build.VERSION.SDK_INT >= 31) redactedWifiInfo() else legacyWifiInfo() + return info?.let { NetStatusRadioReading(it.frequency, it.rssi, it.rxLinkSpeedMbps, it.txLinkSpeedMbps) } + } + + private fun redactedWifiInfo(): WifiInfo? { + @Suppress("DEPRECATION") // the only list of all networks; the Wi-Fi one may sit under a VPN + val networks = connectivity.allNetworks + return networks.firstNotNullOfOrNull { network -> + connectivity.getNetworkCapabilities(network) + ?.takeIf { it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && !it.hasTransport(NetworkCapabilities.TRANSPORT_VPN) } + ?.transportInfo as? WifiInfo + } + } + + @Suppress("DEPRECATION") // API 29–30 only, see the class comment + private fun legacyWifiInfo(): WifiInfo? { + val connected = connectivity.allNetworks.any { network -> + connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true + } + return if (connected) wifi.connectionInfo?.takeIf { it.networkId != -1 || it.rssi > -127 } else null + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidget.kt b/androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidget.kt new file mode 100644 index 0000000..0e3d8b4 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidget.kt @@ -0,0 +1,311 @@ +package cz.netkit.app.netstatus + +import android.appwidget.AppWidgetManager +import android.appwidget.AppWidgetProviderInfo +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.icu.text.DateFormat +import android.os.Bundle +import android.os.SystemClock +import android.widget.RemoteViews +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.core.net.toUri +import androidx.glance.ColorFilter +import androidx.glance.GlanceId +import androidx.glance.GlanceModifier +import androidx.glance.GlanceTheme +import androidx.glance.Image +import androidx.glance.ImageProvider +import androidx.glance.LocalContext +import androidx.glance.LocalSize +import androidx.glance.action.Action +import androidx.glance.action.clickable +import androidx.glance.appwidget.AndroidRemoteViews +import androidx.glance.appwidget.GlanceAppWidget +import androidx.glance.appwidget.GlanceAppWidgetManager +import androidx.glance.appwidget.GlanceAppWidgetReceiver +import androidx.glance.appwidget.LocalAppWidgetOptions +import androidx.glance.appwidget.SizeMode +import androidx.glance.appwidget.action.actionSendBroadcast +import androidx.glance.appwidget.action.actionStartActivity +import androidx.glance.appwidget.appWidgetBackground +import androidx.glance.appwidget.cornerRadius +import androidx.glance.appwidget.provideContent +import androidx.glance.appwidget.updateAll +import androidx.glance.background +import androidx.glance.layout.Alignment +import androidx.glance.layout.Column +import androidx.glance.layout.Row +import androidx.glance.layout.Spacer +import androidx.glance.layout.fillMaxSize +import androidx.glance.layout.fillMaxWidth +import androidx.glance.layout.padding +import androidx.glance.layout.size +import androidx.glance.material3.ColorProviders +import androidx.glance.text.FontWeight +import androidx.glance.text.Text +import androidx.glance.text.TextStyle +import androidx.glance.unit.ColorProvider +import cz.netkit.app.R +import cz.netkit.app.nav.AppShortcuts +import cz.netkit.app.ui.theme.netKitMaterialColorScheme +import cz.netkit.app.wol.NetKitApplication +import cz.netkit.shared.nav.AppTarget +import cz.netkit.shared.netstatus.NET_STATUS_REFRESH_BUDGET_MS +import cz.netkit.shared.netstatus.NetStatusData +import cz.netkit.shared.netstatus.NetStatusState +import cz.netkit.shared.netstatus.NetStatusView +import cz.netkit.shared.netstatus.NetStatusWidgetSize +import cz.netkit.shared.netstatus.netStatusRefreshData +import cz.netkit.shared.netstatus.netStatusView +import cz.netkit.shared.netstatus.parseNetStatusRefreshData +import cz.netkit.shared.wifi.WifiBand +import java.util.Date +import java.util.Locale +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull + +/* + * Network status widget (zadání 37, Jetpack Glance): the last foreground measurement with an honest age, + * a refresh icon that reads the current radio values without location and without network traffic, + * and a tap on the body that opens Přehled (whitelisted target `signal`). No periodic updates + * (updatePeriodMillis = 0, no WorkManager); it redraws after a snapshot write and after a refresh. + * The signal age is a RemoteViews Chronometer, so it keeps counting on the home screen without any redraw. + */ + +/** Home-screen widget receiver; not exported, the system delivers the AppWidget broadcasts (docs/bezpecnost.md). */ +class NetStatusWidgetReceiver : GlanceAppWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = NetStatusWidget() +} + +/** Smallest drawing per layout; Glance picks the largest that fits the placed widget. */ +internal val NET_STATUS_SMALL = DpSize(100.dp, 40.dp) +internal val NET_STATUS_MEDIUM = DpSize(200.dp, 110.dp) + +internal fun netStatusSize(size: DpSize): NetStatusWidgetSize = + if (size.width >= NET_STATUS_MEDIUM.width && size.height >= NET_STATUS_MEDIUM.height) NetStatusWidgetSize.MEDIUM else NetStatusWidgetSize.SMALL + +/** Host category from the widget options: Android 15+ may host the widget on the lock screen (keyguard). */ +internal fun isLockscreenHost(options: Bundle?): Boolean = + options?.getInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY, -1) == AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD + +class NetStatusWidget : GlanceAppWidget() { + override val sizeMode: SizeMode = SizeMode.Responsive(setOf(NET_STATUS_SMALL, NET_STATUS_MEDIUM)) + + override suspend fun provideGlance(context: Context, id: GlanceId) { + val app = context.applicationContext as NetKitApplication + // Every widget update checks the privacy rules first (option off or location revoked = SSID deleted). + val initial = try { app.netStatus.enforcePrivacy() } catch (e: CancellationException) { throw e } catch (_: Exception) { NetStatusData() } + val appWidgetId = try { GlanceAppWidgetManager(context).getAppWidgetId(id) } catch (_: IllegalArgumentException) { null } + val colors = ColorProviders(light = netKitMaterialColorScheme(false), dark = netKitMaterialColorScheme(true)) + provideContent { + val data by app.netStatus.data.collectAsState() + GlanceTheme(colors = colors) { + val size = netStatusSize(LocalSize.current) + val now = System.currentTimeMillis() + val view = netStatusView(data ?: initial, now, size, lockscreen = isLockscreenHost(LocalAppWidgetOptions.current)) + NetStatusContent(view, now, SystemClock.elapsedRealtime(), appWidgetId) + } + } + } +} + +/** + * One drawing. [nowMs]/[elapsedNowMs] are the wall and monotonic clocks of this drawing (for the live age); + * [appWidgetId] `null` = preview/test without a refresh action. + */ +@Composable +internal fun NetStatusContent(view: NetStatusView, nowMs: Long, elapsedNowMs: Long, appWidgetId: Int?) { + val context = LocalContext.current + val colors = GlanceTheme.colors + val grey = view.state != NetStatusState.FRESH + val open = actionStartActivity(AppShortcuts.openIntent(context, AppTarget.Signal)) + val refresh = appWidgetId?.let { actionSendBroadcast(NetStatusRefreshReceiver.intent(context, it)) } + val box = GlanceModifier.fillMaxSize().appWidgetBackground().background(if (grey) colors.surfaceVariant else colors.surface) + .cornerRadius(16.dp).clickable(open) + val muted = colors.onSurfaceVariant + val strong = if (grey) colors.onSurfaceVariant else colors.onSurface + val text = NetStatusTexts(context) + if (view.size == NetStatusWidgetSize.SMALL) { + Row(box.padding(horizontal = 10.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) { + Column(GlanceModifier.defaultWeight()) { + Text(text.headline(view), style = TextStyle(color = strong, fontSize = 14.sp, fontWeight = FontWeight.Bold), maxLines = 1) + // Narrow 2×1: the channel sits with the age on the second line, so neither gets cut. + Row(verticalAlignment = Alignment.CenterVertically) { + text.smallChannel(view)?.let { Text(it, style = TextStyle(color = muted, fontSize = 11.sp, fontWeight = FontWeight.Medium), maxLines = 1) } + AgeLine(view, text, nowMs, elapsedNowMs, muted, signalPrefix = false) + } + } + refresh?.let { RefreshIcon(it, muted) } + } + return + } + Column(box.padding(horizontal = 12.dp, vertical = 8.dp)) { + Row(GlanceModifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text(text.title(view), GlanceModifier.defaultWeight(), style = TextStyle(color = muted, fontSize = 12.sp, fontWeight = FontWeight.Medium), maxLines = 1) + refresh?.let { RefreshIcon(it, muted) } + } + Text(text.headline(view), style = TextStyle(color = strong, fontSize = 15.sp, fontWeight = FontWeight.Bold), maxLines = 1) + if (view.state == NetStatusState.FRESH) { + text.linkLine(view)?.let { Text(it, style = TextStyle(color = muted, fontSize = 11.sp), maxLines = 1) } + text.speedLine(view)?.let { Text(it, style = TextStyle(color = muted, fontSize = 11.sp), maxLines = 1) } + text.publicIpLine(view)?.let { Text(it, style = TextStyle(color = muted, fontSize = 11.sp), maxLines = 1) } + } + Spacer(GlanceModifier.defaultWeight()) + AgeLine(view, text, nowMs, elapsedNowMs, muted, signalPrefix = true) + } +} + +@Composable +private fun RefreshIcon(action: Action, tint: ColorProvider) { + val context = LocalContext.current + Image(ImageProvider(R.drawable.ic_widget_refresh), context.getString(R.string.netstatus_refresh), + GlanceModifier.size(32.dp).padding(4.dp).clickable(action), colorFilter = ColorFilter.tint(tint)) +} + +/** + * The age line: a live Chronometer counting from the signal time ("před 12:05"); without signal values the + * newest part's absolute time; stale/no data: "Otevři NetKit pro měření" (+ last time). + */ +@Composable +private fun AgeLine(view: NetStatusView, text: NetStatusTexts, nowMs: Long, elapsedNowMs: Long, color: ColorProvider, signalPrefix: Boolean) { + val style = TextStyle(color = color, fontSize = 11.sp) + val radioAt = view.radioAtMs + when { + view.state != NetStatusState.FRESH -> Text(text.staleLine(view), style = style, maxLines = 2) + radioAt != null -> { + val context = LocalContext.current + val format = context.getString(when { + !signalPrefix -> R.string.netstatus_age_format + view.fromRefresh -> R.string.netstatus_refreshed_age_format + else -> R.string.netstatus_signal_age_format + }) + val views = RemoteViews(context.packageName, R.layout.netstatus_age).apply { + setChronometer(R.id.netstatus_age, netStatusChronometerBase(radioAt, nowMs, elapsedNowMs), format, true) + } + AndroidRemoteViews(views) + } + else -> Text(text.measuredAt(view.lastAtMs), style = style, maxLines = 1) + } +} + +/** Chronometer base (elapsedRealtime) such that it shows `now − measured`; never in the future. */ +internal fun netStatusChronometerBase(measuredAtMs: Long, nowMs: Long, elapsedNowMs: Long): Long = + elapsedNowMs - (nowMs - measuredAtMs).coerceAtLeast(0) + +/** Localised widget texts (resources CS/EN; numbers in the current locale). */ +internal class NetStatusTexts(private val context: Context) { + private val locale: Locale = context.resources.configuration.locales[0] + private val stampFormat = DateFormat.getInstanceForSkeleton("dMjm", locale) + + fun title(view: NetStatusView): String = view.ssid?.let { ssid -> + ssid.ownTimeMs?.let { context.getString(R.string.netstatus_with_time, ssid.value, stamp(it)) } ?: ssid.value + } ?: context.getString(R.string.netstatus_title) + + fun headline(view: NetStatusView): String = when { + view.state == NetStatusState.NO_DATA -> context.getString(R.string.netstatus_no_data) + view.state == NetStatusState.STALE -> context.getString(R.string.netstatus_open_app) + view.wifi == false -> context.getString(R.string.netstatus_no_wifi) + view.wifi == null -> context.getString(R.string.netstatus_no_signal) + else -> listOfNotNull( + view.rssiDbm?.let { context.getString(R.string.netstatus_rssi, it) }, + view.channel?.takeIf { view.size == NetStatusWidgetSize.MEDIUM }?.let { context.getString(R.string.netstatus_channel, it) }, + band(view.band).takeIf { view.size == NetStatusWidgetSize.MEDIUM }, + view.widthMhz?.let { context.getString(R.string.netstatus_width, it) }, + ).joinToString(" · ").ifEmpty { context.getString(R.string.netstatus_title) } + } + + /** Small layout, second line before the age: "k. 36 · ". */ + fun smallChannel(view: NetStatusView): String? = view.channel?.takeIf { view.state == NetStatusState.FRESH && view.wifi == true } + ?.let { context.getString(R.string.netstatus_channel_short, it) + " · " } + + private fun band(band: WifiBand): String? = when (band) { + WifiBand.GHZ_2_4 -> context.getString(R.string.netstatus_band_24) + WifiBand.GHZ_5 -> context.getString(R.string.netstatus_band_5) + WifiBand.GHZ_6 -> context.getString(R.string.netstatus_band_6) + WifiBand.UNKNOWN -> null + } + + fun linkLine(view: NetStatusView): String? { + val link = if (view.rxLinkMbps != null || view.txLinkMbps != null) + context.getString(R.string.netstatus_link, view.rxLinkMbps?.toString() ?: "–", view.txLinkMbps?.toString() ?: "–") else null + val gateway = view.gatewayMs?.let { g -> + val value = context.getString(R.string.netstatus_gateway, ms(g.value)) + g.ownTimeMs?.let { context.getString(R.string.netstatus_with_time, value, stamp(it)) } ?: value + } + return listOfNotNull(link, gateway).joinToString(" · ").ifEmpty { null } + } + + fun speedLine(view: NetStatusView): String? = view.speed?.let { s -> + val rates = context.getString(R.string.netstatus_speed, s.downloadMbps?.let(::mbps) ?: "–", s.uploadMbps?.let(::mbps) ?: "–") + val ping = s.pingMs?.let { context.getString(R.string.netstatus_ms, ms(it)) } + listOfNotNull(rates, ping, stamp(s.atMs)).joinToString(" · ") + } + + fun publicIpLine(view: NetStatusView): String? = view.publicIp?.let { ip -> + val value = context.getString(R.string.netstatus_public_ip, ip.value) + ip.ownTimeMs?.let { context.getString(R.string.netstatus_with_time, value, stamp(it)) } ?: value + } + + fun staleLine(view: NetStatusView): String = view.lastAtMs?.let { context.getString(R.string.netstatus_last, stamp(it)) } + ?: context.getString(R.string.netstatus_open_app) + + fun measuredAt(atMs: Long?): String = atMs?.let { context.getString(R.string.netstatus_measured_at, stamp(it)) } ?: "" + + /** Absolute day and time ("1. 12. 14:32"): true without redraws, unlike a relative text. */ + fun stamp(atMs: Long): String = stampFormat.format(Date(atMs)) + + private fun mbps(value: Double) = String.format(locale, if (value >= 100) "%.0f" else "%.1f", value) + private fun ms(value: Double) = String.format(locale, if (value >= 10) "%.0f" else "%.1f", value) +} + +private val refreshScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + +/** + * The refresh icon (zadání 37 §2.2): an explicit broadcast from the widget's own PendingIntent to this + * non-exported receiver; the data URI carries only the app widget ID ([netStatusRefreshData]). Reads the + * radio values without location and without network traffic and redraws, all within + * [NET_STATUS_REFRESH_BUDGET_MS] from entry (receiver limit ~10 s, goAsync). No activity is started. + */ +class NetStatusRefreshReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val started = SystemClock.elapsedRealtime() + val appWidgetId = parseNetStatusRefreshData(intent.dataString) ?: return + // Only a placed widget of this app's status provider. + if (AppWidgetManager.getInstance(context).getAppWidgetInfo(appWidgetId)?.provider != + ComponentName(context, NetStatusWidgetReceiver::class.java)) return + val app = context.applicationContext as NetKitApplication + val pending = goAsync() + refreshScope.launch { + try { + withTimeoutOrNull(NET_STATUS_REFRESH_BUDGET_MS - (SystemClock.elapsedRealtime() - started)) { app.netStatus.refresh() } + } catch (e: CancellationException) { throw e + } catch (_: Exception) { + // Store failure: nothing changed, nothing to report. + } finally { pending.finish() } + } + } + + companion object { + fun intent(context: Context, appWidgetId: Int): Intent = + Intent(context, NetStatusRefreshReceiver::class.java).setData(netStatusRefreshData(appWidgetId).toUri()) + } +} + +/** Redraws every placed status widget (after a snapshot change). */ +object NetStatusWidgets { + suspend fun redraw(context: Context) { + try { NetStatusWidget().updateAll(context) } catch (e: CancellationException) { throw e } catch (_: IllegalStateException) { } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidgetConfigActivity.kt b/androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidgetConfigActivity.kt new file mode 100644 index 0000000..fbaed9a --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidgetConfigActivity.kt @@ -0,0 +1,161 @@ +package cz.netkit.app.netstatus + +import android.Manifest +import android.appwidget.AppWidgetManager +import android.content.ComponentName +import android.content.Intent +import android.content.pm.PackageManager +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.compose.ui.unit.dp +import androidx.core.content.ContextCompat +import androidx.lifecycle.lifecycleScope +import cz.netkit.app.BuildConfig +import cz.netkit.app.R +import cz.netkit.app.publicip.publicIpLookupEnabled +import cz.netkit.app.ssh.netKitSwitchColors +import cz.netkit.app.ui.PrimaryButton +import cz.netkit.app.ui.ScreenHeader +import cz.netkit.app.ui.SectionCard +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.StatusBanner +import cz.netkit.app.ui.StatusKind +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.app.wol.NetKitApplication +import cz.netkit.shared.netstatus.NetStatusSettings +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * Options of the network status widget (zadání 37 §2.4–2.5): SSID and public IP, both off by default. + * Exported only because the launcher starts it through `APPWIDGET_CONFIGURE`; an app widget ID that does + * not belong to [NetStatusWidgetReceiver] closes it at once. Saving an option as off deletes the stored value. + */ +class NetStatusWidgetConfigActivity : ComponentActivity() { + private data class Form(val settings: NetStatusSettings, val locationGranted: Boolean, val lookupEnabled: Boolean) + private val form = mutableStateOf(null) + private val failed = mutableStateOf(false) + private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID + private var saving = false + + @OptIn(ExperimentalComposeUiApi::class) + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // Backing out leaves a new widget unplaced (launcher contract). + setResult(RESULT_CANCELED) + appWidgetId = try { intent?.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) } + catch (_: RuntimeException) { null } ?: AppWidgetManager.INVALID_APPWIDGET_ID + val provider = if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) null + else AppWidgetManager.getInstance(this).getAppWidgetInfo(appWidgetId)?.provider + if (provider != ComponentName(this, NetStatusWidgetReceiver::class.java)) { finish(); return } + enableEdgeToEdge() + val app = application as NetKitApplication + lifecycleScope.launch { + val settings = try { app.netStatus.load().settings } catch (e: CancellationException) { throw e } catch (_: Exception) { NetStatusSettings() } + val lookup = withContext(Dispatchers.IO) { publicIpLookupEnabled(app) } + form.value = Form(settings, hasFineLocation(), lookup) + } + setContent { + NetKitTheme { + Surface(Modifier.fillMaxSize().semantics { testTagsAsResourceId = BuildConfig.DEBUG }, color = NetKitTheme.colors.background) { + Column(Modifier.safeDrawingPadding().verticalScroll(rememberScrollState()).padding(Spacing.normal), + verticalArrangement = Arrangement.spacedBy(Spacing.normal)) { + ScreenHeader(stringResource(R.string.netstatus_config_title), stringResource(R.string.netstatus_config_subtitle)) + when (val current = form.value) { + null -> CircularProgressIndicator(color = NetKitTheme.colors.accent) + else -> Options(current) + } + } + } + } + } + } + + override fun onResume() { + super.onResume() + // The location permission may have changed in the system settings meanwhile. + form.value?.let { form.value = it.copy(locationGranted = hasFineLocation()) } + } + + private fun hasFineLocation() = + ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED + + @Composable + private fun Options(current: Form) { + Text(stringResource(R.string.netstatus_config_info), style = NetKitType.body, color = NetKitTheme.colors.muted) + SectionCard { + OptionRow(stringResource(R.string.netstatus_config_ssid), stringResource(R.string.netstatus_config_ssid_detail), + current.settings.showSsid, "netstatus_config_ssid") { form.value = current.copy(settings = current.settings.copy(showSsid = it)) } + if (current.settings.showSsid && !current.locationGranted) + StatusBanner(stringResource(R.string.netstatus_config_ssid_no_location), StatusKind.WARNING) + OptionRow(stringResource(R.string.netstatus_config_ip), stringResource(R.string.netstatus_config_ip_detail), + current.settings.showPublicIp, "netstatus_config_ip") { form.value = current.copy(settings = current.settings.copy(showPublicIp = it)) } + if (current.settings.showPublicIp && !current.lookupEnabled) + StatusBanner(stringResource(R.string.netstatus_config_ip_lookup_off), StatusKind.WARNING) + } + if (failed.value) StatusBanner(stringResource(R.string.netstatus_config_failed), StatusKind.ERROR) + PrimaryButton(stringResource(R.string.netstatus_config_save), { save(current.settings) }, Modifier.fillMaxWidth().testTag("netstatus_config_save")) + } + + @Composable + private fun OptionRow(title: String, detail: String, checked: Boolean, tag: String, onChange: (Boolean) -> Unit) { + val colors = NetKitTheme.colors + Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).toggleable(value = checked, role = Role.Switch, onValueChange = onChange).testTag(tag), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(title, style = NetKitType.body, color = colors.text) + Text(detail, style = NetKitType.label, color = colors.muted) + } + Switch(checked = checked, onCheckedChange = null, colors = netKitSwitchColors()) + } + } + + private fun save(settings: NetStatusSettings) { + if (saving) return + saving = true + val app = application as NetKitApplication + lifecycleScope.launch { + try { + // An option switched off deletes the stored SSID / public IP in the same write. + app.netStatus.setSettings(settings) + setResult(RESULT_OK, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)) + NetStatusWidgets.redraw(app) + finish() + } catch (e: CancellationException) { throw e + } catch (_: Exception) { + failed.value = true + saving = false + } + } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/overview/CellDetailSection.kt b/androidApp/src/main/kotlin/cz/netkit/app/overview/CellDetailSection.kt new file mode 100644 index 0000000..ade98db --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/overview/CellDetailSection.kt @@ -0,0 +1,253 @@ +package cz.netkit.app.overview + +import android.Manifest +import android.content.Context +import android.content.pm.PackageManager +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.stateDescription +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.LifecycleResumeEffect +import cz.netkit.app.R +import cz.netkit.app.cellular.CellDetailEntry +import cz.netkit.app.cellular.CellDetailStatus +import cz.netkit.app.cellular.CellDetailUiState +import cz.netkit.app.ui.Eyebrow +import cz.netkit.app.ui.KeyValue +import cz.netkit.app.ui.KeyValueRow +import cz.netkit.app.ui.KeyValueRows +import cz.netkit.app.ui.NetKitIcons +import cz.netkit.app.ui.NeutralButton +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.Tag +import cz.netkit.app.ui.TonalButton +import cz.netkit.app.ui.Tone +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.cellular.CellBand +import cz.netkit.shared.cellular.CellDetail +import cz.netkit.shared.cellular.CellTech +import cz.netkit.shared.cellular.CellularSim +import cz.netkit.shared.cellular.NeighborCell +import cz.netkit.shared.cellular.ServingCell +import cz.netkit.shared.cellular.lteEnodeb +import cz.netkit.shared.cellular.lteLocalCellId +import java.text.NumberFormat +import java.util.Locale + +/** + * Everything the mobile cards need for the expandable "Detail buňky" (zadání 53). The permission + * requests reuse the Overview launchers: location as for Wi-Fi, READ_PHONE_STATE as "Zobrazit + * obě SIM" (O-4). [locationBlocked] / [phoneDenied] switch the request button to app settings. + */ +internal class CellDetailHost( + val state: CellDetailUiState, + val onShow: (Int) -> Unit, + val onHide: (Int) -> Unit, + val onRequestLocation: () -> Unit, + val onRequestPhone: () -> Unit, + val onAppSettings: () -> Unit, + val locationBlocked: Boolean, + val phoneDenied: Boolean, +) + +/** + * "Detail buňky ›" under one SIM; expanded it shows serving cells and neighbours. Cell info is + * requested only while the expanded detail is composed and the app is resumed (`show`/`hide`), + * so a collapsed, scrolled-away or backgrounded card costs nothing. + */ +@Composable +internal fun CellDetailToggle(sim: CellularSim, host: CellDetailHost?) { + host ?: return + val colors = NetKitTheme.colors + val id = sim.subscriptionId + var expanded by rememberSaveable(id) { mutableStateOf(false) } + val stateText = stringResource(if (expanded) R.string.cell_detail_expanded else R.string.cell_detail_collapsed) + Row( + Modifier.fillMaxWidth().heightIn(min = 48.dp) + .clickable(role = Role.Button) { expanded = !expanded } + .semantics { stateDescription = stateText } + .testTag("cell_detail_toggle_$id"), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.small), + ) { + Text(stringResource(R.string.cell_detail_title), style = NetKitType.body.copy(fontWeight = FontWeight.SemiBold), + color = colors.accent, modifier = Modifier.weight(1f)) + Icon(NetKitIcons.ChevronRight, null, Modifier.size(18.dp).rotate(if (expanded) 90f else 0f), tint = colors.accent) + } + if (expanded) CellDetailBody(id, host) +} + +@Composable +private fun CellDetailBody(id: Int, host: CellDetailHost) { + val context = LocalContext.current + // Re-read the permissions after every resume (the system dialog pauses the activity). + var epoch by remember { mutableIntStateOf(0) } + LifecycleResumeEffect(Unit) { + epoch++ + onPauseOrDispose { } + } + val location = remember(epoch) { context.granted(Manifest.permission.ACCESS_FINE_LOCATION) } + val phone = remember(epoch) { context.granted(Manifest.permission.READ_PHONE_STATE) } + Column(Modifier.fillMaxWidth().testTag("cell_detail_$id"), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + val entry = host.state.bySim[id] + if (!location || !phone) { + PermissionExplanation(location, phone, host) + } else { + LifecycleResumeEffect(id) { + host.onShow(id) + onPauseOrDispose { host.onHide(id) } + } + DetailContent(entry) + } + } +} + +@Composable +private fun PermissionExplanation(location: Boolean, phone: Boolean, host: CellDetailHost) { + val colors = NetKitTheme.colors + Column(Modifier.fillMaxWidth().testTag("cell_detail_permission"), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(stringResource(R.string.cell_detail_permission_why), style = NetKitType.body, color = colors.muted) + val settings = (!location && host.locationBlocked) || (!phone && host.phoneDenied) + FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + if (!location && !host.locationBlocked) TonalButton(stringResource(R.string.cell_detail_allow_location), host.onRequestLocation, + small = true, modifier = Modifier.testTag("cell_detail_allow_location")) + if (!phone && !host.phoneDenied) TonalButton(stringResource(R.string.cell_detail_allow_phone), host.onRequestPhone, + small = true, modifier = Modifier.testTag("cell_detail_allow_phone")) + if (settings) NeutralButton(stringResource(R.string.cell_detail_app_settings), host.onAppSettings, small = true, + modifier = Modifier.testTag("cell_detail_app_settings")) + } + } +} + +@Composable +private fun DetailContent(entry: CellDetailEntry?) { + val colors = NetKitTheme.colors + val detail = entry?.detail + when { + detail == null -> Text( + stringResource(when (entry?.status) { + CellDetailStatus.FAILED -> R.string.cell_detail_failed + // Revoked between the UI check and the request: the next resume shows the buttons. + CellDetailStatus.NO_PERMISSION -> R.string.cell_detail_permission_why + else -> R.string.cell_detail_loading + }), + style = NetKitType.body, color = colors.muted, modifier = Modifier.testTag("cell_detail_status"), + ) + detail.isEmpty -> Text(stringResource(R.string.cell_detail_empty), style = NetKitType.body, color = colors.muted, + modifier = Modifier.testTag("cell_detail_status")) + else -> DetailCells(detail) + } + Text(stringResource(R.string.cell_detail_local_note), style = NetKitType.label, color = colors.muted) +} + +@Composable +private fun DetailCells(detail: CellDetail) { + val colors = NetKitTheme.colors + detail.otherRat?.let { rat -> + Text(stringResource(R.string.cell_detail_other_rat, stringResource(ratText(rat))), style = NetKitType.body, color = colors.muted) + } + detail.serving.forEachIndexed { index, cell -> ServingCellBlock(cell, index) } + if (detail.neighbors.isNotEmpty()) { + Column(Modifier.fillMaxWidth().testTag("cell_detail_neighbors")) { + Eyebrow(stringResource(R.string.cell_detail_neighbors, detail.neighbors.size), Modifier.padding(top = Spacing.small, bottom = Spacing.tiny)) + detail.neighbors.forEachIndexed { index, cell -> + val dbm = cell.rsrpDbm?.let { stringResource(R.string.cellular_value_dbm, signed(it)) } ?: stringResource(R.string.wifi_signal_no_value) + KeyValueRow(neighborLabel(cell), dbm, showDivider = index > 0) + } + } + } else if (detail.serving.isNotEmpty()) { + Text(stringResource(R.string.cell_detail_no_neighbors), style = NetKitType.label, color = colors.muted) + } +} + +@Composable +private fun ServingCellBlock(cell: ServingCell, index: Int) { + val dash = stringResource(R.string.wifi_signal_no_value) + val locale = LocalConfiguration.current.locales[0] + val db = stringResource(R.string.cellular_unit_db) + Column(Modifier.fillMaxWidth().testTag("cell_detail_serving_$index"), verticalArrangement = Arrangement.spacedBy(Spacing.tiny)) { + val title = listOfNotNull( + stringResource(if (cell.tech == CellTech.LTE) R.string.cellular_rat_lte else R.string.cell_detail_nr), + cell.band?.let { bandLabel(it) }, + cell.downlinkKhz?.let { stringResource(R.string.cell_detail_mhz, formatMhz(it, locale)) }, + ).joinToString(" · ") + Row(Modifier.fillMaxWidth().padding(top = Spacing.small), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(title, style = NetKitType.body.copy(fontWeight = FontWeight.SemiBold), color = NetKitTheme.colors.text, + modifier = Modifier.weight(1f)) + Tag(stringResource(if (cell.primary) R.string.cell_detail_primary else R.string.cell_detail_secondary), + if (cell.primary) Tone.ACCENT else Tone.NEUTRAL) + } + val lte = cell.tech == CellTech.LTE + val cellId = cell.cellId?.let { id -> + if (lte) stringResource(R.string.cell_detail_eci_value, id.toString(), lteEnodeb(id).toString(), lteLocalCellId(id)) else id.toString() + } + KeyValueRows(listOfNotNull( + KeyValue(stringResource(if (lte) R.string.cell_detail_earfcn else R.string.cell_detail_nrarfcn), cell.arfcn?.toString() ?: dash, monospace = cell.arfcn != null), + KeyValue(stringResource(R.string.cell_detail_pci), cell.pci?.toString() ?: dash, monospace = cell.pci != null), + KeyValue(stringResource(if (lte) R.string.cell_detail_eci else R.string.cell_detail_nci), cellId ?: dash, monospace = cellId != null), + KeyValue(stringResource(R.string.cell_detail_tac), cell.tac?.toString() ?: dash, monospace = cell.tac != null), + if (lte) KeyValue(stringResource(R.string.cell_detail_bandwidth), + cell.bandwidthKhz?.let { stringResource(R.string.cell_detail_mhz, formatMhz(it, locale)) } ?: dash) else null, + cell.timingAdvance?.let { KeyValue(stringResource(R.string.cell_detail_ta), it.toString()) }, + KeyValue(stringResource(R.string.cellular_rsrp), cell.rsrpDbm?.let { stringResource(R.string.cellular_value_dbm, signed(it)) } ?: dash), + KeyValue(stringResource(R.string.cellular_rsrq), cell.rsrqDb?.let { "${signed(it)} $db" } ?: dash), + KeyValue(stringResource(R.string.cellular_sinr), cell.sinrDb?.let { "${signed(it)} $db" } ?: dash), + )) + } +} + +@Composable +private fun neighborLabel(cell: NeighborCell): String { + val parts = listOfNotNull( + stringResource(if (cell.tech == CellTech.LTE) R.string.cellular_rat_lte else R.string.cell_detail_nr), + cell.band?.let { bandLabel(it) }, + cell.pci?.let { stringResource(R.string.cell_detail_pci_value, it) }, + cell.arfcn?.let { stringResource(R.string.cell_detail_arfcn_value, it) }, + ) + return parts.joinToString(" · ") +} + +/** "B3", "n78"; a band derived from an ambiguous NR-ARFCN gets "(odhad)". */ +@Composable +internal fun bandLabel(band: CellBand): String { + val name = if (band.tech == CellTech.LTE) "B${band.number}" else "n${band.number}" + return if (band.derived && band.ambiguous) stringResource(R.string.cell_detail_band_estimate, name) else name +} + +/** kHz → MHz with up to 3 decimals in the UI locale ("1815", "3549,99"), no grouping. */ +internal fun formatMhz(khz: Int, locale: Locale): String = + NumberFormat.getNumberInstance(locale).apply { + minimumFractionDigits = 0 + maximumFractionDigits = 3 + isGroupingUsed = false + }.format(khz / 1000.0) + +private fun Context.granted(permission: String): Boolean = checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED diff --git a/androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportDialog.kt b/androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportDialog.kt new file mode 100644 index 0000000..4e6a958 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportDialog.kt @@ -0,0 +1,241 @@ +package cz.netkit.app.overview + +import android.content.Context +import android.net.Uri +import android.widget.Toast +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.compose.ui.unit.dp +import cz.netkit.app.BuildConfig +import cz.netkit.app.R +import cz.netkit.app.ssh.netKitSwitchColors +import cz.netkit.app.ui.NeutralButton +import cz.netkit.app.ui.PrimaryButton +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.StatusBanner +import cz.netkit.app.ui.StatusKind +import cz.netkit.app.ui.TonalButton +import cz.netkit.app.ui.copyPlainText +import cz.netkit.app.ui.shareText +import cz.netkit.app.ui.theme.NetKitShape +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.app.wifi.ExportNotice +import cz.netkit.app.wifi.SmallChip +import cz.netkit.shared.report.DiagnosticReportOptions +import cz.netkit.shared.report.ReportLabel +import cz.netkit.shared.report.ReportLabels +import cz.netkit.shared.report.buildDiagnosticReport +import cz.netkit.shared.report.diagnosticReportJson +import cz.netkit.shared.report.diagnosticReportText +import cz.netkit.shared.report.hasConsentableAddresses + +/** Text or JSON form of the report; Copy and Share use the selected one, Save names the file by it. */ +enum class ReportFormat(val mimeType: String, val extension: String) { TEXT("text/plain", "txt"), JSON("application/json", "json") } + +/** Labels of the text forms from the current (per-app) locale. */ +internal fun reportLabels(context: Context): ReportLabels { + val res = context.resources + val ids = ReportLabel.entries.associateWith { key -> + when (key) { + ReportLabel.TITLE -> R.string.report_label_title + ReportLabel.SPEED_TITLE -> R.string.report_label_speed_title + ReportLabel.TIME -> R.string.report_label_time + ReportLabel.APP_VERSION -> R.string.report_label_app_version + ReportLabel.SECTION_NETWORK -> R.string.report_label_section_network + ReportLabel.NETWORK_TYPE -> R.string.report_label_network_type + ReportLabel.METERED -> R.string.report_label_metered + ReportLabel.INTERFACE -> R.string.report_label_interface + ReportLabel.IPV4 -> R.string.report_label_ipv4 + ReportLabel.IPV6 -> R.string.report_label_ipv6 + ReportLabel.GATEWAY -> R.string.report_label_gateway + ReportLabel.DNS -> R.string.report_label_dns + ReportLabel.PRIVATE_DNS -> R.string.report_label_private_dns + ReportLabel.DHCP_SERVER -> R.string.report_label_dhcp_server + ReportLabel.MTU -> R.string.report_label_mtu + ReportLabel.SECTION_WIFI -> R.string.report_label_section_wifi + ReportLabel.SSID -> R.string.report_label_ssid + ReportLabel.BSSID -> R.string.report_label_bssid + ReportLabel.SIGNAL -> R.string.report_label_signal + ReportLabel.LINK_RATE -> R.string.report_label_link_rate + ReportLabel.CHANNEL -> R.string.report_label_channel + ReportLabel.BAND -> R.string.report_label_band + ReportLabel.WIDTH -> R.string.report_label_width + ReportLabel.STANDARD -> R.string.report_label_standard + ReportLabel.SECTION_LATENCY -> R.string.report_label_section_latency + ReportLabel.LATENCY_GATEWAY -> R.string.report_label_latency_gateway + ReportLabel.LATENCY_INTERNET -> R.string.report_label_latency_internet + ReportLabel.LOSS -> R.string.report_label_loss + ReportLabel.NO_DATA -> R.string.report_label_no_data + ReportLabel.SECTION_PUBLIC_IP -> R.string.report_label_section_public_ip + ReportLabel.PUBLIC_IP -> R.string.report_label_public_ip + ReportLabel.ASN -> R.string.report_label_asn + ReportLabel.PROVIDER -> R.string.report_label_provider + ReportLabel.SECTION_SPEED -> R.string.report_label_section_speed + ReportLabel.SECTION_IPERF3 -> R.string.report_label_section_iperf3 + ReportLabel.SERVER -> R.string.report_label_server + ReportLabel.ENGINE -> R.string.report_label_engine + ReportLabel.DOWNLOAD -> R.string.report_label_download + ReportLabel.UPLOAD -> R.string.report_label_upload + ReportLabel.LATENCY -> R.string.report_label_latency + ReportLabel.JITTER -> R.string.report_label_jitter + ReportLabel.RETRANSMITS -> R.string.report_label_retransmits + ReportLabel.PARTIAL -> R.string.report_label_partial + ReportLabel.YES -> R.string.report_label_yes + ReportLabel.NO -> R.string.report_label_no + ReportLabel.NET_WIFI -> R.string.net_kind_wifi + ReportLabel.NET_CELLULAR -> R.string.net_kind_cellular + ReportLabel.NET_ETHERNET -> R.string.net_kind_ethernet + ReportLabel.NET_VPN -> R.string.net_kind_vpn + ReportLabel.NET_OTHER -> R.string.net_kind_other + } + }.mapValues { (_, id) -> res.getString(id) } + return ReportLabels { ids.getValue(it) } +} + +/** + * The two SAF launchers of the report, registered at the caller's (screen) scope so a recreated + * dialog keeps the result callback. Returns "open the picker for this format", false on failure. + */ +@Composable +internal fun rememberReportSaveLauncher(onResult: (Uri?) -> Unit): (ReportFormat) -> Boolean { + val callback by rememberUpdatedState(onResult) + val text = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument(ReportFormat.TEXT.mimeType)) { callback(it) } + val json = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument(ReportFormat.JSON.mimeType)) { callback(it) } + return { format -> + try { + when (format) { + ReportFormat.TEXT -> text.launch("netkit-report.txt") + ReportFormat.JSON -> json.launch("netkit-report.json") + } + true + } catch (_: Exception) { false } + } +} + +/** + * Zadání 47 §1: the report dialog. SSID, BSSID and the public IP are off by default; the preview + * shows exactly what Copy, Share and Save hand over. The clip is marked sensitive when an + * identifier is included. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun DiagnosticReportDialog( + state: DiagnosticReportUiState, onDismiss: () -> Unit, onSave: (ReportFormat, String) -> Unit, +) { + val colors = NetKitTheme.colors + val context = LocalContext.current + val configuration = LocalConfiguration.current + var includeSsid by rememberSaveable { mutableStateOf(false) } + var includeBssid by rememberSaveable { mutableStateOf(false) } + var includePublicIp by rememberSaveable { mutableStateOf(false) } + var format by rememberSaveable { mutableStateOf(ReportFormat.TEXT) } + val input = state.input + val labels = remember(configuration) { reportLabels(context) } + val options = DiagnosticReportOptions(includeSsid, includeBssid, includePublicIp) + val text = remember(input, options, format, labels) { + input?.let { buildDiagnosticReport(it, options) }?.let { report -> + if (format == ReportFormat.JSON) diagnosticReportJson(report) else diagnosticReportText(report, labels) + } + } + val sensitive = includeSsid || includeBssid || includePublicIp + val shareTitle = stringResource(R.string.report_share_chooser) + val subject = stringResource(R.string.report_title) + AlertDialog( + onDismissRequest = onDismiss, + containerColor = colors.surface, + modifier = Modifier.testTag("report_dialog").semantics { testTagsAsResourceId = BuildConfig.DEBUG }, + title = { Text(stringResource(R.string.report_title), style = NetKitType.panelTitle, color = colors.text) }, + text = { + Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { + StatusBanner(stringResource(R.string.report_identifiers_note), StatusKind.INFO) + val wifi = input?.wifi + ToggleRow(stringResource(R.string.report_include_ssid), includeSsid, enabled = wifi?.ssid != null, "report_include_ssid") { includeSsid = it } + ToggleRow(stringResource(R.string.report_include_bssid), includeBssid, enabled = wifi?.bssid != null, "report_include_bssid") { includeBssid = it } + ToggleRow(stringResource(R.string.report_include_public_ip), includePublicIp, enabled = input?.let(::hasConsentableAddresses) == true, + "report_include_public_ip") { includePublicIp = it } + Row(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + ReportFormat.entries.forEach { entry -> + SmallChip(stringResource(if (entry == ReportFormat.TEXT) R.string.lan_format_text else R.string.lan_format_json), + entry == format, Modifier.testTag("report_format_${entry.extension}")) { format = entry } + } + } + FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + PrimaryButton(stringResource(R.string.report_share), { + if (text != null && !shareText(context, shareTitle, text, subject)) + Toast.makeText(context, R.string.report_share_failed, Toast.LENGTH_SHORT).show() + }, Modifier.testTag("report_share"), enabled = text != null, small = true) + TonalButton(stringResource(R.string.report_copy), { + if (text != null) { + val copied = copyPlainText(context, subject, text, sensitive) + Toast.makeText(context, if (copied) R.string.report_copied else R.string.report_copy_failed, Toast.LENGTH_SHORT).show() + } + }, Modifier.testTag("report_copy"), enabled = text != null, small = true) + NeutralButton(stringResource(R.string.report_save), { if (text != null) onSave(format, text) }, + Modifier.testTag("report_save"), enabled = text != null, small = true) + } + when (state.saveNotice) { + ExportNotice.SAVED -> StatusBanner(stringResource(R.string.report_saved), StatusKind.INFO) + ExportNotice.FAILED -> StatusBanner(stringResource(R.string.report_save_failed), StatusKind.ERROR) + null -> Unit + } + Text(stringResource(R.string.report_preview), style = NetKitType.label, color = colors.muted) + Box(Modifier.fillMaxWidth().heightIn(max = 220.dp).background(colors.surface2, NetKitShape.nested) + .verticalScroll(rememberScrollState()).padding(Spacing.medium).testTag("report_preview")) { + Text(text ?: stringResource(R.string.report_loading), style = NetKitType.addressFor(NetKitType.label), color = colors.text) + } + Text(stringResource(R.string.report_local_note), style = NetKitType.label, color = colors.muted) + } + }, + confirmButton = { + TextButton(onDismiss, Modifier.testTag("report_close")) { Text(stringResource(R.string.report_close), color = colors.accent) } + }, + ) +} + +@Composable +private fun ToggleRow(text: String, checked: Boolean, enabled: Boolean, tag: String, onChange: (Boolean) -> Unit) { + val colors = NetKitTheme.colors + Row( + Modifier.fillMaxWidth().heightIn(min = 48.dp) + .toggleable(value = checked && enabled, enabled = enabled, role = Role.Switch, onValueChange = onChange).testTag(tag), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium), + ) { + Text(text, Modifier.weight(1f), style = NetKitType.body, color = if (enabled) colors.text else colors.dim) + Switch(checked = checked && enabled, onCheckedChange = null, enabled = enabled, colors = netKitSwitchColors()) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportViewModel.kt new file mode 100644 index 0000000..1e6ecf2 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportViewModel.kt @@ -0,0 +1,189 @@ +package cz.netkit.app.overview + +import cz.netkit.app.backup.ConfigFile +import android.app.Application +import android.net.Uri +import android.net.wifi.ScanResult +import android.net.wifi.WifiManager +import android.os.Build +import android.os.SystemClock +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import cz.netkit.app.BuildConfig +import cz.netkit.app.net.ActiveNetworkInfo +import cz.netkit.app.speed.SpeedStore +import cz.netkit.app.wifi.ExportNotice +import cz.netkit.app.wifi.ExportSession +import cz.netkit.app.wifi.live.LiveWifiStandard +import cz.netkit.app.wifi.live.WifiLiveState +import cz.netkit.app.wifi.writeExportDocument +import cz.netkit.shared.net.NetKind +import cz.netkit.shared.report.DIAGNOSTIC_LATENCY_WINDOW_S +import cz.netkit.shared.report.DiagnosticLatencyInput +import cz.netkit.shared.report.DiagnosticPublicIpInput +import cz.netkit.shared.report.DiagnosticReportInput +import cz.netkit.shared.report.DiagnosticWifiInput +import cz.netkit.shared.speed.SpeedEngine +import cz.netkit.shared.speed.SpeedRecord +import cz.netkit.shared.wifi.LiveSeries +import cz.netkit.shared.wifi.WifiBand +import cz.netkit.shared.wifi.normalizeBssid +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * The link facts of the active network the report needs, without the platform `Network` handle + * (so [diagnosticReportInput] is a plain JVM function). + */ +internal data class ReportNetworkFacts( + val kind: NetKind, + val metered: Boolean, + val interfaceName: String?, + val ipv4: String?, + val ipv6: String?, + val gateway: String?, + val dnsServers: List, + val privateDns: Boolean, + val privateDnsHost: String?, + val dhcpServer: String?, + val mtu: Int, +) + +internal fun ActiveNetworkInfo.reportFacts() = ReportNetworkFacts(kind, metered, interfaceName, localIpv4, localIpv6, gateway, dnsServers, + privateDnsActive, privateDnsServerName, dhcpServer, mtu) + +/** + * Report input from what Přehled already holds (zadání 47 §1): the live state, the active + * network's link facts and the newest speed-test / iperf3 records. Latency is the last + * [DIAGNOSTIC_LATENCY_WINDOW_S] seconds before [nowElapsedMs]; the gateway only on Wi-Fi. + * Deliberately nothing from the mobile card or the cell detail (D31: cell identity stays local). + */ +internal fun diagnosticReportInput( + live: WifiLiveState, network: ReportNetworkFacts?, records: List, widthMhz: Int?, + appVersion: String, nowEpochMs: Long, nowElapsedMs: Long, +): DiagnosticReportInput { + val link = live.link + val wifiActive = link != null && (network == null || network.kind == NetKind.WIFI || network.kind == NetKind.VPN) + // Revize kolo 1 (P2): the Wi-Fi monitor fills a missing address only when Wi-Fi is the reported + // network; with mobile data or a VPN as the default it would describe a different network. + val wifiReported = link != null && network?.kind == NetKind.WIFI + fun window(series: LiveSeries): List = + series.samples.filter { it.elapsedMs > nowElapsedMs - DIAGNOSTIC_LATENCY_WINDOW_S * 1_000L && it.elapsedMs <= nowElapsedMs }.map { it.value } + val publicIp = live.publicIp.info?.takeIf { live.publicIp.enabled } + return DiagnosticReportInput( + generatedAtMs = nowEpochMs, + appVersion = appVersion, + networkKind = network?.kind, + metered = network?.metered, + interfaceName = network?.interfaceName, + ipv4 = network?.ipv4 ?: link?.ipv4Address?.takeIf { wifiReported }, + ipv6 = network?.ipv6, + gateway = network?.gateway ?: link?.gatewayIpv4?.takeIf { wifiReported }, + dnsServers = network?.dnsServers.orEmpty(), + privateDns = network?.privateDns == true, + privateDnsHost = network?.privateDnsHost, + dhcpServer = network?.dhcpServer, + mtu = network?.mtu?.takeIf { it > 0 }, + wifi = if (!wifiActive || link == null) null else DiagnosticWifiInput( + ssid = link.ssid, bssid = link.bssid, rssiDbm = link.rssiDbm, rxLinkMbps = link.rxLinkMbps, txLinkMbps = link.txLinkMbps, + frequencyMhz = link.frequencyMhz, channel = link.channel, band = link.band, widthMhz = widthMhz, + standard = link.wifiStandard?.let { standardText(it, link.band) }, + ), + gatewayLatency = if (wifiActive) DiagnosticLatencyInput(live.gatewayLatency.target, window(live.gatewayLatency.series)) else null, + internetLatency = DiagnosticLatencyInput(live.internetLatency.target, window(live.internetLatency.series)), + publicIp = publicIp?.let { DiagnosticPublicIpInput(it.v4?.address, it.v6?.address, it.asn, it.provider) }, + lastSpeedTest = records.filter { it.engine != SpeedEngine.IPERF3 }.maxByOrNull { it.timestampMs }, + lastIperf3 = records.filter { it.engine == SpeedEngine.IPERF3 }.maxByOrNull { it.timestampMs }, + ) +} + +/** "802.11ax (Wi-Fi 6E)" on 6 GHz; the generation names of the Wi-Fi Alliance. */ +internal fun standardText(standard: LiveWifiStandard, band: WifiBand): String = when (standard) { + LiveWifiStandard.LEGACY -> "802.11a/b/g" + LiveWifiStandard.N -> "802.11n (Wi-Fi 4)" + LiveWifiStandard.AC -> "802.11ac (Wi-Fi 5)" + LiveWifiStandard.AX -> if (band == WifiBand.GHZ_6) "802.11ax (Wi-Fi 6E)" else "802.11ax (Wi-Fi 6)" + LiveWifiStandard.AD -> "802.11ad" + LiveWifiStandard.BE -> "802.11be (Wi-Fi 7)" +} + +/** UI state of the report dialog; [input] null while [loading] or closed. */ +data class DiagnosticReportUiState( + val open: Boolean = false, + val loading: Boolean = false, + val input: DiagnosticReportInput? = null, + val saveNotice: ExportNotice? = null, +) + +/** + * Zadání 47 §1: builds the report input when the dialog opens (speed history read from the + * app-private store, channel width from the last cached scan; no new scan, no network request) + * and writes the chosen text to a SAF document. Nothing is kept after [close]. + */ +class DiagnosticReportViewModel(application: Application) : AndroidViewModel(application) { + private val app = application + private val store = SpeedStore(ConfigFile.SPEED.resolve(application)) + private val export = ExportSession { uri, text -> writeExportDocument(app, uri, text) } + private val _state = MutableStateFlow(DiagnosticReportUiState()) + val state: StateFlow = _state.asStateFlow() + private var job: Job? = null + + internal fun open(live: WifiLiveState, network: ActiveNetworkInfo?) { + job?.cancel() + export.clear() + _state.value = DiagnosticReportUiState(open = true, loading = true) + val facts = network?.reportFacts() + val nowElapsed = SystemClock.elapsedRealtime() + val nowEpoch = System.currentTimeMillis() + job = viewModelScope.launch { + val records = store.read().data.records + val width = withContext(Dispatchers.IO) { cachedWidthMhz(live.link?.bssid) } + val input = diagnosticReportInput(live, facts, records, width, BuildConfig.VERSION_NAME, nowEpoch, nowElapsed) + _state.update { if (it.open) it.copy(loading = false, input = input) else it } + } + } + + fun close() { + job?.cancel() + export.clear() + _state.value = DiagnosticReportUiState() + } + + /** Captures [text] for the SAF picker result; the file gets exactly this snapshot. */ + fun prepareSave(text: String): Boolean = export.prepare(text).also { syncNotice() } + + fun saveLaunchFailed() { + export.launchFailed() + syncNotice() + } + + fun save(uri: Uri?) { + viewModelScope.launch { + export.save(uri) + syncNotice() + } + } + + private fun syncNotice() = _state.update { it.copy(saveNotice = export.notice.value) } + + /** Width of the connected BSS from the last scan the system cached; null without a match or permission. */ + private fun cachedWidthMhz(bssid: String?): Int? { + val target = normalizeBssid(bssid) ?: return null + val wifi = app.applicationContext.getSystemService(WifiManager::class.java) ?: return null + val result = try { wifi.scanResults.orEmpty().firstOrNull { normalizeBssid(it.BSSID) == target } } catch (_: SecurityException) { null } + ?: return null + return when (result.channelWidth) { + ScanResult.CHANNEL_WIDTH_20MHZ -> 20 + ScanResult.CHANNEL_WIDTH_40MHZ -> 40 + ScanResult.CHANNEL_WIDTH_80MHZ -> 80 + ScanResult.CHANNEL_WIDTH_160MHZ, ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ -> 160 + else -> if (Build.VERSION.SDK_INT >= 33 && result.channelWidth == ScanResult.CHANNEL_WIDTH_320MHZ) 320 else null + } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/overview/OverviewCards.kt b/androidApp/src/main/kotlin/cz/netkit/app/overview/OverviewCards.kt index 4bddc64..350cfbf 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/overview/OverviewCards.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/overview/OverviewCards.kt @@ -79,7 +79,7 @@ private val CELL_SIDE_BY_SIDE_MIN = 320.dp */ @Composable internal fun ConnectionPathCard(state: WifiLiveState, mode: OverviewMode, apDetail: String?, onRefresh: () -> Unit, - onLookupChange: (Boolean) -> Unit) { + onLookupChange: (Boolean) -> Unit, onRdap: ((String) -> Unit)? = null) { val network = state.network val publicIp = state.publicIp val info = publicIp.info @@ -93,12 +93,12 @@ internal fun ConnectionPathCard(state: WifiLiveState, mode: OverviewMode, apDeta ProviderNodeState.READY, ProviderNodeState.CARRIER_NAT -> listOfNotNull( info?.v4?.let { PathLine(it.address, mono = true) }, info?.v6?.let { PathLine(it.address, mono = true) }, - info?.asn?.let { PathLine(stringResource(R.string.overview_asn, it), mono = false, dim = true) }, + info?.asn?.let { PathLine(stringResource(R.string.overview_asn, it), mono = false) }, ) - ProviderNodeState.LOADING -> listOf(PathLine(stringResource(R.string.overview_provider_loading), mono = false, dim = true)) - ProviderNodeState.UNAVAILABLE -> listOf(PathLine(stringResource(R.string.overview_provider_unavailable), mono = false, dim = true)) - ProviderNodeState.DISABLED -> listOf(PathLine(stringResource(R.string.overview_provider_disabled), mono = false, dim = true)) - ProviderNodeState.NO_NETWORK -> listOf(PathLine(stringResource(R.string.net_kind_none), mono = false, dim = true)) + ProviderNodeState.LOADING -> listOf(PathLine(stringResource(R.string.overview_provider_loading), mono = false)) + ProviderNodeState.UNAVAILABLE -> listOf(PathLine(stringResource(R.string.overview_provider_unavailable), mono = false)) + ProviderNodeState.DISABLED -> listOf(PathLine(stringResource(R.string.overview_provider_disabled), mono = false)) + ProviderNodeState.NO_NETWORK -> listOf(PathLine(stringResource(R.string.net_kind_none), mono = false)) } val nodes = buildList { add(PathNode( @@ -108,26 +108,33 @@ internal fun ConnectionPathCard(state: WifiLiveState, mode: OverviewMode, apDeta providerLines, tag = if (provider == ProviderNodeState.CARRIER_NAT) stringResource(R.string.overview_carrier_nat) to Tone.INFO else null, testTag = "overview_node_provider", + copyValue = if (provider == ProviderNodeState.READY || provider == ProviderNodeState.CARRIER_NAT) + (info?.v4 ?: info?.v6)?.address else null, + copySensitive = true, )) if (mode == OverviewMode.WIFI) add(PathNode( NetKitIcons.Router, stringResource(R.string.wifi_signal_access_point), listOfNotNull(apDetail?.let { PathLine(it, mono = false) }), testTag = "overview_node_ap", + copyValue = state.link?.channel?.toString(), )) val local = network?.localIpv4 ?: network?.localIpv6 add(PathNode( NetKitIcons.Phone, stringResource(R.string.overview_this_phone), - listOf(if (local != null) PathLine(local, mono = true) else PathLine(stringResource(R.string.overview_no_address), mono = false, dim = true)), + listOf(if (local != null) PathLine(local, mono = true) else PathLine(stringResource(R.string.overview_no_address), mono = false)), tag = if (network?.kind == NetKind.VPN) stringResource(R.string.net_kind_vpn) to Tone.NEUTRAL else null, testTag = "overview_node_phone", + copyValue = local, )) } var menu by remember { mutableStateOf(false) } SectionCard(stringResource(R.string.overview_path_title), trailing = { Box { - IconButton(onClick = { menu = true }, modifier = Modifier.size(40.dp).testTag("overview_path_menu")) { + IconButton(onClick = { menu = true }, modifier = Modifier.size(48.dp).testTag("overview_path_menu")) { Icon(NetKitIcons.More, stringResource(R.string.overview_menu), tint = NetKitTheme.colors.muted) } - PathMenu(expanded = menu, onDismiss = { menu = false }, enabled = publicIp.enabled, + PathMenu(expanded = menu, onDismiss = { menu = false }, enabled = publicIp.enabled, settingLoaded = publicIp.settingLoaded, + rdapTargets = if (publicIp.enabled && onRdap != null) listOfNotNull(info?.v4?.address, info?.v6?.address, info?.asn?.let { "AS$it" }) else emptyList(), + onTarget = { menu = false; onRdap?.invoke(it) }, canRefresh = publicIp.enabled && network != null, onRefresh = { menu = false; onRefresh() }, onLookupChange = { menu = false; onLookupChange(it) }) } @@ -141,8 +148,8 @@ internal fun ConnectionPathCard(state: WifiLiveState, mode: OverviewMode, apDeta } @Composable -private fun PathMenu(expanded: Boolean, onDismiss: () -> Unit, enabled: Boolean, canRefresh: Boolean, onRefresh: () -> Unit, - onLookupChange: (Boolean) -> Unit) { +private fun PathMenu(expanded: Boolean, onDismiss: () -> Unit, enabled: Boolean, settingLoaded: Boolean, canRefresh: Boolean, onRefresh: () -> Unit, + onLookupChange: (Boolean) -> Unit, rdapTargets: List, onTarget: (String) -> Unit) { val colors = NetKitTheme.colors DropdownMenu(expanded = expanded, onDismissRequest = onDismiss, shape = NetKitShape.nested, containerColor = colors.surface2, tonalElevation = 0.dp, @@ -153,9 +160,12 @@ private fun PathMenu(expanded: Boolean, onDismiss: () -> Unit, enabled: Boolean, leadingIcon = { Icon(NetKitIcons.Refresh, null, Modifier.size(18.dp), tint = if (canRefresh) colors.muted else colors.dim) }, modifier = Modifier.testTag("overview_public_ip_refresh"), ) + rdapTargets.forEach { target -> + DropdownMenuItem(text = { Text(stringResource(R.string.diag_rdap_target, target)) }, onClick = { onTarget(target) }) + } DropdownMenuItem( text = { Text(stringResource(R.string.overview_lookup_toggle), style = NetKitType.body, color = colors.text) }, - onClick = { onLookupChange(!enabled) }, + onClick = { onLookupChange(!enabled) }, enabled = settingLoaded, trailingIcon = { Checkbox(checked = enabled, onCheckedChange = null, colors = CheckboxDefaults.colors( checkedColor = colors.accent, checkmarkColor = colors.accentInk, uncheckedColor = colors.muted)) @@ -170,9 +180,11 @@ private fun PathMenu(expanded: Boolean, onDismiss: () -> Unit, enabled: Boolean, /** * Main mobile card (no Wi-Fi): RSRP gauge on the −140…−44 dBm scale, SIM, operator and tags * beside it, RSRQ / SINR / IPv4 tiles, other SIMs as rows and the "both SIMs" permission block. + * Each SIM has an expandable "Detail buňky" ([CellDetailToggle], zadání 53) when [cellDetail] is set. */ @Composable -internal fun CellularHeroPanel(state: WifiLiveState, permissionDenied: Boolean, onRequestPhonePermission: () -> Unit) { +internal fun CellularHeroPanel(state: WifiLiveState, permissionDenied: Boolean, onRequestPhonePermission: () -> Unit, + cellDetail: CellDetailHost? = null) { val dash = stringResource(R.string.wifi_signal_no_value) val cellular = state.cellular val sims = sortedSims(cellular?.sims.orEmpty()) @@ -210,9 +222,13 @@ internal fun CellularHeroPanel(state: WifiLiveState, permissionDenied: Boolean, StatTile(stringResource(R.string.cellular_sinr), signal?.sinrDb?.let(::signed) ?: dash, unit = db.takeIf { signal?.sinrDb != null }), StatTile(stringResource(R.string.wifi_signal_ipv4), ipv4 ?: dash, weight = 1.45f, monospace = ipv4 != null), )) + primary?.takeIf { cellular?.airplaneMode != true }?.let { CellDetailToggle(it, cellDetail) } val others = sims.filter { it !== primary } if (others.isNotEmpty()) Column(Modifier.fillMaxWidth()) { - others.forEachIndexed { index, sim -> SimRow(sim, showDivider = index > 0) } + others.forEachIndexed { index, sim -> + SimRow(sim, showDivider = index > 0) + if (cellular?.airplaneMode != true) CellDetailToggle(sim, cellDetail) + } } PermissionBlock(state.cellularPermissionNeeded, permissionDenied, onRequestPhonePermission) } @@ -220,10 +236,12 @@ internal fun CellularHeroPanel(state: WifiLiveState, permissionDenied: Boolean, /** * Compact "Mobilní síť" card under the Wi-Fi card: one row per SIM (SIM n, operator, standard, - * dBm and quality, tag "Data"), or the airplane / no SIM state, plus the permission block. + * dBm and quality, tag "Data"), or the airplane / no SIM state, plus the permission block; under + * each SIM the expandable "Detail buňky" ([CellDetailToggle], zadání 53). */ @Composable -internal fun CellularCompactCard(state: WifiLiveState, permissionDenied: Boolean, onRequestPhonePermission: () -> Unit) { +internal fun CellularCompactCard(state: WifiLiveState, permissionDenied: Boolean, onRequestPhonePermission: () -> Unit, + cellDetail: CellDetailHost? = null) { val colors = NetKitTheme.colors val cellular = state.cellular val sims = sortedSims(cellular?.sims.orEmpty()) @@ -234,7 +252,10 @@ internal fun CellularCompactCard(state: WifiLiveState, permissionDenied: Boolean cellular.airplaneMode -> Text(stringResource(R.string.cellular_airplane), style = NetKitType.body, color = colors.muted) sims.isEmpty() -> Text(stringResource(if (cellular.noSim) R.string.cellular_no_sim else R.string.cellular_no_service), style = NetKitType.body, color = colors.muted) - else -> sims.forEachIndexed { index, sim -> SimRow(sim, showDivider = index > 0, dataTag = true) } + else -> sims.forEachIndexed { index, sim -> + SimRow(sim, showDivider = index > 0, dataTag = true) + CellDetailToggle(sim, cellDetail) + } } } PermissionBlock(state.cellularPermissionNeeded, permissionDenied, onRequestPhonePermission) diff --git a/androidApp/src/main/kotlin/cz/netkit/app/overview/PathCard.kt b/androidApp/src/main/kotlin/cz/netkit/app/overview/PathCard.kt index 92aa224..c1f8174 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/overview/PathCard.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/overview/PathCard.kt @@ -37,6 +37,7 @@ import androidx.compose.ui.unit.dp import cz.netkit.app.ui.Spacing import cz.netkit.app.ui.Tag import cz.netkit.app.ui.Tone +import cz.netkit.app.ui.copyOnLongPress import cz.netkit.app.ui.motion.rememberBreathing import cz.netkit.app.ui.theme.NetKitTheme import cz.netkit.app.ui.theme.NetKitType @@ -48,9 +49,9 @@ private val NodeGap = Spacing.small /** Font scale from which the nodes always stack (docs/design.md §4, large text). */ private const val STACK_FONT_SCALE = 1.3f -/** One text line under a node title: a machine value in mono ([mono]) or a dim sans hint. */ +/** One text line under a node title: a machine value in mono ([mono]) or a muted sans label. */ @Immutable -internal data class PathLine(val text: String, val mono: Boolean, val dim: Boolean = false) +internal data class PathLine(val text: String, val mono: Boolean) /** * One node of the path card. [lines] are never ellipsized; [tag] is an optional state tag @@ -63,6 +64,9 @@ internal data class PathNode( val lines: List, val tag: Pair? = null, val testTag: String, + /** Zadání 47: a long press on the node copies this value; [copySensitive] marks the clip sensitive (API 33+). */ + val copyValue: String? = null, + val copySensitive: Boolean = false, ) /** @@ -116,7 +120,7 @@ private fun SideBySideNodes(nodes: List, live: Boolean, firstLinkBroke horizontalArrangement = Arrangement.spacedBy(NodeGap), ) { nodes.forEach { node -> - Column(Modifier.weight(1f).testTag(node.testTag).semantics(mergeDescendants = true) {}, + Column(Modifier.weight(1f).testTag(node.testTag).copyOnLongPress(node.copyValue, node.copySensitive).semantics(mergeDescendants = true) {}, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(Spacing.tiny)) { NodeIconTile(node.icon) NodeTexts(node, centered = true) @@ -135,7 +139,7 @@ private fun StackedNodes(nodes: List, live: Boolean, firstLinkBroken: Layout( content = { nodes.forEach { node -> - Row(Modifier.fillMaxWidth().testTag(node.testTag).semantics(mergeDescendants = true) {}, + Row(Modifier.fillMaxWidth().testTag(node.testTag).copyOnLongPress(node.copyValue, node.copySensitive).semantics(mergeDescendants = true) {}, horizontalArrangement = Arrangement.spacedBy(Spacing.medium), verticalAlignment = Alignment.Top) { NodeIconTile(node.icon) Box(Modifier.weight(1f)) { NodeTexts(node, centered = false) } @@ -193,7 +197,7 @@ private fun NodeTexts(node: PathNode, centered: Boolean) { verticalArrangement = Arrangement.spacedBy(2.dp)) { Text(node.title, style = NetKitType.body.copy(fontWeight = FontWeight.SemiBold), color = colors.text, textAlign = align) node.lines.forEach { line -> - Text(line.text, style = lineStyle(line), color = if (line.dim) colors.dim else if (line.mono) colors.text else colors.muted, + Text(line.text, style = lineStyle(line), color = if (line.mono) colors.text else colors.muted, textAlign = align) } node.tag?.let { (text, tone) -> Tag(text, tone, dot = tone != Tone.NEUTRAL) } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt b/androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt index 1f4bd04..12da421 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt @@ -67,8 +67,13 @@ private const val KEY_LOOKUP_ENABLED = "public_ip.enabled" * - Setting "look up the public IP" (default on) in the app-private SharedPreferences file * `overview`, excluded from backups like every other app file. Off clears the cache. * - * Disk access ([isLookupEnabled], [setLookupEnabled]) belongs off the main thread. + * Read [isLookupEnabled] off the main thread before enabling the toggle. [setLookupEnabled] + * uses apply() on the loaded preferences, making the new gate visible before returning. */ +/** The stored "look up the public IP" setting without creating a repository (widget snapshot, zadání 37). Disk read. */ +internal fun publicIpLookupEnabled(context: Context): Boolean = + context.applicationContext.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE).getBoolean(KEY_LOOKUP_ENABLED, true) + internal class PublicIpRepository(context: Context) { private val preferences = context.applicationContext.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE) private val userAgent = "NetKit/${BuildConfig.VERSION_NAME} (Android)" diff --git a/androidApp/src/main/kotlin/cz/netkit/app/settings/AppLanguageSystem.kt b/androidApp/src/main/kotlin/cz/netkit/app/settings/AppLanguageSystem.kt new file mode 100644 index 0000000..d7656c1 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/settings/AppLanguageSystem.kt @@ -0,0 +1,74 @@ +package cz.netkit.app.settings + +import android.app.LocaleManager +import android.content.ActivityNotFoundException +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.os.LocaleList +import android.provider.Settings +import androidx.annotation.ChecksSdkIntAtLeast +import androidx.annotation.RequiresApi +import androidx.glance.appwidget.updateAll +import cz.netkit.app.netstatus.NetStatusWidgets +import cz.netkit.app.ssh.SshSessionService +import cz.netkit.app.wol.NetKitApplication +import cz.netkit.app.wol.widget.WolWidget +import cz.netkit.shared.settings.AppLanguage +import cz.netkit.shared.settings.appLanguageFromTags +import kotlinx.coroutines.launch + +/** + * Per-app language through the framework [LocaleManager] (Android 13+, zadání 46 §1), no AppCompat. + * The system keeps the choice (also shown in Settings → Apps → NetKit → Language, from the + * `LocaleConfig` AGP generates); setting it recreates the activity with the new configuration. + * Below Android 13 the app follows the system language and the Settings screen only says so. + */ +internal object AppLanguageSystem { + @get:ChecksSdkIntAtLeast(api = Build.VERSION_CODES.TIRAMISU) + val supported: Boolean get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU + + /** The current choice, `null` below Android 13. */ + fun current(context: Context): AppLanguage? = + if (supported) appLanguageFromTags(manager(context).applicationLocales.toLanguageTags()) else null + + /** Applies [language] ([AppLanguage.SYSTEM] = empty list = follow the system); main thread. */ + fun set(context: Context, language: AppLanguage) { + if (!supported) return + manager(context).applicationLocales = language.tag?.let { LocaleList.forLanguageTags(it) } ?: LocaleList.getEmptyLocaleList() + } + + /** Opens the system per-app language page; false when no activity handles it. */ + fun openSystemSettings(context: Context): Boolean { + if (!supported) return false + return try { + context.startActivity(Intent(Settings.ACTION_APP_LOCALE_SETTINGS, Uri.fromParts("package", context.packageName, null))) + true + } catch (_: ActivityNotFoundException) { + false + } + } + + @RequiresApi(Build.VERSION_CODES.TIRAMISU) + private fun manager(context: Context): LocaleManager = context.getSystemService(LocaleManager::class.java) +} + +/** The system also sends this when per-app language is changed outside NetKit, even with no activity open. */ +class AppLocaleReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action != Intent.ACTION_LOCALE_CHANGED) return + val app = context.applicationContext as NetKitApplication + SshSessionService.createChannel(app, onlyIfPresent = true) + val pending = goAsync() + app.appScope.launch { + try { + NetStatusWidgets.redraw(app) + WolWidget().updateAll(app) + } catch (_: IllegalStateException) { + // A widget can disappear while Glance is enumerating or updating its instances. + } finally { pending.finish() } + } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/settings/OwnedOperation.kt b/androidApp/src/main/kotlin/cz/netkit/app/settings/OwnedOperation.kt new file mode 100644 index 0000000..b80392e --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/settings/OwnedOperation.kt @@ -0,0 +1,13 @@ +package cz.netkit.app.settings + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.async + +/** + * Runs the whole [block] in [owner] (the ViewModel scope) and lets the caller only await the result. + * Settings actions start from a composition scope that is cancelled when the user leaves the screen + * or rotates the phone: the block then still finishes, including the state change after a store write + * and the cancellation of running work (zadání 46, revize kolo 1). Cancelling [owner] cancels the block. + */ +internal suspend fun awaitInOwner(owner: CoroutineScope, block: suspend CoroutineScope.() -> T): T = + owner.async(block = block).await() diff --git a/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsHost.kt b/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsHost.kt new file mode 100644 index 0000000..0dd3809 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsHost.kt @@ -0,0 +1,42 @@ +package cz.netkit.app.settings + +import android.graphics.Color +import androidx.activity.ComponentActivity +import androidx.activity.SystemBarStyle +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import cz.netkit.app.ui.LocalKeepScreenOnSetting +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.shared.settings.isDark + +/** + * Applies the stored settings around the app UI (zadání 46 §3): the theme ([NetKitTheme] and the + * system bar icons) and the "keep the display on" setting for [cz.netkit.app.ui.KeepScreenOn]. + * Nothing is drawn until the settings file has been read once (a few ms; the window background + * shows meanwhile), so a forced theme does not flash the system one. + */ +@Composable +fun SettingsHost(settings: SettingsViewModel, activity: ComponentActivity, content: @Composable () -> Unit) { + val prefs = settings.settings.collectAsStateWithLifecycle().value ?: return + val dark = prefs.theme.isDark(isSystemInDarkTheme()) + LaunchedEffect(dark) { applySystemBars(activity, dark) } + NetKitTheme(darkTheme = dark) { + CompositionLocalProvider(LocalKeepScreenOnSetting provides prefs.keepScreenOn, content = content) + } +} + +/** Same bars as the default `enableEdgeToEdge()`, but light/dark icons follow the app theme, not only the system. */ +private fun applySystemBars(activity: ComponentActivity, dark: Boolean) { + activity.enableEdgeToEdge( + statusBarStyle = SystemBarStyle.auto(Color.TRANSPARENT, Color.TRANSPARENT) { dark }, + // The scrims of androidx.activity's default navigation bar style (3-button navigation). + navigationBarStyle = SystemBarStyle.auto(LIGHT_SCRIM, DARK_SCRIM) { dark }, + ) +} + +private val LIGHT_SCRIM = Color.argb(0xe6, 0xFF, 0xFF, 0xFF) +private val DARK_SCRIM = Color.argb(0x80, 0x1b, 0x1b, 0x1b) diff --git a/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsScreen.kt new file mode 100644 index 0000000..3c1c0e7 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsScreen.kt @@ -0,0 +1,271 @@ +package cz.netkit.app.settings + +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.selection.toggleable +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import cz.netkit.app.R +import cz.netkit.app.lan.LanViewModel +import cz.netkit.app.lan.LanDevicesViewModel +import cz.netkit.app.speed.SpeedTestViewModel +import cz.netkit.app.ssh.NetKitAlert +import cz.netkit.app.ssh.netKitSwitchColors +import cz.netkit.app.ui.InfoNote +import cz.netkit.app.ui.ListRow +import cz.netkit.app.ui.NetKitIcons +import cz.netkit.app.ui.NeutralButton +import cz.netkit.app.ui.PrimaryButton +import cz.netkit.app.ui.SectionCard +import cz.netkit.app.ui.SegmentedTabs +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.StatusBanner +import cz.netkit.app.ui.StatusKind +import cz.netkit.app.ui.about.SubscreenHeader +import cz.netkit.app.ui.about.UpdatesCard +import cz.netkit.app.ui.about.updatesNote +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.app.update.UpdateViewModel +import cz.netkit.app.update.openLink +import cz.netkit.app.wifi.live.WifiLiveViewModel +import cz.netkit.shared.settings.AppLanguage +import cz.netkit.shared.settings.AppSettings +import cz.netkit.shared.settings.ThemeMode +import cz.netkit.shared.speed.SpeedHistoryKind +import cz.netkit.shared.speed.countOf +import kotlinx.coroutines.launch + +/** One reset/delete action of the screen; the name is also the test-tag suffix. */ +private enum class SettingsAction(val tag: String) { + LAN_CONSENT("lan_consent"), NDT7_CONSENT("ndt7_consent"), SPEED_HISTORY("speed_history"), + IPERF_HISTORY("iperf_history"), IPERF_TARGET("iperf_target"), TOOL_TARGETS("tool_targets"), +} + +/** + * Settings (zadání 46 §3), a subscreen of Přehled next to About: theme, app language (Android 13+), + * keep the display on during measurements, consents and online queries, histories and the iperf3 + * target, and the update check moved here from About. Every reset acts through the ViewModel that + * owns the data, so the open screens see the change at once. Deleting a history asks first. + */ +@Composable +fun SettingsScreen( + settings: SettingsViewModel, update: UpdateViewModel, live: WifiLiveViewModel, speed: SpeedTestViewModel, + devices: LanDevicesViewModel, lan: LanViewModel, onBack: () -> Unit, modifier: Modifier = Modifier, onBackup: () -> Unit, +) { + val prefs = settings.settings.collectAsStateWithLifecycle().value ?: AppSettings() + val writeFailed by settings.writeFailed.collectAsStateWithLifecycle() + val updateState by update.state.collectAsStateWithLifecycle() + val liveState by live.state.collectAsStateWithLifecycle() + val speedState by speed.state.collectAsStateWithLifecycle() + val context = LocalContext.current + val scope = rememberCoroutineScope() + // Read once per composition of the screen; changing it recreates the activity anyway. + var language by remember { mutableStateOf(AppLanguageSystem.current(context)) } + var confirm by rememberSaveable { mutableStateOf(null) } + val results = remember { mutableStateMapOf() } + val speedCount = speedState.history.countOf(SpeedHistoryKind.SPEED_TEST) + val iperfCount = speedState.history.countOf(SpeedHistoryKind.IPERF3) + val targetCount = lan.state.collectAsStateWithLifecycle().value.targets.recent.size + val note = updatesNote(updateState) + + fun run(action: SettingsAction) { + confirm = null + scope.launch { + results[action] = when (action) { + SettingsAction.LAN_CONSENT -> devices.forgetAllConsents() + SettingsAction.NDT7_CONSENT -> speed.resetNdt7Consent() + SettingsAction.SPEED_HISTORY -> speed.clearHistory(SpeedHistoryKind.SPEED_TEST) + SettingsAction.IPERF_HISTORY -> speed.clearHistory(SpeedHistoryKind.IPERF3) + SettingsAction.TOOL_TARGETS -> lan.clearTargetHistory().await() + SettingsAction.IPERF_TARGET -> speed.forgetIperfTarget() + } + } + } + + BackHandler(onBack = onBack) + LazyColumn( + modifier.fillMaxSize().testTag("settings_screen"), + contentPadding = PaddingValues(start = Spacing.normal, end = Spacing.normal, bottom = Spacing.normal), + verticalArrangement = Arrangement.spacedBy(Spacing.normal), + ) { + item(key = "header") { SubscreenHeader(stringResource(R.string.settings_title), "settings_back", onBack) } + if (writeFailed) item(key = "write_failed") { StatusBanner(stringResource(R.string.settings_write_failed), StatusKind.WARNING) } + item(key = "backup") { + NeutralButton(stringResource(R.string.backup_title), onBackup, Modifier.testTag("settings_backup")) + val app = context.applicationContext as cz.netkit.app.wol.NetKitApplication + if (app.restoreIoError) StatusBanner(stringResource(R.string.backup_retry_start), StatusKind.ERROR) + if (app.restoreMapReset) StatusBanner(stringResource(R.string.backup_map_reset), StatusKind.WARNING) + app.restoreApplied?.let { + StatusBanner(stringResource(if (it) R.string.backup_applied else R.string.backup_stale)) + } + } + item(key = "appearance") { + SectionCard(stringResource(R.string.settings_appearance)) { + Caption(stringResource(R.string.settings_theme)) + SegmentedTabs( + listOf(stringResource(R.string.settings_theme_system), stringResource(R.string.settings_theme_light), + stringResource(R.string.settings_theme_dark)), + prefs.theme.ordinal, { settings.setTheme(ThemeMode.entries[it]) }, + testTags = ThemeMode.entries.map { "settings_theme_" + it.name.lowercase() }, + ) + } + } + item(key = "language") { + SectionCard(stringResource(R.string.settings_language)) { + val current = language + if (current == null) { + Text(stringResource(R.string.settings_language_unsupported), Modifier.testTag("settings_language_unsupported"), + style = NetKitType.body, color = NetKitTheme.colors.muted) + } else { + SegmentedTabs( + listOf(stringResource(R.string.settings_language_system), stringResource(R.string.settings_language_cs), + stringResource(R.string.settings_language_en)), + current.ordinal, + { index -> + val chosen = AppLanguage.entries[index] + if (chosen != language) { language = chosen; AppLanguageSystem.set(context, chosen) } + }, + testTags = AppLanguage.entries.map { "settings_language_" + it.name.lowercase() }, + ) + Text(stringResource(R.string.settings_language_detail), style = NetKitType.label, color = NetKitTheme.colors.muted) + ListRow(stringResource(R.string.settings_language_open), stringResource(R.string.settings_language_open_detail), + NetKitIcons.Globe, showDivider = true, modifier = Modifier.testTag("settings_language_open"), onClick = { + if (!AppLanguageSystem.openSystemSettings(context)) { + Toast.makeText(context, R.string.settings_language_open_failed, Toast.LENGTH_LONG).show() + } + }) + } + } + } + item(key = "measure") { + SectionCard(stringResource(R.string.settings_measure)) { + SwitchRow(stringResource(R.string.settings_keep_screen), stringResource(R.string.settings_keep_screen_detail), + prefs.keepScreenOn, "settings_keep_screen", onChange = settings::setKeepScreenOn) + } + } + item(key = "privacy") { + SectionCard(stringResource(R.string.settings_privacy)) { + SwitchRow(stringResource(R.string.settings_online), stringResource(R.string.settings_online_detail), + liveState.publicIp.enabled, "settings_online", enabled = liveState.publicIp.settingLoaded, + onChange = live::setPublicIpLookup) + ActionRow(stringResource(R.string.settings_lan_consent), stringResource(R.string.settings_lan_consent_detail), + SettingsAction.LAN_CONSENT, stringResource(R.string.settings_forget), results[SettingsAction.LAN_CONSENT]) { + confirm = SettingsAction.LAN_CONSENT + } + ActionRow(stringResource(R.string.settings_ndt7_consent), + stringResource(if (speedState.ndt7Acknowledged) R.string.settings_ndt7_acknowledged else R.string.settings_ndt7_pending), + SettingsAction.NDT7_CONSENT, stringResource(R.string.settings_show_again), results[SettingsAction.NDT7_CONSENT], + enabled = speedState.loaded && speedState.ndt7Acknowledged) { run(SettingsAction.NDT7_CONSENT) } + } + } + item(key = "data") { + SectionCard(stringResource(R.string.settings_data)) { + ActionRow(stringResource(R.string.settings_history_speed), + pluralStringResource(R.plurals.settings_history_count, speedCount, speedCount), + SettingsAction.SPEED_HISTORY, stringResource(R.string.settings_delete), results[SettingsAction.SPEED_HISTORY], + enabled = speedState.loaded && speedCount > 0) { confirm = SettingsAction.SPEED_HISTORY } + ActionRow(stringResource(R.string.settings_history_iperf), + pluralStringResource(R.plurals.settings_history_count, iperfCount, iperfCount), + SettingsAction.IPERF_HISTORY, stringResource(R.string.settings_delete), results[SettingsAction.IPERF_HISTORY], + enabled = speedState.loaded && iperfCount > 0) { confirm = SettingsAction.IPERF_HISTORY } + // The stored server, not the iperf3 form being edited (revize kolo 1). + val target = speedState.savedIperfTarget + ActionRow(stringResource(R.string.settings_iperf_target), + target ?: stringResource(R.string.settings_iperf_target_none), + SettingsAction.IPERF_TARGET, stringResource(R.string.settings_forget), results[SettingsAction.IPERF_TARGET], + enabled = speedState.loaded && !speedState.running && target != null) { run(SettingsAction.IPERF_TARGET) } + ActionRow(stringResource(R.string.settings_target_history), + pluralStringResource(R.plurals.settings_history_count, targetCount, targetCount), + SettingsAction.TOOL_TARGETS, stringResource(R.string.settings_delete), results[SettingsAction.TOOL_TARGETS], + enabled = targetCount > 0) { confirm = SettingsAction.TOOL_TARGETS } + } + } + item(key = "updates") { + UpdatesCard(updateState, onToggle = update::setEnabled, onCheck = update::checkNow, onOpen = { url -> openLink(context, url) }) + } + note?.let { detail -> item(key = "updates_note") { InfoNote(stringResource(R.string.about_updates_note_summary), detail) } } + } + + confirm?.let { action -> + val (title, text) = when (action) { + SettingsAction.LAN_CONSENT -> stringResource(R.string.settings_confirm_lan_title) to stringResource(R.string.settings_confirm_lan_text) + SettingsAction.TOOL_TARGETS -> stringResource(R.string.settings_target_history) to stringResource(R.string.settings_confirm_targets, + pluralStringResource(R.plurals.settings_history_count, targetCount, targetCount)) + SettingsAction.SPEED_HISTORY -> stringResource(R.string.settings_confirm_delete_title) to stringResource(R.string.settings_confirm_delete_text, + stringResource(R.string.settings_history_speed), pluralStringResource(R.plurals.settings_history_count, speedCount, speedCount)) + else -> stringResource(R.string.settings_confirm_delete_title) to stringResource(R.string.settings_confirm_delete_text, + stringResource(R.string.settings_history_iperf), pluralStringResource(R.plurals.settings_history_count, iperfCount, iperfCount)) + } + NetKitAlert( + onDismiss = { confirm = null }, title = title, + confirm = { PrimaryButton(stringResource(if (action == SettingsAction.LAN_CONSENT) R.string.settings_forget else R.string.settings_delete), + { run(action) }, Modifier.testTag("settings_confirm")) }, + dismiss = { NeutralButton(stringResource(R.string.settings_cancel), { confirm = null }, Modifier.testTag("settings_confirm_cancel")) }, + ) { Text(text, style = NetKitType.body, color = NetKitTheme.colors.muted) } + } +} + +@Composable +private fun Caption(text: String) = Text(text, style = NetKitType.label, color = NetKitTheme.colors.muted) + +/** Whole row toggles (48 dp+), switch on the right; [tag] goes on the row. */ +@Composable +private fun SwitchRow(title: String, detail: String, checked: Boolean, tag: String, enabled: Boolean = true, onChange: (Boolean) -> Unit) { + val colors = NetKitTheme.colors + Row( + Modifier.fillMaxWidth().heightIn(min = 48.dp) + .toggleable(value = checked, enabled = enabled, role = Role.Switch, onValueChange = onChange).testTag(tag), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium), + ) { + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(title, style = NetKitType.body, color = if (enabled) colors.text else colors.dim) + Text(detail, style = NetKitType.label, color = colors.muted) + } + Switch(checked = checked, onCheckedChange = null, enabled = enabled, colors = netKitSwitchColors()) + } +} + +/** Title, state line and one small button; after the action the state line ends with "Hotovo" or the failure. */ +@Composable +private fun ActionRow(title: String, detail: String, action: SettingsAction, button: String, result: Boolean?, + enabled: Boolean = true, onClick: () -> Unit) { + val colors = NetKitTheme.colors + Row(Modifier.fillMaxWidth().heightIn(min = 56.dp), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(title, style = NetKitType.body, color = colors.text) + Text(detail, Modifier.testTag("settings_${action.tag}_detail"), style = NetKitType.label, color = colors.muted) + result?.let { ok -> + Text(stringResource(if (ok) R.string.settings_done else R.string.settings_failed), Modifier.testTag("settings_${action.tag}_result"), + style = NetKitType.label, color = if (ok) colors.ok else colors.err) + } + } + NeutralButton(button, onClick, Modifier.testTag("settings_${action.tag}"), enabled = enabled, small = true) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsStore.kt b/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsStore.kt new file mode 100644 index 0000000..ab9e0c2 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsStore.kt @@ -0,0 +1,48 @@ +package cz.netkit.app.settings + +import cz.netkit.app.backup.ConfigFile +import android.content.Context +import androidx.datastore.core.CorruptionException +import androidx.datastore.core.DataStore +import androidx.datastore.core.DataStoreFactory +import androidx.datastore.core.Serializer +import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler +import cz.netkit.app.ssh.readBytesBounded +import cz.netkit.shared.settings.APP_SETTINGS_MAX_BYTES +import cz.netkit.shared.settings.AppSettings +import cz.netkit.shared.settings.AppSettingsCodec +import cz.netkit.shared.settings.AppSettingsCorrupt +import java.io.InputStream +import java.io.OutputStream + +/** Bounded strict JSON (shared [AppSettingsCodec]); anything unreadable is a DataStore corruption. */ +internal object AppSettingsSerializer : Serializer { + override val defaultValue = AppSettings() + override suspend fun readFrom(input: InputStream): AppSettings { + return try { + AppSettingsCodec.decode(input.readBytesBounded(APP_SETTINGS_MAX_BYTES).decodeToString()) + } catch (error: IllegalArgumentException) { + throw CorruptionException("Settings file too large", error) + } catch (error: AppSettingsCorrupt) { + throw CorruptionException("Invalid settings", error) + } + } + override suspend fun writeTo(t: AppSettings, output: OutputStream) { + output.write(AppSettingsCodec.encode(t).encodeToByteArray()) + } +} + +/** + * The one DataStore of `filesDir/datastore/settings.json` (zadání 46 §3). App-private like every + * other app file and outside any backup (`allowBackup=false`). A corrupt file is replaced by defaults. + */ +internal object SettingsStore { + private var instance: DataStore? = null + + @Synchronized fun get(context: Context): DataStore = + instance ?: DataStoreFactory.create( + serializer = AppSettingsSerializer, + corruptionHandler = ReplaceFileCorruptionHandler { AppSettingsSerializer.defaultValue }, + produceFile = { ConfigFile.SETTINGS.resolve(context) }, + ).also { instance = it } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsViewModel.kt new file mode 100644 index 0000000..8dc62cd --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsViewModel.kt @@ -0,0 +1,60 @@ +package cz.netkit.app.settings + +import android.app.Application +import androidx.lifecycle.AndroidViewModel +import androidx.lifecycle.viewModelScope +import cz.netkit.shared.settings.AppSettings +import cz.netkit.shared.settings.ThemeMode +import java.io.IOException +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.catch +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeoutOrNull + +/** + * App settings (zadání 46 §3): theme and "keep the display on during measurements". + * [settings] is `null` until the file has been read once; MainActivity draws the UI only after + * that, so a forced theme does not flash the system one. An unreadable file yields the defaults. + * [writeFailed] is set when the last change could not be stored (it still applies in memory). + */ +class SettingsViewModel(application: Application) : AndroidViewModel(application) { + private val store = SettingsStore.get(application) + private val _settings = MutableStateFlow(null) + val settings: StateFlow = _settings.asStateFlow() + private val _writeFailed = MutableStateFlow(false) + val writeFailed: StateFlow = _writeFailed.asStateFlow() + + init { + viewModelScope.launch { + store.data + .catch { error -> if (error is IOException) emit(AppSettings()) else throw error } + .collect { _settings.value = it } + } + } + + fun setTheme(theme: ThemeMode) = update { it.copy(theme = theme) } + + fun setKeepScreenOn(enabled: Boolean) = update { it.copy(keepScreenOn = enabled) } + + private fun update(transform: (AppSettings) -> AppSettings) { + // Applied at once in memory; the store catches up (or reports the failure). + _settings.value = transform(_settings.value ?: AppSettings()) + viewModelScope.launch { + val written = try { + withTimeoutOrNull(WRITE_TIMEOUT_MS) { store.updateData(transform) } != null + } catch (cancel: CancellationException) { + throw cancel + } catch (_: IOException) { + false + } + _writeFailed.value = !written + } + } + + private companion object { + const val WRITE_TIMEOUT_MS = 3_000L + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Client.kt b/androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Client.kt new file mode 100644 index 0000000..bded209 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Client.kt @@ -0,0 +1,223 @@ +package cz.netkit.app.speed + +import android.net.Network +import cz.netkit.shared.speed.ByteSample +import cz.netkit.shared.speed.Iperf3Handshake +import cz.netkit.shared.speed.Iperf3Options +import cz.netkit.shared.speed.Iperf3Protocol +import cz.netkit.shared.speed.Iperf3ServerFailure +import cz.netkit.shared.speed.Iperf3State +import cz.netkit.shared.speed.ThroughputSummary +import cz.netkit.shared.speed.summarizeThroughput + +import java.io.EOFException +import java.io.IOException +import java.net.InetSocketAddress +import java.net.SocketTimeoutException +import java.nio.ByteBuffer +import java.nio.channels.ReadableByteChannel +import java.nio.channels.SocketChannel +import java.util.UUID +import kotlin.math.roundToLong +import kotlin.random.Random +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.delay +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull + +internal data class Iperf3Measurement(val summary: ThroughputSummary, val retransmits: Long?, val workingStreams: Int) + +/** Both reverse phases read from the same budget. One extra byte distinguishes excess from an exact fit. */ +internal class Iperf3ReceiveBudget(limitBytes: Long?) { + private var remaining = limitBytes ?: Long.MAX_VALUE + + inline fun read(buffer: ByteBuffer, readInto: (ByteBuffer) -> Int): Int { + if (remaining < buffer.remaining()) buffer.limit(buffer.position() + remaining.toInt() + 1) + val bytes = readInto(buffer) + if (bytes > remaining) throw SpeedTestFailure(SpeedFailureKind.IPERF_LIMIT_EXCEEDED) + if (bytes > 0) remaining -= bytes.toLong() + return bytes + } +} + +/** Only the JVM fixture uses the unbound constructor. The application supplies its selected Network. */ +internal class Iperf3Client(private val bind: (java.net.Socket) -> Unit) { + constructor(network: Network) : this(network::bindSocket) + + suspend fun measure(target: InetSocketAddress, options: Iperf3Options, sample: (ByteSample) -> Unit): Iperf3Measurement = + withContext(Dispatchers.IO) { + require(!target.isUnresolved && target.port > 0) + val cookie = Iperf3Protocol.cookie(UUID.randomUUID().toString()) + val machine = Iperf3Handshake() + SocketChannel.open().use { control -> + val streams = mutableListOf() + try { + connect(control, target, cookie) + readState(control, machine) + write(control, Iperf3Protocol.frame(Iperf3Protocol.parameters(options))) + readState(control, machine) + controlStep { + repeat(options.streams) { + val stream = SocketChannel.open() + streams.add(stream) + connect(stream, target, cookie) + } + } + readState(control, machine) + readState(control, machine) + val counts = LongArray(options.streams) + val budget = Iperf3ReceiveBudget(options.payloadLimitBytes) + val samples = transfer(control, machine, streams, options, counts, budget, sample) + write(control, byteArrayOf(machine.send(Iperf3State.TEST_END))) + if (options.reverse) receiveState(control, machine, drainUntilState(control, streams, budget)) + else readState(control, machine) + write(control, Iperf3Protocol.frame(Iperf3Protocol.results(options, counts, samples.last().elapsedMs))) + val result = controlStep { + val size = Iperf3Protocol.payloadLength(read(control, 4)) + Iperf3Protocol.decode(read(control, size)) + } + val retransmits = Iperf3Protocol.retransmits(result, options.streams) + val local = requireNotNull(summarizeThroughput(samples, minWarmupMs = 0, maxWarmupMs = 0)) + val receiver = if (options.reverse) null else Iperf3Protocol.receiver(result, options) + val measurement = if (receiver == null) { + Iperf3Measurement(local, retransmits, counts.count { it > 0 }) + } else { + val summary = local.copy(mbps = receiver.mbps, measuredMs = receiver.elapsedMs.roundToLong(), + totalBytes = receiver.bytes) + Iperf3Measurement(summary, retransmits, receiver.workingStreams) + } + readState(control, machine) + write(control, byteArrayOf(machine.send(Iperf3State.IPERF_DONE))) + measurement + } catch (failure: Exception) { + if (control.isConnected && failure !is Iperf3ServerFailure) { + // One nonblocking attempt even on cancellation, control timeout or malformed results. + runCatching { control.write(ByteBuffer.wrap(byteArrayOf(Iperf3State.CLIENT_TERMINATE.wire.toByte()))) } + } + throw failure + } finally { + streams.forEach { it.close() } + } + } + } + + private suspend fun connect(channel: SocketChannel, target: InetSocketAddress, cookie: ByteArray) = controlStep { + channel.configureBlocking(false) + bind(channel.socket()) + if (!channel.connect(target)) while (!channel.finishConnect()) delay(2) + write(channel, cookie) + } + + private suspend fun readState(control: SocketChannel, machine: Iperf3Handshake) = + receiveState(control, machine, read(control, 1).single()) + + internal suspend fun drainUntilState(control: ReadableByteChannel, streams: List, + budget: Iperf3ReceiveBudget): Byte = controlStep { + // Unblock a pending server write, even if a different stream is already closed. + val active = streams.toMutableList() + val discard = ByteBuffer.allocateDirect(Iperf3Protocol.BLOCK_BYTES) + // Bound discarded data even without -b. Once drained, wait only on the control channel. + var drainLeft = 8 * 1024 * 1024 * streams.size + val next = ByteBuffer.allocate(1) + while (next.hasRemaining()) { + currentCoroutineContext().ensureActive() + when (control.read(next)) { + -1 -> throw EOFException() + 0 -> { + var progressed = false + val iterator = active.iterator() + while (iterator.hasNext() && drainLeft > 0) { + val stream = iterator.next() + discard.clear() + discard.limit(minOf(discard.capacity(), drainLeft)) + val bytes = budget.read(discard) { buffer -> + runCatching { stream.read(buffer) }.getOrElse { if (it is IOException) -1 else throw it } + } + if (bytes < 0) iterator.remove() + if (bytes > 0) { + drainLeft -= bytes + progressed = true + } + } + if (!progressed) delay(2) + } + } + } + next.get(0) + } + + private suspend fun receiveState(control: SocketChannel, machine: Iperf3Handshake, state: Byte) { + if (state.toInt() == Iperf3State.SERVER_ERROR.wire) { + try { + read(control, 8) + } catch (_: IOException) { + // The state is authoritative even when the two diagnostic integers are truncated. + } + } + machine.receive(state) + } + + private suspend fun read(channel: SocketChannel, size: Int): ByteArray = controlStep { + val buffer = ByteBuffer.allocate(size) + while (buffer.hasRemaining()) { + when (channel.read(buffer)) { + -1 -> throw EOFException() + 0 -> delay(2) + } + } + buffer.array() + } + + private suspend fun write(channel: SocketChannel, bytes: ByteArray) = controlStep { + val buffer = ByteBuffer.wrap(bytes) + while (buffer.hasRemaining()) if (channel.write(buffer) == 0) delay(2) + } + + private suspend fun controlStep(block: suspend () -> T): T = + withTimeoutOrNull(10_000) { block() } ?: throw SocketTimeoutException() + + /** All streams progress concurrently on a single IO worker. A blocked stream never holds the timer. */ + private suspend fun transfer(control: SocketChannel, machine: Iperf3Handshake, streams: List, + options: Iperf3Options, counts: LongArray, budget: Iperf3ReceiveBudget, sample: (ByteSample) -> Unit): List { + val buffer = ByteBuffer.allocateDirect(options.blockBytes) + if (!options.reverse) buffer.put(Random.nextBytes(buffer.capacity())) + val state = ByteBuffer.allocate(1) + val samples = ArrayList(options.seconds) + val start = System.nanoTime() + var nextSample = 1_000L + val duration = options.seconds * 1_000L + while (true) { + currentCoroutineContext().ensureActive() + val elapsed = (System.nanoTime() - start) / 1_000_000 + if (elapsed >= nextSample || elapsed >= duration) { + val point = ByteSample(elapsed, counts.sum()) + samples.add(point) + sample(point) + nextSample = (elapsed / 1_000 + 1) * 1_000 + } + if (elapsed >= duration) return samples + when (control.read(state)) { + -1 -> throw EOFException() + 1 -> receiveState(control, machine, state.get(0)) + } + + var progressed = false + for ((index, stream) in streams.withIndex()) { + buffer.clear() + if (!options.reverse && options.bitsPerSecond > 0) { + // -b is per stream. Use at most 5 ms of credit ahead of the clock. + val allowance = options.bitsPerSecond * minOf(duration, elapsed + 5) / 8_000 - counts[index] + if (allowance <= 0) continue + buffer.limit(minOf(buffer.capacity().toLong(), allowance).toInt()) + } + val bytes = if (options.reverse) budget.read(buffer, stream::read) else stream.write(buffer) + if (bytes < 0) throw EOFException() + counts[index] += bytes.toLong() + if (bytes > 0) progressed = true + } + if (!progressed) delay(2) + } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Form.kt b/androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Form.kt new file mode 100644 index 0000000..d0f86f3 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Form.kt @@ -0,0 +1,59 @@ +package cz.netkit.app.speed + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.FilterChip +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.KeyboardType +import cz.netkit.app.R +import cz.netkit.app.ui.SectionCard +import cz.netkit.shared.speed.Iperf3Options +import cz.netkit.shared.speed.validIperf3Host + +private val iperfRateRange = "0.01".toBigDecimal().."1000000".toBigDecimal() + +data class Iperf3Form(val host: String = "", val port: String = "5201", val streams: String = "1", + val seconds: String = "10", val reverse: Boolean = false, val rateMbps: String = "") { + internal val rateBitsPerSecond: Long? get() { + if (rateMbps.isEmpty()) return 0L + val mbps = rateMbps.replace(',', '.').toBigDecimalOrNull() ?: return null + if (mbps.signum() == 0) return 0L + return mbps.takeIf { it in iperfRateRange }?.movePointRight(6)?.toLong() + } + + val options: Iperf3Options? get() { + if (!validIperf3Host(host) || port.toIntOrNull() !in 1..65535) return null + val count = streams.toIntOrNull()?.takeIf { it in 1..8 } ?: return null + val duration = seconds.toIntOrNull()?.takeIf { it in 3..30 } ?: return null + val rate = rateBitsPerSecond ?: return null + return Iperf3Options(count, duration, reverse, rate) + } +} + +@Composable +internal fun Iperf3Settings(form: Iperf3Form, enabled: Boolean, change: (Iperf3Form) -> Unit) { + SectionCard(stringResource(R.string.iperf_title)) { + @Composable fun field(value: String, label: Int, tag: String, keyboard: KeyboardType, edit: (String) -> Unit) { + OutlinedTextField(value, edit, Modifier.fillMaxWidth().testTag(tag), enabled = enabled, singleLine = true, + label = { Text(stringResource(label)) }, keyboardOptions = KeyboardOptions(keyboardType = keyboard)) + } + field(form.host, R.string.iperf_host, "iperf_host", KeyboardType.Uri) { if (it.length <= 253) change(form.copy(host = it.trim())) } + field(form.port, R.string.iperf_port, "iperf_port", KeyboardType.Number) { if (it.length <= 5) change(form.copy(port = it)) } + field(form.streams, R.string.iperf_streams, "iperf_streams", KeyboardType.Number) { if (it.length <= 2) change(form.copy(streams = it)) } + field(form.seconds, R.string.iperf_seconds, "iperf_seconds", KeyboardType.Number) { if (it.length <= 2) change(form.copy(seconds = it)) } + OutlinedTextField(form.rateMbps, { if (it.length <= 16) change(form.copy(rateMbps = it)) }, + Modifier.fillMaxWidth().testTag("iperf_rate"), enabled = enabled, singleLine = true, + label = { Text(stringResource(R.string.iperf_rate)) }, isError = form.rateBitsPerSecond == null, + supportingText = { Text(stringResource(R.string.iperf_rate_range)) }, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)) + FilterChip(selected = form.reverse, onClick = { change(form.copy(reverse = !form.reverse)) }, enabled = enabled, + label = { Text(stringResource(if (form.reverse) R.string.iperf_reverse else R.string.iperf_forward)) }, + modifier = Modifier.testTag("iperf_reverse")) + Text(stringResource(R.string.iperf_load)) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/speed/SignalHost.kt b/androidApp/src/main/kotlin/cz/netkit/app/speed/SignalHost.kt index 9ab76f6..36ba2c8 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/speed/SignalHost.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/speed/SignalHost.kt @@ -10,6 +10,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import cz.netkit.app.R +import cz.netkit.app.cellular.CellDetailViewModel import cz.netkit.app.ui.SegmentedTabs import cz.netkit.app.ui.Spacing import cz.netkit.app.wifi.live.SignalScreen @@ -24,7 +25,9 @@ import cz.netkit.app.wifi.live.WifiLiveViewModel */ @Composable fun SignalHost(live: WifiLiveViewModel, speed: SpeedTestViewModel, modifier: Modifier = Modifier, - updateCard: (@Composable () -> Unit)? = null, onOpenAbout: (() -> Unit)? = null) { + updateCard: (@Composable () -> Unit)? = null, onOpenAbout: (() -> Unit)? = null, onOpenSettings: (() -> Unit)? = null, + cellDetail: CellDetailViewModel? = null, + onRdap: ((String) -> Unit)? = null) { var segment by rememberSaveable { mutableIntStateOf(0) } Column(modifier) { SegmentedTabs( @@ -33,7 +36,8 @@ fun SignalHost(live: WifiLiveViewModel, speed: SpeedTestViewModel, modifier: Mod Modifier.padding(horizontal = Spacing.normal, vertical = Spacing.small), testTags = listOf("signal_segment_live", "speed_segment"), ) - if (segment == 0) SignalScreen(live, Modifier.weight(1f), topCard = updateCard, onOpenAbout = onOpenAbout) + if (segment == 0) SignalScreen(live, Modifier.weight(1f), topCard = updateCard, onOpenAbout = onOpenAbout, + onOpenSettings = onOpenSettings, cellDetailModel = cellDetail, onRdap = onRdap) else SpeedTestScreen(speed, Modifier.weight(1f)) } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedDial.kt b/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedDial.kt index cf7ac65..0c94b2e 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedDial.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedDial.kt @@ -36,6 +36,7 @@ import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import cz.netkit.app.ui.motion.LocalReduceMotion +import cz.netkit.app.ui.spokenStatus import cz.netkit.app.ui.theme.NetKitTheme import cz.netkit.app.ui.theme.NetKitType import cz.netkit.shared.speed.SPEED_DIAL_LABELS @@ -146,6 +147,7 @@ fun SpeedReadout( phaseLabel: String, phaseColor: Color, modifier: Modifier = Modifier, + statusDescription: String = phaseLabel, ) { val colors = NetKitTheme.colors val locale = LocalConfiguration.current.locales[0] ?: Locale.getDefault() @@ -178,7 +180,7 @@ fun SpeedReadout( verticalAlignment = Alignment.CenterVertically, ) { Box(Modifier.size(8.dp).background(phaseColor, CircleShape)) - Text(phaseLabel, style = NetKitType.valueSmall, color = colors.muted, textAlign = TextAlign.Center) + Text(phaseLabel, Modifier.spokenStatus(statusDescription), style = NetKitType.valueSmall, color = colors.muted, textAlign = TextAlign.Center) } } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedHttp.kt b/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedHttp.kt index ee217fc..56af4de 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedHttp.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedHttp.kt @@ -32,7 +32,7 @@ enum class SpeedFailureKind { NO_NETWORK, NETWORK_LOST, DNS, CONNECT, TLS, TIMEOUT, HTTP_STATUS, PROTOCOL, /** The server answers, but not like a LibreSpeed backend (HTML/text, tiny garbage, non-empty empty.php). */ NOT_LIBRESPEED, - NO_CAPACITY, NO_SERVER, NO_DATA, + NO_CAPACITY, NO_SERVER, NO_DATA, IPERF_DENIED, IPERF_TERMINATED, IPERF_SERVER_ERROR, IPERF_LIMIT_EXCEEDED, } internal class SpeedTestFailure(val kind: SpeedFailureKind, val httpCode: Int? = null, cause: Throwable? = null) : diff --git a/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedShare.kt b/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedShare.kt new file mode 100644 index 0000000..39af933 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedShare.kt @@ -0,0 +1,97 @@ +package cz.netkit.app.speed + +import android.widget.Toast +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.toggleable +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.compose.ui.unit.dp +import cz.netkit.app.BuildConfig +import cz.netkit.app.R +import cz.netkit.app.overview.reportLabels +import cz.netkit.app.ssh.netKitSwitchColors +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.shareText +import cz.netkit.app.ui.theme.NetKitShape +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.speed.SpeedRecord +import cz.netkit.shared.report.speedShareText + +/** The stored record of the run on screen (zadání 47 §4); null while running or when nothing was stored. */ +internal fun shareableRecord(state: SpeedUiState): SpeedRecord? = + if (state.running) null else state.startedAtMs?.let { start -> state.history.firstOrNull { it.timestampMs == start } } + +/** + * Share text of one speed-test / iperf3 result: preview, SSID off by default, then the system + * share sheet. Nothing is sent by the app itself. + */ +@Composable +internal fun SpeedShareDialog(record: SpeedRecord, onDismiss: () -> Unit) { + val colors = NetKitTheme.colors + val context = LocalContext.current + val configuration = LocalConfiguration.current + var includeSsid by rememberSaveable { mutableStateOf(false) } + val labels = remember(configuration) { reportLabels(context) } + val hasSsid = !record.ssid.isNullOrBlank() + val text = remember(record, includeSsid, labels) { speedShareText(record, labels, includeSsid && hasSsid) } + val chooser = stringResource(R.string.speed_share_chooser) + AlertDialog( + onDismissRequest = onDismiss, + containerColor = colors.surface, + modifier = Modifier.testTag("speed_share_dialog").semantics { testTagsAsResourceId = BuildConfig.DEBUG }, + title = { Text(stringResource(R.string.speed_share_title), style = NetKitType.panelTitle, color = colors.text) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { + Text(stringResource(R.string.speed_share_note), style = NetKitType.label, color = colors.muted) + Row( + Modifier.fillMaxWidth().heightIn(min = 48.dp) + .toggleable(value = includeSsid && hasSsid, enabled = hasSsid, role = Role.Switch) { includeSsid = it } + .testTag("speed_share_include_ssid"), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium), + ) { + Text(stringResource(R.string.speed_share_include_ssid), Modifier.weight(1f), style = NetKitType.body, + color = if (hasSsid) colors.text else colors.dim) + Switch(checked = includeSsid && hasSsid, onCheckedChange = null, enabled = hasSsid, colors = netKitSwitchColors()) + } + Box(Modifier.fillMaxWidth().heightIn(max = 220.dp).background(colors.surface2, NetKitShape.nested) + .verticalScroll(rememberScrollState()).padding(Spacing.medium).testTag("speed_share_preview")) { + Text(text, style = NetKitType.addressFor(NetKitType.label), color = colors.text) + } + } + }, + confirmButton = { + TextButton({ + if (shareText(context, chooser, text)) onDismiss() + else Toast.makeText(context, R.string.speed_share_failed, Toast.LENGTH_SHORT).show() + }, Modifier.testTag("speed_share_confirm")) { Text(stringResource(R.string.speed_share_confirm), color = colors.accent) } + }, + dismissButton = { TextButton(onDismiss) { Text(stringResource(R.string.speed_share_cancel), color = colors.muted) } }, + ) +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestScreen.kt index c620eb7..e2cb8e8 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestScreen.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestScreen.kt @@ -31,6 +31,7 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.shape.CircleShape @@ -42,7 +43,9 @@ import androidx.compose.material3.OutlinedTextFieldDefaults import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable +import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable @@ -66,14 +69,14 @@ import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.testTagsAsResourceId -import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import cz.netkit.app.BuildConfig @@ -83,6 +86,7 @@ import cz.netkit.app.overview.ratText import cz.netkit.app.overview.signed import cz.netkit.shared.cellular.CellRat import cz.netkit.app.ui.InfoNote +import cz.netkit.app.ui.KeepScreenOn import cz.netkit.app.ui.KeyValue import cz.netkit.app.ui.KeyValueRow import cz.netkit.app.ui.KeyValueRows @@ -93,6 +97,9 @@ import cz.netkit.app.ui.PrimaryButton import cz.netkit.app.ui.ScreenHeader import cz.netkit.app.ui.SectionCard import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.speedSummary +import cz.netkit.app.ui.spoken +import cz.netkit.app.ui.OffscreenRunSummary import cz.netkit.app.ui.StatusBanner import cz.netkit.app.ui.StatusKind import cz.netkit.app.ui.Tag @@ -115,6 +122,7 @@ import cz.netkit.shared.speed.SPEED_DOWNLOAD_STREAMS import cz.netkit.shared.speed.SPEED_HISTORY_MAX import cz.netkit.shared.speed.SPEED_SAMPLE_MS import cz.netkit.shared.speed.SPEED_UPLOAD_STREAMS +import cz.netkit.shared.speed.SpeedDataEstimate import cz.netkit.shared.speed.SpeedEngine import cz.netkit.shared.speed.SpeedRecord import cz.netkit.shared.speed.bufferbloatGrade @@ -139,6 +147,8 @@ import java.util.Locale @Composable fun SpeedTestScreen(viewModel: SpeedTestViewModel, modifier: Modifier = Modifier) { val state by viewModel.state.collectAsStateWithLifecycle() + // Zadání 46 §4: a running LibreSpeed, NDT7 or iperf3 test keeps the display on. + KeepScreenOn(state.running) val context = LocalContext.current LifecycleResumeEffect(Unit) { viewModel.setActive(true) @@ -146,10 +156,15 @@ fun SpeedTestScreen(viewModel: SpeedTestViewModel, modifier: Modifier = Modifier onPauseOrDispose { if (context.findActivity()?.isChangingConfigurations != true) viewModel.setActive(false) } } var customDialog by rememberSaveable { mutableStateOf(false) } + var shareOpen by rememberSaveable { mutableStateOf(false) } + val shareRecord = shareableRecord(state) val finished = !state.running && state.engine != null + val listState = rememberLazyListState() + OffscreenRunSummary(state.running, speedSummary(state).spoken(), listState, "measure") LazyColumn( modifier.fillMaxSize().testTag("speed_screen"), + state = listState, contentPadding = PaddingValues(Spacing.normal), verticalArrangement = Arrangement.spacedBy(Spacing.normal), ) { @@ -160,7 +175,9 @@ fun SpeedTestScreen(viewModel: SpeedTestViewModel, modifier: Modifier = Modifier val network = stringResource(state.networkKind?.let(::netKindLabel) ?: R.string.net_kind_none) ScreenHeader(stringResource(R.string.speed_title), stringResource(R.string.speed_subtitle_network, network), trailing = live) } - item(key = "measure") { MeasurementCard(state, onStart = viewModel::start, onStop = viewModel::stop) } + item(key = "measure") { + MeasurementCard(state, onStart = viewModel::start, onStop = viewModel::stop, onShare = shareRecord?.let { { shareOpen = true } }) + } if (state.storeCorrupt) item(key = "store") { StatusBanner(stringResource(R.string.speed_store_failed), StatusKind.WARNING) } state.failure?.let { failure -> item(key = "failure") { @@ -179,9 +196,17 @@ fun SpeedTestScreen(viewModel: SpeedTestViewModel, modifier: Modifier = Modifier if (finished && (state.idle != null || state.loadedDownload != null || state.loadedUpload != null)) { item(key = "latency") { LatencyCard(state) } } - if (finished && (state.downloadPoints.isNotEmpty() || state.uploadPoints.isNotEmpty())) { + if ((finished || state.engine == SpeedEngine.IPERF3) && (state.downloadPoints.isNotEmpty() || state.uploadPoints.isNotEmpty())) { item(key = "trace") { TraceCard(state) } } + val retransmits = state.retransmits + if (state.phase == SpeedPhase.DONE && state.engine == SpeedEngine.IPERF3 && retransmits != null) { + item(key = "iperf_retransmits") { + SectionCard(stringResource(R.string.iperf_server_view)) { + KeyValueRows(listOf(KeyValue(stringResource(R.string.iperf_retransmits), retransmits.toString()))) + } + } + } if (finished && state.engine == SpeedEngine.NDT7 && (state.ndt7Download != null || state.ndt7Upload != null)) { item(key = "ndt7") { Ndt7Card(state) } } @@ -192,10 +217,20 @@ fun SpeedTestScreen(viewModel: SpeedTestViewModel, modifier: Modifier = Modifier item(key = "servers") { ServerCard(state, onSelect = viewModel::select, onAdd = { customDialog = true }, onRemove = viewModel::removeCustomServer) } + if (state.selectedChoice?.engine == SpeedEngine.IPERF3) item(key = "iperf_settings") { + Iperf3Settings(state.iperf, state.loaded && !state.running, viewModel::setIperfForm) + } item(key = "history") { HistoryCard(state.history, enabled = !state.running, onClear = viewModel::clearHistory) } item(key = "note") { InfoNote(stringResource(R.string.speed_note_summary), stringResource(R.string.speed_note_detail)) } } + state.iperfTargetPrompt?.let { target -> + NetKitDialog("iperf_target", viewModel::stop, stringResource(R.string.lan_confirm_title), + confirm = { PrimaryButton(stringResource(R.string.lan_confirm), viewModel::acceptIperfTarget) }, + dismiss = { NeutralButton(stringResource(R.string.speed_custom_cancel), viewModel::stop) }) { + Text(stringResource(R.string.iperf_confirm, target)) + } + } if (state.consentPending) { NetKitDialog( tag = "speed_consent", @@ -208,6 +243,7 @@ fun SpeedTestScreen(viewModel: SpeedTestViewModel, modifier: Modifier = Modifier ) { Text(stringResource(R.string.speed_consent_text), style = NetKitType.body, color = NetKitTheme.colors.muted) } } state.meteredPrompt?.let { prompt -> MeteredDialog(prompt, onAccept = viewModel::acceptMetered, onDismiss = viewModel::dismissMetered) } + if (shareOpen && shareRecord != null) SpeedShareDialog(shareRecord, onDismiss = { shareOpen = false }) if (customDialog) { CustomServerDialog(onDismiss = { customDialog = false }, onSubmit = { text -> viewModel.setCustomServer(text).also { if (it == null) customDialog = false } @@ -218,41 +254,43 @@ fun SpeedTestScreen(viewModel: SpeedTestViewModel, modifier: Modifier = Modifier // --- Measurement card --------------------------------------------------------------------------- @Composable -private fun phaseColor(phase: SpeedPhase): Color { +private fun phaseColor(state: SpeedUiState): Color { val colors = NetKitTheme.colors - return when (phase) { - SpeedPhase.IDLE, SpeedPhase.CANCELLED -> colors.dim + return when (state.phase) { + SpeedPhase.IDLE, SpeedPhase.CANCELLED -> colors.muted SpeedPhase.PREPARING, SpeedPhase.LOCATING, SpeedPhase.LATENCY -> colors.accent - SpeedPhase.DOWNLOAD, SpeedPhase.DONE -> colors.info + SpeedPhase.DOWNLOAD -> colors.info + SpeedPhase.DONE -> if (state.uploadOnlyResult) colors.violet else colors.info SpeedPhase.UPLOAD -> colors.violet SpeedPhase.FAILED -> colors.err } } +private val SpeedUiState.uploadOnlyResult get() = download == null && upload != null + @StringRes -private fun phaseLabel(phase: SpeedPhase): Int = when (phase) { +private fun phaseLabel(state: SpeedUiState): Int = when (state.phase) { SpeedPhase.IDLE -> R.string.speed_phase_idle SpeedPhase.PREPARING -> R.string.speed_phase_preparing SpeedPhase.LOCATING -> R.string.speed_phase_locating SpeedPhase.LATENCY -> R.string.speed_phase_latency SpeedPhase.DOWNLOAD -> R.string.speed_phase_download SpeedPhase.UPLOAD -> R.string.speed_phase_upload - SpeedPhase.DONE -> R.string.speed_phase_done + SpeedPhase.DONE -> if (state.uploadOnlyResult) R.string.speed_phase_done_upload else R.string.speed_phase_done SpeedPhase.FAILED -> R.string.speed_phase_failed SpeedPhase.CANCELLED -> R.string.speed_phase_cancelled } @Composable -private fun MeasurementCard(state: SpeedUiState, onStart: () -> Unit, onStop: () -> Unit) { +internal fun MeasurementCard(state: SpeedUiState, onStart: () -> Unit, onStop: () -> Unit, onShare: (() -> Unit)? = null) { val colors = NetKitTheme.colors val phase = state.phase - // Live value of the running direction; after a finished test the final download (prototype "Hotovo · stahování"). val shown: Double? = when (phase) { SpeedPhase.DOWNLOAD, SpeedPhase.UPLOAD -> state.liveMbps - SpeedPhase.DONE -> state.download?.mbps + SpeedPhase.DONE -> state.download?.mbps ?: state.upload?.mbps else -> null } - val color = phaseColor(phase) + val color = phaseColor(state) val unit = stringResource(R.string.speed_unit_mbps) Panel(Modifier.testTag("speed_result")) { Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { @@ -262,7 +300,9 @@ private fun MeasurementCard(state: SpeedUiState, onStart: () -> Unit, onStop: () color = if (phase == SpeedPhase.FAILED) colors.dim else color, description = stringResource(R.string.speed_dial_description, shown?.let(::mbpsText) ?: stringResource(R.string.speed_no_value)), ) - SpeedReadout(shown?.toFloat(), unit, stringResource(phaseLabel(phase)), color, Modifier.testTag("speed_phase")) + val phaseText = stringResource(phaseLabel(state)) + SpeedReadout(shown?.toFloat(), unit, phaseText, color, Modifier.testTag("speed_phase"), + statusDescription = speedSummary(state).spoken().ifEmpty { phaseText }) } PhaseTiles(state) if (state.running) { @@ -270,13 +310,16 @@ private fun MeasurementCard(state: SpeedUiState, onStart: () -> Unit, onStop: () } else { PrimaryButton( stringResource(if (phase == SpeedPhase.IDLE) R.string.speed_start else R.string.speed_restart), onStart, - Modifier.fillMaxWidth().testTag("speed_start"), enabled = state.loaded && state.selectedChoice != null, + Modifier.fillMaxWidth().testTag("speed_start"), enabled = state.loaded && state.selectedChoice != null && + (state.selectedChoice?.engine != SpeedEngine.IPERF3 || state.iperf.options != null), ) + // Zadání 47 §4: share the stored result of this run as text. + onShare?.let { NeutralButton(stringResource(R.string.speed_share), it, Modifier.fillMaxWidth().testTag("speed_share")) } } } } -private class PhaseTileData(val label: String, val value: String?, val unit: String, val color: Color, val active: Boolean, +private class PhaseTileData(val label: String, val value: AnnotatedString, val color: Color, val active: Boolean, val progress: Float?, val tag: String?) /** Latency / download / upload in a row of three; stacked as label–value rows on a narrow card or large font. */ @@ -285,18 +328,35 @@ private fun PhaseTiles(state: SpeedUiState) { val colors = NetKitTheme.colors val ms = stringResource(R.string.speed_unit_ms) val mbps = stringResource(R.string.speed_unit_mbps) + val missing = stringResource(R.string.speed_no_value) + val unitStyle = NetKitType.unit.toSpanStyle().copy(color = colors.muted) + fun reading(number: String?, unit: String) = buildAnnotatedString { + append(number ?: missing) + append(' ') + withStyle(unitStyle) { append(unit) } + } val tiles = listOf( - PhaseTileData(stringResource(R.string.speed_tile_latency), state.idle?.medianMs?.let(::msText), ms, colors.accent, + PhaseTileData(stringResource(R.string.speed_tile_latency), reading(state.idle?.medianMs?.let(::msText), ms), colors.accent, state.phase == SpeedPhase.LATENCY, null, null), - PhaseTileData(stringResource(R.string.speed_download), state.download?.mbps?.let(::mbpsText), mbps, colors.info, + PhaseTileData(stringResource(R.string.speed_download), reading(state.download?.mbps?.let(::mbpsText), mbps), colors.info, state.phase == SpeedPhase.DOWNLOAD, state.phaseProgress, "speed_download"), - PhaseTileData(stringResource(R.string.speed_upload), state.upload?.mbps?.let(::mbpsText), mbps, colors.violet, + PhaseTileData(stringResource(R.string.speed_upload), reading(state.upload?.mbps?.let(::mbpsText), mbps), colors.violet, state.phase == SpeedPhase.UPLOAD, state.phaseProgress, "speed_upload"), ) - val fontScale = LocalDensity.current.fontScale + val measurer = rememberTextMeasurer() + val density = LocalDensity.current BoxWithConstraints(Modifier.fillMaxWidth()) { - // Three labels like "Odesílání" need ~280 dp at font scale 1.0; below that the row would break words. - if (maxWidth >= 280.dp * fontScale) { + val innerWidth = with(density) { + (constraints.maxWidth - Spacing.small.roundToPx() * (tiles.size - 1)) / tiles.size - 2 * Spacing.medium.roundToPx() + } + val fits = tiles.all { + measurer.measure(it.value, NetKitType.metric, softWrap = false).size.width <= innerWidth && + measurer.measure(it.label, NetKitType.tag, softWrap = false).size.width <= innerWidth + } + // Keep a running test stacked after its first overflow, including when scrolled off screen. + var holdColumn by key(state.startedAtMs, state.running, constraints.maxWidth) { rememberSaveable { mutableStateOf(false) } } + if (state.running && !fits && !holdColumn) SideEffect { holdColumn = true } + if (fits && !holdColumn) { Row(Modifier.fillMaxWidth().height(IntrinsicSize.Min), horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { tiles.forEach { PhaseTile(it, stacked = false, Modifier.weight(1f).fillMaxHeight()) } } @@ -311,23 +371,18 @@ private fun PhaseTiles(state: SpeedUiState) { @Composable private fun PhaseTile(tile: PhaseTileData, stacked: Boolean, modifier: Modifier) { val colors = NetKitTheme.colors - val value = buildAnnotatedString { - append(tile.value ?: stringResource(R.string.speed_no_value)) - append(' ') - withStyle(SpanStyle(fontSize = 11.5.sp, fontWeight = FontWeight.SemiBold, color = colors.muted, letterSpacing = 0.sp)) { append(tile.unit) } - } Box(modifier.clip(NetKitShape.nested).background(colors.surface2) .then(if (tile.tag != null) Modifier.testTag(tile.tag) else Modifier).semantics(mergeDescendants = true) {}) { val padding = Modifier.padding(Spacing.medium) if (stacked) { Row(padding.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { Text(tile.label, Modifier.weight(1f), style = NetKitType.tag, color = colors.muted) - Text(value, style = NetKitType.metric, color = colors.text) + Text(tile.value, softWrap = false, maxLines = 1, style = NetKitType.metric, color = colors.text) } } else { Column(padding, verticalArrangement = Arrangement.spacedBy(2.dp)) { Text(tile.label, style = NetKitType.tag, color = colors.muted) - Text(value, style = NetKitType.metric, color = colors.text) + Text(tile.value, softWrap = false, maxLines = 1, style = NetKitType.metric, color = colors.text) } } if (tile.active) PhaseProgressLine(tile.progress, tile.color, Modifier.align(Alignment.BottomStart)) @@ -421,7 +476,7 @@ private fun gradeText(grade: BufferbloatGrade): String = when (grade) { */ @OptIn(ExperimentalLayoutApi::class) @Composable -private fun TraceCard(state: SpeedUiState) { +internal fun TraceCard(state: SpeedUiState) { val colors = NetKitTheme.colors val dash = stringResource(R.string.speed_no_value) val unit = stringResource(R.string.speed_unit_mbps) @@ -442,7 +497,7 @@ private fun TraceCard(state: SpeedUiState) { up.takeIf { it.isNotEmpty() }?.let { ChartLine(upLabel, it, colors.violet, dashed = true) }, ), capacity = maxOf(down.size, up.size, 2), - sampleIntervalMs = SPEED_SAMPLE_MS, + sampleIntervalMs = if (state.engine == SpeedEngine.IPERF3) 1000L else SPEED_SAMPLE_MS, range = null, ticks = null, unitLabel = unit, @@ -520,7 +575,11 @@ private fun ContextCard(state: SpeedUiState) { SectionCard(stringResource(R.string.speed_context_section)) { KeyValueRows(listOfNotNull( KeyValue(stringResource(R.string.speed_context_engine), stringResource( - if (state.engine == SpeedEngine.NDT7) R.string.speed_engine_ndt7 else R.string.speed_engine_librespeed)), + when (state.engine) { + SpeedEngine.IPERF3 -> R.string.iperf_title + SpeedEngine.NDT7 -> R.string.speed_engine_ndt7 + else -> R.string.speed_engine_librespeed + })), KeyValue(stringResource(R.string.speed_context_server), listOfNotNull(state.serverLabel, state.serverHost?.takeIf { it != state.serverLabel }).joinToString("\n").ifEmpty { dash }), state.ispText?.let { KeyValue(stringResource(R.string.speed_context_isp), it, monospace = true) }, @@ -552,11 +611,12 @@ private fun ServerCard(state: SpeedUiState, onSelect: (String) -> Unit, onAdd: ( Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { state.choices.forEachIndexed { index, choice -> ServerOption( - title = choice.name, + title = if (choice.engine == SpeedEngine.IPERF3) stringResource(R.string.iperf_title) else choice.name, subtitle = when (choice.engine) { SpeedEngine.LIBRESPEED -> stringResource(R.string.speed_server_librespeed, SPEED_DOWNLOAD_STREAMS.toString(), SPEED_UPLOAD_STREAMS.toString()) SpeedEngine.NDT7 -> stringResource(R.string.speed_server_ndt7) + SpeedEngine.IPERF3 -> stringResource(R.string.iperf_load) }, custom = choice.custom, selected = choice.id == selectedId, @@ -623,7 +683,8 @@ private fun HistoryCard(history: List, enabled: Boolean, onClear: ( } else { Column(Modifier.fillMaxWidth()) { history.forEachIndexed { index, record -> - val label = listOfNotNull(historyTime(record.timestampMs), record.serverName, stringResource(netKindLabel(record.measuredKind)), + val label = listOfNotNull(historyTime(record.timestampMs), + "iperf3".takeIf { record.engine == SpeedEngine.IPERF3 }, record.serverName, stringResource(netKindLabel(record.measuredKind)), partial.takeIf { record.partial }) .joinToString(" · ") val value = stringResource(R.string.speed_history_row, record.downloadMbps?.let(::mbpsText) ?: dash, @@ -734,7 +795,7 @@ private fun CustomServerDialog(onDismiss: () -> Unit, onSubmit: (String) -> Libr @Composable private fun MeteredDialog(prompt: MeteredPrompt, onAccept: () -> Unit, onDismiss: () -> Unit) { val locale = LocalConfiguration.current.locales[0] ?: Locale.getDefault() - val megabytes = remember(prompt.estimate.megabytes, locale) { NumberFormat.getIntegerInstance(locale).format(prompt.estimate.megabytes) } + val number = remember(locale) { NumberFormat.getIntegerInstance(locale) } NetKitDialog( tag = "speed_metered", onDismiss = onDismiss, @@ -743,10 +804,19 @@ private fun MeteredDialog(prompt: MeteredPrompt, onAccept: () -> Unit, onDismiss dismiss = { NeutralButton(stringResource(R.string.speed_metered_decline), onDismiss, Modifier.testTag("speed_metered_decline")) }, ) { Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { - Text(stringResource(if (prompt.kind == NetKind.CELLULAR) R.string.speed_metered_cellular else R.string.speed_metered_other, megabytes), - Modifier.testTag("speed_metered_estimate"), style = NetKitType.body, color = NetKitTheme.colors.text) - Text(stringResource(if (prompt.estimate.fromHistory) R.string.speed_metered_from_history else R.string.speed_metered_default), - style = NetKitType.label, color = NetKitTheme.colors.muted) + val estimate = prompt.estimate + val message = when (estimate) { + SpeedDataEstimate.Unlimited -> stringResource(R.string.iperf_metered_unlimited) + is SpeedDataEstimate.PayloadUpperBound -> stringResource(R.string.iperf_metered_limit, number.format(estimate.megabytes)) + is SpeedDataEstimate.Approximate -> stringResource( + if (prompt.kind == NetKind.CELLULAR) R.string.speed_metered_cellular else R.string.speed_metered_other, + number.format(estimate.megabytes)) + } + Text(message, Modifier.testTag("speed_metered_estimate"), style = NetKitType.body, color = NetKitTheme.colors.text) + if (estimate is SpeedDataEstimate.Approximate) { + Text(stringResource(if (estimate.fromHistory) R.string.speed_metered_from_history else R.string.speed_metered_default), + style = NetKitType.label, color = NetKitTheme.colors.muted) + } } } } @@ -776,6 +846,10 @@ private fun failureText(kind: SpeedFailureKind, code: Int?): String = when (kind SpeedFailureKind.NOT_LIBRESPEED -> stringResource(R.string.speed_error_not_librespeed) SpeedFailureKind.NO_CAPACITY -> stringResource(R.string.speed_error_no_capacity) SpeedFailureKind.NO_SERVER -> stringResource(R.string.speed_error_no_server) + SpeedFailureKind.IPERF_DENIED -> stringResource(R.string.iperf_denied) + SpeedFailureKind.IPERF_TERMINATED -> stringResource(R.string.iperf_terminated) + SpeedFailureKind.IPERF_SERVER_ERROR -> stringResource(R.string.iperf_server_error) + SpeedFailureKind.IPERF_LIMIT_EXCEEDED -> stringResource(R.string.iperf_limit_exceeded) SpeedFailureKind.NO_DATA -> stringResource(R.string.speed_error_no_data) } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt index 3206b99..b9ba703 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt @@ -1,9 +1,24 @@ package cz.netkit.app.speed +import cz.netkit.app.backup.ConfigFile import android.app.Application import android.content.Context import android.net.ConnectivityManager import android.net.Network +import android.net.InetAddresses +import cz.netkit.app.lan.LanBackend +import cz.netkit.app.lan.ToolRoute +import cz.netkit.shared.lan.Ipv4Subnet +import cz.netkit.shared.lan.requiresTargetConfirmation +import cz.netkit.app.settings.awaitInOwner +import cz.netkit.shared.speed.Iperf3Options +import cz.netkit.shared.speed.Iperf3ServerFailure +import cz.netkit.shared.speed.Iperf3State +import java.net.Inet4Address +import java.net.InetSocketAddress +import java.net.UnknownHostException +import java.io.IOException +import kotlinx.coroutines.CompletableDeferred import android.net.wifi.WifiManager import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope @@ -44,11 +59,15 @@ import cz.netkit.shared.speed.ndt7ServerView import cz.netkit.shared.speed.rateSeriesMbps import cz.netkit.shared.speed.summarizeThroughput import cz.netkit.shared.speed.withRecord +import cz.netkit.shared.speed.SpeedHistoryKind +import cz.netkit.shared.speed.withoutHistory +import cz.netkit.shared.speed.savedIperfTarget +import cz.netkit.shared.speed.withoutIperfTarget +import cz.netkit.shared.speed.withoutNdt7Consent import cz.netkit.shared.cellular.CellRat import cz.netkit.shared.cellular.CellularState import cz.netkit.shared.cellular.primaryDbm import cz.netkit.shared.net.NetKind -import java.io.File import java.util.Collections import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope @@ -79,11 +98,15 @@ private const val CELLULAR_SETTLE_MS = 2_000L private const val NDT7_MESSAGES_MAX = 500 /** - * A selectable server: LibreSpeed (preset or custom base URL) or M-Lab NDT7 (located per run). + * A selectable server: LibreSpeed URL, NDT7 discovery or the user-entered iperf3 endpoint. * [id] is stable across list changes (a custom server loading later does not shift the selection). */ data class SpeedServerChoice(val engine: SpeedEngine, val name: String, val baseUrl: String?, val custom: Boolean = false) { - val id: String get() = if (engine == SpeedEngine.NDT7) NDT7_CHOICE_ID else "librespeed:$baseUrl" + val id: String get() = when (engine) { + SpeedEngine.NDT7 -> NDT7_CHOICE_ID + SpeedEngine.IPERF3 -> "iperf3" + SpeedEngine.LIBRESPEED -> "librespeed:$baseUrl" + } } const val NDT7_CHOICE_ID = "ndt7" @@ -107,6 +130,9 @@ enum class SpeedPhase { IDLE, PREPARING, LOCATING, LATENCY, DOWNLOAD, UPLOAD, DO */ data class SpeedUiState( val choices: List = emptyList(), + val iperf: Iperf3Form = Iperf3Form(), + val iperfTargetPrompt: String? = null, + val retransmits: Long? = null, val selectedId: String? = null, /** The store (consent, custom server, history) has been read; starting is gated on it. */ val loaded: Boolean = false, @@ -137,6 +163,13 @@ data class SpeedUiState( val downloadStreams: DirectionStreams? = null, val uploadStreams: DirectionStreams? = null, val consentPending: Boolean = false, + /** The M-Lab notice was acknowledged (stored); the Settings screen can reset it (zadání 46). */ + val ndt7Acknowledged: Boolean = false, + /** + * The iperf3 server kept in the store (`host:port`, null = none), independent of the form being + * edited: Settings shows and forgets this one (zadání 46, revize kolo 1). + */ + val savedIperfTarget: String? = null, val networkKind: NetKind? = null, val measuredKind: NetKind? = null, val meteredPrompt: MeteredPrompt? = null, @@ -159,7 +192,7 @@ data class MeteredPrompt(val estimate: SpeedDataEstimate, val kind: NetKind, int * Speed test (M2): own LibreSpeed-protocol client and NDT7 (M-Lab). See docs/funkce/speedtest.md. * * Lifecycle: the screen calls `setActive(false)` on pause/dispose, which cancels a running test - * (every socket is closed via [CallRegistry]); nothing runs in background. All traffic is bound to + * and releases its transport; nothing runs in background. All traffic is bound to * the active (default) `Network` (sockets + DNS): Wi-Fi, mobile data, ethernet or VPN (M4). On a * metered network the user confirms the estimated data first; losing or replacing the network * mid-test ends the run as NETWORK_LOST. @@ -167,7 +200,7 @@ data class MeteredPrompt(val estimate: SpeedDataEstimate, val kind: NetKind, int class SpeedTestViewModel(application: Application) : AndroidViewModel(application) { private val connectivity = application.getSystemService(ConnectivityManager::class.java) private val wifiManager = application.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager - private val store = SpeedStore(File(application.noBackupFilesDir, "speedtest.json")) + private val store = SpeedStore(ConfigFile.SPEED.resolve(application)) private val userAgent = "NetKit/${BuildConfig.VERSION_NAME} (Android)" private val baseClient by lazy { speedHttpClient() } @@ -175,6 +208,8 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio val state: StateFlow = _state.asStateFlow() private var data = SpeedStoreData() + private val lan by lazy { LanBackend(application) } + private var targetConsent: CompletableDeferred? = null private var run: Job? = null private val monitor = ActiveNetworkMonitor(connectivity) @Volatile private var active: ActiveNetworkInfo? = null @@ -193,7 +228,8 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio viewModelScope.launch { val read = store.read() data = read.data - _state.update { it.copy(choices = choices(data.customUrl), history = data.records, storeCorrupt = read.corrupt, loaded = true) } + _state.update { it.copy(iperf = Iperf3Form(host = data.iperfHost, port = data.iperfPort.toString()), + choices = choices(data.customUrl), storeCorrupt = read.corrupt, loaded = true).withStore(data) } } } @@ -205,6 +241,7 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio ?.let { add(SpeedServerChoice(SpeedEngine.LIBRESPEED, it.name, it.baseUrl, custom = true)) } } add(SpeedServerChoice(SpeedEngine.NDT7, "M-Lab NDT7", null)) + add(SpeedServerChoice(SpeedEngine.IPERF3, "iperf3", null)) } /** `false` (screen paused/left) cancels a running test immediately. */ @@ -240,6 +277,12 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio persist { it.copy(customUrl = null) } } + fun setIperfForm(form: Iperf3Form) { + _state.update { if (it.running) it else it.copy(iperf = form, meteredPrompt = null) } + } + + fun acceptIperfTarget() { targetConsent?.complete(Unit) } + fun start() = start(confirmedMetered = null) private fun start(confirmedMetered: Network?) { @@ -247,6 +290,7 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio // Before the store is read the consent and custom server are unknown. if (current.running || !current.loaded) return val choice = current.selectedChoice ?: return + val options = if (choice.engine == SpeedEngine.IPERF3) current.iperf.options ?: return else Iperf3Options() if (choice.engine == SpeedEngine.NDT7 && data.ndt7ConsentMs == null) { _state.update { it.copy(consentPending = true) } return @@ -254,7 +298,7 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio // O-3: always the full test, but on a metered network only after an explicit confirmation. val network = active ?: connectivity.readActiveNetworkInfo() if (network != null && network.metered && network.network != confirmedMetered) { - val estimate = estimateSpeedTestData(choice.engine, data.records, network.kind) + val estimate = estimateSpeedTestData(choice.engine, data.records, network.kind, options) _state.update { it.copy(meteredPrompt = MeteredPrompt(estimate, network.kind, network.network)) } return } @@ -291,6 +335,43 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio persist { it.copy(records = emptyList()) } } + /** Settings (zadání 46 §3): removes one history group; false when the store could not be written. */ + suspend fun clearHistory(kind: SpeedHistoryKind): Boolean = persistNow { it.withoutHistory(kind) } + + /** + * Settings: forgets the stored iperf3 server and clears the form's host and port (other options + * stay). The write and the form change run together in the ViewModel scope (revize kolo 1). + */ + suspend fun forgetIperfTarget(): Boolean = awaitInOwner(viewModelScope) { + writeStore { it.withoutIperfTarget() }.also { written -> + if (written) _state.update { if (it.running) it else it.copy(iperf = it.iperf.copy(host = "", port = "5201")) } + } + } + + /** Settings: the M-Lab notice is shown again before the next NDT7 run. */ + suspend fun resetNdt7Consent(): Boolean = persistNow { it.withoutNdt7Consent() } + + /** Like [persist], but awaited: the write runs in the ViewModel scope, so leaving the caller does not cut it off. */ + private suspend fun persistNow(transform: (SpeedStoreData) -> SpeedStoreData): Boolean = + awaitInOwner(viewModelScope) { writeStore(transform) } + + /** One store update and the state derived from it; false (and storeCorrupt) when the write failed. */ + private suspend fun writeStore(transform: (SpeedStoreData) -> SpeedStoreData): Boolean { + return try { + data = store.update(transform) + _state.update { it.copy(storeCorrupt = false).withStore(data) } + true + } catch (cancel: CancellationException) { + throw cancel + } catch (_: Exception) { + _state.update { it.copy(storeCorrupt = true) } + false + } + } + + private fun SpeedUiState.withStore(stored: SpeedStoreData) = copy(history = stored.records, + ndt7Acknowledged = stored.ndt7ConsentMs != null, savedIperfTarget = stored.savedIperfTarget()) + override fun onCleared() { run?.cancel() super.onCleared() @@ -300,7 +381,7 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio viewModelScope.launch { try { data = store.update(transform) - _state.update { it.copy(history = data.records, storeCorrupt = false) } + _state.update { it.copy(storeCorrupt = false).withStore(data) } } catch (cancel: CancellationException) { throw cancel } catch (_: Exception) { @@ -315,7 +396,7 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio private fun launchRun(choice: SpeedServerChoice, confirmedMetered: Network?) { _state.update { - it.copy(phase = SpeedPhase.PREPARING, phaseProgress = null, liveMbps = null, downloadPoints = emptyList(), + it.copy(retransmits = null, phase = SpeedPhase.PREPARING, phaseProgress = null, liveMbps = null, downloadPoints = emptyList(), uploadPoints = emptyList(), idle = null, loadedDownload = null, loadedUpload = null, download = null, upload = null, ndt7Download = null, ndt7Upload = null, engine = choice.engine, serverLabel = if (choice.engine == SpeedEngine.LIBRESPEED) choice.name else null, @@ -353,15 +434,15 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio cellularState?.sims?.firstOrNull { it.isDataSim }?.let { sim -> _state.update { it.copy(cellular = SpeedCellularContext(sim.operatorName, sim.rat, primaryDbm(sim.signal))) } } - val client = baseClient.boundTo(network.network) coroutineScope { // Losing the measured network mid-test is reported as such, not as a socket error. val watcher = launch { watchNetwork(network.network, network.metered, this@coroutineScope) } try { when (choice.engine) { SpeedEngine.LIBRESPEED -> runLibreSpeed(LibreSpeedServer(choice.name, choice.baseUrl!!, hostOf(choice.baseUrl)), - client, snapshot) - SpeedEngine.NDT7 -> runNdt7(client, snapshot) + baseClient.boundTo(network.network), snapshot) + SpeedEngine.NDT7 -> runNdt7(baseClient.boundTo(network.network), snapshot) + SpeedEngine.IPERF3 -> runIperf3(network, _state.value.iperf) } } finally { watcher.cancel() @@ -387,7 +468,7 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio } finally { networkLost = false // Do not keep idle keep-alive connections to the test server after the run. - viewModelScope.launch(Dispatchers.IO) { baseClient.connectionPool.evictAll() } + if (choice.engine != SpeedEngine.IPERF3) viewModelScope.launch(Dispatchers.IO) { baseClient.connectionPool.evictAll() } } saveRecord(partial = !completed) } @@ -576,15 +657,83 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio } } + private suspend fun runIperf3(network: ActiveNetworkInfo, form: Iperf3Form) { + val options = requireNotNull(form.options) + val route = ToolRoute.active(network, null) + val address = try { + if (InetAddresses.isNumericAddress(form.host)) InetAddresses.parseNumericAddress(form.host) + else { + val addresses = lan.resolve(route, form.host) + addresses.firstOrNull { it is Inet4Address } ?: addresses.firstOrNull() ?: throw UnknownHostException() + } + } catch (_: IOException) { + throw SpeedTestFailure(SpeedFailureKind.DNS) + } + val port = form.port.toInt() + val target = InetSocketAddress(address, port) + fun endpoint(host: String) = if (':' in host) "[$host]:$port" else "$host:$port" + val numeric = requireNotNull(address.hostAddress) + val range = Ipv4Subnet.parse("$numeric/32") + val own = connectivity.getLinkProperties(network.network)?.linkAddresses.orEmpty() + .filter { it.prefixLength > 0 } + .mapNotNull { Ipv4Subnet.parse("${it.address.hostAddress}/${it.prefixLength}") } + if (range == null || own.none { !requiresTargetConfirmation(range, it) }) { + val decision = CompletableDeferred() + targetConsent = decision + _state.update { it.copy(iperfTargetPrompt = endpoint(numeric)) } + try { + decision.await() + } finally { + targetConsent = null + _state.update { it.copy(iperfTargetPrompt = null) } + } + } + val current = connectivity.readActiveNetworkInfo() + if (current?.network != network.network || (current.metered && !network.metered)) { + throw RunFailure(SpeedFailureKind.NETWORK_LOST, null) + } + persist { it.copy(iperfHost = form.host, iperfPort = port) } + val phase = if (options.reverse) SpeedPhase.DOWNLOAD else SpeedPhase.UPLOAD + _state.update { it.copy(serverLabel = endpoint(form.host), serverHost = numeric) } + val trace = ThroughputTrace() + val result = try { + Iperf3Client(network.network).measure(target, options) { point -> + trace.add(point.elapsedMs, point.bytes) + val points = chartPoints(trace.samples, capacity = options.seconds, slotMs = 1000) + val live = rateSeriesMbps(trace.samples).last() + _state.update { + it.copy(phase = phase, phaseProgress = (point.elapsedMs / (options.seconds * 1000f)).coerceAtMost(1f), + liveMbps = live, downloadPoints = if (options.reverse) points else emptyList(), + uploadPoints = if (options.reverse) emptyList() else points) + } + } + } catch (e: Iperf3ServerFailure) { + throw SpeedTestFailure(when (e.state) { + Iperf3State.ACCESS_DENIED -> SpeedFailureKind.IPERF_DENIED + Iperf3State.SERVER_TERMINATE -> SpeedFailureKind.IPERF_TERMINATED + else -> SpeedFailureKind.IPERF_SERVER_ERROR + }) + } catch (e: IOException) { + throw classifySpeedFailure(e) + } + val summary = result.summary + if (summary.totalBytes == 0L) throw SpeedTestFailure(SpeedFailureKind.NO_DATA) + val streams = DirectionStreams(options.streams, result.workingStreams) + _state.update { + if (options.reverse) it.copy(download = summary, downloadStreams = streams, retransmits = result.retransmits) + else it.copy(upload = summary, uploadStreams = streams, retransmits = result.retransmits) + } + } + private fun saveRecord(partial: Boolean) { val s = _state.value - val download = s.download ?: return + if (s.download == null && s.upload == null) return if (s.phase == SpeedPhase.CANCELLED) return val record = SpeedRecord( timestampMs = s.startedAtMs ?: System.currentTimeMillis(), engine = s.engine ?: return, serverName = (s.serverLabel ?: s.serverHost ?: "?").take(128), - downloadMbps = download.mbps, + downloadMbps = s.download?.mbps, uploadMbps = s.upload?.mbps, idleLatencyMs = s.idle?.medianMs, idleJitterMs = s.idle?.jitterMs, @@ -592,13 +741,14 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio loadedUploadMs = s.loadedUpload?.medianMs, serverDownloadMbps = s.ndt7Download?.appMbps, serverUploadMbps = s.ndt7Upload?.appMbps, + retransmits = s.retransmits, retransPercent = s.ndt7Download?.retransPercent?.coerceIn(0.0, 100.0), ssid = s.wifi?.ssid?.take(128), frequencyMhz = s.wifi?.frequencyMhz, rssiDbm = s.wifi?.rssiDbm, rxLinkMbps = s.wifi?.rxLinkMbps, txLinkMbps = s.wifi?.txLinkMbps, - partial = partial || s.upload == null || s.streamsDegraded, + partial = partial || (s.engine != SpeedEngine.IPERF3 && s.upload == null) || s.streamsDegraded, downloadStreams = s.downloadStreams?.working, uploadStreams = s.uploadStreams?.working, plannedDownloadStreams = s.downloadStreams?.planned, @@ -606,5 +756,12 @@ class SpeedTestViewModel(application: Application) : AndroidViewModel(applicatio networkKind = s.measuredKind, ) persist { it.withRecord(record) } + // Zadání 37: the result (and its Wi-Fi context) for the network status widget. + val wifi = s.wifi?.takeIf { record.measuredKind == NetKind.WIFI } + (getApplication() as? cz.netkit.app.wol.NetKitApplication)?.netStatus?.offerSpeed( + atMs = record.timestampMs, downloadMbps = record.downloadMbps, uploadMbps = record.uploadMbps, pingMs = record.idleLatencyMs, + wifi = wifi?.let { cz.netkit.shared.netstatus.NetStatusRadioReading(it.frequencyMhz, it.rssiDbm, it.rxLinkMbps, it.txLinkMbps) }, + ssid = wifi?.ssid, + ) } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleConnection.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleConnection.kt new file mode 100644 index 0000000..e581e48 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleConnection.kt @@ -0,0 +1,165 @@ +package cz.netkit.app.ssh + +import cz.netkit.shared.ssh.SshSession +import cz.netkit.shared.ssh.TelnetCodec +import java.io.Closeable +import java.io.InputStream +import java.net.InetSocketAddress +import java.net.Socket +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference +import kotlin.coroutines.resume +import kotlin.coroutines.resumeWithException +import kotlinx.coroutines.* +import kotlinx.coroutines.channels.Channel +import okio.buffer +import okio.sink + +interface TerminalConnection : SshSession { fun start() } + +internal interface ConsoleWire : Closeable { + val input: InputStream + fun write(text: String) + fun resize(columns: Int, rows: Int) {} + suspend fun sendBreak() { throw UnsupportedOperationException() } +} + +/** Reader and single ordered writer. Closing the wire wakes a blocked platform read. */ +internal class ConsoleConnection( + private val scope: CoroutineScope, + private val open: suspend () -> ConsoleWire, + private val onText: (String) -> Unit, private val onConnected: () -> Unit, + private val onEnd: (Boolean) -> Unit, +) : TerminalConnection { + private sealed interface Command { + data class Text(val text: String) : Command + data object Resize : Command + data object Break : Command + } + private val writes = Channel(32) + private val closed = AtomicBoolean() + private val wire = AtomicReference() + @Volatile private var size = 80 to 24 + private var job: Job? = null + + override fun start() { + check(job == null) + val failed = AtomicBoolean() + job = scope.launch(Dispatchers.IO) { + try { + val port = open() + wire.set(port) + ensureActive() + if (closed.get()) return@launch + size.let { port.resize(it.first, it.second) } + onConnected() + coroutineScope { + val writer = launch(Dispatchers.IO) { + try { + for (command in writes) { + size.let { port.resize(it.first, it.second) } + when (command) { + is Command.Text -> port.write(command.text) + Command.Break -> port.sendBreak() + Command.Resize -> Unit + } + } + } finally { closeWire() } + } + try { + val reader = port.input.reader(Charsets.UTF_8) + val chars = CharArray(4096) + while (isActive) { + val count = reader.read(chars) + if (count < 0) break + if (count > 0) onText(String(chars, 0, count)) + } + } finally { writer.cancel(); closeWire() } + } + } catch (_: TimeoutCancellationException) { + failed.set(true) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + failed.set(!closed.get()) + } finally { + closeWire() + } + } + // A cancelled job can finish before the IO dispatcher starts its body. + job?.invokeOnCompletion { + closed.set(true) + writes.cancel() + onEnd(failed.get()) + } + } + + override fun send(text: String) = !closed.get() && text.length <= 16384 && writes.trySend(Command.Text(text)).isSuccess + fun sendBreak() = !closed.get() && writes.trySend(Command.Break).isSuccess + override fun resize(columns: Int, rows: Int) { + size = columns to rows + // Every queued write is bounded. If full, the writer applies the latest size before the next write. + writes.trySend(Command.Resize) + } + private fun closeWire() { wire.getAndSet(null)?.let { runCatching { it.close() } } } + override fun close() { + closed.set(true) + job?.cancel() + writes.cancel() + scope.launch(Dispatchers.IO + NonCancellable) { closeWire() } + } +} + +internal class TelnetWire(private val socket: Socket) : ConsoleWire { + private val codec = TelnetCodec() + private val sink = socket.sink().also { it.timeout().timeout(5, TimeUnit.SECONDS) }.buffer() + private val source = socket.getInputStream() + private val raw = ByteArray(8192) + override val input = object : InputStream() { + override fun read(): Int { + val one = ByteArray(1) + return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 255 + } + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (len == 0) return 0 + while (true) { + val count = source.read(raw, 0, minOf(len, raw.size)) + if (count < 0) return -1 + val result = synchronized(codec) { codec.receive(raw, count).also { transmit(it.reply) } } + if (result.data.isNotEmpty()) { + result.data.copyInto(b, off) + return result.data.size + } + } + } + } + private fun transmit(bytes: ByteArray) { if (bytes.isNotEmpty()) { sink.write(bytes); sink.flush() } } + override fun write(text: String) = synchronized(codec) { + // The shared terminal Enter key emits a single CR. + transmit(TelnetCodec.encode((if (text == "\r") "\r\n" else text).encodeToByteArray())) + } + override fun resize(columns: Int, rows: Int) = synchronized(codec) { transmit(codec.resize(columns, rows)) } + override fun close() = socket.close() +} + +internal suspend fun openTelnet(host: String, port: Int): TelnetWire { + var last: java.io.IOException? = null + for (address in resolveSshHost(host)) { + currentCoroutineContext().ensureActive() + val socket = Socket() + try { + suspendCancellableCoroutine { connected -> + connected.invokeOnCancellation { socket.close() } + try { + socket.connect(InetSocketAddress(address, port), 3500) + connected.resume(Unit) + } catch (e: java.io.IOException) { connected.resumeWithException(e) } + } + socket.tcpNoDelay = true + return TelnetWire(socket) + } catch (e: java.io.IOException) { last = e; socket.close() } + catch (e: Exception) { socket.close(); throw e } + } + throw last ?: java.net.UnknownHostException() +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleProfileUi.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleProfileUi.kt new file mode 100644 index 0000000..bf7065f --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleProfileUi.kt @@ -0,0 +1,133 @@ +package cz.netkit.app.ssh + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.FilterChip +import androidx.compose.material3.Icon +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Checkbox +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.draw.rotate +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import cz.netkit.app.R +import cz.netkit.app.ui.* +import cz.netkit.shared.ssh.* + +@Composable +internal fun consoleType(kind: ConsoleKind) = stringResource(if (kind == ConsoleKind.TELNET) R.string.console_telnet else R.string.console_serial) + +@Composable +internal fun ConsoleForm(initial: ConsoleProfile, busy: Boolean, save: (ConsoleProfile) -> Unit, close: () -> Unit) { + var draft by remember(initial) { mutableStateOf(initial) } + var number by remember(initial) { mutableStateOf((if (initial.kind == ConsoleKind.TELNET) initial.port else initial.serial.baud).toString()) } + val serial = draft.serial + fun preset(s: SerialSettings) { number = s.baud.toString(); draft = draft.copy(serial = s) } + val profile = if (draft.kind == ConsoleKind.TELNET) draft.copy(port = number.toIntOrNull() ?: 0) + else draft.copy(serial = serial.copy(baud = number.toIntOrNull() ?: 0)) + NetKitAlert(onDismiss = close, title = consoleType(draft.kind), confirm = { + PrimaryButton(stringResource(R.string.ssh_save), onClick = { save(profile.copy(group = profile.group?.trim())) }, enabled = profile.valid() && !busy) + }, dismiss = { NeutralButton(stringResource(R.string.ssh_cancel), onClick = close) }, text = { + Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + SshField(draft.name, { draft = draft.copy(name = it.take(100)) }, R.string.ssh_name) + SshField(draft.group.orEmpty(), { draft = draft.copy(group = it.take(60).ifEmpty { null }) }, R.string.ssh_group) + if (draft.kind == ConsoleKind.TELNET) { + SshField(draft.host, { draft = draft.copy(host = it.take(253)) }, R.string.ssh_host, mono = true, hint = R.string.ssh_host_hint) + SshField(number, { number = it.take(5) }, R.string.ssh_port, number = true) + } else { + listOf(SerialSettings.enterprise to R.string.console_preset_enterprise, + SerialSettings.mikrotik to R.string.console_preset_mikrotik).forEach { (settings, label) -> + FilterChip(selected = profile.serial == settings, onClick = { preset(settings) }, + label = { Text(stringResource(label), maxLines = 1, overflow = TextOverflow.Ellipsis) }) + } + SshField(number, { number = it.take(6) }, R.string.console_baud, number = true) + ConsoleChoice(stringResource(R.string.console_bits), (5..8).toList(), serial.dataBits, { it.toString() }) { + draft = draft.copy(serial = serial.copy(dataBits = it)) + } + ConsoleChoice(stringResource(R.string.console_parity), SerialParity.entries, serial.parity, { + stringResource(when (it) { + SerialParity.NONE -> R.string.console_none + SerialParity.ODD -> R.string.console_odd + SerialParity.EVEN -> R.string.console_even + SerialParity.MARK -> R.string.console_mark + SerialParity.SPACE -> R.string.console_space + }) + }) { draft = draft.copy(serial = serial.copy(parity = it)) } + ConsoleChoice(stringResource(R.string.console_stop), SerialStopBits.entries, serial.stopBits, { + when (it) { SerialStopBits.ONE -> "1"; SerialStopBits.ONE_AND_HALF -> "1.5"; SerialStopBits.TWO -> "2" } + }) { draft = draft.copy(serial = serial.copy(stopBits = it)) } + ConsoleChoice(stringResource(R.string.console_flow), listOf(false, true), serial.rtsCts, { + stringResource(if (it) R.string.console_rts else R.string.console_none) + }) { draft = draft.copy(serial = serial.copy(rtsCts = it)) } + } + } + }) +} + +@Composable +private fun ConsoleChoice(label: String, options: List, value: T, display: @Composable (T) -> String, choose: (T) -> Unit) { + var open by remember { mutableStateOf(false) } + Box { + OutlinedButton(onClick = { open = true }) { + Text("$label · ${display(value)}") + Icon(NetKitIcons.ChevronRight, null, Modifier.size(18.dp).rotate(90f)) + } + NetKitMenu(expanded = open, onDismiss = { open = false }) { + options.forEach { option -> + DropdownMenuItem(text = { Text(display(option)) }, onClick = { choose(option); open = false }) + } + } + } +} + +@Composable +internal fun ConsoleConnect(profile: ConsoleProfile, viewModel: SshViewModel, replacement: String?, + close: () -> Unit) { + var rememberWarning by remember(profile) { mutableStateOf(false) } + var refresh by remember { mutableIntStateOf(0) } + var ports by remember { mutableStateOf>(emptyList()) } + var selected by remember { mutableStateOf(null) } + var loading by remember { mutableStateOf(profile.kind == ConsoleKind.SERIAL) } + var enumerationFailed by remember { mutableStateOf(false) } + if (profile.kind == ConsoleKind.SERIAL) LaunchedEffect(refresh) { + loading = true + try { + ports = viewModel.usbPorts() + selected = ports.singleOrNull() + enumerationFailed = false + } catch (e: kotlinx.coroutines.CancellationException) { throw e } + catch (_: Exception) { ports = emptyList(); selected = null; enumerationFailed = true } + finally { loading = false } + } + NetKitAlert(onDismiss = close, title = profile.name, confirm = { + PrimaryButton(stringResource(R.string.ssh_connect), enabled = profile.kind == ConsoleKind.TELNET || (!loading && selected != null), + onClick = { viewModel.connectConsole(profile, selected, warningAccepted = true, remember = rememberWarning, replacement = replacement); close() }) + }, dismiss = { NeutralButton(stringResource(R.string.ssh_cancel), onClick = close) }, text = { + Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + if (profile.kind == ConsoleKind.TELNET) { + Text(stringResource(R.string.console_endpoint, profile.host, profile.port)) + if (!profile.skipTelnetWarning) { + Text(stringResource(R.string.console_warning)) + Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox(checked = rememberWarning, onCheckedChange = { rememberWarning = it }) + Text(stringResource(R.string.console_skip_warning)) + } + } + } else { + Text(stringResource(R.string.console_select_port)) + ports.forEach { port -> + if (port == selected) TonalButton(port.label, onClick = { selected = port }) + else NeutralButton(port.label, onClick = { selected = port }) + } + if (!loading && ports.isEmpty()) Text(stringResource(if (enumerationFailed) R.string.console_usb_error else R.string.console_no_usb)) + NeutralButton(stringResource(R.string.console_refresh), enabled = !loading, onClick = { refresh++ }) + } + } + }) +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt index f2ec5f3..87eb725 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt @@ -1,5 +1,6 @@ package cz.netkit.app.ssh +import com.jcraft.jsch.ChannelSftp import com.jcraft.jsch.ChannelShell import com.jcraft.jsch.HostKey import com.jcraft.jsch.HostKeyRepository @@ -15,7 +16,11 @@ import cz.netkit.shared.ssh.HostKeyDecision import cz.netkit.shared.ssh.SshAlgorithms import cz.netkit.shared.ssh.SshAuthentication import cz.netkit.shared.ssh.SshProfile -import cz.netkit.shared.ssh.SshSession +import cz.netkit.shared.ssh.SSH_MAX_JUMP_HOPS +import cz.netkit.shared.ssh.SshForwardKind +import cz.netkit.shared.ssh.SshForwardState +import cz.netkit.shared.ssh.SshForwardStatus +import cz.netkit.shared.ssh.SshSocksCredentials import cz.netkit.shared.ssh.TrustedHostKey import cz.netkit.shared.ssh.hostKeyDecision import java.io.InputStream @@ -23,6 +28,7 @@ import java.io.OutputStream import java.net.InetSocketAddress import java.net.Socket import java.util.Base64 +import java.util.concurrent.CopyOnWriteArrayList import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import kotlinx.coroutines.CancellationException @@ -40,9 +46,17 @@ import kotlinx.coroutines.withTimeout interface SshInteraction { suspend fun confirmHost(offered: TrustedHostKey, previous: TrustedHostKey?): Boolean suspend fun authenticate(name: String, instruction: String, prompts: List, echo: List): List? + /** Per-hop identity for ProxyJump chains; the default keeps single-hop implementations unchanged. */ + suspend fun authenticateHop(hop: SshProfile, name: String, instruction: String, prompts: List, echo: List): List? = + authenticate(name, instruction, prompts, echo) } -/** One JSch instance per connection; no shared identities, auth responses, logger, or permissive verifier. */ +/** + * One JSch instance per hop; no shared identities, auth responses, logger, or permissive verifier. + * [jumps] are ProxyJump hops in connection order; each is verified (known host key) and authenticated + * with its own profile before the next hop's SSH stream is opened through it. Forwards of [profile] + * start after the final hop is authenticated and listen on 127.0.0.1 only. + */ class JschConnection( private val profile: SshProfile, private val store: SshStore, @@ -53,80 +67,48 @@ class JschConnection( private val onConnected: () -> Unit, private val onEnd: (Boolean) -> Unit, private val onFailure: (SshFailure) -> Unit = {}, -) : SshSession { + private val jumps: List = emptyList(), + private val onForwards: (List) -> Unit = {}, +) : TerminalConnection { private val closed = AtomicBoolean(false) private val outcome = SshConnectionOutcome(onFailure) private val socket = AtomicReference() - private val session = AtomicReference() + private val sessions = CopyOnWriteArrayList() private val channel = AtomicReference() + /** Authenticated session of [profile] (last hop); SFTP channels open on it (zadání 42). */ + private val target = AtomicReference() + private val sftpChannels = CopyOnWriteArrayList() + private val socks = AtomicReference() + /** `-L` listeners; at most 32 forwarded clients per session at a time (each is a channel + 2 threads). */ + private val localForwards = CopyOnWriteArrayList() + private val localForwardSlots = java.util.concurrent.Semaphore(32) private val input = TerminalWritePump(scope) private var job: Job? = null private var writer: Job? = null @Volatile private var columns = 80 @Volatile private var rows = 24 - fun start() { + /** Every address a forward of this connection listens on (all loopback by construction). */ + val listeningAddresses: List get() = localForwards.map { it.address } + listOfNotNull(socks.get()?.address) + + override fun start() { check(job == null) job = scope.launch(Dispatchers.IO) { - val jsch = JSch(); var passwordBytes: ByteArray? = null; var privateKey: ByteArray? = null + val instances = mutableListOf() try { - require(profile.valid()); SshCrypto.configure() - jsch.hostKeyRepository = verifier() - if (profile.authentication == SshAuthentication.KEY) { - privateKey = secrets.get(requireNotNull(profile.keyRef)); require(privateKey != null) - jsch.addIdentity("NetKit", privateKey, null, null) - } else if (profile.authentication == SshAuthentication.PASSWORD) { - passwordBytes = profile.secretRef?.let { secrets.get(it) } - } - val transport = jsch.getSession(profile.username, profile.host, profile.port) - session.set(transport) - transport.setConfig("StrictHostKeyChecking", "yes") - transport.setConfig("kex", SshAlgorithms.kex.joinToString(",")) - transport.setConfig("server_host_key", SshAlgorithms.hostKeyPreference(store.read().hostKeys.find { it.endpoint == profile.endpoint }?.algorithm).joinToString(",")) - transport.setConfig("PubkeyAcceptedAlgorithms", SshAlgorithms.hostKeys.joinToString(",")) - for (direction in listOf("c2s", "s2c")) { - transport.setConfig("cipher.$direction", SshAlgorithms.ciphers.joinToString(",")) - transport.setConfig("mac.$direction", SshAlgorithms.macs.joinToString(",")) - transport.setConfig("compression.$direction", "none") + require(profile.valid() && jumps.size <= SSH_MAX_JUMP_HOPS && jumps.all { it.valid() } && + (jumps + profile).map { it.id }.distinct().size == jumps.size + 1) + SshCrypto.configure() + var via: Session? = null + for (hop in jumps + profile) { + if (closed.get()) throw CancellationException() + val jsch = JSch(); instances += jsch + via = connectHop(jsch, hop, via) } - transport.setConfig("PreferredAuthentications", when (profile.authentication) { - SshAuthentication.KEY -> "publickey" - SshAuthentication.PASSWORD -> "password" - SshAuthentication.INTERACTIVE -> "keyboard-interactive" - }) - transport.setConfig("MaxAuthTries", "3") - transport.setConfig("FingerprintHash", "sha256") - transport.setConfig("enable_strict_kex", "yes") - transport.setConfig("prefer_known_host_key_types", "no") - transport.setServerAliveInterval(profile.keepaliveSeconds * 1000) - transport.setServerAliveCountMax(3) - transport.userInfo = authentication() - passwordBytes?.let { transport.setPassword(it) } - val addresses = resolveSshHost(profile.host) - transport.setSocketFactory(object : SocketFactory { - override fun createSocket(host: String, port: Int): Socket { - val deadline = System.nanoTime() + 15_000_000_000L - var failure: Exception = java.io.IOException("Connection failed") - for (address in addresses) { - val remaining = ((deadline - System.nanoTime()) / 1_000_000L).toInt() - if (remaining <= 0 || closed.get()) break - val value = Socket(); socket.set(value) - if (closed.get()) { value.close(); throw java.io.IOException("Closed") } - try { - value.connect(InetSocketAddress(address, port), minOf(5000, remaining)) - if (closed.get()) { value.close(); throw java.io.IOException("Closed") } - return value - } catch (e: Exception) { value.close(); failure = e } - } - throw failure - } - override fun getInputStream(socket: Socket): InputStream = socket.getInputStream() - override fun getOutputStream(socket: Socket): OutputStream = socket.getOutputStream() - }) - // Each network stage and UI challenge is bounded; cancellation also closes the raw socket. - withTimeout(SshPromptPolicy.HANDSHAKE_TIMEOUT_MILLIS) { runInterruptible { transport.connect(20000) } } - passwordBytes?.fill(0); passwordBytes = null; privateKey?.fill(0); privateKey = null + val transport = requireNotNull(via) if (closed.get()) throw CancellationException() + target.set(transport) + startForwards(transport) val shell = transport.openChannel("shell") as ChannelShell; channel.set(shell) shell.setPtyType("xterm-256color", columns, rows, 0, 0) val reader = shell.inputStream.bufferedReader(Charsets.UTF_8) @@ -152,11 +134,136 @@ class JschConnection( catch (e: CancellationException) { throw e } catch (e: Exception) { if (!closed.get()) outcome.record(classifySshFailure(e)) } finally { - passwordBytes?.fill(0); privateKey?.fill(0) - closeTransport(); jsch.removeAllIdentity(); onEnd(outcome.failed) + closeTransport(); instances.forEach { it.removeAllIdentity() }; onEnd(outcome.failed) + } + } + } + + /** Opens, verifies and authenticates one hop. The first hop uses a socket; later hops tunnel through [via]. */ + private suspend fun connectHop(jsch: JSch, hop: SshProfile, via: Session?): Session { + var passwordBytes: ByteArray? = null; var privateKey: ByteArray? = null + try { + jsch.hostKeyRepository = verifier(hop) + if (hop.authentication == SshAuthentication.KEY) { + privateKey = secrets.get(requireNotNull(hop.keyRef)); require(privateKey != null) + jsch.addIdentity("NetKit", privateKey, null, null) + } else if (hop.authentication == SshAuthentication.PASSWORD) { + passwordBytes = hop.secretRef?.let { secrets.get(it) } + } + val transport = jsch.getSession(hop.username, hop.host, hop.port) + sessions += transport + if (closed.get()) throw CancellationException() + transport.setConfig("StrictHostKeyChecking", "yes") + transport.setConfig("kex", SshAlgorithms.kex.joinToString(",")) + transport.setConfig("server_host_key", SshAlgorithms.hostKeyPreference(store.read().hostKeys.find { it.endpoint == hop.endpoint }?.algorithm).joinToString(",")) + transport.setConfig("PubkeyAcceptedAlgorithms", SshAlgorithms.hostKeys.joinToString(",")) + for (direction in listOf("c2s", "s2c")) { + transport.setConfig("cipher.$direction", SshAlgorithms.ciphers.joinToString(",")) + transport.setConfig("mac.$direction", SshAlgorithms.macs.joinToString(",")) + transport.setConfig("compression.$direction", "none") + } + transport.setConfig("PreferredAuthentications", when (hop.authentication) { + SshAuthentication.KEY -> "publickey" + SshAuthentication.PASSWORD -> "password" + SshAuthentication.INTERACTIVE -> "keyboard-interactive" + }) + transport.setConfig("MaxAuthTries", "3") + transport.setConfig("FingerprintHash", "sha256") + transport.setConfig("enable_strict_kex", "yes") + transport.setConfig("prefer_known_host_key_types", "no") + transport.setServerAliveInterval(hop.keepaliveSeconds * 1000) + transport.setServerAliveCountMax(3) + transport.userInfo = authentication(hop) + passwordBytes?.let { transport.setPassword(it) } + if (via == null) { + val addresses = resolveSshHost(hop.host) + transport.setSocketFactory(object : SocketFactory { + override fun createSocket(host: String, port: Int): Socket { + val deadline = System.nanoTime() + 15_000_000_000L + var failure: Exception = java.io.IOException("Connection failed") + for (address in addresses) { + val remaining = ((deadline - System.nanoTime()) / 1_000_000L).toInt() + if (remaining <= 0 || closed.get()) break + val value = Socket(); socket.set(value) + if (closed.get()) { value.close(); throw java.io.IOException("Closed") } + try { + value.connect(InetSocketAddress(address, port), minOf(5000, remaining)) + if (closed.get()) { value.close(); throw java.io.IOException("Closed") } + return value + } catch (e: Exception) { value.close(); failure = e } + } + throw failure + } + override fun getInputStream(socket: Socket): InputStream = socket.getInputStream() + override fun getOutputStream(socket: Socket): OutputStream = socket.getOutputStream() + }) + } else { + // The jump server resolves and connects; this hop still gets its own host key check and login. + transport.setProxy(JumpProxy(via, 15000)) + } + // Each network stage and UI challenge is bounded; cancellation also closes the raw socket. + withTimeout(SshPromptPolicy.HANDSHAKE_TIMEOUT_MILLIS) { runInterruptible { transport.connect(20000) } } + if (closed.get()) throw CancellationException() + return transport + } finally { passwordBytes?.fill(0); privateKey?.fill(0) } + } + + /** -L and -D of the target profile; a busy port marks that rule only, the shell still opens. */ + private fun startForwards(transport: Session) { + if (profile.localForwards.isEmpty() && profile.dynamicForwardPort == null) return + val statuses = mutableListOf() + for (rule in profile.localForwards) { + val state = try { + val server = LocalForwardServer(rule.localPort, rule.host, rule.port, + open = { host, port -> transport.getStreamForwarder(host, port) }, slots = localForwardSlots) + localForwards += server + if (closed.get()) server.close() else server.start() + SshForwardState.ACTIVE + } catch (e: Exception) { forwardFailure(e) } + statuses += SshForwardStatus(SshForwardKind.LOCAL, rule.localPort, rule.target, state) + } + profile.dynamicForwardPort?.let { port -> + // Default: RFC 1929 login with a fresh random secret for this session only (never stored), so + // another app on the phone cannot use the tunnel without it. No-auth only by explicit profile choice. + val credentials = if (profile.dynamicForwardNoAuth) null else java.security.SecureRandom().let { random -> + SshSocksCredentials.generate { bound -> random.nextInt(bound) } } + val state = try { + val server = Socks5Server(port, open = { host, target -> transport.getStreamForwarder(host, target) }, credentials = credentials) + socks.set(server) + if (closed.get()) server.close() else server.start() + SshForwardState.ACTIVE + } catch (e: Exception) { forwardFailure(e) } + statuses += SshForwardStatus(SshForwardKind.DYNAMIC, port, null, state, credentials.takeIf { state == SshForwardState.ACTIVE }) } + onForwards(statuses.toList()) + } + private fun forwardFailure(error: Exception): SshForwardState = + if (generateSequence(error) { it.cause }.take(6).any { it is java.net.BindException }) SshForwardState.PORT_IN_USE + else SshForwardState.FAILED + + /** + * Opens an SFTP channel on the already authenticated target session (same host key check and login + * as the shell, no new connection). Blocking; call off the main thread. The caller disconnects it; + * closing the connection disconnects it too. + */ + fun openSftp(): ChannelSftp { + val transport = target.get() + check(transport != null && transport.isConnected && !closed.get()) { "Session not connected" } + val sftp = transport.openChannel("sftp") as ChannelSftp + sftpChannels.removeAll { it.isClosed } // closed by the server or a peer without releaseSftp + sftpChannels += sftp + try { sftp.connect(15000) } catch (e: Exception) { releaseSftp(sftp); throw e } + if (closed.get()) { releaseSftp(sftp); throw java.io.IOException("Closed") } + return sftp } + + /** Closes [channel] and forgets it, so a long session (kept by the service) does not collect closed channels. */ + fun releaseSftp(channel: ChannelSftp) { sftpChannels -= channel; channel.disconnect() } + + /** Registered SFTP channels (tests: closed ones must not accumulate). */ + internal val sftpChannelCount: Int get() = sftpChannels.size + override fun send(text: String): Boolean = text.length <= 16384 && !closed.get() && input.send(text) override fun resize(columns: Int, rows: Int) { this.columns = columns.coerceIn(10, 240); this.rows = rows.coerceIn(2, 100) @@ -165,15 +272,19 @@ class JschConnection( override fun close() { closeTransport(); job?.cancel() } private fun closeTransport() { closed.set(true); input.close(); writer?.cancel() + socks.get()?.close(); localForwards.forEach { it.close() } try { socket.getAndSet(null)?.close() } catch (_: Exception) { } - channel.getAndSet(null)?.disconnect(); session.getAndSet(null)?.disconnect() + channel.getAndSet(null)?.disconnect() + sftpChannels.forEach { it.disconnect() }; sftpChannels.clear(); target.set(null) + // Innermost first: the target session (and its -L listeners), then each jump host. + sessions.reversed().forEach { it.disconnect() }; sessions.clear() } - private fun verifier() = object : HostKeyRepository { + private fun verifier(hop: SshProfile) = object : HostKeyRepository { override fun check(host: String, key: ByteArray): Int = runBlocking { if (closed.get()) return@runBlocking HostKeyRepository.CHANGED - val algorithm = HostKey(profile.endpoint, key).type - val offered = TrustedHostKey(profile.endpoint, algorithm, Base64.getEncoder().encodeToString(key), SshCrypto.fingerprint(key)) - val previous = store.read().hostKeys.find { it.endpoint == profile.endpoint } + val algorithm = HostKey(hop.endpoint, key).type + val offered = TrustedHostKey(hop.endpoint, algorithm, Base64.getEncoder().encodeToString(key), SshCrypto.fingerprint(key)) + val previous = store.read().hostKeys.find { it.endpoint == hop.endpoint } when (hostKeyDecision(previous, offered)) { HostKeyDecision.TRUSTED -> HostKeyRepository.OK HostKeyDecision.CHANGED -> { @@ -199,14 +310,14 @@ class JschConnection( override fun getHostKey(): Array = emptyArray() override fun getHostKey(host: String?, type: String?): Array = emptyArray() } - private fun authentication() = object : UserInfo, UIKeyboardInteractive { + private fun authentication(hop: SshProfile) = object : UserInfo, UIKeyboardInteractive { private var answer: String? = null override fun getPassphrase(): String? = null override fun getPassword(): String? = answer.also { answer = null } override fun promptPassphrase(message: String?) = false override fun promptPassword(message: String?): Boolean { if (closed.get()) return false - answer = runBlocking { SshPromptPolicy.await { interaction.authenticate(profile.name, "", listOf("Password"), listOf(false))?.singleOrNull() } } + answer = runBlocking { SshPromptPolicy.await { interaction.authenticateHop(hop, hop.name, "", listOf("Password"), listOf(false))?.singleOrNull() } } return answer != null } override fun promptYesNo(message: String?) = false @@ -214,7 +325,7 @@ class JschConnection( override fun promptKeyboardInteractive(destination: String?, name: String?, instruction: String?, prompt: Array?, echo: BooleanArray?): Array? { if (closed.get() || prompt == null || prompt.size > 8) return null return runBlocking { SshPromptPolicy.await { - interaction.authenticate(name.orEmpty().take(200), instruction.orEmpty().take(1000), prompt.map { it.take(200) }, prompt.indices.map { echo?.getOrNull(it) == true })?.toTypedArray() + interaction.authenticateHop(hop, name.orEmpty().take(200), instruction.orEmpty().take(1000), prompt.map { it.take(200) }, prompt.indices.map { echo?.getOrNull(it) == true })?.toTypedArray() } } } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpClient.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpClient.kt new file mode 100644 index 0000000..10fb2ac --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpClient.kt @@ -0,0 +1,201 @@ +package cz.netkit.app.ssh + +import com.jcraft.jsch.ChannelSftp +import com.jcraft.jsch.SftpATTRS +import com.jcraft.jsch.SftpException +import cz.netkit.shared.ssh.SFTP_MAX_ENTRIES +import cz.netkit.shared.ssh.SFTP_MAX_FILE_BYTES +import cz.netkit.shared.ssh.SftpEntry +import cz.netkit.shared.ssh.SftpEntryKind +import cz.netkit.shared.ssh.SftpFailure +import cz.netkit.shared.ssh.isValidSftpName +import cz.netkit.shared.ssh.sftpChild +import cz.netkit.shared.ssh.sftpFailureForStatus +import cz.netkit.shared.ssh.sftpParentRequest +import cz.netkit.shared.ssh.sortSftpEntries +import java.io.InputStream +import java.io.OutputStream + +/** A failed SFTP operation with a fixed reason; the server's message text is never shown or logged. */ +class SftpOperationException(val reason: SftpFailure, cause: Throwable? = null) : Exception(reason.name, cause) + +/** One listing: server-resolved [path], entries with valid single-element names, [truncated] past the limit. */ +data class SftpListing(val path: String, val entries: List, val truncated: Boolean, val hidden: Int) + +/** + * Blocking wrapper over one [ChannelSftp] (zadání 42). Not thread-safe: callers serialize calls and run + * them off the main thread. Rules: + * - every directory the browser shows is the server's `realpath` answer; `..` is only ever sent to + * `realpath` ([parent]), never joined into a path used for an operation; + * - names from the server are used only when [isValidSftpName] (no `/`, `.`, `..`, control chars); + * - JSch expands `*` and `?` in most path arguments, so those paths are escaped ([glob]) — otherwise + * deleting a file named `*` would delete every file of the directory; + * - transfers stop at [SFTP_MAX_FILE_BYTES] even when the announced size was smaller or unknown. + */ +class SftpClient(private val channel: ChannelSftp, private val release: (ChannelSftp) -> Unit = { it.disconnect() }) { + val connected: Boolean get() = channel.isConnected && !channel.isClosed + + fun home(): String = call { channel.realpath(".") } + fun resolve(path: String): String = call { channel.realpath(path) } + fun parent(directory: String): String = resolve(sftpParentRequest(directory)) + + fun list(directory: String): SftpListing = call { + val entries = ArrayList() + var truncated = false; var hidden = 0 + channel.ls(glob(directory)) { entry -> + val name = entry.filename + if (name == "." || name == "..") return@ls ChannelSftp.LsEntrySelector.CONTINUE + if (!isValidSftpName(name)) { hidden++; return@ls ChannelSftp.LsEntrySelector.CONTINUE } + if (entries.size >= SFTP_MAX_ENTRIES) { truncated = true; return@ls ChannelSftp.LsEntrySelector.BREAK } + entries += entry(name, entry.attrs) + ChannelSftp.LsEntrySelector.CONTINUE + } + SftpListing(directory, sortSftpEntries(entries), truncated, hidden) + } + + /** Follows a link (server side) and says what it points to; the target path itself comes from `realpath`. */ + fun follow(directory: String, name: String): Pair = call { + val resolved = channel.realpath(sftpChild(directory, name)) + val attrs = channel.stat(glob(resolved)) + resolved to kind(attrs) + } + + fun stat(path: String): SftpATTRS = call { channel.stat(glob(path)) } + + /** Copies [path] to [output]; [onProgress] gets bytes done; [cancelled] is checked between chunks. */ + fun download(path: String, output: OutputStream, onProgress: (Long) -> Unit, cancelled: () -> Boolean): Long = call { + val attrs = channel.stat(glob(path)) + if (!attrs.isReg) throw SftpOperationException(SftpFailure.FAILURE) + if (attrs.size > SFTP_MAX_FILE_BYTES) throw SftpOperationException(SftpFailure.TOO_LARGE) + channel.get(glob(path)).use { input -> copy(input, output, onProgress, cancelled) } + } + + /** + * Uploads [input] as a new file [name] in [directory]; never overwrites. The data goes to a random + * temporary name in the same directory first (`.netkit-upload-.part`, only ever created and + * removed by us), then [publish] gives it the final name without replacing anything. A check-then-write + * on the final name would race with a file or symlink created meanwhile (TOCTOU). A cancelled or + * failed upload removes only the temporary file; an existing target is never touched. + */ + fun upload(directory: String, name: String, input: InputStream, onProgress: (Long) -> Unit, cancelled: () -> Boolean): Long { + if (!isValidSftpName(name)) throw SftpOperationException(SftpFailure.INVALID_NAME) + val target = sftpChild(directory, name) + call { if (exists(target)) throw SftpOperationException(SftpFailure.EXISTS) } + val temp = sftpChild(directory, temporaryName()) + call { if (exists(temp)) throw SftpOperationException(SftpFailure.FAILURE) } + try { + val total = call { channel.put(glob(temp), ChannelSftp.OVERWRITE).use { output -> copy(input, output, onProgress, cancelled) } } + call { publish(temp, target) } // the finally block removes temp when it still exists + return total + } finally { + // Only our own random temporary name is removed, never the target (gone after a rename). + if (connected) try { channel.rm(glob(temp)) } catch (_: Exception) { } + } + } + + /** + * Gives [temp] the name [target] without ever replacing an existing [target]: + * - `hardlink@openssh.com` (link(2) fails with EEXIST); the caller removes the old name; + * - otherwise plain SSH_FXP_RENAME, which SFTP v3 defines as failing on an existing target — + * but only when the server does not offer `posix-rename@openssh.com`, because JSch then sends + * that overwriting extension instead of RENAME. Such a server without hardlink is refused. + * Returns true when [temp] still exists (hardlink) and the caller removes it. + */ + internal fun publish(temp: String, target: String): Boolean { + val hardlink = channel.getExtension(HARDLINK) == "1" + val posixRename = channel.getExtension(POSIX_RENAME) == "1" + try { + return when { + hardlink -> { channel.hardlink(glob(temp), glob(target)); true } + !posixRename -> { channel.rename(glob(temp), glob(target)); false } + else -> throw SftpOperationException(SftpFailure.UNSUPPORTED) + } + } catch (e: SftpException) { + if (exists(target)) throw SftpOperationException(SftpFailure.EXISTS, e) + throw e + } + } + + /** + * Renames one entry; never replaces an existing name (review round 1). Files and links go through + * [publish]: hardlink + removal of the old name, plain RENAME on a server without posix-rename, else + * refused as UNSUPPORTED — JSch would send the overwriting posix-rename. (OpenSSH `link(2)` on a + * symlink links the link itself.) A directory cannot be hard-linked: it is renamed after a check; on a + * server with posix-rename, rename(2) of a directory can replace only an *empty* directory created + * in that window (never a file or a non-empty directory) — the documented residual case. + */ + fun rename(directory: String, from: String, to: String) = call { + if (!isValidSftpName(to)) throw SftpOperationException(SftpFailure.INVALID_NAME) + val source = sftpChild(directory, from) + val target = sftpChild(directory, to) + if (exists(target)) throw SftpOperationException(SftpFailure.EXISTS) + if (!channel.lstat(glob(source)).isDir) { + if (publish(source, target)) channel.rm(glob(source)) + } else { + try { channel.rename(glob(source), glob(target)) } + catch (e: SftpException) { if (exists(target)) throw SftpOperationException(SftpFailure.EXISTS, e); throw e } + } + } + + /** Deletes one file or link (the link itself, never its target) or one empty directory. */ + fun delete(directory: String, entry: SftpEntry) = call { + val path = sftpChild(directory, entry.name) + if (entry.kind == SftpEntryKind.DIRECTORY) channel.rmdir(glob(path)) else channel.rm(glob(path)) + } + + fun mkdir(directory: String, name: String) = call { + if (!isValidSftpName(name)) throw SftpOperationException(SftpFailure.INVALID_NAME) + channel.mkdir(sftpChild(directory, name)) // mkdir does not glob: raw path + } + + /** Closes the channel through its owner (JschConnection.releaseSftp unregisters it). Safe from any thread. */ + fun close() { release(channel) } + + private fun exists(path: String): Boolean = try { channel.lstat(glob(path)); true } + catch (e: SftpException) { if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) false else throw e } + + private fun copy(input: InputStream, output: OutputStream, onProgress: (Long) -> Unit, cancelled: () -> Boolean): Long { + val buffer = ByteArray(32 * 1024) + var total = 0L + while (true) { + if (cancelled()) throw SftpOperationException(SftpFailure.CANCELLED) + val count = input.read(buffer) + if (count < 0) break + total += count + if (total > SFTP_MAX_FILE_BYTES) throw SftpOperationException(SftpFailure.TOO_LARGE) + output.write(buffer, 0, count) + onProgress(total) + } + output.flush() + return total + } + + private inline fun call(block: () -> T): T = try { block() } + catch (e: SftpOperationException) { throw e } + catch (e: SftpException) { throw SftpOperationException(if (e.id == 4 && !connected) SftpFailure.CONNECTION else sftpFailureForStatus(e.id), e) } + catch (e: java.io.IOException) { throw SftpOperationException(SftpFailure.CONNECTION, e) } + + private fun temporaryName(): String { + val bytes = ByteArray(12).also { java.security.SecureRandom().nextBytes(it) } + return ".netkit-upload-" + bytes.joinToString("") { "%02x".format(it.toInt() and 0xff) } + ".part" + } + + companion object { + const val HARDLINK = "hardlink@openssh.com" + const val POSIX_RENAME = "posix-rename@openssh.com" + + /** Escapes JSch's glob characters (`\`, `*`, `?`) for methods that expand patterns. */ + fun glob(path: String): String = buildString(path.length) { + for (char in path) { if (char == '\\' || char == '*' || char == '?') append('\\'); append(char) } + } + + fun kind(attrs: SftpATTRS): SftpEntryKind = when { + attrs.isLink -> SftpEntryKind.LINK + attrs.isDir -> SftpEntryKind.DIRECTORY + attrs.isReg -> SftpEntryKind.FILE + else -> SftpEntryKind.OTHER + } + + fun entry(name: String, attrs: SftpATTRS) = SftpEntry(name, kind(attrs), attrs.size.coerceAtLeast(0), attrs.mTime.toLong() and 0xffffffffL) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpController.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpController.kt new file mode 100644 index 0000000..3d993ef --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpController.kt @@ -0,0 +1,264 @@ +package cz.netkit.app.ssh + +import android.content.ContentResolver +import android.net.Uri +import android.provider.DocumentsContract +import android.provider.OpenableColumns +import com.jcraft.jsch.ChannelSftp +import cz.netkit.shared.ssh.SftpEntry +import cz.netkit.shared.ssh.SftpEntryKind +import cz.netkit.shared.ssh.SftpFailure +import cz.netkit.shared.ssh.isValidSftpName +import cz.netkit.shared.ssh.sftpChild +import cz.netkit.shared.ssh.sftpSizeAllowed +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withContext + +data class SftpTransfer(val upload: Boolean, val name: String, val done: Long, val total: Long?) +enum class SftpNotice { DOWNLOADED, UPLOADED, RENAMED, DELETED, CREATED } + +data class SftpUiState( + val sessionId: String, val path: String? = null, val entries: List = emptyList(), + val truncated: Boolean = false, val hidden: Int = 0, val loading: Boolean = true, + val failure: SftpFailure? = null, val transfer: SftpTransfer? = null, val notice: SftpNotice? = null, +) + +/** + * SFTP browser of one SSH session (zadání 42). Operations run one at a time on [Dispatchers.IO]. + * + * Review round 1: a blocking JSch call or document provider cannot be interrupted by a flag alone. + * Every operation has a watchdog: no progress for [ioTimeoutMs] (timeout → CONNECTION) or a pending + * "Cancel" for [cancelGraceMs] (→ CANCELLED) aborts it — the channel and the SAF stream are closed + * from another thread, a half-written download document is deleted, and the browser is usable at once. + * Each abort (and [close]) starts a new *generation*: the stuck thread, when it finally returns, may + * neither touch the UI state nor keep a channel (one opened after the abort is released immediately). + * Review round 2: stream, clean-up, activity clock and cancel request belong to one [SftpRun], never to + * the controller, and the abort closes channel, stream and document independently ([SftpAbandon]). + * Transfers survive the app going to the background because the SSH session (and its service) does. + */ +class SftpController( + private val scope: CoroutineScope, + val sessionId: String, + private val resolver: ContentResolver, + private val open: () -> ChannelSftp, + private val release: (ChannelSftp) -> Unit = { it.disconnect() }, + private val ioTimeoutMs: Long = IO_TIMEOUT_MS, + private val cancelGraceMs: Long = CANCEL_GRACE_MS, + private val now: () -> Long = { System.nanoTime() / 1_000_000 }, + private val canOperate: () -> Boolean = { true }, +) { + companion object { + /** No byte moved and no reply for this long: the peer or the document provider hangs. */ + const val IO_TIMEOUT_MS = 30_000L + /** "Cancel" first asks the copy loop; after this the channel and stream are closed under it. */ + const val CANCEL_GRACE_MS = 2_000L + } + + private val mutable = MutableStateFlow(SftpUiState(sessionId)) + val state: StateFlow = mutable.asStateFlow() + @Volatile private var closed = false + private val jobs = mutableListOf() + + /** Guards [client], [generation] and [lock]; never held during network or provider calls. */ + private val handoff = Any() + private var client: SftpClient? = null + private var generation = 0 + private var lock = Mutex() + /** The running operation (its stream, clean-up, clock and cancel request live there, review round 2). */ + @Volatile private var running: SftpRun? = null + + /** One running operation: its client, and state updates that are dropped once it was aborted. */ + private inner class Op(val run: SftpRun, val client: SftpClient) { + fun isCurrent(): Boolean = synchronized(handoff) { run.generation == generation } + fun update(change: (SftpUiState) -> SftpUiState) { if (isCurrent()) mutable.update(change) } + fun alive() { run.alive() } + fun progress(): (Long) -> Unit { + var last = 0L + return { done -> + run.alive() + if (done - last >= 64 * 1024) { last = done; update { s -> s.copy(transfer = s.transfer?.copy(done = done)) } } + } + } + fun show(path: String) { + val listing = client.list(path); alive() + update { it.copy(path = listing.path, entries = listing.entries, truncated = listing.truncated, hidden = listing.hidden) } + } + } + + fun start() = operation { show(client.home()) } + fun refresh() = operation { show(current()) } + fun up() = operation { show(client.parent(current())) } + + fun open(entry: SftpEntry) = operation { + val directory = current() + when (entry.kind) { + SftpEntryKind.DIRECTORY -> show(client.resolve(sftpChild(directory, entry.name))) + SftpEntryKind.LINK -> { + val (target, kind) = client.follow(directory, entry.name) + if (kind == SftpEntryKind.DIRECTORY) show(target) else throw SftpOperationException(SftpFailure.UNSUPPORTED) + } + else -> Unit + } + } + + fun mkdir(name: String) = operation { + client.mkdir(current(), name); show(current()); update { it.copy(notice = SftpNotice.CREATED) } + } + fun rename(entry: SftpEntry, name: String) = operation { + client.rename(current(), entry.name, name); show(current()); update { it.copy(notice = SftpNotice.RENAMED) } + } + fun delete(entry: SftpEntry) = operation { + client.delete(current(), entry); show(current()); update { it.copy(notice = SftpNotice.DELETED) } + } + + /** Downloads [entry] (a file or a link to a file) into the SAF document [uri]; a failed copy deletes the document. */ + fun download(entry: SftpEntry, uri: Uri) = operation(transfer = true) { + val path = sftpChild(current(), entry.name) + val attrs = client.stat(path); alive() + if (!sftpSizeAllowed(attrs.size)) { discard(uri); throw SftpOperationException(SftpFailure.TOO_LARGE) } + update { it.copy(transfer = SftpTransfer(false, entry.name, 0, attrs.size)) } + run.onFailure { discard(uri) } + try { + val output = resolver.openOutputStream(uri, "wt") ?: throw java.io.IOException("Destination unavailable") + run.attach(output); alive() + output.use { client.download(path, it, progress(), run.cancelled::get) } + } catch (e: Exception) { run.cleanUp(); throw e } // no-op when the watchdog already took the clean-up + run.completed() + update { it.copy(notice = SftpNotice.DOWNLOADED) } + } + + /** Uploads the SAF document [uri] under its display name into the current directory; never overwrites. */ + fun upload(uri: Uri) = operation(transfer = true) { + val (name, size) = describe(uri); alive() + if (name == null || !isValidSftpName(name)) throw SftpOperationException(SftpFailure.INVALID_NAME) + if (!sftpSizeAllowed(size)) throw SftpOperationException(SftpFailure.TOO_LARGE) + update { it.copy(transfer = SftpTransfer(true, name, 0, size?.takeIf { it >= 0 })) } + val input = resolver.openInputStream(uri) ?: throw java.io.IOException("Source unavailable") + run.attach(input); alive() + input.use { client.upload(current(), name, it, progress(), run.cancelled::get) } + run.completed() + show(current()) + update { it.copy(notice = SftpNotice.UPLOADED) } + } + + /** Asks only the running transfer to stop; a finished transfer leaves nothing behind for the next operation. */ + fun cancelTransfer() { running?.requestCancel() } + fun dismiss() { mutable.update { it.copy(failure = null, notice = null) } } + + /** Ends the browser: stops a transfer and closes the channel, also one still being opened (the SSH session stays). */ + fun close() { + closed = true + val victim = synchronized(handoff) { generation++; client.also { client = null } } + val resources = running?.abort() + running = null + synchronized(jobs) { jobs.forEach { it.cancel() } } + SftpAbandon.release(victim?.let { { it.close() } }, resources?.first, resources?.second) + } + + /** Test hook: the channel the browser currently keeps (null after close or an abort). */ + internal val hasClient: Boolean get() = synchronized(handoff) { client != null } + + private fun current(): String = mutable.value.path ?: throw SftpOperationException(SftpFailure.FAILURE) + + private fun describe(uri: Uri): Pair = + resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { cursor -> + if (!cursor.moveToFirst()) return@use null to null + val name = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME).takeIf { it >= 0 && !cursor.isNull(it) }?.let(cursor::getString) + val size = cursor.getColumnIndex(OpenableColumns.SIZE).takeIf { it >= 0 && !cursor.isNull(it) }?.let(cursor::getLong) + name to size + } ?: (uri.lastPathSegment?.substringAfterLast('/') to null) // file:// (tests) has no provider columns + + private fun discard(uri: Uri) { + try { + when (uri.scheme) { + ContentResolver.SCHEME_CONTENT -> DocumentsContract.deleteDocument(resolver, uri) + ContentResolver.SCHEME_FILE -> uri.path?.let { java.io.File(it).delete() } + } + } catch (_: Exception) { /* Provider may not support delete; the UI reports the failure. */ } + } + + private fun operation(transfer: Boolean = false, block: suspend Op.() -> Unit) { + if (closed || !canOperate()) return + val (gen, mutex) = synchronized(handoff) { generation to lock } + val job = scope.launch(Dispatchers.IO) { + mutex.withLock { + if (closed || !canOperate() || synchronized(handoff) { gen != generation }) return@withLock + val run = SftpRun(gen, transfer, now) + running = run + mutable.update { it.copy(loading = true, failure = null, notice = null) } + val watchdog = scope.launch { watch(run) } + try { + Op(run, obtain(gen)).block() + } catch (e: CancellationException) { throw e } + catch (e: Exception) { + val reason = (e as? SftpOperationException)?.reason + ?: if (synchronized(handoff) { client?.connected } != true) SftpFailure.CONNECTION else SftpFailure.FAILURE + if (reason == SftpFailure.CONNECTION || reason == SftpFailure.CANCELLED) reset(gen) + if (!closed && synchronized(handoff) { gen == generation }) mutable.update { it.copy(failure = reason) } + } finally { + watchdog.cancel() + withContext(NonCancellable) { + if (running === run) running = null + if (!run.isAborted && synchronized(handoff) { gen == generation }) + mutable.update { it.copy(loading = false, transfer = null) } + } + } + } + } + synchronized(jobs) { jobs.removeAll { !it.isActive }; jobs += job } + } + + /** The kept client, or a new channel; one opened after an abort or [close] is released, never kept. */ + private fun obtain(gen: Int): SftpClient { + synchronized(handoff) { client?.takeIf { it.connected }?.let { return it } } + val channel = open() // may block; close() or an abort meanwhile starts a new generation + val (kept, stale) = synchronized(handoff) { + if (closed || gen != generation) null to null + else SftpClient(channel, release).let { fresh -> fresh to client.also { client = fresh } } + } + if (kept == null) { + release(channel) + throw SftpOperationException(SftpFailure.CANCELLED) + } + stale?.close() + return kept + } + + private suspend fun watch(run: SftpRun) { + val step = (minOf(ioTimeoutMs, cancelGraceMs) / 4).coerceIn(10, 500) + while (true) { + delay(step) + run.overdue(ioTimeoutMs, cancelGraceMs)?.let { reason -> abort(run, reason); return } + } + } + + /** The running operation hangs: give up on it without waiting for its thread. */ + private fun abort(run: SftpRun, reason: SftpFailure) { + val victim = synchronized(handoff) { + if (run.generation != generation) return + generation++; lock = Mutex() + client.also { client = null } + } + val (stream, cleanup) = run.abort() ?: return + if (running === run) running = null + SftpAbandon.release(victim?.let { { it.close() } }, stream, cleanup) + if (!closed) mutable.update { it.copy(loading = false, transfer = null, failure = reason) } + } + + private fun reset(gen: Int) { + val victim = synchronized(handoff) { if (gen != generation) null else client.also { client = null } } + victim?.close() + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpRun.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpRun.kt new file mode 100644 index 0000000..b001424 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpRun.kt @@ -0,0 +1,94 @@ +package cz.netkit.app.ssh + +import cz.netkit.shared.ssh.SftpFailure +import java.io.Closeable +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference + +/** + * State of ONE SFTP browser operation (review round 2): its stream, its clean-up, its activity clock + * and its cancel request. Nothing here is shared with the next operation, so a thread that returns + * late from a hanging provider or peer can neither replace the next transfer's stream, nor remove its + * clean-up, nor leave a cancel request behind that would abort the next refresh. + */ +internal class SftpRun( + val generation: Int, + val transfer: Boolean, + private val now: () -> Long, +) { + @Volatile private var activity = now() + @Volatile private var cancelAt = 0L + /** Cooperative flag for the copy loops (checked every 32 KiB). */ + val cancelled = AtomicBoolean(false) + private val aborted = AtomicBoolean(false) + private val stream = AtomicReference() + private val cleanup = AtomicReference<(() -> Unit)?>() + + fun alive() { activity = now() } + + /** "Cancel" applies only to this transfer; non-transfer operations ignore it. */ + fun requestCancel(): Boolean { + if (!transfer || aborted.get()) return false + if (cancelAt == 0L) cancelAt = now() + cancelled.set(true) + return true + } + + /** Why the watchdog must abort this run now, or null. */ + fun overdue(ioTimeoutMs: Long, cancelGraceMs: Long): SftpFailure? { + val time = now() + val requested = cancelAt + return when { + requested != 0L && time - requested > cancelGraceMs -> SftpFailure.CANCELLED + time - activity > ioTimeoutMs -> SftpFailure.CONNECTION + else -> null + } + } + + /** Registers the SAF stream of this run; after an abort it is closed at once instead (late return). */ + fun attach(value: Closeable) { + stream.set(value) + if (aborted.get()) stream.getAndSet(null)?.let { late -> SftpAbandon.closeQuietly("netkit-sftp-late-stream") { late.close() } } + } + + fun onFailure(action: () -> Unit) { cleanup.set(action) } + + /** The operation finished normally: its clean-up is no longer needed. */ + fun completed() { cleanup.set(null); stream.set(null) } + + /** Runs the clean-up if this run still owns it (exactly once, by the run or by the watchdog). */ + fun cleanUp() { cleanup.getAndSet(null)?.invoke() } + + val isAborted: Boolean get() = aborted.get() + + /** + * Gives up on this run: returns its stream and clean-up exactly once (null on a second call). + * The caller closes them through [SftpAbandon.release]. + */ + fun abort(): Pair Unit)?>? { + if (!aborted.compareAndSet(false, true)) return null + cancelled.set(true) + return stream.getAndSet(null) to cleanup.getAndSet(null) + } +} + +/** Closing after an abort: every step may block in a provider or a stuck transport, none may hold up another. */ +internal object SftpAbandon { + /** How long the document clean-up waits for the stream to close before deleting anyway. */ + const val STREAM_CLOSE_WAIT_MS = 3_000L + + fun closeQuietly(name: String, action: () -> Unit): Thread = + Thread({ try { action() } catch (_: Exception) { } }, name).apply { isDaemon = true; start() } + + /** + * The SFTP channel is closed on its own thread first, independent of the SAF stream; the stream on + * another; the half-written document is deleted after the stream closed or after [STREAM_CLOSE_WAIT_MS]. + */ + fun release(channel: (() -> Unit)?, stream: Closeable?, cleanup: (() -> Unit)?, streamWaitMs: Long = STREAM_CLOSE_WAIT_MS) { + channel?.let { closeQuietly("netkit-sftp-abort-channel", it) } + val closing = stream?.let { open -> closeQuietly("netkit-sftp-abort-stream") { open.close() } } + cleanup?.let { delete -> + closeQuietly("netkit-sftp-abort-cleanup") { closing?.join(streamWaitMs); delete() } + } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpScreen.kt new file mode 100644 index 0000000..5111d68 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpScreen.kt @@ -0,0 +1,211 @@ +package cz.netkit.app.ssh + +import android.text.format.Formatter +import androidx.activity.compose.BackHandler +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import cz.netkit.app.R +import cz.netkit.app.ui.* +import cz.netkit.app.ui.theme.NetKitShape +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.ssh.SFTP_MAX_ENTRIES +import cz.netkit.shared.ssh.SFTP_MAX_NAME +import cz.netkit.shared.ssh.SftpEntry +import cz.netkit.shared.ssh.SftpEntryKind +import cz.netkit.shared.ssh.SftpFailure +import cz.netkit.shared.ssh.displaySftpName +import cz.netkit.shared.ssh.isValidSftpName +import cz.netkit.shared.ssh.sftpProgress + +internal fun sftpFailureResource(failure: SftpFailure): Int = when (failure) { + SftpFailure.NOT_FOUND -> R.string.sftp_error_not_found + SftpFailure.PERMISSION -> R.string.sftp_error_permission + SftpFailure.EXISTS -> R.string.sftp_error_exists + SftpFailure.FAILURE -> R.string.sftp_error_failure + SftpFailure.TOO_LARGE -> R.string.sftp_error_too_large + SftpFailure.INVALID_NAME -> R.string.sftp_error_invalid_name + SftpFailure.CONNECTION -> R.string.sftp_error_connection + SftpFailure.UNSUPPORTED -> R.string.sftp_error_unsupported + SftpFailure.CANCELLED -> R.string.sftp_error_cancelled +} + +private fun sftpNoticeResource(notice: SftpNotice): Int = when (notice) { + SftpNotice.DOWNLOADED -> R.string.sftp_notice_downloaded + SftpNotice.UPLOADED -> R.string.sftp_notice_uploaded + SftpNotice.RENAMED -> R.string.sftp_notice_renamed + SftpNotice.DELETED -> R.string.sftp_notice_deleted + SftpNotice.CREATED -> R.string.sftp_notice_created +} + +/** Name dialog for "Nová složka" (entry == null) and "Přejmenovat". */ +private data class NameRequest(val entry: SftpEntry?) + +/** + * SFTP browser of the selected session (zadání 42 §2.3). Names are shown through [displaySftpName]; + * every SAF document is picked by the user, nothing is written without that choice. + */ +@Composable +internal fun SftpBrowser(controller: SftpController, onClose: () -> Unit, modifier: Modifier = Modifier, + onTransfer: (() -> Unit) -> Unit = { it() }) { + val state by controller.state.collectAsStateWithLifecycle() + val context = LocalContext.current + val colors = NetKitTheme.colors + var pendingDownload by rememberSaveable { mutableStateOf(null) } + var naming by remember { mutableStateOf(null) } + var deleting by remember { mutableStateOf(null) } + val download = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/octet-stream")) { uri -> + val name = pendingDownload; pendingDownload = null + val entry = state.entries.find { it.name == name } + if (uri != null && entry != null) onTransfer { controller.download(entry, uri) } + } + val upload = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> if (uri != null) onTransfer { controller.upload(uri) } } + BackHandler(onBack = onClose) + val busy = state.loading || state.transfer != null + Column(modifier, verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + SubscreenHeader(stringResource(R.string.sftp_title), onBack = onClose) + Text(state.path?.let(::displaySftpName).orEmpty(), style = FieldMono, color = colors.muted, maxLines = 2, + overflow = TextOverflow.MiddleEllipsis, modifier = Modifier.testTag("sftp_path")) + Row(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalAlignment = Alignment.CenterVertically) { + IconButton(onClick = controller::up, enabled = !busy && state.path != null && state.path != "/", modifier = Modifier.testTag("sftp_up")) { + Icon(NetKitIcons.FolderUp, contentDescription = stringResource(R.string.sftp_up), tint = colors.muted) + } + IconButton(onClick = controller::refresh, enabled = !busy && state.path != null, modifier = Modifier.testTag("sftp_refresh")) { + Icon(NetKitIcons.Refresh, contentDescription = stringResource(R.string.sftp_refresh), tint = colors.muted) + } + Spacer(Modifier.weight(1f)) + NeutralButton(stringResource(R.string.sftp_new_folder), small = true, icon = NetKitIcons.Plus, enabled = !busy && state.path != null, + onClick = { naming = NameRequest(null) }, modifier = Modifier.testTag("sftp_mkdir")) + PrimaryButton(stringResource(R.string.sftp_upload), small = true, icon = NetKitIcons.Upload, enabled = !busy && state.path != null, + onClick = { + try { upload.launch(arrayOf("*/*")) } + catch (_: android.content.ActivityNotFoundException) { + android.widget.Toast.makeText(context, R.string.ssh_share_unavailable, android.widget.Toast.LENGTH_LONG).show() + } + }, modifier = Modifier.testTag("sftp_upload")) + } + state.transfer?.let { transfer -> + Panel(Modifier.testTag("sftp_transfer")) { + Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(stringResource(if (transfer.upload) R.string.sftp_uploading else R.string.sftp_downloading, displaySftpName(transfer.name)), + style = NetKitType.body, color = colors.text, maxLines = 1, overflow = TextOverflow.Ellipsis) + val fraction = sftpProgress(transfer.done, transfer.total) + if (fraction != null) LinearProgressIndicator(progress = { fraction }, modifier = Modifier.fillMaxWidth(), color = colors.accent) + else LinearProgressIndicator(Modifier.fillMaxWidth(), color = colors.accent) + Row(verticalAlignment = Alignment.CenterVertically) { + Text(transfer.total?.let { stringResource(R.string.sftp_progress, Formatter.formatShortFileSize(context, transfer.done), Formatter.formatShortFileSize(context, it)) } + ?: stringResource(R.string.sftp_progress_unknown, Formatter.formatShortFileSize(context, transfer.done)), + Modifier.weight(1f), style = NetKitType.label, color = colors.muted) + NeutralButton(stringResource(R.string.sftp_cancel), small = true, onClick = controller::cancelTransfer, modifier = Modifier.testTag("sftp_cancel")) + } + } + } + } + if (state.loading && state.transfer == null) NetKitProgress() + state.failure?.let { failure -> + Box(Modifier.testTag("sftp_failure")) { StatusBanner(stringResource(sftpFailureResource(failure)), StatusKind.ERROR) } + } + state.notice?.let { notice -> Box(Modifier.testTag("sftp_notice")) { StatusBanner(stringResource(sftpNoticeResource(notice))) } } + if (state.truncated) Hint(pluralStringResource(R.plurals.sftp_truncated, SFTP_MAX_ENTRIES, SFTP_MAX_ENTRIES)) + if (state.hidden > 0) Hint(pluralStringResource(R.plurals.sftp_hidden, state.hidden, state.hidden)) + LazyColumn(Modifier.weight(1f).testTag("sftp_list")) { + if (!state.loading && state.path != null && state.entries.isEmpty()) item { EmptyState(stringResource(R.string.sftp_empty), NetKitIcons.Folder) } + items(state.entries, key = { it.name }) { entry -> + SftpRow(entry, enabled = !busy, onOpen = { controller.open(entry) }, + onDownload = { + pendingDownload = entry.name + try { download.launch(displaySftpName(entry.name)) } + catch (_: android.content.ActivityNotFoundException) { + pendingDownload = null + android.widget.Toast.makeText(context, R.string.ssh_share_unavailable, android.widget.Toast.LENGTH_LONG).show() + } + }, + onRename = { naming = NameRequest(entry) }, onDelete = { deleting = entry }) + } + item { Hint(stringResource(R.string.sftp_limit_note)) } + } + } + naming?.let { request -> NameDialog(request, onCancel = { naming = null }) { name -> + naming = null + if (request.entry == null) controller.mkdir(name) else controller.rename(request.entry, name) + } } + deleting?.let { entry -> + ConfirmDialog(stringResource(when (entry.kind) { + SftpEntryKind.DIRECTORY -> R.string.sftp_delete_dir_confirm + SftpEntryKind.LINK -> R.string.sftp_delete_link_confirm + else -> R.string.sftp_delete_file_confirm + }, displaySftpName(entry.name)), onCancel = { deleting = null }) { controller.delete(entry); deleting = null } + } +} + +@Composable +private fun SftpRow(entry: SftpEntry, enabled: Boolean, onOpen: () -> Unit, onDownload: () -> Unit, onRename: () -> Unit, onDelete: () -> Unit) { + val context = LocalContext.current + val colors = NetKitTheme.colors + var menu by remember { mutableStateOf(false) } + val navigable = entry.kind == SftpEntryKind.DIRECTORY || entry.kind == SftpEntryKind.LINK + val subtitle = when (entry.kind) { + SftpEntryKind.DIRECTORY -> stringResource(R.string.sftp_directory) + SftpEntryKind.LINK -> stringResource(R.string.sftp_link) + SftpEntryKind.FILE -> Formatter.formatShortFileSize(context, entry.size) + SftpEntryKind.OTHER -> stringResource(R.string.sftp_other) + } + val icon = when (entry.kind) { + SftpEntryKind.DIRECTORY -> NetKitIcons.Folder + SftpEntryKind.LINK -> NetKitIcons.Link + else -> NetKitIcons.File + } + ListRow(displaySftpName(entry.name), subtitle, icon, onClick = if (navigable && enabled) onOpen else null, + modifier = Modifier.testTag("sftp_entry_${entry.name.take(64)}"), showDivider = true) { + Box { + IconButton(onClick = { menu = true }, enabled = enabled, modifier = Modifier.testTag("sftp_entry_menu_${entry.name.take(64)}")) { + Icon(NetKitIcons.More, contentDescription = stringResource(R.string.sftp_entry_actions), tint = colors.muted) + } + NetKitMenu(expanded = menu, onDismiss = { menu = false }) { + // A link may point at a file: download follows it on the server (stat), size limit included. + if (entry.kind == SftpEntryKind.FILE || entry.kind == SftpEntryKind.LINK) DropdownMenuItem(text = { MenuText(stringResource(R.string.sftp_download)) }, + leadingIcon = { Icon(NetKitIcons.Download, null, Modifier.size(20.dp)) }, + onClick = { menu = false; onDownload() }, modifier = Modifier.testTag("sftp_download")) + DropdownMenuItem(text = { MenuText(stringResource(R.string.sftp_rename)) }, onClick = { menu = false; onRename() }, + modifier = Modifier.testTag("sftp_rename")) + DropdownMenuItem(text = { MenuText(stringResource(R.string.sftp_delete)) }, onClick = { menu = false; onDelete() }, + modifier = Modifier.testTag("sftp_delete")) + } + } + } +} + +@Composable +private fun NameDialog(request: NameRequest, onCancel: () -> Unit, onConfirm: (String) -> Unit) { + var name by rememberSaveable { mutableStateOf(request.entry?.name.orEmpty()) } + val valid = isValidSftpName(name) && name != request.entry?.name + NetKitAlert(onDismiss = onCancel, title = stringResource(if (request.entry == null) R.string.sftp_new_folder else R.string.sftp_rename), + text = { + Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + OutlinedTextField(name, { name = it.take(SFTP_MAX_NAME) }, label = { Text(stringResource(R.string.sftp_name)) }, singleLine = true, + textStyle = FieldMono, shape = NetKitShape.nested, colors = netKitFieldColors(), + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), modifier = Modifier.fillMaxWidth().testTag("sftp_name")) + if (name.isNotEmpty() && !isValidSftpName(name)) Hint(stringResource(R.string.sftp_error_invalid_name)) + } + }, + confirm = { PrimaryButton(stringResource(if (request.entry == null) R.string.sftp_create else R.string.sftp_save), small = true, enabled = valid, + onClick = { onConfirm(name) }, modifier = Modifier.testTag("sftp_name_confirm")) }, + dismiss = { NeutralButton(stringResource(R.string.sftp_cancel), small = true, onClick = onCancel) }) +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshAccess.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshAccess.kt new file mode 100644 index 0000000..898e0a8 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshAccess.kt @@ -0,0 +1,72 @@ +package cz.netkit.app.ssh + +import android.content.Context +import android.content.SharedPreferences +import android.os.SystemClock +import androidx.core.content.edit +import cz.netkit.shared.ssh.SshUnlock +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +/** Main-thread owner. Only the settings survive process death. The prompt belongs to the visible SSH screen. */ +internal class SshAccess(context: Context, private val scope: CoroutineScope) { + private val prefs = context.getSharedPreferences("ssh_access", Context.MODE_PRIVATE) + private fun settings() = SshUnlock(prefs.getBoolean("enabled", false), prefs.getInt("minutes", 5).coerceIn(0, 15)) + private val mutable = MutableStateFlow(settings()) + val state = mutable.asStateFlow() + private var expiry: Job? = null + var prompt: ((onSuccess: () -> Unit) -> Unit)? = null + private val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, _ -> + // Keep the authentication that authorised the change and re-time it under the new settings. + val now = SystemClock.elapsedRealtime() + val stored = settings() + mutable.value = mutable.value.reconfigure(stored.enabled, stored.minutes, now) + schedule(now) + } + + init { prefs.registerOnSharedPreferenceChangeListener(listener) } + + fun protect(fresh: Boolean = false, action: () -> Unit) { + if (!fresh && mutable.value.canReuse(SystemClock.elapsedRealtime())) action() + else prompt?.invoke { + actionAfterAuthentication(action) + } + } + + private fun actionAfterAuthentication(action: () -> Unit) { + val now = SystemClock.elapsedRealtime() + mutable.value = settings().copy(authenticatedAt = now) + schedule(now) + action() + } + + private fun schedule(now: Long) { + expiry?.cancel() + expiry = null + val wait = mutable.value.expiresIn(now) ?: return + expiry = scope.launch { + delay(wait) + refresh() + } + } + + fun setEnabled(enabled: Boolean) = protect(fresh = true) { prefs.edit { putBoolean("enabled", enabled) } } + fun setMinutes(minutes: Int) { + require(minutes in 0..15) + protect { prefs.edit { putInt("minutes", minutes) } } + } + fun canView() = mutable.value.canView(SystemClock.elapsedRealtime()) + fun refresh() { + val grant = mutable.value + if (!grant.canView(SystemClock.elapsedRealtime())) mutable.value = grant.copy(authenticatedAt = null) + } + fun leave() { + if (mutable.value.minutes == 0) mutable.value = mutable.value.copy(authenticatedAt = null) + else refresh() + } + fun close() { prefs.unregisterOnSharedPreferenceChangeListener(listener); prompt = null; expiry?.cancel() } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshForwarders.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshForwarders.kt new file mode 100644 index 0000000..743d40b --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshForwarders.kt @@ -0,0 +1,254 @@ +package cz.netkit.app.ssh + +import com.jcraft.jsch.Channel +import com.jcraft.jsch.Proxy +import com.jcraft.jsch.Session +import com.jcraft.jsch.SocketFactory +import cz.netkit.shared.ssh.Socks5 +import cz.netkit.shared.ssh.Socks5Parse +import cz.netkit.shared.ssh.Socks5Reply +import cz.netkit.shared.ssh.SshSocksCredentials +import java.io.Closeable +import java.io.InputStream +import java.io.OutputStream +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Semaphore +import java.util.concurrent.atomic.AtomicBoolean + +/** 127.0.0.1 as a literal: never resolved, never a wildcard or an external interface. */ +internal val LOOPBACK_V4: InetAddress = InetAddress.getByAddress("localhost", byteArrayOf(127, 0, 0, 1)) + +/** + * `-L` listener on 127.0.0.1:[port] → [host]:[targetPort] through the SSH session. Own accept loop + * instead of JSch `setPortForwardingL`: JSch disconnects the channel as soon as the local client sends + * EOF, which drops the reply of a request–response client (revize P2); [startTunnel] half-closes instead. + * Every client holds one of the session's [slots] (shared by all rules) until its tunnel ends; a client + * over the limit is closed at once, before any channel or thread exists for it. + */ +internal class LocalForwardServer( + port: Int, + private val host: String, + private val targetPort: Int, + private val open: (host: String, port: Int) -> Channel, + private val slots: Semaphore, + private val connectMillis: Int = 15_000, +) : Closeable { + private val server = ServerSocket(port, 16, LOOPBACK_V4) + val address: InetSocketAddress get() = server.localSocketAddress as InetSocketAddress + private val clients = ConcurrentHashMap.newKeySet() + private val closed = AtomicBoolean(false) + + fun start() { + Thread({ + while (!closed.get()) { + val client = try { server.accept() } catch (_: Exception) { break } + if (!slots.tryAcquire()) { try { client.close() } catch (_: Exception) { }; continue } + clients += client + Thread({ handle(client) }, "netkit-forward-client").apply { isDaemon = true }.start() + } + }, "netkit-forward-accept").apply { isDaemon = true }.start() + } + + private fun release(client: Socket) { if (clients.remove(client)) slots.release() } + + private fun handle(client: Socket) { + var opened: Channel? = null + var tunneled = false + try { + client.tcpNoDelay = true + val channel = open(host, targetPort) + opened = channel + val fromRemote = channel.inputStream; val toRemote = channel.outputStream + channel.connect(connectMillis) + if (closed.get()) return + tunneled = true + startTunnel("netkit-forward-tunnel", client, channel, toRemote, fromRemote) { release(client) } + } catch (_: Exception) { + } finally { + if (!tunneled) { try { client.close() } catch (_: Exception) { }; opened?.disconnect(); release(client) } + } + } + + override fun close() { + if (!closed.compareAndSet(false, true)) return + try { server.close() } catch (_: Exception) { } + clients.toList().forEach { try { it.close() } catch (_: Exception) { } } + } +} + +/** + * ProxyJump transport: the next hop's SSH stream runs inside a direct-tcpip channel of the previous + * session. The jump server resolves [host], as OpenSSH -J does. No local socket exists for this hop. + */ +internal class JumpProxy(private val via: Session, private val timeoutMillis: Int) : Proxy { + @Volatile private var channel: Channel? = null + private var input: InputStream? = null + private var output: OutputStream? = null + override fun connect(factory: SocketFactory?, host: String, port: Int, timeout: Int) { + val forwarder = via.getStreamForwarder(host, port) + input = forwarder.inputStream; output = forwarder.outputStream + channel = forwarder + forwarder.connect(if (timeout > 0) minOf(timeout, timeoutMillis) else timeoutMillis) + } + override fun getInputStream(): InputStream? = input + override fun getOutputStream(): OutputStream? = output + override fun getSocket(): Socket? = null + override fun close() { channel?.disconnect(); channel = null } +} + +/** + * Copies both directions on plain threads (Dispatchers.IO stays free). EOF of one direction only + * half-closes the other side (SSH channel EOF / TCP shutdownOutput), so a request–response client that + * shuts down its sending side still receives the reply. An error or both EOFs close everything once. + */ +internal fun startTunnel(name: String, client: Socket, channel: Channel, toRemote: OutputStream, fromRemote: InputStream, onClosed: () -> Unit) { + val closed = AtomicBoolean(false) + val finished = java.util.concurrent.atomic.AtomicInteger(0) + fun close() { + if (!closed.compareAndSet(false, true)) return + try { client.close() } catch (_: Exception) { } + channel.disconnect() + onClosed() + } + fun pump(input: InputStream, output: OutputStream, halfClose: () -> Unit) = Thread({ + val buffer = ByteArray(16384) + try { + while (!closed.get()) { + val count = input.read(buffer) + if (count < 0) { + halfClose() + if (finished.incrementAndGet() == 2) close() + return@Thread + } + output.write(buffer, 0, count); output.flush() + } + } catch (_: Exception) { close() } + }, name).apply { isDaemon = true } + // Closing JSch's channel output stream sends SSH_MSG_CHANNEL_EOF without closing the channel. + val up = pump(client.getInputStream(), toRemote) { try { toRemote.close() } catch (_: Exception) { } } + val down = pump(fromRemote, client.getOutputStream()) { try { client.shutdownOutput() } catch (_: Exception) { close() } } + up.start(); down.start() +} + +/** + * `-D`: minimal SOCKS5 server (no authentication, CONNECT only) on 127.0.0.1:[port]. Each accepted + * request opens a direct-tcpip channel through the SSH session; the SSH server resolves domain names. + * Bounded: [maxConnections] concurrent clients, handshake within [handshakeMillis], bounded buffers. + */ +internal class Socks5Server( + port: Int, + private val open: (host: String, port: Int) -> Channel, + /** Null only after the user explicitly chose "no authentication" in the profile. */ + private val credentials: SshSocksCredentials?, + private val maxConnections: Int = 32, + private val handshakeMillis: Int = 10_000, + private val connectMillis: Int = 15_000, +) : Closeable { + private val server = ServerSocket(port, 16, LOOPBACK_V4) + val address: InetSocketAddress get() = server.localSocketAddress as InetSocketAddress + private val slots = Semaphore(maxConnections) + private val clients = ConcurrentHashMap.newKeySet() + private val closed = AtomicBoolean(false) + + fun start() { + Thread({ + while (!closed.get()) { + val client = try { server.accept() } catch (_: Exception) { break } + if (!slots.tryAcquire()) { try { client.close() } catch (_: Exception) { }; continue } + clients += client + Thread({ handle(client) }, "netkit-socks-client").apply { isDaemon = true }.start() + } + }, "netkit-socks-accept").apply { isDaemon = true }.start() + } + + private fun release(client: Socket) { if (clients.remove(client)) slots.release() } + + private fun handle(client: Socket) { + var tunneled = false + var opened: Channel? = null + try { + client.soTimeout = handshakeMillis; client.tcpNoDelay = true + val input = client.getInputStream(); val output = client.getOutputStream() + val buffer = ByteArray(Socks5.MAX_GREETING + Socks5.MAX_USERPASS + Socks5.MAX_REQUEST) + var length = 0 + fun fill(): Boolean { + if (length == buffer.size) return false + val count = input.read(buffer, length, buffer.size - length) + if (count < 0) return false + length += count; return true + } + fun consume(count: Int) { System.arraycopy(buffer, count, buffer, 0, length - count); length -= count } + val method = if (credentials == null) Socks5.METHOD_NO_AUTH else Socks5.METHOD_USERNAME_PASSWORD + while (true) { + when (val greeting = Socks5.parseGreeting(buffer, length, method)) { + is Socks5Parse.Done -> { + output.write(if (credentials == null) Socks5.NO_AUTH_REPLY else Socks5.USERNAME_PASSWORD_REPLY); output.flush() + consume(greeting.consumed); break + } + is Socks5Parse.Invalid -> { + if (greeting.reply == Socks5Reply.NO_ACCEPTABLE_METHOD) { output.write(Socks5.NO_ACCEPTABLE_METHOD_REPLY); output.flush() } + return + } + Socks5Parse.NeedMore -> if (!fill()) return + } + } + if (credentials != null) while (true) { + when (val login = Socks5.parseUserPass(buffer, length)) { + is Socks5Parse.Done -> { + consume(login.consumed) + val ok = Socks5.constantTimeEquals(login.value.username, credentials.username.encodeToByteArray()) and + Socks5.constantTimeEquals(login.value.password, credentials.password.encodeToByteArray()) + login.value.password.fill(0) + output.write(if (ok) Socks5.AUTH_SUCCESS_REPLY else Socks5.AUTH_FAILURE_REPLY); output.flush() + if (!ok) return // RFC 1929: failure closes the connection. + break + } + is Socks5Parse.Invalid -> return + Socks5Parse.NeedMore -> if (!fill()) return + } + } + val request: cz.netkit.shared.ssh.Socks5Request + while (true) { + when (val parsed = Socks5.parseRequest(buffer, length)) { + is Socks5Parse.Done -> { request = parsed.value; consume(parsed.consumed); break } + is Socks5Parse.Invalid -> { + if (parsed.reply.code >= 0) { output.write(Socks5.reply(parsed.reply)); output.flush() } + return + } + Socks5Parse.NeedMore -> if (!fill()) return + } + } + val channel: Channel; val fromRemote: InputStream; val toRemote: OutputStream + try { + // Streams must exist before connect, otherwise early server data is lost (JSch stream forwarder contract). + channel = open(request.host, request.port) + opened = channel + fromRemote = channel.inputStream; toRemote = channel.outputStream + channel.connect(connectMillis) + } catch (_: Exception) { + // The SSH server refused or could not reach the target; its message is never forwarded. + output.write(Socks5.reply(Socks5Reply.CONNECTION_REFUSED)); output.flush(); return + } + output.write(Socks5.reply(Socks5Reply.SUCCEEDED)); output.flush() + if (length > 0) { toRemote.write(buffer, 0, length); toRemote.flush() } // Optimistic data. + client.soTimeout = 0 + tunneled = true + startTunnel("netkit-socks-tunnel", client, channel, toRemote, fromRemote) { release(client) } + } catch (_: Exception) { + } finally { + // Any failure before the hand-over (including writing the success reply) must not leak the channel. + if (!tunneled) { try { client.close() } catch (_: Exception) { }; opened?.disconnect(); release(client) } + } + } + + override fun close() { + if (!closed.compareAndSet(false, true)) return + try { server.close() } catch (_: Exception) { } + clients.toList().forEach { try { it.close() } catch (_: Exception) { } } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshLockUi.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshLockUi.kt new file mode 100644 index 0000000..6900d1e --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshLockUi.kt @@ -0,0 +1,132 @@ +package cz.netkit.app.ssh + +import android.app.Activity +import android.app.KeyguardManager +import android.os.Build +import android.os.SystemClock +import android.widget.Toast +import androidx.activity.compose.LocalActivity +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.biometric.BiometricManager +import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG +import androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL +import androidx.biometric.BiometricPrompt +import androidx.compose.foundation.layout.* +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveableStateHolder +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.fragment.app.FragmentActivity +import androidx.lifecycle.withResumed +import kotlinx.coroutines.launch +import cz.netkit.app.R +import cz.netkit.app.ui.* +import cz.netkit.shared.ssh.SshUnlock + +@Suppress("DEPRECATION") // Android 10 cannot combine STRONG and DEVICE_CREDENTIAL in BiometricPrompt. +@Composable +internal fun SshLockHost(access: SshAccess, modifier: Modifier, content: @Composable () -> Unit) { + val activity = LocalActivity.current as FragmentActivity + var pending by remember { mutableStateOf<(() -> Unit)?>(null) } + var credentialAction by remember { mutableStateOf<(() -> Unit)?>(null) } + val scope = rememberCoroutineScope() + fun finish(success: Boolean) { + val action = pending ?: return + if (!success) { pending = null; return } + scope.launch { + activity.lifecycle.withResumed { + if (pending === action && !activity.isFinishing) { + pending = null + action() + } + } + } + } + val credential = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { + val request = credentialAction + credentialAction = null + if (request != null && pending === request) finish(it.resultCode == Activity.RESULT_OK) + } + DisposableEffect(access, activity) { + val title = activity.getString(R.string.ssh_unlock) + val manager = BiometricManager.from(activity) + fun unavailable() { + finish(false) + Toast.makeText(activity, R.string.ssh_auth_unavailable, Toast.LENGTH_LONG).show() + } + fun confirmCredential() { + val guard = activity.getSystemService(KeyguardManager::class.java) + val intent = if (guard.isDeviceSecure) guard.createConfirmDeviceCredentialIntent(title, null) else null + if (intent == null) unavailable() else { + credentialAction = pending + try { credential.launch(intent) } + catch (_: android.content.ActivityNotFoundException) { credentialAction = null; unavailable() } + } + } + val biometric = BiometricPrompt(activity, activity.mainExecutor, object : BiometricPrompt.AuthenticationCallback() { + override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) = finish(true) + override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { + if (pending == null) return + val useCredential = Build.VERSION.SDK_INT == 29 && errorCode in setOf( + BiometricPrompt.ERROR_NEGATIVE_BUTTON, BiometricPrompt.ERROR_LOCKOUT, + BiometricPrompt.ERROR_LOCKOUT_PERMANENT, BiometricPrompt.ERROR_HW_UNAVAILABLE, + ) + if (useCredential) confirmCredential() + else { + finish(false) + Toast.makeText(activity, errString, Toast.LENGTH_SHORT).show() + } + } + }) + access.prompt = { action -> + if (pending == null) { + pending = action + scope.launch { + activity.lifecycle.withResumed { + if (pending !== action || activity.isFinishing) return@withResumed + val combined = Build.VERSION.SDK_INT >= 30 + val allowed = if (combined) BIOMETRIC_STRONG or DEVICE_CREDENTIAL else BIOMETRIC_STRONG + if (manager.canAuthenticate(allowed) == BiometricManager.BIOMETRIC_SUCCESS) { + val info = BiometricPrompt.PromptInfo.Builder().setTitle(title).setAllowedAuthenticators(allowed) + if (!combined) info.setNegativeButtonText(activity.getString(R.string.ssh_device_credential)) + biometric.authenticate(info.build()) + } else if (!combined) confirmCredential() else unavailable() + } + } + } + } + onDispose { + access.prompt = null + credentialAction = null + if (pending != null) { pending = null; biometric.cancelAuthentication() } + access.leave() + } + } + val grant by access.state.collectAsState() + val holder = rememberSaveableStateHolder() + if (grant.canView(SystemClock.elapsedRealtime())) holder.SaveableStateProvider("content") { content() } + else Column(modifier.padding(Spacing.normal), verticalArrangement = Arrangement.spacedBy(Spacing.normal)) { + ScreenHeader(stringResource(R.string.ssh_lock_title)) + PrimaryButton(stringResource(R.string.ssh_unlock), onClick = { access.protect { } }, + modifier = Modifier.testTag("ssh_unlock")) + } +} + +@Composable +internal fun SshLockSettings(access: SshAccess, grant: SshUnlock) { + var menu by remember { mutableStateOf(false) } + CheckRow(grant.enabled, stringResource(R.string.ssh_lock_title)) { access.setEnabled(it) } + if (grant.enabled) Box { + NeutralButton(stringResource(R.string.ssh_lock_duration, grant.minutes), onClick = { menu = true }) + NetKitMenu(expanded = menu, onDismiss = { menu = false }) { + (0..15).forEach { minutes -> + DropdownMenuItem(text = { Text(if (minutes == 0) stringResource(R.string.ssh_lock_each) else stringResource(R.string.ssh_lock_minutes, minutes)) }, + onClick = { menu = false; access.setMinutes(minutes) }) + } + } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProductivityUi.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProductivityUi.kt new file mode 100644 index 0000000..2a015a6 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProductivityUi.kt @@ -0,0 +1,316 @@ +@file:OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class) + +package cz.netkit.app.ssh + +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.clickable +import androidx.compose.foundation.horizontalScroll +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.runtime.* +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import cz.netkit.app.R +import cz.netkit.app.ui.* +import cz.netkit.app.ui.theme.NetKitShape +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.ssh.* +import java.util.UUID +import kotlinx.serialization.json.Json + +/** Entry card on the profile list, same layout as the key card. */ +@Composable +internal fun SnippetCard(state: SshUiState, onOpen: () -> Unit) { + val count = state.data.snippets.size + Panel(Modifier.testTag("ssh_snippets"), padding = 0.dp, onClick = onOpen) { + ListRow(stringResource(R.string.ssh_snippets), + if (count == 0) stringResource(R.string.ssh_snippets_card_empty) else pluralStringResource(R.plurals.ssh_snippets_card_count, count, count), + NetKitIcons.Document, modifier = Modifier.padding(horizontal = Spacing.normal, vertical = Spacing.tiny)) { + Icon(NetKitIcons.ChevronRight, null, Modifier.size(18.dp), tint = NetKitTheme.colors.dim) + } + } +} + +/** Snippet list with an inline editor. A text that looks like a credential needs an explicit second confirmation. */ +@Composable +internal fun SnippetManager(state: SshUiState, viewModel: SshViewModel, onClose: () -> Unit) { + var editingJson by rememberSaveable { mutableStateOf(null) } + val editing = remember(editingJson) { editingJson?.let { Json.decodeFromString(it) } } + var name by rememberSaveable(editing?.id) { mutableStateOf(editing?.name.orEmpty()) } + var text by rememberSaveable(editing?.id) { mutableStateOf(editing?.text.orEmpty()) } + var sendEnter by rememberSaveable(editing?.id) { mutableStateOf(editing?.sendEnter ?: true) } + var scope by rememberSaveable(editing?.id) { mutableStateOf(editing?.profileId) } + var deleting by remember { mutableStateOf(null) } + var secretWarning by remember { mutableStateOf(null) } + val colors = NetKitTheme.colors + val reset = { editingJson = null; name = ""; text = ""; sendEnter = true; scope = null } + BackHandler { if (editing != null) reset() else onClose() } + val draft = SshSnippet(editing?.id ?: "draft", name.trim(), text, sendEnter, scope) + val full = editing == null && state.data.snippets.size >= SSH_MAX_SNIPPETS + val duplicate = draft.name.isNotEmpty() && snippetNameTaken(state.data, draft) + LazyColumn(verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { + item { SubscreenHeader(stringResource(R.string.ssh_snippets), onBack = { if (editing != null) reset() else onClose() }) } + item { + Panel { + Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + SshField(name, { name = it.take(SSH_SNIPPET_NAME_LIMIT) }, R.string.ssh_snippet_name) + OutlinedTextField(text, { value -> text = value.take(SSH_SNIPPET_TEXT_LIMIT) }, label = { Text(stringResource(R.string.ssh_snippet_text)) }, + textStyle = FieldMono, shape = NetKitShape.nested, colors = netKitFieldColors(), + modifier = Modifier.fillMaxWidth().testTag("ssh_snippet_text")) + CheckRow(sendEnter, stringResource(R.string.ssh_snippet_send_enter)) { sendEnter = it } + Text(stringResource(R.string.ssh_snippet_scope_label), style = NetKitType.label, color = colors.muted) + ChoiceRow(scope == null, stringResource(R.string.ssh_snippet_scope_all), onClick = { scope = null }) + state.data.profiles.forEach { profile -> + ChoiceRow(scope == profile.id, stringResource(R.string.ssh_snippet_scope_profile, profile.name), onClick = { scope = profile.id }) + } + Hint(stringResource(if (full) R.string.ssh_snippet_limit else R.string.ssh_snippet_hint)) + if (name.isNotEmpty() && text.isNotEmpty() && !draft.copy(id = "draft").valid()) Hint(stringResource(R.string.ssh_snippet_invalid)) + if (duplicate) Box(Modifier.testTag("ssh_snippet_duplicate")) { StatusBanner(stringResource(R.string.ssh_snippet_duplicate), StatusKind.WARNING) } + FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + PrimaryButton(stringResource(if (editing == null) R.string.ssh_snippet_add else R.string.ssh_save), small = true, + enabled = draft.copy(id = "draft").valid() && !duplicate && !state.busy && !full, modifier = Modifier.testTag("ssh_snippet_save"), + onClick = { + val snippet = draft.copy(id = editing?.id ?: UUID.randomUUID().toString()) + if (snippetLooksSecret(snippet.text)) secretWarning = snippet + else viewModel.saveSnippet(snippet) { reset() } + }) + if (editing != null) NeutralButton(stringResource(R.string.ssh_cancel), small = true, onClick = reset) + } + } + } + } + if (state.data.snippets.isEmpty()) item { Panel { EmptyState(stringResource(R.string.ssh_snippet_empty), NetKitIcons.Document) } } + items(state.data.snippets, key = { it.id }) { snippet -> + Panel { + Text(snippet.name, style = NetKitType.panelTitle, color = colors.text) + Text(snippet.text + if (snippet.sendEnter) " ⏎" else "", style = NetKitType.addressFor(NetKitType.label), color = colors.muted, + maxLines = 3, overflow = TextOverflow.Ellipsis) + snippet.profileId?.let { id -> state.data.profiles.find { it.id == id } }?.let { + Tag(stringResource(R.string.ssh_snippet_scope_profile, it.name), Tone.NEUTRAL) + } + FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + TonalButton(stringResource(R.string.ssh_edit), small = true, enabled = !state.busy, + onClick = { editingJson = Json.encodeToString(snippet) }) + DangerTextButton(stringResource(R.string.ssh_delete), enabled = !state.busy) { deleting = snippet } + } + } + } + } + deleting?.let { snippet -> ConfirmDialog(stringResource(R.string.ssh_snippet_delete, snippet.name), onCancel = { deleting = null }) { + viewModel.deleteSnippet(snippet.id); deleting = null + if (editing?.id == snippet.id) reset() + } } + secretWarning?.let { snippet -> + NetKitAlert(onDismiss = { secretWarning = null }, title = stringResource(R.string.ssh_snippet_secret_title), + text = { Box(Modifier.testTag("ssh_snippet_secret_warning")) { StatusBanner(stringResource(R.string.ssh_snippet_secret_warning), StatusKind.WARNING) } }, + confirm = { PrimaryButton(stringResource(R.string.ssh_snippet_save_anyway), small = true, modifier = Modifier.testTag("ssh_snippet_save_anyway"), + onClick = { viewModel.saveSnippet(snippet) { reset() }; secretWarning = null }) }, + dismiss = { NeutralButton(stringResource(R.string.ssh_cancel), small = true, onClick = { secretWarning = null }) }) + } +} + +/** Horizontal snippet bar above the terminal keys; sends through the normal bounded write queue. */ +@Composable +internal fun SnippetBar(snippets: List, enabled: Boolean, onSend: (SshSnippet) -> Unit) { + if (snippets.isEmpty()) return + Row(Modifier.horizontalScroll(rememberScrollState()).testTag("ssh_snippet_bar"), horizontalArrangement = Arrangement.spacedBy(Spacing.tiny)) { + snippets.forEach { snippet -> + val label = stringResource(R.string.ssh_snippet_send, snippet.name) + KeyPill(snippet.name, { onSend(snippet) }, enabled = enabled, width = 64.dp, + modifier = Modifier.testTag("ssh_snippet_${snippet.id}").semantics { contentDescription = label }) + } + } +} + +/** Active forwards of a session: loopback address, target, state, copy action. */ +@Composable +internal fun SessionForwards(session: SshSessionState, access: SshAccess, expanded: Boolean, setExpanded: (Boolean) -> Unit) { + if (session.forwards.isEmpty()) return + val context = LocalContext.current + val colors = NetKitTheme.colors + val problems = session.forwards.count { it.state != SshForwardState.ACTIVE } + val openSocks = session.forwards.any { it.kind == SshForwardKind.DYNAMIC && it.state == SshForwardState.ACTIVE && it.credentials == null } + // Review of 41 (P2): up to 8× -L and -D above the terminal must not eat its height (with the keyboard + // open the terminal would get 0 px). One summary line; details on demand in a bounded, scrolled panel. + // Details and the keyboard exclude each other: typing collapses them, opening them closes the keyboard. + val imeVisible = WindowInsets.isImeVisible + LaunchedEffect(imeVisible) { if (imeVisible) setExpanded(false) } + val view = LocalView.current + Column(Modifier.fillMaxWidth().testTag("ssh_forwards"), verticalArrangement = Arrangement.spacedBy(Spacing.tiny)) { + Row(Modifier.fillMaxWidth().clickable { + if (expanded) setExpanded(false) + else access.protect { + context.getSystemService(android.view.inputmethod.InputMethodManager::class.java) + ?.hideSoftInputFromWindow(view.windowToken, 0) + setExpanded(true) + } + }.padding(vertical = Spacing.tiny).testTag("ssh_forwards_toggle"), + horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalAlignment = Alignment.CenterVertically) { + Text(pluralStringResource(R.plurals.ssh_forwards_summary, session.forwards.size, session.forwards.size), + Modifier.weight(1f), style = NetKitType.label, color = colors.text, maxLines = 1, overflow = TextOverflow.Ellipsis) + if (problems > 0) Tag(pluralStringResource(R.plurals.ssh_forwards_problems, problems, problems), Tone.ERR, dot = true) + // The open-SOCKS warning stays visible even when collapsed (security, zadání 41). + if (openSocks) Tag(stringResource(R.string.ssh_forwards_socks_open_tag), Tone.WARN, dot = true) + Icon(if (expanded) NetKitIcons.Minus else NetKitIcons.Expand, + contentDescription = stringResource(if (expanded) R.string.ssh_forwards_collapse else R.string.ssh_forwards_expand), + tint = colors.muted, modifier = Modifier.size(18.dp)) + } + if (expanded) Column(Modifier.fillMaxWidth().heightIn(max = 120.dp).verticalScroll(rememberScrollState()).testTag("ssh_forwards_details"), + verticalArrangement = Arrangement.spacedBy(Spacing.tiny)) { + session.forwards.forEach { forward -> ForwardDetail(forward, context, access) } + } + } +} + +@Composable +private fun ForwardDetail(forward: SshForwardStatus, context: android.content.Context, access: SshAccess) { + val colors = NetKitTheme.colors + val (stateText, tone) = when (forward.state) { + SshForwardState.ACTIVE -> R.string.ssh_forward_active to Tone.OK + SshForwardState.PORT_IN_USE -> R.string.ssh_forward_port_in_use to Tone.ERR + SshForwardState.FAILED -> R.string.ssh_forward_failed to Tone.ERR + } + FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(Spacing.small), + verticalArrangement = Arrangement.spacedBy(Spacing.tiny), itemVerticalAlignment = Alignment.CenterVertically) { + Text(if (forward.kind == SshForwardKind.DYNAMIC) stringResource(R.string.ssh_forward_socks, forward.localAddress) + else "${forward.localAddress} → ${forward.target}", style = NetKitType.addressFor(NetKitType.label), color = colors.text) + Tag(stringResource(stateText), tone, dot = true, modifier = Modifier.testTag("ssh_forward_state_${forward.localPort}")) + if (forward.state == SshForwardState.ACTIVE) NeutralButton(stringResource(R.string.ssh_forward_copy, forward.localAddress), small = true, + modifier = Modifier.testTag("ssh_forward_copy_${forward.localPort}"), onClick = { copyText(context, forward.localAddress) }) + } + forward.credentials?.let { login -> + // Shown only while the session runs; generated per session and never stored. + FlowRow(Modifier.fillMaxWidth().testTag("ssh_socks_login"), horizontalArrangement = Arrangement.spacedBy(Spacing.small), + verticalArrangement = Arrangement.spacedBy(Spacing.tiny), itemVerticalAlignment = Alignment.CenterVertically) { + Text(stringResource(R.string.ssh_forward_socks_login, login.username, login.password), + style = NetKitType.addressFor(NetKitType.label), color = colors.muted) + NeutralButton(stringResource(R.string.ssh_forward_socks_copy_password), small = true, + onClick = { access.protect { copyText(context, login.password, sensitive = true) } }) + } + } + if (forward.kind == SshForwardKind.DYNAMIC && forward.state == SshForwardState.ACTIVE && forward.credentials == null) + StatusBanner(stringResource(R.string.ssh_forward_socks_open_warning), StatusKind.WARNING) +} + +/** Recording indicator and the reason a log stopped by itself. */ +@Composable +internal fun SessionLogStatus(session: SshSessionState, viewModel: SshViewModel) { + if (session.logging) Box(Modifier.testTag("ssh_log_active")) { Tag(stringResource(R.string.ssh_log_active), Tone.WARN, dot = true) } + session.logStop?.let { reason -> + val (text, kind) = when (reason) { + SshLogStop.LIMIT -> R.string.ssh_log_stopped_limit to StatusKind.WARNING + SshLogStop.WRITE_FAILED -> R.string.ssh_log_stopped_failed to StatusKind.ERROR + SshLogStop.OVERFLOW -> R.string.ssh_log_stopped_overflow to StatusKind.WARNING + SshLogStop.USER, SshLogStop.SESSION_ENDED -> R.string.ssh_log_stopped to StatusKind.INFO + } + Column(Modifier.testTag("ssh_log_stopped"), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + StatusBanner(stringResource(text), kind) + NeutralButton(stringResource(R.string.ssh_ok), small = true, onClick = { viewModel.dismissLogStop(session.id) }) + } + } +} + +/** Editable jump/forwarding settings of the profile form; every value is saveable (none is a secret). */ +internal class ProfileRouting(jumpState: MutableState, private val forwardsState: MutableState, + dynamicEnabledState: MutableState, dynamicPortState: MutableState, dynamicNoAuthState: MutableState, + localPortState: MutableState, targetHostState: MutableState, targetPortState: MutableState) { + var localPort by localPortState + var targetHost by targetHostState + var targetPort by targetPortState + val hasPendingForward get() = localPort.isNotEmpty() || targetPort.isNotEmpty() || targetHost != "127.0.0.1" + var jump: String? by jumpState + var forwards: List + get() = Json.decodeFromString(forwardsState.value) + set(value) { forwardsState.value = Json.encodeToString(value) } + var dynamicEnabled: Boolean by dynamicEnabledState + var dynamicPort: String by dynamicPortState + var dynamicNoAuth: Boolean by dynamicNoAuthState + fun apply(profile: SshProfile): SshProfile = profile.copy(jumpProfileId = jump, localForwards = forwards, + dynamicForwardPort = if (dynamicEnabled) dynamicPort.toIntOrNull() ?: -1 else null, + dynamicForwardNoAuth = dynamicEnabled && dynamicNoAuth) +} + +@Composable +internal fun rememberProfileRouting(original: SshProfile): ProfileRouting { + val jump = rememberSaveable(original.id) { mutableStateOf(original.jumpProfileId) } + val forwards = rememberSaveable(original.id) { mutableStateOf(Json.encodeToString(original.localForwards)) } + val enabled = rememberSaveable(original.id) { mutableStateOf(original.dynamicForwardPort != null) } + val port = rememberSaveable(original.id) { mutableStateOf(original.dynamicForwardPort?.toString() ?: "1080") } + val noAuth = rememberSaveable(original.id) { mutableStateOf(original.dynamicForwardNoAuth) } + val localPort = rememberSaveable(original.id) { mutableStateOf("") } + val targetHost = rememberSaveable(original.id) { mutableStateOf("127.0.0.1") } + val targetPort = rememberSaveable(original.id) { mutableStateOf("") } + return remember(original.id) { ProfileRouting(jump, forwards, enabled, port, noAuth, localPort, targetHost, targetPort) } +} + +/** Jump host choice and -L/-D rules inside the profile form. */ +@Composable +internal fun ProfileRoutingFields(draft: SshProfile, data: SshData, routing: ProfileRouting) { + val colors = NetKitTheme.colors + val candidates = data.jumpCandidates(draft) + Text(stringResource(R.string.ssh_jump_host), style = NetKitType.panelTitle, color = colors.text) + Column(Modifier.testTag("ssh_jump_choices")) { + ChoiceRow(routing.jump == null, stringResource(R.string.ssh_jump_none), onClick = { routing.jump = null }) + candidates.forEach { candidate -> + ChoiceRow(routing.jump == candidate.id, stringResource(R.string.ssh_jump_via, candidate.name), + onClick = { routing.jump = candidate.id }, modifier = Modifier.testTag("ssh_jump_${candidate.id}")) + } + } + if (routing.jump != null && candidates.none { it.id == routing.jump }) StatusBanner(stringResource(R.string.ssh_jump_missing), StatusKind.WARNING) + Hint(stringResource(R.string.ssh_jump_hint)) + HorizontalDivider(thickness = 1.dp, color = colors.divider) + Text(stringResource(R.string.ssh_forwards), style = NetKitType.panelTitle, color = colors.text) + routing.forwards.forEach { rule -> + Row(verticalAlignment = Alignment.CenterVertically) { + Text("127.0.0.1:${rule.localPort} → ${rule.target}", Modifier.weight(1f), style = NetKitType.addressFor(NetKitType.label), color = colors.text) + val label = stringResource(R.string.ssh_forward_remove, "${rule.localPort}") + IconButton(onClick = { routing.forwards = routing.forwards - rule }, modifier = Modifier.semantics { contentDescription = label }) { + Icon(NetKitIcons.Close, null, Modifier.size(18.dp), tint = colors.muted) + } + } + } + if (routing.forwards.isNotEmpty()) StatusBanner(stringResource(R.string.ssh_forward_local_warning), StatusKind.WARNING) + if (routing.forwards.size < SSH_MAX_LOCAL_FORWARDS) { + val rule = SshLocalForward(routing.localPort.toIntOrNull() ?: 0, routing.targetHost.trim(), routing.targetPort.toIntOrNull() ?: 0) + val usedPorts = routing.forwards.map { it.localPort } + listOfNotNull(routing.dynamicPort.toIntOrNull().takeIf { routing.dynamicEnabled }) + val addable = rule.valid() && rule.localPort !in usedPorts + SshField(routing.localPort, { routing.localPort = it.filter(Char::isDigit).take(5) }, R.string.ssh_forward_local_port, number = true, mono = true) + SshField(routing.targetHost, { routing.targetHost = it.take(253) }, R.string.ssh_forward_host, mono = true) + SshField(routing.targetPort, { routing.targetPort = it.filter(Char::isDigit).take(5) }, R.string.ssh_forward_port, number = true, mono = true) + if ((routing.localPort.isNotEmpty() && routing.targetPort.isNotEmpty()) && !addable) Hint(stringResource(R.string.ssh_forward_invalid)) + NeutralButton(stringResource(R.string.ssh_forward_add), small = true, enabled = addable, modifier = Modifier.testTag("ssh_forward_add"), + onClick = { + routing.forwards = routing.forwards + rule + routing.localPort = "" + routing.targetHost = "127.0.0.1" + routing.targetPort = "" + }) + } + CheckRow(routing.dynamicEnabled, stringResource(R.string.ssh_forward_dynamic)) { routing.dynamicEnabled = it } + if (routing.dynamicEnabled) { + SshField(routing.dynamicPort, { routing.dynamicPort = it.filter(Char::isDigit).take(5) }, R.string.ssh_forward_dynamic_port, number = true, mono = true) + Hint(stringResource(R.string.ssh_forward_dynamic_hint)) + CheckRow(routing.dynamicNoAuth, stringResource(R.string.ssh_forward_dynamic_no_auth)) { routing.dynamicNoAuth = it } + if (routing.dynamicNoAuth) StatusBanner(stringResource(R.string.ssh_forward_socks_open_warning), StatusKind.WARNING) + } + Hint(stringResource(R.string.ssh_forward_hint)) +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt index e3e001c..a1406a9 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt @@ -13,7 +13,7 @@ sealed interface SshProfileImportError { enum class Operation : SshProfileImportError { BLOCKED, IO, TIMEOUT, KEY_UNAVAILABLE } } -data class PendingSshProfileImport(val incoming: SshProfileImport, val plan: SshImportPlan) +typealias PendingSshProfileImport = cz.netkit.shared.ssh.PendingSshProfileImport data class SshProfileImportState( val pendingProfileImport: PendingSshProfileImport? = null, val busy: Boolean = false, @@ -51,9 +51,9 @@ internal class SshProfileImportController( if (blocked()) { fail(SshProfileImportError.Operation.BLOCKED); return@withLock } val incoming = withContext(worker) { decodeSshProfileImport(readBytes()) } val data = read() - val plan = withContext(worker) { planSshProfileImport(data, incoming, null, generateId) } + val pending = withContext(worker) { PendingSshProfileImport.prepare(data, incoming, generateId) } if (blocked()) fail(SshProfileImportError.Operation.BLOCKED) - else mutableState.value = SshProfileImportState(pendingProfileImport = PendingSshProfileImport(incoming, plan)) + else mutableState.value = SshProfileImportState(pendingProfileImport = pending) } } catch (error: Exception) { handle(error) } finally { mutableState.value = mutableState.value.copy(busy = false) } @@ -74,11 +74,8 @@ internal class SshProfileImportController( withContext(worker) { update { current -> if (blocked()) throw ImportBlockedException() - applySshImportPlan(current, pending.plan) // Check preview freshness and capacity inside the transaction. if (keyRef != null && current.keys.none { it.id == keyRef }) throw ImportKeyUnavailableException() - val ids = pending.plan.newProfiles.map { it.after.id }.iterator() - val selected = planSshProfileImport(current, pending.incoming, keyRef) { ids.next() } - applySshImportPlan(current, selected) + pending.apply(current, keyRef) } for (ref in pending.plan.detachedSecretRefs) { try { deleteSecret(ref) } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt index c7989a1..88bd036 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt @@ -51,6 +51,9 @@ internal fun ProfileImportDialog(pending: PendingSshProfileImport, state: SshUiS val colors = NetKitTheme.colors val plan = pending.plan var keyRef by rememberSaveable(plan) { mutableStateOf(state.data.keys.firstOrNull()?.id) } + // A changed snippet sends a different command under a familiar name: explicit acknowledgement. + var snippetsAcknowledged by rememberSaveable(plan) { mutableStateOf(false) } + val profileNames = state.data.profiles.associate { it.id to it.name } + plan.newProfiles.associate { it.after.id to it.after.name } NetKitAlert( onDismiss = { if (!state.profileImportBusy) onCancel() }, title = stringResource(R.string.ssh_import_title), @@ -60,6 +63,8 @@ internal fun ProfileImportDialog(pending: PendingSshProfileImport, state: SshUiS Text(stringResource(R.string.ssh_import_summary, plan.newProfiles.size, plan.updatedProfiles.size, plan.unchangedProfiles.size, plan.skipped.size), style = NetKitType.body, color = colors.text) plan.source?.let { Text(stringResource(R.string.ssh_import_source, it), style = NetKitType.label, color = colors.muted) } + if (plan.newSnippets + plan.updatedSnippets > 0) Text(stringResource(R.string.ssh_import_snippets, plan.newSnippets, plan.updatedSnippets), + style = NetKitType.label, color = colors.muted) } if (plan.newProfiles.isNotEmpty()) { item { Eyebrow(stringResource(R.string.ssh_import_new), Modifier.padding(top = Spacing.small)) } @@ -78,6 +83,31 @@ internal fun ProfileImportDialog(pending: PendingSshProfileImport, state: SshUiS item { Eyebrow(stringResource(R.string.ssh_import_updated), Modifier.padding(top = Spacing.small)) } items(plan.updatedProfiles, key = { "u" + it.incoming.alias }) { ImportRow(it, Tone.WARN, keyRef, state) } } + if (plan.snippetChanges.isNotEmpty()) { + item { + Column(Modifier.testTag("ssh_import_snippets"), verticalArrangement = Arrangement.spacedBy(Spacing.tiny)) { + Eyebrow(stringResource(R.string.ssh_snippets), Modifier.padding(top = Spacing.small)) + StatusBanner(stringResource(R.string.ssh_import_snippets_enter), StatusKind.INFO) + } + } + items(plan.snippetChanges, key = { "snippet-" + it.after.id }) { change -> + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + val scope = change.after.profileId?.let { profileNames[it] } + Text(change.after.name + (scope?.let { " · $it" } ?: ""), style = NetKitType.panelTitle, color = colors.text) + val mono = NetKitType.addressFor(NetKitType.label) + if (change.before != null) { + Text(stringResource(R.string.ssh_import_snippet_before, change.before!!.text), style = mono, color = colors.muted) + Text(stringResource(R.string.ssh_import_snippet_after, change.after.text), style = mono, color = colors.warn) + } else Text(stringResource(R.string.ssh_import_snippet_new, change.after.text), style = mono, color = colors.text) + } + } + if (plan.updatedSnippets > 0) item { + Column(Modifier.testTag("ssh_import_snippets_ack")) { + StatusBanner(stringResource(R.string.ssh_import_snippets_changed_warning), StatusKind.WARNING) + CheckRow(snippetsAcknowledged, stringResource(R.string.ssh_import_snippets_ack)) { snippetsAcknowledged = it } + } + } + } if (plan.skipped.isNotEmpty()) { item { Eyebrow(stringResource(R.string.ssh_import_skipped), Modifier.padding(top = Spacing.small)) } items(plan.skipped, key = { "s" + it.alias }) { skipped -> @@ -92,7 +122,9 @@ internal fun ProfileImportDialog(pending: PendingSshProfileImport, state: SshUiS }, confirm = { PrimaryButton(stringResource(R.string.ssh_import_confirm), small = true, - enabled = !state.profileImportBusy && (plan.newProfiles.isNotEmpty() || plan.updatedProfiles.isNotEmpty()), + enabled = !state.profileImportBusy && + (plan.newProfiles.isNotEmpty() || plan.updatedProfiles.isNotEmpty() || plan.snippetChanges.isNotEmpty()) && + (plan.updatedSnippets == 0 || snippetsAcknowledged), onClick = { onConfirm(if (plan.newProfiles.isEmpty()) null else keyRef) }, modifier = Modifier.testTag("ssh_import_confirm")) }, dismiss = { NeutralButton(stringResource(R.string.ssh_cancel_import), small = true, enabled = !state.profileImportBusy, onClick = onCancel) }, @@ -115,6 +147,7 @@ private fun ImportRow(entry: SshImportEntry, tone: Tone, keyRef: String?, state: Text(stringResource(authenticationResource(authentication)), Modifier.testTag("ssh_import_auth_${entry.incoming.alias}"), style = NetKitType.label, color = colors.muted) if (after.startupCommand.isNotEmpty()) StatusBanner(stringResource(R.string.ssh_import_startup_warning) + "\n" + after.startupCommand, StatusKind.WARNING) } else { + ImportChange(R.string.ssh_group, before.group.orEmpty(), after.group.orEmpty()) ImportChange(R.string.ssh_host, before.host, after.host) ImportChange(R.string.ssh_port, before.port.toString(), after.port.toString()) ImportChange(R.string.ssh_username, before.username, after.username) diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt index 4442ab4..e00acae 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt @@ -12,6 +12,8 @@ import android.os.PersistableBundle import android.text.Editable import android.text.TextWatcher import androidx.compose.ui.viewinterop.AndroidView +import androidx.core.content.edit +import androidx.core.net.toUri import androidx.activity.compose.BackHandler import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts @@ -39,14 +41,15 @@ import android.app.Activity import android.content.pm.ApplicationInfo import android.view.WindowManager import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.drawBehind -import androidx.compose.ui.geometry.Offset import androidx.compose.ui.draw.rotate import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalContext +import android.widget.Toast +import cz.netkit.app.nav.AppShortcuts +import cz.netkit.shared.nav.AppTarget import androidx.compose.ui.platform.testTag import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics @@ -54,6 +57,10 @@ import androidx.compose.ui.semantics.testTagsAsResourceId import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.SpanStyle +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontStyle +import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.KeyboardType @@ -69,12 +76,15 @@ import androidx.compose.ui.unit.em import androidx.compose.ui.unit.IntSize import com.jcraft.jsch.KeyPair import cz.netkit.app.R +import cz.netkit.shared.lan.ipv4Number import cz.netkit.app.BuildConfig import cz.netkit.app.ui.* import cz.netkit.app.ui.theme.DarkNetKitColors import cz.netkit.app.ui.theme.NetKitShape import cz.netkit.app.ui.theme.NetKitTheme import cz.netkit.app.ui.theme.NetKitType +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.compose.currentStateAsState import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.compose.ui.graphics.toArgb import kotlinx.serialization.json.Json @@ -84,18 +94,69 @@ import cz.netkit.shared.net.localTargetNeedsVpn import java.util.UUID /** The terminal is dark in both themes, so its chrome (pills, input strip) always uses the dark tokens. */ -private val TerminalChrome = DarkNetKitColors +internal val TerminalChrome = DarkNetKitColors + +private enum class KeyPage { USER_KEYS, HOST_KEYS } @Composable -fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHost: String? = null, onPrefillConsumed: () -> Unit = {}) { +fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHost: String? = null, onPrefillConsumed: () -> Unit = {}, + connectProfileId: String? = null, onConnectRequestConsumed: () -> Unit = {}, landscape: Boolean = false, + onTerminalVisible: (Boolean) -> Unit = {}) { + val context = LocalContext.current + var secureScreen by rememberSaveable { + mutableStateOf(context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE == 0) + } + DisposableEffect(context, secureScreen) { + val activity = context as? Activity + if (secureScreen) activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE) + else activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) + if (android.os.Build.VERSION.SDK_INT >= 33) activity?.setRecentsScreenshotEnabled(!secureScreen) + onDispose { + activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) + if (android.os.Build.VERSION.SDK_INT >= 33) activity?.setRecentsScreenshotEnabled(true) + } + } + // A device credential prompt can stop the activity. Keep navigation owned by its host + // so the successful callback can open the requested page after the content is re-created. + var keyPage by rememberSaveable { mutableStateOf(null) } + var forwardDetails by rememberSaveable { mutableStateOf(null) } + var destination by rememberSaveable { mutableStateOf(null) } + val export = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri -> + if (uri == null) viewModel.cancelExport() else destination = uri.toString() + } + SshLockHost(viewModel.access, modifier) { + LaunchedEffect(destination) { + destination?.let { value -> + destination = null + viewModel.export(value.toUri()) + } + } + SshContent(viewModel, modifier, prefillHost, onPrefillConsumed, connectProfileId, onConnectRequestConsumed, + landscape, onTerminalVisible, keyPage, { keyPage = it }, + forwardDetails, { forwardDetails = it }, secureScreen, { secureScreen = it }, + onExport = { export.launch("netkit-ssh-profiles.json") }) + } +} + +@Composable +private fun SshContent(viewModel: SshViewModel, modifier: Modifier, prefillHost: String?, onPrefillConsumed: () -> Unit, + connectProfileId: String?, onConnectRequestConsumed: () -> Unit, landscape: Boolean, + onTerminalVisible: (Boolean) -> Unit, keyPage: KeyPage?, showKeys: (KeyPage?) -> Unit, + forwardDetails: String?, showForwards: (String?) -> Unit, + secureScreen: Boolean, setSecureScreen: (Boolean) -> Unit, onExport: () -> Unit) { val state by viewModel.state.collectAsStateWithLifecycle() var editorJson by rememberSaveable { mutableStateOf(null) } val editor = remember(editorJson) { editorJson?.let { Json.decodeFromString(it) } } - var keys by rememberSaveable { mutableStateOf(false) } - var hostKeys by rememberSaveable { mutableStateOf(false) } + var snippets by rememberSaveable { mutableStateOf(false) } + var logWarning by remember { mutableStateOf(null) } + var logTarget by rememberSaveable { mutableStateOf(null) } var deleting by remember { mutableStateOf(null) } var connecting by remember { mutableStateOf(null) } var reconnecting by remember { mutableStateOf?>(null) } + var consoleEditor by remember { mutableStateOf(null) } + var consoleConnect by remember { mutableStateOf(null) } + var consoleReplacement by remember { mutableStateOf(null) } + var consoleDeleting by remember { mutableStateOf(null) } var closing by remember { mutableStateOf(null) } var closingAll by remember { mutableStateOf(false) } var recovering by remember { mutableStateOf(false) } @@ -103,41 +164,87 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos var actionsMenu by remember { mutableStateOf(false) } val context = LocalContext.current val colors = NetKitTheme.colors - var secureScreen by rememberSaveable { - mutableStateOf(context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE == 0) + val grant by viewModel.access.state.collectAsState() + var query by rememberSaveable { mutableStateOf("") } + val listPrefs = remember(context) { context.getSharedPreferences("ssh_list", Context.MODE_PRIVATE) } + var sort by remember { mutableStateOf(ProfileSort.entries.find { it.name == listPrefs.getString("sort", null) } ?: ProfileSort.MANUAL) } + val groups = remember(state.data, query, sort) { state.data.profileGroups(query, sort) } + val importProfiles = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> uri?.let(viewModel::previewProfileImport) } + // Session log destination: the user picks the file (SAF); nothing is written before that. + val logFile = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("text/plain")) { uri -> + val id = logTarget; logTarget = null + if (uri != null && id != null) viewModel.startLog(id, uri) } - DisposableEffect(context, secureScreen) { - val activity = context as? Activity - if (secureScreen) activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_SECURE) - else activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) - if (android.os.Build.VERSION.SDK_INT >= 33) activity?.setRecentsScreenshotEnabled(!secureScreen) - onDispose { - activity?.window?.clearFlags(WindowManager.LayoutParams.FLAG_SECURE) - if (android.os.Build.VERSION.SDK_INT >= 33) activity?.setRecentsScreenshotEnabled(true) + // Zadání 42: POST_NOTIFICATIONS is asked once, together with the first connection; the answer only + // decides whether the session service may run (denied = 5-minute background limit as before). + val notificationPermission = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { viewModel.notificationPermissionChanged() } + LaunchedEffect(state.sessions.isNotEmpty()) { + if (state.sessions.isNotEmpty() && viewModel.shouldAskNotifications()) { + viewModel.notificationsAsked() + try { notificationPermission.launch(android.Manifest.permission.POST_NOTIFICATIONS) } + catch (_: android.content.ActivityNotFoundException) { } + } + } + val sftpController by viewModel.sftp.collectAsStateWithLifecycle() + val serviceForeground by viewModel.serviceForeground.collectAsStateWithLifecycle() + val lifecycleState by LocalLifecycleOwner.current.lifecycle.currentStateAsState() + // Re-read on resume (the user may have changed notification settings) and when sessions change. + val notificationsOn = remember(lifecycleState, state.sessions.size, serviceForeground) { viewModel.notificationsAllowed() } + consoleEditor?.let { profile -> ConsoleForm(profile, state.busy, + save = { viewModel.saveConsole(it) { consoleEditor = null } }, close = { consoleEditor = null }) } + consoleConnect?.let { profile -> ConsoleConnect(profile, viewModel, consoleReplacement) { consoleConnect = null; consoleReplacement = null } } + consoleDeleting?.let { profile -> + ConfirmDialog(stringResource(R.string.ssh_delete_profile, profile.name), onCancel = { consoleDeleting = null }) { + viewModel.deleteConsole(profile.id); consoleDeleting = null } } - val export = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri -> if (uri == null) viewModel.cancelExport() else viewModel.export(uri) } - val importProfiles = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> uri?.let(viewModel::previewProfileImport) } val terminalStateHolder = rememberSaveableStateHolder() val profileFormStateHolder = rememberSaveableStateHolder() val active = state.sessions.find { it.id == state.selectedSession } - val inList = editor == null && !keys && !hostKeys + val sftpOpen = sftpController?.takeIf { active != null && it.sessionId == active.id } + val inList = editor == null && keyPage == null && !snippets + // The SFTP browser (42) replaces the terminal: then neither landscape compact mode (52) nor KeepScreenOn (46) applies. + val terminalVisible = active?.connected == true && inList && sftpOpen == null + DisposableEffect(terminalVisible) { + onTerminalVisible(terminalVisible) + onDispose { onTerminalVisible(false) } + } + val compact = landscape && terminalVisible + var controlsExpanded by rememberSaveable(active?.id) { mutableStateOf(false) } + val showControls = !compact || controlsExpanded // The import transaction must not race a profile/key edit or a connection confirmation. - val dialogOpen = editor != null || keys || hostKeys || connecting != null || reconnecting != null || state.keySelectionRequired != null || deleting != null + val dialogOpen = consoleEditor != null || consoleConnect != null || consoleDeleting != null || editor != null || keyPage != null || connecting != null || reconnecting != null || state.keySelectionRequired != null || deleting != null LaunchedEffect(dialogOpen) { viewModel.setProfileImportBlockedByDialog(dialogOpen) } // Device detail "Otevřít SSH": open the new-profile form with the host filled in, once. LaunchedEffect(prefillHost, state.loaded) { val host = prefillHost ?: return@LaunchedEffect if (!state.loaded) return@LaunchedEffect - if (editorJson == null) editorJson = Json.encodeToString(SshProfile(UUID.randomUUID().toString(), host, host, username = "")) + if (editorJson == null) { + val name = if (ipv4Number(host) != null) + context.getString(R.string.ssh_device_by_octet, host.substringAfterLast('.')) + else context.getString(R.string.wol_section_device) + editorJson = Json.encodeToString(SshProfile(UUID.randomUUID().toString(), name, host, username = "")) + } onPrefillConsumed() } + // Pinned shortcut (zadání 36 §2.1): show the usual connect confirmation; connecting needs a tap. + LaunchedEffect(connectProfileId, state.loaded, state.storeFailed) { + val id = connectProfileId ?: return@LaunchedEffect + if (!state.loaded && !state.storeFailed) return@LaunchedEffect + val profile = state.data.profiles.find { it.id == id } + if (profile != null && editorJson == null && connecting == null && reconnecting == null) connecting = profile + onConnectRequestConsumed() + } state.pendingProfileImport?.let { pending -> ProfileImportDialog(pending, state, onConfirm = viewModel::confirmProfileImport, onCancel = viewModel::cancelProfileImport) } - BackHandler(enabled = active != null && editor == null && !keys && !hostKeys) { closing = active?.id } - Column(modifier.imePadding().padding(Spacing.normal), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { - if (active == null && inList) ScreenHeader(stringResource(R.string.ssh_title), + BackHandler(enabled = active != null && sftpOpen == null && inList) { + if (showControls) closing = active?.id else controlsExpanded = true + } + // Zadání 46 §4: a connected terminal in the foreground keeps the display on. + KeepScreenOn(terminalVisible) + val directoryHeader: @Composable () -> Unit = { + ScreenHeader(stringResource(R.string.ssh_title), subtitle = if (state.loaded) sshSubtitle(state.data) else null) { PrimaryButton(stringResource(R.string.ssh_add), small = true, icon = NetKitIcons.Plus, enabled = state.loaded && !state.busy, onClick = { editorJson = Json.encodeToString(SshProfile(UUID.randomUUID().toString(), "", "", username = "")) }, @@ -147,12 +254,17 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos Icon(NetKitIcons.More, contentDescription = stringResource(R.string.ssh_more_actions), tint = colors.muted) } NetKitMenu(expanded = actionsMenu, onDismiss = { actionsMenu = false }) { + ConsoleKind.entries.forEach { kind -> + DropdownMenuItem(text = { MenuText(stringResource(R.string.console_add, consoleType(kind))) }, + enabled = state.loaded && !state.busy && !state.profileImportBusy, + onClick = { actionsMenu = false; consoleEditor = ConsoleProfile(UUID.randomUUID().toString(), "", kind) }) + } DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_host_keys)) }, enabled = state.loaded, leadingIcon = { Icon(NetKitIcons.Router, null, Modifier.size(20.dp)) }, - onClick = { actionsMenu = false; hostKeys = true }, modifier = Modifier.testTag("ssh_host_keys")) + onClick = { actionsMenu = false; viewModel.access.protect { showKeys(KeyPage.HOST_KEYS) } }, modifier = Modifier.testTag("ssh_host_keys")) DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_export)) }, enabled = state.loaded && !state.busy, leadingIcon = { Icon(NetKitIcons.Download, null, Modifier.size(20.dp)) }, - onClick = { actionsMenu = false; viewModel.prepareExport { export.launch("netkit-ssh-profiles.json") } }, modifier = Modifier.testTag("ssh_export")) + onClick = { actionsMenu = false; viewModel.prepareExport(onExport) }, modifier = Modifier.testTag("ssh_export")) DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_import_profiles)) }, enabled = state.loaded && !state.busy && !state.profileImportBusy, leadingIcon = { Icon(NetKitIcons.Download, null, Modifier.size(20.dp)) }, @@ -166,6 +278,10 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos } } } + } + Column(modifier.imePadding().padding(if (compact) Spacing.tiny else Spacing.normal), + verticalArrangement = Arrangement.spacedBy(if (compact) 0.dp else Spacing.small)) { + if (active == null && inList && !landscape) directoryHeader() if (state.busy) NetKitProgress() if (state.error) BannerWithAction(stringResource(sshFailureResource(state.failure)), StatusKind.ERROR, stringResource(R.string.ssh_ok), viewModel::clearError) @@ -184,14 +300,15 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos stringResource(R.string.ssh_ok), viewModel::cancelProfileImport) } when { - keys -> KeyManager(state, viewModel, onClose = { keys = false }) + keyPage == KeyPage.USER_KEYS -> KeyManager(state, viewModel, onClose = { showKeys(null) }) editor != null -> profileFormStateHolder.SaveableStateProvider(editor.id) { ProfileForm(editor, state, viewModel, onClose = { editorJson = null; profileFormStateHolder.removeState(editor.id) }, - onCreateKey = { keys = true }) + onCreateKey = { viewModel.access.protect { showKeys(KeyPage.USER_KEYS) } }) } - hostKeys -> HostKeys(state, viewModel, onClose = { hostKeys = false }) + keyPage == KeyPage.HOST_KEYS -> HostKeys(state, viewModel, onClose = { showKeys(null) }) + snippets -> SnippetManager(state, viewModel, onClose = { snippets = false }) else -> { - if (state.sessions.isNotEmpty()) Row(verticalAlignment = Alignment.CenterVertically) { + if (showControls && state.sessions.isNotEmpty()) Row(verticalAlignment = Alignment.CenterVertically) { Row(Modifier.weight(1f).horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalAlignment = Alignment.CenterVertically) { SessionTab(stringResource(R.string.ssh_profiles), selected = active == null, tone = null) { viewModel.selectSession(null) } @@ -205,20 +322,44 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos } NetKitMenu(expanded = sessionMenu, onDismiss = { sessionMenu = false }) { DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_secure_screen)) }, - onClick = { secureScreen = !secureScreen; sessionMenu = false }, + onClick = { setSecureScreen(!secureScreen); sessionMenu = false }, trailingIcon = { Switch(checked = secureScreen, onCheckedChange = null, colors = netKitSwitchColors()) }, modifier = Modifier.testTag("ssh_secure_screen")) + if (active.logging) DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_log_stop)) }, + onClick = { sessionMenu = false; viewModel.stopLog(active.id) }, modifier = Modifier.testTag("ssh_log_stop")) + else if (active.consoleKind != ConsoleKind.TELNET) DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_log_start)) }, enabled = !active.ended, + onClick = { sessionMenu = false; logWarning = active.id }, modifier = Modifier.testTag("ssh_log_start")) + // SFTP only on an SSH session (zadání 44: not for Telnet or the USB serial console). + if (active.consoleKind == null) DropdownMenuItem(text = { MenuText(stringResource(R.string.sftp_open)) }, enabled = active.connected && !active.ended, + leadingIcon = { Icon(NetKitIcons.Folder, null, Modifier.size(20.dp)) }, + onClick = { sessionMenu = false; viewModel.openSftp(active.id) }, modifier = Modifier.testTag("ssh_sftp_open")) DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_close_all)) }, onClick = { closingAll = true; sessionMenu = false }) } } } if (active != null) { - SessionStatusRow(active, onReconnect = { viewModel.reconnectProfile(active.id)?.let { reconnecting = active.id to it } }, + if (showControls) SessionStatusRow(active, onReconnect = { + if (active.consoleKind == null) viewModel.reconnectProfile(active.id)?.let { reconnecting = active.id to it } + else state.data.consoles.find { it.id == active.profileId }?.let { consoleReplacement = active.id; consoleConnect = it } + }, canReconnect = active.consoleKind == null || state.data.consoles.any { it.id == active.profileId }, onClose = { closing = active.id }) active.failure?.let { StatusBanner(stringResource(sshFailureResource(it)), StatusKind.ERROR) } - terminalStateHolder.SaveableStateProvider(active.id) { Terminal(active, viewModel, Modifier.weight(1f)) } + if (active.consoleKind != null && active.failed) StatusBanner(stringResource( + if (active.consoleKind == ConsoleKind.SERIAL) R.string.console_usb_error else R.string.ssh_error_connection), StatusKind.ERROR) + // While typing the terminal needs the height; the hint returns when the keyboard closes. + if (showControls && !active.ended && !notificationsOn && !WindowInsets.isImeVisible) BackgroundLimitBanner() + if (sftpOpen != null) SftpBrowser(sftpOpen, onTransfer = { action -> viewModel.access.protect(action = action) }, onClose = viewModel::closeSftp, modifier = Modifier.weight(1f)) + else { + SessionLogStatus(active, viewModel) + if (showControls) SessionForwards(active, viewModel.access, forwardDetails == active.id) { showForwards(if (it) active.id else null) } + terminalStateHolder.SaveableStateProvider(active.id) { + Terminal(active, viewModel, if (active.consoleKind == null) state.data.snippetsFor(active.profileId) else emptyList(), Modifier.weight(1f), + compact, showControls, onToggleControls = { controlsExpanded = !controlsExpanded }) + } + } } else { LazyColumn(verticalArrangement = Arrangement.spacedBy(Spacing.normal)) { + if (landscape) item("directory_header") { directoryHeader() } if (state.storeFailed) item { Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { StatusBanner(stringResource(R.string.ssh_storage_failed), StatusKind.ERROR) @@ -232,28 +373,51 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos if (!state.loaded && !state.storeFailed) item { Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { CircularProgressIndicator(color = colors.accent) } } - if (state.loaded && state.data.profiles.isEmpty()) item { Panel { EmptyState(stringResource(R.string.ssh_empty), NetKitIcons.Terminal) } } - if (state.data.profiles.isNotEmpty()) item(key = "profiles") { - SectionCard(title = stringResource(R.string.ssh_profiles)) { - Column { - val canConnect = !state.busy && state.sessions.count { !it.ended } < 4 - val profiles = state.data.profiles - profiles.forEachIndexed { index, profile -> - key(profile.id) { - ProfileRow(profile, - live = state.sessions.any { it.connected && !it.ended && viewModel.reconnectProfile(it.id)?.id == profile.id }, - canConnect = canConnect, busy = state.busy || state.profileImportBusy || state.pendingProfileImport != null, first = index == 0, last = index == profiles.lastIndex, - onConnect = { connecting = profile }, - onEdit = { editorJson = Json.encodeToString(profile) }, - onDelete = { deleting = profile }, onMove = { viewModel.moveProfile(profile.id, it) }) - } + if (state.loaded && state.data.profiles.isEmpty() && state.data.consoles.isEmpty()) item { Panel { EmptyState(stringResource(R.string.ssh_empty), NetKitIcons.Terminal) } } + if (state.data.profiles.isNotEmpty() || state.data.consoles.isNotEmpty()) item(key = "filter") { + DirectoryFilter(query, { query = it }, sort) { + sort = it + listPrefs.edit { putString("sort", it.name) } + } + if (groups.isEmpty()) Hint(stringResource(R.string.ssh_no_matches)) + } + groups.forEach { (group, rows) -> + item(key = "group:${group.orEmpty()}") { + Text(group ?: stringResource(R.string.ssh_ungrouped), style = NetKitType.panelTitle) + } + items(rows.size, key = { rows[it].listKey }) { index -> + val profile = rows[index] + val editable = !state.busy && !state.profileImportBusy && state.pendingProfileImport == null + val canConnect = editable && state.sessions.count { !it.ended } < 4 + val first = sort != ProfileSort.MANUAL || index == 0 + val last = sort != ProfileSort.MANUAL || index == rows.lastIndex + fun move(delta: Int) { + rows.getOrNull(index + delta)?.let { viewModel.swapProfileRows(profile.listKey, it.listKey) } + } + Panel { + when (profile) { + is ConsoleProfile -> ProfileRow(profile, + live = state.sessions.any { it.connected && !it.ended && it.consoleKind == profile.kind && it.profileId == profile.id }, + canConnect = canConnect, busy = !editable, first = first, last = last, + onConnect = { consoleConnect = profile }, onEdit = { consoleEditor = profile }, + onDelete = { consoleDeleting = profile }, onMove = ::move) + is SshProfile -> ProfileRow(profile, + live = state.sessions.any { it.connected && !it.ended && viewModel.reconnectProfile(it.id)?.id == profile.id }, + canConnect = canConnect, busy = !editable, first = first, last = last, + onConnect = { connecting = profile }, onEdit = { editorJson = Json.encodeToString(profile) }, + onDelete = { deleting = profile }, onMove = ::move, + onPin = if (AppShortcuts.canPin(context, cz.netkit.shared.nav.AppRecordKind.SSH_PROFILE, profile.id)) ({ + if (!AppShortcuts.requestPin(context, AppTarget.SshProfile(profile.id), profile.name)) + Toast.makeText(context, R.string.shortcut_pin_failed, Toast.LENGTH_SHORT).show() + }) else null) } } } } + if (state.loaded) item(key = "snippets") { SnippetCard(state, onOpen = { snippets = true }) } if (state.loaded) item(key = "keys") { // The whole card is the tap target; ListRow only lays out icon, texts and chevron. - Panel(Modifier.testTag("ssh_keys"), padding = 0.dp, onClick = { keys = true }) { + Panel(Modifier.testTag("ssh_keys"), padding = 0.dp, onClick = { viewModel.access.protect { showKeys(KeyPage.USER_KEYS) } }) { ListRow(stringResource(R.string.ssh_keys), keyCardSubtitle(state.data.keys), NetKitIcons.Key, modifier = Modifier.padding(horizontal = Spacing.normal, vertical = Spacing.tiny)) { Icon(NetKitIcons.ChevronRight, null, Modifier.size(18.dp), tint = colors.dim) @@ -263,12 +427,13 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos item(key = "privacy") { Panel(padding = Spacing.small) { Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(NetKitShape.nested).testTag("ssh_secure_screen") - .toggleable(secureScreen, role = Role.Switch, onValueChange = { secureScreen = it }) + .toggleable(secureScreen, role = Role.Switch, onValueChange = setSecureScreen) .padding(horizontal = Spacing.small), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { Text(stringResource(R.string.ssh_secure_screen), Modifier.weight(1f), style = NetKitType.body, color = colors.text) Switch(checked = secureScreen, onCheckedChange = null, colors = netKitSwitchColors()) } + SshLockSettings(viewModel.access, grant) if (state.sessions.isNotEmpty()) TextButton(onClick = { closingAll = true }, shape = NetKitShape.buttonSmall, colors = ButtonDefaults.textButtonColors(contentColor = colors.err)) { Text(stringResource(R.string.ssh_close_all), style = NetKitType.body.copy(fontWeight = FontWeight.Bold)) @@ -300,7 +465,28 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos if (closingAll) ConfirmDialog(stringResource(R.string.ssh_close_all_confirm), onCancel = { closingAll = false }) { viewModel.closeAllSessions(); closingAll = false } - deleting?.let { profile -> ConfirmDialog(stringResource(R.string.ssh_delete_profile, profile.name), onCancel = { deleting = null }) { viewModel.deleteProfile(profile.id); deleting = null } } + deleting?.let { profile -> + val dependents = state.data.profiles.filter { it.jumpProfileId == profile.id }.joinToString(", ") { it.name } + ConfirmDialog(stringResource(R.string.ssh_delete_profile, profile.name), onCancel = { deleting = null }, + warning = dependents.takeIf { it.isNotEmpty() }?.let { stringResource(R.string.ssh_delete_profile_jump_warning, it) }) { + viewModel.deleteProfile(profile.id); deleting = null + } + } + logWarning?.let { sessionId -> + NetKitAlert(onDismiss = { logWarning = null }, title = stringResource(R.string.ssh_log_title), + text = { Box(Modifier.testTag("ssh_log_warning")) { StatusBanner(stringResource(R.string.ssh_log_warning), StatusKind.WARNING) } }, + confirm = { PrimaryButton(stringResource(R.string.ssh_log_choose), small = true, modifier = Modifier.testTag("ssh_log_confirm"), onClick = { + logWarning = null; logTarget = sessionId + val name = state.sessions.find { it.id == sessionId }?.name.orEmpty().filter { it.isLetterOrDigit() || it in "-_." }.take(40) + val stamp = java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss")) + try { logFile.launch("netkit-ssh-${name.ifEmpty { "session" }}-$stamp.txt") } + catch (_: android.content.ActivityNotFoundException) { + logTarget = null + android.widget.Toast.makeText(context, R.string.ssh_share_unavailable, android.widget.Toast.LENGTH_LONG).show() + } + }) }, + dismiss = { NeutralButton(stringResource(R.string.ssh_cancel), small = true, onClick = { logWarning = null }) }) + } closing?.let { id -> ConfirmDialog(stringResource(R.string.ssh_close_confirm), onCancel = { closing = null }) { viewModel.closeSession(id); closing = null } } // Only a hint: a VPN outside the Android API (split tunnel) may still reach the address, so connecting stays allowed. @Composable fun localWarning(profile: SshProfile): String? = @@ -318,7 +504,7 @@ fun SshScreen(viewModel: SshViewModel, modifier: Modifier = Modifier, prefillHos /** "3 profily · klíč Ed25519 v Keystore": profile count and what the phone holds for key login. */ @Composable private fun sshSubtitle(data: SshData): String { - val profiles = pluralStringResource(R.plurals.ssh_subtitle_profiles, data.profiles.size, data.profiles.size) + val profiles = pluralStringResource(R.plurals.ssh_subtitle_profiles, data.profiles.size + data.consoles.size, data.profiles.size + data.consoles.size) val keys = when (data.keys.size) { 0 -> stringResource(R.string.ssh_subtitle_no_key) 1 -> stringResource(R.string.ssh_subtitle_key, keyAlgorithm(data.keys.single().publicKey)) @@ -344,8 +530,25 @@ private fun keyCardSubtitle(keys: List): String = * Session state (dot + text) with reconnect/close on the right. A flow row: at 360 dp and large * font the buttons drop under the state instead of squeezing the text into a narrow column. */ +/** Notifications off: the session keeps the 5-minute background limit; one tap to the app's notification settings. */ @Composable -private fun SessionStatusRow(session: SshSessionState, onReconnect: () -> Unit, onClose: () -> Unit) { +private fun BackgroundLimitBanner() { + val context = LocalContext.current + // One compact line: the terminal or SFTP list below must keep its height. + Row(Modifier.fillMaxWidth().testTag("ssh_background_limited"), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(stringResource(R.string.ssh_background_limited), Modifier.weight(1f), style = NetKitType.label, + color = NetKitTheme.colors.muted) + TextButton(onClick = { + val intent = android.content.Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS) + .putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, context.packageName) + try { context.startActivity(intent) } catch (_: android.content.ActivityNotFoundException) { } + }) { Text(stringResource(R.string.ssh_background_enable), style = NetKitType.label) } + } +} + +@Composable +private fun SessionStatusRow(session: SshSessionState, onReconnect: () -> Unit, canReconnect: Boolean, onClose: () -> Unit) { val colors = NetKitTheme.colors FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalArrangement = Arrangement.spacedBy(Spacing.small), itemVerticalAlignment = Alignment.CenterVertically) { @@ -361,14 +564,14 @@ private fun SessionStatusRow(session: SshSessionState, onReconnect: () -> Unit, }), Modifier.testTag("ssh_status"), style = NetKitType.body.copy(fontWeight = FontWeight.SemiBold), color = colors.text) } Row(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalAlignment = Alignment.CenterVertically) { - if (session.ended || session.networkLost) TonalButton(stringResource(R.string.ssh_reconnect), onClick = onReconnect, small = true) + if (canReconnect && (session.ended || session.networkLost)) TonalButton(stringResource(R.string.ssh_reconnect), onClick = onReconnect, small = true) NeutralButton(stringResource(R.string.ssh_close), onClick = onClose, small = true, modifier = Modifier.testTag("ssh_close")) } } } /** State dot of a session: live OK, lost network WARN, ended or failed ERR, handshake in progress INFO. */ -private fun sessionTone(session: SshSessionState): Tone = when { +internal fun sessionTone(session: SshSessionState): Tone = when { session.networkLost && !session.ended -> Tone.WARN session.failed || session.ended -> Tone.ERR session.connected -> Tone.OK @@ -432,13 +635,13 @@ internal fun netKitFieldColors() = NetKitTheme.colors.let { colors -> focusedBorderColor = colors.accent, unfocusedBorderColor = colors.border, disabledBorderColor = colors.divider, errorBorderColor = colors.err, focusedLabelColor = colors.accent, unfocusedLabelColor = colors.muted, disabledLabelColor = colors.dim, errorLabelColor = colors.err, focusedSupportingTextColor = colors.muted, unfocusedSupportingTextColor = colors.muted, errorSupportingTextColor = colors.err, - focusedPlaceholderColor = colors.dim, unfocusedPlaceholderColor = colors.dim, + focusedPlaceholderColor = colors.muted, unfocusedPlaceholderColor = colors.muted, ) } /** Field text: body 15 for words, mono 0.92× for hosts, ports and commands. */ -private val FieldText = NetKitType.body.copy(fontSize = 15.sp, lineHeight = 22.sp) -private val FieldMono = NetKitType.addressFor(FieldText) +internal val FieldText = NetKitType.body.copy(fontSize = 15.sp, lineHeight = 22.sp) +internal val FieldMono = NetKitType.addressFor(FieldText) /** Selectable radio row (48 dp, radius 12) used by forms and the import dialog. */ @Composable @@ -452,7 +655,7 @@ internal fun ChoiceRow(selected: Boolean, label: String, onClick: () -> Unit, mo } @Composable -private fun CheckRow(checked: Boolean, label: String, onChange: (Boolean) -> Unit) { +internal fun CheckRow(checked: Boolean, label: String, onChange: (Boolean) -> Unit) { Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(NetKitShape.nested) .toggleable(checked, role = Role.Checkbox, onValueChange = onChange).padding(horizontal = Spacing.tiny), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { @@ -502,10 +705,29 @@ private fun profileMonogram(name: String): String { return letters.joinToString("").uppercase().ifEmpty { "?" } } -/** `user@host` with ` :port` only when it is not 22; IPv6 literals get brackets so the port stays unambiguous. */ -private fun profileAddress(profile: SshProfile): String { - val host = if (profile.host.contains(':')) "[${profile.host}]" else profile.host - return "${profile.username}@$host" + if (profile.port != 22) " :${profile.port}" else "" +internal fun hostPort(host: String, port: Int): String = + if (':' in host) "[$host]:$port" else "$host:$port" + +@Composable +private fun DirectoryFilter(query: String, onQuery: (String) -> Unit, sort: ProfileSort, onSort: (ProfileSort) -> Unit) { + var menu by remember { mutableStateOf(false) } + fun label(value: ProfileSort) = when (value) { + ProfileSort.MANUAL -> R.string.ssh_sort_manual + ProfileSort.ALPHABETICAL -> R.string.ssh_sort_alpha + ProfileSort.RECENT -> R.string.ssh_sort_recent + } + Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + OutlinedTextField(query, onQuery, label = { Text(stringResource(R.string.ssh_search)) }, + singleLine = true, colors = netKitFieldColors(), modifier = Modifier.fillMaxWidth().testTag("ssh_search")) + Box { + NeutralButton(stringResource(label(sort)), onClick = { menu = true }, modifier = Modifier.testTag("ssh_sort"), small = true) + NetKitMenu(expanded = menu, onDismiss = { menu = false }) { + ProfileSort.entries.forEach { option -> + DropdownMenuItem(text = { Text(stringResource(label(option))) }, onClick = { menu = false; onSort(option) }) + } + } + } + } } /** @@ -513,50 +735,78 @@ private fun profileAddress(profile: SshProfile): String { * Connect retains its stable test tag. */ @Composable -internal fun ProfileRow(profile: SshProfile, live: Boolean, canConnect: Boolean, busy: Boolean, first: Boolean, last: Boolean, - onConnect: () -> Unit, onEdit: () -> Unit, onDelete: () -> Unit, onMove: (Int) -> Unit) { +private fun ProfileMoveButtons(name: String, id: String, up: Boolean, down: Boolean, onMove: (Int) -> Unit) { val colors = NetKitTheme.colors - val divider = colors.divider - Column(Modifier.fillMaxWidth() - .then(if (first) Modifier else Modifier.drawBehind { drawLine(divider, Offset(0f, 0f), Offset(size.width, 0f), 1.dp.toPx()) }) - .padding(top = if (first) 0.dp else Spacing.medium, bottom = if (last) 0.dp else Spacing.medium)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { - Box(Modifier.size(44.dp).clip(NetKitShape.nested).background(colors.surface2), contentAlignment = Alignment.Center) { - Text(profileMonogram(profile.name), style = NetKitType.panelTitle.copy(fontWeight = FontWeight.ExtraBold, letterSpacing = (-0.02).em), - color = colors.accent, maxLines = 1, softWrap = false) - } - Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Text(profile.name, style = NetKitType.panelTitle, color = colors.text, maxLines = 2, overflow = TextOverflow.Ellipsis) - Text(profileAddress(profile), style = NetKitType.addressFor(NetKitType.label), color = colors.muted) - if (live) Tag(stringResource(R.string.ssh_chip_live), Tone.OK, dot = true) + IconButton(onClick = { onMove(-1) }, enabled = up, modifier = Modifier.testTag("ssh_up_$id")) { + Icon(NetKitIcons.ChevronRight, stringResource(R.string.ssh_move_up, name), Modifier.size(20.dp).rotate(-90f), + tint = if (up) colors.muted else colors.dim) + } + IconButton(onClick = { onMove(1) }, enabled = down, modifier = Modifier.testTag("ssh_down_$id")) { + Icon(NetKitIcons.ChevronRight, stringResource(R.string.ssh_move_down, name), Modifier.size(20.dp).rotate(90f), + tint = if (down) colors.muted else colors.dim) + } +} + +@Composable +internal fun ProfileRow(profile: TerminalProfile, live: Boolean, canConnect: Boolean, busy: Boolean, first: Boolean, last: Boolean, + onConnect: () -> Unit, onEdit: () -> Unit, onDelete: () -> Unit, onMove: (Int) -> Unit, onPin: (() -> Unit)? = null) { + val colors = NetKitTheme.colors + val rowId = if (profile is ConsoleProfile) profile.listKey else profile.id + val address = when (profile) { + is SshProfile -> "${profile.username}@${hostPort(profile.host, profile.port)}" + is ConsoleProfile -> when (profile.kind) { + ConsoleKind.TELNET -> stringResource(R.string.console_profile_telnet, hostPort(profile.host, profile.port)) + ConsoleKind.SERIAL -> stringResource(R.string.console_profile_serial, profile.serial.baud) + } + } + Column(Modifier.fillMaxWidth()) { + FlowRow(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, + itemVerticalAlignment = Alignment.CenterVertically) { + Row(Modifier.padding(end = Spacing.small), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { + Box(Modifier.size(44.dp).clip(NetKitShape.nested).background(colors.surface2), contentAlignment = Alignment.Center) { + if (profile is ConsoleProfile) { + Icon(if (profile.kind == ConsoleKind.SERIAL) NetKitIcons.Link else NetKitIcons.Terminal, + null, Modifier.size(24.dp), tint = colors.accent) + } else Text(profileMonogram(profile.name), style = NetKitType.panelTitle.copy(fontWeight = FontWeight.ExtraBold, letterSpacing = (-0.02).em), + color = colors.accent, maxLines = 1, softWrap = false) + } + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(profile.name, style = NetKitType.panelTitle, color = colors.text, maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(address, style = NetKitType.addressFor(NetKitType.label), color = colors.muted) + if (live) Tag(stringResource(R.string.ssh_chip_live), Tone.OK, dot = true) + } } TonalButton(stringResource(R.string.ssh_connect), onClick = onConnect, enabled = canConnect, small = true, - modifier = Modifier.testTag("ssh_connect_${profile.id}")) + modifier = Modifier.testTag("ssh_connect_$rowId")) } HorizontalDivider(Modifier.padding(top = Spacing.small), thickness = 1.dp, color = colors.divider) val editLabel = stringResource(R.string.ssh_edit_profile, profile.name) val deleteLabel = stringResource(R.string.ssh_delete_profile_action, profile.name) Row(verticalAlignment = Alignment.CenterVertically) { TextButton(onClick = onEdit, enabled = !busy, shape = NetKitShape.buttonSmall, - modifier = Modifier.testTag("ssh_edit_${profile.id}").semantics { contentDescription = editLabel }) { Text(stringResource(R.string.ssh_edit)) } + modifier = Modifier.testTag("ssh_edit_$rowId").semantics { contentDescription = editLabel }) { Text(stringResource(R.string.ssh_edit)) } TextButton(onClick = onDelete, enabled = !busy, shape = NetKitShape.buttonSmall, colors = ButtonDefaults.textButtonColors(contentColor = colors.err), - modifier = Modifier.testTag("ssh_delete_${profile.id}").semantics { contentDescription = deleteLabel }) { Text(stringResource(R.string.ssh_delete)) } + modifier = Modifier.testTag("ssh_delete_$rowId").semantics { contentDescription = deleteLabel }) { Text(stringResource(R.string.ssh_delete)) } Spacer(Modifier.weight(1f)) - IconButton(onClick = { onMove(-1) }, enabled = !busy && !first, modifier = Modifier.testTag("ssh_up_${profile.id}")) { - Icon(NetKitIcons.ChevronRight, stringResource(R.string.ssh_move_up, profile.name), Modifier.size(20.dp).rotate(-90f), - tint = if (!busy && !first) colors.muted else colors.dim) - } - IconButton(onClick = { onMove(1) }, enabled = !busy && !last, modifier = Modifier.testTag("ssh_down_${profile.id}")) { - Icon(NetKitIcons.ChevronRight, stringResource(R.string.ssh_move_down, profile.name), Modifier.size(20.dp).rotate(90f), - tint = if (!busy && !last) colors.muted else colors.dim) + ProfileMoveButtons(profile.name, rowId, !busy && !first, !busy && !last, onMove) + // Pinned shortcut (zadání 36 §2.3): opens the connect confirmation, never connects by itself. + if (onPin != null) Box { + var menu by remember { mutableStateOf(false) } + IconButton(onClick = { menu = true }, modifier = Modifier.testTag("ssh_more_$rowId")) { + Icon(NetKitIcons.More, stringResource(R.string.shortcut_more_actions, profile.name), tint = colors.muted) + } + NetKitMenu(expanded = menu, onDismiss = { menu = false }) { + DropdownMenuItem(text = { MenuText(stringResource(R.string.shortcut_pin)) }, onClick = { menu = false; onPin() }, + modifier = Modifier.testTag("ssh_pin_$rowId")) + } } } } } @Composable -private fun ConfirmDialog(message: String, onCancel: () -> Unit, warning: String? = null, onConfirm: () -> Unit) { +internal fun ConfirmDialog(message: String, onCancel: () -> Unit, warning: String? = null, onConfirm: () -> Unit) { NetKitAlert(onDismiss = onCancel, text = { Column(verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { if (warning != null) Box(Modifier.testTag("ssh_local_warning")) { StatusBanner(warning, StatusKind.WARNING) } @@ -569,7 +819,7 @@ private fun ConfirmDialog(message: String, onCancel: () -> Unit, warning: String /** Back (ChevronLeft on a 40 dp `surface2` tile) + title, for the profile form, keys and trusted servers. */ @Composable -private fun SubscreenHeader(title: String, onBack: () -> Unit, enabled: Boolean = true) { +internal fun SubscreenHeader(title: String, onBack: () -> Unit, enabled: Boolean = true) { val colors = NetKitTheme.colors val back = stringResource(R.string.ssh_back) Row(Modifier.fillMaxWidth().heightIn(min = 52.dp), verticalAlignment = Alignment.CenterVertically, @@ -584,25 +834,49 @@ private fun SubscreenHeader(title: String, onBack: () -> Unit, enabled: Boolean } @Composable -private fun Hint(text: String) { +internal fun Hint(text: String) { Text(text, style = NetKitType.label, color = NetKitTheme.colors.muted) } +// Compare the values the form can save, including profiles imported with settings hidden by the current mode. +private fun SshProfile.editorValues() = copy( + group = group?.trim()?.ifEmpty { null }, host = host.trim(), username = username.trim(), + keyRef = keyRef.takeIf { authentication == SshAuthentication.KEY }, + dynamicForwardNoAuth = dynamicForwardPort != null && dynamicForwardNoAuth, +) + +internal fun profileHasEdits(original: SshProfile, draft: SshProfile, passwordEntered: Boolean, savePassword: Boolean): Boolean = + draft.editorValues() != original.editorValues() || passwordEntered || savePassword != (original.secretRef != null) + @Composable private fun ProfileForm(original: SshProfile, state: SshUiState, viewModel: SshViewModel, onClose: () -> Unit, onCreateKey: () -> Unit) { var name by rememberSaveable(original.id) { mutableStateOf(original.name) }; var host by rememberSaveable(original.id) { mutableStateOf(original.host) } + var group by rememberSaveable(original.id) { mutableStateOf(original.group.orEmpty()) } var port by rememberSaveable(original.id) { mutableStateOf(original.port.toString()) }; var user by rememberSaveable(original.id) { mutableStateOf(original.username) } var auth by rememberSaveable(original.id) { mutableStateOf(original.authentication) }; var keyRef by rememberSaveable(original.id) { mutableStateOf(original.keyRef) } var command by rememberSaveable(original.id) { mutableStateOf(original.startupCommand) }; var keepalive by rememberSaveable(original.id) { mutableStateOf(original.keepaliveSeconds.toString()) } // Deliberately not rememberSaveable: credentials must never reach savedInstanceState. var password by remember { mutableStateOf("") }; var savePassword by rememberSaveable { mutableStateOf(original.secretRef != null) } var discard by remember { mutableStateOf(false) } - val draft = original.copy(name = name, host = host.trim(), port = port.toIntOrNull() ?: 0, username = user.trim(), authentication = auth, keyRef = if (auth == SshAuthentication.KEY) keyRef else null, startupCommand = command, keepaliveSeconds = keepalive.toIntOrNull() ?: -1) - BackHandler { discard = true } + val routing = rememberProfileRouting(original) + // Reads the field states when called: a back press right after an edit (before recomposition) + // must still see the edit, so the dirty check does not use the draft captured by the last composition. + fun currentDraft() = routing.apply(original.copy( + name = name, group = group, host = host, port = port.toIntOrNull() ?: 0, username = user, + authentication = auth, keyRef = keyRef, startupCommand = command, keepaliveSeconds = keepalive.toIntOrNull() ?: -1, + )).editorValues() + val draft = currentDraft() + val chainValid = resolveSshJumpChain(state.data.profiles, draft) is SshJumpResolution.Chain + val close = { + if (routing.hasPendingForward || profileHasEdits(original, currentDraft(), password.isNotEmpty(), savePassword)) discard = true + else onClose() + } + BackHandler { if (!state.busy) close() } Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { - SubscreenHeader(stringResource(R.string.ssh_profile), onBack = { discard = true }, enabled = !state.busy) + SubscreenHeader(stringResource(R.string.ssh_profile), onBack = close, enabled = !state.busy) SshField(name, { name = it.take(100) }, R.string.ssh_name) - SshField(host, { host = it.take(253) }, R.string.ssh_host, mono = true) + SshField(group, { group = it.take(60) }, R.string.ssh_group) + SshField(host, { host = it.take(253) }, R.string.ssh_host, mono = true, hint = R.string.ssh_host_hint) SshField(port, { port = it.take(5) }, R.string.ssh_port, number = true, mono = true) SshField(user, { user = it.take(128) }, R.string.ssh_username) Column { @@ -631,19 +905,21 @@ private fun ProfileForm(original: SshProfile, state: SshUiState, viewModel: SshV } SshField(command, { command = it.take(4096) }, R.string.ssh_startup_command, mono = true) SshField(keepalive, { keepalive = it.take(3) }, R.string.ssh_keepalive, number = true) + ProfileRoutingFields(draft, state.data, routing) Hint(stringResource(R.string.ssh_profile_validation)) FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { - PrimaryButton(stringResource(R.string.ssh_save), modifier = Modifier.testTag("ssh_profile_save"), enabled = draft.valid() && !state.busy && (auth != SshAuthentication.KEY || state.data.keys.any { it.id == keyRef }), + PrimaryButton(stringResource(R.string.ssh_save), modifier = Modifier.testTag("ssh_profile_save"), enabled = draft.valid() && chainValid && !state.busy && (auth != SshAuthentication.KEY || state.data.keys.any { it.id == keyRef }), onClick = { viewModel.saveProfile(draft, password, savePassword) { password = ""; onClose() } }) - NeutralButton(stringResource(R.string.ssh_back), enabled = !state.busy, onClick = { discard = true }) + NeutralButton(stringResource(R.string.ssh_back), enabled = !state.busy, onClick = close) } } if (discard) ConfirmDialog(stringResource(R.string.ssh_discard), onCancel = { discard = false }) { password = ""; onClose() } } @Composable -private fun SshField(value: String, change: (String) -> Unit, label: Int, number: Boolean = false, mono: Boolean = false) { +internal fun SshField(value: String, change: (String) -> Unit, label: Int, number: Boolean = false, mono: Boolean = false, hint: Int? = null) { OutlinedTextField(value, change, label = { Text(stringResource(label)) }, singleLine = true, + supportingText = hint?.let { { Text(stringResource(it)) } }, textStyle = if (mono) FieldMono else FieldText, shape = NetKitShape.nested, colors = netKitFieldColors(), keyboardOptions = KeyboardOptions(keyboardType = if (number) KeyboardType.Number else KeyboardType.Text), modifier = Modifier.fillMaxWidth()) } @@ -689,9 +965,9 @@ private fun KeyManager(state: SshUiState, viewModel: SshViewModel, onClose: () - Text(key.name, style = NetKitType.panelTitle, color = colors.text) SelectionContainer { Text(key.publicKey, style = NetKitType.addressFor(NetKitType.label), color = colors.muted) } FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { - TonalButton(stringResource(R.string.ssh_copy_public), small = true, onClick = { copyText(context, key.publicKey) }) + TonalButton(stringResource(R.string.ssh_copy_public), small = true, onClick = { viewModel.access.protect { copyText(context, key.publicKey) } }) // Public half only: the PC script `install-pubkey` distributes it to the aliases. - NeutralButton(stringResource(R.string.ssh_share_public), small = true, onClick = { sharePublicKey(context, key.name, key.publicKey) }) + NeutralButton(stringResource(R.string.ssh_share_public), small = true, onClick = { viewModel.access.protect { sharePublicKey(context, key.name, key.publicKey) } }) DangerTextButton(stringResource(R.string.ssh_delete), enabled = !state.busy && state.data.profiles.none { it.keyRef == key.id }) { deleting = key } } } } @@ -702,7 +978,7 @@ private fun KeyManager(state: SshUiState, viewModel: SshViewModel, onClose: () - /** Destructive action without a filled container: `err` text, small-button radius. */ @Composable -private fun DangerTextButton(text: String, enabled: Boolean = true, onClick: () -> Unit) { +internal fun DangerTextButton(text: String, enabled: Boolean = true, onClick: () -> Unit) { TextButton(onClick = onClick, enabled = enabled, shape = NetKitShape.buttonSmall, modifier = Modifier.heightIn(min = 36.dp), colors = ButtonDefaults.textButtonColors(contentColor = NetKitTheme.colors.err, disabledContentColor = NetKitTheme.colors.dim)) { Text(text, style = NetKitType.body.copy(fontWeight = FontWeight.Bold)) @@ -721,7 +997,7 @@ private fun sharePublicKey(context: Context, name: String, publicKey: String) { } } -private fun copyText(context: Context, text: String, sensitive: Boolean = false) { +internal fun copyText(context: Context, text: String, sensitive: Boolean = false) { // Clipboard is Binder IPC. A full scrollback can exceed its shared transaction buffer. if (text.length > 65_536) { android.widget.Toast.makeText(context, R.string.ssh_clipboard_too_large, android.widget.Toast.LENGTH_LONG).show() @@ -795,7 +1071,7 @@ private fun AuthenticationDialog(challenge: AuthChallenge, viewModel: SshViewMod NetKitAlert(onDismiss = { viewModel.answerAuthentication(challenge.requestId, null) }, title = stringResource(R.string.ssh_authenticate), text = { Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { Text(stringResource(R.string.ssh_auth_identity, challenge.trustedIdentity), style = NetKitType.addressFor(NetKitType.body), color = colors.text) - Text(stringResource(R.string.ssh_server_prompts), style = NetKitType.label, color = colors.dim) + Text(stringResource(R.string.ssh_server_prompts), style = NetKitType.label, color = colors.muted) Text(challenge.name, style = NetKitType.body, color = colors.text); Text(challenge.instruction, style = NetKitType.body, color = colors.muted) challenge.prompts.forEachIndexed { index, prompt -> OutlinedTextField(answers[index], { value -> answers = answers.mapIndexed { i, old -> if (i == index) value.take(4096) else old } }, label = { Text(if (prompt == "Password") stringResource(R.string.ssh_password) else prompt) }, singleLine = true, @@ -812,7 +1088,7 @@ private fun AuthenticationDialog(challenge: AuthChallenge, viewModel: SshViewMod * equal [width]. [active] != null makes it a toggle (Ctrl/Alt/more keys) on the accent soft fill. */ @Composable -private fun KeyPill(label: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, +internal fun KeyPill(label: String, onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, active: Boolean? = null, icon: ImageVector? = null, width: Dp = 52.dp) { val chrome = TerminalChrome val on = active == true @@ -835,7 +1111,8 @@ private const val TERMINAL_FONT_DEFAULT = 12.5f private const val TERMINAL_LINE_RATIO = 1.6f @Composable -private fun Terminal(session: SshSessionState, viewModel: SshViewModel, modifier: Modifier) { +private fun Terminal(session: SshSessionState, viewModel: SshViewModel, snippets: List, modifier: Modifier, + compact: Boolean, showControls: Boolean, onToggleControls: () -> Unit) { // Terminal input/paste must not survive in savedInstanceState. var input by remember(session.id) { mutableStateOf("") } var paste by remember(session.id) { mutableStateOf(null) } @@ -869,13 +1146,18 @@ private fun Terminal(session: SshSessionState, viewModel: SshViewModel, modifier val sendKey: (TerminalKey, Boolean, Boolean, Boolean) -> Unit = { key, ctrlPressed, altPressed, shiftPressed -> directInput?.flushComposing(); sendKeyRaw(key, ctrlPressed, altPressed, shiftPressed) } - val sendInput: () -> Unit = { sendText(safeTerminalPaste(input), false, false); input = "" } + val sendInput: () -> Unit = { + directInput?.flushComposing() + val payload = terminalFallbackPayload(input, control, alt, session.terminal.bracketedPaste) + if (payload.isNotEmpty()) viewModel.send(session.id, payload) + control = false; alt = false; input = "" + } val colors = NetKitTheme.colors val chrome = TerminalChrome val background = colors.terminalBackground val foregroundDefault = colors.terminalText - val cursorColor = chrome.accent - val cursorText = chrome.accentInk + val terminalTheme = TerminalTheme(foregroundDefault.toArgb(), background.toArgb(), chrome.accent, chrome.accentInk) + val heading = session.terminal.title.takeIf { it.isNotBlank() }?.let { stringResource(R.string.ssh_terminal_title, session.name, it) } ?: session.name val grid = if (terminalSize.width > 0 && terminalSize.height > 0 && cell.width > 0 && cell.height > 0) (terminalSize.width / cell.width).coerceIn(10, 240) to (terminalSize.height / cell.height).coerceIn(2, 100) else null Column(modifier, verticalArrangement = Arrangement.spacedBy(Spacing.small)) { @@ -884,22 +1166,16 @@ private fun Terminal(session: SshSessionState, viewModel: SshViewModel, modifier Row(Modifier.fillMaxWidth().padding(horizontal = Spacing.tiny), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { Box(Modifier.size(6.dp).clip(CircleShape).background(chrome.tone(sessionTone(session)).foreground)) - Text(grid?.let { (columns, height) -> stringResource(R.string.ssh_terminal_header, session.name, columns, height) } ?: session.name, + Text(grid?.let { (columns, height) -> stringResource(R.string.ssh_terminal_header, heading, columns, height) } ?: heading, Modifier.weight(1f), style = NetKitType.label, color = chrome.muted, maxLines = 1, overflow = TextOverflow.Ellipsis) } SelectionContainer(Modifier.weight(1f).fillMaxWidth().background(background).testTag("ssh_terminal_output")) { LazyColumn(state = list, modifier = Modifier.fillMaxSize().onSizeChanged { terminalSize = it }) { - items(rows.size) { index -> Text(buildAnnotatedString { - rows[index].runs.forEach { run -> - withStyle(SpanStyle(color = terminalForeground(run.foreground, foregroundDefault, background), - background = terminalBackground(run.background, foregroundDefault, background), - fontWeight = if (run.bold) FontWeight.Bold else FontWeight.Normal)) { append(run.text) } - } - if (session.connected && session.terminal.cursorVisible && index == session.terminal.history.size + session.terminal.cursorRow) { - val column = session.terminal.cursorColumn - if (column < length) addStyle(SpanStyle(color = cursorText, background = cursorColor), column, column + 1) - } - }, style = style, softWrap = false, maxLines = 1) } + items(rows.size) { index -> + val terminal = session.terminal + val cursor = if (session.connected && terminal.cursorVisible && index == terminal.history.size + terminal.cursorRow) terminal.cursorColumn else -1 + TerminalLine(rows[index], cursor, style, terminalTheme) + } } } LaunchedEffect(session.terminal) { @@ -927,6 +1203,11 @@ private fun Terminal(session: SshSessionState, viewModel: SshViewModel, modifier Icon(NetKitIcons.More, contentDescription = stringResource(R.string.ssh_terminal_options), tint = chrome.muted) } NetKitMenu(expanded = menu, onDismiss = { menu = false }) { + if (compact) DropdownMenuItem(text = { MenuText(stringResource( + if (showControls) R.string.ssh_hide_controls else R.string.ssh_show_controls)) }, + onClick = { menu = false; onToggleControls() }, modifier = Modifier.testTag("ssh_toggle_controls")) + if (session.consoleKind == ConsoleKind.SERIAL && session.connected) DropdownMenuItem( + text = { MenuText(stringResource(R.string.console_break)) }, onClick = { menu = false; viewModel.serialBreak(session.id) }) DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_font_smaller)) }, onClick = { fontSize = (fontSize - 1).coerceAtLeast(8f) }) DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_font_larger)) }, onClick = { fontSize = (fontSize + 1).coerceAtMost(24f) }) DropdownMenuItem(text = { MenuText(stringResource(R.string.ssh_paste)) }, onClick = { @@ -939,7 +1220,11 @@ private fun Terminal(session: SshSessionState, viewModel: SshViewModel, modifier } } } - Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(Spacing.tiny)) { + if (showControls) SnippetBar(snippets, enabled = session.connected) { snippet -> + directInput?.flushComposing(); control = false; alt = false + viewModel.sendSnippet(session.id, snippet) + } + if (showControls) Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(Spacing.tiny)) { KeyPill(stringResource(R.string.ssh_ctrl), { directInput?.flushComposing(); control = !control }, active = control) KeyPill(stringResource(R.string.ssh_alt), { directInput?.flushComposing(); alt = !alt }, active = alt) val keys = listOf(R.string.ssh_esc to TerminalKey.ESCAPE, R.string.ssh_tab to TerminalKey.TAB, @@ -950,7 +1235,7 @@ private fun Terminal(session: SshSessionState, viewModel: SshViewModel, modifier modifier = if (key == TerminalKey.ENTER) Modifier.testTag("ssh_enter") else Modifier) } KeyPill(stringResource(R.string.ssh_more_keys), { directInput?.flushComposing(); moreKeys = !moreKeys }, active = moreKeys, icon = NetKitIcons.More) } - if (moreKeys) Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(Spacing.tiny)) { + if (showControls && moreKeys) Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(Spacing.tiny)) { val keys = listOf(R.string.ssh_home to TerminalKey.HOME, R.string.ssh_end to TerminalKey.END, R.string.ssh_page_up to TerminalKey.PAGE_UP, R.string.ssh_page_down to TerminalKey.PAGE_DOWN, R.string.ssh_key_insert to TerminalKey.INSERT, R.string.ssh_key_delete to TerminalKey.DELETE) @@ -1007,29 +1292,41 @@ private fun Terminal(session: SshSessionState, viewModel: SshViewModel, modifier dismiss = { NeutralButton(stringResource(R.string.ssh_cancel), small = true, onClick = { paste = null }) }) } } +/** Theme colours of the terminal surface; immutable, so unchanged rows skip recomposition and re-layout. */ +@Immutable +private data class TerminalTheme(val foreground: Int, val background: Int, val cursor: Color, val cursorText: Color) + /** - * Default colours (SGR 39/49, foreground 7 on background 0, and their inverse) follow the - * terminal tokens, so plain output matches the app; explicit ANSI colours keep the palette. + * One terminal row. [TerminalBuffer] returns the same [TerminalRow] instance for an unchanged row, so with + * strong skipping only changed rows (and the cursor row) are rebuilt; colours come from [TerminalPalette]. */ -private fun terminalForeground(index: Int, text: Color, background: Color): Color = when (index) { - 7 -> text - 0 -> background - else -> terminalColor(index) -} - -private fun terminalBackground(index: Int, text: Color, background: Color): Color = when (index) { - 0 -> background - 7 -> text - else -> terminalColor(index) +@Composable +private fun TerminalLine(row: TerminalRow, cursorColumn: Int, style: TextStyle, theme: TerminalTheme) { + val text = remember(row, cursorColumn, theme) { terminalLineText(row, cursorColumn, theme) } + Text(text, style = style, softWrap = false, maxLines = 1) } -private fun terminalColor(index: Int): Color { - if (index >= 0x1000000) return Color(0xff000000L or (index.toLong() and 0xffffff)) - val basic = longArrayOf(0xff000000, 0xffcc4444, 0xff44cc44, 0xffcccc44, 0xff6688dd, 0xffcc44cc, 0xff44cccc, 0xffdddddd, 0xff777777, 0xffff7777, 0xff77ff77, 0xffffff77, 0xff99bbff, 0xffff77ff, 0xff77ffff, 0xffffffff) - if (index < 16) return Color(basic[index.coerceAtLeast(0)]) - if (index >= 232) { val level = (8 + (index.coerceAtMost(255) - 232) * 10); return Color(level, level, level) } - val n = index - 16; fun component(n: Int) = if (n == 0) 0 else 55 + n * 40 - return Color(component(n / 36), component(n / 6 % 6), component(n % 6)) +private fun terminalLineText(row: TerminalRow, cursorColumn: Int, theme: TerminalTheme): AnnotatedString = buildAnnotatedString { + row.runs.forEach { run -> + val colors = TerminalPalette.resolve(run, theme.foreground, theme.background) + val decoration = when { + run.underline && run.strikethrough -> TextDecoration.combine(listOf(TextDecoration.Underline, TextDecoration.LineThrough)) + run.underline -> TextDecoration.Underline + run.strikethrough -> TextDecoration.LineThrough + else -> null + } + withStyle(SpanStyle(color = Color(colors.foreground), background = Color(colors.background), + fontWeight = if (run.bold) FontWeight.Bold else FontWeight.Normal, + fontStyle = if (run.italic) FontStyle.Italic else FontStyle.Normal, textDecoration = decoration)) { append(run.text) } + } + if (cursorColumn >= 0) { + val plain = row.text + val start = row.offsetOf(cursorColumn) + if (start < plain.length) { + val end = if (plain[start].isHighSurrogate() && start + 1 < plain.length) start + 2 else start + 1 + addStyle(SpanStyle(color = theme.cursorText, background = theme.cursor), start, end) + } + } } private fun sshFailureResource(failure: SshFailure?): Int = when (failure) { @@ -1046,5 +1343,6 @@ private fun sshFailureResource(failure: SshFailure?): Int = when (failure) { SshFailure.IMPORT_FORMAT -> R.string.ssh_error_import_format SshFailure.SECRET_UNAVAILABLE -> R.string.ssh_error_secret SshFailure.STORAGE -> R.string.ssh_storage_failed + SshFailure.JUMP_CHAIN -> R.string.ssh_error_jump_chain else -> R.string.ssh_operation_failed } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionLog.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionLog.kt new file mode 100644 index 0000000..dda3846 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionLog.kt @@ -0,0 +1,165 @@ +package cz.netkit.app.ssh + +import cz.netkit.shared.ssh.SSH_SESSION_LOG_LIMIT_BYTES +import cz.netkit.shared.ssh.SessionLogBudget +import cz.netkit.shared.ssh.TerminalLogFilter +import java.io.OutputStream +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter +import java.time.temporal.ChronoUnit +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.util.concurrent.atomic.AtomicBoolean +import java.util.concurrent.atomic.AtomicReference + +enum class SshLogStop { USER, SESSION_ENDED, LIMIT, OVERFLOW, WRITE_FAILED } + +/** + * Plain-text session log written off the main thread. Terminal output is filtered (no escape + * sequences), bounded to [limitBytes] including header and footer, and every stop writes a footer + * with the end time and reason. Output arriving faster than the file accepts stops the log rather + * than growing memory ([SshLogStop.OVERFLOW]). + * + * A document provider may block forever in open, write, flush or close (review of 41, P2). Every such + * call is timed: one that takes longer than [ioTimeoutMs] aborts the log — [cancelOpen] cancels a + * pending open, the stream is closed from another thread and [onStopped] reports + * [SshLogStop.WRITE_FAILED] exactly once, so the session can start a new log. A thread stuck inside + * the provider is abandoned (it ends when the provider returns or fails on the closed descriptor). + */ +class SshSessionLog( + private val scope: CoroutineScope, + private val sessionName: String, + private val open: suspend () -> OutputStream, + private val onStopped: (SshLogStop) -> Unit, + private val limitBytes: Long = SSH_SESSION_LOG_LIMIT_BYTES, + private val now: () -> OffsetDateTime = { OffsetDateTime.now().truncatedTo(ChronoUnit.SECONDS) }, + private val cancelOpen: () -> Unit = {}, + private val ioTimeoutMs: Long = IO_TIMEOUT_MS, +) { + companion object { const val IO_TIMEOUT_MS = 15_000L } + private val reported = AtomicBoolean(false) + private val activeStream = AtomicReference() + /** Monotonic start (ms) of the blocking provider call in progress, 0 when none. */ + @Volatile private var busySince = 0L + + private sealed interface Item { class Text(val value: String) : Item; class Stop(val reason: SshLogStop) : Item } + private val queue = Channel(capacity = 512) + @Volatile var stopped = false; private set + @Volatile private var pendingReason: SshLogStop? = null + + private val started = java.util.concurrent.atomic.AtomicBoolean(false) + + /** + * Separate from construction: the owner first registers this instance, then starts it, so even an + * immediate open failure reports [onStopped] for a fully registered log (revize P2). + */ + fun start() { + check(started.compareAndSet(false, true)) + scope.launch(Dispatchers.IO) { run() } + scope.launch { watch() } + } + + private fun clock() = System.nanoTime() / 1_000_000 + + private suspend fun watch() { + val step = (ioTimeoutMs / 4).coerceIn(10, 1000) + while (!reported.get()) { + delay(step) + val since = busySince + if (since != 0L && clock() - since > ioTimeoutMs) { abort(); return } + } + } + + /** A provider call hangs: give up on it without waiting for it. */ + private fun abort() { + stopped = true; queue.close() + try { cancelOpen() } catch (_: Exception) { } + activeStream.getAndSet(null)?.let(::closeAsync) + report(SshLogStop.WRITE_FAILED) + } + + /** Closing may block in the provider as well: never on the caller's thread. */ + private fun closeAsync(stream: OutputStream) { + Thread({ try { stream.close() } catch (_: Exception) { } }, "netkit-log-close").apply { isDaemon = true }.start() + } + + private fun report(reason: SshLogStop) { if (reported.compareAndSet(false, true)) onStopped(reason) } + + private inline fun io(block: () -> T): T { + if (reported.get()) throw java.io.IOException("Log aborted") + busySince = clock().coerceAtLeast(1) + try { return block() } finally { busySince = 0L } + } + + /** Called from the transport reader thread; never blocks it. */ + fun append(text: String) { + if (stopped || text.isEmpty()) return + if (queue.trySend(Item.Text(text)).isFailure) stop(SshLogStop.OVERFLOW) + } + + fun stop(reason: SshLogStop) { + if (stopped) return + stopped = true + // The stop marker must not be lost to a full buffer: close after a best-effort marker. + if (queue.trySend(Item.Stop(reason)).isFailure) pendingReason = reason + queue.close() + } + + private suspend fun run() { + val filter = TerminalLogFilter() + val format = DateTimeFormatter.ISO_OFFSET_DATE_TIME + val footerReserve = 256 + val budget = SessionLogBudget((limitBytes - footerReserve).coerceAtLeast(0)) + var stream: OutputStream? = null + var reason: SshLogStop = SshLogStop.SESSION_ENDED + try { + val output = io { open() } + stream = output + activeStream.set(output) + fun write(text: String): Boolean { + val part = budget.take(text) + if (part.isNotEmpty()) io { output.write(part.toByteArray(Charsets.UTF_8)) } + return !budget.exhausted + } + write("# NetKit SSH log: ${sessionName.filter { it.code >= 32 }}\n# start: ${now().format(format)}\n") + io { output.flush() } + loop@ for (item in queue) { + when (item) { + is Item.Text -> if (!write(filter.feed(item.value))) { reason = SshLogStop.LIMIT; break@loop } + is Item.Stop -> { reason = item.reason; break@loop } + } + if (queue.isEmpty) io { output.flush() } + } + if (reason != SshLogStop.LIMIT) pendingReason?.let { reason = it } + if (reason != SshLogStop.LIMIT && !write(filter.flush())) reason = SshLogStop.LIMIT + val footer = "# end: ${now().format(format)}" + when (reason) { + SshLogStop.LIMIT -> " (size limit ${limitBytes / (1024 * 1024)} MiB reached)" + SshLogStop.OVERFLOW -> " (output faster than storage, log stopped)" + else -> "" + } + "\n" + io { output.write(footer.toByteArray(Charsets.UTF_8)) } + io { output.flush() } + } catch (e: CancellationException) { + reason = SshLogStop.WRITE_FAILED; throw e + } catch (_: Exception) { + reason = SshLogStop.WRITE_FAILED + } finally { + stopped = true; queue.close() + // After an abort the closing thread owns the stream; otherwise close it here, also timed. + val own = stream?.takeIf { activeStream.compareAndSet(it, null) } + withContext(NonCancellable) { + if (own != null) { + if (reported.get()) closeAsync(own) // aborted while open() was still returning + else try { io { own.close() } } catch (_: Exception) { reason = SshLogStop.WRITE_FAILED } + } + } + report(reason) + } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionService.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionService.kt new file mode 100644 index 0000000..ae72876 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionService.kt @@ -0,0 +1,199 @@ +package cz.netkit.app.ssh + +import android.Manifest +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.content.pm.ServiceInfo +import android.content.res.Configuration +import android.os.Build +import android.os.IBinder +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.core.content.ContextCompat +import cz.netkit.app.R +import cz.netkit.app.nav.AppShortcuts +import cz.netkit.app.wol.NetKitApplication +import cz.netkit.shared.nav.AppTarget +import cz.netkit.shared.ssh.sshServiceWanted +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +/** What the notification may show: a count and the session (profile) names, never host or address. */ +data class SshLiveSessions(val count: Int = 0, val names: List = emptyList()) + +/** Decide at connect time, while the actual host is known. Null is localized when the notification is drawn. */ +internal fun sessionNotificationName(name: String, host: String): String? { + val label = name.trim() + val target = host.trim().trimEnd('.') + if (label.isEmpty() || (target.isNotEmpty() && label.contains(target, ignoreCase = true))) return null + // Search inside longer labels as well (prefixes, user@host:port, bracketed or scoped IPv6). + if (notificationAddress.containsMatchIn(label)) return null + return label.take(40) +} + +// Fail closed for address-shaped labels: dotted quad, compressed IPv6, or full IPv6 groups. +private val notificationAddress = Regex("""(?:[0-9]{1,3}\.){3}[0-9]{1,3}|::|(?:[0-9a-fA-F]{1,4}:){7}""") + +/** + * Process-wide link between [SshViewModel] (owns the connections) and [SshSessionService] (keeps the + * process in the foreground while a session is live). The service never holds a connection itself. + */ +class SshSessionKeeper(private val context: Context) { + private val live = MutableStateFlow(SshLiveSessions()) + val sessions: StateFlow = live.asStateFlow() + private val foreground = MutableStateFlow(false) + /** True while the service runs as a foreground service; then the 5-minute background limit is off. */ + val serviceForeground: StateFlow = foreground.asStateFlow() + @Volatile private var disconnect: (() -> Unit)? = null + @Volatile private var starting = false + + fun attach(onDisconnectAll: () -> Unit) { disconnect = onDisconnectAll } + fun detach(onDisconnectAll: () -> Unit) { if (disconnect === onDisconnectAll) disconnect = null } + + /** POST_NOTIFICATIONS (API 33+) granted and notifications not switched off for the app. */ + fun notificationsAllowed(): Boolean = + (Build.VERSION.SDK_INT < 33 || ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) && + NotificationManagerCompat.from(context).areNotificationsEnabled() + + /** + * Called on the main thread with every change of live (connecting or connected) sessions. Starts the + * service while the app is visible (a session starts only from a tap); a refused start (background + * start restriction, notifications off) leaves the 5-minute fallback. + */ + fun update(value: SshLiveSessions) { + live.value = value + if (sshServiceWanted(value.count, notificationsAllowed()) && !foreground.value && !starting) { + starting = true + try { ContextCompat.startForegroundService(context, Intent(context, SshSessionService::class.java)) } + catch (_: IllegalStateException) { starting = false } // ForegroundServiceStartNotAllowedException (API 31+) + catch (_: SecurityException) { starting = false } + } + } + + internal fun disconnectAll() { disconnect?.invoke() } + + companion object { + /** Private preferences: whether the once-only POST_NOTIFICATIONS question was already asked. */ + const val PREFS = "ssh_session_service" + const val PREF_ASKED = "asked" + } + internal fun started() { starting = false; foreground.value = true } + internal fun stopped() { starting = false; foreground.value = false } +} + +/** + * Foreground service of type `specialUse` (docs/bezpecnost.md § SSH na pozadí; Telnet a USB konzole): only a notification and + * the process priority; it runs from the first live session to the last one and stops itself then. + * Not exported; its only external entry is the app's own immutable "Odpojit vše" PendingIntent. + */ +class SshSessionService : Service() { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private val keeper get() = (application as NetKitApplication).sshKeeper + private var observing = false + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + if (intent?.action == ACTION_DISCONNECT_ALL) { + keeper.disconnectAll() + if (!keeper.serviceForeground.value) stopSelf() + return START_NOT_STICKY + } + // startForegroundService() requires startForeground() even when the last session ended meanwhile. + try { + createChannel(this) + val notification = notification(keeper.sessions.value) + if (Build.VERSION.SDK_INT >= 34) startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE) + else startForeground(NOTIFICATION_ID, notification) + } catch (_: RuntimeException) { + // ForegroundServiceStartNotAllowedException / type mismatch: no protection, 5-minute fallback stays. + keeper.stopped(); stopSelf(); return START_NOT_STICKY + } + keeper.started() + if (!observing) { + observing = true + scope.launch { + keeper.sessions.collect { sessions -> + if (sessions.count == 0) { stopForeground(STOP_FOREGROUND_REMOVE); keeper.stopped(); stopSelf() } + else redraw(sessions) + } + } + } + // Process death ends every connection; a restarted service would protect nothing. + return START_NOT_STICKY + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + val sessions = keeper.sessions.value + if (keeper.serviceForeground.value && sessions.count > 0) redraw(sessions) + } + + private fun redraw(sessions: SshLiveSessions) { + if (Build.VERSION.SDK_INT < 33 || ContextCompat.checkSelfPermission(this, + Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) + NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification(sessions)) + } + + override fun onDestroy() { keeper.stopped(); scope.cancel(); super.onDestroy() } + + private fun notification(sessions: SshLiveSessions): Notification { + val count = sessions.count.coerceAtLeast(1) + val title = resources.getQuantityString(R.plurals.ssh_notification_title, count, count) + val open = PendingIntent.getActivity(this, 0, + AppShortcuts.openIntent(this, AppTarget.Ssh).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + val disconnect = PendingIntent.getService(this, 1, + Intent(this, SshSessionService::class.java).setAction(ACTION_DISCONNECT_ALL), PendingIntent.FLAG_IMMUTABLE) + // Lock screen: the public version has no names; even the private one has no host or address. + val public = NotificationCompat.Builder(this, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification_ssh) + .setContentTitle(getString(R.string.ssh_notification_public)) + .setOngoing(true).build() + val names = sessions.names.mapIndexed { index, name -> + name ?: getString(R.string.ssh_notification_session, index + 1) + }.joinToString(", ").take(200) + return NotificationCompat.Builder(this, CHANNEL_ID) + .setSmallIcon(R.drawable.ic_notification_ssh) + .setContentTitle(title) + .setContentText(names.ifEmpty { getString(R.string.ssh_notification_text) }) + .setContentIntent(open) + .addAction(0, getString(R.string.ssh_notification_disconnect_all), disconnect) + .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) + .setPublicVersion(public) + .setCategory(NotificationCompat.CATEGORY_SERVICE) + .setPriority(NotificationCompat.PRIORITY_LOW) + .setOnlyAlertOnce(true).setOngoing(true).setShowWhen(false) + .setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE) + .build() + } + + companion object { + const val CHANNEL_ID = "ssh_sessions" + const val NOTIFICATION_ID = 4201 + const val ACTION_DISCONNECT_ALL = "cz.netkit.app.ssh.action.DISCONNECT_ALL" + + fun createChannel(context: Context, onlyIfPresent: Boolean = false) { + val manager = context.getSystemService(NotificationManager::class.java) ?: return + if (onlyIfPresent && manager.getNotificationChannel(CHANNEL_ID) == null) return + manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.ssh_notification_channel), + NotificationManager.IMPORTANCE_LOW).apply { + description = context.getString(R.string.ssh_notification_channel_description) + setShowBadge(false) + lockscreenVisibility = Notification.VISIBILITY_PRIVATE + }) + } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt index c18f16e..2040d6e 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt @@ -1,5 +1,6 @@ package cz.netkit.app.ssh +import cz.netkit.app.backup.ConfigFile import android.content.Context import android.content.pm.PackageManager import android.security.keystore.KeyGenParameterSpec @@ -61,7 +62,7 @@ fun InputStream.readBytesBounded(limit: Int): ByteArray { } class SshStore(private val file: File, private val ownerScope: CoroutineScope) { - constructor(context: Context, scope: CoroutineScope, file: File = context.filesDir.resolve("datastore/ssh.json")) : this(file, scope) + constructor(context: Context, scope: CoroutineScope, file: File = ConfigFile.SSH.resolve(context)) : this(file, scope) private val mutex = Mutex() private var job: Job? = null private var store: androidx.datastore.core.DataStore? = null diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt index 902ea31..753cd63 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt @@ -1,5 +1,6 @@ package cz.netkit.app.ssh +import androidx.core.content.edit import android.app.Application import android.net.Uri import android.net.Network @@ -19,13 +20,23 @@ import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.map +import cz.netkit.app.nav.AppShortcuts +import cz.netkit.shared.nav.AppTarget import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock class SshSessionState(val id: String, val name: String, val terminal: TerminalSnapshot, - val connected: Boolean = false, val ended: Boolean = false, val failed: Boolean = false, val failure: SshFailure? = null, val networkLost: Boolean = false) { + val connected: Boolean = false, val ended: Boolean = false, val failed: Boolean = false, val failure: SshFailure? = null, val networkLost: Boolean = false, + val profileId: String? = null, val forwards: List = emptyList(), + val logging: Boolean = false, val logStop: SshLogStop? = null, val consoleKind: ConsoleKind? = null, val notificationName: String? = null) { fun copy(terminal: TerminalSnapshot = this.terminal, connected: Boolean = this.connected, - ended: Boolean = this.ended, failed: Boolean = this.failed, failure: SshFailure? = this.failure, networkLost: Boolean = this.networkLost) = SshSessionState(id, name, terminal, connected, ended, failed, failure, networkLost) + ended: Boolean = this.ended, failed: Boolean = this.failed, failure: SshFailure? = this.failure, networkLost: Boolean = this.networkLost, + forwards: List = this.forwards, logging: Boolean = this.logging, logStop: SshLogStop? = this.logStop, + name: String = this.name, notificationName: String? = this.notificationName) = + SshSessionState(id, name, terminal, connected, ended, failed, failure, networkLost, profileId, forwards, logging, logStop, consoleKind, notificationName) } data class HostChallenge(val requestId: String, val sessionId: String, val offered: TrustedHostKey, val previous: TrustedHostKey?, val lastRejected: TrustedHostKey? = null) data class AuthChallenge(val requestId: String, val sessionId: String, val trustedIdentity: String, val name: String, val instruction: String, val prompts: List, val echo: List) @@ -53,19 +64,22 @@ internal suspend fun completeSshProfileExport( class SshViewModel(application: Application) : AndroidViewModel(application) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) - private val storeScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) - private val store = SshStore(application, storeScope) + internal val access = SshAccess(application, scope) + /** Process-wide singleton (zadání 36 §2.8); the ViewModel never closes it. */ + private val store = (application as NetKitApplication).sshStore private val secrets = (application as NetKitApplication).createSshSecretStore() private val _state = MutableStateFlow(SshUiState()) val state = _state.asStateFlow() private val operations = Mutex(); private val prompts = Mutex() private val profileImporter = SshProfileImportController(scope, operations, store::read, store::update, blocked = { _state.value.blocksProfileImport() }, generateId = { UUID.randomUUID().toString() }, deleteSecret = secrets::delete) - private val connections = mutableMapOf() + private val connections = mutableMapOf() + private val usb = UsbConsole(application) private val buffers = java.util.concurrent.ConcurrentHashMap() private val attempts = SshAttemptGate() private val sessionProfiles = mutableMapOf() private val sessionNetworks = java.util.concurrent.ConcurrentHashMap() + private val logs = java.util.concurrent.ConcurrentHashMap() private val connectivity = application.getSystemService(ConnectivityManager::class.java) private val networkCallback = object : ConnectivityManager.NetworkCallback() { override fun onLost(network: Network) = networkWarning { it == network } @@ -89,24 +103,67 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { } private val hostReplies = PromptReplyGate() private val authReplies = PromptReplyGate?>() - private val backgroundPolicy = SshBackgroundPolicy(android.os.SystemClock::elapsedRealtime) + private val backgroundPolicy = SshBackgroundPolicy((application as NetKitApplication).sshBackgroundGraceMillis, + android.os.SystemClock::elapsedRealtime) private var backgroundTimeout: Job? = null private var loader: Job? = null + /** Zadání 42: foreground service while a session is live; it lifts the 5-minute background limit. */ + private val keeper = (application as NetKitApplication).sshKeeper + private val disconnectAll: () -> Unit = { scope.launch { closeAllSessions() } } fun onForeground() { + access.refresh() backgroundTimeout?.cancel(); backgroundTimeout = null - if (backgroundPolicy.foreground()) cancelActive() + if (sshBackgroundCloses(backgroundPolicy.foreground(), keeper.serviceForeground.value)) cancelActive() + // Notifications may have been allowed in system settings meanwhile: start the service now. + publishLiveSessions() } fun onBackground() { + access.leave() backgroundPolicy.background() if (backgroundTimeout?.isActive == true) return backgroundTimeout = scope.launch { delay(backgroundPolicy.remainingMillis() ?: return@launch) - if (backgroundPolicy.expired()) cancelActive() + if (sshBackgroundCloses(backgroundPolicy.expired(), keeper.serviceForeground.value)) cancelActive() } } fun closeAllSessions() { _state.value.sessions.map { it.id }.forEach(::closeSession) } + /** Called after the POST_NOTIFICATIONS answer (granted or not) so the service follows at once. */ + fun notificationPermissionChanged() { publishLiveSessions() } + private val prefs = application.getSharedPreferences(SshSessionKeeper.PREFS, android.content.Context.MODE_PRIVATE) + /** The runtime notification question comes once, at the first connection (zadání 42 §2.1). */ + fun shouldAskNotifications(): Boolean = android.os.Build.VERSION.SDK_INT >= 33 && !keeper.notificationsAllowed() && + !prefs.getBoolean(SshSessionKeeper.PREF_ASKED, false) + fun notificationsAsked() { prefs.edit { putBoolean(SshSessionKeeper.PREF_ASKED, true) } } + fun notificationsAllowed(): Boolean = keeper.notificationsAllowed() + val serviceForeground get() = keeper.serviceForeground + private fun publishLiveSessions() { + val live = _state.value.sessions.filter { !it.ended } + keeper.update(SshLiveSessions(live.size, live.map { it.notificationName })) + } + + // --- SFTP browser (zadání 42 §2.3): one at a time, on the selected session ------------------- + private val _sftp = MutableStateFlow(null) + val sftp = _sftp.asStateFlow() + fun openSftp(sessionId: String) = access.protect { openAuthorizedSftp(sessionId) } + private fun openAuthorizedSftp(sessionId: String) { + // SFTP exists only on an SSH transport (zadání 44: Telnet and USB serial sessions have none). + val connection = connections[sessionId] as? JschConnection ?: return + if (_state.value.sessions.none { it.id == sessionId && it.connected && !it.ended }) return + closeSftp() + val controller = SftpController(scope, sessionId, getApplication().contentResolver, + open = connection::openSftp, release = connection::releaseSftp, canOperate = access::canView) + _sftp.value = controller + controller.start() + } + fun closeSftp() { _sftp.value?.close(); _sftp.value = null } + private fun closeSftpOf(sessionId: String) { if (_sftp.value?.sessionId == sessionId) closeSftp() } + init { + keeper.attach(disconnectAll) + scope.launch { + _state.map { state -> state.sessions.filter { !it.ended }.map { it.notificationName } }.distinctUntilChanged().collect { publishLiveSessions() } + } scope.launch { profileImporter.state.collect { transfer -> _state.update { it.copy(pendingProfileImport = transfer.pendingProfileImport, @@ -120,6 +177,16 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { } try { connectivity.registerDefaultNetworkCallback(networkCallback); observingNetwork = true } catch (_: SecurityException) { /* Connection still has transport errors; no false network status claim. */ } + // Pinned shortcuts follow every successfully loaded profile list (zadání 36 §2.3). + scope.launch { + _state.map { state -> state.data.profiles.takeIf { state.loaded && !state.storeFailed } }.filterNotNull() + .distinctUntilChanged().collect { profiles -> + val app = getApplication() + withContext(Dispatchers.IO) { + AppShortcuts.sync(app, cz.netkit.shared.nav.AppRecordKind.SSH_PROFILE, profiles.associate { it.id to it.name }, app.getString(cz.netkit.app.R.string.shortcut_disabled_ssh)) + } + } + } reload(); scope.launch { try { val value = secrets.protection(); _state.update { it.copy(protection = value) } } catch (error: Exception) { _state.update { it.copy(error = true, failure = classifySshFailure(error)) } } } } fun reload() { loader?.cancel() @@ -185,18 +252,51 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { if (previous?.secretRef != ref) previous?.secretRef?.let { secrets.delete(it) } withContext(Dispatchers.Main) { onSaved() } } - fun moveProfile(id: String, delta: Int) { - if (_state.value.busy || profileImporter.active) return - operation { store.update { moveSshProfile(it, id, delta) } } - } + fun swapProfileRows(key: String, neighbor: String) = operation { store.update { it.swapProfiles(key, neighbor) } } fun deleteProfile(id: String) = operation { val profile = store.read().profiles.find { it.id == id } ?: return@operation - store.update { it.copy(profiles = it.profiles.filterNot { p -> p.id == id }) } + // Its own snippets go with it; profiles that used it as a jump host lose the link (the dialog warned). + store.update { removeSshProfile(it, id) } profile.secretRef?.let { secrets.delete(it) } } + /** Snippets are not secrets; the UI warns before saving text that looks like a credential. */ + fun saveSnippet(snippet: SshSnippet, onSaved: () -> Unit = {}) = operation { + store.update { data -> requireNotNull(upsertSnippet(data, snippet)) } + withContext(Dispatchers.Main) { onSaved() } + } + fun deleteSnippet(id: String) = operation { store.update { data -> data.copy(snippets = data.snippets.filterNot { it.id == id }) } } + /** Sends exactly the snippet text (+ Enter when set) through the same bounded write queue as typing. */ + fun sendSnippet(sessionId: String, snippet: SshSnippet) { send(sessionId, snippet.payload()) } + /** Explicit per-session opt-in via SAF; never on by default. Stops at session end, close or 50 MiB. */ + fun startLog(sessionId: String, uri: Uri) { + val session = _state.value.sessions.find { it.id == sessionId } ?: return + if (session.consoleKind == ConsoleKind.TELNET || session.ended || logs.containsKey(sessionId)) return + val resolver = getApplication().contentResolver + val holder = AtomicReference() + // A cancellable open: a provider that never answers is cancelled by the log's I/O timeout (review of 41). + val opening = android.os.CancellationSignal() + val log = SshSessionLog(scope, session.name, open = { + val descriptor = resolver.openFileDescriptor(uri, "wt", opening) ?: throw java.io.IOException("Log destination unavailable") + android.os.ParcelFileDescriptor.AutoCloseOutputStream(descriptor) // closing the stream closes the descriptor + }, cancelOpen = opening::cancel, onStopped = { reason -> + holder.get()?.let { logs.remove(sessionId, it) } + _state.update { state -> state.copy(sessions = state.sessions.map { + if (it.id == sessionId) it.copy(logging = false, logStop = reason) else it }) } + }) + holder.set(log) + if (logs.putIfAbsent(sessionId, log) != null) return + // Publish "logging" before start: a fast failure then always ends in logging = false + reason. + _state.update { state -> state.copy(sessions = state.sessions.map { + if (it.id == sessionId) it.copy(logging = true, logStop = null) else it }) } + log.start() + } + fun stopLog(sessionId: String) { logs[sessionId]?.stop(SshLogStop.USER) } + fun dismissLogStop(sessionId: String) { + _state.update { state -> state.copy(sessions = state.sessions.map { if (it.id == sessionId) it.copy(logStop = null) else it }) } + } fun forgetHost(endpoint: String) = operation { // Do not let an open session silently retain old trust while the user changes it. - withContext(Dispatchers.Main) { cancelActive() } + withContext(Dispatchers.Main) { cancelConnections(connections.values.filterIsInstance()) } store.update { it.copy(hostKeys = it.hostKeys.filterNot { key -> key.endpoint == endpoint }) } } fun generateKey(name: String, type: Int = KeyPair.ED25519) = operation { @@ -227,7 +327,10 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { } private var preparedExport: ByteArray? = null /** Validate and freeze bytes BEFORE the document picker can create a destination. */ - fun prepareExport(onReady: () -> Unit) = operation { + internal fun canCloseForRestore() = !operations.isLocked && !profileImporter.active && !state.value.blocksProfileImport() + + fun prepareExport(onReady: () -> Unit) = access.protect { prepareAuthorizedExport(onReady) } + private fun prepareAuthorizedExport(onReady: () -> Unit) = operation { preparedExport = null _state.update { it.copy(exportFailure = null) } try { preparedExport = encodeSshProfileExport(store.read(), source = "netkit-android") } @@ -237,7 +340,8 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { withContext(Dispatchers.Main) { onReady() } } fun cancelExport() { preparedExport = null } - fun export(uri: Uri) = operation { + fun export(uri: Uri) = access.protect { exportAuthorized(uri) } + private fun exportAuthorized(uri: Uri) = operation { val prepared = preparedExport preparedExport = null _state.update { it.copy(exportFailure = null) } @@ -246,18 +350,124 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { } _state.update { it.copy(exportFailure = failure, exported = failure == null) } } + fun saveConsole(profile: ConsoleProfile, done: () -> Unit) = operation { + require(profile.valid()) + store.update { data -> + val old = data.consoles.find { it.id == profile.id } + val saved = profile.copy(skipTelnetWarning = old?.skipTelnetWarning == true && + old.kind == profile.kind && old.host == profile.host && old.port == profile.port) + data.copy(consoles = if (old == null) data.consoles + saved else data.consoles.map { if (it.id == saved.id) saved else it }) + } + withContext(Dispatchers.Main) { done() } + } + + fun deleteConsole(id: String) = operation { + store.update { data -> data.copy(consoles = data.consoles.filterNot { it.id == id }, + profileOrder = data.profileOrder - "console:$id", recentProfiles = data.recentProfiles - "console:$id") } + } + + suspend fun usbPorts() = withContext(Dispatchers.IO) { usb.ports() } + + fun connectConsole(profile: ConsoleProfile, port: ConsoleUsbPort?, warningAccepted: Boolean, remember: Boolean, + replacement: String? = null) = access.protect { connectAuthorizedConsole(profile, port, warningAccepted, remember, replacement) } + + private fun connectAuthorizedConsole(profile: ConsoleProfile, port: ConsoleUsbPort?, warningAccepted: Boolean, remember: Boolean, + replacement: String?) { + if (profileImporter.active || !_state.value.loaded || profile !in _state.value.data.consoles || + replacement != null && _state.value.sessions.none { it.id == replacement && it.profileId == profile.id } || + _state.value.sessions.count { !it.ended && it.id != replacement } >= 4 || + profile.kind == ConsoleKind.SERIAL && port == null || + profile.kind == ConsoleKind.TELNET && !profile.skipTelnetWarning && !warningAccepted) { + _state.update { it.copy(error = true) }; return + } + if (profile.kind == ConsoleKind.TELNET && warningAccepted && remember) operation { + store.update { data -> data.copy(consoles = data.consoles.map { + if (it == profile) it.copy(skipTelnetWarning = true) else it + }) } + } + openTab(profile.name, profile.host, profile.id, profile.kind, replacement) { _, _, events -> + ConsoleConnection(scope, open = { + when (profile.kind) { + ConsoleKind.TELNET -> openTelnet(profile.host, profile.port) + ConsoleKind.SERIAL -> usb.open(requireNotNull(port), profile.serial) + } + }, onText = events.onText, onConnected = events.onConnected, onEnd = events.onEnd) + } + } + + fun serialBreak(id: String) { + if (_state.value.sessions.none { it.id == id && it.consoleKind == ConsoleKind.SERIAL && it.connected }) return + if ((connections[id] as? ConsoleConnection)?.sendBreak() != true) _state.update { it.copy(error = true) } + } fun connect(profile: SshProfile) { startConnection(profile, null) } - private fun startConnection(profile: SshProfile, replacement: String?) { + private fun startConnection(profile: SshProfile, replacement: String?) = access.protect { + if (replacement == null || _state.value.data.profiles.any { it.id == profile.id }) startAuthorizedConnection(profile, replacement) + else _state.update { it.copy(profileUnavailable = true) } + } + private fun startAuthorizedConnection(profile: SshProfile, replacement: String?) { if (profileImporter.active || !profile.valid() || !_state.value.loaded || _state.value.sessions.count { !it.ended && it.id != replacement } >= 4 || replacement != null && _state.value.sessions.none { it.id == replacement }) { _state.update { it.copy(error = true) }; return } - if (profile.needsKeySelection(_state.value.data)) { - _state.update { it.copy(keySelectionRequired = profile) } + val chain = resolveSshJumpChain(_state.value.data.profiles, profile) + if (chain !is SshJumpResolution.Chain) { + _state.update { it.copy(error = true, failure = SshFailure.JUMP_CHAIN) }; return + } + val hops = chain.hops + (hops + profile).firstOrNull { it.needsKeySelection(_state.value.data) }?.let { missing -> + _state.update { it.copy(keySelectionRequired = missing) } return // No session, buffer, attempt, transport or DNS is created. } _state.update { it.copy(keySelectionRequired = null, profileUnavailable = false) } + openTab(profile.name, profile.host, profile.id, null, replacement) { id, attempt, events -> + sessionProfiles[id] = profile + JschConnection(profile, store, secrets, sshInteraction(profile, id, attempt), scope, + onText = events.onText, onConnected = events.onConnected, onEnd = events.onEnd, + onFailure = events.onFailure, jumps = hops, onForwards = { forwards -> + attempts.publish(id, attempt) { _state.update { state -> state.copy(sessions = state.sessions.map { + if (it.id == id) it.copy(forwards = forwards) else it }) } } + }) + } + } + + private fun sshInteraction(profile: SshProfile, id: String, attempt: Long) = object : SshInteraction { + override suspend fun confirmHost(offered: TrustedHostKey, previous: TrustedHostKey?): Boolean = prompts.withLock { + if (!attempts.isCurrent(id, attempt)) throw CancellationException() + val requestId = UUID.randomUUID().toString() + val answer = hostReplies.open(requestId) + try { + val rejected = store.read().rejectedHostKeys.find { it.endpoint == offered.endpoint } + if (!attempts.publish(id, attempt) { _state.update { it.copy(hostChallenge = HostChallenge(requestId, id, offered, previous, distinctRejectedHostKey(offered, rejected))) } }) throw CancellationException() + answer.await() + } finally { + withContext(NonCancellable) { hostReplies.close(requestId) } + _state.update { if (it.hostChallenge?.requestId == requestId) it.copy(hostChallenge = null) else it } + } + } + override suspend fun authenticate(name: String, instruction: String, prompts: List, echo: List): List? = + authenticateHop(profile, name, instruction, prompts, echo) + override suspend fun authenticateHop(hop: SshProfile, name: String, instruction: String, prompts: List, echo: List): List? = this@SshViewModel.prompts.withLock { + if (!attempts.isCurrent(id, attempt)) throw CancellationException() + val requestId = UUID.randomUUID().toString() + val answer = authReplies.open(requestId) + try { + // A jump hop names itself, so a password is never typed for the wrong server. + val identity = "${hop.name} · ${hop.username}@${hop.endpoint}" + if (hop.id != profile.id) " → ${profile.name}" else "" + if (!attempts.publish(id, attempt) { _state.update { it.copy(authChallenge = AuthChallenge(requestId, id, identity, name, instruction, prompts, echo)) } }) throw CancellationException() + answer.await() + } finally { + withContext(NonCancellable) { authReplies.close(requestId) } + _state.update { if (it.authChallenge?.requestId == requestId) it.copy(authChallenge = null) else it } + } + } + } + + private class TerminalEvents(val onText: (String) -> Unit, val onConnected: () -> Unit, + val onEnd: (Boolean) -> Unit, val onFailure: (SshFailure) -> Unit) + + private fun openTab(name: String, host: String, profileId: String, kind: ConsoleKind?, replacement: String?, + create: (String, Long, TerminalEvents) -> TerminalConnection) { // A replacement reuses its existing tab; keep its previous output until onConnected. if (replacement == null) while (_state.value.sessions.size >= 4) { val ended = _state.value.sessions.firstOrNull { it.ended } ?: break @@ -268,41 +478,16 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { connections.remove(id)?.close() val terminal = buffers.getOrPut(id) { TerminalSessionBuffers() } val buffer = synchronized(terminal) { terminal.beginConnection() } - sessionProfiles[id] = profile sessionNetworks.remove(id) - connectivity.activeNetwork?.let { sessionNetworks[id] = it } + if (kind != ConsoleKind.SERIAL) connectivity.activeNetwork?.let { sessionNetworks[id] = it } + val notificationName = sessionNotificationName(name, host) _state.update { state -> state.copy(sessions = if (replacement == null) - state.sessions + SshSessionState(id, profile.name, buffer.snapshot()) - else state.sessions.map { if (it.id == id) it.copy(connected = false, ended = false, failed = false, failure = null, networkLost = false) else it }, + state.sessions + SshSessionState(id, name, buffer.snapshot(), profileId = profileId, consoleKind = kind, notificationName = notificationName) + else state.sessions.map { if (it.id == id) it.copy(name = name, notificationName = notificationName, connected = false, ended = false, failed = false, failure = null, networkLost = false, forwards = emptyList()) else it }, selectedSession = id) } - val replyTransport = AtomicReference() - val connection = JschConnection(profile, store, secrets, object : SshInteraction { - override suspend fun confirmHost(offered: TrustedHostKey, previous: TrustedHostKey?): Boolean = prompts.withLock { - if (!attempts.isCurrent(id, attempt)) throw CancellationException() - val requestId = UUID.randomUUID().toString() - val answer = hostReplies.open(requestId) - try { - val rejected = store.read().rejectedHostKeys.find { it.endpoint == offered.endpoint } - if (!attempts.publish(id, attempt) { _state.update { it.copy(hostChallenge = HostChallenge(requestId, id, offered, previous, distinctRejectedHostKey(offered, rejected))) } }) throw CancellationException() - answer.await() - } finally { - withContext(NonCancellable) { hostReplies.close(requestId) } - _state.update { if (it.hostChallenge?.requestId == requestId) it.copy(hostChallenge = null) else it } - } - } - override suspend fun authenticate(name: String, instruction: String, prompts: List, echo: List): List? = this@SshViewModel.prompts.withLock { - if (!attempts.isCurrent(id, attempt)) throw CancellationException() - val requestId = UUID.randomUUID().toString() - val answer = authReplies.open(requestId) - try { - if (!attempts.publish(id, attempt) { _state.update { it.copy(authChallenge = AuthChallenge(requestId, id, "${profile.name} · ${profile.username}@${profile.endpoint}", name, instruction, prompts, echo)) } }) throw CancellationException() - answer.await() - } finally { - withContext(NonCancellable) { authReplies.close(requestId) } - _state.update { if (it.authChallenge?.requestId == requestId) it.copy(authChallenge = null) else it } - } - } - }, scope, onText = { text -> + val replyTransport = AtomicReference() + val events = TerminalEvents(onText = { text -> + if (attempts.isCurrent(id, attempt)) logs[id]?.append(text) var reply = "" attempts.publish(id, attempt) { synchronized(terminal) { @@ -323,6 +508,12 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { } }, onConnected = { attempts.publish(id, attempt) { + val key = if (kind == null) "ssh:$profileId" else "console:$profileId" + scope.launch { + try { store.update { it.profileUsed(key) } } + catch (e: CancellationException) { throw e } + catch (_: Exception) { _state.update { it.copy(error = true, failure = SshFailure.STORAGE) } } + } synchronized(terminal) { terminal.connected(buffer) _state.update { state -> state.copy(sessions = state.sessions.map { if (it.id == id) it.copy(terminal = buffer.snapshot(), connected = true) else it }) } @@ -332,8 +523,11 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { attempts.publish(id, attempt) { _state.update { state -> state.copy(sessions = state.sessions.map { if (it.id == id) it.copy(failure = failure) else it }) } } }, onEnd = { failed -> synchronized(terminal) { terminal.ended(buffer) } - attempts.publish(id, attempt) { _state.update { state -> state.copy(sessions = state.sessions.map { if (it.id == id) it.copy(connected = false, ended = true, failed = it.failed || failed) else it }) } } + if (attempts.isCurrent(id, attempt)) logs[id]?.stop(SshLogStop.SESSION_ENDED) + attempts.publish(id, attempt) { _state.update { state -> state.copy(sessions = state.sessions.map { if (it.id == id) it.copy(connected = false, ended = true, failed = it.failed || failed, forwards = emptyList()) else it }) } } + if (attempts.isCurrent(id, attempt)) scope.launch { closeSftpOf(id) } }) + val connection = create(id, attempt, events) replyTransport.set(connection) connections[id] = connection // Initialize PTY before start; same-tab reconnect does not retrigger the Compose size effect. @@ -364,13 +558,24 @@ class SshViewModel(application: Application) : AndroidViewModel(application) { attempts.invalidate(id) _state.value.hostChallenge?.takeIf { it.sessionId == id }?.let { confirmHost(it.requestId, false) } _state.value.authChallenge?.takeIf { it.sessionId == id }?.let { answerAuthentication(it.requestId, null) } + logs[id]?.stop(SshLogStop.USER) + closeSftpOf(id) connections.remove(id)?.close(); buffers.remove(id); sessionProfiles.remove(id); sessionNetworks.remove(id) _state.update { state -> val list = state.sessions.filterNot { it.id == id }; state.copy(sessions = list, selectedSession = if (state.selectedSession == id) list.lastOrNull()?.id else state.selectedSession) } } - fun cancelActive() { + fun cancelActive() = cancelConnections(connections.values) + + private fun cancelConnections(active: Collection) { _state.value.hostChallenge?.let { confirmHost(it.requestId, false) } _state.value.authChallenge?.let { answerAuthentication(it.requestId, null) } - connections.values.forEach { it.close() } + active.forEach { it.close() } + } + override fun onCleared() { + access.close() + if (observingNetwork) connectivity.unregisterNetworkCallback(networkCallback) + closeSftp(); cancelActive() + // Connections live in this ViewModel: without it nothing is live, so the service stops. + keeper.detach(disconnectAll); keeper.update(SshLiveSessions()) + scope.cancel(); super.onCleared() } - override fun onCleared() { if (observingNetwork) connectivity.unregisterNetworkCallback(networkCallback); cancelActive(); scope.cancel(); storeScope.cancel(); super.onCleared() } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ssh/UsbConsole.kt b/androidApp/src/main/kotlin/cz/netkit/app/ssh/UsbConsole.kt new file mode 100644 index 0000000..680a581 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ssh/UsbConsole.kt @@ -0,0 +1,194 @@ +package cz.netkit.app.ssh + +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.hardware.usb.UsbDevice +import android.hardware.usb.UsbManager +import android.net.Uri +import com.hoho.android.usbserial.driver.* +import cz.netkit.shared.ssh.* +import java.io.IOException +import java.io.InputStream +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeout + +data class ConsoleUsbPort(val deviceName: String, val vendor: Int, val product: Int, val number: Int, val label: String) + +/** Immutable explicit PendingIntent. Only its unique request URI is consumed. + * The authoritative result is hasPermission on the originally selected, still-attached device. */ +class ConsoleUsbPermissionReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + intent.dataString?.let { requests[it]?.complete(Unit) } + } + companion object { + private val requests = ConcurrentHashMap>() + internal suspend fun request(context: Context, manager: UsbManager, device: UsbDevice) { + if (manager.hasPermission(device)) return + val uri = Uri.Builder().scheme("netkit-usb").authority("permission").appendPath(UUID.randomUUID().toString()).build() + val signal = CompletableDeferred() + val pending = PendingIntent.getBroadcast(context, 0, + Intent(context, ConsoleUsbPermissionReceiver::class.java).setData(uri), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT) + requests[uri.toString()] = signal + try { + manager.requestPermission(device, pending) + withTimeout(60_000) { signal.await() } + if (!manager.hasPermission(device)) throw SecurityException() + } finally { requests.remove(uri.toString()); pending.cancel() } + } + } +} + +internal class UsbConsole(private val context: Context) { + private val manager get() = context.getSystemService(UsbManager::class.java) + private fun driver(device: UsbDevice): UsbSerialDriver? { + fun matches(ids: Map) = ids[device.vendorId]?.contains(device.productId) == true + return when { + matches(FtdiSerialDriver.getSupportedDevices()) -> FtdiSerialDriver(device) + matches(Cp21xxSerialDriver.getSupportedDevices()) -> Cp21xxSerialDriver(device) + matches(Ch34xSerialDriver.getSupportedDevices()) -> Ch34xSerialDriver(device) + matches(ProlificSerialDriver.getSupportedDevices()) -> ProlificSerialDriver(device) + matches(CdcAcmSerialDriver.getSupportedDevices()) || CdcAcmSerialDriver.probe(device) -> CdcAcmSerialDriver(device) + else -> null + } + } + + private fun key(port: UsbSerialPort) = port.device.let { + ConsoleUsbPort(it.deviceName, it.vendorId, it.productId, port.portNumber, + "%04X:%04X · %s · #%d".format(java.util.Locale.ROOT, it.vendorId, it.productId, it.deviceName.substringAfterLast('/'), port.portNumber + 1)) + } + + fun ports() = manager?.deviceList.orEmpty().values.flatMap { device -> driver(device)?.ports.orEmpty().map(::key) } + .sortedBy { it.label } + + suspend fun open(selected: ConsoleUsbPort, config: SerialSettings): SerialWire { + val usb = manager ?: throw IOException() + val device = usb.deviceList[selected.deviceName] ?: throw IOException() + val port = driver(device)?.ports?.firstOrNull { key(it) == selected } ?: throw IOException() + check(claimed.add(selected)) + try { + ConsoleUsbPermissionReceiver.request(context, usb, device) + if (usb.deviceList[device.deviceName]?.deviceId != device.deviceId) throw IOException() + val handle = usb.openDevice(device) ?: throw IOException() + try { port.open(handle) } catch (e: Exception) { handle.close(); throw e } + } catch (e: Exception) { + claimed.remove(selected) + throw e + } + val wire = SerialWire(port, attached = { usb.deviceList.containsKey(device.deviceName) }, + release = { claimed.remove(selected) }, + packetSize = port.readEndpoint?.maxPacketSize?.takeIf { it > 0 } ?: DEFAULT_USB_PACKET_SIZE) + try { wire.configure(config); return wire } + catch (e: Exception) { wire.close(); throw e } + } + + companion object { + private val claimed = ConcurrentHashMap.newKeySet() + } +} + +/** Full-speed bulk packet; used only if the driver does not expose its read endpoint. */ +internal const val DEFAULT_USB_PACKET_SIZE = 64 +private const val SERIAL_READ_TARGET = 8192 + +/** Largest multiple of [packetSize] not above 8 KiB (at least one packet): the driver's read request size. */ +internal fun alignedSerialReadSize(packetSize: Int): Int { + require(packetSize > 0) + return maxOf(packetSize, SERIAL_READ_TARGET / packetSize * packetSize) +} + +internal class SerialWire( + private val port: UsbSerialPort, private val attached: () -> Boolean, private val release: () -> Unit, + packetSize: Int = DEFAULT_USB_PACKET_SIZE, +) : ConsoleWire { + private val closed = AtomicBoolean() + private var breaking = false + fun configure(config: SerialSettings) { + require(config.valid()) + val stop = when (config.stopBits) { + SerialStopBits.ONE -> UsbSerialPort.STOPBITS_1 + SerialStopBits.ONE_AND_HALF -> UsbSerialPort.STOPBITS_1_5 + SerialStopBits.TWO -> UsbSerialPort.STOPBITS_2 + } + val parity = when (config.parity) { + SerialParity.NONE -> UsbSerialPort.PARITY_NONE + SerialParity.ODD -> UsbSerialPort.PARITY_ODD + SerialParity.EVEN -> UsbSerialPort.PARITY_EVEN + SerialParity.MARK -> UsbSerialPort.PARITY_MARK + SerialParity.SPACE -> UsbSerialPort.PARITY_SPACE + } + port.setParameters(config.baud, config.dataBits, stop, parity) + port.flowControl = if (config.rtsCts) UsbSerialPort.FlowControl.RTS_CTS else UsbSerialPort.FlowControl.NONE + if (UsbSerialPort.ControlLine.DTR in port.supportedControlLines) port.setDTR(true) + } + + /* + * Review P2 (integrace 2.0): the UTF-8 reader of ConsoleConnection asks for odd lengths (e.g. 8191 after a split character, or 1 + * for a single byte), but the drivers need packet-aligned requests: a shorter bulk transfer can lose the rest of a + * packet during continuous output, and FTDI rejects lengths up to its 2-byte status header. The port is therefore + * always read into the full aligned [raw] buffer; bytes beyond the caller's `len` stay in [raw] for the next read. + */ + private val raw = ByteArray(alignedSerialReadSize(packetSize)) + private var pendingStart = 0 + private var pendingEnd = 0 + override val input = object : InputStream() { + override fun read(): Int { + val one = ByteArray(1) + return if (read(one, 0, 1) < 0) -1 else one[0].toInt() and 255 + } + override fun read(b: ByteArray, off: Int, len: Int): Int { + if (len == 0) return 0 + while (!closed.get()) { + if (pendingStart < pendingEnd) { + val count = minOf(len, pendingEnd - pendingStart) + raw.copyInto(b, off, pendingStart, pendingStart + count) + pendingStart += count + return count + } + val n = try { port.read(raw, raw.size, 1000) } + catch (e: IOException) { if (closed.get() || !attached()) return -1 else throw e } + if (n > 0) { pendingStart = 0; pendingEnd = n; continue } + if (!attached()) return -1 + } + return -1 + } + override fun available(): Int = pendingEnd - pendingStart + } + /** + * A pulled cable makes the pending write fail: that is the end of the line, not an error (review P3). + * Close the wire so a blocked read returns EOF at once and the session ends cleanly; any other failure + * while the adapter is still attached stays an error. + */ + override fun write(text: String) { + try { port.write(text.encodeToByteArray(), 5000) } + catch (e: IOException) { + if (closed.get()) return + if (attached()) throw e + close() + } + } + override suspend fun sendBreak() { + synchronized(this) { + check(!closed.get()) + port.setBreak(true) + breaking = true + } + try { delay(250) } finally { clearBreak() } + } + @Synchronized private fun clearBreak() { + if (breaking) { + port.setBreak(false) + breaking = false + } + } + override fun close() { + if (!closed.compareAndSet(false, true)) return + try { try { clearBreak() } finally { port.close() } } finally { release() } + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/tile/SignalTileService.kt b/androidApp/src/main/kotlin/cz/netkit/app/tile/SignalTileService.kt new file mode 100644 index 0000000..75298a1 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/tile/SignalTileService.kt @@ -0,0 +1,48 @@ +package cz.netkit.app.tile + +import android.annotation.SuppressLint +import android.app.PendingIntent +import android.content.Intent +import android.os.Build +import android.service.quicksettings.Tile +import android.service.quicksettings.TileService +import cz.netkit.app.nav.AppShortcuts +import cz.netkit.shared.nav.AppTarget + +/** + * Quick Settings tile "Signál Wi-Fi" (zadání 36 §2.4): a tap only opens Přehled. The tile shows no + * data (no SSID, RSSI or IP): it is visible on the lock screen and a tile has no foreground location + * access, so it could not read the SSID reliably anyway (background location is not allowed). + * + * Exported only to the system UI: the manifest requires BIND_QUICK_SETTINGS_TILE. + */ +class SignalTileService : TileService() { + override fun onStartListening() { + super.onStartListening() + qsTile?.apply { + state = Tile.STATE_INACTIVE // an action tile, not a toggle + updateTile() + } + } + + override fun onClick() { + super.onClick() + // On the lock screen the user unlocks first; the app is never shown over the keyguard. + if (isLocked) unlockAndRun(::openOverview) else openOverview() + } + + @SuppressLint("StartActivityAndCollapseDeprecated") // the Intent variant runs only below API 34 + private fun openOverview() { + val intent = AppShortcuts.openIntent(this, AppTarget.Signal).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + // API 34+: only the PendingIntent variant is allowed for targetSdk 34+. + startActivityAndCollapse(PendingIntent.getActivity(this, REQUEST_OVERVIEW, intent, + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)) + } else { + @Suppress("DEPRECATION") + startActivityAndCollapse(intent) + } + } + + private companion object { const val REQUEST_OVERVIEW = 1 } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ui/Components.kt b/androidApp/src/main/kotlin/cz/netkit/app/ui/Components.kt index 077eefa..ead1d95 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ui/Components.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ui/Components.kt @@ -51,10 +51,7 @@ import androidx.compose.ui.draw.rotate import androidx.compose.ui.draw.shadow import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size -import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.Path -import androidx.compose.ui.graphics.PathEffect import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.graphics.drawscope.Stroke @@ -69,6 +66,10 @@ import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.testTag +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription @@ -163,7 +164,7 @@ private val LightShadowInk = Color(0xFF0C2D41) Layout( content = { Column(verticalArrangement = Arrangement.spacedBy(titleGap)) { - Text(title, style = style, color = colors.text) + Text(title, Modifier.semantics { heading() }, style = style, color = colors.text) subtitle?.invoke() } if (trailing != null) Row(verticalAlignment = Alignment.CenterVertically, @@ -220,15 +221,48 @@ internal fun headerWords(title: String): List = title.split(' ', '\n', ' ) { Column(Modifier.padding(padding), verticalArrangement = Arrangement.spacedBy(Spacing.cardGap), content = content) } } -/** Card with a `panelTitle` heading, an optional muted [meta] text and trailing content. */ -@Composable fun SectionCard(title: String? = null, trailing: (@Composable RowScope.() -> Unit)? = null, meta: String? = null, +/** + * One slice of a [Panel] whose rows are separate lazy list items: [first] rounds the top corners + * and adds the top padding, [last] the bottom ones. Consecutive slices without spacing between + * them look like one card (same surface, radius and light-theme shadow). + */ +@Composable fun PanelSegment(first: Boolean, last: Boolean, modifier: Modifier = Modifier, padding: Dp = Spacing.card, content: @Composable ColumnScope.() -> Unit) { val colors = NetKitTheme.colors + val radius = 16.dp + val shape = androidx.compose.foundation.shape.RoundedCornerShape( + topStart = if (first) radius else 0.dp, topEnd = if (first) radius else 0.dp, + bottomStart = if (last) radius else 0.dp, bottomEnd = if (last) radius else 0.dp) + val surface = colors.surface + Surface( + modifier = modifier.fillMaxWidth() + .then(if (colors.isDark) Modifier else Modifier.shadow(1.dp, shape, clip = false, ambientColor = LightShadowInk, spotColor = LightShadowInk)) + // The shadow of a flat top edge would draw a line across the seam; paint it over (inside this layer, above its shadow). + .then(if (first || colors.isDark) Modifier else Modifier.drawBehind { + val seam = 2.dp.toPx() + drawRect(surface, topLeft = androidx.compose.ui.geometry.Offset(0f, -seam), size = androidx.compose.ui.geometry.Size(size.width, seam + 1f)) + }), + shape = shape, color = colors.surface, contentColor = colors.text, + ) { + Column(Modifier.padding(start = padding, end = padding, top = if (first) padding else 0.dp, bottom = if (last) padding else 0.dp), + content = content) + } +} + +/** + * Card with a `panelTitle` heading, an optional muted [meta] text and trailing content. + * [metaModifier] styles only the meta text (zadání 49, TalkBack live region), not the card, hence its name and position. + */ +@android.annotation.SuppressLint("ModifierParameter") +@Composable fun SectionCard(title: String? = null, trailing: (@Composable RowScope.() -> Unit)? = null, meta: String? = null, + metaModifier: Modifier = Modifier, heading: Boolean = true, content: @Composable ColumnScope.() -> Unit) { + val colors = NetKitTheme.colors Panel { if (title != null || trailing != null || meta != null) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { - Text(title.orEmpty(), Modifier.weight(1f), style = NetKitType.panelTitle, color = colors.text) - meta?.let { Text(it, style = NetKitType.label, color = colors.muted, maxLines = 1) } + if (!title.isNullOrBlank()) Text(title, Modifier.weight(1f).then(if (heading) Modifier.semantics { heading() } else Modifier), style = NetKitType.panelTitle, color = colors.text) + else Spacer(Modifier.weight(1f)) + meta?.let { Text(it, metaModifier, style = NetKitType.label, color = colors.muted, maxLines = 1) } trailing?.invoke(this) } content() @@ -258,7 +292,7 @@ internal fun headerWords(title: String): List = title.split(' ', '\n', ' Row(Modifier.fillMaxWidth().clip(NetKitShape.nested).background(tone.fill).padding(horizontal = 14.dp, vertical = Spacing.medium), horizontalArrangement = Arrangement.spacedBy(10.dp)) { Box(Modifier.padding(top = 6.dp).size(7.dp).clip(CircleShape).background(tone.foreground)) - Text(text, Modifier.weight(1f), style = NetKitType.body, color = NetKitTheme.colors.text) + Text(text, Modifier.weight(1f).semantics { liveRegion = LiveRegionMode.Polite }, style = NetKitType.body, color = NetKitTheme.colors.text) } } @@ -303,10 +337,6 @@ internal fun headerWords(title: String): List = title.split(' ', '\n', ' } } -/** Pre-M3 name of [Tag]; same look. */ -@Composable fun StatusChip(text: String, tone: Tone = Tone.NEUTRAL, dot: Boolean = false, modifier: Modifier = Modifier) = - Tag(text, tone, dot, modifier) - /** Accent pill "živě · 1 s" with a pulsing dot (stops when paused or with animations off). */ @Composable fun LiveBadge(text: String, modifier: Modifier = Modifier) { val colors = NetKitTheme.colors @@ -317,17 +347,6 @@ internal fun headerWords(title: String): List = title.split(' ', '\n', ' } } -/** Label + value (`value`, tabular) + optional muted unit. [filled] draws the `surface2` tile. */ -@Composable fun MetricTile(label: String, value: String, unit: String? = null, tone: Tone = Tone.NEUTRAL, modifier: Modifier = Modifier, - filled: Boolean = false) { - val colors = NetKitTheme.colors - Column(modifier.then(if (filled) Modifier.clip(NetKitShape.nested).background(colors.surface2).padding(horizontal = 12.dp, vertical = 10.dp) else Modifier), - verticalArrangement = Arrangement.spacedBy(2.dp)) { - Eyebrow(label) - ValueWithUnit(value, unit, NetKitType.value, if (tone == Tone.NEUTRAL) colors.text else colors.tone(tone).foreground) - } -} - /** * Value and unit as one text. The unit is glued to the end of the value by a narrow no-break * space and never broken inside ("Mb/s"); a long value (IPv6) may still wrap, taking the unit @@ -442,7 +461,7 @@ data class KeyValue(val label: String, val value: String, val tone: Tone = Tone. /** * Segmented control: `surface2` track (radius 12, padding 4) with a sliding `surface` indicator * (radius 9) that animates to the measured bounds of the selected item with the `base` token. - * Items are at least 38 dp high and share the width equally; [testTags] go on the items. + * Items are at least 48 dp high and share the width equally; [testTags] go on the items. */ @Composable fun SegmentedTabs(options: List, selected: Int, onSelect: (Int) -> Unit, modifier: Modifier = Modifier, testTags: List? = null) { @@ -479,7 +498,7 @@ data class KeyValue(val label: String, val value: String, val tone: Tone = Tone. options.forEachIndexed { index, label -> val on = index == selected val ink by animateColorAsState(if (on) colors.text else colors.muted, rememberNetKitTween(MotionToken.FAST), label = "segment-ink") - Box(Modifier.weight(1f).heightIn(min = 38.dp) + Box(Modifier.weight(1f).heightIn(min = 48.dp) .onPlaced { val b = it.positionInParent().x to it.size.width.toFloat(); if (bounds[index] != b) bounds[index] = b } .then(testTags?.getOrNull(index)?.let { Modifier.testTag(it) } ?: Modifier) .clip(thumbShape) @@ -586,7 +605,9 @@ private val PickerPadding = 11.dp /** One tile of [StatTiles]; [weight] is the share of the row width (Signal: 1 / 1.45 / 1.45). */ @Immutable data class StatTile(val label: String, val value: String, val unit: String? = null, val weight: Float = 1f, - val monospace: Boolean = false, val tone: Tone = Tone.NEUTRAL) + val monospace: Boolean = false, val tone: Tone = Tone.NEUTRAL, + /** Zadání 47: a long press copies this value (null = no copy action). */ + val copyValue: String? = null, val testTag: String? = null) /** * Value tiles on `surface2`, gap 8, widths by [StatTile.weight]. A value is never ellipsized: @@ -597,7 +618,9 @@ data class StatTile(val label: String, val value: String, val unit: String? = nu Layout( content = { tiles.forEach { tile -> - Column(Modifier.clip(NetKitShape.nested).background(colors.surface2).padding(horizontal = 12.dp, vertical = 10.dp), + Column(Modifier.clip(NetKitShape.nested).copyOnLongPress(tile.copyValue) + .then(if (tile.testTag != null) Modifier.testTag(tile.testTag) else Modifier) + .background(colors.surface2).padding(horizontal = 12.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) { Eyebrow(tile.label) ValueWithUnit(tile.value, tile.unit, if (tile.monospace) NetKitType.addressFor(NetKitType.value).copy(fontSize = 14.5.sp) @@ -793,64 +816,6 @@ internal fun gaugeFraction(dbm: Double?, range: ClosedFloatingPointRange) } } -data class ChartSeries(val values: List, val color: Color) - -/** - * Live line chart with area fill and a faint grid. Values are clamped to [range]; `null` - * breaks the line (lost sample). Y ticks are labelled on the right like WiFiman's charts. - * All series share the x step: [capacity] slots, newest sample at the right edge. - */ -@Composable fun LiveLineChart( - series: List, range: ClosedFloatingPointRange, ticks: List, unit: String, - capacity: Int, description: String, modifier: Modifier = Modifier, height: Dp = 180.dp, -) { - val colors = NetKitTheme.colors - val span = (range.endInclusive - range.start).takeIf { it > 0f } ?: 1f - Column(modifier.fillMaxWidth().clearAndSetSemantics { contentDescription = description }) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) { - Canvas(Modifier.weight(1f).height(height)) { - fun y(v: Float) = size.height - ((v.coerceIn(range.start, range.endInclusive) - range.start) / span) * size.height - ticks.forEach { t -> drawLine(colors.borderSoft, Offset(0f, y(t)), Offset(size.width, y(t)), 1.dp.toPx()) } - for (i in 1..3) { - val x = size.width * i / 4f - drawLine(colors.borderSoft, Offset(x, 0f), Offset(x, size.height), 1.dp.toPx(), pathEffect = PathEffect.dashPathEffect(floatArrayOf(4f, 6f))) - } - val step = size.width / (capacity - 1).coerceAtLeast(1) - series.forEach { s -> - val offset = capacity - s.values.size - var line = Path(); var area = Path(); var open = false; var startX = 0f; var lastX = 0f - fun flush() { - if (!open) return - area.lineTo(lastX, size.height); area.lineTo(startX, size.height); area.close() - drawPath(area, Brush.verticalGradient(listOf(s.color.copy(alpha = .26f), s.color.copy(alpha = 0f)))) - drawPath(line, s.color, style = Stroke(2.dp.toPx(), cap = StrokeCap.Round)) - line = Path(); area = Path(); open = false - } - s.values.forEachIndexed { i, v -> - val x = (offset + i) * step - if (v == null) { flush(); return@forEachIndexed } - if (!open) { line.moveTo(x, y(v)); area.moveTo(x, y(v)); startX = x; open = true } - else { line.lineTo(x, y(v)); area.lineTo(x, y(v)) } - lastX = x - } - flush() - s.values.lastOrNull()?.let { v -> drawCircle(s.color, 3.5.dp.toPx(), Offset((capacity - 1) * step, y(v))) } - } - } - Box(Modifier.width(34.dp).height(height)) { - ticks.forEach { t -> - val fraction = 1f - (t - range.start) / span - Text(formatTick(t), Modifier.align(Alignment.TopEnd).padding(top = (height * fraction - 8.dp).coerceIn(0.dp, height - 16.dp)), - style = NetKitType.valueSmall, color = colors.dim) - } - } - } - // Unit sits under the tick column so it never collides with the lowest tick label. - Text(unit, Modifier.align(Alignment.End), style = NetKitType.valueSmall, color = colors.dim) - } -} -private fun formatTick(value: Float) = if (value == value.toInt().toFloat()) value.toInt().toString() else "%.1f".format(value) - /** Thin proportional bar (hop latency, utilization); the fill animates with the `base` token. */ @Composable fun ValueBar(fraction: Float, tone: Tone = Tone.ACCENT, modifier: Modifier = Modifier) { val colors = NetKitTheme.colors diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ui/KeepScreenOn.kt b/androidApp/src/main/kotlin/cz/netkit/app/ui/KeepScreenOn.kt new file mode 100644 index 0000000..fef7f44 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ui/KeepScreenOn.kt @@ -0,0 +1,36 @@ +package cz.netkit.app.ui + +import android.view.View +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.compositionLocalOf +import androidx.compose.ui.platform.LocalView +import cz.netkit.app.R +import cz.netkit.shared.settings.keepScreenOnActive +import cz.netkit.shared.settings.screenOnHolders + +/** The user's "keep the display on during measurements" setting (zadání 46 §3); provided by MainActivity. */ +val LocalKeepScreenOnSetting = compositionLocalOf { true } + +/** + * Holds the display on (`View.keepScreenOn` of the composition's view, i.e. the activity window's + * FLAG_KEEP_SCREEN_ON) while [running] is true, the setting is on and this composable is shown. + * Leaving the screen, the end of the run or switching the setting off releases it. No permission: + * it is a window flag, not a wake lock, so it only works while NetKit is in the foreground. + * Several holders on one view are counted, so one finishing does not clear another (zadání 46 §4). + */ +@Composable +fun KeepScreenOn(running: Boolean) { + if (!keepScreenOnActive(LocalKeepScreenOnSetting.current, running)) return + val view = LocalView.current + DisposableEffect(view) { + holdScreenOn(view, acquire = true) + onDispose { holdScreenOn(view, acquire = false) } + } +} + +private fun holdScreenOn(view: View, acquire: Boolean) { + val holders = screenOnHolders(view.getTag(R.id.keep_screen_on_holders) as? Int ?: 0, acquire) + view.setTag(R.id.keep_screen_on_holders, holders) + view.keepScreenOn = holders > 0 +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ui/NetKitIcons.kt b/androidApp/src/main/kotlin/cz/netkit/app/ui/NetKitIcons.kt index 93ae00d..fa54848 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ui/NetKitIcons.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ui/NetKitIcons.kt @@ -49,6 +49,9 @@ object NetKitIcons { val More = icon("more", "M12 5.2a1 1 0 1 0 0 2a1 1 0 1 0 0-2z", "M12 11a1 1 0 1 0 0 2a1 1 0 1 0 0-2z", "M12 16.8a1 1 0 1 0 0 2a1 1 0 1 0 0-2z", filled = setOf(0, 1, 2)) val Info = icon("info", "M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18z", "M12 11v5", "M12 7.5h.01") + /** Settings (zadání 46): two sliders. */ + val Settings = icon("settings", "M4 7h9", "M17 7h3", "M15 5a2 2 0 1 0 0 4a2 2 0 1 0 0-4z", + "M4 17h3", "M11 17h9", "M9 15a2 2 0 1 0 0 4a2 2 0 1 0 0-4z") val Add = icon("add", "M12 5v14", "M5 12h14") /** Same glyph as [Add]; name used by the M3 design (zoom "+", add device). */ val Plus = Add @@ -62,4 +65,15 @@ object NetKitIcons { val Shield = icon("shield", "M12 3l7 3v5c0 4.5-3 8.3-7 10c-4-1.7-7-5.5-7-10V6z", "M9 12l2 2l4-4") /** Licence texts (About, open-source licences). */ val Document = icon("document", "M6 3h8l4 4v14H6z", "M14 3v4h4", "M9 12h6", "M9 16h6") + /** SFTP browser (zadání 42): directory, file, symbolic link, upload, parent directory. */ + val Folder = icon("folder", "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z") + val File = icon("file", "M6 3h8l4 4v14H6z", "M14 3v4h4") + val Link = icon("link", "M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1", "M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1") + val Upload = icon("upload", "M12 15V3", "M8 7l4-4 4 4", "M4 19h16") + val FolderUp = icon("folder-up", "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z", "M12 16v-6", "M9.5 12.5L12 10l2.5 2.5") + /** Zadání 48: target history (recent targets) at a tool's input. */ + val History = icon("history", "M4 12a8 8 0 1 0 2.3-5.7", "M4 4v4h4", "M12 8v4l3 2") + /** Favourite target: outline = not starred, [StarFilled] = starred. */ + val Star = icon("star", "M12 3.5l2.6 5.3l5.9 0.9l-4.25 4.15l1 5.85L12 16.9l-5.25 2.8l1-5.85L3.5 9.7l5.9-0.9z") + val StarFilled = icon("star-filled", "M12 3.5l2.6 5.3l5.9 0.9l-4.25 4.15l1 5.85L12 16.9l-5.25 2.8l1-5.85L3.5 9.7l5.9-0.9z", filled = setOf(0)) } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ui/RunSummary.kt b/androidApp/src/main/kotlin/cz/netkit/app/ui/RunSummary.kt new file mode 100644 index 0000000..28a3a5d --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ui/RunSummary.kt @@ -0,0 +1,90 @@ +package cz.netkit.app.ui + +import androidx.annotation.StringRes +import androidx.compose.foundation.lazy.LazyListState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.liveRegion +import cz.netkit.app.R +import cz.netkit.app.lan.LanDevicesState +import cz.netkit.app.lan.LanTool +import cz.netkit.app.lan.LanUiState +import cz.netkit.app.speed.SpeedPhase +import cz.netkit.app.speed.SpeedUiState +import cz.netkit.shared.lan.LanRunStatus +import cz.netkit.shared.lan.pingStatistics +import cz.netkit.shared.speed.SpeedEngine + +/** Only the status label belongs in this node. Keep changing counters and sibling actions separate. */ +internal fun Modifier.spokenStatus(description: String) = clearAndSetSemantics { + liveRegion = LiveRegionMode.Polite + contentDescription = description +} + +/** + * A lazy list disposes the status node when the user reads results farther down. + * Announce that transition once from the foreground view; opening an old result stays quiet. + */ +@Composable +internal fun OffscreenRunSummary(running: Boolean, summary: String, list: LazyListState, statusKey: String) { + val view = LocalView.current + var wasRunning by remember { mutableStateOf(false) } + LaunchedEffect(running, summary) { + if (wasRunning && !running && summary.isNotEmpty() && view.hasWindowFocus() && + list.layoutInfo.visibleItemsInfo.none { it.key == statusKey }) { + view.announceForAccessibility(summary) + } + wasRunning = running + } +} + +internal class ResultPhrase(@StringRes val resource: Int, vararg val arguments: Any) + +@Composable +internal fun List.spoken(): String = map { stringResource(it.resource, *it.arguments) }.joinToString(" ") + +internal fun pingSummary(sent: Int, received: Int, samples: List, + @StringRes completion: Int = R.string.a11y_ping_done): List = buildList { + add(ResultPhrase(completion, received, sent)) + pingStatistics(samples).average?.let { average -> + add(if (sent > samples.size) ResultPhrase(R.string.a11y_ping_window_average, samples.size, average) + else ResultPhrase(R.string.a11y_ping_average, average)) + } +} + +internal fun lanSummary(state: LanUiState): List { + if (state.runStatus != LanRunStatus.FINISHED || state.mtuSweep) return emptyList() + return when (state.tool) { + LanTool.PING -> pingSummary(state.sent, state.received, state.samples) + LanTool.TCP_PING -> pingSummary(state.sent, state.received, state.samples, R.string.a11y_tcp_ping_done) + LanTool.TRACE -> listOf(ResultPhrase(R.string.a11y_trace_done, state.results.size, state.results.count { it.address.isNotEmpty() })) + LanTool.PORTS -> listOf(ResultPhrase(R.string.a11y_ports_done, state.probeCounts.open, state.progress)) + LanTool.DISCOVERY -> listOf(ResultPhrase(R.string.a11y_scan_done, state.results.size)) + LanTool.DNS -> listOf(ResultPhrase(R.string.a11y_dns_done, state.results.size)) + // A DNS records row can also be a header, an RCODE or a per-route failure. + LanTool.RECORDS -> listOf(ResultPhrase(R.string.a11y_records_done, state.results.size)) + else -> emptyList() + } +} + +internal fun deviceScanSummary(state: LanDevicesState): List = + if (state.scan.status == LanRunStatus.FINISHED) + listOf(ResultPhrase(R.string.a11y_scan_done, state.devices.size)) + else emptyList() + +internal fun speedSummary(state: SpeedUiState): List = buildList { + if (state.phase != SpeedPhase.DONE) return@buildList + add(ResultPhrase(if (state.engine == SpeedEngine.IPERF3) R.string.a11y_iperf_done else R.string.a11y_speed_done)) + state.download?.let { add(ResultPhrase(R.string.a11y_speed_download, it.mbps)) } + state.upload?.let { add(ResultPhrase(R.string.a11y_speed_upload, it.mbps)) } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ui/ShareActions.kt b/androidApp/src/main/kotlin/cz/netkit/app/ui/ShareActions.kt new file mode 100644 index 0000000..f836658 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/ui/ShareActions.kt @@ -0,0 +1,95 @@ +package cz.netkit.app.ui + +import android.content.ActivityNotFoundException +import android.content.ClipData +import android.content.ClipDescription +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.PersistableBundle +import android.widget.Toast +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.ui.Modifier +import androidx.compose.ui.hapticfeedback.HapticFeedbackType +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalHapticFeedback +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.onLongClick +import androidx.compose.ui.semantics.semantics +import cz.netkit.app.R +import cz.netkit.shared.lan.lanTextFitsIpc + +/* + * Zadání 47: copy, share and long-press helpers. Everything here runs only on a user action; the + * app never sends a copied, shared or saved value anywhere by itself (docs/public/evidence toků). + */ + +/** + * Puts [text] on the clipboard. [sensitive] marks the clip `EXTRA_IS_SENSITIVE` on API 33+, so + * the system preview and keyboard suggestions hide it (public IP, BSSID, a report with them). + * False when the text is over the Binder-safe size or the clipboard refused it. + */ +fun copyPlainText(context: Context, label: String, text: String, sensitive: Boolean): Boolean { + if (!lanTextFitsIpc(text)) return false + return try { + val clip = ClipData.newPlainText(label, text) + if (sensitive && Build.VERSION.SDK_INT >= 33) { + clip.description.extras = PersistableBundle().apply { putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true) } + } + context.getSystemService(ClipboardManager::class.java).setPrimaryClip(clip) + true + } catch (_: RuntimeException) { false } +} + +/** Opens the system share sheet with [text] as `text/plain`; false when it is too large or no target exists. */ +fun shareText(context: Context, chooserTitle: String, text: String, subject: String? = null): Boolean { + if (!lanTextFitsIpc(text)) return false + val send = Intent(Intent.ACTION_SEND).apply { + type = "text/plain" + putExtra(Intent.EXTRA_TEXT, text) + subject?.let { putExtra(Intent.EXTRA_SUBJECT, it) } + } + return try { + context.startActivity(Intent.createChooser(send, chooserTitle).apply { + if (context !is android.app.Activity) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + }) + true + } catch (_: ActivityNotFoundException) { false } catch (_: SecurityException) { false } +} + +/** + * Feedback after a copy like the subnet calculator (zadání 35): a toast on failure, and on success + * only below API 33 (from 33 on the system shows its own clipboard confirmation). + */ +fun copyFeedback(context: Context, copied: Boolean) { + if (!copied || Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) { + Toast.makeText(context, if (copied) R.string.lan_value_copied else R.string.lan_copy_failed, Toast.LENGTH_SHORT).show() + } +} + +/** + * Long press copies [value] (null = nothing to copy, modifier is a no-op) with haptic and toast + * feedback. No click handler is added: a tap keeps doing what the element did before. The long-press + * action is exposed to accessibility services as "Kopírovat hodnotu". + */ +@Composable +fun Modifier.copyOnLongPress(value: String?, sensitive: Boolean = false): Modifier { + if (value.isNullOrEmpty()) return this + val context = LocalContext.current + val haptics = LocalHapticFeedback.current + val label = stringResource(R.string.lan_copy_value) + val clipLabel = stringResource(R.string.app_name) + val current by rememberUpdatedState(value) + val copy = { + haptics.performHapticFeedback(HapticFeedbackType.LongPress) + copyFeedback(context, copyPlainText(context, clipLabel, current, sensitive)) + } + return this + .semantics { onLongClick(label) { copy(); true } } + .pointerInput(Unit) { detectTapGestures(onLongPress = { copy() }) } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt index abd2a6c..d183382 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt @@ -41,7 +41,6 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import cz.netkit.app.BuildConfig import cz.netkit.app.R import cz.netkit.app.ssh.netKitSwitchColors -import cz.netkit.app.ui.InfoNote import cz.netkit.app.ui.ListRow import cz.netkit.app.ui.NetKitIcons import cz.netkit.app.ui.NeutralButton @@ -65,17 +64,18 @@ import cz.netkit.shared.update.localizedWebUrl import cz.netkit.shared.update.privacyPolicyUrl /** - * About (zadání 21, D14, D22): name and version from [PackageManager], update switch and - * "Zkontrolovat teď", project links (web, sources, privacy policy, open-source licences, app - * licence), the scanning notice and what the check sends. A subscreen of Přehled opened from its - * header menu; the number of tabs does not change. [onOpenLicenses] opens [OssLicensesScreen]. + * About (zadání 21, D14, D22): name and version from [PackageManager], project links (web, + * sources, privacy policy, open-source licences, app licence) and the scanning notice. The update + * switch and "Zkontrolovat teď" moved to Settings (zadání 46 §3); a row here opens it + * ([onOpenSettings]). A subscreen of Přehled opened from its header menu; the number of tabs does + * not change. [onOpenLicenses] opens [OssLicensesScreen]. */ @Composable -fun AboutScreen(update: UpdateViewModel, onBack: () -> Unit, onOpenLicenses: () -> Unit, modifier: Modifier = Modifier) { +fun AboutScreen(update: UpdateViewModel, onBack: () -> Unit, onOpenLicenses: () -> Unit, onOpenSettings: () -> Unit, + modifier: Modifier = Modifier) { val state by update.state.collectAsStateWithLifecycle() val context = LocalContext.current val version = remember(context) { packageVersion(context) } - val note = updatesNote(state) BackHandler(onBack = onBack) LazyColumn( modifier.fillMaxSize().testTag("about_screen"), @@ -94,14 +94,15 @@ fun AboutScreen(update: UpdateViewModel, onBack: () -> Unit, onOpenLicenses: () } } item(key = "updates") { - UpdatesCard(state, onToggle = update::setEnabled, onCheck = update::checkNow, - onOpen = { url -> openLink(context, url) }) + Panel { + ListRow(stringResource(R.string.about_updates_title), stringResource(R.string.about_updates_in_settings), NetKitIcons.Settings, + onClick = onOpenSettings, modifier = Modifier.testTag("about_open_settings"), subtitleMaxLines = 2) + if (state.available) Text(statusText(state), Modifier.testTag("about_update_status"), style = NetKitType.label, + color = NetKitTheme.colors.muted) + } } item(key = "project") { ProjectCard(onOpen = { url -> openLink(context, url) }, onOpenLicenses = onOpenLicenses) } item(key = "safety") { StatusBanner(stringResource(R.string.lan_safety), StatusKind.WARNING) } - note?.let { detail -> - item(key = "note") { InfoNote(stringResource(R.string.about_updates_note_summary), detail) } - } } } @@ -121,8 +122,9 @@ internal fun SubscreenHeader(title: String, backTag: String, onBack: () -> Unit) } } +/** Update switch, status and "Zkontrolovat teď" (D14); shown in Settings since zadání 46. */ @Composable -private fun UpdatesCard(state: UpdateUiState, onToggle: (Boolean) -> Unit, onCheck: () -> Unit, onOpen: (String) -> Unit) { +internal fun UpdatesCard(state: UpdateUiState, onToggle: (Boolean) -> Unit, onCheck: () -> Unit, onOpen: (String) -> Unit) { val colors = NetKitTheme.colors val language = LocalConfiguration.current.locales[0].language SectionCard(stringResource(R.string.about_updates_title)) { @@ -184,7 +186,7 @@ private fun lastCheckText(lastCheckMs: Long?, source: UpdateSource?): String { /** What the check sends, by the sources this build has; `null` when it has none. */ @Composable -private fun updatesNote(state: UpdateUiState): String? { +internal fun updatesNote(state: UpdateUiState): String? { val web = state.webHost return when { web != null && state.githubSource -> stringResource(R.string.about_updates_note_detail, web) diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ui/chart/FullscreenChart.kt b/androidApp/src/main/kotlin/cz/netkit/app/ui/chart/FullscreenChart.kt index 30431d1..3ed7387 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ui/chart/FullscreenChart.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ui/chart/FullscreenChart.kt @@ -25,6 +25,7 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.sizeIn import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.rememberScrollState @@ -154,7 +155,7 @@ fun FullscreenChart( Column(Modifier.fillMaxSize().padding(12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { - Box(Modifier.size(40.dp).testTag("chart_close").clip(CircleShape).background(colors.surface3) + Box(Modifier.size(48.dp).testTag("chart_close").clip(CircleShape).background(colors.surface3) .clickable(role = Role.Button, onClickLabel = closeLabel, onClick = onClose) .semantics { contentDescription = closeLabel }, contentAlignment = Alignment.Center) { Text("×", style = NetKitType.value, color = colors.text) @@ -276,7 +277,7 @@ fun FullscreenChart( } } } - Text(stringResource(R.string.chart_events), style = NetKitType.valueSmall, color = colors.dim) + Text(stringResource(R.string.chart_events), style = NetKitType.valueSmall, color = colors.muted) val windowEvents = events.filter { it.index in visible }.sortedByDescending { it.index } if (windowEvents.isEmpty()) Text(stringResource(R.string.chart_no_events), style = NetKitType.valueSmall, color = colors.muted) @@ -290,7 +291,7 @@ fun FullscreenChart( } } Text(relativeClock(elapsedSeconds(total - 1 - event.index, sampleIntervalMs)), - style = NetKitType.valueSmall, color = colors.dim) + style = NetKitType.valueSmall, color = colors.muted) } } Surface(shape = RoundedCornerShape(12.dp), color = colors.surface) { @@ -409,7 +410,7 @@ private fun ChartPill(label: String, selected: Boolean, tag: String, onClick: () Surface(shape = CircleShape, color = if (selected) colors.surface3 else colors.surface, border = BorderStroke(1.dp, if (selected) colors.accent else colors.borderSoft)) { Box(Modifier.testTag(tag).clip(CircleShape).selectable(selected, role = Role.Tab, onClick = onClick) - .heightIn(min = 36.dp).padding(horizontal = 12.dp, vertical = 6.dp), contentAlignment = Alignment.Center) { + .sizeIn(minWidth = 48.dp, minHeight = 48.dp).padding(horizontal = 12.dp, vertical = 6.dp), contentAlignment = Alignment.Center) { Text(label, style = NetKitType.valueSmall, color = if (selected) colors.accent else colors.muted) } } @@ -418,7 +419,7 @@ private fun ChartPill(label: String, selected: Boolean, tag: String, onClick: () @Composable private fun ChartZoomButton(symbol: String, label: String, enabled: Boolean, tag: String? = null, onClick: () -> Unit) { val colors = NetKitTheme.colors - Box(Modifier.size(36.dp).then(tag?.let { Modifier.testTag(it) } ?: Modifier).clip(CircleShape).background(colors.surface3) + Box(Modifier.size(48.dp).then(tag?.let { Modifier.testTag(it) } ?: Modifier).clip(CircleShape).background(colors.surface3) .clickable(enabled = enabled, role = Role.Button, onClickLabel = label, onClick = onClick) .semantics { contentDescription = label }, contentAlignment = Alignment.Center) { Text(symbol, style = NetKitType.value, color = if (enabled) colors.text else colors.dim) diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ui/chart/TimeSeriesChart.kt b/androidApp/src/main/kotlin/cz/netkit/app/ui/chart/TimeSeriesChart.kt index 5877986..18cad42 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ui/chart/TimeSeriesChart.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ui/chart/TimeSeriesChart.kt @@ -23,6 +23,7 @@ import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.text.SpanStyle @@ -104,6 +105,28 @@ private class LabelLayouts(private val measurer: TextMeasurer) { private companion object { const val LIMIT = 128 } } +internal data class SeriesReadings(val min: Float, val max: Float, val last: Float?) + +internal fun seriesReadings(values: List, visible: IntRange): SeriesReadings? = + windowStats(values, visible)?.let { stats -> + SeriesReadings(stats.min, stats.max, values.getOrNull(visible.last)?.takeIf { it.isFinite() }) + } + +/** The rightmost slot can be missing even when earlier samples in the window were valid. */ +@Composable +internal fun seriesDescription(label: String, values: List, visible: IntRange, unit: String): String { + val stats = remember(values, visible) { seriesReadings(values, visible) } + ?: return stringResource(R.string.a11y_no_samples, label) + val locale = LocalConfiguration.current.locales[0] + val format = remember(locale) { NumberFormat.getNumberInstance(locale).apply { + isGroupingUsed = false + maximumFractionDigits = 2 + } } + fun reading(value: Float) = "${format.format(value)} $unit".trimEnd() + return stringResource(R.string.a11y_series, label, reading(stats.min), reading(stats.max), + stats.last?.let(::reading) ?: stringResource(R.string.a11y_missing)) +} + @Composable fun TimeSeriesChart( lines: List, capacity: Int, sampleIntervalMs: Long, @@ -173,7 +196,10 @@ fun TimeSeriesChart( } } - Box(modifier.fillMaxWidth().height(height).clearAndSetSemantics { contentDescription = description } + val summaries = lines.map { seriesDescription(it.label, it.values, visible, unitLabel) } + val chartText = if (summaries.isEmpty()) stringResource(R.string.a11y_no_samples, description) + else (listOf(description) + summaries).joinToString("\n") + Box(modifier.fillMaxWidth().height(height).clearAndSetSemantics { contentDescription = chartText } .drawWithCache { val left = chartLeftInset(large, fontScale).toPx().coerceAtMost(size.width * 0.4f) val right = (size.width - ChartRightInset.toPx()).coerceAtLeast(left + 1f) @@ -183,7 +209,7 @@ fun TimeSeriesChart( fun x(index: Int): Float = if (slots == 1) right else left + (index - start).toFloat() / (slots - 1) * width fun y(value: Float): Float = bottom - ((value.coerceIn(low, high) - low) / (high - low)) * (bottom - top) val tickLabels = axisTicks.filter { it.isFinite() && it in low..high }.map { tick -> - y(tick) to labelLayouts.get(numberFormat.format(tick), textStyle.copy(color = colors.dim), + y(tick) to labelLayouts.get(numberFormat.format(tick), textStyle.copy(color = colors.muted), maxWidth = (left - 6.dp.toPx()).roundToInt().coerceAtLeast(1)) } val durationSeconds = (slots - 1).toDouble() * sampleIntervalMs / 1000.0 @@ -213,7 +239,7 @@ fun TimeSeriesChart( else -> resources.getString(R.string.chart_seconds_ago, seconds) } val xx = right - ((seconds - rightSeconds) / durationSeconds.coerceAtLeast(0.001)).toFloat() * width - xx to labelLayouts.get(label, textStyle.copy(color = colors.dim)) + xx to labelLayouts.get(label, textStyle.copy(color = colors.muted)) }.distinctBy { it.first } val eventLabels = events.filter { it.index in visible }.map { event -> event to labelLayouts.get(resources.getString(event.kind.labelResource()), diff --git a/androidApp/src/main/kotlin/cz/netkit/app/ui/theme/Theme.kt b/androidApp/src/main/kotlin/cz/netkit/app/ui/theme/Theme.kt index cba0b0e..4ced738 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/ui/theme/Theme.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/ui/theme/Theme.kt @@ -215,6 +215,9 @@ private fun NetKitColors.toMaterial() = if (isDark) darkColorScheme( surfaceTint = Color.Transparent, scrim = Color(0x730B1A24), ) +/** The app's Material 3 scheme outside Compose UI (WoL widget via Glance, zadání 36 §2.6); no dynamic colours. */ +internal fun netKitMaterialColorScheme(dark: Boolean) = (if (dark) DarkNetKitColors else LightNetKitColors).toMaterial() + object NetKitTheme { val colors: NetKitColors @Composable @ReadOnlyComposable get() = LocalNetKitColors.current } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt b/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt index 4ded5f1..1075891 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt @@ -14,6 +14,8 @@ import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag @@ -47,12 +49,12 @@ internal fun UpdateCard(info: UpdateInfo, onDismiss: () -> Unit, modifier: Modif Panel(modifier.testTag("update_card")) { Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(Spacing.tiny)) { - Text(stringResource(R.string.update_available_title, info.versionName), style = NetKitType.panelTitle, color = colors.text) + Text(stringResource(R.string.update_available_title, info.versionName), Modifier.semantics { heading() }, style = NetKitType.panelTitle, color = colors.text) info.released?.let { localDate(it) }?.let { Text(stringResource(R.string.update_released, it), style = NetKitType.label, color = colors.muted) } } - IconButton(onClick = onDismiss, modifier = Modifier.size(40.dp).testTag("update_dismiss")) { + IconButton(onClick = onDismiss, modifier = Modifier.size(48.dp).testTag("update_dismiss")) { Icon(NetKitIcons.Close, stringResource(R.string.update_dismiss), Modifier.size(18.dp), tint = colors.muted) } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt b/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt index 5530fbd..512fede 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt @@ -14,7 +14,6 @@ import cz.netkit.shared.update.UpdateParseResult import cz.netkit.shared.update.UpdateSource import cz.netkit.shared.update.UpdateUrlPolicy import cz.netkit.shared.update.checkForUpdate -import cz.netkit.shared.update.isUpdateCheckDue import cz.netkit.shared.update.parseLatestJson import java.io.File import java.io.IOException @@ -95,8 +94,6 @@ internal class UpdateChecker(context: Context) { } } - fun isDue(nowMs: Long = System.currentTimeMillis()): Boolean = isUpdateCheckDue(lastCheckMs(), nowMs) - /** The last valid manifest, re-validated against the current policy. */ fun cached(): UpdateInfo? = preferences.getString(KEY_LAST_BODY, null)?.let { body -> (parseLatestJson(body, policy) as? UpdateParseResult.Ok)?.info diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/ExportSession.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/ExportSession.kt new file mode 100644 index 0000000..b3e8b0f --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/ExportSession.kt @@ -0,0 +1,53 @@ +package cz.netkit.app.wifi + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +/** Outcome of the last export, shown as a banner until the next export or dismissal. */ +enum class ExportNotice { SAVED, FAILED } + +/** + * The export state the Wi-Fi and Overview ViewModels share (zadání 38): the text is serialized + * when the picker opens ([prepare]) and exactly that snapshot is written to the document the + * picker returns ([save]), even if the scan or the recording changed meanwhile. [D] is the + * document handle (`Uri` in the app); [write] stores the text and reports success. No Android + * types, so the flow is unit-tested without a device. + */ +class ExportSession(private val write: suspend (D, String) -> Boolean) { + private val _notice = MutableStateFlow(null) + val notice: StateFlow = _notice.asStateFlow() + private var pending: String? = null + + /** Captures [text] for the next picker result; null = nothing to export (picker must not open). */ + fun prepare(text: String?): Boolean { + pending = text + if (text != null) _notice.value = null + return text != null + } + + /** The picker could not be started. */ + fun launchFailed() { + pending = null + _notice.value = ExportNotice.FAILED + } + + fun dismiss() { _notice.value = null } + + fun clear() { + pending = null + _notice.value = null + } + + /** + * Picker result: null [document] = the user cancelled (nothing written, no notice). A result + * without a prepared text (e.g. after process death) or a failed write → [ExportNotice.FAILED]. + * The prepared text is consumed either way. + */ + suspend fun save(document: D?) { + val text = pending + pending = null + if (document == null) return + _notice.value = if (text != null && write(document, text)) ExportNotice.SAVED else ExportNotice.FAILED + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/SpectrumChart.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/SpectrumChart.kt index b728e03..c49dae9 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wifi/SpectrumChart.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/SpectrumChart.kt @@ -42,7 +42,9 @@ import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.graphics.lerp import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource +import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription @@ -53,10 +55,12 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.drawText import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.rememberTextMeasurer +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import cz.netkit.app.R +import cz.netkit.app.ui.NeutralButton import cz.netkit.app.ui.SectionCard import cz.netkit.app.ui.Spacing import cz.netkit.app.ui.Tone @@ -69,6 +73,8 @@ import cz.netkit.shared.wifi.ChannelHealthEntry import cz.netkit.shared.wifi.SpectrumAxis import cz.netkit.shared.wifi.SpectrumTrace import cz.netkit.shared.wifi.WIFI_CHART_AP_LIMIT +import cz.netkit.shared.wifi.PinnedAccessPoint +import cz.netkit.shared.wifi.spectrumSelection import kotlin.math.floor /** Visible dBm range of the spectrum chart; peaks outside are clamped to the edge. */ @@ -77,14 +83,12 @@ private const val SPECTRUM_CEILING_DBM = -30 private val SPECTRUM_DBM_TICKS = listOf(-50, -70, -90) /** - * Traces drawn with the six-colour palette: the connected AP first (so it always gets the - * accent colour), then the strongest others up to [WIFI_CHART_AP_LIMIT]. Colour and marker - * shape follow the position in this list; the AP list reuses the same colours. + * Traces drawn with the six-colour palette without pins: the connected AP first (so it always + * gets the accent colour), then the strongest others up to [WIFI_CHART_AP_LIMIT]. With pins + * use [spectrumSelection] (connected → pinned → strongest). Colour and marker shape follow the + * position in this list; the AP list reuses the same colours. */ -internal fun spectrumDrawnTraces(traces: List): List { - val connected = traces.firstOrNull { it.accessPoint.isCurrent } - return (listOfNotNull(connected) + traces.filterNot { it === connected }).take(WIFI_CHART_AP_LIMIT) -} +internal fun spectrumDrawnTraces(traces: List): List = spectrumSelection(traces).drawn /** 20 MHz channels of the axis lying fully inside each shape (bonded span), e.g. 36–48 for 80 MHz. */ private fun spannedChannels(trace: SpectrumTrace, axis: SpectrumAxis): List> = trace.shapes.map { shape -> @@ -92,25 +96,51 @@ private fun spannedChannels(trace: SpectrumTrace, axis: SpectrumAxis): List, widths: List, gap: Float): List { + require(starts.size == widths.size) + if (starts.size <= 1) return starts.indices.toList() + val last = starts.lastIndex + val drawn = mutableListOf(0) + var end = starts[0] + widths[0] + for (index in 1 until last) { + if (starts[index] < end + gap || starts[index] + widths[index] + gap > starts[last]) continue + drawn += index + end = starts[index] + widths[index] + } + return drawn + last +} + +/** "šířka 40 MHz, střed neznámý" for a bonded AP whose shape covers only the primary 20 MHz. */ +@Composable internal fun centerUnknownNote(trace: SpectrumTrace): String? = trace.accessPoint.widthMhz + ?.takeIf { trace.centerUnknown }?.let { stringResource(R.string.wifi_width_center_unknown, it) } + /** Channel summary for screen readers: primary channel, bonded span when wider than 20 MHz, width. */ @Composable private fun spectrumChannelText(trace: SpectrumTrace, axis: SpectrumAxis): String { val ap = trace.accessPoint val span = spannedChannels(trace, axis).filter { it.size > 1 }.joinToString(" + ") { "${it.first()}–${it.last()}" } - val width = ap.widthMhz?.let { + val width = centerUnknownNote(trace) ?: ap.widthMhz?.let { if (ap.is80Plus80) stringResource(R.string.wifi_width_80_plus_80) else stringResource(R.string.wifi_width_mhz, it) } return listOfNotNull(stringResource(R.string.wifi_spectrum_channel_short, trace.primaryChannel), span.ifBlank { null }, width).joinToString(" · ") } +internal fun BandSpectrum.strongestTrace(): SpectrumTrace? = traces.maxByOrNull { it.accessPoint.rssiDbm } + /** * Spectrum card of one band (prototype `vSpectrum`): AP trapezoids on a real-frequency axis - * drawn directly on the card, band gaps in `surface2`, `divider` grid, `dim` labels, the + * drawn directly on the card, band gaps in `surface2`, `divider` grid, `muted` labels, the * connected AP with a bolder outline and fill. Legend = marker swatch + SSID. * Visualisation of scan results, not an RF measurement (explained in the screen's InfoNote). */ @OptIn(ExperimentalLayoutApi::class) -@Composable internal fun SpectrumPanel(spectrum: BandSpectrum, bandName: String, drawn: List) { +@Composable internal fun SpectrumPanel(spectrum: BandSpectrum, bandName: String, drawn: List, + pinnedKeys: Set = emptySet(), missingPins: List = emptyList(), onUnpin: ((String) -> Unit)? = null) { val colors = NetKitTheme.colors val palette = wifiChartPalette(colors) val axis = spectrum.axis @@ -120,10 +150,16 @@ private fun spannedChannels(trace: SpectrumTrace, axis: SpectrumAxis): List val line = stringResource(R.string.wifi_spectrum_trace_description, index + 1, trace.accessPoint.ssid ?: hiddenName, spectrumChannelText(trace, axis), trace.peakDbm) - if (trace.accessPoint.isCurrent) stringResource(R.string.wifi_spectrum_trace_connected, line) else line + val marked = if (trace.key in pinnedKeys) "$line · ${stringResource(R.string.wifi_pinned_tag)}" else line + if (trace.accessPoint.isCurrent) stringResource(R.string.wifi_spectrum_trace_connected, marked) else marked + } + val missingLines = missingPins.map { stringResource(R.string.wifi_pin_missing, it.ssid ?: hiddenName) } + val outOfBand = if (axis.ticks.any { it.outOfBand && it.channel == 14 }) stringResource(R.string.wifi_spectrum_channel14_out_of_band) else null + val strongest = spectrum.strongestTrace()?.let { trace -> + stringResource(R.string.a11y_strongest, trace.accessPoint.ssid ?: hiddenName, trace.primaryChannel, trace.accessPoint.rssiDbm) } - val description = (listOf(stringResource(R.string.wifi_spectrum_description, bandName, spectrum.traces.size, drawn.size, - SPECTRUM_FLOOR_DBM, SPECTRUM_CEILING_DBM)) + traceLines).joinToString("\n") + val description = (listOfNotNull(stringResource(R.string.wifi_spectrum_description, bandName, spectrum.traces.size, drawn.size, + SPECTRUM_FLOOR_DBM, SPECTRUM_CEILING_DBM), strongest, outOfBand) + traceLines + missingLines).joinToString("\n") SectionCard(stringResource(R.string.wifi_spectrum_chart_title), meta = stringResource(R.string.wifi_spectrum_chart_meta, spectrum.traces.size)) { SpectrumCanvas(axis, drawn, connectedIndex, palette, @@ -132,16 +168,50 @@ private fun spannedChannels(trace: SpectrumTrace, axis: SpectrumAxis): List - val connected = trace.accessPoint.isCurrent - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { - MarkerGlyph(index, Color(palette.series[index])) - val name = trace.accessPoint.ssid ?: hiddenName - Text(if (connected) stringResource(R.string.wifi_spectrum_trace_connected, name) else name, - style = if (connected) NetKitType.label.copy(fontWeight = FontWeight.SemiBold) else NetKitType.label, - color = if (connected) colors.text else colors.muted) - } + SpectrumLegendItem(index, trace, Color(palette.series[index]), hiddenName, pinned = trace.key in pinnedKeys) } - if (hidden > 0) Text(stringResource(R.string.wifi_spectrum_more, hidden), style = NetKitType.label, color = colors.dim) + if (hidden > 0) Text(stringResource(R.string.wifi_spectrum_more, hidden), style = NetKitType.label, color = colors.muted) + } + // Pinned APs absent from the newest scan: named, no marker (nothing is drawn for them), and + // unpinnable here — they have no list row, and would otherwise block the limit of 3 pins. + missingPins.forEachIndexed { index, pin -> + MissingPinRow(missingLines[index], pin.ssid ?: hiddenName, onUnpin?.let { unpin -> { unpin(pin.bssid) } }) + } + } +} + +@Composable private fun MissingPinRow(text: String, name: String, onUnpin: (() -> Unit)?) { + val colors = NetKitTheme.colors + Row(Modifier.fillMaxWidth().testTag("wifi_pin_missing"), verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(text, Modifier.weight(1f), style = NetKitType.label, color = colors.muted) + if (onUnpin != null) { + val label = stringResource(R.string.wifi_unpin_named, name) + NeutralButton(stringResource(R.string.wifi_unpin), onUnpin, + Modifier.testTag("wifi_pin_missing_unpin").semantics { contentDescription = label }, small = true) + } + } +} + +/** + * One legend entry: marker + SSID, and under it the "centre unknown" note. The note sits on its + * own line so a long SSID or a large font scale cannot squeeze it to zero width (Codex review P2); + * the SSID is one line with an ellipsis. The marker is centred on the SSID line. + */ +@Composable internal fun SpectrumLegendItem(index: Int, trace: SpectrumTrace, color: Color, hiddenName: String, pinned: Boolean = false) { + val colors = NetKitTheme.colors + val connected = trace.accessPoint.isCurrent + val name = trace.accessPoint.ssid ?: hiddenName + val lineHeight = with(LocalDensity.current) { NetKitType.label.lineHeight.toDp() } + Row(verticalAlignment = Alignment.Top, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Box(Modifier.height(lineHeight), contentAlignment = Alignment.Center) { MarkerGlyph(index, color) } + Column { + Text(if (connected) stringResource(R.string.wifi_spectrum_trace_connected, name) else name, + style = if (connected) NetKitType.label.copy(fontWeight = FontWeight.SemiBold) else NetKitType.label, + color = if (connected) colors.text else colors.muted, maxLines = 1, overflow = TextOverflow.Ellipsis) + centerUnknownNote(trace)?.let { Text(it, style = NetKitType.label, color = colors.muted) } + if (pinned) Text(stringResource(R.string.wifi_pinned_tag), Modifier.testTag("wifi_legend_pinned"), + style = NetKitType.label, color = colors.accent) } } } @@ -155,8 +225,10 @@ private fun spannedChannels(trace: SpectrumTrace, axis: SpectrumAxis): List + // Frequency ranges without any listed channel keep their real width and are shaded, + // and so is the range outside the permitted band (2.4 GHz above 2483.5 MHz). + (axis.gaps + axis.outOfBand).forEach { gap -> drawRect(colors.surface2, Offset(x(gap.lowerMhz), top), Size(x(gap.upperMhz) - x(gap.lowerMhz), plotHeight)) } SPECTRUM_DBM_TICKS.forEach { dbm -> @@ -206,16 +279,19 @@ private fun spannedChannels(trace: SpectrumTrace, axis: SpectrumAxis): List val tx = x(tick.frequencyMhz) drawLine(tickColor, Offset(tx, bottom), Offset(tx, bottom + (if (tick.labelled) 4 else 2).dp.toPx()), 1.dp.toPx()) - if (!tick.labelled) return@forEach - val label = measurer.measure(tick.channel.toString(), labelStyle) - val lx = (tx - label.size.width / 2f).coerceIn(0f, size.width - label.size.width) - if (lx < lastLabelEnd + 4.dp.toPx()) return@forEach - drawText(label, topLeft = Offset(lx, bottom + 6.dp.toPx())) - lastLabelEnd = lx + label.size.width + } + val labelled = axis.ticks.filter { it.labelled } + val labels = labelled.map { measurer.measure(it.channel.toString(), if (it.outOfBand) outOfBandLabelStyle else labelStyle) } + val starts = labelled.zip(labels) { tick, label -> + (x(tick.frequencyMhz) - label.size.width / 2f).coerceIn(0f, size.width - label.size.width) + } + // 2 dp like the heat strip: with the 2.4 GHz margin a 5 MHz step is ~15 dp on a 411 dp phone and a + // two-digit label ~11.5 dp, so a 4 dp gap would drop 11 and 13 (emulator evidence, zadání 34). + spectrumAxisLabelIndices(starts, labels.map { it.size.width.toFloat() }, 2.dp.toPx()).forEach { index -> + drawText(labels[index], topLeft = Offset(starts[index], bottom + 6.dp.toPx())) } } } @@ -280,13 +356,13 @@ internal fun heatCells(channels: List): List, labelled: Set, selectedChannel: Int?, onSelect: (Int) -> Unit) { val colors = NetKitTheme.colors val select by rememberUpdatedState(onSelect) val measurer = rememberTextMeasurer() - val labelStyle = NetKitType.label.copy(fontSize = 10.5.sp, color = colors.dim) + val labelStyle = NetKitType.label.copy(fontSize = 10.5.sp, color = colors.muted) val selectLabel = stringResource(R.string.wifi_spectrum_health_details) val cellDescriptions = cells.map { entry -> entry?.let { @@ -296,7 +372,10 @@ internal fun heatCells(channels: List): List maxWidth val stripWidth = if (scrolls) needed else maxWidth val scroll = rememberScrollState() @@ -304,7 +383,7 @@ internal fun heatCells(channels: List): List): List val cell = (size.width - gap * (cells.size - 1)) / cells.size val index = floor(change.position.x / (cell + gap)).toInt().coerceIn(0, cells.lastIndex) @@ -321,7 +400,7 @@ internal fun heatCells(channels: List): List): List diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiExportFiles.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiExportFiles.kt new file mode 100644 index 0000000..a3b3c0d --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiExportFiles.kt @@ -0,0 +1,135 @@ +package cz.netkit.app.wifi + +import android.content.Context +import android.content.pm.PackageManager +import android.net.Uri +import android.provider.DocumentsContract +import android.telephony.TelephonyManager +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.rememberUpdatedState +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import cz.netkit.app.R +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.StatusBanner +import cz.netkit.app.ui.StatusKind +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.lan.lanExportFileBytes +import cz.netkit.shared.wifi.WifiExportFormat +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.runInterruptible +import kotlinx.coroutines.withContext + +/* + * Zadání 38: shared plumbing of the Wi-Fi scan export and the walk log export. Files go only to + * a document the user creates through the system picker (SAF, ACTION_CREATE_DOCUMENT); no + * storage permission, nothing leaves the phone by itself. + */ + +/** + * Writes [text] (UTF-8, at most the LAN export limit of 8 MiB) to [uri], truncating it. On a + * failure the document — just created by the picker — is deleted (best effort) and `false` is + * returned; a cancellation also deletes it and is rethrown. + */ +suspend fun writeExportDocument(context: Context, uri: Uri, text: String): Boolean = withContext(Dispatchers.IO) { + var saved = false + try { + val bytes = lanExportFileBytes(text) + runInterruptible { + context.contentResolver.openOutputStream(uri, "wt")?.use { it.write(bytes) } ?: error("Export output unavailable") + } + saved = true + } catch (error: CancellationException) { + throw error + } catch (_: Exception) { + saved = false + } finally { + if (!saved) withContext(NonCancellable) { + // The URI was just created by CreateDocument; never delete an existing user document. + try { DocumentsContract.deleteDocument(context.contentResolver, uri) } catch (_: Exception) { } + } + } + saved +} + +/** + * Two SAF "create document" launchers (CSV, JSON) registered at the caller's scope; returns a + * function that opens the picker with a suggested file name and reports whether it could start. + */ +@Composable +fun rememberExportLauncher(onResult: (Uri?) -> Unit): (WifiExportFormat, String) -> Boolean { + val callback by rememberUpdatedState(onResult) + val csv = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument(WifiExportFormat.CSV.mimeType)) { callback(it) } + val json = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument(WifiExportFormat.JSON.mimeType)) { callback(it) } + return { format, baseName -> + try { + when (format) { + WifiExportFormat.CSV -> csv.launch("$baseName.csv") + WifiExportFormat.JSON -> json.launch("$baseName.json") + } + true + } catch (_: Exception) { false } + } +} + +/** + * Confirmation before an export: the [warning] that the file holds identifiers of nearby networks + * (like the LAN and WoL exports), an optional [note], and the format choice. [onExport] gets the + * chosen format; the dialog closes itself through [onDismiss]. + */ +@Composable +fun ExportDialog(title: String, warning: String, note: String?, onDismiss: () -> Unit, onExport: (WifiExportFormat) -> Unit) { + val colors = NetKitTheme.colors + var format by rememberSaveable { mutableStateOf(WifiExportFormat.CSV) } + AlertDialog( + onDismissRequest = onDismiss, + containerColor = colors.surface, + title = { Text(title, style = NetKitType.panelTitle, color = colors.text) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { + StatusBanner(warning, StatusKind.WARNING) + note?.let { Text(it, style = NetKitType.label, color = colors.muted) } + Row(Modifier.selectableGroup(), horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + WifiExportFormat.entries.forEach { entry -> + SmallChip(stringResource(if (entry == WifiExportFormat.CSV) R.string.lan_format_csv else R.string.lan_format_json), + entry == format, Modifier.testTag("export_format_${entry.extension}")) { format = entry } + } + } + } + }, + confirmButton = { + TextButton({ onExport(format); onDismiss() }, Modifier.testTag("export_confirm")) { + Text(stringResource(R.string.wifi_export_confirm), color = colors.accent) + } + }, + dismissButton = { TextButton(onDismiss) { Text(stringResource(R.string.wifi_export_cancel), color = colors.muted) } }, + ) +} + +/** + * Country of the registered mobile network (ISO 3166-1 alpha-2, lowercase), or null without + * telephony, without a registration (airplane mode, no SIM) or on any failure. No permission: + * `TelephonyManager.getNetworkCountryIso()` (API 1) needs only the radio feature, and throws + * `UnsupportedOperationException` without it (docs/zavislosti.md, 2026-12-01). + */ +fun networkCountryIso(context: Context): String? = try { + if (!context.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) null + else context.getSystemService(TelephonyManager::class.java)?.networkCountryIso?.takeIf { it.isNotBlank() } +} catch (_: Exception) { null } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanBudget.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanBudget.kt index 24118d0..730b8f3 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanBudget.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanBudget.kt @@ -1,5 +1,7 @@ package cz.netkit.app.wifi +internal const val WIFI_SCAN_LIMIT = 4 + internal data class WifiScanBudget(val remaining: Int, val waitSeconds: Long) /** Own accepted startScan calls only. Advisory: the system's budget is not observable. */ @@ -10,14 +12,14 @@ internal class WifiScanWindow(private val nowMs: () -> Long) { prune(nowMs()) starts.addLast(nowMs()) // When throttling is disabled we still need only the last four starts. - while (starts.size > 4) starts.removeFirst() + while (starts.size > WIFI_SCAN_LIMIT) starts.removeFirst() } @Synchronized fun budget(): WifiScanBudget { val now = nowMs() prune(now) - val wait = if (starts.size < 4) 0 else ((120_000 - (now - starts.first()) + 999) / 1000).coerceAtLeast(0) - return WifiScanBudget((4 - starts.size).coerceAtLeast(0), wait) + val wait = if (starts.size < WIFI_SCAN_LIMIT) 0 else ((120_000 - (now - starts.first()) + 999) / 1000).coerceAtLeast(0) + return WifiScanBudget((WIFI_SCAN_LIMIT - starts.size).coerceAtLeast(0), wait) } private fun prune(now: Long) { diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanLimitHelp.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanLimitHelp.kt index 0ecc291..8d2171e 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanLimitHelp.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanLimitHelp.kt @@ -11,6 +11,7 @@ import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import cz.netkit.shared.wifi.WifiScanStatus import cz.netkit.app.R @@ -21,7 +22,7 @@ import cz.netkit.app.ui.theme.NetKitType @Composable internal fun WifiScanBudgetNotice(budget: WifiScanBudget, modifier: Modifier = Modifier) { - Text(if (budget.remaining > 0) stringResource(R.string.wifi_scan_remaining, budget.remaining) + Text(if (budget.remaining > 0) pluralStringResource(R.plurals.wifi_scan_remaining, budget.remaining, budget.remaining, WIFI_SCAN_LIMIT) else stringResource(R.string.wifi_scan_wait_estimate, budget.waitSeconds), modifier.testTag("wifi_scan_budget"), style = NetKitType.label, color = NetKitTheme.colors.muted) } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScreen.kt index 6721f81..268d833 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScreen.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScreen.kt @@ -10,6 +10,9 @@ import android.content.ContextWrapper import android.content.Intent import android.os.SystemClock import android.provider.Settings +import android.widget.Toast +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.combinedClickable import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.animation.animateColorAsState @@ -50,6 +53,7 @@ import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.heading import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight @@ -64,6 +68,7 @@ import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.repeatOnLifecycle +import cz.netkit.app.ui.chart.seriesDescription import cz.netkit.app.R import cz.netkit.app.ui.* import cz.netkit.app.ui.motion.MotionToken @@ -90,6 +95,14 @@ fun WifiScreen(viewModel: WifiViewModel, modifier: Modifier = Modifier) { val state by viewModel.state.collectAsStateWithLifecycle() val history by viewModel.history.collectAsStateWithLifecycle() val scanStarts by viewModel.scanStarts.collectAsStateWithLifecycle() + val pins by viewModel.pins.collectAsStateWithLifecycle() + val exportNotice by viewModel.exportNotice.collectAsStateWithLifecycle() + // Zadání 38: ESS grouping (all bands), expanded groups, scan export dialog, country code. + var grouped by rememberSaveable { mutableStateOf(false) } + var expandedGroups by rememberSaveable { mutableStateOf(listOf()) } + var exportOpen by rememberSaveable { mutableStateOf(false) } + var countryCode by remember { mutableStateOf(null) } + val launchScanExport = rememberExportLauncher(viewModel::saveScanExport) // null = automatic: the connected AP's band, else 2.4 GHz. var selectedBand by rememberSaveable { mutableStateOf(null) } var sort by rememberSaveable { mutableStateOf(WifiSort.SIGNAL) } @@ -119,6 +132,7 @@ fun WifiScreen(viewModel: WifiViewModel, modifier: Modifier = Modifier) { try { refreshIssue() viewModel.refreshCurrent() + countryCode = networkCountryIso(context) while (isActive) { elapsedNow = SystemClock.elapsedRealtime() delay(1_000L) @@ -130,9 +144,16 @@ fun WifiScreen(viewModel: WifiViewModel, modifier: Modifier = Modifier) { val connectedBand = (state.accessPoints.firstOrNull { it.isCurrent }?.band ?: state.current?.frequencyMhz?.let(::bandForFrequency))?.takeIf { it != WifiBand.UNKNOWN } val band = selectedBand ?: connectedBand ?: WifiBand.GHZ_2_4 - val visible = remember(state.accessPoints, band, sort, query) { sortedAccessPoints(state.accessPoints, band, sort, query) } + // Grouped by SSID the list spans all bands: one ESS usually has radios in several bands. + val visible = remember(state.accessPoints, band, sort, query, grouped) { + sortedAccessPoints(state.accessPoints, if (grouped) null else band, sort, query) + } + val entries = remember(visible, sort, grouped) { if (grouped) essListEntries(visible, sort) else null } val spectrum = remember(state.accessPoints, band) { bandSpectrum(state.accessPoints, band) } - val drawn = remember(spectrum) { spectrum?.let { spectrumDrawnTraces(it.traces) }.orEmpty() } + val selection = remember(spectrum, pins, band, state.accessPoints) { + spectrum?.let { spectrumSelection(it.traces, pins, band, state.accessPoints) } + } + val drawn = selection?.drawn.orEmpty() val palette = wifiChartPalette(NetKitTheme.colors) val seriesByKey = remember(drawn, palette) { drawn.mapIndexed { index, trace -> trace.key to Color(palette.series[index]) }.toMap() } val datasetAge = wifiDatasetAge(state.lastUpdatedElapsedMs, elapsedNow) @@ -156,6 +177,15 @@ fun WifiScreen(viewModel: WifiViewModel, modifier: Modifier = Modifier) { WifiAccessIssue.NONE -> viewModel.scan() } } + fun togglePin(point: AccessPoint) { + val message = when (viewModel.togglePin(point)) { + PinChange.PINNED -> context.getString(R.string.wifi_pin_done) + PinChange.UNPINNED -> context.getString(R.string.wifi_unpin_done) + PinChange.LIMIT_REACHED -> context.getString(R.string.wifi_pin_limit, WIFI_PIN_LIMIT) + PinChange.NO_BSSID -> null + } + message?.let { Toast.makeText(context, it, Toast.LENGTH_SHORT).show() } + } val budget = remember(scanStarts, elapsedNow) { viewModel.scanBudget() } val scanning = state.status == WifiScanStatus.SCANNING val notice = scanNotice(state, datasetAge) @@ -170,6 +200,12 @@ fun WifiScreen(viewModel: WifiViewModel, modifier: Modifier = Modifier) { } } item { WifiScanBudgetNotice(budget, Modifier.padding(top = Spacing.small)) } + exportNotice?.let { value -> item(key = "export_notice") { + Box(gap.testTag("wifi_export_notice")) { + StatusBanner(stringResource(if (value == ScanExportNotice.SAVED) R.string.wifi_export_saved else R.string.wifi_export_failed), + if (value == ScanExportNotice.SAVED) StatusKind.INFO else StatusKind.ERROR) + } + } } if (issue != WifiAccessIssue.NONE || settingsFailure || notice != null) item { Column(gap, verticalArrangement = Arrangement.spacedBy(Spacing.small)) { if (issue != WifiAccessIssue.NONE) { @@ -193,7 +229,10 @@ fun WifiScreen(viewModel: WifiViewModel, modifier: Modifier = Modifier) { // The connected AP's band is the automatic choice: picking it again returns to automatic // selection (follows the AP when it moves band), any other band is a manual pick. item { Box(gap) { BandChips(band, connectedBand, counts) { picked -> selectedBand = picked.takeUnless { it == (connectedBand ?: WifiBand.GHZ_2_4) } } } } - spectrum?.let { value -> item { Box(gap) { SpectrumPanel(value, bandLabel(band), drawn) } } } + spectrum?.let { value -> item { Box(gap) { + SpectrumPanel(value, bandLabel(band), drawn, selection?.pinnedKeys.orEmpty(), selection?.missingPins.orEmpty(), + onUnpin = viewModel::unpin) + } } } item { Box(gap) { SegmentedTabs(listOf(stringResource(R.string.wifi_spectrum_tab_networks), stringResource(R.string.wifi_channel_health_title)), @@ -205,19 +244,59 @@ fun WifiScreen(viewModel: WifiViewModel, modifier: Modifier = Modifier) { item { Box(gap) { CurrentConnectionRow(if (datasetAge.allowsRecommendation) current else current.copy(widthMhz = null)) } } } networksCard(visible, seriesByKey, state, history, elapsedNow, sort, { sort = it }, query, { query = it }, - viewModel::excludeConnectedSsid, viewModel::markOwnAccessPoint, viewModel::selectNetwork) + viewModel::excludeConnectedSsid, viewModel::markOwnAccessPoint, viewModel::selectNetwork, + NetworkListOptions(pins, ::togglePin, grouped, { grouped = it }, entries, expandedGroups.toSet(), + { key -> expandedGroups = if (key in expandedGroups) expandedGroups - key else expandedGroups + key }, + onExport = { viewModel.dismissExportNotice(); exportOpen = true }, exportEnabled = state.accessPoints.isNotEmpty())) } else { item { Box(gap) { ChannelHealthSection(state, band, spectrum?.axis, elapsedNow, datasetAge.freshness, candidateWidth, - { candidateWidth = it }, ::onScanAction, scanEnabled = !scanning, onRecommendationScan = viewModel::scan) + { candidateWidth = it }, ::onScanAction, scanEnabled = !scanning, onRecommendationScan = viewModel::scan, + countryCode = countryCode) } } } item { Box(gap) { ScreenInfoNote() } } } + if (exportOpen) ExportDialog(stringResource(R.string.wifi_export_title), stringResource(R.string.wifi_export_warning), + stringResource(R.string.wifi_export_note), onDismiss = { exportOpen = false }) { format -> + if (viewModel.prepareScanExport(format) && !launchScanExport(format, "netkit-wifi-scan")) viewModel.exportLaunchFailed() + } } +/** Zadání 38 options of the "Sítě" card: pins, ESS grouping and the scan export action. */ +internal class NetworkListOptions( + val pins: List = emptyList(), + val onPin: (AccessPoint) -> Unit = {}, + val grouped: Boolean = false, + val onGrouped: (Boolean) -> Unit = {}, + /** Non-null when grouped: the ESS entries of the visible list. */ + val entries: List? = null, + val expandedGroups: Set = emptySet(), + val onToggleGroup: (String) -> Unit = {}, + val onExport: () -> Unit = {}, + val exportEnabled: Boolean = false, +) + +/** One lazy row of the networks card: an ESS group header or an AP (indented inside an open group). */ +private sealed interface NetworkRow { + data class GroupHeader(val group: EssListEntry.Group, val expanded: Boolean) : NetworkRow + data class Ap(val point: AccessPoint, val inGroup: Boolean) : NetworkRow +} + +private fun networkRows(visible: List, options: NetworkListOptions): List = + options.entries?.flatMap { entry -> + when (entry) { + is EssListEntry.Single -> listOf(NetworkRow.Ap(entry.accessPoint, inGroup = false)) + is EssListEntry.Group -> { + val open = entry.key in options.expandedGroups + listOf(NetworkRow.GroupHeader(entry, open)) + + if (open) entry.accessPoints.map { NetworkRow.Ap(it, inGroup = true) } else emptyList() + } + } + } ?: visible.map { NetworkRow.Ap(it, inGroup = false) } + /** "18 sítí · sken před 20 s"; while scanning the age part says so. */ @Composable private fun headerSubtitle(networks: Int, age: WifiDatasetAge, scanning: Boolean): String { val seconds = age.ageMs?.div(1000) @@ -281,7 +360,7 @@ private fun scanNotice(state: WifiAnalyzerState, age: WifiDatasetAge): Pair Unit) { +@Composable internal fun SmallChip(text: String, on: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { val colors = NetKitTheme.colors val fill by animateColorAsState(if (on) colors.accentSoft else colors.surface2, rememberNetKitTween(MotionToken.FAST), label = "chip-fill") val ink by animateColorAsState(if (on) colors.accent else colors.muted, rememberNetKitTween(MotionToken.FAST), label = "chip-ink") - Box(Modifier.heightIn(min = 36.dp).clip(NetKitShape.pill).background(fill) + Box(modifier.sizeIn(minWidth = 48.dp, minHeight = 48.dp).clip(NetKitShape.pill).background(fill) .selectable(selected = on, role = Role.RadioButton, onClick = onClick).padding(horizontal = 14.dp), contentAlignment = Alignment.Center) { Text(text, style = NetKitType.tag.copy(fontSize = 13.sp), color = ink, maxLines = 1, softWrap = false) } } -@Composable private fun WifiCheckboxRow(checked: Boolean, onChecked: (Boolean) -> Unit, label: String, enabled: Boolean = true) { +@Composable private fun WifiCheckboxRow(checked: Boolean, onChecked: (Boolean) -> Unit, label: String, modifier: Modifier = Modifier, + enabled: Boolean = true) { val colors = NetKitTheme.colors - Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).toggleable(checked, enabled = enabled, + Row(modifier.fillMaxWidth().heightIn(min = 48.dp).toggleable(checked, enabled = enabled, role = Role.Checkbox, onValueChange = onChecked), verticalAlignment = Alignment.CenterVertically) { Checkbox(checked = checked, onCheckedChange = null, enabled = enabled, colors = CheckboxDefaults.colors( checkedColor = colors.accent, uncheckedColor = colors.dim, checkmarkColor = colors.accentInk)) @@ -369,23 +449,76 @@ private fun scanNotice(state: WifiAnalyzerState, age: WifiDatasetAge): Pair, seriesByKey: Map, state: WifiAnalyzerState, history: List, elapsedNow: Long, sort: WifiSort, onSort: (WifiSort) -> Unit, query: String, onQuery: (String) -> Unit, onExcludeSsid: (Boolean) -> Unit, onOwn: (String, Boolean) -> Unit, onSelect: (String) -> Unit, + options: NetworkListOptions = NetworkListOptions(), ) { + val rows = networkRows(visible, options) item(key = "networks_header") { - CardSegment(first = true, last = visible.isEmpty(), Modifier.padding(top = Spacing.normal)) { - NetworksHeader(state, sort, onSort, query, onQuery, onExcludeSsid) + CardSegment(first = true, last = rows.isEmpty(), Modifier.padding(top = Spacing.normal)) { + NetworksHeader(state, sort, onSort, query, onQuery, onExcludeSsid, options) if (visible.isEmpty()) EmptyState(stringResource(if (query.isNotBlank()) R.string.wifi_no_filter_results else R.string.wifi_no_results)) } } - val keys = uniqueRowKeys(visible.map(::accessPointKey)) - itemsIndexed(visible, key = { index, _ -> keys[index] }) { index, point -> - CardSegment(first = false, last = index == visible.lastIndex) { - AccessPointRow(point, seriesByKey[accessPointKey(point)], showDivider = index > 0, state = state, - history = history, elapsedNow = elapsedNow, onOwn = { onOwn(point.bssid, it) }, - onSelect = { onSelect(point.bssid) }) + val keys = uniqueRowKeys(rows.map { row -> + when (row) { + is NetworkRow.GroupHeader -> "group:" + row.group.key + is NetworkRow.Ap -> accessPointKey(row.point) + } + }) + itemsIndexed(rows, key = { index, _ -> keys[index] }) { index, row -> + CardSegment(first = false, last = index == rows.lastIndex) { + when (row) { + is NetworkRow.GroupHeader -> EssGroupRow(row.group, row.expanded, showDivider = index > 0) { + options.onToggleGroup(row.group.key) + } + is NetworkRow.Ap -> { + val point = row.point + AccessPointRow(point, seriesByKey[accessPointKey(point)], showDivider = index > 0, state = state, + history = history, elapsedNow = elapsedNow, onOwn = { onOwn(point.bssid, it) }, + onSelect = { onSelect(point.bssid) }, pinned = isPinned(options.pins, point), + onPin = { options.onPin(point) }, indented = row.inGroup) + } + } + } + } +} + +/** + * Header row of one ESS: SSID (+ "připojeno"), "3 AP · 2,4 GHz k. 1 · 5 GHz k. 36, 100" and the + * strongest RSSI; tap expands the group's APs below it. + */ +@Composable private fun EssGroupRow(group: EssListEntry.Group, expanded: Boolean, showDivider: Boolean, onToggle: () -> Unit) { + val colors = NetKitTheme.colors + val divider = colors.divider + val chevron by animateFloatAsState(if (expanded) 90f else 0f, rememberNetKitTween(MotionToken.FAST), label = "group-chevron") + // "3 AP · 2,4 GHz k. 1 · 5 GHz k. 36, 100": channels per band, a bare number is ambiguous across bands. + val perBand = group.channelsByBand.filterKeys { it != WifiBand.UNKNOWN }.map { (band, channels) -> + listOfNotNull(bandLabel(band), channels.takeIf { it.isNotEmpty() } + ?.let { stringResource(R.string.wifi_group_channels, it.joinToString(", ")) }).joinToString(" ") + } + val subtitle = (listOf(stringResource(R.string.wifi_group_ap_count, group.apCount)) + perBand).joinToString(" · ") + Row(Modifier.fillMaxWidth().heightIn(min = 56.dp) + .then(if (showDivider) Modifier.drawBehind { drawLine(divider, Offset(0f, 0f), Offset(size.width, 0f), 1.dp.toPx()) } else Modifier) + .clickable(onClickLabel = stringResource(R.string.wifi_group_expand), role = Role.Button, onClick = onToggle) + .testTag("wifi_ess_group").padding(vertical = 10.dp), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { + Icon(NetKitIcons.ChevronRight, null, Modifier.size(16.dp).rotate(chevron), tint = colors.dim) + Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + Text(group.ssid, Modifier.weight(1f, fill = false), + style = NetKitType.body.copy(fontSize = 14.5.sp, fontWeight = FontWeight.SemiBold), color = colors.text, + maxLines = 1, overflow = TextOverflow.Ellipsis) + if (group.hasCurrent) Tag(stringResource(R.string.wifi_spectrum_connected), Tone.ACCENT, dot = true) + } + Text(subtitle, style = NetKitType.label, color = colors.muted, maxLines = 2, overflow = TextOverflow.Ellipsis) + } + Row(verticalAlignment = Alignment.Bottom) { + Text(group.strongestRssiDbm.toString(), Modifier.alignByBaseline(), style = NetKitType.value, color = rssiInk(group.strongestRssiDbm)) + Text(stringResource(R.string.wifi_spectrum_dbm_unit), Modifier.alignByBaseline().padding(start = 2.dp), + style = NetKitType.unit, color = colors.muted) } } } @@ -416,7 +549,7 @@ internal fun uniqueRowKeys(keys: List): List { /** Header of the "Sítě" card: sort as meta and a "Filtr" toggle with sort chips, SSID filter and same-SSID exclusion. */ @OptIn(ExperimentalLayoutApi::class) @Composable private fun NetworksHeader(state: WifiAnalyzerState, sort: WifiSort, onSort: (WifiSort) -> Unit, query: String, - onQuery: (String) -> Unit, onExcludeSsid: (Boolean) -> Unit) { + onQuery: (String) -> Unit, onExcludeSsid: (Boolean) -> Unit, options: NetworkListOptions) { val colors = NetKitTheme.colors var filtersOpen by rememberSaveable { mutableStateOf(query.isNotBlank()) } val chevron by animateFloatAsState(if (filtersOpen) 90f else 0f, rememberNetKitTween(MotionToken.FAST), label = "filter-chevron") @@ -424,8 +557,16 @@ internal fun uniqueRowKeys(keys: List): List { Column(Modifier.animateContentSize(rememberNetKitTween(MotionToken.BASE)), verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { Column(Modifier.weight(1f)) { - Text(stringResource(R.string.wifi_spectrum_tab_networks), style = NetKitType.panelTitle, color = colors.text) - Text(sortedByLabel(sort), style = NetKitType.label, color = colors.muted) + Text(stringResource(R.string.wifi_spectrum_tab_networks), Modifier.semantics { heading() }, style = NetKitType.panelTitle, color = colors.text) + Text(if (options.grouped) sortedByLabel(sort) + " · " + stringResource(R.string.wifi_grouped_meta) else sortedByLabel(sort), + style = NetKitType.label, color = colors.muted) + } + val exportLabel = stringResource(R.string.wifi_export_action) + Box(Modifier.size(48.dp).clip(NetKitShape.buttonSmall) + .clickable(enabled = options.exportEnabled, onClickLabel = exportLabel, role = Role.Button, onClick = options.onExport) + .testTag("wifi_export_open").semantics { contentDescription = exportLabel }, + contentAlignment = Alignment.Center) { + Icon(NetKitIcons.Download, null, Modifier.size(20.dp), tint = if (options.exportEnabled) colors.muted else colors.dim.copy(alpha = .5f)) } Row(Modifier.heightIn(min = 48.dp).clip(NetKitShape.buttonSmall) .clickable(role = Role.Button) { filtersOpen = !filtersOpen }.padding(horizontal = Spacing.small), @@ -436,6 +577,7 @@ internal fun uniqueRowKeys(keys: List): List { Icon(NetKitIcons.ChevronRight, null, Modifier.size(16.dp).rotate(chevron), tint = colors.dim) } } + WifiCheckboxRow(options.grouped, options.onGrouped, stringResource(R.string.wifi_group_by_ssid), modifier = Modifier.testTag("wifi_group_toggle")) if (filtersOpen) { FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small), modifier = Modifier.selectableGroup()) { @@ -447,20 +589,22 @@ internal fun uniqueRowKeys(keys: List): List { focusedContainerColor = colors.surface2, unfocusedContainerColor = colors.surface2, focusedBorderColor = colors.accent, unfocusedBorderColor = Color.Transparent, focusedTextColor = colors.text, unfocusedTextColor = colors.text, cursorColor = colors.accent, - focusedPlaceholderColor = colors.dim, unfocusedPlaceholderColor = colors.dim)) + focusedPlaceholderColor = colors.muted, unfocusedPlaceholderColor = colors.muted)) WifiCheckboxRow(state.excludeConnectedSsid, onExcludeSsid, stringResource(R.string.wifi_exclude_connected_ssid)) } } } /** - * Compact AP row: series swatch | SSID (+ "připojeno"), the OUI vendor when known and - * "k. 7 · 40 MHz · WPA2" | RSSI. + * Compact AP row: the SSID gets the available width first. Badges and RSSI flow below it + * when needed, followed by the OUI vendor and the channel/width/security summary. * Tapping a row with a BSSID selects it for the RSSI history (one at a time) and expands its * details; rows without a BSSID expand locally. */ +@OptIn(ExperimentalFoundationApi::class) @Composable internal fun AccessPointRow(ap: AccessPoint, series: Color?, showDivider: Boolean, state: WifiAnalyzerState, - history: List, elapsedNow: Long, onOwn: (Boolean) -> Unit, onSelect: () -> Unit) { + history: List, elapsedNow: Long, onOwn: (Boolean) -> Unit, onSelect: () -> Unit, + pinned: Boolean = false, onPin: (() -> Unit)? = null, indented: Boolean = false) { val colors = NetKitTheme.colors val divider = colors.divider var localExpanded by rememberSaveable { mutableStateOf(false) } @@ -471,41 +615,51 @@ internal fun uniqueRowKeys(keys: List): List { ap.widthMhz?.let { if (ap.is80Plus80) stringResource(R.string.wifi_width_80_plus_80_short) else stringResource(R.string.wifi_width_mhz, it) }, shortSecurityLabel(ap.security), ).joinToString(" · ") + val pinnable = selectable && onPin != null Column(Modifier.fillMaxWidth() .then(if (showDivider) Modifier.drawBehind { drawLine(divider, Offset(0f, 0f), Offset(size.width, 0f), 1.dp.toPx()) } else Modifier) + .padding(start = if (indented) 26.dp else 0.dp) .animateContentSize(rememberNetKitTween(MotionToken.BASE))) { Row(Modifier.fillMaxWidth().heightIn(min = 56.dp) - .clickable(onClickLabel = stringResource(R.string.wifi_spectrum_network_details), role = Role.Button) { + .combinedClickable(onClickLabel = stringResource(R.string.wifi_spectrum_network_details), role = Role.Button, + onLongClickLabel = if (pinnable) stringResource(R.string.wifi_pin_long_press) else null, + onLongClick = if (pinnable) onPin else null) { if (selectable) onSelect() else localExpanded = !localExpanded } .padding(vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { Box(Modifier.size(width = 10.dp, height = 34.dp).clip(RoundedCornerShape(4.dp)).background(series ?: colors.surface3)) Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { - Text(ap.ssid ?: stringResource(R.string.wifi_hidden_network), Modifier.weight(1f, fill = false), - style = NetKitType.body.copy(fontSize = 14.5.sp, fontWeight = FontWeight.SemiBold), color = colors.text) - if (ap.isCurrent) Tag(stringResource(R.string.wifi_spectrum_connected), Tone.ACCENT, dot = true) + FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), + verticalArrangement = Arrangement.spacedBy(2.dp)) { + Text(ap.ssid ?: stringResource(R.string.wifi_hidden_network), Modifier.align(Alignment.CenterVertically), + style = NetKitType.body.copy(fontSize = 14.5.sp, fontWeight = FontWeight.SemiBold), color = colors.text, + maxLines = 1, overflow = TextOverflow.Ellipsis) + FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), + verticalArrangement = Arrangement.spacedBy(2.dp)) { + if (ap.isCurrent) Tag(stringResource(R.string.wifi_spectrum_connected), Tone.ACCENT, dot = true) + if (pinned) Tag(stringResource(R.string.wifi_pinned_tag), modifier = Modifier.testTag("wifi_ap_pinned")) + Row(verticalAlignment = Alignment.Bottom) { + Text(ap.rssiDbm.toString(), Modifier.alignByBaseline(), style = NetKitType.value, color = rssiInk(ap.rssiDbm)) + Text(stringResource(R.string.wifi_spectrum_dbm_unit), Modifier.alignByBaseline().padding(start = 2.dp), + style = NetKitType.unit, color = colors.muted) + } + } } ap.vendor?.let { vendor -> - Text(vendor, Modifier.testTag("wifi_ap_vendor"), style = NetKitType.label, color = colors.dim, + Text(vendor, Modifier.testTag("wifi_ap_vendor"), style = NetKitType.label, color = colors.muted, maxLines = 1, overflow = TextOverflow.Ellipsis) } if (subtitle.isNotEmpty()) Text(subtitle, style = NetKitType.label, color = colors.muted) } - Row(verticalAlignment = Alignment.Bottom) { - Text(ap.rssiDbm.toString(), Modifier.alignByBaseline(), style = NetKitType.value, color = rssiInk(ap.rssiDbm)) - Text(stringResource(R.string.wifi_spectrum_dbm_unit), Modifier.alignByBaseline().padding(start = 2.dp), - style = NetKitType.unit, color = colors.muted) - } } if (expanded) AccessPointDetails(ap, state, history.takeIf { normalizeBssid(ap.bssid) == state.historyBssid }.orEmpty(), - elapsedNow, onOwn) + elapsedNow, onOwn, pinned, onPin.takeIf { pinnable }) } } @Composable private fun AccessPointDetails(ap: AccessPoint, state: WifiAnalyzerState, history: List, - elapsedNow: Long, onOwn: (Boolean) -> Unit) { + elapsedNow: Long, onOwn: (Boolean) -> Unit, pinned: Boolean = false, onPin: (() -> Unit)? = null) { val colors = NetKitTheme.colors val unknown = stringResource(R.string.wifi_unknown) val excluded = isOwnAccessPoint(ap, state) @@ -531,15 +685,23 @@ internal fun uniqueRowKeys(keys: List): List { ?.let { stringResource(R.string.wifi_age_seconds, it / 1000) } ?: unknown), load.takeIf { it.isNotEmpty() }?.let { KeyValue(stringResource(R.string.wifi_label_bss_load), it) }, )) + // Bonded width without a reported centre that the raster can place: the chart shows only the primary 20 MHz. + ap.widthMhz?.takeIf { bondingCenterUnknown(ap) }?.let { + Text(stringResource(R.string.wifi_width_center_unknown_detail, it), style = NetKitType.label, color = colors.muted) + } if (ap.bssid.isNotBlank() && ap.isSelected) RssiHistory(history) val vendor = ap.vendor Text(when { vendor != null -> stringResource(R.string.wifi_vendor, vendor) ap.locallyAdministered -> stringResource(R.string.wifi_vendor_local) else -> stringResource(R.string.wifi_vendor_unknown) - }, style = NetKitType.label, color = colors.dim) - if (excluded) Text(stringResource(R.string.wifi_ap_excluded), style = NetKitType.label, color = colors.dim) + }, style = NetKitType.label, color = colors.muted) + if (excluded) Text(stringResource(R.string.wifi_ap_excluded), style = NetKitType.label, color = colors.muted) WifiCheckboxRow(manuallyOwned, onOwn, stringResource(R.string.wifi_own_ap), enabled = ap.bssid.isNotBlank()) + if (onPin != null) { + WifiCheckboxRow(pinned, { onPin() }, stringResource(R.string.wifi_pin_action), modifier = Modifier.testTag("wifi_pin_toggle")) + Text(stringResource(R.string.wifi_pin_note), style = NetKitType.label, color = colors.muted) + } } } @@ -548,9 +710,10 @@ internal fun uniqueRowKeys(keys: List): List { val colors = NetKitTheme.colors Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { Text(stringResource(R.string.wifi_history_title, values.size), style = NetKitType.label, color = colors.muted) - if (values.size < 2) Text(stringResource(R.string.wifi_history_select), style = NetKitType.label, color = colors.dim) + if (values.size < 2) Text(stringResource(R.string.wifi_history_select), style = NetKitType.label, color = colors.muted) else { - val description = stringResource(R.string.wifi_history_values, values.joinToString { it.rssiDbm.toString() }) + val description = seriesDescription(stringResource(R.string.wifi_history_title, values.size), + values.map { it.rssiDbm.toFloat() }, values.indices, stringResource(R.string.wifi_signal_unit_dbm)) val start = values.first().elapsedMs val duration = (values.last().elapsedMs - start).coerceAtLeast(1) Canvas(Modifier.fillMaxWidth().height(56.dp).semantics { contentDescription = description }) { @@ -616,7 +779,7 @@ internal fun uniqueRowKeys(keys: List): List { */ @Composable private fun ChannelHealthSection(state: WifiAnalyzerState, band: WifiBand, axis: SpectrumAxis?, elapsedNow: Long, freshness: WifiDatasetFreshness, candidateWidth: Int, onWidth: (Int) -> Unit, onScan: () -> Unit, scanEnabled: Boolean, - onRecommendationScan: () -> Unit) { + onRecommendationScan: () -> Unit, countryCode: String? = null) { // Recomputed on dataset/band change and on a freshness transition, not on every clock tick. val report = remember(state, band, freshness) { channelHealthReport(state, band, elapsedNow) } val recommended = remember(state, band, freshness) { @@ -624,7 +787,7 @@ internal fun uniqueRowKeys(keys: List): List { } Column(verticalArrangement = Arrangement.spacedBy(Spacing.normal)) { when (report) { - is ChannelHealthReport.Ready -> HeatStripCard(report, state, band, axis, recommended) + is ChannelHealthReport.Ready -> HeatStripCard(report, state, band, axis, recommended, countryCode) is ChannelHealthReport.Stale -> SectionCard(stringResource(R.string.wifi_channel_health_title)) { EmptyState(stringResource(R.string.wifi_health_stale)) { PrimaryButton(stringResource(R.string.wifi_scan), onScan, Modifier.testTag("wifi_health_scan"), enabled = scanEnabled, small = true) @@ -639,7 +802,7 @@ internal fun uniqueRowKeys(keys: List): List { } @Composable private fun HeatStripCard(report: ChannelHealthReport.Ready, state: WifiAnalyzerState, band: WifiBand, axis: SpectrumAxis?, - recommended: Int?) { + recommended: Int?, countryCode: String? = null) { val cells = remember(report) { heatCells(report.channels) } val labelled = remember(axis, band) { axis?.ticks.orEmpty().filter { it.labelled && (band != WifiBand.GHZ_2_4 || it.channel % 2 == 1) }.map { it.channel }.toSet() @@ -654,6 +817,31 @@ internal fun uniqueRowKeys(keys: List): List { HeatScale() } report.channels.firstOrNull { it.channel == selected }?.let { entry -> ChannelDetail(entry, state, band) } + if (band == WifiBand.GHZ_2_4) regional24Raster(countryCode)?.let { RegionalRasterNote(it, selected) } + } +} + +/** + * Informative 2.4 GHz raster of the network's country (zadání 38 §2.5): "Region CZ (EU): kanály + * 2,4 GHz 1–13", whether the selected channel is outside it. Scores and recommendations stay global. + */ +@Composable internal fun RegionalRasterNote(raster: Regional24Raster, selectedChannel: Int?) { + val colors = NetKitTheme.colors + val region = stringResource(when (raster.region) { + WifiRegion.EU -> R.string.wifi_region_eu + WifiRegion.US -> R.string.wifi_region_us + WifiRegion.JP -> R.string.wifi_region_jp + }) + val lines = listOfNotNull( + stringResource(R.string.wifi_region_raster, raster.countryCode, region, raster.firstChannel, raster.lastChannel), + raster.dsssOnlyChannel?.let { stringResource(R.string.wifi_region_dsss_only, it) }, + selectedChannel?.takeIf { it !in raster.firstChannel..raster.lastChannel }?.let { stringResource(R.string.wifi_region_outside, it) }, + stringResource(R.string.wifi_region_note), + ) + Column(Modifier.testTag("wifi_region_note"), verticalArrangement = Arrangement.spacedBy(2.dp)) { + lines.forEach { line -> + Text(line, style = NetKitType.label, color = colors.muted) + } } } @@ -745,7 +933,7 @@ internal fun uniqueRowKeys(keys: List): List { } } AxisLabels(range.first.toInt().toString(), ((range.first + range.second) / 2).toInt().toString(), range.second.toInt().toString()) - Text(stringResource(R.string.wifi_frequency_axis), style = NetKitType.label, color = colors.dim) + Text(stringResource(R.string.wifi_frequency_axis), style = NetKitType.label, color = colors.muted) networks.forEachIndexed { index, _ -> Row(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalAlignment = Alignment.CenterVertically) { Canvas(Modifier.size(16.dp).clearAndSetSemantics { }) { @@ -761,7 +949,7 @@ internal fun uniqueRowKeys(keys: List): List { @Composable private fun RssiAxis() { Column(Modifier.height(128.dp).padding(end = Spacing.small), verticalArrangement = Arrangement.SpaceBetween) { - listOf(-30, -65, -100).forEach { Text(stringResource(R.string.wifi_dbm_value, it), style = NetKitType.label, color = NetKitTheme.colors.dim) } + listOf(-30, -65, -100).forEach { Text(stringResource(R.string.wifi_dbm_value, it), style = NetKitType.label, color = NetKitTheme.colors.muted) } } } @@ -771,9 +959,9 @@ internal fun uniqueRowKeys(keys: List): List { Text(stringResource(R.string.wifi_dbm_value, -100), Modifier.padding(end = Spacing.small).alpha(0f).clearAndSetSemantics { }, style = NetKitType.label) Row(Modifier.weight(1f), horizontalArrangement = Arrangement.SpaceBetween) { - Text(start, style = NetKitType.label, color = NetKitTheme.colors.dim) - Text(middle, style = NetKitType.label, color = NetKitTheme.colors.dim) - Text(end, style = NetKitType.label, color = NetKitTheme.colors.dim) + Text(start, style = NetKitType.label, color = NetKitTheme.colors.muted) + Text(middle, style = NetKitType.label, color = NetKitTheme.colors.muted) + Text(end, style = NetKitType.label, color = NetKitTheme.colors.muted) } } } @@ -782,7 +970,7 @@ internal fun uniqueRowKeys(keys: List): List { @Composable internal fun WifiDatasetNotice(age: WifiDatasetAge) { val colors = NetKitTheme.colors Text(age.ageMs?.let { stringResource(R.string.wifi_last_scan_age, it / 1000) } - ?: stringResource(R.string.wifi_dataset_unknown), style = NetKitType.label, color = colors.dim) + ?: stringResource(R.string.wifi_dataset_unknown), style = NetKitType.label, color = colors.muted) when (age.freshness) { WifiDatasetFreshness.AGING -> Text(stringResource(R.string.wifi_dataset_aging), style = NetKitType.label, color = colors.warn) WifiDatasetFreshness.EXPIRED -> Text(stringResource(R.string.wifi_dataset_expired), style = NetKitType.label, color = colors.warn) diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt index 6123fd4..42f94b2 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt @@ -48,6 +48,14 @@ import cz.netkit.shared.wifi.BSS_LOAD_ELEMENT_ID import cz.netkit.shared.wifi.BssLoad import cz.netkit.shared.wifi.WIFI_ELEMENT_MAX_BODY_LENGTH import cz.netkit.shared.wifi.parseBssLoad +import cz.netkit.shared.wifi.PinChange +import cz.netkit.shared.wifi.PinnedAccessPoint +import cz.netkit.shared.wifi.WifiExportFormat +import cz.netkit.shared.wifi.scanExportText +import cz.netkit.shared.wifi.refreshPinnedAccessPoints +import cz.netkit.shared.wifi.togglePinnedAccessPoint +import cz.netkit.shared.wifi.unpinAccessPoint +import android.net.Uri import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job @@ -87,6 +95,39 @@ class WifiViewModel(application: Application) : AndroidViewModel(application) { internal fun scanBudget(): WifiScanBudget = scanWindow.budget() + // --- Zadání 38: pins and scan export ------------------------------------------------------ + private val _pins = MutableStateFlow>(emptyList()) + /** APs pinned into the spectrum (by BSSID); memory only, kept across scans, lost on restart. */ + val pins: StateFlow> = _pins.asStateFlow() + /** Scan captured when the picker opened; the picker result writes exactly this ([ExportSession]). */ + private val scanExport = ExportSession { uri, text -> writeExportDocument(app, uri, text) } + val exportNotice: StateFlow = scanExport.notice + + /** Pins or unpins [point]; see [togglePinnedAccessPoint] for the limit and anonymous APs. */ + fun togglePin(point: AccessPoint): PinChange { + val update = togglePinnedAccessPoint(_pins.value, point) + _pins.value = update.pins + return update.change + } + + /** Unpins by BSSID, also a pin missing from the last scan (it has no list row to toggle). */ + fun unpin(bssid: String) { _pins.value = unpinAccessPoint(_pins.value, bssid) } + + /** Serializes the current dataset for [format]; false when there is nothing to export. */ + fun prepareScanExport(format: WifiExportFormat): Boolean = + scanExport.prepare(scanExportText(_state.value, format, System.currentTimeMillis(), SystemClock.elapsedRealtime())) + + fun exportLaunchFailed() = scanExport.launchFailed() + + /** SAF result: writes the prepared export to [uri]; null = the user cancelled the picker. */ + fun saveScanExport(uri: Uri?) { viewModelScope.launch { scanExport.save(uri) } } + + fun dismissExportNotice() = scanExport.dismiss() + + private fun onScanPublished(points: List, confirmed: Boolean) { + if (confirmed) _pins.update { refreshPinnedAccessPoints(it, points) } + } + /** Called by the Wi-Fi screen's STARTED block and explicitly at activity onStop. */ fun setScreenActive(active: Boolean) { if (active && !passiveObserver.active) passiveAfterMs = SystemClock.elapsedRealtime() @@ -119,6 +160,7 @@ class WifiViewModel(application: Application) : AndroidViewModel(application) { passiveAfterMs = snapshot.receivedElapsedMs _state.update { old -> publishScanResult(old, markPoints(snapshot.points, old.current?.bssid), true, snapshot.receivedElapsedMs) } + onScanPublished(snapshot.points, snapshot.points.isNotEmpty()) appendHistory() refreshCurrent() } catch (cancel: CancellationException) { throw cancel } @@ -167,6 +209,11 @@ class WifiViewModel(application: Application) : AndroidViewModel(application) { if (hasScanPermission()) readCurrent() else null } _state.update { old -> old.copy(current = current, accessPoints = markPoints(old.accessPoints, current?.bssid)) } + // Zadání 37: channel width of the connected AP for the network status widget (foreground scan only). + val frequency = current?.frequencyMhz + val width = current?.widthMhz + if (frequency != null && width != null) + (app as? cz.netkit.app.wol.NetKitApplication)?.netStatus?.offerWidth(System.currentTimeMillis(), frequency, width) } } @@ -206,6 +253,7 @@ class WifiViewModel(application: Application) : AndroidViewModel(application) { // Results appear before the up-to-four-second identity lookup finishes. _state.update { old -> publishScanResult(old, markPoints(snapshot.points, old.current?.bssid), snapshot.fresh, snapshot.receivedElapsedMs) } + onScanPublished(snapshot.points, snapshot.fresh && snapshot.points.isNotEmpty()) if (snapshot.fresh) appendHistory() refreshCurrent() @@ -488,3 +536,5 @@ class WifiViewModel(application: Application) : AndroidViewModel(application) { val points: List, val fresh: Boolean, val receivedElapsedMs: Long, ) } + +typealias ScanExportNotice = ExportNotice diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/MloReader.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/MloReader.kt new file mode 100644 index 0000000..c35efbb --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/MloReader.kt @@ -0,0 +1,50 @@ +package cz.netkit.app.wifi.live + +import android.annotation.SuppressLint +import android.net.wifi.ScanResult +import android.net.wifi.WifiInfo +import android.net.wifi.WifiManager +import android.os.Build +import androidx.annotation.RequiresApi +import cz.netkit.shared.wifi.AssociatedLink +import cz.netkit.shared.wifi.MloConnection +import cz.netkit.shared.wifi.MloScanWidth +import cz.netkit.shared.wifi.mloConnection +import cz.netkit.shared.wifi.usableBssid + +/** MLO belongs to this radio sample. A platform read failure only drops the MLO detail. */ +internal inline fun readLiveMlo(radio: T?, callbackInfo: T?, read: (T) -> MloConnection?): MloConnection? = + try { (radio ?: callbackInfo)?.let(read) } catch (_: RuntimeException) { null } + +/** One instance per foreground sampling loop. Only read the system scan cache, never start a scan. */ +internal class MloReader(private val wifi: WifiManager) { + private var cachedMld: String? = null + private var readAtMs = 0L + private var widths = emptyList() + + fun read(info: WifiInfo, locationAllowed: Boolean, nowMs: Long): MloConnection? { + if (Build.VERSION.SDK_INT < 34 || info.wifiStandard != ScanResult.WIFI_STANDARD_11BE) return null + val links = info.associatedMloLinks.map { link -> + AssociatedLink(link.linkId, link.band, link.channel, + ScanResult.convertChannelToFrequencyMhzIfSupported(link.channel, link.band), link.rssi, link.state) + } + val mld = if (locationAllowed && links.isNotEmpty()) usableBssid(info.apMldMacAddress?.toString()) else null + if (mld != cachedMld || (mld != null && nowMs - readAtMs >= 10_000)) { + widths = if (mld == null) emptyList() else scanWidths(mld) + cachedMld = mld + readAtMs = nowMs + } + return mloConnection(links, mld, locationAllowed, widths, nowMs) + } + + @RequiresApi(34) + @SuppressLint("MissingPermission") // Caller checked precise location and the system location switch this tick. + private fun scanWidths(mld: String): List = try { + wifi.scanResults.mapNotNull { scan -> + if (scan.apMldMacAddress?.toString() == mld) MloScanWidth(mld, scan.apMloLinkId, scan.frequency, + scan.timestamp / 1000, scan.channelWidth) else null + } + } catch (_: RuntimeException) { + emptyList() // Cache unavailable or permission revoked during the read. Keep the link metrics. + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/SignalScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/SignalScreen.kt index d5fdd6b..4cee9ba 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/SignalScreen.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/SignalScreen.kt @@ -68,11 +68,20 @@ import androidx.core.app.ActivityCompat import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.collectAsStateWithLifecycle import cz.netkit.app.BuildConfig +import cz.netkit.app.wifi.ExportDialog +import cz.netkit.app.wifi.rememberExportLauncher +import cz.netkit.shared.wifi.WalkStatus import cz.netkit.app.R import cz.netkit.app.net.netKindLabel +import cz.netkit.app.cellular.CellDetailViewModel +import cz.netkit.app.overview.CellDetailHost import cz.netkit.app.overview.CellularCompactCard import cz.netkit.app.overview.CellularHeroPanel import cz.netkit.app.overview.ConnectionPathCard +import cz.netkit.app.overview.DiagnosticReportDialog +import cz.netkit.app.overview.DiagnosticReportViewModel +import cz.netkit.app.overview.rememberReportSaveLauncher +import cz.netkit.app.ui.copyOnLongPress import cz.netkit.app.overview.cellQualityText import cz.netkit.app.overview.operatorText import cz.netkit.app.overview.ratText @@ -80,6 +89,7 @@ import cz.netkit.app.overview.signed import cz.netkit.app.ui.Eyebrow import cz.netkit.app.ui.GaugeRange import cz.netkit.app.ui.InfoNote +import cz.netkit.app.ui.KeepScreenOn import cz.netkit.app.ui.LiveBadge import cz.netkit.app.ui.MetricOption import cz.netkit.app.ui.MetricPicker @@ -131,6 +141,10 @@ import cz.netkit.shared.wifi.LiveSeries import cz.netkit.shared.wifi.LiveTimeline import cz.netkit.shared.wifi.RoamingEvent import cz.netkit.shared.wifi.SignalQuality +import cz.netkit.shared.wifi.MloBand +import cz.netkit.shared.wifi.MloConnection +import cz.netkit.shared.wifi.MloState +import cz.netkit.shared.wifi.MloWidth import cz.netkit.shared.wifi.WifiBand import cz.netkit.shared.wifi.WifiSecurity import cz.netkit.shared.wifi.shortBssid @@ -163,7 +177,8 @@ private enum class LiveMetric(val key: String) { SIGNAL("signal"), TRAFFIC("traf */ @Composable fun SignalScreen(viewModel: WifiLiveViewModel, modifier: Modifier = Modifier, topCard: (@Composable () -> Unit)? = null, - onOpenAbout: (() -> Unit)? = null) { + onOpenAbout: (() -> Unit)? = null, onOpenSettings: (() -> Unit)? = null, cellDetailModel: CellDetailViewModel? = null, + onRdap: ((String) -> Unit)? = null) { val state by viewModel.state.collectAsStateWithLifecycle() LifecycleResumeEffect(Unit) { viewModel.setActive(true) @@ -206,13 +221,37 @@ fun SignalScreen(viewModel: WifiLiveViewModel, modifier: Modifier = Modifier, to val metric = LiveMetric.entries[metricIndex.coerceIn(0, LiveMetric.entries.lastIndex)] val events = remember(mode, state.chartEvents, state.cellularChartEvents) { chartEventsFor(mode, state) } val requestPhone = { phoneLauncher.launch(Manifest.permission.READ_PHONE_STATE) } + // Zadání 53: expandable cell detail, requested only while an expanded detail is visible. + val cellDetailState = cellDetailModel?.state?.collectAsStateWithLifecycle()?.value + val cellDetail = if (cellDetailModel != null && cellDetailState != null) CellDetailHost( + state = cellDetailState, onShow = cellDetailModel::show, onHide = cellDetailModel::hide, + onRequestLocation = { + permissionLauncher.launch(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)) + }, + onRequestPhone = requestPhone, + onAppSettings = { openSettings(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", context.packageName, null))) }, + locationBlocked = permissionBlocked, phoneDenied = phoneDenied, + ) else null + // Walk log export (zadání 38): launchers at screen scope, so a closing dialog keeps the SAF callback. + var walkExportOpen by rememberSaveable { mutableStateOf(false) } + val launchWalkExport = rememberExportLauncher(viewModel::saveWalkExport) + val showWalk = wifiMode || state.walk.status != WalkStatus.IDLE + // Zadání 46 §4: a running walk log keeps the display on. + KeepScreenOn(state.walk.status == WalkStatus.RECORDING) + // Zadání 47: diagnostic report; its ViewModel lives with the activity, the SAF launchers at screen scope. + val reportModel = remember(activity) { + (activity as? androidx.activity.ComponentActivity)?.let { androidx.lifecycle.ViewModelProvider(it)[DiagnosticReportViewModel::class.java] } + } + val reportState = reportModel?.state?.collectAsStateWithLifecycle()?.value + val launchReportSave = rememberReportSaveLauncher { uri -> reportModel?.save(uri) } + val openReport: (() -> Unit)? = reportModel?.let { model -> { model.open(state, viewModel.activeNetworkForReport()) } } LazyColumn( modifier.fillMaxSize().testTag("signal_screen"), contentPadding = PaddingValues(start = Spacing.normal, end = Spacing.normal, bottom = Spacing.normal), verticalArrangement = Arrangement.spacedBy(Spacing.normal), ) { - item(key = "header") { Header(state, mode, onOpenAbout) } + item(key = "header") { Header(state, mode, onOpenAbout, onOpenSettings, openReport) } // Update card (D14) right under the header; it is the only card the user can close. topCard?.let { card -> item(key = "update") { card() } } items(issues, key = { "issue_${it.name}" }) { issue -> @@ -235,24 +274,31 @@ fun SignalScreen(viewModel: WifiLiveViewModel, modifier: Modifier = Modifier, to } item(key = "path") { ConnectionPathCard(state, mode, apDetail = apDetail(state.link), onRefresh = viewModel::refreshPublicIp, - onLookupChange = viewModel::setPublicIpLookup) + onLookupChange = viewModel::setPublicIpLookup, onRdap = onRdap) } when (mode) { OverviewMode.WIFI -> { item(key = "hero") { HeroPanel(state) } // A phone without any SIM on Wi-Fi: the mobile card would only say "Bez SIM". if (state.hasTelephony && state.cellular?.noSim != true) item(key = "cellular") { - CellularCompactCard(state, phoneDenied, requestPhone) + CellularCompactCard(state, phoneDenied, requestPhone, cellDetail) } } - OverviewMode.CELLULAR -> item(key = "cellular_hero") { CellularHeroPanel(state, phoneDenied, requestPhone) } - OverviewMode.ETHERNET -> if (state.hasTelephony) item(key = "cellular") { CellularCompactCard(state, phoneDenied, requestPhone) } + OverviewMode.CELLULAR -> item(key = "cellular_hero") { CellularHeroPanel(state, phoneDenied, requestPhone, cellDetail) } + OverviewMode.ETHERNET -> if (state.hasTelephony) item(key = "cellular") { + CellularCompactCard(state, phoneDenied, requestPhone, cellDetail) + } OverviewMode.NO_TELEPHONY -> item(key = "hero") { HeroPanel(state) } } + if (wifiMode) state.link?.mlo?.let { mlo -> item(key = "mlo") { MloCard(mlo) } } item(key = "chart") { ChartPanel(state, mode, metric, events, onSelect = { metricIndex = it.ordinal }, onExpand = { expanded = true }) } item(key = "latency") { LatencyPanel(state, gatewayRow = wifiMode, onChangeTarget = { targetDialog = true }) } + if (showWalk) item(key = "walk") { + WalkCard(state.walk, onStart = viewModel::startWalk, onStop = viewModel::stopWalk, onMark = viewModel::markWalk, + onExport = { walkExportOpen = true }, onDiscard = viewModel::discardWalk) + } if (state.roamingEvents.isNotEmpty()) item(key = "roaming") { RoamingPanel(state.roamingEvents) } item(key = "note") { InfoNote(stringResource(R.string.wifi_signal_sources_summary), stringResource(R.string.wifi_signal_sources_detail)) @@ -268,6 +314,17 @@ fun SignalScreen(viewModel: WifiLiveViewModel, modifier: Modifier = Modifier, to events = events, onClose = { expanded = false }, slotTimes = state.timeline.slots, ) } + if (walkExportOpen) { + ExportDialog(stringResource(R.string.walk_export_title), stringResource(R.string.walk_export_warning), + stringResource(R.string.walk_export_note), onDismiss = { walkExportOpen = false }) { format -> + if (viewModel.prepareWalkExport(format) && !launchWalkExport(format, "netkit-walk")) viewModel.walkExportLaunchFailed() + } + } + if (reportModel != null && reportState?.open == true) { + DiagnosticReportDialog(reportState, onDismiss = reportModel::close) { format, text -> + if (reportModel.prepareSave(text) && !launchReportSave(format)) reportModel.saveLaunchFailed() + } + } if (targetDialog) { TargetDialog( current = state.internetLatency.target ?: LIVE_DEFAULT_INTERNET_TARGET, @@ -296,7 +353,8 @@ private val NON_WIFI_HIDDEN_ISSUES = setOf(WifiLiveIssue.NO_WIFI, WifiLiveIssue. * or operator, when known), no network "Bez připojení". */ @Composable -private fun Header(state: WifiLiveState, mode: OverviewMode, onOpenAbout: (() -> Unit)?) { +private fun Header(state: WifiLiveState, mode: OverviewMode, onOpenAbout: (() -> Unit)?, onOpenSettings: (() -> Unit)?, + onReport: (() -> Unit)? = null) { val link = state.link val kind = state.network?.kind val wifiDetail = link?.let { @@ -337,13 +395,16 @@ private fun Header(state: WifiLiveState, mode: OverviewMode, onOpenAbout: (() -> ScreenHeader(title, subtitle, trailing = { if (state.running) LiveBadge(stringResource(R.string.wifi_signal_live, (state.sampleIntervalMs / 1_000L).toInt().coerceAtLeast(1))) else Tag(stringResource(R.string.wifi_signal_paused)) - onOpenAbout?.let { HeaderMenu(it) } + if (onOpenAbout != null || onOpenSettings != null || onReport != null) HeaderMenu(onOpenAbout, onOpenSettings, onReport) }) } -/** The one header action of Přehled: a menu with "O aplikaci" (zadání 21); no extra tab. */ +/** + * The one header action of Přehled: a menu with "Nastavení" (zadání 46), "Diagnostický report" (zadání 47) + * and "O aplikaci" (zadání 21); no extra tab. + */ @Composable -private fun HeaderMenu(onOpenAbout: () -> Unit) { +private fun HeaderMenu(onOpenAbout: (() -> Unit)?, onOpenSettings: (() -> Unit)?, onReport: (() -> Unit)?) { val colors = NetKitTheme.colors var open by remember { mutableStateOf(false) } Box { @@ -351,7 +412,21 @@ private fun HeaderMenu(onOpenAbout: () -> Unit) { DropdownMenu(expanded = open, onDismissRequest = { open = false }, shape = NetKitShape.nested, containerColor = colors.surface2, tonalElevation = 0.dp, modifier = Modifier.semantics { testTagsAsResourceId = BuildConfig.DEBUG }) { - DropdownMenuItem( + onOpenSettings?.let { openSettings -> + DropdownMenuItem( + text = { Text(stringResource(R.string.settings_title), style = NetKitType.body, color = colors.text) }, + onClick = { open = false; openSettings() }, + leadingIcon = { Icon(NetKitIcons.Settings, null, Modifier.size(18.dp), tint = colors.muted) }, + modifier = Modifier.testTag("overview_menu_settings"), + ) + } + if (onReport != null) DropdownMenuItem( + text = { Text(stringResource(R.string.report_menu), style = NetKitType.body, color = colors.text) }, + onClick = { open = false; onReport() }, + leadingIcon = { Icon(NetKitIcons.Document, null, Modifier.size(18.dp), tint = colors.muted) }, + modifier = Modifier.testTag("overview_menu_report"), + ) + if (onOpenAbout != null) DropdownMenuItem( text = { Text(stringResource(R.string.about_title), style = NetKitType.body, color = colors.text) }, onClick = { open = false; onOpenAbout() }, leadingIcon = { Icon(NetKitIcons.Info, null, Modifier.size(18.dp), tint = colors.muted) }, @@ -447,9 +522,9 @@ private fun HeroPanel(state: WifiLiveState) { StatTile(stringResource(R.string.wifi_signal_phy), link?.rxLinkMbps?.toString() ?: dash, unit = stringResource(R.string.wifi_signal_phy_tx_unit, link?.txLinkMbps?.toString() ?: dash)), StatTile(stringResource(R.string.wifi_signal_ipv4), link?.ipv4Address ?: dash, weight = 1.45f, - monospace = link?.ipv4Address != null), + monospace = link?.ipv4Address != null, copyValue = link?.ipv4Address, testTag = "overview_copy_ipv4"), StatTile(stringResource(R.string.wifi_signal_gateway), link?.gatewayIpv4 ?: dash, weight = 1.45f, - monospace = link?.gatewayIpv4 != null), + monospace = link?.gatewayIpv4 != null, copyValue = link?.gatewayIpv4, testTag = "overview_copy_gateway"), )) } } @@ -462,7 +537,8 @@ private fun AccessPointInfo(link: LiveLink?, centered: Boolean, modifier: Modifi verticalArrangement = Arrangement.spacedBy(Spacing.tiny)) { Eyebrow(stringResource(R.string.wifi_signal_access_point)) val bssid = link?.bssid - if (bssid != null) Text(bssid.uppercase(Locale.ROOT), style = NetKitType.address, color = colors.text, textAlign = align) + if (bssid != null) Text(bssid.uppercase(Locale.ROOT), Modifier.copyOnLongPress(bssid.uppercase(Locale.ROOT), sensitive = true) + .testTag("overview_copy_bssid"), style = NetKitType.address, color = colors.text, textAlign = align) else Text(stringResource(R.string.wifi_signal_bssid_unknown), style = NetKitType.body, color = colors.muted, textAlign = align) val standard = link?.wifiStandard?.let { standardText(it, link.band) } val security = link?.security?.takeUnless { it == WifiSecurity.UNKNOWN }?.let { stringResource(securityText(it)) } @@ -477,6 +553,38 @@ private fun AccessPointInfo(link: LiveLink?, centered: Boolean, modifier: Modifi } } +@Composable +internal fun MloCard(connection: MloConnection) { + val dash = stringResource(R.string.wifi_signal_no_value) + SectionCard(title = stringResource(R.string.wifi_mlo_title)) { + connection.apMldAddress?.let { + Text(stringResource(R.string.wifi_mlo_address, it), style = NetKitType.address) + } + for (link in connection.links) { + val band = when (link.band) { + MloBand.GHZ_2_4 -> stringResource(R.string.wifi_signal_band_24) + MloBand.GHZ_5 -> stringResource(R.string.wifi_signal_band_5) + MloBand.GHZ_6 -> stringResource(R.string.wifi_signal_band_6) + MloBand.GHZ_60 -> stringResource(R.string.wifi_mlo_band_60) + null -> dash + } + val state = stringResource(when (link.state) { + MloState.ACTIVE -> R.string.wifi_mlo_active + MloState.IDLE -> R.string.wifi_mlo_idle + MloState.UNASSOCIATED -> R.string.wifi_mlo_unassociated + MloState.UNKNOWN -> R.string.wifi_signal_no_value + }) + val width = link.advertisedWidth?.let { + if (it == MloWidth.W80_PLUS_80) stringResource(R.string.wifi_width_80_plus_80_short) + else stringResource(R.string.wifi_width_mhz, it.mhz) + } ?: dash + Text(stringResource(R.string.wifi_mlo_link, link.id, state, band, link.channel?.toString() ?: dash, + link.rssiDbm?.let { stringResource(R.string.wifi_mlo_dbm, it) } ?: dash, width), + Modifier.testTag("mlo_link_${link.id}"), style = NetKitType.body) + } + } +} + @Composable private fun bandText(band: WifiBand?): String? = when (band) { WifiBand.GHZ_2_4 -> stringResource(R.string.wifi_signal_band_24) @@ -661,7 +769,7 @@ private fun chartDescription(state: WifiLiveState, mode: OverviewMode, metric: L /** * Latency on the active network: gateway (Wi-Fi only, [gatewayRow]), internet target, DNS with * the resolver (O-5), packet loss and jitter. Notes (address, name) sit on a second line under - * the label in mono `dim`. + * the label in `muted`. */ @Composable private fun LatencyPanel(state: WifiLiveState, gatewayRow: Boolean, onChangeTarget: () -> Unit) { @@ -679,7 +787,8 @@ private fun LatencyPanel(state: WifiLiveState, gatewayRow: Boolean, onChangeTarg ProbeRow(stringResource(R.string.wifi_signal_latency_internet), internet, unitMs, showDivider = gatewayRow) val dnsMs = dns.lastMs.takeIf { dns.status == LiveDnsStatus.OK } LiveRow(stringResource(R.string.wifi_signal_dns_label), listOfNotNull(resolverNote(dns.resolver), monoNote(dns.name)), - value = dnsMs, unit = unitMs, status = if (dnsMs == null) dnsStatusText(dns) else null) + value = dnsMs, unit = unitMs, status = if (dnsMs == null) dnsStatusText(dns) else null, + modifier = Modifier.copyOnLongPress(resolverCopy(dns.resolver)).testTag("overview_copy_dns")) val gatewayStats = gateway.series.stats val internetStats = internet.series.stats val targets = textNote(stringResource(if (gatewayRow) R.string.wifi_signal_pair_targets else R.string.wifi_signal_internet_target)) @@ -701,7 +810,7 @@ private fun ProbeRow(label: String, latency: LiveLatency, unit: String, showDivi liveProbeStatusText(latency.status)?.let { stringResource(it) } ?: stringResource(R.string.wifi_signal_no_value) } else null LiveRow(label, listOfNotNull(latency.target?.let(::monoNote)), value, unit, status, - if (latency.status == LiveProbeStatus.LOST) Tone.ERR else Tone.NEUTRAL, showDivider) + statusTone = if (latency.status == LiveProbeStatus.LOST) Tone.ERR else Tone.NEUTRAL, showDivider = showDivider) } /** "192.168.0.1" (mono) or "Soukromé DNS · dns.example" (host in mono); `null` when unknown. */ @@ -719,6 +828,13 @@ private fun resolverNote(note: DnsResolverNote): AnnotatedString? = when (note) DnsResolverNote.Unknown -> null } +/** The resolver address (or Private DNS host) a long press on the DNS row copies (zadání 47). */ +private fun resolverCopy(note: DnsResolverNote): String? = when (note) { + is DnsResolverNote.Resolver -> note.address + is DnsResolverNote.PrivateDns -> note.host + DnsResolverNote.Unknown -> null +} + /** Mono span at 0.92 × the note size (machine values inside a sans note). */ private fun monoSpan(): SpanStyle { val mono = NetKitType.addressFor(NetKitType.label) @@ -732,13 +848,13 @@ private fun textNote(text: String): AnnotatedString = AnnotatedString(text) /** * Key/value row like [cz.netkit.app.ui.KeyValueRow] (9 dp above and below, `divider` on top): * the label on the first line and its [notes] (address, resolver, queried name) each on its own - * line under it in `dim` (machine values mono). The animated value (or [status]) sits on the + * line under it in `muted` (machine values mono). The animated value (or [status]) sits on the * right, baseline-aligned with the label, at most [LIVE_ROW_VALUE_SHARE] of the width; the 12 dp * gap to the label column is kept at any width and font scale. */ @Composable private fun LiveRow(label: String, notes: List, value: Double?, unit: String?, status: String?, - statusTone: Tone = Tone.NEUTRAL, showDivider: Boolean = true) { + modifier: Modifier = Modifier, statusTone: Tone = Tone.NEUTRAL, showDivider: Boolean = true) { val colors = NetKitTheme.colors val divider = colors.divider val valueStyle = NetKitType.body.copy(fontWeight = FontWeight.SemiBold) @@ -746,7 +862,7 @@ private fun LiveRow(label: String, notes: List, value: Double?, content = { Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { Text(label, style = NetKitType.body, color = colors.muted) - notes.forEach { Text(it, style = NetKitType.label, color = colors.dim) } + notes.forEach { Text(it, style = NetKitType.label, color = colors.muted) } } if (status != null || value == null) { Text(status ?: stringResource(R.string.wifi_signal_no_value), style = valueStyle, @@ -758,7 +874,7 @@ private fun LiveRow(label: String, notes: List, value: Double?, } } }, - modifier = Modifier.fillMaxWidth() + modifier = modifier.fillMaxWidth() .then(if (showDivider) Modifier.drawBehind { drawLine(divider, Offset(0f, 0f), Offset(size.width, 0f), 1.dp.toPx()) } else Modifier) .padding(top = if (showDivider) 9.dp else 0.dp, bottom = 9.dp) .semantics(mergeDescendants = true) {}, diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WalkCard.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WalkCard.kt new file mode 100644 index 0000000..c41b5d4 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WalkCard.kt @@ -0,0 +1,180 @@ +package cz.netkit.app.wifi.live + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import cz.netkit.app.R +import cz.netkit.app.ui.KeyValue +import cz.netkit.app.ui.KeyValueRows +import cz.netkit.app.ui.LiveBadge +import cz.netkit.app.ui.NeutralButton +import cz.netkit.app.ui.NetKitIcons +import cz.netkit.app.ui.PrimaryButton +import cz.netkit.app.ui.SectionCard +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.StatusBanner +import cz.netkit.app.ui.StatusKind +import cz.netkit.app.ui.TonalButton +import cz.netkit.app.ui.Tone +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.shared.wifi.WALK_MARK_MAX_LENGTH +import cz.netkit.shared.wifi.WALK_MAX_DURATION_MS +import cz.netkit.shared.wifi.WALK_MAX_SAMPLES +import cz.netkit.shared.wifi.WalkMarkResult +import cz.netkit.shared.wifi.WalkStatus +import cz.netkit.shared.wifi.WalkStopReason +import cz.netkit.shared.wifi.WalkSummary +import java.text.NumberFormat + +/** "1:05:09" / "5:09" for a duration in milliseconds. */ +internal fun walkDurationText(ms: Long): String { + val total = (ms / 1_000).coerceAtLeast(0) + val hours = total / 3_600 + val minutes = total / 60 % 60 + val seconds = total % 60 + return if (hours > 0) "%d:%02d:%02d".format(hours, minutes, seconds) else "%d:%02d".format(minutes, seconds) +} + +/** + * "Záznam obchůzky" card of the Overview (zadání 38 §2.4), stateless: idle → start; recording → + * elapsed time, samples, "Značka" and stop; stopped → summary, export and discard. The mark + * dialog limits the text to [WALK_MARK_MAX_LENGTH] characters. + */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun WalkCard( + walk: WalkUiState, + onStart: () -> Unit, + onStop: () -> Unit, + onMark: (String) -> WalkMarkResult, + onExport: () -> Unit, + onDiscard: () -> Unit, + modifier: Modifier = Modifier, +) { + val colors = NetKitTheme.colors + var markOpen by rememberSaveable { mutableStateOf(false) } + var markAdded by rememberSaveable { mutableStateOf(false) } + val summary = walk.summary + Column(modifier.testTag("walk_card")) { SectionCard(stringResource(R.string.walk_title), trailing = { + if (walk.status == WalkStatus.RECORDING) LiveBadge(walkDurationText(summary?.durationMs ?: 0)) + }) { + Column(verticalArrangement = Arrangement.spacedBy(Spacing.medium)) { + when (walk.status) { + WalkStatus.IDLE -> { + Text(stringResource(R.string.walk_intro), style = NetKitType.body, color = colors.muted) + PrimaryButton(stringResource(R.string.walk_start), onStart, Modifier.testTag("walk_start"), small = true) + } + WalkStatus.RECORDING -> { + Text(pluralStringResource(R.plurals.walk_recording, summary?.samples ?: 0, walkDurationText(summary?.durationMs ?: 0), + summary?.samples ?: 0), + Modifier.testTag("walk_recording"), style = NetKitType.body, color = colors.text) + if (markAdded) Text(stringResource(R.string.walk_mark_added), style = NetKitType.label, color = colors.ok) + FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + TonalButton(stringResource(R.string.walk_mark), { markAdded = false; markOpen = true }, Modifier.testTag("walk_mark"), + icon = NetKitIcons.Add, small = true) + NeutralButton(stringResource(R.string.walk_stop), onStop, Modifier.testTag("walk_stop"), small = true) + } + } + WalkStatus.STOPPED -> { + StatusBanner(stringResource(when (summary?.stopReason) { + WalkStopReason.PAUSED -> R.string.walk_stopped_paused + WalkStopReason.SAMPLE_LIMIT, WalkStopReason.DURATION_LIMIT -> R.string.walk_stopped_limit + else -> R.string.walk_stopped_user + }), if (summary?.stopReason == WalkStopReason.USER) StatusKind.INFO else StatusKind.WARNING) + summary?.let { WalkSummaryRows(it) } + when (walk.exportNotice) { + WalkExportNotice.SAVED -> StatusBanner(stringResource(R.string.wifi_export_saved), StatusKind.INFO) + WalkExportNotice.FAILED -> StatusBanner(stringResource(R.string.wifi_export_failed), StatusKind.ERROR) + null -> Unit + } + FlowRow(horizontalArrangement = Arrangement.spacedBy(Spacing.small), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + PrimaryButton(stringResource(R.string.walk_export), onExport, Modifier.testTag("walk_export"), + icon = NetKitIcons.Download, small = true, enabled = (summary?.samples ?: 0) > 0) + NeutralButton(stringResource(R.string.walk_new), onStart, Modifier.testTag("walk_new"), small = true) + NeutralButton(stringResource(R.string.walk_discard), onDiscard, Modifier.testTag("walk_discard"), small = true) + } + } + } + Text(stringResource(R.string.walk_precision), style = NetKitType.label, color = colors.muted) + val number = NumberFormat.getIntegerInstance() + Text(stringResource(R.string.walk_limits, number.format(WALK_MAX_DURATION_MS / 3_600_000), number.format(WALK_MAX_SAMPLES)), + style = NetKitType.label, color = colors.muted) + } + } } + if (markOpen) WalkMarkDialog(onDismiss = { markOpen = false }, onSubmit = { text -> + when (onMark(text)) { + WalkMarkResult.ADDED -> { markOpen = false; markAdded = true; true } + WalkMarkResult.NOT_RECORDING -> { markOpen = false; true } + WalkMarkResult.EMPTY, WalkMarkResult.TOO_LONG -> false + } + }) +} + +@Composable +private fun WalkSummaryRows(summary: WalkSummary) { + val unknown = stringResource(R.string.walk_value_unknown) + KeyValueRows(listOf( + KeyValue(stringResource(R.string.walk_summary_duration), walkDurationText(summary.durationMs)), + KeyValue(stringResource(R.string.walk_summary_samples), summary.samples.toString()), + KeyValue(stringResource(R.string.walk_summary_roamings), summary.roamings.toString(), + if (summary.roamings > 0) Tone.ACCENT else Tone.NEUTRAL), + KeyValue(stringResource(R.string.walk_summary_channel_changes), summary.channelChanges.toString()), + KeyValue(stringResource(R.string.walk_summary_min_rssi), summary.minRssiDbm?.let { stringResource(R.string.wifi_dbm_value, it) } ?: unknown), + KeyValue(stringResource(R.string.walk_summary_ping_loss), + stringResource(R.string.walk_summary_ping_loss_value, summary.gatewayLost, summary.gatewaySent), + if (summary.gatewayLost > 0) Tone.WARN else Tone.NEUTRAL), + KeyValue(stringResource(R.string.walk_summary_marks), summary.marks.toString()), + ), Modifier.testTag("walk_summary")) +} + +/** Text of one place mark; [onSubmit] returns whether the dialog may close. */ +@Composable +private fun WalkMarkDialog(onDismiss: () -> Unit, onSubmit: (String) -> Boolean) { + val colors = NetKitTheme.colors + var text by rememberSaveable { mutableStateOf("") } + var invalid by rememberSaveable { mutableStateOf(false) } + fun submit() { invalid = !onSubmit(text) } + AlertDialog( + onDismissRequest = onDismiss, + containerColor = colors.surface, + title = { Text(stringResource(R.string.walk_mark_title), style = NetKitType.panelTitle, color = colors.text) }, + text = { + OutlinedTextField( + value = text, + onValueChange = { text = it.take(WALK_MARK_MAX_LENGTH); invalid = false }, + modifier = Modifier.fillMaxWidth().testTag("walk_mark_input"), + placeholder = { Text(stringResource(R.string.walk_mark_hint)) }, + singleLine = true, + isError = invalid, + supportingText = { + Text(if (invalid) stringResource(R.string.walk_mark_empty) else "${text.length}/$WALK_MARK_MAX_LENGTH") + }, + keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), + keyboardActions = KeyboardActions(onDone = { submit() }), + ) + }, + confirmButton = { + TextButton(::submit, Modifier.testTag("walk_mark_add")) { Text(stringResource(R.string.walk_mark_add), color = colors.accent) } + }, + dismissButton = { TextButton(onDismiss) { Text(stringResource(R.string.wifi_export_cancel), color = colors.muted) } }, + ) +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveState.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveState.kt index e67e518..31a1266 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveState.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveState.kt @@ -12,6 +12,9 @@ import cz.netkit.shared.wifi.LiveSeries import cz.netkit.shared.wifi.LiveTimeline import cz.netkit.shared.wifi.RoamingEvent import cz.netkit.shared.wifi.SignalQuality +import cz.netkit.shared.wifi.WalkStatus +import cz.netkit.shared.wifi.WalkSummary +import cz.netkit.shared.wifi.MloConnection import cz.netkit.shared.wifi.WifiBand import cz.netkit.shared.wifi.WifiSecurity @@ -91,8 +94,22 @@ data class WifiLiveState( val cellularSignalDbm: LiveSeries = LiveSeries(), val cellularChartEvents: List = emptyList(), val publicIp: PublicIpUiState = PublicIpUiState(), + val walk: WalkUiState = WalkUiState(), ) +/** + * "Záznam obchůzky" (zadání 38 §2.4): [status], the running or final [summary] and the start + * (elapsedRealtime) for the elapsed-time label. The samples themselves stay in the ViewModel. + */ +data class WalkUiState( + val status: WalkStatus = WalkStatus.IDLE, + val startedElapsedMs: Long? = null, + val summary: WalkSummary? = null, + val exportNotice: WalkExportNotice? = null, +) + +typealias WalkExportNotice = cz.netkit.app.wifi.ExportNotice + /** * The active network as the Overview shows it (public projection of the internal * `ActiveNetworkInfo`). [networkHandle] identifies the network while it exists. @@ -150,6 +167,7 @@ data class LiveLink( val gatewayIpv4: String?, val wifiStandard: LiveWifiStandard? = null, val security: WifiSecurity? = null, + val mlo: MloConnection? = null, ) /** Wi-Fi standard of the connected link (`WifiInfo.getWifiStandard`). */ diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt index 7a2acdb..63e3384 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt @@ -57,6 +57,15 @@ import cz.netkit.shared.wifi.usableBssid import cz.netkit.shared.wifi.validLiveDnsName import cz.netkit.shared.wifi.validLiveInternetTarget import cz.netkit.shared.wifi.validRssiDbm +import cz.netkit.shared.wifi.WalkMarkResult +import cz.netkit.shared.wifi.WalkRecorder +import cz.netkit.shared.wifi.WalkStatus +import cz.netkit.shared.wifi.WalkStopReason +import cz.netkit.shared.wifi.WifiExportFormat +import cz.netkit.shared.wifi.walkExportText +import cz.netkit.app.wifi.ExportSession +import cz.netkit.app.wifi.writeExportDocument +import android.net.Uri import java.net.InetAddress import java.util.concurrent.Executor import kotlin.coroutines.resume @@ -123,6 +132,8 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application private val cellularMonitor = CellularMonitor(application) private val publicIpRepository = PublicIpRepository(application) private val hasTelephony = application.packageManager.hasSystemFeature(PackageManager.FEATURE_TELEPHONY) + /** Network status widget snapshot (zadání 37): foreground values only, throttled by the service. */ + private val netStatus = (application as? cz.netkit.app.wol.NetKitApplication)?.netStatus private val direct = Executor { it.run() } private val _state = MutableStateFlow(WifiLiveState()) @@ -184,6 +195,12 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application /** Bumped by every lookup request; only the newest one may change the public IP state. */ private var publicIpGeneration = 0 + /** Zadání 38 §2.4: walk log, fed by [applyLink] and the gateway [latencyLoop]; memory only. */ + private val walk = WalkRecorder() + private var walkUi = WalkUiState() + private var walkUiRevision = -1L + private val walkExport = ExportSession { uri, text -> writeExportDocument(app, uri, text) } + init { viewModelScope.launch { publicIpEnabled = withContext(Dispatchers.IO) { publicIpRepository.isLookupEnabled() } @@ -199,6 +216,8 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application */ fun setActive(active: Boolean) { if (!active) { + // No background sampling: leaving the screen or the app ends a running walk log. + walk.stop(SystemClock.elapsedRealtime(), WalkStopReason.PAUSED) session?.cancel() session = null cellularJob?.cancel() @@ -208,6 +227,7 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application publicIpGeneration++ publicIpLoading = false snapshot = null + link = link?.copy(mlo = null) linkKnown = false activeKnown = false publish() @@ -289,10 +309,19 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application /** Switches the public IP lookup on or off (stored); off stops a running lookup and forgets the result. */ fun setPublicIpLookup(enabled: Boolean) { - if (enabled == publicIpEnabled && publicIpSettingLoaded) return + if (!publicIpSettingLoaded || enabled == publicIpEnabled) return publicIpEnabled = enabled - publicIpSettingLoaded = true - viewModelScope.launch(Dispatchers.IO) { publicIpRepository.setLookupEnabled(enabled) } + // The preferences have loaded. apply() publishes to readers (including RDAP) now + // and queues persistence; rapid menu toggles retain their UI order. + publicIpRepository.setLookupEnabled(enabled) + // Zadání 37, revize kolo 1: the widget copy is deleted only after the setting is stored, so a + // snapshot write that checks privacy afterwards (under the same write lock) sees "off" too. + val status = netStatus + if (!enabled && status != null) { + viewModelScope.launch(Dispatchers.IO) { + try { status.clearPublicIp() } catch (e: CancellationException) { throw e } catch (_: Exception) { } + } + } if (!enabled) { publicIpJob?.cancel() publicIpJob = null @@ -300,6 +329,7 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application publicIpLoading = false publicIpInfo = null publicIpKey = null + // The widget keeps no copy once the lookup is off (zadání 37 §2.5): deleted above, after the setting. } else { requestPublicIp(force = false, settle = false) } @@ -309,6 +339,9 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application /** "Obnovit": looks the public IP up again on the current network, ignoring the cache. */ fun refreshPublicIp() = requestPublicIp(force = true, settle = false) + /** Zadání 47: the active network as last reported, for the diagnostic report (main thread). */ + internal fun activeNetworkForReport(): ActiveNetworkInfo? = activeNetwork + /** Cache key of the current active network (type + SSID / data subscription, else the network handle). */ private fun currentNetworkKey(): String? { val info = activeNetwork ?: return null @@ -331,6 +364,7 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application if (info == null) { publicIpLoading = false; publish(); return@launch } if (!force) publicIpRepository.cached(key)?.let { cached -> publicIpInfo = cached + offerWidgetPublicIp(cached) publicIpLoading = false publish() return@launch @@ -346,6 +380,7 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application } if (generation == publicIpGeneration) { publicIpInfo = result + result?.let(::offerWidgetPublicIp) publicIpLoading = false publish() } @@ -385,6 +420,58 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application return true } + // --- Walk log (zadání 38 §2.4) ------------------------------------------------------------ + + /** Starts a new walk log (discarding a previous one); only while sampling runs. */ + fun startWalk() { + if (session?.isActive != true) return + walkExport.clear() + walk.start(SystemClock.elapsedRealtime(), System.currentTimeMillis()) + publish() + } + + fun stopWalk() { + walk.stop(SystemClock.elapsedRealtime(), WalkStopReason.USER) + publish() + } + + /** Adds a place mark to the running walk log. */ + fun markWalk(text: String): WalkMarkResult = walk.mark(SystemClock.elapsedRealtime(), text).also { publish() } + + fun discardWalk() { + walk.clear() + walkExport.clear() + publish() + } + + /** Serializes the finished walk log ([walkExportText]); false while recording or without data. */ + fun prepareWalkExport(format: WifiExportFormat): Boolean = + walkExport.prepare(walkExportText(walk.snapshot(SystemClock.elapsedRealtime()), format)).also { publish() } + + fun walkExportLaunchFailed() { + walkExport.launchFailed() + publish() + } + + /** SAF result for the walk export; null = picker cancelled. */ + fun saveWalkExport(uri: Uri?) { + viewModelScope.launch { + walkExport.save(uri) + publish() + } + } + + private fun walkState(): WalkUiState { + val now = SystemClock.elapsedRealtime() + // The running summary's duration moves with time; recompute while recording, else on change only. + if (walk.revision != walkUiRevision || walk.status == WalkStatus.RECORDING || walkUi.exportNotice != walkExport.notice.value) { + walkUiRevision = walk.revision + val log = walk.snapshot(now) + walkUi = WalkUiState(log.status, log.startedElapsedMs, log.summary, walkExport.notice.value) + } + return walkUi + } + /** Empties all series, statistics, roaming and chart events; sampling state and targets stay. */ fun clear() { listOf(signal, rxLink, txLink, deviceRx, deviceTx, gateway, internet, dnsSeries, cellSignal).forEach { it.clear() } @@ -409,12 +496,14 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application // --- Loops (run on the main dispatcher; blocking work hops to IO) --------------------------- private suspend fun linkLoop() { + val mloReader = MloReader(wifiManager) while (true) { val started = SystemClock.elapsedRealtime() val current = snapshot val generation = clearGeneration - val reading = withContext(Dispatchers.IO) { readLink(current, started) } + val reading = withContext(Dispatchers.IO) { readLink(current, started, mloReader) } if (generation == clearGeneration) applyLink(started, reading) + offerWidgetLink(current, reading) publish() delay(liveTickDelayMs(started, SystemClock.elapsedRealtime())) } @@ -458,6 +547,11 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application series.add(started, value) } if (gatewayProbe) gatewayStatus = status else internetStatus = status + if (gatewayProbe && status == LiveProbeStatus.OK && value != null) + netStatus?.offerGateway(System.currentTimeMillis(), value) + if (gatewayProbe && (status == LiveProbeStatus.OK || status == LiveProbeStatus.LOST)) + // Completion time, not the probe start: a timeout is known only ~1 s later. + walk.observeGateway(SystemClock.elapsedRealtime(), value, lost = status == LiveProbeStatus.LOST) events.observeProbe(probe, started, target, lost = status == LiveProbeStatus.LOST) publish() } @@ -493,20 +587,20 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application ) /** Blocking: binder calls to WifiManager/LocationManager and TrafficStats. */ - private fun readLink(current: WifiLinkSnapshot?, elapsedMs: Long): LinkReading { + private fun readLink(current: WifiLinkSnapshot?, elapsedMs: Long, mloReader: MloReader): LinkReading { val permissionMissing = ContextCompat.checkSelfPermission(app, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED - val locationDisabled = try { - !app.getSystemService(LocationManager::class.java).isLocationEnabled - } catch (_: Exception) { false } + val locationEnabled = try { + app.getSystemService(LocationManager::class.java).isLocationEnabled + } catch (_: Exception) { null } val link = current?.let { snap -> - try { liveLink(snap, elapsedMs) } catch (_: Exception) { null } + try { liveLink(snap, elapsedMs, mloReader, !permissionMissing && locationEnabled == true) } catch (_: Exception) { null } } - return LinkReading(link, TrafficStats.getTotalRxBytes(), TrafficStats.getTotalTxBytes(), permissionMissing, locationDisabled) + return LinkReading(link, TrafficStats.getTotalRxBytes(), TrafficStats.getTotalTxBytes(), permissionMissing, locationEnabled == false) } @Suppress("DEPRECATION") // connectionInfo: only source below API 31, fresher radio values above (see selectLiveRadioSource). - private fun liveLink(snap: WifiLinkSnapshot, elapsedMs: Long): LiveLink { + private fun liveLink(snap: WifiLinkSnapshot, elapsedMs: Long, mloReader: MloReader, locationAllowed: Boolean): LiveLink { val callbackInfo = snap.info val legacy: WifiInfo? = try { wifiManager.connectionInfo } catch (_: Exception) { null } val radio = when (selectLiveRadioSource(Build.VERSION.SDK_INT, callbackInfo != null, callbackInfo?.bssid, @@ -532,6 +626,7 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application gatewayIpv4 = snap.gatewayIpv4, wifiStandard = (radio ?: identity)?.let(::liveWifiStandard), security = (radio ?: identity)?.let(::liveSecurity), + mlo = readLiveMlo(radio, callbackInfo) { info -> mloReader.read(info, locationAllowed, elapsedMs) }, ) } @@ -577,6 +672,7 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application val roam = if (reading.link != null) roaming.observe(started, reading.link.bssid, reading.link.frequencyMhz) else roaming.observe(started, null, null) events.observeLink(started, reading.link?.bssid, reading.link?.channel, roam) + reading.link.let { l -> walk.sample(started, l?.rssiDbm, l?.bssid, l?.channel, l?.rxLinkMbps, l?.txLinkMbps, roam) } // The mobile gauge's SIM, sampled on the same 1 Hz timeline (the modem reports every few seconds). val sims = cellular?.sims.orEmpty() cellSignal.add(started, primaryDbm(primarySim(sims)?.signal)?.toDouble()) @@ -590,6 +686,25 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application if (primed || rate != null) series.add(started, rate) } + /** Zadání 37: the link of this tick for the widget; no Wi-Fi network = "Bez Wi-Fi". SSID only if readable. */ + private fun offerWidgetLink(current: WifiLinkSnapshot?, reading: LinkReading) { + val status = netStatus ?: return + val now = System.currentTimeMillis() + val link = reading.link + when { + link != null -> status.offerLink(now, link.frequencyMhz, link.rssiDbm, link.rxLinkMbps, link.txLinkMbps, link.ssid) + current == null && linkKnown && !monitorFailed -> status.offerNoWifi(now) + } + } + + /** Zadání 37 §2.5: the public IP shown here (lookup enabled), timed when it was looked up. */ + private fun offerWidgetPublicIp(info: PublicIpInfo) { + val address = info.v4?.address ?: info.v6?.address ?: return + if (!publicIpEnabled) return + val at = System.currentTimeMillis() - (SystemClock.elapsedRealtime() - info.fetchedAtMs).coerceAtLeast(0) + netStatus?.offerPublicIp(at, address) + } + private class EchoResult(val status: LiveProbeStatus, val milliseconds: Double?) private suspend fun echo(network: Network, target: String): EchoResult = try { @@ -693,6 +808,7 @@ class WifiLiveViewModel(application: Application) : AndroidViewModel(application enabled = publicIpEnabled, settingLoaded = publicIpSettingLoaded, loading = publicIpLoading, info = publicIpInfo.takeIf { publicIpKey != null && publicIpKey == currentNetworkKey() }, ), + walk = walkState(), ) } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wol/AndroidNetwork.kt b/androidApp/src/main/kotlin/cz/netkit/app/wol/AndroidNetwork.kt index e4bf21c..29b532e 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wol/AndroidNetwork.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wol/AndroidNetwork.kt @@ -7,7 +7,7 @@ import android.net.Network import android.net.NetworkCapabilities import android.os.CancellationSignal import cz.netkit.shared.wol.NetworkInfoProvider -import cz.netkit.shared.wol.PacketSender +import cz.netkit.shared.wol.GuardedPacketSender import cz.netkit.shared.wol.WifiNetworkHandle import cz.netkit.shared.wol.WifiNetworkInfo import java.io.IOException @@ -41,7 +41,7 @@ class AndroidNetworkInfoProvider(context: Context) : NetworkInfoProvider { } } -class AndroidPacketSender(context: Context) : PacketSender by BoundPacketSender(AndroidUdpPlatform(context)) +class AndroidPacketSender(context: Context) : GuardedPacketSender by BoundPacketSender(AndroidUdpPlatform(context)) private class AndroidUdpPlatform(context: Context) : UdpPlatform { private val manager = context.getSystemService(ConnectivityManager::class.java) diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wol/DeviceStore.kt b/androidApp/src/main/kotlin/cz/netkit/app/wol/DeviceStore.kt index c852ff3..dbd3377 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wol/DeviceStore.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wol/DeviceStore.kt @@ -1,5 +1,6 @@ package cz.netkit.app.wol +import cz.netkit.app.backup.ConfigFile import android.content.Context import androidx.datastore.core.CorruptionException import androidx.datastore.core.DataStore @@ -89,7 +90,7 @@ class AndroidDeviceStore( Unit }, ) : WolDeviceStore { - constructor(context: Context) : this(context, context.filesDir.resolve("datastore/wol-devices.json")) + constructor(context: Context) : this(context, ConfigFile.WOL.resolve(context)) constructor(context: Context, file: File) : this(file, CoroutineScope(SupervisorJob() + Dispatchers.IO)) private val mutex = Mutex() diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wol/UdpTransport.kt b/androidApp/src/main/kotlin/cz/netkit/app/wol/UdpTransport.kt index bac963d..280e798 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wol/UdpTransport.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wol/UdpTransport.kt @@ -2,7 +2,8 @@ package cz.netkit.app.wol import cz.netkit.shared.wol.PacketSendException import cz.netkit.shared.wol.SendFailure -import cz.netkit.shared.wol.PacketSender +import cz.netkit.shared.wol.GuardedPacketSender +import cz.netkit.shared.wol.PacketWriteGuard import cz.netkit.shared.wol.WifiNetworkHandle import cz.netkit.shared.wol.parseIpv4 import java.io.Closeable @@ -19,6 +20,10 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.CoroutineStart internal data class NetworkChoice(val handle: T, val wifi: Boolean, val vpn: Boolean) @@ -51,9 +56,19 @@ internal class BoundPacketSender( private val platform: UdpPlatform, private val io: CoroutineDispatcher = Dispatchers.IO, private val timeoutMillis: Long = 5_000, -) : PacketSender { +) : GuardedPacketSender { override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray) { + sendUdp(network, host, port, payload) { write -> write(); true } + } + + /** + * DNS, socket open, broadcast and bind happen first; [guard] then decides and performs the write as + * its last step (the widget does so inside its state transaction). False = the packet was skipped. + */ + override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray, + guard: PacketWriteGuard): Boolean { require(port in 1..65535) + var written = false try { val completed = withTimeoutOrNull(timeoutMillis) { withContext(io) { @@ -62,34 +77,41 @@ internal class BoundPacketSender( platform.resolve(network, host) } catch (error: CancellationException) { throw error } catch (error: Exception) { throw PacketSendException(SendFailure.DNS, error) } - send(network, target, port, payload) + val socket = prepare(network) + try { + coroutineScope { + // Cancellation (timeout, stop) closes the socket, which aborts a blocked write. + // UNDISPATCHED: registered before the write starts, so it can never miss a cancellation. + val closer = launch(start = CoroutineStart.UNDISPATCHED) { try { awaitCancellation() } finally { socket.close() } } + try { written = guard { socket.send(target, port, payload) } } finally { closer.cancel() } + } + } finally { socket.close() } } true } if (completed != true) throw PacketSendException(SendFailure.TIMEOUT) } catch (error: IOException) { throw PacketSendException(SendFailure.IO, error) } + return written } - private suspend fun send(network: WifiNetworkHandle, target: InetAddress, port: Int, payload: ByteArray): Unit = + /** Opens, configures and binds the socket on [io]; cancellation closes it. */ + private suspend fun prepare(network: WifiNetworkHandle): UdpSocket = suspendCancellableCoroutine { cont -> val current = AtomicReference() - cont.invokeOnCancellation { current.get()?.close() } + cont.invokeOnCancellation { current.getAndSet(null)?.close() } io.dispatch(EmptyCoroutineContext) { + var socket: UdpSocket? = null try { - if (cont.isActive) { - platform.openSocket().use { socket -> - current.set(socket) - if (!cont.isActive) return@use - if (!platform.isWifi(network)) throw PacketSendException(SendFailure.NETWORK_LOST) - socket.enableBroadcast() - socket.bind(network) - if (!cont.isActive) return@use - socket.send(target, port, payload) - } - } - cont.resume(Unit) + if (!cont.isActive) return@dispatch + socket = platform.openSocket().also(current::set) + if (!platform.isWifi(network)) throw PacketSendException(SendFailure.NETWORK_LOST) + socket.enableBroadcast() + socket.bind(network) + val ready = socket + socket = null // handed over + cont.resume(ready) { _, _, _ -> ready.close() } } catch (error: Exception) { cont.resumeWithException(error) - } finally { current.getAndSet(null)?.close() } + } finally { socket?.close() } } } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wol/WolScreen.kt b/androidApp/src/main/kotlin/cz/netkit/app/wol/WolScreen.kt index a211af1..c007235 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wol/WolScreen.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wol/WolScreen.kt @@ -54,6 +54,17 @@ import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.material3.minimumInteractiveComponentSize import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import android.widget.Toast +import androidx.compose.ui.platform.LocalContext +import cz.netkit.app.nav.AppShortcuts +import cz.netkit.shared.nav.AppTarget +import cz.netkit.shared.nav.AppRecordKind +import cz.netkit.shared.wol.wolDeviceKey +import cz.netkit.shared.wol.uniqueWolDevicesByKey +import androidx.compose.foundation.border +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable @@ -130,7 +141,7 @@ private val WOL_IMPORT_MIME_TYPES = arrayOf("application/json", "text/plain", "t @OptIn(ExperimentalComposeUiApi::class, ExperimentalLayoutApi::class) @Composable -fun WolScreen(viewModel: WolViewModel, modifier: Modifier = Modifier) { +fun WolScreen(viewModel: WolViewModel, modifier: Modifier = Modifier, highlightId: String? = null) { val controller = viewModel.controller val state by controller.state.collectAsStateWithLifecycle() val transferBusy by viewModel.transferBusy.collectAsStateWithLifecycle() @@ -193,7 +204,23 @@ fun WolScreen(viewModel: WolViewModel, modifier: Modifier = Modifier) { } })) } - LazyColumn(Modifier.weight(1f), contentPadding = PaddingValues(Spacing.normal), verticalArrangement = Arrangement.spacedBy(Spacing.normal)) { + val listState = rememberLazyListState() + // Pinned shortcut or widget (zadání 36 §2.1): scroll to the device; waking still needs a tap. + LaunchedEffect(highlightId, state.loading, state.devices.size) { + val index = state.devices.indexOfFirst { it.id == highlightId } + if (index < 0 || state.loading || state.loadFailed) return@LaunchedEffect + val before = listOf(transferMessage != null, transferBusy, message == WolMessage.SAVE_FAILED, state.archivePath != null) + listState.animateScrollToItem(index + before.count { it }) + } + val context = LocalContext.current + val uniqueKeys = remember(state.devices) { uniqueWolDevicesByKey(state.devices).keys } + fun canPin(device: WolDevice) = wolDeviceKey(device) in uniqueKeys && + AppShortcuts.canPin(context, AppRecordKind.WOL_DEVICE, wolDeviceKey(device)) + fun pin(device: WolDevice) { + if (!AppShortcuts.requestPin(context, AppTarget.WolDevice(wolDeviceKey(device)), device.name)) + Toast.makeText(context, R.string.shortcut_pin_failed, Toast.LENGTH_SHORT).show() + } + LazyColumn(Modifier.weight(1f), state = listState, contentPadding = PaddingValues(Spacing.normal), verticalArrangement = Arrangement.spacedBy(Spacing.normal)) { transferMessage?.let { transfer -> item { Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { StatusBanner(stringResource(when (transfer) { @@ -258,7 +285,8 @@ fun WolScreen(viewModel: WolViewModel, modifier: Modifier = Modifier) { } } items(state.devices, key = { it.id }) { device -> - DeviceCard(device, state.devices, sending = state.sendingDeviceId == device.id, probing = state.probingDeviceId == device.id, + DeviceCard(device, state.devices, highlighted = device.id == highlightId, + onPin = if (canPin(device)) ({ pin(device) }) else null, sending = state.sendingDeviceId == device.id, probing = state.probingDeviceId == device.id, probe = state.probes[device.id], outcome = state.outcomes[device.id], manageEnabled = manageEnabled, wakeEnabled = state.sendingDeviceId == null && state.probingDeviceId != device.id && !state.saving && !transferBusy, onWake = { controller.wake(device.id) }, onCancel = controller::cancelWake, @@ -369,18 +397,19 @@ fun WolScreen(viewModel: WolViewModel, modifier: Modifier = Modifier) { */ @Composable private fun DeviceCard( - device: WolDevice, devices: List, sending: Boolean, probing: Boolean, probe: WakeProbeStatus?, outcome: WolSendOutcome?, + device: WolDevice, devices: List, highlighted: Boolean, onPin: (() -> Unit)?, sending: Boolean, probing: Boolean, probe: WakeProbeStatus?, outcome: WolSendOutcome?, manageEnabled: Boolean, wakeEnabled: Boolean, onWake: () -> Unit, onCancel: () -> Unit, onEdit: () -> Unit, onDelete: () -> Unit, onMove: (Int) -> Unit, ) { val colors = NetKitTheme.colors val state = wolState(sending, probing, probe, outcome, device.probePort) - Panel(Modifier.testTag("wol_device_${device.id}")) { + Panel(Modifier.testTag("wol_device_${device.id}") + .then(if (highlighted) Modifier.border(2.dp, colors.accent, NetKitShape.card) else Modifier)) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.medium)) { Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) { Text(device.name, style = DeviceName, color = colors.text, maxLines = 2, overflow = TextOverflow.Ellipsis) Text(deviceAddressLine(device), style = NetKitType.label, color = colors.muted) - device.note?.let { Text(it, style = NetKitType.label, color = colors.dim, maxLines = 2, overflow = TextOverflow.Ellipsis) } + device.note?.let { Text(it, style = NetKitType.label, color = colors.muted, maxLines = 2, overflow = TextOverflow.Ellipsis) } StateTag(state, Modifier.padding(top = Spacing.small), textModifier = if (outcome != null) Modifier.testTag("wol_status_${device.id}") else Modifier) } @@ -403,6 +432,16 @@ private fun DeviceCard( Icon(NetKitIcons.ChevronRight, stringResource(R.string.wol_move_down), Modifier.size(20.dp).rotate(90f), tint = if (manageEnabled && devices.last().id != device.id) colors.muted else colors.dim) } + if (onPin != null) Box { + var menu by remember { mutableStateOf(false) } + IconButton(onClick = { menu = true }, modifier = Modifier.testTag("wol_more_${device.id}")) { + Icon(NetKitIcons.More, stringResource(R.string.shortcut_more_actions, device.name), tint = colors.muted) + } + WolMenu(expanded = menu, onDismiss = { menu = false }) { + DropdownMenuItem(text = { MenuText(stringResource(R.string.shortcut_pin)) }, onClick = { menu = false; onPin() }, + modifier = Modifier.testTag("wol_pin_${device.id}")) + } + } } } } @@ -475,6 +514,7 @@ private fun sendFailure(reason: SendFailure?) = when (reason) { SendFailure.CANCELLED -> R.string.send_cancelled SendFailure.NO_WIFI -> R.string.no_wifi SendFailure.NO_BROADCAST -> R.string.no_broadcast + SendFailure.SECURE_ON_UNAVAILABLE -> R.string.wol_secureon_unavailable } /** @@ -589,6 +629,25 @@ private fun WolForm( DeviceTextField(draft.customTarget, { controller.updateDraft(draft.copy(customTarget = it)) }, R.string.custom_target, "custom_target", DeviceField.CUSTOM_TARGET in errors, saving) } item { DeviceTextField(draft.port, { controller.updateDraft(draft.copy(port = it)) }, R.string.device_port, "device_port", DeviceField.PORT in errors, saving, KeyboardType.Number) } + item { FormSection(R.string.wol_secureon_section) } + item { Text(stringResource(when { + draft.secureOnStored -> R.string.wol_secureon_stored + draft.secureOnStale -> R.string.wol_secureon_stale + else -> R.string.wol_secureon_hint + }), style = NetKitType.label, color = if (draft.secureOnStale) colors.warn else colors.muted) } + if (!draft.secureOnRemove) item { + DeviceTextField(draft.secureOn, { controller.updateDraft(draft.copy(secureOn = it.take(32))) }, R.string.wol_secureon_field, "device_secureon", + DeviceField.SECURE_ON in errors, saving, KeyboardType.Password, secret = true) + } + if (draft.secureOnStored || draft.secureOnStale) item { Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clip(NetKitShape.nested).testTag("device_secureon_remove") + .toggleable(value = draft.secureOnRemove, enabled = !saving, role = Role.Checkbox, + onValueChange = { controller.updateDraft(draft.copy(secureOnRemove = it, secureOn = "")) }).padding(horizontal = Spacing.tiny), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.small)) { + Checkbox(checked = draft.secureOnRemove, onCheckedChange = null, enabled = !saving, + colors = CheckboxDefaults.colors(checkedColor = colors.accent, uncheckedColor = colors.muted, checkmarkColor = colors.accentInk, + disabledCheckedColor = colors.dim, disabledUncheckedColor = colors.dim)) + Text(stringResource(R.string.wol_secureon_remove), Modifier.weight(1f), style = NetKitType.body, color = colors.text) + } } item { FormSection(R.string.wol_section_repeat) } item { DeviceTextField(draft.repeatCount, { controller.updateDraft(draft.copy(repeatCount = it)) }, R.string.wol_repeat_count, "repeat_count", DeviceField.REPEAT_COUNT in errors, saving, KeyboardType.Number) } item { DeviceTextField(draft.repeatIntervalMs, { controller.updateDraft(draft.copy(repeatIntervalMs = it)) }, R.string.wol_repeat_interval, "repeat_interval", DeviceField.REPEAT_INTERVAL in errors, saving, KeyboardType.Number) } @@ -645,7 +704,7 @@ private val FieldMono = NetKitType.addressFor(FieldText) @Composable private fun DeviceTextField( value: String, change: (String) -> Unit, label: Int, tag: String, error: Boolean, - saving: Boolean, keyboard: KeyboardType = KeyboardType.Text, singleLine: Boolean = true, + saving: Boolean, keyboard: KeyboardType = KeyboardType.Text, singleLine: Boolean = true, secret: Boolean = false, ) { val colors = NetKitTheme.colors OutlinedTextField( @@ -653,6 +712,7 @@ private fun DeviceTextField( modifier = Modifier.fillMaxWidth().testTag(tag), enabled = !saving, singleLine = singleLine, isError = error, textStyle = if (tag in MONO_FIELDS) FieldMono else FieldText, + visualTransformation = if (secret) androidx.compose.ui.text.input.PasswordVisualTransformation() else androidx.compose.ui.text.input.VisualTransformation.None, shape = NetKitShape.nested, colors = OutlinedTextFieldDefaults.colors( focusedTextColor = colors.text, unfocusedTextColor = colors.text, disabledTextColor = colors.dim, errorTextColor = colors.text, @@ -663,12 +723,13 @@ private fun DeviceTextField( ), supportingText = if (error) ({ Text(stringResource(when { tag == "device_mac" -> R.string.invalid_mac + tag == "device_secureon" -> R.string.wol_secureon_invalid tag == "device_name" && value.length > 100 -> R.string.name_too_long tag == "device_note" -> R.string.note_too_long (tag == "custom_target" || tag == "probe_host") && value.length > 253 -> R.string.host_too_long else -> R.string.invalid_value }), style = NetKitType.label) }) else null, - keyboardOptions = KeyboardOptions(keyboardType = keyboard), + keyboardOptions = KeyboardOptions(keyboardType = keyboard, autoCorrectEnabled = if (secret) false else null), ) } @@ -685,6 +746,7 @@ private fun StatusMessage(message: WolMessage) { WolMessage.NO_WIFI -> R.string.no_wifi WolMessage.NO_BROADCAST -> R.string.no_broadcast WolMessage.SENT -> R.string.sent + WolMessage.SECURE_ON_UNAVAILABLE -> R.string.wol_secureon_unavailable }), if (message == WolMessage.SENT) StatusKind.INFO else StatusKind.ERROR) } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wol/WolSecureOnStorage.kt b/androidApp/src/main/kotlin/cz/netkit/app/wol/WolSecureOnStorage.kt new file mode 100644 index 0000000..7092d58 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/wol/WolSecureOnStorage.kt @@ -0,0 +1,53 @@ +package cz.netkit.app.wol + +import java.io.File +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.serialization.json.Json +import cz.netkit.app.ssh.AndroidSecretStore +import cz.netkit.shared.wol.SecureOnEntry +import cz.netkit.shared.wol.WolSecureOnStore +import cz.netkit.shared.wol.decodeSecureOnVault +import cz.netkit.shared.wol.encodeSecureOnVault + +/** + * SecureOn passwords (zadání 39 §2.5) in the same encrypted store as SSH secrets: one AES-GCM + * ciphertext under a non-exportable Android Keystore key (namespace `wol`, `noBackupFilesDir`). + * The device list ([AndroidDeviceStore]) and its JSON/CSV export never contain them. + */ +class AndroidWolSecureOnStore(private val secrets: AndroidSecretStore, private val revocations: File? = null) : WolSecureOnStore { + private suspend fun revokeImported() = withContext(Dispatchers.IO) { + val file = revocations?.takeIf { it.exists() } ?: return@withContext + val ids = Json.decodeFromString>(file.readText()) + val current = read() + if (current.keys.any { it in ids }) write(current - ids) + java.nio.file.Files.delete(file.toPath()) + } + + override suspend fun load() = lock.withLock { + revokeImported() + read() + } + + override suspend fun save(entries: Map) = lock.withLock { + revokeImported() + write(entries) + } + + private suspend fun read(): Map = secrets.get(REFERENCE)?.let { bytes -> + try { decodeSecureOnVault(bytes) } finally { bytes.fill(0) } + } ?: emptyMap() + + private suspend fun write(entries: Map) { + if (entries.isEmpty()) { secrets.delete(REFERENCE); return } + val bytes = encodeSecureOnVault(entries) + try { secrets.put(REFERENCE, bytes) } finally { bytes.fill(0) } + } + + private companion object { + const val REFERENCE = "wol-secureon" + val lock = Mutex() + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wol/WolViewModel.kt b/androidApp/src/main/kotlin/cz/netkit/app/wol/WolViewModel.kt index 59d2211..92c72eb 100644 --- a/androidApp/src/main/kotlin/cz/netkit/app/wol/WolViewModel.kt +++ b/androidApp/src/main/kotlin/cz/netkit/app/wol/WolViewModel.kt @@ -5,6 +5,9 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import cz.netkit.app.R import cz.netkit.app.ssh.AndroidSecretStore +import cz.netkit.app.ssh.SshStore +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob import cz.netkit.shared.wol.WolController import cz.netkit.shared.wol.WolDeviceStore import cz.netkit.shared.wol.WolDeviceDraft @@ -30,11 +33,73 @@ import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.filterNotNull +import kotlinx.coroutines.flow.map +import cz.netkit.app.nav.AppShortcuts +import cz.netkit.app.wol.widget.WolWidgets +import cz.netkit.shared.nav.AppRecordKind +import cz.netkit.shared.wol.uniqueWolDevicesByKey open class NetKitApplication : Application() { open val devices: WolDeviceStore by lazy { createDeviceStore() } protected open fun createDeviceStore(): WolDeviceStore = AndroidDeviceStore(this) open fun createSshSecretStore(): AndroidSecretStore = AndroidSecretStore(this) + /** SecureOn passwords (zadání 39): own Keystore alias and directory, separate from SSH. */ + open fun createWolSecretStore(): AndroidSecretStore = AndroidSecretStore(this, "wol") + internal fun wolVault() = AndroidWolSecureOnStore(createWolSecretStore(), cz.netkit.app.backup.RestoreFiles(this).wolRevocations()) + /** + * The only SSH DataStore of the process (zadání 36 §2.8): DataStore must never have two active + * instances over one file, and the ViewModel, shortcuts and navigation share it. Its scope lives + * as long as the process. + */ + val sshStore: SshStore by lazy { SshStore(this, CoroutineScope(SupervisorJob() + Dispatchers.IO)) } + /** Process scope for short app-level work that must outlive a screen (widget snapshot writes). */ + val appScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + /** + * The only owner of the network status widget snapshot (zadání 37): screens offer foreground measurements, + * the widget reads and refreshes it. One instance per process (single writer of its file). + */ + val netStatus: cz.netkit.app.netstatus.NetStatusService by lazy { cz.netkit.app.netstatus.NetStatusService(this, appScope) } + + internal var restoreApplied: Boolean? = null + private set + + internal var restoreIoError = false + private set + + /** A damaged restore map was set aside at this start; Settings tells the user once (revize 51, kolo 2). */ + internal var restoreMapReset = false + private set + + override fun onCreate() { + super.onCreate() + // Before any store or ViewModel: a damaged map falls back to the default paths instead of a crash loop. + restoreMapReset = try { cz.netkit.app.backup.RestoreFiles(this).recoverDamagedMap() } catch (_: Exception) { false } + try { + restoreApplied = cz.netkit.app.backup.RestoreFiles(this).activate( + { cz.netkit.app.settings.AppLanguageSystem.current(this) }, + forgetSsh = { refs -> + // These local references were detached by the SSH v2 import, after commit. + val secrets = createSshSecretStore() + kotlinx.coroutines.runBlocking(Dispatchers.IO) { refs.forEach { secrets.delete(it) } } + }, + setLanguage = { cz.netkit.app.settings.AppLanguageSystem.set(this, it) }, + ) + } catch (_: Exception) { + // The durable request can be retried on the next launch, including a pending locale change. + restoreIoError = true + } + // Zadání 37 §2.4: at every app start a revoked location permission or a switched-off option deletes the + // stored SSID / public IP (also checked on every widget update). + appScope.launch { + try { netStatus.enforcePrivacy() } catch (e: CancellationException) { throw e } catch (_: Exception) { } + } + } + /** Link between the SSH sessions (ViewModel) and the session foreground service (zadání 42). */ + val sshKeeper: cz.netkit.app.ssh.SshSessionKeeper by lazy { cz.netkit.app.ssh.SshSessionKeeper(this) } + /** Background limit without the foreground service; instrumentation shortens it (zadání 42 AC-001). */ + open val sshBackgroundGraceMillis: Long get() = cz.netkit.shared.ssh.SshBackgroundPolicy.BACKGROUND_GRACE_MILLIS } /** @@ -150,7 +215,7 @@ class WolViewModel(application: Application) : AndroidViewModel(application) { } } private var draftBaseline: WolDeviceDraft? = null - fun add() { controller.add(); draftBaseline = controller.state.value.draft } + fun add(prefill: WolDeviceDraft = WolDeviceDraft()) { controller.add(prefill); draftBaseline = controller.state.value.draft } fun edit(id: String) { controller.edit(id); draftBaseline = controller.state.value.draft } fun hasDraftChanges(): Boolean = controller.state.value.draft != draftBaseline @@ -164,5 +229,24 @@ class WolViewModel(application: Application) : AndroidViewModel(application) { prober = AndroidWakeProber(application), monotonicMillis = SystemClock::elapsedRealtime, nameComparator = czechWolNameComparator(), + secureOn = (application as NetKitApplication).wolVault(), ) + + init { + // Pinned shortcuts and WoL widgets follow every successfully loaded device list (zadání 36 §2.3, §2.6). + viewModelScope.launch { + controller.state.map { if (it.loading || it.loadFailed) null else it.devices }.filterNotNull().distinctUntilChanged() + .collect { devices -> onDevicesChanged(devices) } + } + } + + private suspend fun onDevicesChanged(devices: List) = withContext(Dispatchers.IO) { + val app = getApplication() + // Keyed by the opaque device key: a replaced device (same ID, other MAC) keeps the old shortcut disabled. + // An ambiguous key is left out, so its shortcut is disabled rather than enabled for either device. + AppShortcuts.sync(app, AppRecordKind.WOL_DEVICE, uniqueWolDevicesByKey(devices).mapValues { it.value.name }, app.getString(R.string.shortcut_disabled_wol)) + try { WolWidgets.sync(app, devices) } + catch (e: CancellationException) { throw e } + catch (_: Exception) { /* A widget redraw failure must not affect the WoL screen. */ } + } } diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidget.kt b/androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidget.kt new file mode 100644 index 0000000..0aa3906 --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidget.kt @@ -0,0 +1,308 @@ +package cz.netkit.app.wol.widget + +import android.appwidget.AppWidgetManager +import android.content.Context +import android.content.Intent +import android.text.format.DateFormat +import androidx.compose.runtime.Composable +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.datastore.preferences.core.MutablePreferences +import androidx.datastore.preferences.core.Preferences +import androidx.datastore.preferences.core.longPreferencesKey +import androidx.datastore.preferences.core.stringPreferencesKey +import androidx.glance.Button +import androidx.glance.ButtonDefaults +import androidx.glance.GlanceId +import androidx.glance.GlanceModifier +import androidx.glance.GlanceTheme +import androidx.glance.LocalContext +import androidx.glance.LocalGlanceId +import androidx.glance.LocalSize +import androidx.glance.action.clickable +import androidx.glance.appwidget.GlanceAppWidget +import androidx.glance.appwidget.GlanceAppWidgetManager +import androidx.glance.appwidget.GlanceAppWidgetReceiver +import androidx.glance.appwidget.SizeMode +import androidx.glance.appwidget.action.actionStartActivity +import androidx.glance.appwidget.appWidgetBackground +import androidx.glance.appwidget.cornerRadius +import androidx.glance.appwidget.provideContent +import androidx.glance.appwidget.state.updateAppWidgetState +import androidx.glance.background +import androidx.glance.currentState +import androidx.glance.layout.Alignment +import androidx.glance.layout.Column +import androidx.glance.layout.Row +import androidx.glance.layout.Spacer +import androidx.glance.layout.fillMaxSize +import androidx.glance.layout.fillMaxWidth +import androidx.glance.layout.height +import androidx.glance.layout.padding +import androidx.glance.layout.width +import androidx.glance.material3.ColorProviders +import androidx.glance.state.PreferencesGlanceStateDefinition +import androidx.glance.text.FontWeight +import androidx.glance.text.Text +import androidx.glance.text.TextStyle +import cz.netkit.app.R +import cz.netkit.app.nav.AppShortcuts +import cz.netkit.app.ui.theme.netKitMaterialColorScheme +import cz.netkit.app.wol.AndroidNetworkInfoProvider +import cz.netkit.app.wol.AndroidPacketSender +import cz.netkit.app.wol.NetKitApplication +import cz.netkit.shared.nav.AppTarget +import cz.netkit.shared.nav.isValidAppTargetId +import cz.netkit.shared.nav.isWolDeviceKey +import cz.netkit.shared.wol.WOL_WIDGET_TIMEOUT_MS +import cz.netkit.shared.wol.WolDevice +import cz.netkit.shared.wol.WolWidgetState +import cz.netkit.shared.wol.WolWidgetStatus +import cz.netkit.shared.wol.WolWidgetView +import cz.netkit.shared.wol.boundWolDevice +import cz.netkit.shared.wol.completeWolWidgetWake +import cz.netkit.shared.wol.reserveWolWidgetWake +import cz.netkit.shared.wol.wolDeviceKey +import cz.netkit.shared.wol.wolWidgetRemaining +import cz.netkit.shared.wol.wolWidgetSendBudget +import cz.netkit.shared.wol.WOL_WIDGET_WRITE_RESERVE_MS +import cz.netkit.shared.wol.sendWolWake +import cz.netkit.shared.wol.syncWolWidgetState +import cz.netkit.shared.wol.wolWidgetRepeatCount +import cz.netkit.shared.wol.wolWidgetStatus +import cz.netkit.shared.wol.wolWidgetView +import android.os.SystemClock +import android.content.BroadcastReceiver +import android.content.ComponentName +import androidx.core.net.toUri +import androidx.glance.appwidget.action.actionSendBroadcast +import cz.netkit.shared.wol.parseWolWidgetWakeData +import cz.netkit.shared.wol.wolWidgetWakeData +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.launch +import androidx.glance.appwidget.state.getAppWidgetState +import cz.netkit.shared.wol.WolWidgetStore +import cz.netkit.shared.wol.WolWidgetTap +import cz.netkit.shared.wol.configuredWolWidgetState +import cz.netkit.shared.wol.runWolWidgetWake +import cz.netkit.shared.wol.secureOnPasswordForSend +import java.util.Date +import java.util.UUID +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.withTimeoutOrNull + +/* + * WoL home-screen widget (zadání 36 §2.6, Jetpack Glance): device name, "Wake" button and the last + * result. No MAC on the home screen, no periodic updates (updatePeriodMillis = 0), no wake probe. + * The widget redraws only after its own action and after the device list changed in the app. + */ + +/** Home-screen widget receiver; not exported, the system delivers the AppWidget broadcasts (docs/bezpecnost.md). */ +class WolWidgetReceiver : GlanceAppWidgetReceiver() { + override val glanceAppWidget: GlanceAppWidget = WolWidget() +} + +private val KEY_DEVICE = stringPreferencesKey("wol_device_id") +private val KEY_NAME = stringPreferencesKey("wol_device_name") +private val KEY_STATUS = stringPreferencesKey("wol_status") +private val KEY_AT = longPreferencesKey("wol_status_at") +private val KEY_DEVICE_KEY = stringPreferencesKey("wol_device_key") +private val KEY_RESERVATION = stringPreferencesKey("wol_send_reservation") +private val KEY_REVISION = longPreferencesKey("wol_revision") +private val KEY_BINDING = stringPreferencesKey("wol_binding_key") + +internal fun Preferences.toWolWidgetState() = WolWidgetState( + deviceId = this[KEY_DEVICE]?.takeIf(::isValidAppTargetId), + deviceKey = this[KEY_DEVICE_KEY]?.takeIf(::isWolDeviceKey), + name = this[KEY_NAME], + status = this[KEY_STATUS]?.let { name -> WolWidgetStatus.entries.firstOrNull { it.name == name } } ?: WolWidgetStatus.UNCONFIGURED, + atMillis = this[KEY_AT], + sendToken = this[KEY_RESERVATION], + revision = this[KEY_REVISION] ?: 0, + bindingKey = this[KEY_BINDING]?.takeIf(::isWolDeviceKey), +) + +internal fun MutablePreferences.write(state: WolWidgetState) { + fun put(key: Preferences.Key, value: T?) { if (value == null) remove(key) else this[key] = value } + put(KEY_DEVICE, state.deviceId) + put(KEY_DEVICE_KEY, state.deviceKey) + put(KEY_NAME, state.name) + put(KEY_STATUS, state.status.name) + put(KEY_AT, state.atMillis) + put(KEY_RESERVATION, state.sendToken) + put(KEY_REVISION, state.revision) + put(KEY_BINDING, state.bindingKey) +} + +/** + * One transaction over this widget's Glance preferences (DataStore `updateData`, serialized per widget): + * [change] sees the **current** state, the returned state is stored only if it differs. + */ +internal suspend fun transactWolWidget(context: Context, glanceId: GlanceId, change: (WolWidgetState) -> WolWidgetState): WolWidgetState { + var result = WolWidgetState() + updateAppWidgetState(context, PreferencesGlanceStateDefinition, glanceId) { prefs -> + val before = prefs.toWolWidgetState() + val after = change(before) + result = after + if (after == before) prefs else prefs.toMutablePreferences().apply { write(after) } + } + return result +} + +class WolWidget : GlanceAppWidget() { + override val stateDefinition = PreferencesGlanceStateDefinition + override val sizeMode: SizeMode = SizeMode.Exact + + override suspend fun provideGlance(context: Context, id: GlanceId) { + val colors = ColorProviders(light = netKitMaterialColorScheme(false), dark = netKitMaterialColorScheme(true)) + provideContent { + GlanceTheme(colors = colors) { + WolWidgetContent(wolWidgetView(currentState().toWolWidgetState(), System.currentTimeMillis()), + currentState().toWolWidgetState()) + } + } + } +} + +@Composable +private fun WolWidgetContent(view: WolWidgetView, state: WolWidgetState) { + val context = LocalContext.current + val glanceId = LocalGlanceId.current + val title = view.title ?: context.getString(R.string.wol_widget_choose) + val status = when (view.status) { + WolWidgetStatus.UNCONFIGURED -> context.getString(R.string.wol_widget_unconfigured) + WolWidgetStatus.READY -> context.getString(R.string.wol_widget_ready) + WolWidgetStatus.SENDING -> context.getString(R.string.wol_widget_sending) + WolWidgetStatus.SENT -> if (view.showTime) context.getString(R.string.wol_widget_sent_at, + DateFormat.getTimeFormat(context).format(Date(requireNotNull(state.atMillis)))) else context.getString(R.string.wol_widget_ready) + WolWidgetStatus.NO_WIFI -> context.getString(R.string.wol_widget_no_wifi) + WolWidgetStatus.NO_BROADCAST -> context.getString(R.string.wol_widget_no_broadcast) + WolWidgetStatus.FAILED -> context.getString(R.string.wol_widget_failed) + WolWidgetStatus.DELETED -> context.getString(R.string.wol_widget_deleted) + WolWidgetStatus.SECURE_ON_UNAVAILABLE -> context.getString(R.string.wol_widget_secureon_unavailable) + } + // Title tap: the WoL tab with this device (never a wake), otherwise the configuration to pick one. + val openTitle = if (view.opensDevice) actionStartActivity(AppShortcuts.openIntent(context, AppTarget.WolDevice(requireNotNull(state.deviceKey)))) + else actionStartActivity(Intent(context, WolWidgetConfigActivity::class.java) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, GlanceAppWidgetManager(context).getAppWidgetId(glanceId))) + val colors = GlanceTheme.colors + // No button without a device to wake (unconfigured, deleted): the title then opens the configuration. + val showWake = view.opensDevice + val wakeButton = @Composable { modifier: GlanceModifier -> + // Always clickable: the receiver decides atomically. The explicit broadcast carries widget ID, + // device key and revision in its data URI, so each drawing has its own PendingIntent (Glance + // creates them with FLAG_UPDATE_CURRENT) and a stale drawing or a second tap is refused. + // A running send only gets the muted colours. + val tap = requireNotNull(view.tap) + val wake = WolWidgetWakeReceiver.intent(context, GlanceAppWidgetManager(context).getAppWidgetId(glanceId), tap) + Button(context.getString(R.string.wol_widget_wake), modifier = modifier, + onClick = actionSendBroadcast(wake), + maxLines = 1, + colors = if (view.wakeEnabled) ButtonDefaults.buttonColors(backgroundColor = colors.primary, contentColor = colors.onPrimary) + else ButtonDefaults.buttonColors(backgroundColor = colors.surfaceVariant, contentColor = colors.onSurfaceVariant)) + } + val texts = @Composable { modifier: GlanceModifier -> + Column(modifier.clickable(openTitle)) { + Text(title, style = TextStyle(color = colors.onSurface, fontSize = 15.sp, fontWeight = FontWeight.Bold), maxLines = 1) + Text(status, style = TextStyle(color = if (view.error) colors.error else colors.onSurfaceVariant, fontSize = 12.sp), maxLines = 2) + } + } + val box = GlanceModifier.fillMaxSize().appWidgetBackground().background(colors.surface).cornerRadius(16.dp).padding(12.dp) + // One cell high: name and status beside the button; taller: the button below. + if (LocalSize.current.height < 100.dp) { + Row(box, verticalAlignment = Alignment.CenterVertically) { + texts(GlanceModifier.defaultWeight()) + if (showWake) { + Spacer(GlanceModifier.width(8.dp)) + wakeButton(GlanceModifier) + } + } + } else { + Column(box, verticalAlignment = Alignment.Top) { + texts(GlanceModifier.fillMaxWidth().defaultWeight()) + if (showWake) { + Spacer(GlanceModifier.height(8.dp)) + wakeButton(GlanceModifier.fillMaxWidth()) + } + } + } +} + +private val wakeScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + +/** + * "Wake" tap (revize kolo 3): an explicit broadcast from the widget's own PendingIntent to this + * non-exported receiver. The data URI ([wolWidgetWakeData]) carries widget ID, device key and revision; + * the sequence, deadline and reservation rules live in the common [runWolWidgetWake], within the + * receiver's ~10 s budget (goAsync). No wake probe here. + */ +class WolWidgetWakeReceiver : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + val started = SystemClock.elapsedRealtime() + val (appWidgetId, tap) = parseWolWidgetWakeData(intent.dataString) ?: return + // Only a placed widget of this app's provider. + if (AppWidgetManager.getInstance(context).getAppWidgetInfo(appWidgetId)?.provider != + ComponentName(context, WolWidgetReceiver::class.java)) return + val app = context.applicationContext as NetKitApplication + val pending = goAsync() + wakeScope.launch { + try { + val widget = WolWidget() + val glanceId = GlanceAppWidgetManager(app).getGlanceIdBy(appWidgetId) + runWolWidgetWake( + tap = tap, + reservation = UUID.randomUUID().toString(), + store = object : WolWidgetStore { + override suspend fun transact(change: (WolWidgetState) -> WolWidgetState) = transactWolWidget(app, glanceId, change) + override suspend fun read() = widget.getAppWidgetState(app, glanceId).toWolWidgetState() + }, + loadDevices = { app.devices.load() }, + networkInfo = AndroidNetworkInfoProvider(app), + sender = AndroidPacketSender(app), + nowMillis = System::currentTimeMillis, + elapsedMillis = { SystemClock.elapsedRealtime() - started }, + redraw = { widget.update(app, glanceId) }, + // SecureOn (zadání 39): same encrypted store and fail-closed rule as the app. + // Fail-closed by the device's persistent secureOnRequired flag (revize 39/4). + secureOnPassword = { device -> secureOnPasswordForSend(device, app.wolVault()) }, + ) + } catch (e: CancellationException) { throw e + } catch (_: Exception) { + // Unknown widget ID or store failure: nothing was reserved, nothing to report. + } finally { pending.finish() } + } + } + + companion object { + /** The explicit broadcast of one drawing; also used by the instrumentation to hold an old drawing. */ + fun intent(context: Context, appWidgetId: Int, tap: WolWidgetTap): Intent = + Intent(context, WolWidgetWakeReceiver::class.java).setData(wolWidgetWakeData(appWidgetId, tap).toUri()) + } +} + +/** Keeps every placed WoL widget in step with a successfully loaded device list (rename, deletion). */ +object WolWidgets { + suspend fun sync(context: Context, devices: List) { + val widget = WolWidget() + val ids = try { GlanceAppWidgetManager(context).getGlanceIds(WolWidget::class.java) } catch (_: IllegalStateException) { return } + for (id in ids) { + var changed = false + // Derived from the current state inside the transaction, so a running send is merged, not overwritten. + transactWolWidget(context, id) { current -> syncWolWidgetState(current, devices).also { changed = it != current } } + if (changed) widget.update(context, id) + } + } + + /** Called by the configuration activity after the user picked [device]. */ + suspend fun configure(context: Context, appWidgetId: Int, device: WolDevice) { + val id = GlanceAppWidgetManager(context).getGlanceIdBy(appWidgetId) + // Replaces the binding, drops any running reservation and bumps the revision: an old send cannot + // bind back and a Wake drawn for the previous device is refused. + transactWolWidget(context, id) { current -> configuredWolWidgetState(device, current) } + WolWidget().update(context, id) + } +} diff --git a/androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidgetConfigActivity.kt b/androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidgetConfigActivity.kt new file mode 100644 index 0000000..1da57da --- /dev/null +++ b/androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidgetConfigActivity.kt @@ -0,0 +1,118 @@ +package cz.netkit.app.wol.widget + +import android.appwidget.AppWidgetManager +import android.content.ComponentName +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.mutableStateOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.testTagsAsResourceId +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.lifecycle.lifecycleScope +import cz.netkit.app.BuildConfig +import cz.netkit.app.R +import cz.netkit.app.ui.EmptyState +import cz.netkit.app.ui.NetKitIcons +import cz.netkit.app.ui.Panel +import cz.netkit.app.ui.ScreenHeader +import cz.netkit.app.ui.Spacing +import cz.netkit.app.ui.StatusBanner +import cz.netkit.app.ui.StatusKind +import cz.netkit.app.ui.theme.NetKitTheme +import cz.netkit.app.ui.theme.NetKitType +import cz.netkit.app.wol.NetKitApplication +import cz.netkit.shared.nav.isValidAppTargetId +import cz.netkit.shared.wol.WolDevice +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.launch + +/** + * Picks the device of a newly placed WoL widget (zadání 36 §2.6). Exported only because the launcher + * starts it through `APPWIDGET_CONFIGURE`; an app widget ID that does not belong to [WolWidgetReceiver] + * closes it at once, and the user still has to pick the device (docs/bezpecnost.md). + */ +class WolWidgetConfigActivity : ComponentActivity() { + private sealed interface Load { data object Loading : Load; data object Failed : Load; data class Done(val devices: List) : Load } + private val load = mutableStateOf(Load.Loading) + private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID + private var saving = false + + @OptIn(ExperimentalComposeUiApi::class) + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + // Backing out leaves the widget unplaced (launcher contract). + setResult(RESULT_CANCELED) + appWidgetId = try { intent?.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) } + catch (_: RuntimeException) { null } ?: AppWidgetManager.INVALID_APPWIDGET_ID + val provider = if (appWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) null + else AppWidgetManager.getInstance(this).getAppWidgetInfo(appWidgetId)?.provider + if (provider != ComponentName(this, WolWidgetReceiver::class.java)) { finish(); return } + enableEdgeToEdge() + lifecycleScope.launch { + load.value = try { Load.Done((application as NetKitApplication).devices.load().filter { isValidAppTargetId(it.id) }) } + catch (e: CancellationException) { throw e } catch (_: Exception) { Load.Failed } + } + setContent { + NetKitTheme { + Surface(Modifier.fillMaxSize().semantics { testTagsAsResourceId = BuildConfig.DEBUG }, color = NetKitTheme.colors.background) { + Column(Modifier.safeDrawingPadding()) { + Box(Modifier.padding(Spacing.normal)) { + ScreenHeader(stringResource(R.string.wol_widget_config_title), stringResource(R.string.wol_widget_config_subtitle)) + } + when (val state = load.value) { + Load.Loading -> Box(Modifier.fillMaxWidth().padding(Spacing.large), contentAlignment = Alignment.Center) { + CircularProgressIndicator(color = NetKitTheme.colors.accent) + } + Load.Failed -> Box(Modifier.padding(Spacing.normal)) { StatusBanner(stringResource(R.string.wol_widget_config_failed), StatusKind.ERROR) } + is Load.Done -> if (state.devices.isEmpty()) Box(Modifier.padding(Spacing.normal)) { + Panel { EmptyState(stringResource(R.string.wol_widget_config_empty), NetKitIcons.Power) } + } else LazyColumn(contentPadding = PaddingValues(Spacing.normal), verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + items(state.devices, key = { it.id }) { device -> + Panel(Modifier.testTag("wol_widget_pick_${device.id}"), onClick = { pick(device) }) { + Text(device.name, style = NetKitType.panelTitle, color = NetKitTheme.colors.text, maxLines = 2) + device.note?.let { Text(it, style = NetKitType.label, color = NetKitTheme.colors.muted, maxLines = 1) } + } + } + } + } + } + } + } + } + } + + private fun pick(device: WolDevice) { + if (saving) return + saving = true + lifecycleScope.launch { + try { + WolWidgets.configure(this@WolWidgetConfigActivity, appWidgetId, device) + setResult(RESULT_OK, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)) + } catch (e: CancellationException) { throw e + } catch (_: Exception) { + // Leave RESULT_CANCELED: the launcher drops the half-configured widget. + } + finish() + } + } +} diff --git a/androidApp/src/main/res/drawable/ic_notification_ssh.xml b/androidApp/src/main/res/drawable/ic_notification_ssh.xml new file mode 100644 index 0000000..8ba096e --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_notification_ssh.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_background.xml b/androidApp/src/main/res/drawable/ic_shortcut_background.xml new file mode 100644 index 0000000..df98d68 --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_background.xml @@ -0,0 +1,6 @@ + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_ping.xml b/androidApp/src/main/res/drawable/ic_shortcut_ping.xml new file mode 100644 index 0000000..e072a24 --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_ping.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_ping_foreground.xml b/androidApp/src/main/res/drawable/ic_shortcut_ping_foreground.xml new file mode 100644 index 0000000..37e8d8a --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_ping_foreground.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_signal.xml b/androidApp/src/main/res/drawable/ic_shortcut_signal.xml new file mode 100644 index 0000000..762328f --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_signal.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_signal_foreground.xml b/androidApp/src/main/res/drawable/ic_shortcut_signal_foreground.xml new file mode 100644 index 0000000..b683730 --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_signal_foreground.xml @@ -0,0 +1,14 @@ + + + + + + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_spectrum.xml b/androidApp/src/main/res/drawable/ic_shortcut_spectrum.xml new file mode 100644 index 0000000..d0e6ade --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_spectrum.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_spectrum_foreground.xml b/androidApp/src/main/res/drawable/ic_shortcut_spectrum_foreground.xml new file mode 100644 index 0000000..f7105c3 --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_spectrum_foreground.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_ssh.xml b/androidApp/src/main/res/drawable/ic_shortcut_ssh.xml new file mode 100644 index 0000000..bfc9134 --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_ssh.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_ssh_foreground.xml b/androidApp/src/main/res/drawable/ic_shortcut_ssh_foreground.xml new file mode 100644 index 0000000..102f157 --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_ssh_foreground.xml @@ -0,0 +1,13 @@ + + + + + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_subnet.xml b/androidApp/src/main/res/drawable/ic_shortcut_subnet.xml new file mode 100644 index 0000000..c818f8c --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_subnet.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_subnet_foreground.xml b/androidApp/src/main/res/drawable/ic_shortcut_subnet_foreground.xml new file mode 100644 index 0000000..36b0afa --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_subnet_foreground.xml @@ -0,0 +1,15 @@ + + + + + + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_wol.xml b/androidApp/src/main/res/drawable/ic_shortcut_wol.xml new file mode 100644 index 0000000..525f57f --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_wol.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/androidApp/src/main/res/drawable/ic_shortcut_wol_foreground.xml b/androidApp/src/main/res/drawable/ic_shortcut_wol_foreground.xml new file mode 100644 index 0000000..6337449 --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_shortcut_wol_foreground.xml @@ -0,0 +1,11 @@ + + + + + + + + diff --git a/androidApp/src/main/res/drawable/ic_tile_signal.xml b/androidApp/src/main/res/drawable/ic_tile_signal.xml new file mode 100644 index 0000000..e4baed9 --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_tile_signal.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/androidApp/src/main/res/drawable/ic_widget_refresh.xml b/androidApp/src/main/res/drawable/ic_widget_refresh.xml new file mode 100644 index 0000000..462d60b --- /dev/null +++ b/androidApp/src/main/res/drawable/ic_widget_refresh.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/androidApp/src/main/res/layout/netstatus_age.xml b/androidApp/src/main/res/layout/netstatus_age.xml new file mode 100644 index 0000000..ff2affc --- /dev/null +++ b/androidApp/src/main/res/layout/netstatus_age.xml @@ -0,0 +1,10 @@ + + + diff --git a/androidApp/src/main/res/resources.properties b/androidApp/src/main/res/resources.properties new file mode 100644 index 0000000..fefa5fe --- /dev/null +++ b/androidApp/src/main/res/resources.properties @@ -0,0 +1 @@ +unqualifiedResLocale=cs diff --git a/androidApp/src/main/res/values-en/accessibility.xml b/androidApp/src/main/res/values-en/accessibility.xml new file mode 100644 index 0000000..02fbafb --- /dev/null +++ b/androidApp/src/main/res/values-en/accessibility.xml @@ -0,0 +1,24 @@ + + + Ping complete. Replies: %1$d of %2$d. + TCP ping complete. Replies: %1$d of %2$d. + Average latency %1$.2f ms. + Average latency over the last %1$d probes: %2$.2f ms. + Traceroute complete. Hops probed: %1$d, responding: %2$d. + Port scan complete. Open ports: %1$d of %2$d. + Device scan complete. Devices found: %1$d. + DNS lookup complete. Addresses returned: %1$d. + DNS record lookup complete. Result rows: %1$d. + iperf3 test complete. + Speed test complete. + Download %1$.2f Mbit/s. + Upload %1$.2f Mbit/s. + Device scan in progress. + Ping in progress. + Port scan in progress. + %1$s. Minimum %2$s, maximum %3$s. Last value in the window: %4$s. + %1$s. No samples. + unavailable + Strongest access point: %1$s, channel %2$d, %3$d dBm. + diff --git a/androidApp/src/main/res/values-en/backup.xml b/androidApp/src/main/res/values-en/backup.xml new file mode 100644 index 0000000..0b4322f --- /dev/null +++ b/androidApp/src/main/res/values-en/backup.xml @@ -0,0 +1,40 @@ + + Configuration backup + The file includes profiles, server fingerprints, commands, targets and settings. Check your commands and notes for credentials you entered as text. + Encrypt backup with a password + Save a readable backup? + Anyone with the file can read addresses, usernames and commands and modify the backup. + Use readable JSON + Backup password + Create backup + Open backup to restore + Decrypt and preview + Select sections to restore. Preferences, favorites, servers and settings will be replaced. Profiles and devices will be merged. + Added %1$d · changed %2$d · skipped %3$d + Restore selected sections + NetKit will prepare the changes and close. All changes will take effect together on the next launch. If an affected store changes before then, the restore will be canceled. + Confirm and close NetKit + Finish measurements, close sessions and finish editing before restoring. + Restore was canceled. Reopen the file to review the current changes. + Could not process the file. Check its format, version, size and storage availability. + Incorrect password or damaged encrypted backup. + Backup saved. + Selected configuration restored. + Restore server trust only from a verified backup. Conflicting or rejected host keys are skipped. + SSH profiles and groups + Telnet profiles + Serial profiles + Terminal snippets + SSH forwards + Trusted SSH hosts + Wake-on-LAN devices + Tool preferences + Favorite targets + LibreSpeed and iperf3 servers + Restore could not finish. NetKit will retry on its next launch. + The backup contains text that looks like a credential. Check commands, snippets and notes. + Check that SSH profile names are unique and the profile export fits the size limit. + Previously saved SecureOn passwords will be invalidated for imported devices, even when their configuration matches. + The restored configuration map was damaged. NetKit is using the default storage and set the damaged file aside. Restore the backup again if settings are missing. + Will be restored without a key. Assign the profile key again. + diff --git a/androidApp/src/main/res/values-en/cellular.xml b/androidApp/src/main/res/values-en/cellular.xml index c90817c..5cdd9f1 100644 --- a/androidApp/src/main/res/values-en/cellular.xml +++ b/androidApp/src/main/res/values-en/cellular.xml @@ -25,4 +25,28 @@ Without the phone permission only the data SIM is shown Without the phone permission only the SIM carrying data is shown. Phone numbers, IMEI and SIM identifiers are never read. The permission can be granted in the app settings. Without location access Android withholds the network operator name; the SIM name is used instead. + + + Cell detail + Expanded + Collapsed + Android gives the band, PCI, cell ID and neighbour cells only with precise location and the phone permission. Nothing else is requested and the data stays on the device. + Allow location + Allow phone + App settings + Reading cells… + The modem returned no cells, retrying in 5 s. + The system returned no cells. Android withholds them while location services are off. + Connected over %1$s – the detail covers LTE and 5G only. + On this device only: cell ID and TAC reveal an approximate location, so they are never stored, exported, shared or sent. Refreshed at most every 5 s, only while the detail is open. + Primary + Secondary + %1$s (estimate) + Cell ID (ECI) + Cell ID (NCI) + %1$s (eNB %2$s · %3$d) + Channel bandwidth + Timing advance + Neighbour cells (%1$d) + The modem reports no neighbour cells. diff --git a/androidApp/src/main/res/values-en/lan_rozsireni.xml b/androidApp/src/main/res/values-en/lan_rozsireni.xml new file mode 100644 index 0000000..a614483 --- /dev/null +++ b/androidApp/src/main/res/values-en/lan_rozsireni.xml @@ -0,0 +1,45 @@ + + + + Network info + Show + Hide + Interface + IPv4 + Gateway + DNS servers + Search domain + DHCP server + Interface MTU + IPv6 global + IPv6 ULA + IPv6 link-local + none + unknown + unavailable (Android 11+) + Traceroute supports IPv4 only for now. Use ping or the port check for an IPv6 target. + The MTU search (DF) exists for IPv4 only; IPv6 is not fragmented on the path. + The IPv6 zone (the interface after the percent sign) does not match the network used for the measurement. Omit the zone or enter the Wi-Fi interface. + Services (UDP) + This host only: SNMP v2c (sysName, sysDescr), NTP and the DNS server version. Each probe at most 2 attempts of 1.5 s. Enter an SNMP community only for your own device; it is not stored and an empty field skips SNMP. + SNMP community (optional) + Identify services + Querying SNMP, NTP and DNS… + Cancelled. + SNMP + SNMP sysName + SNMP sysDescr + skipped (no community) + agent error (error-status %1$d) + NTP + stratum %1$d · %2$s + kiss-o’-death %1$s + unsynchronized + DNS version (version.bind) + answers, version not disclosed (RCODE %1$d) + skipped (host is not a DNS server of this network and TCP 53 was not found) + no reply + port closed + invalid reply + — + diff --git a/androidApp/src/main/res/values-en/lan_wol.xml b/androidApp/src/main/res/values-en/lan_wol.xml new file mode 100644 index 0000000..e99ece3 --- /dev/null +++ b/androidApp/src/main/res/values-en/lan_wol.xml @@ -0,0 +1,12 @@ + + + MAC (NetBIOS) + Add to WoL + Sending magic packet… + Magic packet sent + No Wi-Fi + Sending failed + The MAC from NetBIOS will be prefilled: %1$s. Check it before saving. + Enter the MAC by hand: Android does not let apps read the ARP table. + Wake: %1$s + diff --git a/androidApp/src/main/res/values-en/netstatus_widget.xml b/androidApp/src/main/res/values-en/netstatus_widget.xml new file mode 100644 index 0000000..5d39607 --- /dev/null +++ b/androidApp/src/main/res/values-en/netstatus_widget.xml @@ -0,0 +1,42 @@ + + + + Network status + Last measured Wi-Fi signal and speed with the age of the measurement + Wi-Fi + No measurement yet + Open NetKit to measure + No Wi-Fi + Signal not measured yet + %1$d dBm + channel %1$d + ch %1$d + 2.4 GHz + 5 GHz + 6 GHz + %1$d MHz + Link ↓%1$s ↑%2$s Mb/s + gateway %1$s ms + Speed test ↓%1$s ↑%2$s Mb/s + %1$s ms + Public IP %1$s + %1$s (%2$s) + last measured %1$s + Measured %1$s + + %s ago + Signal %s ago + Refreshed %s ago + Refresh signal + Network status widget + What the widget may show. Applies to every network status widget. + Show the network name (SSID) + Only the SSID from measurements in the app is stored, never shown on the lock screen. Turning this off or revoking the location permission deletes the stored SSID. + The app has no precise location permission; no SSID will be stored. + Show the public IP + Only the last value found in Overview; the widget never looks anything up or sends anything. + The public IP lookup is off in Overview; nothing will be stored. + The widget shows the last measurement from Overview and the speed test. The refresh icon reads the current signal without location and without network traffic. Tapping the widget opens Overview. + Save + The settings could not be saved. + diff --git a/androidApp/src/main/res/values-en/settings.xml b/androidApp/src/main/res/values-en/settings.xml new file mode 100644 index 0000000..1ea9db8 --- /dev/null +++ b/androidApp/src/main/res/values-en/settings.xml @@ -0,0 +1,50 @@ + + + Settings + Settings could not be saved; they apply until the app is closed. + Appearance + Theme + System + Light + Dark + Language + System + Android stores the choice; it is also in System settings → Apps → NetKit → Language. + System language settings + App language in Android + The system language settings could not be opened. + Choosing the app language needs Android 13 or later. Here NetKit follows the system language: English for an English system, Czech otherwise. + Measurements + Keep the display on during measurements + Walk log, speed and iperf3, ping, TCP ping, traceroute, port scans and a connected terminal. When the display turns off, NetKit ends the measurement; it does not run in the background. + Consents and online queries + Online queries + Public IP and provider on Overview (Cloudflare, Team Cymru DNS), RDAP in Tools and public IP in the network status widget. + Automatic LAN discovery + Forgets the answers for all networks; the app asks again. + M-Lab notice (NDT7) + Acknowledged, not shown before a test + Shown before an NDT7 test + Forget + Show again + History and targets + Speed history (LibreSpeed, NDT7) + iperf3 history + + %d record + %d records + + Last iperf3 server + None + Clear target history + Delete %1$s from target history? Favourites will be kept. + Delete + Delete history? + %1$s: %2$s. This cannot be undone. + Forget consents? + Automatic device discovery asks again on every network. Manual discovery keeps working. + Cancel + Done + Could not save + The update check is in Settings + diff --git a/androidApp/src/main/res/values-en/sharing.xml b/androidApp/src/main/res/values-en/sharing.xml new file mode 100644 index 0000000..3bffa0b --- /dev/null +++ b/androidApp/src/main/res/values-en/sharing.xml @@ -0,0 +1,84 @@ + + + + NetKit diagnostic report + NetKit speed test + Time + App version + Network + Network type + Metered + Interface + IPv4 + IPv6 + Gateway + DNS + Private DNS + DHCP server + MTU + Wi-Fi + SSID + BSSID + Signal + Link rate RX/TX + Channel + Band + Channel width + Standard + Latency (last minute) + Gateway + Internet + loss + no data + Public IP + Address + ASN + Provider + Last speed test + Last iperf3 + Server + Engine + Download + Upload + Latency + Jitter + Retransmits + incomplete result + yes + no + Diagnostic report + Diagnostic report + Building the report… + Include SSID + Include BSSID + Include public addresses + The SSID, BSSID, public addresses of the phone and gateway, Private DNS hostname and iperf3 server hostname or public address can identify your network. Include them only when sharing with a trusted recipient. + Report preview + Copy + Share + Save + Close + Share diagnostic report + Report copied + Could not copy the report + Could not open sharing + Report saved + Could not save the report + The report is built on the phone from values Overview already measured, and goes only where you copy, share or save it. It contains no mobile cell data and no passwords. + Export list + Export device list + The file contains addresses, names, MAC addresses and open ports of devices on your network. Share it only with someone you trust. + Names, banners and UPnP details come from the devices themselves; control characters are removed in the export. + Save + Cancel + Device list saved + Could not save the device list + Share result + Share result + Include SSID + The text contains time, network type, server, speeds and latency. The SSID is left out by default. + Share measurement result + Share + Could not open sharing + Cancel + diff --git a/androidApp/src/main/res/values-en/shortcuts.xml b/androidApp/src/main/res/values-en/shortcuts.xml new file mode 100644 index 0000000..89f5e41 --- /dev/null +++ b/androidApp/src/main/res/values-en/shortcuts.xml @@ -0,0 +1,17 @@ + + + Signal + Wi-Fi signal (Overview) + Spectrum + Wi-Fi spectrum + Ping + Ping (Tools) + Subnets + Subnet calculator + Add to home screen + More actions: %1$s + The device was deleted in NetKit + The profile was deleted in NetKit + The launcher refused to pin the shortcut + Wi-Fi signal + diff --git a/androidApp/src/main/res/values-en/speedtest.xml b/androidApp/src/main/res/values-en/speedtest.xml index ea71771..2e3806a 100644 --- a/androidApp/src/main/res/values-en/speedtest.xml +++ b/androidApp/src/main/res/values-en/speedtest.xml @@ -34,12 +34,13 @@ Download Upload Done · download + Done · upload Error Stopped Speed %1$s Mbit/s The test was stopped; the result is not saved. The connection dropped or changed during the test. The result is incomplete. - The server name could not be resolved via the Wi-Fi network\'s DNS. + The server name could not be resolved using DNS on the active network. The server does not respond or the connection dropped. Secure connection (TLS) failed: invalid or untrusted server certificate. The server did not answer in time. @@ -73,6 +74,8 @@ Bufferbloat %1$s Server view (M-Lab) + Server view (iperf3) + TCP retransmits (all streams) Download (application) Download (TCP) Retransmissions @@ -98,7 +101,7 @@ Time How it is measured and what limits the result - This measures phone-to-server speed over the active connection: Wi-Fi, mobile data, ethernet or VPN. On a metered network (mobile data) a data estimate is shown before the test. The ceiling is the PHY link rate (in practice about 60–70 %), channel load, the router, the ISP line and the server uplink (rychlost.zelina.eu is a colleague\'s server on Proxmox, M-Lab is shared infrastructure). One test transfers hundreds of MB up to a few GB.\n\nLibreSpeed: 6 parallel HTTPS downloads and 3 uploads of random data, 10 s per direction, the first 2–4 s of ramp-up are excluded. Latency is an HTTP request to empty.php over a kept-alive connection (median; jitter = mean difference of consecutive samples); it includes server processing and is not an ICMP ping.\n\nNDT7: one WebSocket connection, the server ends the test within 10 s, the app after 15 s at most. It has no ping of its own; latency comes from the server\'s TCP_INFO (MinRTT and RTT during download). The server measures the whole test including ramp-up, the client excludes the first seconds, so a difference is expected; the server\'s upload figure is more accurate. Run both engines to compare.\n\nHistory keeps the last 20 results on the phone only, excluded from backup. No IP address is stored. + This measures phone-to-server speed over the active connection: Wi-Fi, mobile data, ethernet or VPN. On a metered network, you must confirm the data usage warning to start the test. The ceiling is the PHY link rate (in practice about 60–70 %), channel load, the router, the ISP line and the server uplink (rychlost.zelina.eu is a colleague\'s server on Proxmox, M-Lab is shared infrastructure). One test transfers hundreds of MB up to a few GB.\n\nLibreSpeed: 6 parallel HTTPS downloads and 3 uploads of random data, 10 s per direction, the first 2–4 s of ramp-up are excluded. Latency is an HTTP request to empty.php over a kept-alive connection (median; jitter = mean difference of consecutive samples); it includes server processing and is not an ICMP ping.\n\nNDT7: one WebSocket connection, the server ends the test within 10 s, the app after 15 s at most. It has no ping of its own; latency comes from the server\'s TCP_INFO (MinRTT and RTT during download). The server measures the whole test including ramp-up, the client excludes the first seconds, so a difference is expected; the server\'s upload figure is more accurate. Run both engines to compare.\n\nHistory keeps the last 20 results on the phone only, excluded from backup. For iperf3 the entered server and port are stored. M-Lab publishes results The NDT7 test runs on Measurement Lab servers. M-Lab stores every test including the public IP address it came from and publishes it as open data (internet research). Anyone reading M-Lab data can see that IP address. If that is fine, continue; the app remembers your consent. Otherwise use LibreSpeed. @@ -120,10 +123,27 @@ Signal at start Network Test on a metered network - The test will use about %1$s MB of mobile data. - The network is marked as metered. The test will use about %1$s MB of data. + The test will use about %1$s\u00a0MB of mobile data. + The network is marked as metered. The test will use about %1$s\u00a0MB of data. Estimated from the last result on this network type. It is always the full test. No result on this network type yet, so the estimate is conservative. It is always the full test. Start test Back + iperf3 (own server) + Host or IP address + TCP port (1–65535) + TCP streams (1–8) + Duration (3–30 s) + Limit per stream (Mbit/s, optional) + 0.01 to 1,000,000 Mbit/s. Leave blank or enter 0 for no limit. + Direction: upload ↑ + Direction: download ↓ + The test can saturate the link. Only test your own server or one you have permission to use. + The destination %1$s could not be verified as part of the local subnet. Do you have permission to load this path and server? + The iperf3 server refused the test. Another measurement may be running. + The iperf3 server terminated the test early. + The iperf3 server reported a test error. + The server sent more data than the configured limit allows. The test was stopped. + The test payload limit is %1$s\u00a0MB. Network overhead is additional. + An unlimited test can transfer several GB of data. diff --git a/androidApp/src/main/res/values-en/ssh_background_sftp.xml b/androidApp/src/main/res/values-en/ssh_background_sftp.xml new file mode 100644 index 0000000..e2de5b3 --- /dev/null +++ b/androidApp/src/main/res/values-en/ssh_background_sftp.xml @@ -0,0 +1,66 @@ + + + + Terminal sessions + Ongoing notification while at least one terminal session runs. Keeps the sessions alive in the background. + + %d active terminal session + %d active terminal sessions + + Session %1$d + Device %1$s + Tap to open the terminal + NetKit: terminal session running + Disconnect all + Without notifications a session stays in the background for 5 minutes at most. + Allow notifications + + Files (SFTP) + Files + Up one level + Refresh + Upload + New folder + Download + Rename + Delete + File actions + Name + Save + Create + Cancel + The folder is empty. + Link + Folder + Special file + + Showing the first %d item. + Showing the first %d items. + + + %d item with an invalid name hidden. + %d items with an invalid name hidden. + + Delete “%s” on the server? This cannot be undone. + Delete the empty folder “%s” on the server? + Delete the link “%s”? Its target stays. + Downloading “%s” + Uploading “%s” + %1$s of %2$s + %s transferred + File limit 2 GiB. An upload never overwrites an existing file. A transfer continues in the background while the session runs. + File saved. + File uploaded. + Renamed. + Deleted. + Folder created. + The file or folder does not exist on the server. + The server denied access. + An item with this name already exists; nothing was overwritten. + The server refused the operation (e.g. the folder is not empty). + The file is larger than 2 GiB. + Invalid name: no slash, “.” or “..”, at most 255 characters. + The SFTP connection failed. Try Refresh; the terminal session keeps running. + This item cannot be opened (the link does not lead to a folder or the server does not support it). + Transfer cancelled; the incomplete file was removed. + diff --git a/androidApp/src/main/res/values-en/ssh_console.xml b/androidApp/src/main/res/values-en/ssh_console.xml new file mode 100644 index 0000000..ff05005 --- /dev/null +++ b/androidApp/src/main/res/values-en/ssh_console.xml @@ -0,0 +1,43 @@ + + + Telnet + USB serial + Add profile · %1$s + Cisco / Huawei / FortiGate + MikroTik + Baud rate (1200–921600 Bd) + Data bits + Parity + Odd + Even + Mark + Space + Stop bits + Flow control + None + RTS/CTS + Telnet · %1$s + USB · %1$d Bd + Telnet · %1$s · TCP %2$d + Telnet sends your password and commands over the network in clear text. + I understand, hide this warning for this profile + Select the USB adapter port. + USB port unavailable. Check permission, cable, port use and adapter settings. + No supported USB adapter found. Connect it via OTG and refresh the list. + Refresh ports + Send BREAK (250 ms) + SSH lock + Unlock SSH + Use device screen lock + Authentication unavailable. Check your device screen lock settings. + Unlock duration · %1$d min + For each protected action + %1$d min + Group (optional) + Search profiles + No matching profiles + Manual order + Alphabetical + Recently used + Ungrouped + diff --git a/androidApp/src/main/res/values-en/ssh_design.xml b/androidApp/src/main/res/values-en/ssh_design.xml index 4be02c2..04e1282 100644 --- a/androidApp/src/main/res/values-en/ssh_design.xml +++ b/androidApp/src/main/res/values-en/ssh_design.xml @@ -18,4 +18,6 @@ Create or import a key %1$s · share the public part + Show session and keys + Hide session and keys diff --git a/androidApp/src/main/res/values-en/ssh_import.xml b/androidApp/src/main/res/values-en/ssh_import.xml index 2a01369..5f5e08c 100644 --- a/androidApp/src/main/res/values-en/ssh_import.xml +++ b/androidApp/src/main/res/values-en/ssh_import.xml @@ -1,7 +1,7 @@ - Import profiles - Import profiles + Import SSH profiles + Import SSH profiles New: %1$d · changed: %2$d · unchanged: %3$d · skipped: %4$d Source: %1$s New profiles @@ -15,7 +15,7 @@ Cancel Share public key No app is available to share or pick a file. - ProxyJump + ProxyJump (jump host not found or cycle) ProxyCommand Match pattern diff --git a/androidApp/src/main/res/values-en/ssh_productivity.xml b/androidApp/src/main/res/values-en/ssh_productivity.xml new file mode 100644 index 0000000..be26d4b --- /dev/null +++ b/androidApp/src/main/res/values-en/ssh_productivity.xml @@ -0,0 +1,86 @@ + + + Snippets + Saved commands for the bar above the terminal keyboard + + %1$d snippet + %1$d snippets + + Add snippet + Name + Command + Send Enter + All profiles + Only profile %1$s + Shown in + One line, no control characters. Snippets are not secrets: they are stored unencrypted and included in the profile export. + Looks like a password + The text contains a word such as password, secret or community. Snippets are stored unencrypted, shown in the bar and exported. Keep passwords in the profile (Keystore) instead. + Save anyway + Delete snippet “%1$s”? + No snippets yet. + Send snippet %1$s + Name 1–60 characters, command 1–4096 characters on one line. + At most 100 snippets. + + Record to file + Stop recording + Session log + The file receives plain text output of this session (no colours or control sequences) from now until you stop, the session ends or 50 MiB. The log may contain sensitive data (configurations, passwords printed by the server). You choose the file in the next step. + Choose file + Recording to file + Recording stopped: 50 MiB limit reached. + Recording stopped: the file cannot be written. + Recording stopped: output was faster than the file write. + Log saved. + + Jump host (ProxyJump) + Direct connection + Via %1$s + The connection goes through the selected profile (at most 3 hops). The server key is verified for each hop separately; the jump host resolves the target host. + The jump host profile no longer exists or forms a cycle. Choose another. + The jump host chain is invalid (missing profile, cycle or more than 3 hops). Edit the profile. + This profile is the jump host for: %1$s. They will then connect directly. + + Port forwarding + -L listens only on 127.0.0.1 of this phone and only during the session. The SSH server resolves the target host. Ports 1024–65535. + Local port + Target host + Target port + Add -L + Remove %1$s + SOCKS5 proxy (-D) + SOCKS5 port + CONNECT only, on 127.0.0.1. By default it requires a login (user and a random password valid for this session only, shown with the session). + active + port in use + error + Copy %1$s + SOCKS5 %1$s + Invalid rule or the port is already used. + Snippets: new %1$d · changed %2$d + A snippet with this name already exists for the same scope. Choose another name — otherwise the profile export would fail. + New and changed snippets are saved without “Send Enter”. Enable Enter manually in Snippets after checking the command. + before: %1$s + after: %1$s + new: %1$s + The file changes the command of an existing snippet. A familiar name would then send a different command. + I have checked the changed commands + login: %1$s / %2$s (this session only) + Copy SOCKS password + SOCKS5 without login: any app on the phone can use the tunnel into the remote network during the session. + No login (not recommended) + The -L port is reachable by every app on the phone during the session (127.0.0.1 cannot be limited to one app). It closes with the session. + + + %d tunnel + %d tunnels + + + %d error + %d errors + + SOCKS without login + Show tunnels + Hide tunnels + diff --git a/androidApp/src/main/res/values-en/ssh_terminal.xml b/androidApp/src/main/res/values-en/ssh_terminal.xml new file mode 100644 index 0000000..61b9665 --- /dev/null +++ b/androidApp/src/main/res/values-en/ssh_terminal.xml @@ -0,0 +1,5 @@ + + + + %1$s · “%2$s” + diff --git a/androidApp/src/main/res/values-en/strings.xml b/androidApp/src/main/res/values-en/strings.xml index fc724d3..7b92293 100644 --- a/androidApp/src/main/res/values-en/strings.xml +++ b/androidApp/src/main/res/values-en/strings.xml @@ -1,8 +1,8 @@ - SSH + Terminal WoL LAN scanner - SSH + SSH and consoles Wake-on-LAN Retry Add device diff --git a/androidApp/src/main/res/values-en/strings_lan.xml b/androidApp/src/main/res/values-en/strings_lan.xml index fdf2282..9293fbd 100644 --- a/androidApp/src/main/res/values-en/strings_lan.xml +++ b/androidApp/src/main/res/values-en/strings_lan.xml @@ -1,6 +1,6 @@ - + Scan only your own networks or networks you are authorized to manage. - Ping, traceroute and port checks to a public target use the active connection (Wi-Fi, mobile data, VPN). A local address (private, CGNAT, link-local) uses Wi-Fi; without Wi-Fi only a VPN, otherwise the tool refuses it. The network scan and mDNS run on Wi-Fi outside VPN only; DNS uses the Wi-Fi resolver, without Wi-Fi the active network. Traceroute uses a system ping process without Network binding; when the default network is not the measured one it requires confirmation. On mobile data many hops do not reply, which is normal. Missing ICMP replies do not mean a host is offline. Android usually cannot provide other hosts’ MAC addresses. Ranges are limited to 4096 hosts or ports. DNS lists A/AAAA; PTR is queried for IPv4. + Ping, traceroute and port checks to a public target use the active connection (Wi-Fi, mobile data, VPN). A local address (private, CGNAT, link-local) uses Wi-Fi; without Wi-Fi only a VPN, otherwise the tool refuses it. The network scan and mDNS run on Wi-Fi outside VPN only; DNS uses the Wi-Fi resolver, without Wi-Fi the active network. Traceroute uses a system ping process without Network binding; when the default network is not the measured one it requires confirmation. On mobile data many hops do not reply, which is normal. Missing ICMP replies do not mean a host is offline. Android usually cannot provide other hosts’ MAC addresses. Ranges are limited to 4096 hosts or ports. DNS lists A/AAAA; PTR is queried for IPv4. Ping and port checks also accept a single IPv6 address (link-local over Wi-Fi); IPv6 subnets are never scanned. unavailable Refresh network Hosts @@ -10,7 +10,7 @@ DNS mDNS IPv4/CIDR range - Hostname or IPv4 + Hostname, IPv4 or IPv6 Ports: 22,80,443 Common ports Read passive banner (max. 256 B) @@ -28,12 +28,12 @@ Enter a valid IPv4 range with prefix 0–32. The range exceeds 4096 hosts. Use a smaller range. Enter ports 1–65535 as a list or ascending ranges. Maximum 4096 ports. - Enter a valid hostname or IPv4 without spaces. + Enter a valid hostname, IPv4 or IPv6 address without spaces. Use a service type such as _http._tcp. or _ssh._tcp. - Operation failed. Check the connection, DNS, target and system restrictions. Probes support IPv4 only; DNS also lists AAAA. + Operation failed. Check the connection, DNS, target and system restrictions. Ping and ports support IPv4 and IPv6, traceroute and the MTU search IPv4 only; DNS lists A and AAAA. This implementation requires Android 14+ for mDNS: older APIs cannot guarantee both selected Wi-Fi and cancellation of service resolution. mDNS discovery finished after 12 seconds. Results depend on the selected service type and LAN multicast. - System ping did not provide every hop address or the target is not responding. The route is incomplete; missing hops cannot reliably be filled without raw ICMP. The test stops after five initially unknown hops. + System ping did not provide every hop address or the target is not responding. The route is incomplete; missing hops cannot reliably be filled without raw ICMP. Sent %1$d · received %2$d Ping: statistics and export use the last 600 samples, the graph and list the last 120 (newest first). Loss covers the whole session. Jitter = average absolute difference between adjacent successful replies. Round-trip time in ms · red dashed line = timeout @@ -82,4 +82,115 @@ The system or VPN refused the ICMP socket; ping cannot be measured. The device may still be reachable over TCP. Consent could not be saved; it applies only to the current connection to this Wi-Fi. The operation failed. Check Wi-Fi and try again. + Could not load or save tool preferences. + Subnets + IPv4/prefix or IPv4 and mask + Check the address and use a contiguous mask or wildcard. + Network + Mask + Wildcard + Broadcast + No broadcast + First host + Last host + Host count + Subnet range + Private (RFC 1918) + CGNAT + Link-local + Loopback + Multicast + Documentation + Other + New prefix for subnetting + + Enter a prefix between %1$d and 32. + + and %1$d more subnet + and %1$d more subnets + + Copy value + DNS (NXDOMAIN, 3) · Domain does not exist. + DNS (NOERROR) · No matching record. + DNS returned RCODE %1$d (%2$s). + unknown code + The system resolver failed without a DNS response. + The DNS resolver timed out. + The first five hops did not reply. Continue from TTL 6? + Continue + Advanced + Hide advanced options + Count 1–1000 (empty = unlimited) + Interval (0.2–10 s) + Payload (0–1472 B) + DF · don’t fragment + Check count, interval and payload in advanced options. + Too large, DF + Find largest payload with DF + Largest confirmed payload %1$d B · IPv4 packet %2$d B. + Finished testing the 548–1472 B range. + Even 548 B is too large with DF. + No echo reply. The exact MTU limit is undetermined. + Input address class + Mixed range + Using netmask (/%1$d) · Switch to wildcard + Using wildcard (/%1$d) · Switch to netmask + Value copied + Could not copy value + The interval is measured between probe starts. If a probe is lost, the next one waits for the timeout. + Estimated limit from repeated timeouts without ICMP frag-needed (possible PMTUD black hole). + DNS records + Web/TLS + RDAP + RDAP · %1$s + Malformed or oversized DNS response. + Enter a valid DNS name (or an IP address for PTR). + DNS name (or IP for PTR) + HTTP(S) URL + Enter an HTTP(S) URL without credentials. Redirects must follow the same rule. + Public IP or ASN + Starting sends the IP or ASN to rdap.org and the relevant registry. + The destination and redirect servers receive the requested URL and your source IP. HTTP sends the request in cleartext. + Comparing also sends the name to the Wi-Fi resolver outside the VPN. This may disclose an internal name. + Compare over Wi-Fi and VPN + Online lookups are off. Enable them in the public IP card menu in Overview. + Enter a public IP or public ASN. Private and reserved ranges cannot be queried. + The registry did not return a usable RDAP response. + The RDAP redirect limit was exceeded or the destination is not a supported HTTPS registry. + Reached the limit of five redirects. + The system could not complete a validated TLS handshake. + TLS · system validation passed + DNS %1$s · TCP %2$s · TLS %3$s · TTFB %4$s (ms) + Certificate %1$d + Subject: %1$s\nIssuer: %2$s\nValid from: %3$s\nValid until: %4$s\nSAN: %5$s\nSHA-256: %6$s + Network (CIDR) + Name + Country + Organization + Abuse email + ASN + Redirect stopped. The destination changed the port to one other than 80 or 443. + The next request was stopped. This probe cannot automatically continue to that host and IP address. + The destination address or network route changed. Start a new measurement. + %1$s resolved to the non-public address %2$s. Continue with this address? + %1$s (%2$s) is routed through a fake-IP proxy. The actual destination cannot be verified. Continue? + Redirect from %1$s to %2$s (%3$s) goes through a fake-IP proxy. The actual destination cannot be verified. Continue? + %1$s · previous measurement + Continue with this IP + Connected IP: %1$s + GET was skipped after the origin changed. + Fill in destination for a new probe + The certificate does not match the server name. + The system does not trust the server certificate chain. + A certificate in the chain has expired or is not yet valid. + TLS negotiation failed. Check the supported TLS versions and cipher suites. + DNS could not resolve the server name to an IP address. + TCP connection failed. The destination may have refused the connection. + Technical detail + The RDAP service blocked access (HTTP 403). + No registry or registration record was found for this object (HTTP 404). + rdap.org allows 10 requests per 10 seconds. The limit was exceeded (HTTP 429). Try again later. + The RDAP service temporarily rate-limited requests (HTTP 429). Try again later. + Retry in %1$d s + A network tool is running. Open RDAP after it finishes. diff --git a/androidApp/src/main/res/values-en/strings_ssh.xml b/androidApp/src/main/res/values-en/strings_ssh.xml index 26e9017..5993ec5 100644 --- a/androidApp/src/main/res/values-en/strings_ssh.xml +++ b/androidApp/src/main/res/values-en/strings_ssh.xml @@ -8,16 +8,16 @@ Connected Connecting… Close - Only connect to devices you are authorised to manage. SSH uses the standard Android route, including VPN. Up to 4 sessions; connections remain open in the background for up to 5 minutes, then close. Android may terminate them earlier. + Use the terminal only with devices you are authorised to manage. SSH and Telnet use the system route, including VPN. You can open four sessions. Without the foreground service they close after five minutes in the background. Terminal: a custom VT subset, ANSI/256 colours, alternate screen and 5000 history lines. Full xterm compatibility, wide characters and combining Unicode are not yet guaranteed. - Profile + SSH profile Keys Trusted hosts - Export profiles - Profiles exported without passwords, keys or secret references. + Export SSH profiles + SSH profiles exported without passwords, keys or secret references. SSH storage cannot be read. Existing data is preserved. Retry - No SSH profiles yet. + No profiles yet. Connect Edit Delete @@ -29,7 +29,8 @@ Cancel SSH profile Name - Host (DNS / IPv4 / IPv6 without brackets) + Host + DNS name, IPv4 or IPv6 without brackets Port Username Password diff --git a/androidApp/src/main/res/values-en/strings_wifi.xml b/androidApp/src/main/res/values-en/strings_wifi.xml index 2173efb..3cec09c 100644 --- a/androidApp/src/main/res/values-en/strings_wifi.xml +++ b/androidApp/src/main/res/values-en/strings_wifi.xml @@ -22,7 +22,6 @@ Channel occupancy %1$s · APs found: %2$d RSSI history · samples: %1$d - %1$s dBm Channel recommendation 2.4 GHz 5 GHz @@ -78,7 +77,10 @@ DNS returned an error (RCODE %1$d) Enter a numeric IPv4 address, for example 1.1.1.1. Enter a valid domain name, for example one.one.one.one. - %1$d of 4 scans remaining + + %1$d scan remaining out of %2$d + %1$d scans remaining out of %2$d + Next scan in about %1$d s The scan was not confirmed. Android limits scan frequency (usually 4 per 2 minutes). You can disable the limit in Developer options → Wi-Fi scan throttling. This is a phone system setting; NetKit does not change it. If Developer options are unavailable, About phone will open. Enable them by tapping the build number 7 times. diff --git a/androidApp/src/main/res/values-en/tools_targets.xml b/androidApp/src/main/res/values-en/tools_targets.xml new file mode 100644 index 0000000..af8f034 --- /dev/null +++ b/androidApp/src/main/res/values-en/tools_targets.xml @@ -0,0 +1,46 @@ + + + + Target history and favourites + Favourites + Recently used + No targets yet + Add to favourites + Remove from favourites + Remove %1$s from favourites + Clear history + Favourite target + Label (optional) + Save + History and favourites stay on this phone only. + You can keep at most 30 favourite targets. Remove one first. + This text is not a valid target. + + TCP ping + Port + Count (empty = until stopped) + One TCP connection per second, never two at once. A reply is a completed connection; a refusal (RST) or a timeout counts as loss. + The port must be 1–65535 and the count 1–1000 or empty. + refused + timed out + error + + MAC → vendor + MAC address or pasted output + One MAC or the output of show mac address-table, display mac-address or /interface bridge host print (at most 64 KiB and 2000 lines). Vendors come from the bundled IEEE OUI list, no internet connection. + Find vendors + Clear + The input is larger than 64 KiB. Paste a smaller part of the output. + The input has more than 2000 lines. Paste a smaller part of the output. + The input contains no MAC address in a supported form. + The vendor list could not be loaded; vendors are not shown. + MAC addresses + Count: %1$d + Known vendor: %1$d · no vendor: %2$d + Vendor not in the IEEE list + Locally administered address (no vendor) + Group address (no vendor) + local + multicast + %1$d× + diff --git a/androidApp/src/main/res/values-en/wifi_ext.xml b/androidApp/src/main/res/values-en/wifi_ext.xml new file mode 100644 index 0000000..7cba9d3 --- /dev/null +++ b/androidApp/src/main/res/values-en/wifi_ext.xml @@ -0,0 +1,67 @@ + + + Pin to chart + pinned + At most %1$d APs can be pinned. Unpin another one first. + Pinned to chart + Unpinned from chart + Pin or unpin in the chart + %1$s · not found in the last scan + Unpin + Unpin %1$s + The chart shows the connected AP, pinned APs and then the strongest. A pin follows the BSSID across new scans until the app is closed. + Group by SSID + Grouped by SSID · all bands + %1$d AP + ch. %1$s + Show this network\'s APs + Export scan + Export Wi-Fi scan + The file contains identifiers of nearby networks (SSID, BSSID, vendor). Save it only to trusted storage and share it with care. + The whole last scan in all bands is exported, regardless of the filter. The file stays only where you save it. + Choose file… + Cancel + Export saved. + The export could not be saved. Choose the file again. + Walk log + Walk the area with the phone: every second the signal, AP (BSSID), channel, link rate and gateway ping are recorded, plus roams and channel changes. Data stays in memory only until you export it. + Resolution is 1 s, so the length of a hand-over cannot be determined exactly. + At most %1$s h or %2$s samples. Leaving Overview or the app stops the recording; it never runs in the background. + Start recording + Stop + Mark + Place mark + E.g. kitchen, 2nd floor + Add + Mark added. + Type the mark text. + + Recording · %1$s · %2$d sample + Recording · %1$s · %2$d samples + + Duration + Samples + Roams + Channel changes + Weakest signal + Lost gateway pings + %1$d of %2$d + Marks + Recording finished. + Recording stopped when you left Overview or the app. + Recording reached its limit and stopped. + Export + Discard + New recording + Export walk log + The file contains identifiers of your APs (BSSID) and your place marks. Save it only to trusted storage. + CSV is one table of samples and events; the summary is in JSON only. + — + Region %1$s (%2$s): 2.4 GHz channels %3$d–%4$d. + 802.11b only: channel %1$d. + Channel %1$d is not permitted in this region. + For information, from the mobile network\'s country code. Scores and recommendations do not change. + EU + USA + Japan + diff --git a/androidApp/src/main/res/values-en/wifi_signal.xml b/androidApp/src/main/res/values-en/wifi_signal.xml index d4c5554..cc8c820 100644 --- a/androidApp/src/main/res/values-en/wifi_signal.xml +++ b/androidApp/src/main/res/values-en/wifi_signal.xml @@ -57,4 +57,12 @@ Where the data comes from and its limits RSSI and the negotiated (PHY) rate are reported by the Wi-Fi driver, usually refreshed every few seconds, so the chart can repeat a value. The modem reports the mobile signal (RSRP, RSRQ, SINR) only on a 2 dB change and at most every 3 s, so its chart is stepped. Receive and transmit are computed from whole-device counters (Wi-Fi, mobile data, VPN, tethering). Latency is measured by ICMP echo once per second to the Wi-Fi gateway and to the chosen target over the active network, DNS every 10 s through the resolver of the active network. The public IP comes from Cloudflare (1.1.1.1/cdn-cgi/trace) and the provider from Team Cymru over DNS, so both services see your public IP. Turn the lookup off in the menu of the Connection card. Everything runs only while this screen is open and the app is in the foreground. History keeps the last 15 minutes in memory only. Vertical lines in the chart mark roaming and a data SIM switch (blue), packet loss (red) and a channel or standard change (orange). + Wi-Fi 7 · MLO + AP MLD · %1$s + 60 GHz + %1$d dBm + active + idle + unassociated + Link %1$d · %2$s · %3$s · channel %4$s\nRSSI %5$s · AP width from scan %6$s diff --git a/androidApp/src/main/res/values-en/wifi_spectrum.xml b/androidApp/src/main/res/values-en/wifi_spectrum.xml index 3f9940b..fc35bee 100644 --- a/androidApp/src/main/res/values-en/wifi_spectrum.xml +++ b/androidApp/src/main/res/values-en/wifi_spectrum.xml @@ -16,6 +16,9 @@ dBm Spectrum %1$s: %2$d APs in the band, %3$d in the chart. Signal axis from %4$d to %5$d dBm. %1$d. %2$s · %3$s · %4$d dBm + width %1$d MHz, centre unknown + Width %1$d MHz, centre unknown: the AP does not report the channel centre and the primary channel does not determine it. The chart shows only the primary 20 MHz channel. + Channel 14 is outside the band permitted in the EU. %1$s · connected utilization %1$d%% Connection details diff --git a/androidApp/src/main/res/values-en/wol_secureon.xml b/androidApp/src/main/res/values-en/wol_secureon.xml new file mode 100644 index 0000000..113aad4 --- /dev/null +++ b/androidApp/src/main/res/values-en/wol_secureon.xml @@ -0,0 +1,13 @@ + + + + SecureOn + Optional network card password: 6 bytes like a MAC (11:22:33:44:55:66) or 4 bytes like IPv4. Stored encrypted on this phone only and never exported. + A SecureOn password is stored (encrypted). An empty field keeps it, a new one replaces it. It never goes into an export. + SecureOn password (optional) + Remove the stored password + Enter 6 bytes like 11:22:33:44:55:66 or 4 bytes like 192.0.2.1. + SecureOn password unavailable — enter it again in the device editor. The packet was not sent without it. + The stored SecureOn password belongs to another MAC or target of this device, so waking is blocked. Enter the password again; saving without one deletes it. + SecureOn password unavailable + diff --git a/androidApp/src/main/res/values-en/wol_widget.xml b/androidApp/src/main/res/values-en/wol_widget.xml new file mode 100644 index 0000000..e8b62eb --- /dev/null +++ b/androidApp/src/main/res/values-en/wol_widget.xml @@ -0,0 +1,19 @@ + + + Wake (WoL) + Wakes the selected device with one tap + Choose a device + Tap to choose + Ready + Sending… + Sent %1$s + No Wi-Fi + Cannot determine broadcast + Sending failed + Device deleted, tap to choose + Wake + WoL widget + Choose the device this widget wakes + No devices yet. Add one on the WoL tab. + The device list could not be loaded. + diff --git a/androidApp/src/main/res/values-night/netstatus_widget_colors.xml b/androidApp/src/main/res/values-night/netstatus_widget_colors.xml new file mode 100644 index 0000000..af80e02 --- /dev/null +++ b/androidApp/src/main/res/values-night/netstatus_widget_colors.xml @@ -0,0 +1,5 @@ + + + + #FF93A6B3 + diff --git a/androidApp/src/main/res/values/accessibility.xml b/androidApp/src/main/res/values/accessibility.xml new file mode 100644 index 0000000..8ef641f --- /dev/null +++ b/androidApp/src/main/res/values/accessibility.xml @@ -0,0 +1,25 @@ + + + Ping dokončen. Počet odpovědí: %1$d z %2$d. + TCP ping dokončen. Počet odpovědí: %1$d z %2$d. + Průměrná odezva %1$.2f ms. + Průměrná odezva v posledních %1$d měřeních: %2$.2f ms. + Traceroute dokončen. Počet skoků: %1$d, s odpovědí: %2$d. + Sken portů dokončen. Otevřené porty: %1$d z %2$d. + Sken zařízení dokončen. Počet nalezených zařízení: %1$d. + + DNS dotaz dokončen. Počet vrácených adres: %1$d. + Dotaz na DNS záznamy dokončen. Počet řádků výsledku: %1$d. + Měření iperf3 dokončeno. + Test rychlosti dokončen. + Stahování %1$.2f Mbit/s. + Odesílání %1$.2f Mbit/s. + Probíhá sken zařízení. + Probíhá ping. + Probíhá sken portů. + %1$s. Minimum %2$s, maximum %3$s. Poslední hodnota v okně: %4$s. + %1$s. Bez měření. + bez hodnoty + Nejsilnější přístupový bod: %1$s, kanál %2$d, %3$d dBm. + diff --git a/androidApp/src/main/res/values/backup.xml b/androidApp/src/main/res/values/backup.xml new file mode 100644 index 0000000..156e656 --- /dev/null +++ b/androidApp/src/main/res/values/backup.xml @@ -0,0 +1,40 @@ + + Záloha konfigurace + Soubor obsahuje profily, otisky serverů, příkazy, cíle a nastavení. Zkontrolujte vlastní texty a poznámky, zda jste do nich nevložili přihlašovací údaje. + Šifrovat zálohu heslem + Uložit čitelnou zálohu? + Kdokoli se souborem může přečíst adresy, uživatelská jména a příkazy a změnit obsah zálohy. + Použít čitelný JSON + Heslo zálohy + Vytvořit zálohu + Otevřít zálohu k obnově + Dešifrovat a zobrazit náhled + Vyberte sekce k obnovení. Předvolby, oblíbené cíle, servery a nastavení se nahradí. Profily a zařízení se sloučí. + Nové %1$d · změněné %2$d · přeskočené %3$d + Obnovit vybrané sekce + NetKit připraví změny a zavře se. Při dalším spuštění je uplatní společně. Pokud se mezitím změní dotčené úložiště, obnovu zruší. + Potvrdit a zavřít NetKit + Před obnovou dokončete měření, zavřete relace a rozpracované editory. + Obnova se neprovedla. Otevřete soubor znovu a zkontrolujte aktuální náhled. + Soubor se nepodařilo zpracovat. Zkontrolujte formát, verzi, velikost a dostupnost úložiště. + Nesprávné heslo nebo poškozená šifrovaná záloha. + Záloha byla uložena. + Vybraná konfigurace byla obnovena. + Důvěru serverům obnovte jen z ověřené zálohy. Existující odlišné nebo odmítnuté otisky se přeskočí. + SSH profily a skupiny + Telnet profily + Sériové profily + Terminálové snippety + Přesměrování SSH + Důvěryhodné SSH servery + Zařízení Wake-on-LAN + Předvolby nástrojů + Oblíbené cíle + Servery LibreSpeed a iperf3 + Obnovu se nepodařilo dokončit. NetKit ji při dalším spuštění zkusí znovu. + Záloha obsahuje text připomínající přihlašovací údaj. Zkontrolujte příkazy, snippety a poznámky. + Zkontrolujte jedinečnost názvů SSH profilů a velikost jejich exportu. + Pro importované karty se zneplatní dříve uložená hesla SecureOn, i když je konfigurace shodná. + Mapa obnovené konfigurace byla poškozená. NetKit použil výchozí úložiště a poškozený soubor odložil stranou. Obnovte zálohu znovu, pokud vám chybí nastavení. + Obnoví se bez klíče. Klíč profilu je třeba znovu přiřadit. + diff --git a/androidApp/src/main/res/values/cellular.xml b/androidApp/src/main/res/values/cellular.xml index a6a9451..2e7b5c9 100644 --- a/androidApp/src/main/res/values/cellular.xml +++ b/androidApp/src/main/res/values/cellular.xml @@ -41,4 +41,36 @@ Bez oprávnění k telefonu je vidět jen SIM s daty Bez oprávnění k telefonu je vidět jen SIM, která nese data. Čísla, IMEI ani identifikátory SIM se nečtou. Oprávnění lze udělit v nastavení aplikace. Bez přístupu k poloze Android neposílá jméno operátora ze sítě; použije se jméno ze SIM. + + + Detail buňky + Rozbaleno + Sbaleno + Pásmo, PCI, ID buňky a sousední buňky vydá Android jen s přesnou polohou a oprávněním k telefonu. Nic dalšího se nežádá a údaje zůstávají jen v zařízení. + Povolit polohu + Povolit telefon + Nastavení aplikace + Načítám buňky… + Modem buňky nevrátil, další pokus za 5 s. + Systém nevrátil žádné buňky. Bez zapnuté polohy (služby určování polohy) je Android nevydá. + Připojeno přes %1$s – detail je jen pro LTE a 5G. + Jen v zařízení: ID buňky a TAC prozrazují přibližnou polohu, proto se neukládají, neexportují, nesdílejí ani neodesílají. Obnova nejvýš jednou za 5 s, jen při otevřeném detailu. + Hlavní + Sekundární + 5G NR + %1$s MHz + %1$s (odhad) + EARFCN + NR-ARFCN + PCI + ID buňky (ECI) + ID buňky (NCI) + %1$s (eNB %2$s · %3$d) + TAC + Šířka kanálu + Timing advance + Sousední buňky (%1$d) + Modem nehlásí žádné sousední buňky. + PCI %1$d + ARFCN %1$d diff --git a/androidApp/src/main/res/values/ids.xml b/androidApp/src/main/res/values/ids.xml index 698ecfd..25b6734 100644 --- a/androidApp/src/main/res/values/ids.xml +++ b/androidApp/src/main/res/values/ids.xml @@ -1,4 +1,6 @@ + + diff --git a/androidApp/src/main/res/values/lan_rozsireni.xml b/androidApp/src/main/res/values/lan_rozsireni.xml new file mode 100644 index 0000000..3337b04 --- /dev/null +++ b/androidApp/src/main/res/values/lan_rozsireni.xml @@ -0,0 +1,45 @@ + + + + Info o síti + Zobrazit + Skrýt + Rozhraní + IPv4 + Brána + DNS servery + Doména hledání + DHCP server + MTU rozhraní + IPv6 globální + IPv6 ULA + IPv6 link-local + žádné + neznámé + nedostupné (Android 11+) + Traceroute zatím umí jen IPv4. Pro IPv6 cíl použijte ping nebo kontrolu portů. + Hledání MTU (DF) existuje jen pro IPv4; IPv6 se po cestě nefragmentuje. + Zóna IPv6 adresy (rozhraní za znakem procenta) neodpovídá síti, přes kterou se měří. Zónu vynechte nebo zadejte rozhraní Wi-Fi. + Služby (UDP) + Jen tento host: SNMP v2c (sysName, sysDescr), NTP a verze DNS serveru. Každá sonda nejvýš 2 pokusy po 1,5 s. Komunitu SNMP zadejte jen pro vlastní zařízení; neukládá se a prázdné pole SNMP přeskočí. + Komunita SNMP (nepovinné) + Identifikovat služby + Ptám se na SNMP, NTP a DNS… + Zrušeno. + SNMP + SNMP sysName + SNMP sysDescr + přeskočeno (bez komunity) + chyba agenta (error-status %1$d) + NTP + stratum %1$d · %2$s + kiss-o’-death %1$s + nesynchronizováno + Verze DNS (version.bind) + odpovídá, verzi neuvádí (RCODE %1$d) + přeskočeno (host není DNS serverem sítě a TCP 53 nebyl nalezen) + neodpovídá + port zavřený + neplatná odpověď + — + diff --git a/androidApp/src/main/res/values/lan_wol.xml b/androidApp/src/main/res/values/lan_wol.xml new file mode 100644 index 0000000..38c1c84 --- /dev/null +++ b/androidApp/src/main/res/values/lan_wol.xml @@ -0,0 +1,13 @@ + + + + MAC (NetBIOS) + Přidat do WoL + Odesílám magic packet… + Magic packet odeslán + Není Wi-Fi + Odeslání se nezdařilo + MAC z NetBIOS se předvyplní: %1$s. Před uložením ji zkontrolujte. + MAC zadejte ručně: Android aplikacím nedovolí číst tabulku ARP. + Probudit: %1$s + diff --git a/androidApp/src/main/res/values/netstatus_widget.xml b/androidApp/src/main/res/values/netstatus_widget.xml new file mode 100644 index 0000000..a123abd --- /dev/null +++ b/androidApp/src/main/res/values/netstatus_widget.xml @@ -0,0 +1,42 @@ + + + + Stav sítě + Poslední změřený signál Wi-Fi a rychlost se stářím měření + Wi-Fi + Zatím bez měření + Otevři NetKit pro měření + Bez Wi-Fi + Signál zatím neměřen + %1$d dBm + kanál %1$d + k. %1$d + 2,4 GHz + 5 GHz + 6 GHz + %1$d MHz + Link ↓%1$s ↑%2$s Mb/s + brána %1$s ms + Speedtest ↓%1$s ↑%2$s Mb/s + %1$s ms + Veřejná IP %1$s + %1$s (%2$s) + naposledy %1$s + Měřeno %1$s + + před %s + Signál před %s + Obnoveno před %s + Obnovit signál + Widget Stav sítě + Co smí widget ukazovat. Platí pro všechny widgety stavu sítě. + Zobrazit název sítě (SSID) + Ukládá se jen SSID z měření v aplikaci, na zamčené obrazovce se nezobrazuje. Vypnutí volby nebo odebrání oprávnění k poloze uložené SSID smaže. + Aplikace nemá oprávnění k přesné poloze, SSID se ukládat nebude. + Zobrazit veřejnou IP + Jen poslední hodnota zjištěná v Přehledu; widget sám nic nezjišťuje ani neposílá. + Zjišťování veřejné IP je v Přehledu vypnuté, nic se ukládat nebude. + Widget ukazuje poslední měření z Přehledu a rychlostního testu. Ikona obnovení přečte aktuální signál bez polohy a bez síťového provozu. Klepnutí na widget otevře Přehled. + Uložit + Nastavení se nepodařilo uložit. + diff --git a/androidApp/src/main/res/values/netstatus_widget_colors.xml b/androidApp/src/main/res/values/netstatus_widget_colors.xml new file mode 100644 index 0000000..2794466 --- /dev/null +++ b/androidApp/src/main/res/values/netstatus_widget_colors.xml @@ -0,0 +1,5 @@ + + + + #FF4E6372 + diff --git a/androidApp/src/main/res/values/settings.xml b/androidApp/src/main/res/values/settings.xml new file mode 100644 index 0000000..810fb7a --- /dev/null +++ b/androidApp/src/main/res/values/settings.xml @@ -0,0 +1,62 @@ + + + + Nastavení + Nastavení se nepodařilo uložit; platí do zavření aplikace. + + Vzhled + Motiv + Systém + Světlý + Tmavý + + Jazyk + Systém + Čeština + English + Volbu ukládá Android; najdete ji i v Nastavení systému → Aplikace → NetKit → Jazyk. + Systémové nastavení jazyka + Jazyk aplikace v Androidu + Systémové nastavení jazyka se nepodařilo otevřít. + Volba jazyka aplikace je v Androidu 13 a novějším. Tady se NetKit řídí jazykem systému: angličtina pro anglický systém, jinak čeština. + + Měření + Displej zapnutý během měření + Záznam obchůzky, rychlost a iperf3, ping, TCP ping, traceroute, kontrola portů a připojený terminál. Když displej zhasne, NetKit měření ukončí, na pozadí neběží. + + Souhlasy a online dotazy + Online dotazy + Veřejná IP a poskytovatel v Přehledu (Cloudflare, DNS Team Cymru), RDAP v Nástrojích a veřejná IP ve widgetu stavu sítě. + Automatické hledání v LAN + Zapomene odpovědi u všech sítí, aplikace se znovu zeptá. + Upozornění M-Lab (NDT7) + Potvrzeno, před testem se nezobrazuje + Zobrazí se před testem NDT7 + Zapomenout + Zobrazit znovu + + Historie a cíle + Historie rychlosti (LibreSpeed, NDT7) + Historie iperf3 + + %d záznam + %d záznamy + %d záznamu + %d záznamů + + Poslední server iperf3 + Žádný + Vymazat historii cílů + Smazat z historie cílů %1$s? Oblíbené cíle zůstanou uložené. + Smazat + + Smazat historii? + %1$s: %2$s. Smazání nejde vrátit. + Zapomenout souhlasy? + Automatické hledání zařízení se u každé sítě znovu zeptá. Ruční hledání funguje dál. + Zrušit + Hotovo + Nepodařilo se uložit + + Kontrola aktualizací je v Nastavení + diff --git a/androidApp/src/main/res/values/sharing.xml b/androidApp/src/main/res/values/sharing.xml new file mode 100644 index 0000000..72378ba --- /dev/null +++ b/androidApp/src/main/res/values/sharing.xml @@ -0,0 +1,84 @@ + + + + Diagnostický report NetKit + Měření rychlosti NetKit + Čas + Verze aplikace + Síť + Typ sítě + Měřená síť + Rozhraní + IPv4 + IPv6 + Brána + DNS + Soukromé DNS + DHCP server + MTU + Wi-Fi + SSID + BSSID + Signál + Rychlost linky RX/TX + Kanál + Pásmo + Šířka kanálu + Standard + Latence (poslední minuta) + Brána + Internet + ztráty + bez dat + Veřejná IP + Adresa + ASN + Poskytovatel + Poslední test rychlosti + Poslední iperf3 + Server + Měření + Stahování + Odesílání + Latence + Jitter + Retransmise + neúplný výsledek + ano + ne + Diagnostický report + Diagnostický report + Sestavuji report… + Zahrnout SSID + Zahrnout BSSID + Zahrnout veřejné adresy + SSID, BSSID, veřejné adresy telefonu a brány, jméno serveru Private DNS a jméno či veřejná adresa serveru iperf3 mohou identifikovat vaši síť. Přidejte je jen při sdílení s důvěryhodným příjemcem. + Náhled reportu + Kopírovat + Sdílet + Uložit + Zavřít + Sdílet diagnostický report + Report zkopírován + Report se nepodařilo zkopírovat + Sdílení se nepodařilo otevřít + Report uložen + Report se nepodařilo uložit + Report vzniká jen v telefonu z hodnot, které Přehled už změřil, a odchází jen tam, kam ho sami zkopírujete, nasdílíte nebo uložíte. Neobsahuje údaje o mobilní buňce ani hesla. + Exportovat seznam + Export seznamu zařízení + Soubor obsahuje adresy, názvy, MAC adresy a otevřené porty zařízení ve vaší síti. Sdílejte ho jen s tím, komu věříte. + Názvy, bannery a údaje UPnP posílají samotná zařízení; v exportu jsou očištěné od řídicích znaků. + Uložit + Zrušit + Seznam zařízení uložen + Seznam zařízení se nepodařilo uložit + Sdílet výsledek + Sdílet výsledek + Zahrnout SSID + Text obsahuje čas, typ sítě, server, rychlosti a latenci. SSID je ve výchozím stavu vynechané. + Sdílet výsledek měření + Sdílet + Sdílení se nepodařilo otevřít + Zrušit + diff --git a/androidApp/src/main/res/values/shortcuts.xml b/androidApp/src/main/res/values/shortcuts.xml new file mode 100644 index 0000000..dbe702c --- /dev/null +++ b/androidApp/src/main/res/values/shortcuts.xml @@ -0,0 +1,20 @@ + + + + Signál + Signál Wi-Fi (Přehled) + Spektrum + Spektrum Wi-Fi + Ping + Ping (Nástroje) + Podsítě + Kalkulačka podsítí + + Přidat na plochu + Další akce: %1$s + Zařízení bylo v NetKitu smazáno + Profil byl v NetKitu smazán + Spouštěč připnutí zkratky odmítl + + Signál Wi-Fi + diff --git a/androidApp/src/main/res/values/speedtest.xml b/androidApp/src/main/res/values/speedtest.xml index 6f3bbbb..6d2ebd2 100644 --- a/androidApp/src/main/res/values/speedtest.xml +++ b/androidApp/src/main/res/values/speedtest.xml @@ -37,6 +37,7 @@ Stahování Odesílání Hotovo · stahování + Hotovo · odesílání Chyba Zastaveno Rychlost %1$s Mbit/s @@ -44,7 +45,7 @@ Připojení se během testu odpojilo nebo změnilo. Výsledek je neúplný. - Název serveru se nepodařilo přeložit přes DNS Wi-Fi sítě. + Název serveru se nepodařilo přeložit přes DNS aktivní sítě. Server neodpovídá nebo spojení spadlo. Zabezpečené spojení (TLS) selhalo: neplatný nebo nedůvěryhodný certifikát serveru. Server neodpověděl v časovém limitu. @@ -84,6 +85,8 @@ Pohled serveru (M-Lab) + Pohled serveru (iperf3) + TCP retransmise (součet streamů) Stahování (aplikace) Stahování (TCP) Opakované přenosy @@ -111,7 +114,7 @@ Jak se měří a co výsledek omezuje - Měří se rychlost od telefonu k serveru přes aktivní připojení: Wi-Fi, mobilní data, ethernet nebo VPN. Na měřené síti (mobilní data) se před testem zobrazí odhad spotřeby dat. Strop tvoří PHY rychlost spojení (reálně asi 60–70 %), vytížení kanálu, router, linka ISP i uplink serveru (rychlost.zelina.eu je server kolegy na Proxmoxu, M-Lab je sdílená infrastruktura). Jeden test přenese stovky MB až jednotky GB.\n\nLibreSpeed: 6 paralelních HTTPS stahování a 3 odesílání náhodných dat, každý směr 10 s, první 2–4 s náběhu se nezapočítávají. Latence je HTTP dotaz na empty.php přes udržované spojení (medián, jitter = průměrný rozdíl po sobě jdoucích), zahrnuje zpracování na serveru a není to ICMP ping.\n\nNDT7: jedno spojení WebSocket, server ukončí test do 10 s, aplikace nejpozději po 15 s. Vlastní ping nemá, latence je z TCP_INFO serveru (MinRTT a RTT během stahování). Server měří celý test včetně náběhu, klient bez prvních sekund, rozdíl je proto očekávaný; odesílání podle serveru je přesnější. Pro srovnání pusťte oba enginy.\n\nHistorie drží posledních 20 výsledků jen v telefonu, mimo zálohu. IP adresa se neukládá. + Měří se rychlost od telefonu k serveru přes aktivní připojení: Wi-Fi, mobilní data, ethernet nebo VPN. Na měřené síti se zobrazí upozornění na spotřebu dat. Test spustíte až potvrzením. Strop tvoří PHY rychlost spojení (reálně asi 60–70 %), vytížení kanálu, router, linka ISP i uplink serveru (rychlost.zelina.eu je server kolegy na Proxmoxu, M-Lab je sdílená infrastruktura). Jeden test přenese stovky MB až jednotky GB.\n\nLibreSpeed: 6 paralelních HTTPS stahování a 3 odesílání náhodných dat, každý směr 10 s, první 2–4 s náběhu se nezapočítávají. Latence je HTTP dotaz na empty.php přes udržované spojení (medián, jitter = průměrný rozdíl po sobě jdoucích), zahrnuje zpracování na serveru a není to ICMP ping.\n\nNDT7: jedno spojení WebSocket, server ukončí test do 10 s, aplikace nejpozději po 15 s. Vlastní ping nemá, latence je z TCP_INFO serveru (MinRTT a RTT během stahování). Server měří celý test včetně náběhu, klient bez prvních sekund, rozdíl je proto očekávaný; odesílání podle serveru je přesnější. Pro srovnání pusťte oba enginy.\n\nHistorie drží posledních 20 výsledků jen v telefonu, mimo zálohu. U iperf3 se ukládá vámi zadaný server a port. M-Lab zveřejňuje výsledky @@ -135,10 +138,27 @@ Signál na začátku Síť Test na měřené síti - Test spotřebuje přibližně %1$s MB mobilních dat. - Síť je označená jako měřená. Test spotřebuje přibližně %1$s MB dat. + Test spotřebuje přibližně %1$s\u00a0MB mobilních dat. + Síť je označená jako měřená. Test spotřebuje přibližně %1$s\u00a0MB dat. Odhad podle posledního výsledku na tomto typu sítě. Vždy jde o plný test. Na tomto typu sítě zatím není výsledek, odhad je konzervativní. Vždy jde o plný test. Spustit test Zpět + iperf3 (vlastní server) + Host nebo IP adresa + TCP port (1–65535) + Počet TCP streamů (1–8) + Délka testu (3–30 s) + Limit na stream (Mbit/s, nepovinný) + 0,01 až 1 000 000 Mbit/s. Prázdné pole nebo 0 znamená bez limitu. + Směr: odesílání ↑ + Směr: stahování ↓ + Test může vytížit celou linku. Spouštějte jej jen proti vlastnímu nebo povolenému serveru. + Cíl %1$s není ověřený jako součást místní podsítě. Máte oprávnění zatížit tuto trasu a server? + Server iperf3 odmítl test. Může právě měřit s jiným klientem. + Server iperf3 předčasně ukončil měření. + Server iperf3 ohlásil chybu měření. + Server poslal víc dat, než odpovídá nastavenému limitu. Test byl ukončen. + Limit testovacích dat je %1$s\u00a0MB. Síťová režie se přičítá zvlášť. + Neomezený test může přenést i několik GB. diff --git a/androidApp/src/main/res/values/ssh_background_sftp.xml b/androidApp/src/main/res/values/ssh_background_sftp.xml new file mode 100644 index 0000000..92cd7c6 --- /dev/null +++ b/androidApp/src/main/res/values/ssh_background_sftp.xml @@ -0,0 +1,72 @@ + + + + Relace terminálu + Trvalé oznámení, dokud běží aspoň jedna relace terminálu. Drží relace naživu na pozadí. + + %d aktivní relace terminálu + %d aktivní relace terminálu + %d aktivní relace terminálu + %d aktivních relací terminálu + + Relace %1$d + Zařízení %1$s + Klepnutím otevřete terminál + NetKit: relace terminálu běží + Odpojit vše + Bez oznámení zůstane relace na pozadí nejvýše 5 minut. + Povolit oznámení + + Soubory (SFTP) + Soubory + O úroveň výš + Obnovit + Nahrát + Nová složka + Stáhnout + Přejmenovat + Smazat + Akce se souborem + Název + Uložit + Vytvořit + Zrušit + Složka je prázdná. + Odkaz + Složka + Speciální soubor + + Zobrazena první %d položka. + Zobrazeny první %d položky. + Zobrazeno prvních %d položky. + Zobrazeno prvních %d položek. + + + %d položka s neplatným názvem skryta. + %d položky s neplatným názvem skryty. + %d položky s neplatným názvem skryto. + %d položek s neplatným názvem skryto. + + Smazat „%s“ na serveru? Nelze vrátit. + Smazat prázdnou složku „%s“ na serveru? + Smazat odkaz „%s“? Cíl odkazu zůstane. + Stahování „%s“ + Nahrávání „%s“ + %1$s z %2$s + %s přeneseno + Limit souboru 2 GiB. Nahrání nikdy nepřepíše existující soubor. Přenos pokračuje i na pozadí, dokud běží relace. + Soubor uložen. + Soubor nahrán. + Přejmenováno. + Smazáno. + Složka vytvořena. + Soubor nebo složka na serveru neexistuje. + Server odmítl přístup. + Položka s tímto názvem už existuje; nic se nepřepsalo. + Server operaci odmítl (např. složka není prázdná). + Soubor je větší než 2 GiB. + Neplatný název: bez lomítka, „.“ a „..“, nejvýše 255 znaků. + SFTP spojení selhalo. Zkuste Obnovit; relace terminálu běží dál. + Tuto položku nelze otevřít (odkaz nevede na složku nebo server operaci nepodporuje). + Přenos zrušen; nedokončený soubor byl odstraněn. + diff --git a/androidApp/src/main/res/values/ssh_console.xml b/androidApp/src/main/res/values/ssh_console.xml new file mode 100644 index 0000000..e15a508 --- /dev/null +++ b/androidApp/src/main/res/values/ssh_console.xml @@ -0,0 +1,43 @@ + + + Telnet + Sériová linka USB + Přidat profil · %1$s + Cisco / Huawei / FortiGate + MikroTik + Přenosová rychlost (1200–921600 Bd) + Datové bity + Parita + Lichá + Sudá + Mark + Space + Stop bity + Řízení toku + Žádné + RTS/CTS + Telnet · %1$s + USB · %1$d Bd + Telnet · %1$s · TCP %2$d + Telnet nešifruje spojení. Heslo i příkazy se po síti přenášejí v čitelné podobě. + Rozumím, nezobrazovat pro tento profil + Vyberte USB port převodníku. + USB port nelze použít. Ověřte oprávnění, kabel, obsazení portu a podporu nastavení převodníkem. + Žádný podporovaný USB převodník. Připojte jej přes OTG a obnovte seznam. + Obnovit porty + Odeslat BREAK (250 ms) + Zámek SSH + Odemknout SSH + Použít zámek zařízení + Ověření není dostupné. Zkontrolujte zámek obrazovky v nastavení zařízení. + Platnost odemčení · %1$d min + Při každé chráněné akci + %1$d min + Skupina (volitelná) + Hledat profil + Žádný odpovídající profil + Ruční pořadí + Abecedně + Naposledy použité + Bez skupiny + diff --git a/androidApp/src/main/res/values/ssh_design.xml b/androidApp/src/main/res/values/ssh_design.xml index 49f5223..9840477 100644 --- a/androidApp/src/main/res/values/ssh_design.xml +++ b/androidApp/src/main/res/values/ssh_design.xml @@ -20,4 +20,6 @@ Vytvořit nebo importovat klíč %1$s · sdílet veřejnou část + Zobrazit relace a klávesy + Skrýt relace a klávesy diff --git a/androidApp/src/main/res/values/ssh_import.xml b/androidApp/src/main/res/values/ssh_import.xml index 6d5cf0d..47bbec7 100644 --- a/androidApp/src/main/res/values/ssh_import.xml +++ b/androidApp/src/main/res/values/ssh_import.xml @@ -1,6 +1,6 @@ - Importovat profily + Importovat SSH profily Import profilů Nové: %1$d · změněné: %2$d · beze změny: %3$d · přeskočené: %4$d Zdroj: %1$s @@ -15,7 +15,7 @@ Zrušit Sdílet veřejný klíč Žádná aplikace pro sdílení ani výběr souboru není k dispozici. - ProxyJump + ProxyJump (jump host nenalezen nebo cyklus) ProxyCommand Match vzor diff --git a/androidApp/src/main/res/values/ssh_productivity.xml b/androidApp/src/main/res/values/ssh_productivity.xml new file mode 100644 index 0000000..57d98fb --- /dev/null +++ b/androidApp/src/main/res/values/ssh_productivity.xml @@ -0,0 +1,93 @@ + + + + Snippety + Uložené příkazy pro panel nad klávesnicí terminálu + + %1$d snippet + %1$d snippety + %1$d snippetu + %1$d snippetů + + Přidat snippet + Název + Příkaz + Odeslat Enter + Všechny profily + Jen profil %1$s + Kde se zobrazí + Jeden řádek, bez řídicích znaků. Snippety nejsou tajemství: ukládají se nešifrovaně a jsou součástí exportu profilů. + Vypadá jako heslo + Text obsahuje slovo typu password, secret nebo community. Snippet se ukládá nešifrovaně, je vidět v panelu a exportuje se. Heslo raději ukládejte v profilu (Keystore). + Uložit přesto + Smazat snippet „%1$s“? + Zatím žádné snippety. + Odeslat snippet %1$s + Název 1–60 znaků, příkaz 1–4096 znaků na jednom řádku. + Nejvýše 100 snippetů. + + Zaznamenávat do souboru + Zastavit záznam + Záznam relace + Do souboru se uloží čistý text výstupu této relace (bez barev a řídicích sekvencí) od teď do zastavení, konce relace nebo 50 MiB. Log může obsahovat citlivé údaje (konfigurace, hesla vypsaná serverem). Soubor si zvolíte v dalším kroku. + Vybrat soubor + Zaznamenává se do souboru + Záznam zastaven: dosažen limit 50 MiB. + Záznam zastaven: do souboru nejde zapisovat. + Záznam zastaven: výstup byl rychlejší než zápis do souboru. + Záznam uložen. + + Jump host (ProxyJump) + Přímé spojení + Přes %1$s + Spojení vede přes vybraný profil (nejvýše 3 skoky). Klíč serveru se ověřuje pro každý skok zvlášť; host cíle překládá jump host. + Jump host profilu už neexistuje nebo tvoří cyklus. Vyberte jiný. + Řetěz jump hostů je neplatný (chybí profil, cyklus nebo víc než 3 skoky). Upravte profil. + Profil je jump host pro: %1$s. Ty se pak budou připojovat přímo. + + Přesměrování portů + -L naslouchá jen na 127.0.0.1 tohoto telefonu a jen během relace. Cílový host překládá SSH server. Porty 1024–65535. + Místní port + Cílový host + Cílový port + Přidat -L + Odebrat %1$s + SOCKS5 proxy (-D) + Port SOCKS5 + Jen CONNECT na 127.0.0.1. Ve výchozím stavu vyžaduje přihlášení (uživatel a náhodné heslo platné jen pro relaci, zobrazí se u relace). + aktivní + port obsazený + chyba + Kopírovat %1$s + SOCKS5 %1$s + Neplatné pravidlo nebo port už je použitý. + Snippety: nové %1$d · změněné %2$d + Snippet s tímto názvem už pro stejný rozsah existuje. Zvolte jiný název — jinak by export profilů selhal. + Nové a změněné snippety se uloží bez „Odeslat Enter“. Enter zapnete ručně v Snippetech po kontrole příkazu. + před: %1$s + po: %1$s + nový: %1$s + Soubor mění příkaz existujícího snippetu. Pod známým názvem by se pak poslal jiný příkaz. + Zkontroloval(a) jsem změněné příkazy + přihlášení: %1$s / %2$s (jen pro tuto relaci) + Kopírovat heslo SOCKS + SOCKS5 bez přihlášení: kterákoli aplikace v telefonu může během relace použít tunel do vzdálené sítě. + Bez přihlášení (nedoporučeno) + Port -L je během relace dostupný všem aplikacím v telefonu (127.0.0.1 nelze omezit na jednu aplikaci). Po zavření relace se zavře. + + + %d tunel + %d tunely + %d tunelu + %d tunelů + + + %d chyba + %d chyby + %d chyby + %d chyb + + SOCKS bez přihlášení + Zobrazit tunely + Skrýt tunely + diff --git a/androidApp/src/main/res/values/ssh_terminal.xml b/androidApp/src/main/res/values/ssh_terminal.xml new file mode 100644 index 0000000..3d1d505 --- /dev/null +++ b/androidApp/src/main/res/values/ssh_terminal.xml @@ -0,0 +1,5 @@ + + + + %1$s · „%2$s“ + diff --git a/androidApp/src/main/res/values/strings.xml b/androidApp/src/main/res/values/strings.xml index 832db13..a529809 100644 --- a/androidApp/src/main/res/values/strings.xml +++ b/androidApp/src/main/res/values/strings.xml @@ -1,9 +1,9 @@ NetKit - SSH + Terminál WoL LAN skener - SSH + SSH a konzole Wake-on-LAN Zkusit znovu Přidat zařízení diff --git a/androidApp/src/main/res/values/strings_lan.xml b/androidApp/src/main/res/values/strings_lan.xml index 153f459..46e69e9 100644 --- a/androidApp/src/main/res/values/strings_lan.xml +++ b/androidApp/src/main/res/values/strings_lan.xml @@ -1,6 +1,6 @@ - + Skenujte jen vlastní sítě nebo sítě, které smíte spravovat. - Ping, traceroute a kontrola portu na veřejný cíl jdou přes aktivní připojení (Wi-Fi, mobilní data, VPN). Místní adresa (privátní, CGNAT, link-local) jde přes Wi-Fi; bez Wi-Fi jen přes VPN, jinak ji nástroj odmítne. Skener sítě a mDNS běží jen na Wi-Fi mimo VPN, DNS používá resolver Wi-Fi, bez Wi-Fi aktivní síť. Traceroute spouští systémový ping bez vazby na Network; když výchozí síť není ta, přes kterou se měří, vyžaduje potvrzení. Na mobilních datech řada hopů neodpoví, to je běžné. Nedostupný ICMP neznamená vypnutý host. MAC adresy jiných hostů Android běžně neposkytuje. Rozsah je omezen na 4096 hostů či portů. DNS vrací A/AAAA, PTR se zjišťuje pro IPv4. + Ping, traceroute a kontrola portu na veřejný cíl jdou přes aktivní připojení (Wi-Fi, mobilní data, VPN). Místní adresa (privátní, CGNAT, link-local) jde přes Wi-Fi; bez Wi-Fi jen přes VPN, jinak ji nástroj odmítne. Skener sítě a mDNS běží jen na Wi-Fi mimo VPN, DNS používá resolver Wi-Fi, bez Wi-Fi aktivní síť. Traceroute spouští systémový ping bez vazby na Network; když výchozí síť není ta, přes kterou se měří, vyžaduje potvrzení. Na mobilních datech řada hopů neodpoví, to je běžné. Nedostupný ICMP neznamená vypnutý host. MAC adresy jiných hostů Android běžně neposkytuje. Rozsah je omezen na 4096 hostů či portů. DNS vrací A/AAAA, PTR se zjišťuje pro IPv4. Ping a kontrola portů přijmou i jednu IPv6 adresu (link-local přes Wi-Fi); IPv6 podsítě se neprohledávají. nedostupná Obnovit síť Hosté @@ -10,7 +10,7 @@ DNS mDNS Rozsah IPv4/CIDR - Host nebo IPv4 + Host, IPv4 nebo IPv6 Porty: 22,80,443 Běžné porty Pasivně přečíst banner (max. 256 B) @@ -28,12 +28,12 @@ Zadejte platný IPv4 rozsah s prefixem 0–32. Rozsah obsahuje více než 4096 hostů. Zmenšete jej. Zadejte porty 1–65535 jako seznam nebo vzestupné rozsahy. Maximum je 4096 portů. - Zadejte platný název hostu nebo IPv4 bez mezer. + Zadejte platný název hostu, IPv4 nebo IPv6 adresu bez mezer. Použijte typ služby ve tvaru _http._tcp. nebo _ssh._tcp. - Operace selhala. Ověřte připojení, DNS, cíl a omezení systému. Tento nástroj sondy provádí pouze přes IPv4; DNS vypisuje i AAAA. + Operace selhala. Ověřte připojení, DNS, cíl a omezení systému. Ping a porty umí IPv4 i IPv6, traceroute a hledání MTU jen IPv4; DNS vypisuje A i AAAA. mDNS v této verzi vyžaduje Android 14+: starší API neumí současně garantovat vybranou Wi-Fi a zrušení překladu služby. mDNS hledání skončilo po 12 sekundách. Výsledky závisejí na zadaném typu služby a multicastu v LAN. - Systémový ping neposkytl všechny adresy hopů nebo cíl neodpovídá. Trasa je neúplná; bez raw ICMP nelze spolehlivě doplnit chybějící hopy. Po pěti úvodních neznámých hopech test končí. + Systémový ping neposkytl všechny adresy hopů nebo cíl neodpovídá. Trasa je neúplná; bez raw ICMP nelze spolehlivě doplnit chybějící hopy. Odesláno %1$d · přijato %2$d Ping: statistiky a export z posledních 600 vzorků, graf a seznam z posledních 120 (nejnovější nahoře). Ztráta platí pro celou relaci. Jitter = průměr absolutních rozdílů sousedních úspěšných odpovědí. Odezva v ms · červená čárkovaná čára = timeout @@ -82,4 +82,117 @@ Systém nebo VPN odmítl ICMP socket; ping nelze změřit. Zařízení může být dostupné přes TCP. Souhlas se nepodařilo uložit; platí jen pro aktuální připojení k této Wi-Fi. Operace selhala. Ověřte Wi-Fi a zkuste to znovu. + Předvolby nástrojů se nepodařilo načíst nebo uložit. + Podsítě + IPv4/prefix nebo IPv4 a maska + Zkontrolujte adresu a souvislost bitů masky nebo wildcard. + Síť + Maska + Wildcard + Broadcast + Bez broadcastu + První host + Poslední host + Počet hostů + Rozsah podsítě + Privátní (RFC 1918) + CGNAT + Link-local + Loopback + Multicast + Dokumentační + Ostatní + Nový prefix pro rozdělení + + Zadejte prefix %1$d až 32. + + a %1$d další podsíť + a %1$d další podsítě + a %1$d další podsítě + a %1$d dalších podsítí + + Kopírovat hodnotu + DNS (NXDOMAIN, 3) · Doména neexistuje. + DNS (NOERROR) · Požadovaný záznam neexistuje. + DNS vrátil RCODE %1$d (%2$s). + neznámý kód + Systémový resolver selhal bez DNS odpovědi. + Vypršel časový limit DNS resolveru. + Prvních pět hopů neodpovědělo. Pokračovat od TTL 6? + Pokračovat + Pokročilé + Skrýt pokročilé volby + Počet 1–1000 (prázdné = bez limitu) + Interval (0,2–10 s) + Payload (0–1472 B) + DF · nefragmentovat + Zkontrolujte počet, interval a velikost v pokročilých volbách. + Příliš velké, DF + Najít největší payload s DF + Největší potvrzený payload %1$d B · IPv4 paket %2$d B. + Hledání v rozsahu 548–1472 B dokončeno. + Ani 548 B se s DF nevejde. + Chybí echo odpověď. Přesnou hranici MTU nelze určit. + Třída zadané adresy + Smíšený rozsah + Použita maska (/%1$d) · Přepnout na wildcard + Použit wildcard (/%1$d) · Přepnout na masku + Hodnota zkopírována + Hodnotu se nepodařilo zkopírovat + Interval se počítá mezi začátky sond. Při ztrátě další sonda počká na vypršení timeoutu. + Odhad podle opakovaného timeoutu bez ICMP frag-needed (možná PMTUD black hole). + DNS záznamy + Web/TLS + RDAP + RDAP · %1$s + Poškozená nebo příliš velká odpověď DNS. + Zadejte platné DNS jméno (pro PTR také IP adresu). + DNS jméno (PTR také IP) + HTTP(S) URL + Zadejte HTTP(S) URL bez přihlašovacích údajů. Stejné pravidlo platí pro přesměrování. + Veřejná IP nebo ASN + Spuštěním odešlete zadanou IP nebo ASN službě rdap.org a příslušnému registru. + Cílový server a servery přesměrování uvidí požadovanou URL a vaši zdrojovou IP. HTTP přenáší dotaz nešifrovaně. + Porovnání odešle jméno také resolveru Wi-Fi mimo VPN. Může tak prozradit interní název. + Porovnat přes Wi-Fi a VPN + Online dotazy jsou vypnuté. Povolíte je v nabídce karty veřejné IP v Přehledu. + Zadejte veřejnou IP nebo veřejné ASN. Soukromé a rezervované rozsahy nelze dotazovat. + Registr neposlal použitelnou odpověď RDAP. + Přesměrování RDAP překročilo limit nebo nevede na podporovaný registr přes HTTPS. + Dosažen limit pěti přesměrování. + Systém nedokončil ověřený TLS handshake. + TLS · systémové ověření úspěšné + DNS %1$s · TCP %2$s · TLS %3$s · TTFB %4$s (ms) + Certifikát %1$d + Subjekt: %1$s\nVydavatel: %2$s\nPlatný od: %3$s\nPlatný do: %4$s\nSAN: %5$s\nSHA-256: %6$s + Síť (CIDR) + Název + Země + Organizace + E-mail pro hlášení zneužití + ASN + Přesměrování zastaveno. Cíl změnil port na jiný než 80 nebo 443. + Další požadavek byl zastaven. Na tento host a IP nelze v tomto měření automaticky pokračovat. + Cílová adresa nebo síťová trasa se změnila. Spusťte nové měření. + Jméno %1$s se přeložilo na neveřejnou adresu %2$s. Pokračovat ve spojení s touto adresou? + %1$s (%2$s) — trasa přes fake-IP proxy, skutečný cíl nelze ověřit. Pokračovat? + Přesměrování z %1$s na %2$s (%3$s) vede přes fake-IP proxy. Skutečný cíl nelze ověřit. Pokračovat? + %1$s · předchozí měření + Pokračovat na uvedenou IP + IP spojení: %1$s + Po změně originu nebyl GET vyzkoušen. + Předvyplnit cíl pro nové měření + Jméno serveru neodpovídá certifikátu. + Systém nedůvěřuje řetězci certifikátů serveru. + Některý certifikát v řetězci vypršel nebo jeho platnost ještě nezačala. + Vyjednání TLS selhalo. Zkontrolujte podporované verze TLS a šifrové sady. + DNS nepřeložilo jméno serveru na IP adresu. + TCP spojení se nepodařilo navázat. Cíl mohl spojení odmítnout. + Technický detail + Služba RDAP zablokovala přístup (HTTP 403). + Pro tento objekt nebyl nalezen registr nebo registrační záznam (HTTP 404). + rdap.org povoluje 10 dotazů za 10 sekund. Limit byl překročen (HTTP 429). Zkuste to později. + Služba RDAP dočasně omezila počet dotazů (HTTP 429). Zkuste to později. + Další pokus za %1$d s + V nástrojích běží měření. RDAP můžete otevřít po jeho dokončení. diff --git a/androidApp/src/main/res/values/strings_ssh.xml b/androidApp/src/main/res/values/strings_ssh.xml index 20cd3c3..8638e94 100644 --- a/androidApp/src/main/res/values/strings_ssh.xml +++ b/androidApp/src/main/res/values/strings_ssh.xml @@ -8,16 +8,16 @@ Připojeno Připojování… Zavřít - SSH používejte jen vůči zařízením, která smíte spravovat. Připojení používá standardní trasu Androidu včetně VPN. Nejvýše 4 relace; na pozadí zůstávají otevřené nejvýše 5 minut, poté se ukončí. Systém je může ukončit dříve. + Používejte terminál jen pro zařízení, která smíte spravovat. SSH a Telnet používají systémovou trasu včetně VPN. Současně lze otevřít čtyři relace. Bez služby na pozadí se po pěti minutách zavřou. Terminál: vlastní VT subset, ANSI/256 barev, alternativní obrazovka, 5000 řádků historie. Úplná kompatibilita xterm, široké znaky a kombinující Unicode zatím nejsou zaručeny. - Profil + SSH profil Klíče Ověřené servery - Export profilů - Profily exportovány bez hesel, klíčů a referencí na tajemství. + Export SSH profilů + SSH profily exportovány bez hesel, klíčů a referencí na tajemství. Úložiště SSH nelze přečíst. Data se nepřepisují. Zkusit znovu - Zatím nemáte SSH profily. + Zatím nemáte profily. Připojit Upravit Smazat @@ -29,7 +29,8 @@ Zrušit SSH profil Název - Host (DNS / IPv4 / IPv6 bez hranatých závorek) + Host + DNS jméno, IPv4 nebo IPv6 bez hranatých závorek Port Uživatel Heslo diff --git a/androidApp/src/main/res/values/strings_wifi.xml b/androidApp/src/main/res/values/strings_wifi.xml index b7ef70f..bd90140 100644 --- a/androidApp/src/main/res/values/strings_wifi.xml +++ b/androidApp/src/main/res/values/strings_wifi.xml @@ -22,7 +22,6 @@ Obsazení kanálů %1$s · nalezeno AP: %2$d Historie RSSI · měření: %1$d - %1$s dBm Doporučení kanálu 2,4 GHz 5 GHz @@ -45,8 +44,8 @@ Zdraví kanálů Výborný Dobrý - Průměrný - Špatný + Slabší + Slabý Kanál %1$d · %2$s %1$s dBm žádný @@ -63,9 +62,9 @@ Wi-Fi síť nemá výchozí bránu IPv4; latenci k bráně nelze měřit. Zařízení neposkytuje čítače přenesených dat; propustnost nelze zobrazit. Údaje o Wi-Fi spojení nejsou dostupné. - Vynikající + Výborný Dobrý - Uspokojivý + Slabší Slabý Neznámý Čekám na první měření… @@ -78,7 +77,11 @@ DNS vrátil chybu (RCODE %1$d) Zadejte číselnou adresu IPv4, například 1.1.1.1. Zadejte platné doménové jméno, například one.one.one.one. - Zbývá %1$d ze 4 + + Zbývá %1$d ze %2$d + Zbývají %1$d ze %2$d + Zbývá %1$d ze %2$d + Další sken asi za %1$d s Sken nebyl potvrzen. Android omezuje četnost skenů (obvykle 4 za 2 minuty). Omezení lze vypnout v Možnostech pro vývojáře → Omezení vyhledávání Wi-Fi. Jde o systémové nastavení telefonu, které NetKit nemění. Pokud Možnosti pro vývojáře nejsou dostupné, otevřou se informace o telefonu. Zapnete je 7× klepnutím na číslo sestavení. diff --git a/androidApp/src/main/res/values/tools_targets.xml b/androidApp/src/main/res/values/tools_targets.xml new file mode 100644 index 0000000..d0e09c9 --- /dev/null +++ b/androidApp/src/main/res/values/tools_targets.xml @@ -0,0 +1,46 @@ + + + + Historie a oblíbené cíle + Oblíbené + Naposledy použité + Zatím žádné cíle + Přidat k oblíbeným + Odebrat z oblíbených + Odebrat %1$s z oblíbených + Vymazat historii + Oblíbený cíl + Popisek (nepovinný) + Uložit + Historie a oblíbené zůstávají jen v tomto telefonu. + Oblíbených cílů může být nejvýše 30. Nejdřív některý odeberte. + Tento text není platný cíl. + + TCP ping + Port + Počet (prázdné = do zastavení) + Jedno TCP spojení za sekundu, nikdy dvě naráz. Odpověď = dokončené spojení; odmítnutí (RST) nebo vypršení se počítá jako ztráta. + Port musí být 1–65535 a počet 1–1000 nebo prázdný. + odmítnuto + vypršelo + chyba + + MAC → výrobce + MAC adresa nebo vložený výpis + Jedna MAC nebo výpis show mac address-table, display mac-address či /interface bridge host print (nejvýše 64 KiB a 2000 řádků). Výrobce z přibaleného seznamu IEEE OUI, bez připojení k internetu. + Najít výrobce + Vymazat + Vstup je větší než 64 KiB. Vložte menší část výpisu. + Vstup má víc než 2000 řádků. Vložte menší část výpisu. + Ve vstupu není žádná MAC adresa v podporovaném tvaru. + Seznam výrobců se nepodařilo načíst; výrobce se nezobrazí. + MAC adresy + Počet: %1$d + Známý výrobce: %1$d · bez výrobce: %2$d + Výrobce není v seznamu IEEE + Lokálně spravovaná adresa (bez výrobce) + Skupinová adresa (bez výrobce) + lokální + multicast + %1$d× + diff --git a/androidApp/src/main/res/values/wifi_ext.xml b/androidApp/src/main/res/values/wifi_ext.xml new file mode 100644 index 0000000..fe5e63e --- /dev/null +++ b/androidApp/src/main/res/values/wifi_ext.xml @@ -0,0 +1,75 @@ + + + + + Připnout do grafu + připnuto + Připnout lze nejvýš %1$d AP. Nejdřív jiný odepněte. + Připnuto do grafu + Odepnuto z grafu + Připnout nebo odepnout v grafu + %1$s · nenalezen v posledním skenu + Odepnout + Odepnout %1$s + Graf ukáže připojené AP, připnuté AP a pak nejsilnější. Připnutí platí podle BSSID i po novém skenu, do zavření aplikace. + + Seskupit podle SSID + Seskupeno podle SSID · všechna pásma + %1$d AP + k. %1$s + Zobrazit AP této sítě + + Exportovat sken + Export skenu Wi-Fi + Soubor obsahuje identifikátory sítí v okolí (SSID, BSSID, výrobce). Uložte ho jen do důvěryhodného úložiště a sdílejte uváženě. + Exportuje se celý poslední sken ve všech pásmech bez ohledu na filtr. Soubor zůstane jen tam, kam ho uložíte. + Vybrat soubor… + Zrušit + Export byl uložen. + Export se nepodařilo uložit. Vyberte soubor znovu. + + Záznam obchůzky + Projděte prostor s telefonem: každou sekundu se zapíše signál, AP (BSSID), kanál, rychlost linky a ping brány, k tomu roamingy a změny kanálu. Data zůstávají jen v paměti, dokud je neexportujete. + Přesnost je 1 s, délku handoveru z toho přesně určit nedá. + Nejvýš %1$s h nebo %2$s vzorků. Při odchodu z Přehledu nebo z aplikace se záznam zastaví, na pozadí neběží. + Spustit záznam + Zastavit + Značka + Značka místa + Např. kuchyň, 2. patro + Přidat + Značka přidána. + Napište text značky. + + Nahrávám · %1$s · %2$d vzorek + Nahrávám · %1$s · %2$d vzorky + Nahrávám · %1$s · %2$d vzorku + Nahrávám · %1$s · %2$d vzorků + + Délka + Vzorky + Roamingy + Změny kanálu + Nejslabší signál + Ztracené pingy brány + %1$d z %2$d + Značky + Záznam je ukončený. + Záznam se zastavil při odchodu z Přehledu nebo z aplikace. + Záznam dosáhl limitu a zastavil se. + Exportovat + Zahodit + Nový záznam + Export záznamu obchůzky + Soubor obsahuje identifikátory vašich AP (BSSID) a vaše značky míst. Uložte ho jen do důvěryhodného úložiště. + CSV má jednu tabulku vzorků a událostí, souhrn je jen v JSON. + — + + Region %1$s (%2$s): kanály 2,4 GHz %3$d–%4$d. + Jen 802.11b: kanál %1$d. + Kanál %1$d v tomto regionu není povolen. + Informativně podle kódu země mobilní sítě. Skóre a doporučení se nemění. + EU + USA + Japonsko + diff --git a/androidApp/src/main/res/values/wifi_signal.xml b/androidApp/src/main/res/values/wifi_signal.xml index 5d53660..f4a1916 100644 --- a/androidApp/src/main/res/values/wifi_signal.xml +++ b/androidApp/src/main/res/values/wifi_signal.xml @@ -81,4 +81,12 @@ Odkud data pocházejí a jaké mají limity RSSI a vyjednanou rychlost (PHY) hlásí ovladač Wi-Fi a obnovuje je obvykle jednou za několik sekund, proto se hodnota v grafu může opakovat. Mobilní signál (RSRP, RSRQ, SINR) posílá modem jen při změně o 2 dB a nejvýš jednou za 3 s, graf je proto schodovitý. Příjem a odesílání se počítají z čítačů celého zařízení (Wi-Fi, mobilní data, VPN, tethering). Latence se měří ICMP echem jednou za sekundu na bránu Wi-Fi a na zvolený cíl přes aktivní síť, DNS každých 10 s přes resolver aktivní sítě. Veřejnou IP vrací Cloudflare (1.1.1.1/cdn-cgi/trace) a poskytovatele Team Cymru přes DNS; obě služby tak vidí vaši veřejnou IP. Zjišťování vypnete v nabídce karty Připojení. Vše běží jen tehdy, když je obrazovka otevřená a aplikace v popředí. Historie drží posledních 15 minut jen v paměti. Svislé čáry v grafu značí roaming a přepnutí datové SIM (modrá), ztrátu paketů (červená) a změnu kanálu nebo standardu (oranžová). + Wi-Fi 7 · MLO + AP MLD · %1$s + 60 GHz + %1$d dBm + aktivní + nečinná + neasociovaná + Linka %1$d · %2$s · %3$s · kanál %4$s\nRSSI %5$s · šířka AP ze skenu %6$s diff --git a/androidApp/src/main/res/values/wifi_spectrum.xml b/androidApp/src/main/res/values/wifi_spectrum.xml index ae6a23e..8133d70 100644 --- a/androidApp/src/main/res/values/wifi_spectrum.xml +++ b/androidApp/src/main/res/values/wifi_spectrum.xml @@ -16,6 +16,9 @@ dBm Spektrum %1$s: AP v pásmu %2$d, v grafu %3$d. Osa signálu od %4$d do %5$d dBm. %1$d. %2$s · %3$s · %4$d dBm + šířka %1$d MHz, střed neznámý + Šířka %1$d MHz, střed neznámý: AP nehlásí střed kanálu a z primárního kanálu ho nelze jednoznačně určit. Graf ukazuje jen primární kanál 20 MHz. + Kanál 14 je mimo pásmo povolené v EU. %1$s · připojeno vytížení %1$d %% Podrobnosti připojení diff --git a/androidApp/src/main/res/values/wol_secureon.xml b/androidApp/src/main/res/values/wol_secureon.xml new file mode 100644 index 0000000..ebcf6bc --- /dev/null +++ b/androidApp/src/main/res/values/wol_secureon.xml @@ -0,0 +1,13 @@ + + + + SecureOn + Nepovinné heslo síťové karty: 6 bajtů jako MAC (11:22:33:44:55:66) nebo 4 bajty jako IPv4. Ukládá se šifrovaně jen v tomto telefonu a nikdy se neexportuje. + Heslo SecureOn je uložené (šifrovaně). Prázdné pole ho ponechá, nové ho nahradí. Do exportu se nikdy nedostane. + Heslo SecureOn (nepovinné) + Odebrat uložené heslo + Zadejte 6 bajtů jako 11:22:33:44:55:66 nebo 4 bajty jako 192.0.2.1. + SecureOn heslo nedostupné — zadejte ho znovu v úpravě zařízení. Paket se bez hesla neodeslal. + Uložené heslo SecureOn patří jiné MAC nebo cíli tohoto zařízení, proto se probuzení blokuje. Zadejte heslo znovu; uložení bez hesla ho smaže. + SecureOn heslo nedostupné + diff --git a/androidApp/src/main/res/values/wol_widget.xml b/androidApp/src/main/res/values/wol_widget.xml new file mode 100644 index 0000000..a7c59b5 --- /dev/null +++ b/androidApp/src/main/res/values/wol_widget.xml @@ -0,0 +1,20 @@ + + + + Probudit (WoL) + Probudí vybrané zařízení jedním klepnutím + Vyberte zařízení + Klepněte pro výběr + Připraveno + Odesílám… + Odesláno %1$s + Není Wi-Fi + Nelze určit broadcast + Odeslání selhalo + Zařízení smazáno, klepněte pro výběr + Probudit + Widget WoL + Vyberte zařízení, které má widget probouzet + Zatím nemáte žádné zařízení. Přidejte ho v záložce WoL. + Seznam zařízení se nepodařilo načíst. + diff --git a/androidApp/src/main/res/xml/netstatus_widget_info.xml b/androidApp/src/main/res/xml/netstatus_widget_info.xml new file mode 100644 index 0000000..61f5c1b --- /dev/null +++ b/androidApp/src/main/res/xml/netstatus_widget_info.xml @@ -0,0 +1,21 @@ + + + + diff --git a/androidApp/src/main/res/xml/shortcuts.xml b/androidApp/src/main/res/xml/shortcuts.xml new file mode 100644 index 0000000..71388f9 --- /dev/null +++ b/androidApp/src/main/res/xml/shortcuts.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/androidApp/src/main/res/xml/wol_widget_info.xml b/androidApp/src/main/res/xml/wol_widget_info.xml new file mode 100644 index 0000000..c24f7eb --- /dev/null +++ b/androidApp/src/main/res/xml/wol_widget_info.xml @@ -0,0 +1,20 @@ + + + + diff --git a/androidApp/src/test/kotlin/cz/netkit/app/backup/BackupCryptoTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/backup/BackupCryptoTest.kt new file mode 100644 index 0000000..5960781 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/backup/BackupCryptoTest.kt @@ -0,0 +1,34 @@ +package cz.netkit.app.backup + +import cz.netkit.shared.backup.* +import java.util.Base64 +import kotlin.test.* +import kotlinx.serialization.json.* + +class BackupCryptoTest { + @Test fun authenticatedRoundTripUsesFreshSaltAndNonceAndRejectsTampering() { + val pass = java.util.UUID.randomUUID().toString().toCharArray() + val plain = """{"format":"netkit-backup-v1"}""".encodeToByteArray() + val sealed = BackupCrypto.seal(plain, pass) + val header = backupDocument(sealed, BACKUP_FILE_BYTES) + val second = backupDocument(BackupCrypto.seal(plain, pass), BACKUP_FILE_BYTES) + assertFalse(encryptedBackup(plain)) + assertTrue(encryptedBackup(sealed)) + assertEquals(JsonPrimitive(600000), header["iterations"]) + for ((key, size) in mapOf("salt" to 16, "iv" to 12)) { + assertEquals(size, Base64.getDecoder().decode(header.getValue(key).jsonPrimitive.content).size) + assertNotEquals(header[key], second[key]) + } + assertContentEquals(plain, BackupCrypto.open(sealed, pass)) + assertFailsWith { BackupCrypto.open(sealed, pass.reversedArray()) } + val payload = Base64.getDecoder().decode(header.getValue("ciphertext").jsonPrimitive.content) + payload[0] = payload[0].inc() + fun modified(key: String, value: JsonElement) = JsonObject(header + (key to value)).toString().encodeToByteArray() + assertFailsWith { + BackupCrypto.open(modified("ciphertext", JsonPrimitive(Base64.getEncoder().encodeToString(payload))), pass) + } + for ((key, value) in mapOf("iterations" to JsonPrimitive(Int.MAX_VALUE), "iv" to JsonPrimitive(""), + "format" to JsonPrimitive("future"), "kdf" to JsonPrimitive("other"), "extra" to JsonPrimitive(1))) + assertFailsWith { BackupCrypto.open(modified(key, value), pass) } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/backup/BackupRepositoryTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/backup/BackupRepositoryTest.kt new file mode 100644 index 0000000..19c1ea7 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/backup/BackupRepositoryTest.kt @@ -0,0 +1,66 @@ +package cz.netkit.app.backup + +import cz.netkit.app.lan.* +import cz.netkit.app.settings.AppSettingsSerializer +import cz.netkit.app.ssh.SshDataSerializer +import cz.netkit.app.wol.DeviceEnvelope +import cz.netkit.app.wol.DeviceSerializer +import cz.netkit.shared.backup.* +import cz.netkit.shared.lan.* +import cz.netkit.shared.settings.* +import cz.netkit.shared.speed.* +import cz.netkit.shared.ssh.* +import cz.netkit.shared.wol.* +import java.nio.file.Files +import kotlin.test.* +import kotlinx.coroutines.runBlocking + +class BackupRepositoryTest { + @Test fun transferUsesRealStoreCodecsAndPreservesLocalOnlyData() = runBlocking { + val root = Files.createTempDirectory("config-transfer").toFile() + try { + val source = RestoreFiles(root.resolve("source"), root.resolve("source-private")) + val target = RestoreFiles(root.resolve("target"), root.resolve("target-private")) + fun path(files: RestoreFiles, key: ConfigFile) = files.resolve(key).also { it.parentFile!!.mkdirs() } + val profile = SshProfile("p1", "Lab", "192.0.2.3", username = "operator", secretRef = "source-ref", group = "Rack") + path(source, ConfigFile.SSH).outputStream().use { SshDataSerializer.writeTo(SshData(profiles = listOf(profile)), it) } + val device = WolDevice("w1", "Lab", "02:00:00:00:00:01", TargetMode.LIMITED_BROADCAST, createdAt = 1, updatedAt = 1, + secureOnRequired = true) + path(source, ConfigFile.WOL).outputStream().use { DeviceSerializer.writeTo(DeviceEnvelope(2, listOf(device)), it) } + val favorite = FavoriteTarget("192.0.2.4", "Lab") + path(source, ConfigFile.LAN).outputStream().use { LanPreferencesSerializer.writeTo( + LanToolPreferences(targets = ToolTargets(listOf("source-history.example.org"), listOf(favorite))), it) } + path(source, ConfigFile.SPEED).writeText(SpeedStoreCodec.encode(SpeedStoreData(customUrl = "https://example.org/", + iperfHost = "192.0.2.5", iperfPort = 5202))) + path(source, ConfigFile.SETTINGS).outputStream().use { AppSettingsSerializer.writeTo(AppSettings(theme = ThemeMode.DARK), it) } + + val record = SpeedRecord(1, SpeedEngine.LIBRESPEED, "local-history") + path(target, ConfigFile.SPEED).writeText(SpeedStoreCodec.encode(SpeedStoreData(ndt7ConsentMs = 42, records = listOf(record)))) + val localHistory = listOf("destination-history.example.org") + path(target, ConfigFile.LAN).outputStream().use { LanPreferencesSerializer.writeTo( + LanToolPreferences(targets = ToolTargets(recent = localHistory)), it) } + path(target, ConfigFile.SSH).outputStream().use { SshDataSerializer.writeTo(SshData(profiles = listOf(profile.copy( + id = "target-id", host = "192.0.2.9", secretRef = "target-ref"))), it) } + val plain = BackupRepository(source) { AppLanguage.EN }.snapshot().export() + for (excluded in listOf("source-ref", "source-history", "ndt7ConsentMs", "records")) assertFalse(excluded in plain.decodeToString()) + var language = AppLanguage.CS + val repo = BackupRepository(target) { language } + val before = repo.snapshot() + val plan = repo.plan(before, repo.validate(plain), BackupSection.entries.toSet()) + repo.stage(before, plan) + assertEquals(before.state, repo.snapshot().state) + val detached = mutableSetOf() + assertEquals(true, target.activate({ language }, { detached += it }) { language = it }) + val after = repo.snapshot() + assertEquals(plan.state, after.state) + assertEquals(setOf("target-ref"), detached) + assertNull(after.state.ssh.profiles.single().secretRef) + assertEquals(localHistory, after.lan.targets.recent) + assertEquals(listOf(record), after.speed.records) + assertEquals(42L, after.speed.ndt7ConsentMs) + assertEquals(listOf(device), after.state.devices) + assertEquals(AppLanguage.EN, language) + } finally { root.deleteRecursively() } + Unit + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/backup/RestoreFilesTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/backup/RestoreFilesTest.kt new file mode 100644 index 0000000..b60a996 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/backup/RestoreFilesTest.kt @@ -0,0 +1,78 @@ +package cz.netkit.app.backup + +import cz.netkit.shared.settings.AppLanguage +import java.nio.file.Files +import kotlin.test.* + +class RestoreFilesTest { + private fun fixture(test: (RestoreFiles) -> Unit) { + val root = Files.createTempDirectory("config-restore").toFile() + try { test(RestoreFiles(root.resolve("files"), root.resolve("private"))) } finally { root.deleteRecursively() } + } + + @Test fun switchIsAllOrNothingAndInterruptedLocaleDeliveryIsRetried() = fixture { store -> + val changes = mapOf(ConfigFile.SSH to byteArrayOf(1), ConfigFile.WOL to byteArrayOf(2)) + store.stage(changes.mapValues { store.stamp(null) }, changes, AppLanguage.SYSTEM, AppLanguage.CS, setOf("w1")) + assertTrue(changes.keys.none { store.resolve(it).exists() }) + assertNull(store.wolRevocations()) + assertFailsWith { store.activate({ AppLanguage.SYSTEM }) { error("interrupted") } } + changes.forEach { (key, bytes) -> assertContentEquals(bytes, store.contents(key)) } + assertTrue(checkNotNull(store.wolRevocations()).readText().contains("w1")) + var language = AppLanguage.SYSTEM + assertEquals(true, store.activate({ language }) { language = it }) + assertEquals(AppLanguage.CS, language) + assertNull(store.activate({ language }) { fail() }) + } + + @Test fun stalePreviewOrEditBeforeColdStartPreservesEveryStore() = fixture { store -> + val hash = mapOf(ConfigFile.LAN to store.stamp(null), ConfigFile.WOL to store.stamp(null)) + val changes = hash.mapValues { byteArrayOf(3) } + store.stage(hash, changes, null, null) + val path = store.resolve(ConfigFile.LAN) + path.parentFile!!.mkdirs() + path.writeBytes(byteArrayOf(7)) + assertEquals(false, store.activate({ null }) { fail() }) + assertNull(store.contents(ConfigFile.WOL)) + assertContentEquals(byteArrayOf(7), store.contents(ConfigFile.LAN)) + assertFailsWith { store.stage(hash, changes, null, null) } + } + + @Test fun subsequentPartialActivationKeepsUnselectedGenerationAndPendingVaultRevocations() = fixture { store -> + fun apply(changes: Map, ids: Set) { + store.stage(changes.mapValues { store.stamp(store.contents(it.key)) }, changes, null, null, ids) + assertEquals(true, store.activate({ null }) { fail() }) + } + apply(mapOf(ConfigFile.WOL to byteArrayOf(1), ConfigFile.SSH to byteArrayOf(2)), setOf("one")) + val ssh = store.resolve(ConfigFile.SSH) + apply(mapOf(ConfigFile.WOL to byteArrayOf(3)), setOf("two")) + assertEquals(ssh, store.resolve(ConfigFile.SSH)) + assertContentEquals(byteArrayOf(2), store.contents(ConfigFile.SSH)) + val revoked = checkNotNull(store.wolRevocations()).readText() + assertTrue("one" in revoked && "two" in revoked) + } + + @Test fun damagedMapFallsBackToDefaultPathsSetsItAsideAndReportsOnce() { + for (damage in listOf("{\"id\":", "{\"id\":\"\",\"locations\":{\"SSH\":\"../../files\"}}", "\u0000\u00ff")) { + val root = Files.createTempDirectory("config-restore").toFile() + try { + val store = RestoreFiles(root.resolve("files"), root.resolve("private")) + val changes = mapOf(ConfigFile.SSH to byteArrayOf(1)) + store.stage(changes.mapValues { store.stamp(null) }, changes, null, null) + assertEquals(true, store.activate({ null }) { fail() }) + val map = root.resolve("private/configuration-restore/active.json") + map.writeText(damage) + // No exception for any store owner; the default path is used and the map is set aside. + assertEquals(root.resolve("files/datastore/ssh.json"), store.resolve(ConfigFile.SSH)) + assertFalse(map.exists()) + assertEquals(1, map.parentFile!!.listFiles()!!.count { it.name.startsWith("active.corrupt-") }) + assertTrue(store.recoverDamagedMap()) + assertFalse(store.recoverDamagedMap()) + assertNull(store.wolRevocations()) + // A later restore works on top of the default paths. + store.stage(changes.mapValues { store.stamp(null) }, changes, null, null) + assertEquals(true, store.activate({ null }) { fail() }) + assertContentEquals(byteArrayOf(1), store.contents(ConfigFile.SSH)) + } finally { root.deleteRecursively() } + } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/lan/DiagnosticLookupTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/lan/DiagnosticLookupTest.kt new file mode 100644 index 0000000..be076e1 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/lan/DiagnosticLookupTest.kt @@ -0,0 +1,113 @@ +package cz.netkit.app.lan + +import android.net.DnsResolver +import cz.netkit.app.R +import cz.netkit.shared.lan.LanExport +import cz.netkit.shared.lan.exportLan +import cz.netkit.shared.lan.RecordType +import cz.netkit.shared.lan.RecordReply +import cz.netkit.shared.net.NetKind +import cz.netkit.shared.publicip.RdapInfo +import java.io.IOException +import kotlinx.coroutines.test.runTest +import okhttp3.Protocol +import okhttp3.Response +import okhttp3.ResponseBody.Companion.toResponseBody +import kotlin.test.* + +class DiagnosticLookupTest { + @Test fun callbackPreservesNegativeReplyAndFlagsAndSeparatesWireErrors() { + var result: Result? = null + val callback = RecordCallback { result = it } + val negative = ByteArray(12).apply { this[2] = 0x83.toByte(); this[3] = 0x83.toByte() } + callback.onAnswer(negative, 3) + val rows = result!!.getOrThrow().rows("example.test", RecordType.A, "VPN") + assertContains(rows.single().detail, "NXDOMAIN") + assertContains(rows.single().detail, "AA=0 TC=1 RD=1 RA=1") + for (format in LanExport.entries) { + val exported = exportLan(rows, format) + assertContains(exported, "example.test") + assertContains(exported, "RCODE=3 NXDOMAIN") + assertContains(exported, "VPN") + } + callback.onAnswer(negative, 0) + assertEquals(R.string.diag_bad_dns, (result!!.exceptionOrNull() as DnsFailure).resource) + callback.onAnswer(byteArrayOf(), 0) + assertTrue(result!!.isFailure) + callback.onError(DnsResolver.DnsException(DnsResolver.ERROR_SYSTEM, IOException())) + assertEquals(R.string.lan_dns_resolver, (result!!.exceptionOrNull() as DnsFailure).resource) + } + + @Test fun onlyExplicitComparisonAddsWifiToTheQueryLoop() { + val calls = mutableListOf() + recordRoutes("vpn", NetKind.VPN, "wifi", false).forEach { calls += it.second } + assertEquals(listOf("vpn"), calls) + assertEquals(listOf(NetKind.VPN to "vpn", NetKind.WIFI to "wifi"), recordRoutes("vpn", NetKind.VPN, "wifi", true)) + assertTrue(recordRoutes("vpn", NetKind.VPN, null, true).isEmpty()) + assertTrue(recordRoutes("wifi", NetKind.WIFI, "wifi", true).isEmpty()) + assertEquals(listOf(NetKind.CELLULAR to "mobile"), recordRoutes("mobile", NetKind.CELLULAR, "wifi", false)) + } + + @Test fun rdapHttpErrorsAndRetryAfterUseTheResponseFromTheRegistry() = runTest { + for ((status, label) in listOf(429 to R.string.diag_rdap_limited, 404 to R.string.diag_rdap_unknown, + 403 to R.string.diag_rdap_blocked, 500 to R.string.diag_rdap_response)) { + for (retryAfter in listOf(null, "23", "Sun, 06 Nov 1994 08:49:37 GMT", "invalid")) { + val hosts = mutableListOf() + val client = diagnosticClient().newBuilder().addInterceptor { chain -> + val request = chain.request() + assertEquals(diagnosticUserAgent, request.header("User-Agent")) + hosts += request.url.host + val response = Response.Builder().request(request).protocol(Protocol.HTTP_1_1) + .message("fixture").body("".toResponseBody()) + if (hosts.size == 1) response.code(302).header("Location", "https://rdap.arin.net/registry/autnum/123") + else { + response.code(status) + if (retryAfter != null) response.header("Retry-After", retryAfter) + } + response.build() + }.build() + val failure = assertFailsWith { fetchRdap("autnum/123", client) { true } } + assertEquals(label, failure.label) + val delay = when { + status != 429 -> null + retryAfter == "23" -> 23L + retryAfter?.startsWith("Sun") == true -> 0L + else -> null + } + assertEquals(delay, failure.retryAfterSeconds) + assertEquals(listOf("rdap.org", "rdap.arin.net"), hosts) + } + } + } + + @Test fun bootstrapLimitIsReportedWithoutRetry() = runTest { + var requests = 0 + val client = diagnosticClient().newBuilder().addInterceptor { chain -> + requests++ + assertEquals("NetKit/${cz.netkit.app.BuildConfig.VERSION_NAME}", chain.request().header("User-Agent")) + Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1).code(429) + .header("Retry-After", "10").message("fixture").body("".toResponseBody()).build() + }.build() + val failure = assertFailsWith { fetchRdap("autnum/123", client) { true } } + assertEquals(R.string.diag_rdap_bootstrap_limited, failure.label) + assertEquals(10L, failure.retryAfterSeconds) + assertEquals(1, requests) + } + + @Test fun rdapGatePrecedesTransport() = runTest { + val sent = mutableListOf() + val send: suspend (String) -> RdapInfo = { + sent += it + RdapInfo(null, null, null, null, null, null) + } + // Private literal assembled locally; the transport below only records calls. + val privateAddress = listOf(10, 0, 0, 1).joinToString(".") + for (input in listOf(privateAddress, "203.0.113.1", "2001:db8::1", "example.test")) { + assertFailsWith { lookupRdap(input, { true }, send) } + } + assertFailsWith { lookupRdap("AS123", { false }, send) } + assertTrue(sent.isEmpty()) + lookupRdap("AS123", { true }, send) + assertEquals(listOf("autnum/123"), sent) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/lan/DnsLookupTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/lan/DnsLookupTest.kt new file mode 100644 index 0000000..e9cb539 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/lan/DnsLookupTest.kt @@ -0,0 +1,40 @@ +package cz.netkit.app.lan + +import android.net.DnsResolver +import cz.netkit.app.R +import java.io.File +import java.io.IOException +import java.net.InetAddress +import javax.xml.parsers.DocumentBuilderFactory +import kotlin.test.* + +class DnsLookupTest { + @Test fun callbackSeparatesEmptyAnswerRcodesAndResolverFailure() { + val errors = mutableListOf() + val callback = LookupCallback { errors += it.exceptionOrNull() as DnsFailure } + callback.onAnswer(emptyList(), 0) + callback.onAnswer(emptyList(), 3) + callback.onAnswer(emptyList(), 2) + callback.onError(DnsResolver.DnsException(DnsResolver.ERROR_SYSTEM, IOException())) + assertEquals(listOf(R.string.lan_dns_no_record, R.string.lan_dns_nxdomain, R.string.lan_dns_rcode, + R.string.lan_dns_resolver), errors.map { it.resource }) + assertEquals(listOf(null, null, 2, null), errors.map { it.rcode }) + } + + @Test fun dnsDiagnosticsHaveCzechAndEnglishResources() { + val expected = setOf("lan_dns_nxdomain", "lan_dns_no_record", "lan_dns_rcode", "lan_dns_unknown", + "lan_dns_resolver", "lan_dns_timeout") + for (folder in listOf("values", "values-en")) { + val xml = File("src/main/res/$folder/strings_lan.xml") + val strings = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xml).getElementsByTagName("string") + val keys = (0 until strings.length).map { strings.item(it) }.filter { it.textContent.isNotBlank() } + .map { it.attributes.getNamedItem("name").nodeValue }.filter { it.startsWith("lan_dns_") }.toSet() + assertEquals(expected, keys, folder) + } + } + + @Test fun successfulLookupKeepsAddresses() { + val addresses = listOf(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))) + LookupCallback { assertEquals(addresses, it.getOrThrow()) }.onAnswer(addresses, 0) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/lan/LanIpv6ToolsTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/lan/LanIpv6ToolsTest.kt new file mode 100644 index 0000000..3c17599 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/lan/LanIpv6ToolsTest.kt @@ -0,0 +1,110 @@ +package cz.netkit.app.lan + +import cz.netkit.app.R +import cz.netkit.shared.lan.Ipv4Subnet +import cz.netkit.shared.lan.Ipv6Prefix +import cz.netkit.shared.lan.TargetConfirmationReason +import java.net.InetAddress +import kotlin.coroutines.cancellation.CancellationException +import kotlin.test.* +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runTest + +class LanIpv6ToolsTest { + private fun address(text: String) = InetAddress.getByAddress(when { + ':' in text -> cz.netkit.shared.lan.Ipv6Address.parse(text)!!.bytes + else -> text.split('.').map { it.toInt().toByte() }.toByteArray() + }) + + @Test fun lookupMergeKeepsIpv4FirstAndFailsOnlyWithoutAnyAddress() { + val a = address("192.168.1.10"); val aaaa = address("fd00::10") + assertEquals(listOf(a, aaaa), mergeLookups(Result.success(listOf(a)), Result.success(listOf(aaaa)))) + // IPv4-only name: the AAAA "no record" error is not shown. + assertEquals(listOf(a), mergeLookups(Result.success(listOf(a)), Result.failure(DnsFailure(R.string.lan_dns_no_record)))) + // IPv6-only name: the A error is not shown. + assertEquals(listOf(aaaa), mergeLookups(Result.failure(DnsFailure(R.string.lan_dns_no_record)), Result.success(listOf(aaaa)))) + val nx = DnsFailure(R.string.lan_dns_nxdomain) + assertSame(nx, assertFailsWith { mergeLookups(Result.failure(nx), Result.failure(DnsFailure(R.string.lan_dns_rcode, 2))) }) + assertEquals(R.string.lan_dns_no_record, assertFailsWith { mergeLookups(Result.success(emptyList()), Result.success(emptyList())) }.resource) + assertFailsWith { mergeLookups(Result.success(listOf(a)), Result.failure(CancellationException())) } + } + + @Test fun pickedTargetPrefersIpv4ThenCanonicalIpv6() { + assertEquals("192.168.1.10", pickToolAddress(listOf(address("fd00::10"), address("192.168.1.10")))) + assertEquals("fd00::10", pickToolAddress(listOf(address("fd00:0:0:0:0:0:0:10")))) + assertNull(pickToolAddress(emptyList())) + } + + @Test fun confirmationAndLinkUseBothFamilies() { + val subnet = Ipv4Subnet.parse("192.168.1.0/24")!! + val prefixes = listOf(Ipv6Prefix.parse("fd00:1::/64")!!) + assertEquals(emptySet(), toolTargetReasons("192.168.1.20", subnet, prefixes, 3)) + assertEquals(setOf(TargetConfirmationReason.OUTSIDE_WIFI), toolTargetReasons("192.168.2.20", subnet, prefixes, 3)) + assertEquals(emptySet(), toolTargetReasons("fd00:1::20", subnet, prefixes, 3)) + assertEquals(emptySet(), toolTargetReasons("fe80::20%wlan0", subnet, prefixes, 3)) + assertEquals(setOf(TargetConfirmationReason.OUTSIDE_WIFI), toolTargetReasons("fd00:2::20", subnet, prefixes, 3)) + // IPv4-mapped is judged as its IPv4. + assertEquals(emptySet(), toolTargetReasons("::ffff:192.168.1.20", subnet, prefixes, 3)) + assertTrue(onWifiLink("fe80::1", subnet) { error("link-local needs no prefixes") }) + assertTrue(onWifiLink("fd00:1::1", subnet) { prefixes }) + assertFalse(onWifiLink("fd00:2::1", subnet) { prefixes }) + assertTrue(onWifiLink("192.168.1.1", subnet) { error("IPv4 needs no prefixes") }) + assertFalse(onWifiLink("router.lan", subnet) { prefixes }) + } + + @Test fun traceAndMtuStayIpv4() { + assertEquals(R.string.lan39_ipv6_trace_unsupported, ipv6Refusal(LanTool.TRACE, "fd00::1", false)) + assertEquals(R.string.lan39_ipv6_mtu_unsupported, ipv6Refusal(LanTool.PING, "fd00::1", true)) + assertNull(ipv6Refusal(LanTool.PING, "fd00::1", false)) + assertNull(ipv6Refusal(LanTool.PORTS, "fd00::1", false)) + assertNull(ipv6Refusal(LanTool.TRACE, "192.168.1.1", false)) + } + + @Test fun ipv4LiteralNeedsNoInterface() { + assertEquals(address("192.168.1.10"), toolInetAddress("192.168.1.10", null)) + assertEquals(address("fd00::10"), toolInetAddress("fd00::10", null)) + assertFailsWith { toolInetAddress("fd00::10%rmnet0", "wlan0") } + assertFailsWith { toolInetAddress("fe80::10", null) } + assertFailsWith { toolInetAddress("router.lan", "wlan0") } + } + + @Test fun numericZoneOfTheRouteInterfaceIsAccepted() { + // Our own TCP/DNS rows print a scope set by index as "%12"; the Ping action must accept it back. + assertTrue(zoneMatches(null, "wlan0") { error("no lookup without zone") }) + assertTrue(zoneMatches("wlan0", "wlan0") { error("no lookup for a name") }) + assertTrue(zoneMatches("12", "wlan0") { 12 }) + assertFalse(zoneMatches("13", "wlan0") { 12 }) + assertFalse(zoneMatches("0", "wlan0") { 0 }) + assertFalse(zoneMatches("rmnet0", "wlan0") { 12 }) + assertFalse(zoneMatches("12", null) { 12 }) + assertFalse(zoneMatches("99999999999", "wlan0") { 12 }) + } + + @Test fun droppedAaaaDoesNotLoseTheIpv4Answer() = runTest { + val a = address("192.168.1.10") + val started = currentTime + val result = lookupBoth({ delay(50); listOf(a) }, { awaitCancellation() }) + assertEquals(listOf(a), result) + assertEquals(LOOKUP_TYPE_TIMEOUT_MS, currentTime - started, "waits only the per-type limit") + assertTrue(LOOKUP_TYPE_TIMEOUT_MS < 4_000, "inside the 4 s limit of the whole resolution") + // IPv6-only name whose A query is dropped. + val aaaa = address("fd00::10") + assertEquals(listOf(aaaa), lookupBoth({ awaitCancellation() }, { listOf(aaaa) })) + // Both silent: a DNS timeout, not an empty success. + assertEquals(R.string.lan_dns_timeout, assertFailsWith { lookupBoth({ awaitCancellation() }, { awaitCancellation() }) }.resource) + } + + @Test fun cancellingTheLookupIsNotTurnedIntoAResult() = runTest { + var finished = false + val job = launch { lookupBoth({ awaitCancellation() }, { awaitCancellation() }); finished = true } + advanceTimeBy(100) + job.cancel() + job.join() + assertTrue(job.isCancelled) + assertFalse(finished) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/lan/LanNetworkInfoRefreshTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/lan/LanNetworkInfoRefreshTest.kt new file mode 100644 index 0000000..690f037 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/lan/LanNetworkInfoRefreshTest.kt @@ -0,0 +1,22 @@ +package cz.netkit.app.lan + +import cz.netkit.shared.lan.LanNetworkInfo +import kotlin.test.* + +/** Revize 39/1: LinkProperties changes of the same Wi-Fi refresh only the "Info o síti" snapshot. */ +class LanNetworkInfoRefreshTest { + private fun info(dns: String) = LanNetworkInfo("wlan0", "192.168.1.30", 24, emptyList(), listOf(dns), null, true, null, 0, emptyList()) + + @Test fun sameWifiGetsTheNewSnapshotOtherStateIsKept() { + val state = LanDevicesState(loadingNetwork = false, network = LanDevicesNetwork("192.168.1.30", 24, "192.168.1.0/24", "192.168.1.1", null, info("192.168.1.1")), + selectedAddress = "192.168.1.5") + val refreshed = refreshedNetworkInfo(state, "192.168.1.30", info("192.168.1.53")) + assertEquals(listOf("192.168.1.53"), refreshed.network?.info?.dnsServers) + assertEquals(state.copy(network = refreshed.network), refreshed) + // Another Wi-Fi (address changed meanwhile) or no network: unchanged. + assertSame(state, refreshedNetworkInfo(state, "192.168.2.30", info("192.168.1.53"))) + val empty = LanDevicesState() + assertSame(empty, refreshedNetworkInfo(empty, "192.168.1.30", info("192.168.1.53"))) + assertSame(state, refreshedNetworkInfo(state, "192.168.1.30", info("192.168.1.1"))) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/lan/LanToolPreferencesTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/lan/LanToolPreferencesTest.kt new file mode 100644 index 0000000..9f1f0b0 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/lan/LanToolPreferencesTest.kt @@ -0,0 +1,88 @@ +package cz.netkit.app.lan + +import androidx.datastore.core.DataStoreFactory +import cz.netkit.shared.lan.MaskInterpretation +import cz.netkit.shared.lan.TargetField +import cz.netkit.shared.lan.ToolTargets +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlinx.coroutines.* +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.test.runTest + +class LanToolPreferencesTest { + @Test fun corruptFilesAreReplacedWithPersistedDefaults() = runTest { + val directory = Files.createTempDirectory("netkit-lan-corrupt").toFile() + val owner = CoroutineScope(SupervisorJob() + Dispatchers.IO) + try { + for ((index, content) in listOf("", "{", """{"ports":"830","unknown":true}""").withIndex()) { + val file = directory.resolve("lan-tools-$index.json") + file.writeText(content) + val store = DataStoreFactory.create(serializer = LanPreferencesSerializer, + corruptionHandler = LanToolStore.corruptionHandler, scope = owner) { file } + assertEquals(LanToolPreferences(), store.data.first()) + file.inputStream().use { assertEquals(LanToolPreferences(), LanPreferencesSerializer.readFrom(it)) } + } + } finally { + owner.coroutineContext.job.cancelAndJoin() + directory.deleteRecursively() + } + } + + @Test fun independentEditsSurviveReopeningToolStore() = runTest { + val directory = Files.createTempDirectory("netkit-lan-tools").toFile() + val file = directory.resolve("lan-tools.json") + val expected = LanToolPreferences(PingFields("4", "0,2", "1464", true), "192.0.2.10 0.0.0.0", "830,8291", MaskInterpretation.WILDCARD) + var owner = CoroutineScope(SupervisorJob() + Dispatchers.IO) + fun open() = DataStoreFactory.create(serializer = LanPreferencesSerializer, scope = owner) { file } + try { + val store = open() + assertEquals(LanToolPreferences(), store.data.first()) + coroutineScope { + launch { store.updateData { it.copy(ports = expected.ports) } } + launch { store.updateData { it.copy(subnetInput = expected.subnetInput, maskInterpretation = expected.maskInterpretation) } } + launch { store.updateData { it.copy(ping = expected.ping) } } + } + owner.coroutineContext.job.cancelAndJoin() + owner = CoroutineScope(SupervisorJob() + Dispatchers.IO) + assertEquals(expected, open().data.first()) + } finally { + owner.coroutineContext.job.cancelAndJoin() + directory.deleteRecursively() + } + } + + /** Zadání 48: files written before the target history still load; history and favourites survive reopening. */ + @Test fun targetHistoryIsStoredWithTheToolPreferences() = runTest { + val directory = Files.createTempDirectory("netkit-lan-targets").toFile() + val file = directory.resolve("lan-tools.json") + file.writeText("""{"ports":"830"}""") + var owner = CoroutineScope(SupervisorJob() + Dispatchers.IO) + fun open() = DataStoreFactory.create(serializer = LanPreferencesSerializer, scope = owner) { file } + try { + val store = open() + assertEquals(LanToolPreferences(ports = "830"), store.data.first()) + val targets = (ToolTargets().remember("192.0.2.1").star("198.51.100.2", "Lab") as cz.netkit.shared.lan.FavoriteChange.Updated).targets + store.updateData { it.copy(targets = targets) } + owner.coroutineContext.job.cancelAndJoin() + owner = CoroutineScope(SupervisorJob() + Dispatchers.IO) + val reopened = open() + assertEquals(targets, reopened.data.first().targets) + LanToolStore.clearTargetHistory(reopened) + assertEquals(LanToolPreferences(ports = "830", targets = targets.copy(recent = emptyList())), reopened.data.first()) + assertEquals(listOf("198.51.100.2"), reopened.data.first().targets.suggestions(TargetField.HOST).map { it.value }) + } finally { + owner.coroutineContext.job.cancelAndJoin() + directory.deleteRecursively() + } + } + + @Test fun singleTargetToolsShareTheHistoryField() { + assertEquals(listOf(LanTool.PING, LanTool.TCP_PING, LanTool.TRACE, LanTool.PORTS, LanTool.DNS), + LanTool.entries.filter { it.targetField == TargetField.HOST }) + assertEquals(mapOf(LanTool.RECORDS to TargetField.DNS_NAME, LanTool.WEB to TargetField.URL, LanTool.RDAP to TargetField.RDAP), + LanTool.entries.filter { it.diagnostic }.associateWith { it.targetField }) + assertEquals(listOf(LanTool.DISCOVERY, LanTool.MDNS, LanTool.SUBNET, LanTool.MAC_VENDOR), LanTool.entries.filter { it.targetField == null }) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/lan/PingOptionsTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/lan/PingOptionsTest.kt new file mode 100644 index 0000000..137e6eb --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/lan/PingOptionsTest.kt @@ -0,0 +1,130 @@ +package cz.netkit.app.lan + +import cz.netkit.shared.lan.matchesIcmpEchoReply +import kotlin.test.* +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.test.runTest + +@OptIn(ExperimentalCoroutinesApi::class) +class PingOptionsTest { + @Test fun countAndSpacingUseVirtualTime() = runTest { + val starts = mutableListOf() + val options = PingFields(count = "3", seconds = "0,2").options(false)!! + runPingSeries(options, { testScheduler.currentTime }) { + starts += testScheduler.currentTime + delay(60) + } + assertEquals(listOf(0L, 200L, 400L), starts) + assertEquals(460L, testScheduler.currentTime) + } + + @Test fun defaultsAndBounds() { + assertEquals(PingOptions(null, 1000, 16, false), PingFields().options(true)) + assertEquals(PingOptions(1000, 10000, 1472, true), PingFields("1000", "10", "1472", true).options(true)) + assertFalse(PingFields(df = true).options(false)!!.df) + for (fields in listOf(PingFields(count = "0"), PingFields(count = "1001"), PingFields(seconds = "0.19"), + PingFields(seconds = "10.1"), PingFields(seconds = "NaN"), PingFields(payload = "-1"), PingFields(payload = "1473"))) + assertNull(fields.options(true)) + } + + @Test fun socketRequestAndReplyIncludeExactlyTheChosenPayload() { + for (size in listOf(0, 1, 16, 548, 1472)) { + val request = echoRequest(size) + assertEquals(size + 8, request.size) + val echo = request.copyOf().apply { this[0] = 0 } + assertTrue(matchesIcmpEchoReply(request, echo, echo.size, size == 0)) + echo[7] = echo[7].inc() + assertFalse(matchesIcmpEchoReply(request, echo, echo.size, size == 0)) + } + } + + @Test fun socketRequiresDfOnRequestAndOnlyDisablesItForLargerPayloads() { + val calls = mutableListOf>() + for (size in listOf(0, 16, 17)) { + configureDf(false, size) { option, value -> calls += option to value } + assertEquals(if (size > 16) listOf(10 to 0) else emptyList(), calls) + calls.clear() + configureDf(true, size) { option, value -> calls += option to value } + assertEquals(listOf(10 to 2), calls) + calls.clear() + } + } + + @Test fun unsupportedOptionIsToleratedOnlyWithDfOff() { + val denied: (Int, Int) -> Unit = { _, _ -> throw SecurityException() } + configureDf(false, 1472, denied) + assertFailsWith { configureDf(true, 1472, denied) } + } + + @Test fun terminalSocketErrorsOnlyReportTooLargeWithDf() { + // Framework constants in the local JVM android.jar are stubs. + val errnos = IcmpErrnos(messageTooLarge = 90, unreachable = setOf(101, 111, 113)) + assertEquals(IcmpError.TOO_LARGE, errnos.classify(90, df = true)) + assertEquals(IcmpError.NO_REPLY, errnos.classify(90, df = false)) + for (df in listOf(true, false)) { + for (errno in listOf(101, 111, 113)) assertEquals(IcmpError.NO_REPLY, errnos.classify(errno, df)) + assertEquals(IcmpError.UNAVAILABLE, errnos.classify(9, df)) + } + } + + @Test fun sweepSeparatesSizeLimitFromLoss() = runTest { + for (limit in listOf(547, 548, 1464, 1472)) { + val sizes = mutableListOf() + val result = findMtuPayload { size -> + sizes += size + if (size <= limit) DfProbe.REPLY else DfProbe.TOO_LARGE + } + assertEquals(SweepResult(limit.takeIf { it >= 548 }, SweepLimit.SIZE_OR_MAXIMUM), result) + assertTrue(sizes.all { it in 548..1472 } && sizes.size <= 11) + } + val attempts = mutableListOf() + assertEquals(SweepResult(null, SweepLimit.NO_BASELINE), findMtuPayload { + attempts += it + DfProbe.NO_REPLY + }) + assertEquals(listOf(548, 548), attempts) + } + + @Test fun sweepRecoversFromOneLostEchoAtEachSize() = runTest { + val seen = mutableSetOf() + assertEquals(SweepResult(1464, SweepLimit.SIZE_OR_MAXIMUM), findMtuPayload { + when { + seen.add(it) -> DfProbe.NO_REPLY + it <= 1464 -> DfProbe.REPLY + else -> DfProbe.TOO_LARGE + } + }) + } + + @Test fun repeatedTimeoutSetsSoftUpperBoundAboveConfirmedPayload() = runTest { + val attempts = mutableMapOf() + val result = findMtuPayload { + attempts[it] = attempts.getOrElse(it) { 0 } + 1 + if (it <= 900) DfProbe.REPLY else DfProbe.NO_REPLY + } + assertEquals(SweepResult(900, SweepLimit.SOFT_TIMEOUT), result) + assertEquals(2, attempts[901]) + assertTrue(attempts.filterKeys { it > 900 }.values.all { it == 2 }) + } + + @Test fun sweepIsInconclusiveWhenLastConfirmedSizeStopsReplying() = runTest { + val attempts = mutableListOf() + val result = findMtuPayload { size -> + attempts += size + if (attempts.size <= 2) DfProbe.REPLY else DfProbe.NO_REPLY + } + assertEquals(listOf(548, 1010, 1241, 1241, 1010), attempts) + assertEquals(SweepResult(null, SweepLimit.NO_BASELINE), result) + } + + @Test fun closerSizeErrorSupersedesEarlierSoftBound() = runTest { + assertEquals(SweepResult(899, SweepLimit.SIZE_OR_MAXIMUM), findMtuPayload { + when { + it > 1000 -> DfProbe.NO_REPLY + it >= 900 -> DfProbe.TOO_LARGE + else -> DfProbe.REPLY + } + }) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/lan/TracePathTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/lan/TracePathTest.kt new file mode 100644 index 0000000..a44c28a --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/lan/TracePathTest.kt @@ -0,0 +1,52 @@ +package cz.netkit.app.lan + +import cz.netkit.shared.lan.PingReply +import kotlin.test.* +import kotlinx.coroutines.* +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest + +@OptIn(ExperimentalCoroutinesApi::class) +class TracePathTest { + private val target = "10.0.2.2" + + @Test fun fiveSilentHopsWaitForContinueThenReachTarget() = runTest { + val gate = CompletableDeferred() + val rows = mutableListOf>() + val run = async { + tracePath(target, null, { ttl -> PingReply(if (ttl == 6) 1.0 else null) }, + { ttl, address, _ -> rows += ttl to address }, gate::await) + } + runCurrent() + assertFalse(run.isCompleted) + assertEquals((1..5).map { it to "" }, rows) + gate.complete(Unit) + assertTrue(run.await()) + assertEquals(6 to target, rows.last()) + } + + @Test fun cancellationDuringNextProbeCannotAppendAHop() = runTest { + val gate = CompletableDeferred() + val enteredSix = CompletableDeferred() + val rows = mutableListOf() + val job = launch { + tracePath(target, null, { ttl -> + if (ttl == 6) { enteredSix.complete(Unit); awaitCancellation() } + PingReply(null) + }, { ttl, _, _ -> rows += ttl }, gate::await) + } + runCurrent() + gate.complete(Unit) + enteredSix.await() + job.cancelAndJoin() + assertEquals((1..5).toList(), rows) + } + + @Test fun knownIntermediateHopSkipsPauseAndLimitRemainsThirty() = runTest { + val rows = mutableListOf() + val reached = tracePath(target, null, { PingReply(null, hop = if (it == 2) "127.0.0.1" else null) }, + { ttl, _, _ -> rows += ttl }, { fail("unexpected pause") }) + assertFalse(reached) + assertEquals((1..30).toList(), rows) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/lan/UdpServicesFixtureTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/lan/UdpServicesFixtureTest.kt new file mode 100644 index 0000000..3c46862 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/lan/UdpServicesFixtureTest.kt @@ -0,0 +1,89 @@ +package cz.netkit.app.lan + +import cz.netkit.shared.lan.NtpReferenceKind +import cz.netkit.shared.lan.UdpProbeOutcome +import cz.netkit.shared.lan.UdpServicePorts +import cz.netkit.shared.lan.probeUdpServices +import java.io.File +import java.net.DatagramSocket +import java.net.InetAddress +import java.util.concurrent.TimeUnit +import kotlin.random.Random +import kotlin.test.* +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking + +/** + * Integration (zadání 39 AC-004): the production [DatagramUdpExchange] and shared codecs against + * the stdlib loopback fixture `tools/testsrv/udp_services.py`. Synthetic community and values only. + */ +class UdpServicesFixtureTest { + private val script = File("../tools/testsrv/udp_services.py").absoluteFile + private val loopback = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)) + + private fun withFixture(community: String, body: (UdpServicePorts) -> T): T { + check(script.isFile) { "fixture missing: $script" } + val process = ProcessBuilder("python3", "-I", script.path, "--community", community, "--duration", "30") + .redirectError(ProcessBuilder.Redirect.INHERIT).start() + try { + val ready = process.inputStream.bufferedReader().readLine()?.split(' ') ?: error("fixture did not start") + assertEquals("READY", ready[0]) + val ports = ready.drop(1).associate { it.substringBefore('=') to it.substringAfter('=').toInt() } + return body(UdpServicePorts(ports.getValue("snmp"), ports.getValue("ntp"), ports.getValue("dns"))) + } finally { + process.destroy() + process.waitFor(5, TimeUnit.SECONDS) + } + } + + @Test fun allThreeServicesAnswerOverLoopback() = withFixture("lab-community") { ports -> + val result = runBlocking { + probeUdpServices(DatagramUdpExchange(loopback), "lab-community".encodeToByteArray(), dnsAllowed = true, + randomBytes = { Random.nextBytes(it) }, ports = ports) + } + assertEquals(UdpProbeOutcome.OK, result.snmp.outcome) + assertEquals("netkit-fixture", result.snmp.sysName) + assertEquals("NetKit fixture SNMP agent (synthetic)", result.snmp.sysDescr) + assertEquals(UdpProbeOutcome.OK, result.ntp.outcome) + assertEquals(2, result.ntp.reply!!.stratum) + assertEquals(NtpReferenceKind.UPSTREAM_ADDRESS to "192.0.2.1", result.ntp.reply!!.referenceKind to result.ntp.reply!!.reference) + assertEquals(UdpProbeOutcome.OK, result.dns.outcome) + assertEquals("netkit-fixture", result.dns.reply!!.version) + } + + @Test fun wrongCommunityIsSilentAndClosedPortIsReported() = withFixture("lab-community") { ports -> + // A port with nothing bound on loopback answers with ICMP port unreachable. + val closed = DatagramSocket(0, loopback).use { it.localPort } + val started = System.nanoTime() + val result = runBlocking { + probeUdpServices(DatagramUdpExchange(loopback), "guess".encodeToByteArray(), dnsAllowed = true, + randomBytes = { Random.nextBytes(it) }, ports = ports.copy(dns = closed)) + } + val elapsedMs = (System.nanoTime() - started) / 1_000_000 + assertEquals(UdpProbeOutcome.NO_REPLY, result.snmp.outcome) + assertEquals(UdpProbeOutcome.OK, result.ntp.outcome) + assertEquals(UdpProbeOutcome.CLOSED, result.dns.outcome) + // Two attempts of 1.5 s in parallel with the others: bounded, not serial. + assertTrue(elapsedMs in 2_900..4_500, "elapsed $elapsedMs ms") + } + + @Test fun cancellationClosesTheSocketWithoutWaitingForTheTimeout() { + // A bound but silent peer: receive() blocks until the 5 s timeout unless the socket is closed. + DatagramSocket(0, loopback).use { silent -> + var socket: DatagramSocket? = null + val exchange = DatagramUdpExchange(loopback, bind = { socket = it }) + val elapsedMs = runBlocking { + val job = launch(Dispatchers.Default) { exchange.exchange(silent.localPort, byteArrayOf(1, 2, 3), 5_000) { _, _ -> false } } + delay(300) + val started = System.nanoTime() + job.cancelAndJoin() + (System.nanoTime() - started) / 1_000_000 + } + assertTrue(elapsedMs < 1_000, "cancel took $elapsedMs ms") + assertTrue(assertNotNull(socket).isClosed, "the cancellation hook closed the socket right away") + } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/lan/WebDiagnosticTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/lan/WebDiagnosticTest.kt new file mode 100644 index 0000000..b7f3327 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/lan/WebDiagnosticTest.kt @@ -0,0 +1,516 @@ +package cz.netkit.app.lan + +import java.io.ByteArrayOutputStream +import java.io.File +import java.net.ConnectException +import java.net.Inet6Address +import java.net.InetSocketAddress +import java.net.Socket +import java.net.SocketAddress +import java.net.SocketTimeoutException +import java.net.UnknownHostException +import java.security.cert.CertPathValidatorException +import java.security.cert.CertificateExpiredException +import java.security.cert.CertificateNotYetValidException +import javax.net.SocketFactory +import javax.net.ssl.SSLHandshakeException +import javax.net.ssl.SSLPeerUnverifiedException +import java.net.InetAddress +import java.security.KeyStore +import java.security.cert.CertificateFactory +import java.util.concurrent.TimeUnit +import javax.net.ssl.SSLContext +import javax.net.ssl.TrustManagerFactory +import javax.net.ssl.X509TrustManager +import javax.xml.parsers.DocumentBuilderFactory +import kotlinx.coroutines.runBlocking +import okhttp3.Dns +import okhttp3.OkHttpClient +import kotlin.test.* + +class WebDiagnosticTest { + @Test fun urlsAllowOnlyHttpSchemesAndDropFragments() { + assertNull(diagnosticUrl("file:///example")) + assertNull(diagnosticUrl("https://user@example.test/")) + assertEquals("https://example.test/x", diagnosticUrl("https://example.test/x#private").toString()) + } + + @Test fun responseChainConsumesOnlyHeadersAndKeepsRedirectsOnTlsFailure() = runBlocking { + var reads = 0 + val responses = listOf( + "HTTP/1.1 302 Found\r\nLocation: /next\r\n\r\n", + "HTTP/1.1 501 Unsupported\r\n\r\n", + "HTTP/1.1 103 Early Hints\r\n\r\nHTTP/1.1 302 Found\r\nLocation: https://example.test/secure\r\n\r\n", + ) + val report = inspectWeb("http://example.test/") { url, method, _, _ -> + if (url.isHttps) throw javax.net.ssl.SSLHandshakeException("fixture") + val input = (responses[reads++] + "body").byteInputStream() + readPlainHeaders(input, url, method, WebTimings(), publicIp) {}.also { assertEquals(4, input.available()) } + } + assertEquals(WebError.TLS_HANDSHAKE, report.error) + assertEquals("https://example.test/secure", report.failedUrl.toString()) + assertEquals(listOf(302, 501, 302), report.hops.map { it.status }) + assertEquals(listOf("HEAD", "HEAD", "GET"), report.hops.map { it.method }) + val limit = inspectWeb("http://example.test/") { url, method, _, _ -> + WebHop(url, method, 307, WebTimings(), null, null, "/loop", null, publicIp) + } + assertEquals(WebError.REDIRECT_LIMIT, limit.error) + assertEquals(6, limit.hops.size) + } + + private val publicIp = InetAddress.getByAddress(byteArrayOf(8, 8, 8, 8)) + private val local = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)) + + private fun resolver(resolve: (String) -> List) = object : Dns { + override fun lookup(hostname: String) = resolve(hostname) + } + + private fun sockets(create: () -> Socket) = object : SocketFactory() { + override fun createSocket() = create() + override fun createSocket(host: String, port: Int): Socket = error("Expected an unconnected socket") + override fun createSocket(host: InetAddress, port: Int): Socket = error("Expected an unconnected socket") + override fun createSocket(host: String, port: Int, local: InetAddress, localPort: Int): Socket = error("Unexpected bind") + override fun createSocket(host: InetAddress, port: Int, local: InetAddress, localPort: Int): Socket = error("Unexpected bind") + } + + private fun memorySocket(onConnect: (InetAddress) -> Unit, reply: (String) -> String) = object : Socket() { + private val wire = ByteArrayOutputStream() + override fun setSoTimeout(timeout: Int) = Unit + override fun connect(endpoint: SocketAddress, timeout: Int) = onConnect((endpoint as InetSocketAddress).address) + override fun getOutputStream() = wire + override fun getInputStream() = reply(wire.toString("US-ASCII")).byteInputStream() + } + + /** Exercise the production DNS and HTTP paths without opening any real socket. */ + private suspend fun publicProbe(response: String, nextAddresses: List, expectedLookups: Int): WebReport { + var lookups = 0 + val connections = mutableListOf() + val requests = mutableListOf() + val client = diagnosticClient().newBuilder() + .dns(resolver { if (lookups++ == 0) listOf(publicIp, local) else nextAddresses }) + .socketFactory(sockets { memorySocket(connections::add) { requests += it; response } }).build() + val report = inspectWeb("http://example.test/", client) + assertEquals(listOf(publicIp), connections, "Only the first socket may connect") + assertContains(requests.single(), "User-Agent: $diagnosticUserAgent\r\n") + assertEquals(expectedLookups, lookups) + return report + } + + @Test fun publicPeerChecksEveryConnectAnswerIncludingSameHostAndGetRetry() = runBlocking { + val mapped = Inet6Address.getByAddress(null, ByteArray(16).apply { + this[10] = -1; this[11] = -1; publicIp.address.copyInto(this, 12) + }, -1) + for (answers in listOf(listOf(local), listOf(publicIp, local), listOf(mapped), + listOf(publicIp, InetAddress.getByName("198.18.0.7")), listOf(InetAddress.getByName("64:ff9b::7f00:1")))) { + for (location in listOf("/next", "https://other.test/next")) { + val response = "HTTP/1.1 302 Found\r\nLocation: $location\r\n\r\n" + val report = publicProbe(response, answers, 2) + assertEquals(WebError.LOCAL_REDIRECT, report.error) + assertEquals(location, report.hops.single().location) + } + } + val sameHost = publicProbe("HTTP/1.1 302 Found\r\nLocation: /next\r\n\r\n", listOf(InetAddress.getByName("198.18.0.7")), 2) + assertEquals(WebError.LOCAL_REDIRECT, sameHost.error) + val fallback = publicProbe("HTTP/1.1 405 Method Not Allowed\r\n\r\n", listOf(local), 2) + assertEquals(WebError.LOCAL_REDIRECT, fallback.error) + assertEquals("HEAD", fallback.hops.single().method) + } + + @Test fun publicRedirectRejectsLocalLiteralsBeforeDnsAndPortChangesBeforeConnect() = runBlocking { + for (literal in listOf("127.0.0.1", "10.0.0.1", "172.16.0.1", "192.168.0.1", "100.64.0.1", + "169.254.0.1", "0.1.2.3", "224.0.0.1", "[::1]", "[fe80::1]", "[fd00::1]", "[ff02::1]", + "[::ffff:127.0.0.1]", "[::ffff:8.8.8.8]", "127.1", "198.19.0.1", "[64:ff9b::a00:1]")) { + for (scheme in listOf("http", "https")) { + val location = "$scheme://$literal/next" + val report = publicProbe("HTTP/1.1 302 Found\r\nLocation: $location\r\n\r\n", emptyList(), 1) + assertEquals(WebError.LOCAL_REDIRECT, report.error, location) + assertEquals(location, report.hops.single().location) + } + } + val changed = publicProbe("HTTP/1.1 302 Found\r\nLocation: http://example.test:8080/next\r\n\r\n", emptyList(), 1) + assertEquals(WebError.REDIRECT_PORT, changed.error) + } + + @Test fun explicitLocalProbeRetainsFallbackAndCanFollowLocalRedirect() = runBlocking { + val replies = listOf("302 Found\r\nLocation: /next", "405 Method Not Allowed", "200 OK").iterator() + val methods = mutableListOf() + val client = diagnosticClient().newBuilder() + .dns(resolver { listOf(local) }) + .socketFactory(sockets { + memorySocket({ assertEquals(local, it) }) { request -> + methods += request.substringBefore(' ') + "HTTP/1.1 ${replies.next()}\r\n\r\n" + } + }).build() + val report = inspectWeb("http://127.0.0.1:8080/", client) + assertNull(report.error) + assertEquals(listOf("HEAD", "HEAD", "GET"), methods) + assertEquals(listOf(302, 405, 200), report.hops.map { it.status }) + } + + @Test fun sameHostRedirectAndGetRetainNat64AndFakeIpRoutes() = runBlocking { + val custom = WebNat64Prefix(InetAddress.getByName("fd12:3456:789a::"), 48) + for (route in listOf("64:ff9b::808:808", "fd12:3456:789a:808:8:800::", "198.18.0.7", "198.19.255.254")) { + val ip = InetAddress.getByName(route) + val replies = listOf("302 Found\r\nLocation: /next", "405 Method Not Allowed", "200 OK").iterator() + val client = diagnosticClient().newBuilder() + .dns(resolver { listOf(ip) }) + .socketFactory(sockets { memorySocket({ assertEquals(ip, it) }) { "HTTP/1.1 ${replies.next()}\r\n\r\n" } }) + .build() + val url = "http://example.test/" + val initial = inspectWeb(url, client) { custom } + val report = if (route.startsWith("198.")) { + val grant = assertNotNull(initial.confirmation) + assertEquals(WebRoute.FAKE_IP, grant.route) + assertTrue(initial.hops.isEmpty()) + inspectWeb(url, client, grant) { custom } + } else initial + assertNull(report.error, route) + assertNull(report.confirmation, route) + assertEquals(listOf("HEAD", "HEAD", "GET"), report.hops.map { it.method }, route) + assertEquals(List(3) { ip }, report.hops.map { it.peer }, route) + } + } + + @Test fun translatedPrivateAddressStillNeedsConsentAndSameHostCannotSwitchFakePeer() = runBlocking { + val prefix = WebNat64Prefix(InetAddress.getByName("2001:db8:1234::"), 48) + val fake = InetAddress.getByName("198.18.0.7") + val nextFake = InetAddress.getByName("198.18.0.8") + val translatedLocal = InetAddress.getByName("2001:db8:1234:c0a8:0:100::") + val noConnect = sockets { error("Unexpected socket") } + val url = "http://example.test/" + for (scheme in listOf("http", "https")) { + val client = diagnosticClient().newBuilder().dns(resolver { listOf(translatedLocal) }).socketFactory(noConnect).build() + assertEquals(translatedLocal, inspectWeb("$scheme://example.test/", client) { prefix }.confirmation?.address) + } + for (nextIp in listOf(local, nextFake, translatedLocal)) { + var connections = 0 + val client = diagnosticClient().newBuilder() + .dns(resolver { listOf(if (connections == 0) fake else nextIp) }) + .socketFactory(sockets { memorySocket({ connections++ }) { "HTTP/1.1 302 Found\r\nLocation: /next\r\n\r\n" } }) + .build() + val grant = assertNotNull(inspectWeb(url, client) { prefix }.confirmation) + val result = inspectWeb(url, client, grant) { prefix } + assertEquals(WebError.LOCAL_REDIRECT, result.error) + assertEquals(1, connections) + } + } + + @Test fun fakeIpConsentPrecedesHttpAndTlsAndPinsOneAddress() = runBlocking { + val fake = InetAddress.getByName("198.18.0.7") + val other = InetAddress.getByName("198.19.0.8") + for (scheme in listOf("http", "https")) { + var answers = listOf(local, fake, other) + val attempts = mutableListOf() + val client = diagnosticClient().newBuilder().dns(resolver { answers }) + .socketFactory(sockets { memorySocket({ attempts += it; throw ConnectException("fixture") }) { error("No request expected") } }) + .build() + val url = "$scheme://example.test/" + val grant = assertNotNull(inspectWeb(url, client).confirmation) + assertEquals(WebRoute.FAKE_IP, grant.route) + assertEquals(fake, grant.address) + for (host in listOf("198.19.0.8", "[64:ff9b::c612:7]")) { + assertEquals(WebRoute.FAKE_IP, inspectWeb("$scheme://$host/", client).confirmation?.route) + } + answers = listOf(other) + assertEquals(other, inspectWeb(url, client, grant).confirmation?.address) + for (changed in listOf(listOf(local), listOf(fake, publicIp))) { + answers = changed + assertEquals(WebError.ROUTE_CHANGED, inspectWeb(url, client, grant).error) + } + answers = listOf(other, local, fake) + assertEquals(WebError.ROUTE_CHANGED, inspectWeb(url, client, grant) { + WebNat64Prefix(InetAddress.getByName("2001:db8::"), 96) + }.error) + assertTrue(attempts.isEmpty()) + assertEquals(WebError.CONNECT, inspectWeb(url, client, grant).error) + assertEquals(listOf(fake), attempts) + } + } + + @Test fun redirectToFakeHostRequiresFreshConsentEvenForIdenticalPeer() = runBlocking { + val url = "http://example.test/" + val next = "http://next.example.test/status%20page/detail?view=full" + val fake = InetAddress.getByName("198.18.0.7") + val replacement = InetAddress.getByName("198.19.0.8") + for (first in listOf(publicIp, fake)) { + var nextAnswers = listOf(fake) + val connections = mutableListOf() + val client = diagnosticClient().newBuilder() + .dns(resolver { if (it == "example.test") listOf(first) else nextAnswers }) + .socketFactory(sockets { memorySocket(connections::add) { request -> + if (request.startsWith("HEAD / ")) "HTTP/1.1 302 Found\r\nLocation: $next\r\n\r\n" + else "HTTP/1.1 405 Method Not Allowed\r\n\r\n" + } }).build() + val initial = inspectWeb(url, client) + val redirected = if (first == fake) { + val firstGrant = assertNotNull(initial.confirmation) + assertNull(firstGrant.redirectFromHost) + inspectWeb(url, client, firstGrant) + } else initial + val grant = assertNotNull(redirected.confirmation) + assertEquals("example.test", grant.redirectFromHost) + assertEquals(next, grant.url.toString()) + assertEquals(fake, grant.address) + assertEquals(listOf(first), connections) + assertEquals(302, redirected.hops.single().status) + assertFalse(redirected.hops.single().fromPreviousRun) + nextAnswers = listOf(local, fake) + val failed = inspectWeb(url, client, grant) + assertEquals(WebError.ROUTE_CHANGED, failed.error) + assertTrue(failed.hops.single().fromPreviousRun) + nextAnswers = listOf(replacement) + val renewed = assertNotNull(inspectWeb(url, client, grant).confirmation) + assertEquals(grant.redirectFromHost, renewed.redirectFromHost) + assertEquals(replacement, renewed.address) + assertEquals(listOf(first), connections) + val resumed = inspectWeb(url, client, renewed) + assertNull(resumed.error) + assertEquals(diagnosticUrl(next), resumed.skippedGet) + assertEquals(listOf("HEAD", "HEAD"), resumed.hops.map { it.method }) + assertEquals(listOf(true, false), resumed.hops.map { it.fromPreviousRun }) + assertEquals(listOf(first, replacement), connections) + } + } + + @Test fun redirectBudgetSurvivesConfirmations() = runBlocking { + val url = "http://example.test/" + val fake = InetAddress.getByName("198.18.0.7") + var requests = 0 + val client = diagnosticClient().newBuilder().dns(resolver { listOf(fake) }) + .socketFactory(sockets { memorySocket({ assertEquals(fake, it) }) { + "HTTP/1.1 302 Found\r\nLocation: http://hop${++requests}.example.test/\r\n\r\n" + } }).build() + var report = inspectWeb(url, client) + repeat(6) { index -> + assertEquals(index, requests) + val grant = assertNotNull(report.confirmation) + val source = when (index) { + 0 -> null + 1 -> "example.test" + else -> "hop${index - 1}.example.test" + } + assertEquals(source, grant.redirectFromHost) + report = inspectWeb(url, client, grant) + assertEquals(List(index) { true } + false, report.hops.map { it.fromPreviousRun }) + } + assertEquals(WebError.REDIRECT_LIMIT, report.error) + assertEquals(6, report.hops.size) + assertEquals(6, requests) + } + + @Test fun redirectAndPreviousMeasurementLabelsInBothLanguages() { + val source = "example.test" + val target = "https://next.example.test/status%20page/detail" + val address = "192.0.2.7" + for ((folder, from, previous) in listOf( + Triple("values", "Přesměrování z", "předchozí měření"), + Triple("values-en", "Redirect from", "previous measurement"), + )) { + val file = File("src/main/res/$folder/strings_lan.xml") + val strings = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file).getElementsByTagName("string") + fun template(name: String) = (0 until strings.length).map(strings::item) + .single { it.attributes.getNamedItem("name").nodeValue == name }.textContent + val message = template("diag_fake_ip_redirect_confirmation").format(source, target, address) + assertContains(message, "$from $source") + assertContains(message, target) + assertContains(message, address) + assertContains(message, "fake-IP") + assertEquals("HEAD 302 · $previous", template("diag_previous_measurement").format("HEAD 302")) + } + } + + @Test fun nat64PrefixChangesAndInvalidReservedOctetCannotOpenPublicRoute() = runBlocking { + val prefix = WebNat64Prefix(InetAddress.getByName("2001:db8:1234::"), 48) + val invalid = InetAddress.getByName("2001:db8:1234:808:108:800::") + val noConnect = diagnosticClient().newBuilder().dns(resolver { listOf(invalid) }) + .socketFactory(sockets { error("Unexpected socket") }).build() + assertEquals(invalid, inspectWeb("http://nas.test/", noConnect) { prefix }.confirmation?.address) + + var connects = 0 + val client = diagnosticClient().newBuilder().dns(resolver { listOf(publicIp) }) + .socketFactory(sockets { memorySocket({ connects++ }) { "HTTP/1.1 302 Found\r\nLocation: /next\r\n\r\n" } }).build() + val report = inspectWeb("http://example.test/", client) { if (connects == 0) null else prefix } + assertEquals(WebError.ROUTE_CHANGED, report.error) + assertEquals(1, connects) + } + + @Test fun firstHostnameWithMixedAnswersNeverFallsBackToLan() = runBlocking { + for (scheme in listOf("http", "https")) { + val attempted = mutableListOf() + val client = diagnosticClient().newBuilder() + .dns(resolver { listOf(local, publicIp, InetAddress.getByName("198.19.0.1")) }) + .socketFactory(sockets { memorySocket({ attempted += it; throw ConnectException("refused") }) { error("No request expected") } }) + .build() + val report = inspectWeb("$scheme://example.test/", client) + assertEquals(WebError.CONNECT, report.error) + assertNull(report.confirmation) + assertEquals(listOf(publicIp), attempted) + } + } + + @Test fun splitDnsConfirmationPrecedesSocketAndGrantsOnlyDisplayedUrlAndAddress() = runBlocking { + val url = "http://nas.lan/status" + val other = InetAddress.getByName("192.168.1.1") + var answers = listOf(local, other) + val attempts = mutableListOf() + val replies = listOf("405 Method Not Allowed", "200 OK").iterator() + val client = diagnosticClient().newBuilder().dns(resolver { answers }) + .socketFactory(sockets { memorySocket(attempts::add) { "HTTP/1.1 ${replies.next()}\r\n\r\n" } }).build() + val pending = inspectWeb(url, client) + val grant = assertNotNull(pending.confirmation) + assertEquals(diagnosticUrl(url), grant.url) + assertEquals(local, grant.address) + assertTrue(pending.hops.isEmpty()) + answers = listOf(other) + assertEquals(other, inspectWeb(url, client, confirmed = grant).confirmation?.address) + for (changed in listOf(listOf(publicIp), listOf(InetAddress.getByName("198.18.0.7")), listOf(local, publicIp))) { + answers = changed + assertEquals(WebError.ROUTE_CHANGED, inspectWeb(url, client, confirmed = grant).error) + } + answers = listOf(other, local) + assertNotNull(inspectWeb("$url/changed", client, confirmed = grant).confirmation) + assertTrue(attempts.isEmpty()) + val allowed = inspectWeb(url, client, confirmed = grant) + assertNull(allowed.error) + assertEquals(listOf("HEAD", "GET"), allowed.hops.map { it.method }) + assertEquals(listOf(local, local), allowed.hops.map { it.peer }) + assertEquals(listOf(local, local), attempts) + } + + @Test fun crossOriginRedirectStaysHeadOnly() = runBlocking { + for (target in listOf("https://example.test/", "http://other.test:8080/", "http://example.test/")) { + for (status in listOf(405, 501)) { + val report = inspectWeb("http://example.test:8080/") { url, method, previous, _ -> + if (previous != null) WebHop(url, method, status, WebTimings(), null, null, null, null, publicIp) + else WebHop(url, method, 302, WebTimings(), null, null, target, null, publicIp) + } + assertNull(report.error) + assertEquals(listOf("HEAD", "HEAD"), report.hops.map { it.method }) + assertEquals(diagnosticUrl(target), report.skippedGet) + assertEquals(report.skippedGet, report.prefillUrl) + } + } + } + + @Test fun transportErrorsKeepMachineDetailsSecondary() = runBlocking { + val cases = listOf( + SSLPeerUnverifiedException("fixture") to WebError.TLS_NAME, + SSLHandshakeException("fixture").apply { initCause(CertPathValidatorException()) } to WebError.TLS_TRUST, + SSLHandshakeException("fixture").apply { initCause(CertPathValidatorException(CertificateExpiredException())) } to WebError.TLS_VALIDITY, + SSLHandshakeException("fixture").apply { initCause(CertificateNotYetValidException()) } to WebError.TLS_VALIDITY, + SSLHandshakeException("fixture") to WebError.TLS_HANDSHAKE, + UnknownHostException("fixture") to WebError.DNS, ConnectException("fixture") to WebError.CONNECT, + SocketTimeoutException("fixture") to WebError.TIMEOUT, + ) + for ((exception, expected) in cases) { + val report = inspectWeb("https://example.test/") { _, _, _, _ -> throw exception } + assertEquals(expected, report.error) + assertEquals("fixture", report.reason) + } + } + + @Test fun loopbackRedirectFallbackTimingsAndCertificateValidation() = runBlocking { + val fixture = File("../tools/testsrv/web_diagnostic.py").canonicalPath + val child = ProcessBuilder("python3", "-I", fixture).redirectError(ProcessBuilder.Redirect.INHERIT).start() + try { + val (http, https, cert) = requireNotNull(child.inputStream.bufferedReader().readLine()) { + "Loopback fixture did not start" + }.split(" ", limit = 3) + val client = diagnosticClient().newBuilder().dns(object : Dns { + override fun lookup(hostname: String): List { + require(hostname == "example.test") + return listOf(InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))) + } + }).build() + // The route seen by the client is public. This test factory wires only that route to the fixture. + var connects = 0 + val publicClient = trustFixture(client, File(cert)).newBuilder() + .dns(resolver { host -> assertEquals("example.test", host); listOf(publicIp) }) + .socketFactory(sockets { object : Socket() { + override fun connect(endpoint: SocketAddress, timeout: Int) { + val route = endpoint as InetSocketAddress + assertEquals(publicIp, route.address) + connects++ + super.connect(InetSocketAddress(local, route.port), timeout) + } + } }).build() + for (origin in listOf("http://example.test:$http", "https://example.test:$https")) { + val before = connects + val blocked = inspectWeb("$origin/local-location", publicClient) + assertEquals(WebError.LOCAL_REDIRECT, blocked.error) + assertEquals("http://127.0.0.1:${origin.substringAfterLast(':')}/fallback", blocked.hops.single().location) + assertEquals(before + 1, connects) + assertEquals(diagnosticUserAgent, inspectWeb("$origin/user-agent", publicClient).hops.single().server) + } + suspend fun confirmedProbe(url: String, transport: OkHttpClient): WebReport { + val grant = assertNotNull(inspectWeb(url, transport).confirmation) + assertEquals(local, grant.address) + return inspectWeb(url, transport, confirmed = grant) + } + // Simulate the HTTP redirect in memory, then complete a real TLS handshake on the fixture. + for (route in listOf(InetAddress.getByName("64:ff9b::808:808"), InetAddress.getByName("198.18.0.7"))) { + var socketCount = 0 + val upgrade = trustFixture(client, File(cert)).newBuilder().dns(resolver { listOf(route) }) + .socketFactory(sockets { + if (socketCount++ == 0) memorySocket({ assertEquals(route, it) }) { + "HTTP/1.1 301 Moved\r\nLocation: https://example.test:$https/\r\n\r\n" + } else object : Socket() { + override fun connect(endpoint: SocketAddress, timeout: Int) { + assertEquals(route, (endpoint as InetSocketAddress).address) + super.connect(InetSocketAddress(local, endpoint.port), timeout) + } + } + }).build() + val source = "http://example.test:$https/" + val initial = inspectWeb(source, upgrade) + val upgraded = if (route.address.size == 4) { + inspectWeb(source, upgrade, assertNotNull(initial.confirmation)) + } else initial + assertNull(upgraded.error) + assertEquals(listOf(route, route), upgraded.hops.map { it.peer }) + assertNotNull(upgraded.hops.last().tls) + } + val plain = confirmedProbe("http://example.test:$http/redirect", client) + assertNull(plain.error) + assertEquals(listOf(302, 405, 200), plain.hops.map { it.status }) + assertEquals(listOf("HEAD", "HEAD", "GET"), plain.hops.map { it.method }) + assertEquals("/fallback", plain.hops.first().location) + assertTrue(plain.hops.all { it.times.dns != null && it.times.tcp != null && it.times.tls == null }) + assertTrue(requireNotNull(plain.hops.last().times.ttfb) >= 20) + assertEquals("max-age=300", plain.hops.last().hsts) + assertNotNull(plain.hops.last().server) + val loop = confirmedProbe("http://example.test:$http/loop", client) + assertEquals(WebError.REDIRECT_LIMIT, loop.error) + assertEquals(6, loop.hops.size) + + val url = "https://example.test:$https/" + val rejected = confirmedProbe(url, client) + assertEquals(WebError.TLS_TRUST, rejected.error) + assertTrue(rejected.hops.isEmpty()) + val verified = confirmedProbe(url, trustFixture(client, File(cert))) + assertNull(verified.error) + val hop = verified.hops.single() + assertTrue(listOf(hop.times.dns, hop.times.tcp, hop.times.tls, hop.times.ttfb).all { it != null && it >= 0 }) + assertEquals(local, hop.peer) + val leaf = assertNotNull(hop.tls).certificates.single() + assertContains(leaf.san, "example.test") + assertEquals(32, leaf.fingerprint.split(':').size) + } finally { + child.outputStream.close() + if (!child.waitFor(5, TimeUnit.SECONDS)) child.destroyForcibly() + } + } + + /** Normal PKIX and hostname verification with only this run's generated test trust anchor. */ + private fun trustFixture(client: OkHttpClient, cert: File): OkHttpClient { + val store = KeyStore.getInstance(KeyStore.getDefaultType()).apply { + load(null, null) + setCertificateEntry("fixture", cert.inputStream().use { CertificateFactory.getInstance("X.509").generateCertificate(it) }) + } + val factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).apply { init(store) } + val trust = factory.trustManagers.filterIsInstance().single() + val tls = SSLContext.getInstance("TLS").apply { init(null, arrayOf(trust), null) } + return client.newBuilder().sslSocketFactory(tls.socketFactory, trust).build() + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/nav/ManifestExportsTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/nav/ManifestExportsTest.kt new file mode 100644 index 0000000..dcea748 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/nav/ManifestExportsTest.kt @@ -0,0 +1,182 @@ +package cz.netkit.app.nav + +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.w3c.dom.Element +import kotlin.test.* + +/** + * Exported components, their protection and the final permissions (zadání 36 §2.9, docs/bezpecnost.md). + * Checks the **merged** manifests (library components included) that Gradle declares as inputs of + * every unit test task: debug and dev always, release with `-PnetkitRequireReleaseManifest=true`. A new exported component, a weakened protection or + * a new permission fails here until the table and the docs change. + */ +class ManifestExportsTest { + private val android = "http://schemas.android.com/apk/res/android" + private val tools = "http://schemas.android.com/tools" + + private fun parse(file: File): Element = DocumentBuilderFactory.newInstance().apply { + isNamespaceAware = true + setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) + }.newDocumentBuilder().parse(file).documentElement + + /** variant → merged manifest file, from the Gradle test configuration. */ + private val merged: Map by lazy { + val property = assertNotNull(System.getProperty("netkit.mergedManifests"), "Gradle passes netkit.mergedManifests") + property.split(',').associate { entry -> entry.substringBefore('=') to File(entry.substringAfter('=')) } + } + + /** Every manifest Gradle declared must exist; nothing is filtered out silently. */ + private fun required(): List> { + for ((variant, file) in merged) assertTrue(file.isFile, "merged manifest of $variant at $file") + assertTrue("debug" in merged && "dev" in merged, "debug and dev are always checked: ${merged.keys}") + if (System.getProperty("netkit.requireReleaseManifest") == "true") assertTrue("release" in merged, "release manifest required") + return merged.map { (variant, file) -> variant to parse(file) } + } + + private fun Element.children(tag: String): List { + val nodes = getElementsByTagName(tag) + return (0 until nodes.length).map { nodes.item(it) as Element } + } + + private fun Element.attr(name: String): String = getAttributeNS(android, name) + private fun Element.actions(): Set = children("action").map { it.attr("name") }.toSet() + /** Explicit `exported`, else the platform default: exported when it has an intent filter. */ + private fun Element.exported(): Boolean = attr("exported").ifEmpty { null }?.toBoolean() ?: children("intent-filter").isNotEmpty() + + @Test fun exportedComponentsAreKnownAndProtected() { + for ((variant, manifest) in required()) { + val components = listOf("activity", "activity-alias", "service", "receiver", "provider").flatMap { manifest.children(it) } + val exported = components.filter { it.exported() }.associate { it.attr("name") to it } + assertEquals(setOf( + "cz.netkit.app.MainActivity", + "cz.netkit.app.tile.SignalTileService", + "cz.netkit.app.wol.widget.WolWidgetConfigActivity", + "cz.netkit.app.netstatus.NetStatusWidgetConfigActivity", + "androidx.glance.appwidget.GlanceRemoteViewsService", + "androidx.work.impl.background.systemjob.SystemJobService", + ), exported.keys, variant) + assertTrue(manifest.children("activity-alias").isEmpty(), "$variant: no activity-alias") + // Launcher only; external navigation is an explicit intent with the whitelisted target (no extra filter). + assertEquals(setOf("android.intent.action.MAIN"), exported.getValue("cz.netkit.app.MainActivity").actions(), variant) + exported.getValue("cz.netkit.app.tile.SignalTileService").let { + assertEquals("android.permission.BIND_QUICK_SETTINGS_TILE", it.attr("permission"), variant) + assertEquals(setOf("android.service.quicksettings.action.QS_TILE"), it.actions(), variant) + } + assertEquals(setOf("android.appwidget.action.APPWIDGET_CONFIGURE"), + exported.getValue("cz.netkit.app.wol.widget.WolWidgetConfigActivity").actions(), variant) + assertEquals(setOf("android.appwidget.action.APPWIDGET_CONFIGURE"), + exported.getValue("cz.netkit.app.netstatus.NetStatusWidgetConfigActivity").actions(), variant) + assertEquals("android.permission.BIND_REMOTEVIEWS", exported.getValue("androidx.glance.appwidget.GlanceRemoteViewsService").attr("permission")) + assertEquals("android.permission.BIND_JOB_SERVICE", + exported.getValue("androidx.work.impl.background.systemjob.SystemJobService").attr("permission")) + val byName = components.associateBy { it.attr("name") } + val locale = assertNotNull(byName["cz.netkit.app.settings.AppLocaleReceiver"], variant) + assertFalse(locale.exported(), variant) + assertEquals(setOf("android.intent.action.LOCALE_CHANGED"), locale.actions(), variant) + // The widget receiver gets AppWidget broadcasts from the system only (revize kolo 1, bod 1). + val receiver = assertNotNull(byName["cz.netkit.app.wol.widget.WolWidgetReceiver"], variant) + assertFalse(receiver.exported(), "$variant: widget receiver not exported") + assertEquals(setOf("android.appwidget.action.APPWIDGET_UPDATE"), receiver.actions()) + // Waking goes only through the app's own non-exported receiver (explicit broadcast, no filter). + val wake = assertNotNull(byName["cz.netkit.app.wol.widget.WolWidgetWakeReceiver"], variant) + assertFalse(wake.exported(), "$variant: wake receiver not exported") + assertTrue(wake.children("intent-filter").isEmpty(), "$variant: wake receiver has no intent filter") + // Network status widget (zadání 37): receiver from the system only, refresh only by its own explicit broadcast. + val status = assertNotNull(byName["cz.netkit.app.netstatus.NetStatusWidgetReceiver"], variant) + assertFalse(status.exported(), "$variant: status widget receiver not exported") + assertEquals(setOf("android.appwidget.action.APPWIDGET_UPDATE"), status.actions()) + val refresh = assertNotNull(byName["cz.netkit.app.netstatus.NetStatusRefreshReceiver"], variant) + assertFalse(refresh.exported(), "$variant: refresh receiver not exported") + assertTrue(refresh.children("intent-filter").isEmpty(), "$variant: refresh receiver has no intent filter") + assertFalse(assertNotNull(byName["androidx.glance.appwidget.action.ActionCallbackBroadcastReceiver"], variant).exported()) + assertNull(byName["androidx.work.impl.diagnostics.DiagnosticsReceiver"], "$variant: DiagnosticsReceiver removed") + } + } + + /** Zadání 44: USB host optional, USB permission receiver private, no USB attach filter. */ + @Test fun usbHostIsOptionalAndPermissionReceiverIsPrivate() { + for ((variant, manifest) in required()) { + val feature = manifest.children("uses-feature").single { it.attr("name") == "android.hardware.usb.host" } + assertEquals("false", feature.attr("required"), variant) + val receiver = manifest.children("receiver").single { it.attr("name") == "cz.netkit.app.ssh.ConsoleUsbPermissionReceiver" } + assertEquals("false", receiver.attr("exported"), variant) + assertTrue(receiver.children("intent-filter").isEmpty(), variant) + assertFalse("android.hardware.usb.action.USB_DEVICE_ATTACHED" in manifest.actions(), variant) + } + } + + /** The exact permission set; zadání 42 added the SSH session service trio (docs/bezpecnost.md § SSH na pozadí). */ + @Test fun noNewPermissions() { + for ((variant, manifest) in required()) { + val requested = manifest.children("uses-permission").map { it.attr("name") }.toSet() + val appId = manifest.getAttribute("package") + assertEquals(setOf("INTERNET", "ACCESS_NETWORK_STATE", "ACCESS_WIFI_STATE", "CHANGE_WIFI_STATE", "ACCESS_FINE_LOCATION", + "ACCESS_COARSE_LOCATION", "READ_PHONE_STATE", "READ_BASIC_PHONE_STATE", "USE_BIOMETRIC", + "FOREGROUND_SERVICE", "FOREGROUND_SERVICE_SPECIAL_USE", "POST_NOTIFICATIONS").map { "android.permission.$it" }.toSet() + + // Signature permission of androidx.core for ContextCompat.registerReceiver (present before zadání 36). + "$appId.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION", requested, variant) + assertFalse("android.permission.ACCESS_BACKGROUND_LOCATION" in requested) + assertFalse("android.permission.WAKE_LOCK" in requested, "$variant: no wake lock") + assertFalse("android.permission.RECEIVE_BOOT_COMPLETED" in requested, "$variant: no boot start") + } + } + + /** Every requested permission has an "added" row in the docs/bezpecnost.md §2 table and vice versa. */ + @Test fun permissionsMatchSecurityDoc() { + val doc = File(File(".").canonicalFile.parentFile, "docs/bezpecnost.md").readLines() + val start = doc.indexOfFirst { it.startsWith("## 2. ") } + val table = doc.drop(start + 1).takeWhile { !it.startsWith("## ") }.filter { it.startsWith("| `") } + val documented = table.mapNotNull { row -> + val cells = row.trim('|').split(" | ") + val state = cells.last() + if ("nepřidáno" in state || !("přidáno" in state || "vráceno" in state)) null + else Regex("`([A-Za-z0-9_.]+)`").findAll(cells.first()).map { it.groupValues[1] }.toList() + }.flatten().toSet() + for ((variant, manifest) in required()) { + val appId = manifest.getAttribute("package") + val requested = manifest.children("uses-permission").map { it.attr("name") } + .map { it.removePrefix("android.permission.").replace("$appId.", "cz.netkit.app.") }.toSet() + assertEquals(documented, requested, "$variant: manifest vs docs/bezpecnost.md §2") + } + } + + /** Zadání 42/44: the terminal session service is private, typed specialUse with its Play subtype, no filter. */ + @Test fun sshSessionServiceIsPrivateSpecialUse() { + for ((variant, manifest) in required()) { + val service = assertNotNull(manifest.children("service").singleOrNull { it.attr("name") == "cz.netkit.app.ssh.SshSessionService" }, variant) + assertFalse(service.exported(), "$variant: not exported") + assertEquals("false", service.attr("exported"), "$variant: explicit exported=false") + assertTrue(service.children("intent-filter").isEmpty(), "$variant: no intent filter") + assertEquals("specialUse", service.attr("foregroundServiceType"), variant) + val subtype = service.children("property").singleOrNull { it.attr("name") == "android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE" } + // One service for every terminal transport (zadání 42 + 44): the Play subtype names all of them. + val value = assertNotNull(subtype, variant).attr("value") + for (transport in listOf("SSH", "SFTP", "Telnet", "USB serial")) assertTrue(transport in value, "$variant: subtype names $transport") + // Only the app's own services may run in the foreground; WorkManager's stays unused (no ForegroundInfo). + val typed = manifest.children("service").filter { it.attr("foregroundServiceType").isNotEmpty() }.map { it.attr("name") } + assertEquals(listOf("cz.netkit.app.ssh.SshSessionService"), typed, variant) + } + } + + /** Zadání 46: predictive back opt-in and the AGP-generated per-app language list (cs, en) in every variant. */ + @Test fun predictiveBackAndLocaleConfig() { + for ((variant, manifest) in required()) { + val application = manifest.children("application").single() + assertEquals("true", application.attr("enableOnBackInvokedCallback"), variant) + assertEquals("@xml/_generated_res_locale_config", application.attr("localeConfig"), variant) + } + val generated = File(File(".").canonicalFile, "build/generated/res/localeConfig/debug/xml/_generated_res_locale_config.xml") + assertTrue(generated.isFile, "generated LocaleConfig at $generated") + val config = parse(generated) + assertEquals("cs", config.attr("defaultLocale")) + assertEquals(listOf("cs", "en"), config.children("locale").map { it.attr("name") }) + } + + @Test fun sourceManifestRemovesWorkManagerExtras() { + val source = parse(File(File(".").canonicalFile, "src/main/AndroidManifest.xml")) + val removed = source.children("uses-permission").filter { it.getAttributeNS(tools, "node") == "remove" }.map { it.attr("name") }.toSet() + // Zadání 42: FOREGROUND_SERVICE is the app's own again (SSH session service); the legacy fingerprint permission is removed at minSdk 29. + assertEquals(setOf("WAKE_LOCK", "RECEIVE_BOOT_COMPLETED", "USE_FINGERPRINT").map { "android.permission.$it" }.toSet(), removed) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/nav/ShortcutResourcesTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/nav/ShortcutResourcesTest.kt new file mode 100644 index 0000000..33edf5b --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/nav/ShortcutResourcesTest.kt @@ -0,0 +1,74 @@ +package cz.netkit.app.nav + +import cz.netkit.shared.nav.APP_TARGET_ACTION +import cz.netkit.shared.nav.APP_TARGET_EXTRA +import cz.netkit.shared.nav.AppTarget +import cz.netkit.shared.nav.AppLanTool +import cz.netkit.shared.nav.parseAppTarget +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.w3c.dom.Element +import kotlin.test.* + +/** Static shortcuts (zadání 36 §2.2): whitelist targets only, both languages, dev copy in sync. */ +class ShortcutResourcesTest { + private val module = File(".").canonicalFile + private val android = "http://schemas.android.com/apk/res/android" + + private fun elements(file: File, tag: String): List { + val factory = DocumentBuilderFactory.newInstance().apply { + isNamespaceAware = true + setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) + } + val nodes = factory.newDocumentBuilder().parse(file).getElementsByTagName(tag) + return (0 until nodes.length).map { nodes.item(it) as Element } + } + + private fun shortcuts(variant: String) = elements(File(module, "src/$variant/res/xml/shortcuts.xml"), "shortcut") + + @Test fun staticShortcutsOpenOnlyWhitelistedTargets() { + val main = shortcuts("main") + assertTrue(main.size <= 4, "launchers show at most 4 static + dynamic shortcuts") + val targets = main.map { shortcut -> + val intents = shortcut.getElementsByTagName("intent") + assertEquals(1, intents.length) + val intent = intents.item(0) as Element + assertEquals(APP_TARGET_ACTION, intent.getAttributeNS(android, "action")) + assertEquals("cz.netkit.app", intent.getAttributeNS(android, "targetPackage")) + assertEquals("cz.netkit.app.MainActivity", intent.getAttributeNS(android, "targetClass")) + val extras = intent.getElementsByTagName("extra") + assertEquals(1, extras.length, "a shortcut intent carries only the target") + val extra = extras.item(0) as Element + assertEquals(APP_TARGET_EXTRA, extra.getAttributeNS(android, "name")) + assertNull(intent.getAttributeNS(android, "data").ifEmpty { null }, "no data URI") + assertNotNull(parseAppTarget(extra.getAttributeNS(android, "value"))) + } + assertEquals(listOf(AppTarget.Signal, AppTarget.Spectrum, AppTarget.LanTools(AppLanTool.PING), AppTarget.LanTools(AppLanTool.SUBNET)), targets) + } + + @Test fun everyWhitelistedLanToolExistsInTheApp() { + // MainActivity maps the target with LanTool.valueOf; a missing tool would crash navigation. + AppLanTool.entries.forEach { assertEquals(it.name, cz.netkit.app.lan.LanTool.valueOf(it.name).name) } + } + + @Test fun devCopyDiffersOnlyInPackage() { + val main = File(module, "src/main/res/xml/shortcuts.xml").readText().substringAfter(" + val text = assertNotNull(strings[name], "$folder/$name") + if (name.endsWith("_short")) assertTrue(text.length <= 10, "$folder/$name: $text") + assertTrue(text.length <= 25, "$folder/$name: $text") + } + // Quick Settings tile label: at most 18 characters (Android tile label guidance). + assertTrue(assertNotNull(strings["tile_signal_label"]).length <= 18, folder) + } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/netstatus/NetStatusWidgetTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/netstatus/NetStatusWidgetTest.kt new file mode 100644 index 0000000..9b1ef24 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/netstatus/NetStatusWidgetTest.kt @@ -0,0 +1,89 @@ +package cz.netkit.app.netstatus + +import androidx.compose.ui.unit.DpSize +import androidx.compose.ui.unit.dp +import cz.netkit.shared.netstatus.NetStatusData +import cz.netkit.shared.netstatus.NetStatusLabel +import cz.netkit.shared.netstatus.NetStatusRadioSource +import cz.netkit.shared.netstatus.NetStatusSettings +import cz.netkit.shared.netstatus.NetStatusWidgetSize +import cz.netkit.shared.netstatus.netStatusRadio +import java.io.File +import java.nio.file.Files +import javax.xml.parsers.DocumentBuilderFactory +import kotlinx.coroutines.runBlocking +import kotlin.test.* + +/** + * Zadání 37 on the JVM: the snapshot file, the widget sizes and the static guarantees of the refresh path + * (AC-002: no location flag, no network callback, no socket, HTTP or DNS API in the widget code; the + * instrumentation phase `netstatus-widget` checks the same at run time on the emulator). + */ +class NetStatusWidgetTest { + private val t0 = 1_800_000_000_000L + private val sources = File(File(".").canonicalFile, "src/main/kotlin/cz/netkit/app/netstatus") + + @Test fun fileStoreRoundTripAndAtomicReplace() = runBlocking { + val dir = Files.createTempDirectory("netstatus").toFile() + try { + val file = File(dir, NET_STATUS_FILE) + val store = FileNetStatusStore(file) + assertEquals(NetStatusData(), store.read(), "missing file = empty, options off") + val data = NetStatusData(settings = NetStatusSettings(showSsid = true), + radio = netStatusRadio(t0, 2437, -61, 144, 144, NetStatusRadioSource.FOREGROUND), ssid = NetStatusLabel(t0, "TestNet")) + store.update { data } + assertEquals(data, FileNetStatusStore(file).read()) + assertEquals(data, store.data.value) + assertFalse(File(dir, "$NET_STATUS_FILE.tmp").exists()) + } finally { dir.deleteRecursively() } + } + + @Test fun corruptFileReadsAsEmptyAndIsReplacedOnWrite() = runBlocking { + val dir = Files.createTempDirectory("netstatus").toFile() + try { + val file = File(dir, NET_STATUS_FILE).apply { writeText("""{"schema":1,"ssid":{"atMs":1,"value":""}}""") } + val store = FileNetStatusStore(file) + assertEquals(NetStatusData(), store.read()) + store.update { it.copy(settings = NetStatusSettings(showPublicIp = true)) } + assertEquals(NetStatusSettings(showPublicIp = true), FileNetStatusStore(file).read().settings) + } finally { dir.deleteRecursively() } + } + + @Test fun responsiveSizes() { + assertEquals(NetStatusWidgetSize.SMALL, netStatusSize(NET_STATUS_SMALL)) + assertEquals(NetStatusWidgetSize.MEDIUM, netStatusSize(NET_STATUS_MEDIUM)) + assertEquals(NetStatusWidgetSize.SMALL, netStatusSize(DpSize(400.dp, 60.dp)), "wide but one row stays small") + assertTrue(NET_STATUS_SMALL.width < NET_STATUS_MEDIUM.width && NET_STATUS_SMALL.height < NET_STATUS_MEDIUM.height) + } + + @Test fun chronometerBaseShowsTheAge() { + // Measured 12 min ago: the chronometer starts at elapsed − 12 min and counts on by itself. + assertEquals(1_000_000L - 720_000, netStatusChronometerBase(t0 - 720_000, t0, 1_000_000)) + assertEquals(1_000_000L, netStatusChronometerBase(t0 + 5_000, t0, 1_000_000), "never in the future") + } + + @Test fun refreshPathHasNoLocationFlagNoCallbackAndNoNetworkApi() { + val files = sources.listFiles { f -> f.extension == "kt" }.orEmpty() + assertTrue(files.map { it.name }.containsAll(listOf("NetStatusService.kt", "NetStatusWidget.kt", "NetStatusWidgetConfigActivity.kt"))) + val forbidden = listOf("FLAG_INCLUDE_LOCATION_INFO", "registerNetworkCallback", "requestNetwork", "registerDefaultNetworkCallback", + "Socket", "okhttp3", "OkHttp", "URL(", "HttpURLConnection", "openConnection", "DnsResolver", "InetAddress", "getByName", + "WorkManager", "PeriodicWork", "AlarmManager", "ACCESS_BACKGROUND_LOCATION", "startScan", "getScanResults", "scanResults") + for (file in files) { + val code = file.readLines().filterNot { it.trimStart().startsWith("*") || it.trimStart().startsWith("//") || it.trimStart().startsWith("/*") } + .joinToString("\n") + for (token in forbidden) assertFalse(token in code, "${file.name} uses $token") + } + // The only Wi-Fi reads of the refresh: one-shot capabilities (API 31+) or connectionInfo (API 29–30), radio fields only. + val reader = File(sources, "NetStatusService.kt").readText().substringAfter("internal class AndroidNetStatusRadioReader") + assertFalse(".ssid" in reader || ".bssid" in reader || "macAddress" in reader, "the reader never touches SSID/BSSID") + } + + @Test fun widgetInfoHasNoPeriodicUpdate() { + val info = File(File(".").canonicalFile, "src/main/res/xml/netstatus_widget_info.xml") + val root = DocumentBuilderFactory.newInstance().apply { isNamespaceAware = true }.newDocumentBuilder().parse(info).documentElement + val android = "http://schemas.android.com/apk/res/android" + assertEquals("0", root.getAttributeNS(android, "updatePeriodMillis")) + assertEquals("cz.netkit.app.netstatus.NetStatusWidgetConfigActivity", root.getAttributeNS(android, "configure")) + assertEquals(setOf("home_screen", "keyguard"), root.getAttributeNS(android, "widgetCategory").split('|').toSet()) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/overview/DiagnosticReportInputTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/overview/DiagnosticReportInputTest.kt new file mode 100644 index 0000000..812057d --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/overview/DiagnosticReportInputTest.kt @@ -0,0 +1,121 @@ +package cz.netkit.app.overview + +import cz.netkit.app.speed.SpeedUiState +import cz.netkit.app.speed.shareableRecord +import cz.netkit.app.wifi.live.LiveLatency +import cz.netkit.app.wifi.live.LiveLink +import cz.netkit.app.wifi.live.LiveWifiStandard +import cz.netkit.app.wifi.live.PublicIpUiState +import cz.netkit.app.wifi.live.WifiLiveState +import cz.netkit.shared.net.NetKind +import cz.netkit.shared.publicip.IpFamily +import cz.netkit.shared.publicip.PublicAddress +import cz.netkit.shared.publicip.PublicIpInfo +import cz.netkit.shared.report.buildDiagnosticReport +import cz.netkit.shared.speed.SpeedEngine +import cz.netkit.shared.speed.SpeedRecord +import cz.netkit.shared.wifi.LiveSample +import cz.netkit.shared.wifi.LiveSeries +import cz.netkit.shared.wifi.WifiBand +import java.io.File +import kotlin.test.* + +/** Zadání 47 §1: what the Overview hands to the report, and what it must never touch. */ +class DiagnosticReportInputTest { + private val now = 1_000_000L + private fun series(vararg points: Pair) = LiveSeries(points.map { (t, v) -> LiveSample(t, v) }) + private val link = LiveLink(now, "HomeNet", "aa:bb:cc:00:11:22", -60, 866, 780, 5500, 100, WifiBand.GHZ_5, "192.168.1.50", + "192.168.1.1", LiveWifiStandard.AX) + private val live = WifiLiveState( + link = link, + gatewayLatency = LiveLatency("192.168.1.1", series(now - 61_000 to 50.0, now - 30_000 to 2.0, now - 1_000 to null, now to 4.0)), + internetLatency = LiveLatency("1.1.1.1", series(now - 59_000 to 10.0, now to 12.0)), + publicIp = PublicIpUiState(enabled = true, settingLoaded = true, + info = PublicIpInfo(PublicAddress(IpFamily.V4, "203.0.113.7"), null, 64500, null, "Example", null, null, 0)), + ) + private val wifiNet = ReportNetworkFacts(NetKind.WIFI, false, "wlan0", "192.168.1.50", null, "192.168.1.1", + listOf("192.168.1.1"), false, null, "192.168.1.1", 1500) + private val records = listOf( + SpeedRecord(3_000, SpeedEngine.IPERF3, "192.0.2.10:5201", downloadMbps = 900.0), + SpeedRecord(2_000, SpeedEngine.NDT7, "M-Lab", downloadMbps = 300.0), + SpeedRecord(1_000, SpeedEngine.LIBRESPEED, "Old", downloadMbps = 100.0), + SpeedRecord(4_000, SpeedEngine.LIBRESPEED, "New", downloadMbps = 200.0), + ) + + @Test fun latencyCoversTheLastMinuteOnly() { + val input = diagnosticReportInput(live, wifiNet, records, 80, "2.0.0", 5_000, now) + assertEquals(listOf(2.0, null, 4.0), input.gatewayLatency!!.samples, "the 61 s old sample is outside the window") + assertEquals(listOf(10.0, 12.0), input.internetLatency!!.samples) + assertEquals(80, input.wifi!!.widthMhz) + assertEquals("802.11ax (Wi-Fi 6)", input.wifi!!.standard) + assertEquals(1500, input.mtu) + } + + @Test fun newestRecordPerEngineGroup() { + val input = diagnosticReportInput(live, wifiNet, records, null, "2.0.0", 5_000, now) + assertEquals("New", input.lastSpeedTest!!.serverName) + assertEquals(SpeedEngine.IPERF3, input.lastIperf3!!.engine) + } + + @Test fun mobileDataHasNoWifiAndNoGateway() { + val cellular = wifiNet.copy(kind = NetKind.CELLULAR, interfaceName = "rmnet0", gateway = null) + val input = diagnosticReportInput(live, cellular, emptyList(), null, "2.0.0", 5_000, now) + assertNull(input.wifi) + assertNull(input.gatewayLatency) + assertNull(input.lastSpeedTest) + } + + /** Revize kolo 1 (P2): with mobile data or a VPN as default, Wi-Fi values do not fill missing ones. */ + @Test fun wifiFallbackOnlyWhenWifiIsTheReportedNetwork() { + for (kind in listOf(NetKind.CELLULAR, NetKind.VPN)) { + val other = wifiNet.copy(kind = kind, ipv4 = null, gateway = null) + val input = diagnosticReportInput(live, other, emptyList(), null, "2.0.0", 5_000, now) + assertNull(input.ipv4, "$kind") + assertNull(input.gateway, "$kind") + } + val wifiMissing = diagnosticReportInput(live, wifiNet.copy(ipv4 = null, gateway = null), emptyList(), null, "2.0.0", 5_000, now) + assertEquals("192.168.1.50", wifiMissing.ipv4) + assertEquals("192.168.1.1", wifiMissing.gateway) + val unknown = diagnosticReportInput(live, null, emptyList(), null, "2.0.0", 5_000, now) + assertNull(unknown.ipv4, "no reported network: nothing is guessed") + } + + @Test fun publicIpOnlyWhenLookupEnabledAndStillOptIn() { + val off = diagnosticReportInput(live.copy(publicIp = live.publicIp.copy(enabled = false)), wifiNet, emptyList(), null, "2.0.0", 5_000, now) + assertNull(off.publicIp) + val on = diagnosticReportInput(live, wifiNet, emptyList(), null, "2.0.0", 5_000, now) + assertEquals("203.0.113.7", on.publicIp!!.ipv4) + assertNull(buildDiagnosticReport(on).publicIp, "default options still leave it out") + } + + @Test fun standardNames() { + assertEquals("802.11ax (Wi-Fi 6E)", standardText(LiveWifiStandard.AX, WifiBand.GHZ_6)) + assertEquals("802.11be (Wi-Fi 7)", standardText(LiveWifiStandard.BE, WifiBand.GHZ_5)) + } + + @Test fun shareableRecordIsTheStoredRecordOfTheShownRun() { + val record = SpeedRecord(7_000, SpeedEngine.LIBRESPEED, "Praha", downloadMbps = 1.0) + assertEquals(record, shareableRecord(SpeedUiState(startedAtMs = 7_000, history = listOf(record)))) + assertNull(shareableRecord(SpeedUiState(startedAtMs = 8_000, history = listOf(record))), "a run that stored nothing") + assertNull(shareableRecord(SpeedUiState(history = listOf(record)))) + } + + /** + * D31 / zadání 53: the report sources must not read the cell detail, the mobile card state or + * any secret store. A source guard, because the Kotlin types alone would not stop a later edit + * from adding such a read to [diagnosticReportInput]. + */ + @Test fun reportSourcesDoNotReadCellDetailOrSecrets() { + val module = File(".").canonicalFile + val sources = listOf("overview/DiagnosticReportViewModel.kt", "overview/DiagnosticReportDialog.kt", "ui/ShareActions.kt", + "speed/SpeedShare.kt", "lan/DevicesExport.kt").map { File(module, "src/main/kotlin/cz/netkit/app/$it") } + val forbidden = listOf("CellDetail", "cellDetail", "CellularState", "CellularMonitor", ".cellular", "CellInfo", "SecureOn", "secureOn", "SshSecret", "secretRef", + "Keystore", "password", "privateKey", "WolSecureOnStorage") + sources.forEach { file -> + assertTrue(file.isFile, "missing $file") + val code = file.readLines().filterNot { it.trimStart().startsWith("*") || it.trimStart().startsWith("//") || it.trimStart().startsWith("/**") } + .joinToString("\n") + forbidden.forEach { token -> assertFalse(token in code, "${file.name} references $token") } + } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/settings/CzechLocaleResourcesTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/settings/CzechLocaleResourcesTest.kt new file mode 100644 index 0000000..1b7fecd --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/settings/CzechLocaleResourcesTest.kt @@ -0,0 +1,59 @@ +package cz.netkit.app.settings + +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.w3c.dom.Element +import kotlin.test.* + +/** + * Czech texts live in the unqualified values/ (zadání 46). With a locale list ([cs,en_US]: app language + * cs on an English system) Android 15 picks values-en for every string without a cs-qualified entry, so + * the build generates values-cs from values/ (generateCzechLocaleStrings in androidApp/build.gradle.kts). + * This checks the generated copy of the debug variant against the sources. + */ +class CzechLocaleResourcesTest { + private val module = File(".").canonicalFile + private val kinds = setOf("string", "plurals", "string-array") + + private fun entries(file: File): List { + val factory = DocumentBuilderFactory.newInstance().apply { + isNamespaceAware = true + setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) + } + val nodes = factory.newDocumentBuilder().parse(file).documentElement.childNodes + return (0 until nodes.length).mapNotNull { nodes.item(it) as? Element }.filter { it.tagName in kinds } + } + + /** kind:name → normalized text (plural items and array items keep their order). */ + private fun Element.key() = "$tagName:${getAttribute("name")}" + private fun Element.value() = textContent.trim().replace(Regex("\\s+"), " ") + + private fun sources(dir: String) = File(module, "src/$dir/res/values").listFiles { f -> f.extension == "xml" }.orEmpty() + .sortedBy { it.name }.flatMap(::entries) + + private val generated by lazy { + val file = File(module, "build/generated/res/generateDebugCzechLocaleStrings/values-cs/netkit_cs_strings.xml") + assertTrue(file.isFile, "generated values-cs at $file") + entries(file) + } + + @Test fun everyTranslatableCzechTextHasACsQualifiedCopy() { + val translatable = sources("main").filter { it.getAttribute("translatable") != "false" } + assertTrue(translatable.size > 1000, "sanity: ${translatable.size} translatable entries in values/") + assertEquals(translatable.associate { it.key() to it.value() }, generated.associate { it.key() to it.value() }) + assertEquals(generated.size, generated.map { it.key() }.toSet().size, "no duplicates") + } + + @Test fun nonTranslatableEntriesAreNotCopied() { + assertTrue(generated.none { it.getAttribute("translatable") == "false" }) + assertTrue(generated.none { it.getAttribute("name") == "app_name" }, "app_name stays overridable by the dev build") + } + + /** A cs copy of a string the dev build type overrides would win over the override in Czech. */ + @Test fun devOverridesOnlyNonTranslatableEntries() { + val copied = generated.map { it.getAttribute("name") }.toSet() + val overridden = sources("dev").map { it.getAttribute("name") } + assertTrue(overridden.isNotEmpty()) + assertTrue(overridden.none { it in copied }, "dev overrides copied names: ${overridden.filter { it in copied }}") + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/settings/OwnedOperationTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/settings/OwnedOperationTest.kt new file mode 100644 index 0000000..f8e92ca --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/settings/OwnedOperationTest.kt @@ -0,0 +1,75 @@ +package cz.netkit.app.settings + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineStart +import kotlinx.coroutines.Job +import kotlinx.coroutines.launch +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlin.test.* + +/** + * Revize kolo 1 (zadání 46): a Settings action started from a composition scope must finish its + * whole operation (store write, then state change) when the caller is cancelled while the write is + * pending; only the owner (ViewModel scope) may cancel it. + */ +class OwnedOperationTest { + @Test fun cancelledCallerDoesNotCutTheTail() { + val dispatcher = StandardTestDispatcher() + val owner = TestScope(dispatcher) + val callerScope = TestScope(dispatcher) + val write = CompletableDeferred() + val steps = mutableListOf() + var callerFailure: Throwable? = null + val caller = callerScope.launch(start = CoroutineStart.UNDISPATCHED) { + try { + awaitInOwner(owner) { + steps += "state" + val written = write.await() + steps += "after-write:$written" + written + } + } catch (cancel: CancellationException) { + callerFailure = cancel + throw cancel + } + } + dispatcher.scheduler.runCurrent() + assertEquals(listOf("state"), steps) + caller.cancel() + dispatcher.scheduler.runCurrent() + assertTrue(caller.isCancelled) + assertIs(callerFailure) + // The store answers after the caller is gone: the rest of the operation still runs. + write.complete(true) + dispatcher.scheduler.runCurrent() + assertEquals(listOf("state", "after-write:true"), steps) + } + + @Test fun ownerCancellationStopsTheOperation() { + val dispatcher = StandardTestDispatcher() + val owner = TestScope(dispatcher) + val write = CompletableDeferred() + var finished = false + var result: Result? = null + TestScope(dispatcher).launch { + result = runCatching { awaitInOwner(owner) { write.await().also { finished = true } } } + } + dispatcher.scheduler.runCurrent() + owner.coroutineContext[Job]!!.cancel() + write.complete(true) + dispatcher.scheduler.runCurrent() + assertFalse(finished) + assertIs(result?.exceptionOrNull()) + } + + @Test fun resultReachesALiveCaller() { + val dispatcher = StandardTestDispatcher() + val owner = TestScope(dispatcher) + var result: Boolean? = null + TestScope(dispatcher).launch { result = awaitInOwner(owner) { false } } + dispatcher.scheduler.runCurrent() + assertEquals(false, result) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/settings/SettingsStoreTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/settings/SettingsStoreTest.kt new file mode 100644 index 0000000..1dfa7c6 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/settings/SettingsStoreTest.kt @@ -0,0 +1,59 @@ +package cz.netkit.app.settings + +import androidx.datastore.core.CorruptionException +import androidx.datastore.core.DataStoreFactory +import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler +import cz.netkit.shared.settings.APP_SETTINGS_MAX_BYTES +import cz.netkit.shared.settings.AppSettings +import cz.netkit.shared.settings.ThemeMode +import java.nio.file.Files +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.flow.first +import kotlinx.coroutines.job +import kotlinx.coroutines.test.runTest + +class SettingsStoreTest { + @Test fun corruptOrOversizedFilesFallBackToDefaults() = runTest { + val directory = Files.createTempDirectory("netkit-settings-corrupt").toFile() + val owner = CoroutineScope(SupervisorJob() + Dispatchers.IO) + try { + val bad = listOf("", "{", """{"schema":2,"theme":"DARK"}""", """{"schema":1,"theme":"SEPIA"}""", + """{"schema":1,"pad":"""" + "a".repeat(APP_SETTINGS_MAX_BYTES + 10) + "\"}") + for ((index, content) in bad.withIndex()) { + val file = directory.resolve("settings-$index.json") + file.writeText(content) + file.inputStream().use { input -> assertFailsWith { AppSettingsSerializer.readFrom(input) } } + val store = DataStoreFactory.create(serializer = AppSettingsSerializer, + corruptionHandler = ReplaceFileCorruptionHandler { AppSettings() }, scope = owner) { file } + assertEquals(AppSettings(), store.data.first()) + } + } finally { + owner.coroutineContext.job.cancelAndJoin() + directory.deleteRecursively() + } + } + + @Test fun changesSurviveReopening() = runTest { + val directory = Files.createTempDirectory("netkit-settings").toFile() + val file = directory.resolve("settings.json") + var owner = CoroutineScope(SupervisorJob() + Dispatchers.IO) + fun open() = DataStoreFactory.create(serializer = AppSettingsSerializer, scope = owner) { file } + try { + val store = open() + assertEquals(AppSettings(), store.data.first()) + store.updateData { it.copy(theme = ThemeMode.DARK, keepScreenOn = false) } + owner.coroutineContext.job.cancelAndJoin() + owner = CoroutineScope(SupervisorJob() + Dispatchers.IO) + assertEquals(AppSettings(theme = ThemeMode.DARK, keepScreenOn = false), open().data.first()) + } finally { + owner.coroutineContext.job.cancelAndJoin() + directory.deleteRecursively() + } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/speed/Iperf3ClientTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/speed/Iperf3ClientTest.kt new file mode 100644 index 0000000..4719e4b --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/speed/Iperf3ClientTest.kt @@ -0,0 +1,312 @@ +package cz.netkit.app.speed + +import cz.netkit.shared.speed.ByteSample +import cz.netkit.shared.speed.Iperf3Protocol +import cz.netkit.shared.speed.Iperf3Options +import cz.netkit.shared.speed.Iperf3ServerFailure +import cz.netkit.shared.speed.Iperf3State +import java.io.BufferedReader +import java.io.DataInputStream +import java.io.EOFException +import java.io.File +import java.io.IOException +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import java.net.SocketTimeoutException +import java.nio.ByteBuffer +import java.nio.channels.ReadableByteChannel +import java.util.concurrent.TimeUnit +import kotlin.test.* +import kotlinx.coroutines.* +import org.testng.SkipException + +class Iperf3ClientTest { + private val loopback = InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)) + + private suspend fun withFixture(block: suspend (InetSocketAddress, BufferedReader) -> Unit) { + val root = generateSequence(File(".").absoluteFile) { it.parentFile } + .map { File(it, "tools/testsrv/iperf3_fixture.py") }.first { it.isFile } + val server = ProcessBuilder("python3", "-I", root.absolutePath, "--port", "0") + .redirectError(ProcessBuilder.Redirect.INHERIT).start() + try { + val output = server.inputStream.bufferedReader() + val port = output.readLine()?.toInt() ?: error("fixture did not start") + block(InetSocketAddress(loopback, port), output) + assertTrue(server.waitFor(5, TimeUnit.SECONDS), "fixture did not finish") + assertEquals(0, server.exitValue()) + } finally { + server.destroyForcibly() + server.waitFor(5, TimeUnit.SECONDS) + } + } + + private suspend fun direction(target: InetSocketAddress, reverse: Boolean): Iperf3Measurement { + val options = Iperf3Options(streams = 2, seconds = 3, reverse = reverse, bitsPerSecond = 2_000_000) + val seen = mutableListOf() + var bound = 0 + val result = Iperf3Client { bound++ }.measure(target, options) { seen.add(it) } + assertEquals(3, bound) + assertEquals(2, result.workingStreams) + if (reverse) assertEquals(seen.last().bytes, result.summary.totalBytes) + assertTrue(seen.last().elapsedMs in 3000L..5000L) + assertTrue(seen.size >= 2 && seen.zipWithNext().all { (a,b) -> b.elapsedMs > a.elapsedMs && b.bytes > a.bytes }) + assertTrue(seen.last().bytes in 1_100_000L..1_850_000L, "two paced streams: ${seen.last()}") + return result + } + + @Test fun upload() = runBlocking { + withFixture { target, output -> + val result = direction(target, false) + assertNull(result.retransmits) + val (received, seconds) = output.readLine().split(' ') + assertEquals(received.toLong(), result.summary.totalBytes) + assertEquals(received.toDouble() * 8 / seconds.toDouble() / 1e6, result.summary.mbps, 1e-9) + } + } + + @Test fun reverse() = runBlocking { withFixture { target, _ -> assertEquals(3L, direction(target, true).retransmits) } } + + private suspend fun cancelTransfer(target: InetSocketAddress, options: Iperf3Options) = coroutineScope { + val halfway = CompletableDeferred() + val test = launch { + Iperf3Client {}.measure(target, options) { point -> + if (point.elapsedMs >= options.seconds * 500L) halfway.complete(Unit) + } + } + withTimeout(options.seconds * 500L + 5_000) { halfway.await() } + withTimeout(2_000) { test.cancelAndJoin() } + assertTrue(test.isCancelled) + } + + @Test fun stopInTransferSendsTerminate() = runBlocking { + withFixture { target, _ -> cancelTransfer(target, Iperf3Options(seconds = 4, bitsPerSecond = 100_000)) } + } + + private suspend fun withPeer(peer: (Socket, ServerSocket) -> Unit, client: suspend (InetSocketAddress) -> T): T = + coroutineScope { + ServerSocket(0, 9, loopback).use { listener -> + listener.soTimeout = 5_000 + val server = launch(Dispatchers.IO) { + listener.accept().use { control -> + control.soTimeout = 15_000 + DataInputStream(control.getInputStream()).readFully(ByteArray(37)) + peer(control, listener) + } + } + client(InetSocketAddress(loopback, listener.localPort)).also { server.join() } + } + } + + private suspend fun controlFailure(peer: (Socket, ServerSocket) -> Unit) = withPeer(peer) { target -> + assertFailsWith { Iperf3Client {}.measure(target, Iperf3Options(), {}) } + } + + private fun startPeer(control: Socket, listener: ServerSocket, streams: Int, run: (List) -> Unit) { + val output = control.getOutputStream() + val input = DataInputStream(control.getInputStream()) + output.write(9) + input.readFully(ByteArray(input.readInt())) + output.write(10) + val data = mutableListOf() + try { + repeat(streams) { + val stream = listener.accept() + data.add(stream) + stream.soTimeout = 5_000 + DataInputStream(stream.getInputStream()).readFully(ByteArray(37)) + } + output.write(byteArrayOf(1, 2)) + run(data) + } finally { + data.forEach { it.close() } + } + } + + @Test fun minimumRateInForm() { + val form = Iperf3Form(host = "127.0.0.1", seconds = "3", reverse = true) + for (rate in listOf("0.01", "0,01")) { + val options = assertNotNull(form.copy(rateMbps = rate).options) + assertEquals(10_000L, options.bitsPerSecond) + assertEquals(7_423L, options.payloadLimitBytes) + } + for (rate in listOf("0.000001", "0,009999", "-1", "abc", "1000000.1")) { + assertNull(form.copy(rateMbps = rate).options, rate) + } + for (rate in listOf("", "0")) assertEquals(0L, form.copy(rateMbps = rate).options?.bitsPerSecond) + } + + @Test fun shortReverseAllowsInitialBlockAnd300msControlRtt() = runBlocking { + val options = Iperf3Options(streams = 2, seconds = 3, reverse = true, bitsPerSecond = 10_000_000) + val budget = Iperf3ReceiveBudget(options.payloadLimitBytes) + // Each stream sends one block at startup and another 125,000 B every 100 ms. + val block = ByteBuffer.allocate(options.blockBytes) + repeat(options.streams * (1 + options.seconds * 10)) { + assertEquals(125_000, budget.read(block) { it.remaining() }) + } + // Model the extra RTT in virtual time. EXCHANGE_RESULTS arrives after three more blocks per stream. + val pending = IntArray(options.streams) { 3 * options.blockBytes } + val streams = pending.indices.map { i -> + channel { dst -> minOf(pending[i], dst.remaining()).also { pending[i] -= it } } + } + val control = channel { dst -> + if (pending.all { it == 0 }) { dst.put(Iperf3State.EXCHANGE_RESULTS.wire.toByte()); 1 } else 0 + } + val state = Iperf3Client {}.drainUntilState(control, streams, budget) + assertEquals(Iperf3State.EXCHANGE_RESULTS.wire.toByte(), state) + } + + @Test fun ignoringReverseLimitSendsTerminateDuringTransferAndDrain() = runBlocking { + val options = Iperf3Options(streams = 2, seconds = 3, reverse = true, bitsPerSecond = 10_000) + for (duringDrain in listOf(false, true)) { + withPeer({ control, listener -> + startPeer(control, listener, options.streams) { streams -> + // 4.3 seconds of data plus two 1 KiB blocks per stream. + streams.forEach { it.getOutputStream().write(ByteArray(7_423)) } + if (duringDrain) assertEquals(4, control.getInputStream().read()) + streams.last().getOutputStream().write(1) + assertEquals(12, control.getInputStream().read()) + } + }) { target -> + val error = assertFailsWith { Iperf3Client {}.measure(target, options, {}) } + assertEquals(SpeedFailureKind.IPERF_LIMIT_EXCEEDED, error.kind) + } + } + } + + @Test fun reverseBudgetBoundsEachReadAndDetectsOneExtraByte() { + val budget = Iperf3ReceiveBudget(150) + val buffer = ByteBuffer.allocate(128) + assertEquals(128, budget.read(buffer) { it.remaining() }) + assertEquals(22, budget.read(buffer) { assertEquals(23, it.remaining()); 22 }) + val failure = assertFailsWith { + budget.read(buffer) { assertEquals(1, it.remaining()); 1 } + } + assertEquals(SpeedFailureKind.IPERF_LIMIT_EXCEEDED, failure.kind) + } + + private fun channel(readInto: (ByteBuffer) -> Int) = object : ReadableByteChannel { + override fun read(dst: ByteBuffer) = readInto(dst) + override fun isOpen() = true + override fun close() {} + } + + @Test fun drainDropsBrokenStreamAndCapsUnpacedReadsWhileWaitingForControl() = runBlocking { + var brokenReads = 0 + val broken = channel { brokenReads++; throw IOException("connection reset") } + var discarded = 0 + val data = channel { buffer -> buffer.remaining().also { discarded += it } } + var polls = 0 + val control = channel { buffer -> + if (++polls > 150) { buffer.put(13); 1 } else 0 + } + val state = Iperf3Client {}.drainUntilState(control, listOf(broken, data), Iperf3ReceiveBudget(null)) + assertEquals(13.toByte(), state) + assertEquals(1, brokenReads) + assertEquals(16 * 1024 * 1024, discarded) + } + + @Test fun drainUsesOnlyTheRemainingReverseBudget() = runBlocking { + val budget = Iperf3ReceiveBudget(3300) + val buffer = ByteBuffer.allocate(3000) + budget.read(buffer) { it.remaining() } // Payload already counted during the measurement. + var discarded = 0 + val ignoringLimit = channel { dst -> dst.remaining().also { discarded += it } } + val failure = assertFailsWith { + Iperf3Client {}.drainUntilState(channel { 0 }, listOf(ignoringLimit), budget) + } + assertEquals(301, discarded) + assertEquals(SpeedFailureKind.IPERF_LIMIT_EXCEEDED, failure.kind) + } + + @Test fun lowRateUploadFeedsReceiverEarlyAndFallsBackToClientSummary() = runBlocking { + val options = Iperf3Options(seconds = 3, bitsPerSecond = 100_000) + withPeer({ control, listener -> + startPeer(control, listener, 1) { streams -> + // A receiver waiting for a full negotiated block must see data in the first second. + val started = System.nanoTime() + streams.single().soTimeout = 1_000 + DataInputStream(streams.single().getInputStream()).readFully(ByteArray(options.blockBytes)) + assertTrue(System.nanoTime() - started < TimeUnit.SECONDS.toNanos(1)) + val input = DataInputStream(control.getInputStream()) + assertEquals(4, input.read()) + val output = control.getOutputStream() + output.write(13) + input.readFully(ByteArray(input.readInt())) + val missingTime = Iperf3Protocol.decode("""{"streams":[{"id":1,"bytes":42}]}""".encodeToByteArray()) + output.write(Iperf3Protocol.frame(missingTime) + 14.toByte()) + assertEquals(16, input.read()) + } + }) { target -> + val samples = mutableListOf() + val result = Iperf3Client {}.measure(target, options) { samples.add(it) } + assertTrue(samples.first().bytes > 0) + assertEquals(samples.last().bytes, result.summary.totalBytes) + assertEquals(samples.last().elapsedMs, result.summary.measuredMs) + assertEquals(1, result.workingStreams) + } + } + + @Test fun incompleteServerErrorIsPreservedBeforeAndDuringTransfer() = runBlocking { + for (inTransfer in listOf(false, true)) { + val failure = controlFailure { control, listener -> + val output = control.getOutputStream() + fun shortError() { + output.write(byteArrayOf(-2, 0, 0)) + control.shutdownOutput() + } + if (inTransfer) { + output.write(9) + val input = DataInputStream(control.getInputStream()) + input.readFully(ByteArray(input.readInt())) + output.write(10) + listener.accept().use { stream -> + stream.soTimeout = 5_000 + DataInputStream(stream.getInputStream()).readFully(ByteArray(37)) + output.write(byteArrayOf(1, 2)) + shortError() + input.read() // Keep the data channel open until the client processes SERVER_ERROR. + } + } else shortError() + } + assertEquals(Iperf3State.SERVER_ERROR, assertIs(failure).state) + } + } + + @Test fun controlErrorsSendTerminate() = runBlocking { + val unexpectedState = controlFailure { control, _ -> + control.getOutputStream().write(99) + assertEquals(12, control.getInputStream().read()) + } + assertIs(unexpectedState) + val eof = controlFailure { control, _ -> + control.shutdownOutput() + assertEquals(12, control.getInputStream().read()) + } + assertIs(eof) + val timeout = controlFailure { control, _ -> assertEquals(12, control.getInputStream().read()) } + assertIs(timeout) + Unit + } + + /** Opt in only with a real, already running loopback server on this port. */ + @Test fun installedServerInterop() = runBlocking { + val port = System.getenv("NETKIT_IPERF3_INTEROP_PORT")?.toInt() + ?: throw SkipException("NETKIT_IPERF3_INTEROP_PORT not set") + val target = InetSocketAddress(loopback, port) + direction(target, false) + delay(500) + cancelTransfer(target, Iperf3Options(seconds = 4, bitsPerSecond = 100_000)) + delay(500) + direction(target, true) + delay(500) + val unpaced = Iperf3Options(streams = 8, seconds = 3, reverse = true) + cancelTransfer(target, unpaced.copy(seconds = 4)) + // The standard server must release the cancelled session and accept the next handshake. + delay(500) + val result = Iperf3Client {}.measure(target, unpaced) {} + assertEquals(8, result.workingStreams) + assertTrue(result.summary.totalBytes > 0 && result.summary.mbps > 0) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ssh/ProfileEditorTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ssh/ProfileEditorTest.kt new file mode 100644 index 0000000..0df4985 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/ssh/ProfileEditorTest.kt @@ -0,0 +1,42 @@ +package cz.netkit.app.ssh + +import cz.netkit.shared.ssh.SshAuthentication +import cz.netkit.shared.ssh.SshProfile +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ProfileEditorTest { + private val empty = SshProfile("new", "", "", username = "") + private val saved = SshProfile("lab", "Lab", "switch.example.org", username = "operator", + secretRef = "ref", group = "Core") + + @Test fun untouchedNewAndExistingProfilesCloseDirectly() { + assertFalse(profileHasEdits(empty, empty.copy(), false, false)) + assertFalse(profileHasEdits(saved, saved.copy(), false, true)) + val legacy = saved.copy(group = " Core ", keyRef = "unused", dynamicForwardNoAuth = true) + assertFalse(profileHasEdits(legacy, saved, false, true)) + } + + @Test fun effectiveChangesPromptAndRevertingThemClearsThePrompt() { + val edited = saved.copy(group = "Lab") + assertTrue(profileHasEdits(saved, edited, false, true)) + assertFalse(profileHasEdits(saved, edited.copy(group = "Core"), false, true)) + assertTrue(profileHasEdits(saved, saved.copy(port = 0), false, true)) + assertTrue(profileHasEdits(saved, saved.copy(jumpProfileId = "gateway"), false, true)) + assertTrue(profileHasEdits(saved, saved.copy(authentication = SshAuthentication.KEY, keyRef = "key"), false, true)) + } + + @Test fun passwordAndRememberChoiceCountIndependentlyOfProfileChanges() { + assertTrue(profileHasEdits(empty, empty, true, false)) + assertTrue(profileHasEdits(empty, empty, false, true)) + assertTrue(profileHasEdits(saved, saved, false, false)) + } + + @Test fun endpointsIncludeThePortAndBracketOnlyIpv6() { + assertEquals("switch.example.org:22", hostPort("switch.example.org", 22)) + assertEquals("192.0.2.1:2222", hostPort("192.0.2.1", 2222)) + assertEquals("[2001:db8::1]:23", hostPort("2001:db8::1", 23)) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ssh/SessionNotificationTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SessionNotificationTest.kt new file mode 100644 index 0000000..a8541da --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SessionNotificationTest.kt @@ -0,0 +1,21 @@ +package cz.netkit.app.ssh + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class SessionNotificationTest { + @Test fun privateNotificationHidesNumericNamesAndTheConnectedHost() { + for (name in listOf("192.0.2.1", "2001:db8::1", "[2001:db8::1]", "[fe80::1%wlan0]:22", + "192.0.2.1:22", "rack-192.0.2.1", "Lab:192.0.2.1", "2001:0db8:0:0:0:0:0:1", "IPv6 [2001:db8::1]:22", "SWITCH.example.org.", "Office (user@switch.example.org:22)", " ")) { + assertNull(sessionNotificationName(name, "switch.example.org"), name) + } + } + + @Test fun friendlyNamesSurviveAndLongNamesAreCheckedBeforeTruncation() { + assertEquals("Rack A", sessionNotificationName("Rack A", "switch.example.org")) + assertEquals("USB console", sessionNotificationName("USB console", "")) + assertEquals("x".repeat(40), sessionNotificationName("x".repeat(50), "switch.example.org")) + assertNull(sessionNotificationName("A".repeat(39) + " 192.0.2.1", "switch.example.org")) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ssh/SftpRunTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SftpRunTest.kt new file mode 100644 index 0000000..f635992 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SftpRunTest.kt @@ -0,0 +1,104 @@ +package cz.netkit.app.ssh + +import cz.netkit.shared.ssh.SftpFailure +import java.io.Closeable +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import kotlin.test.* + +/** Review round 2 of zadání 42: per-operation SFTP state and the abort clean-up with hanging peers. */ +class SftpRunTest { + private class Hanging : Closeable { + val closeStarted = CountDownLatch(1) + val release = CountDownLatch(1) + override fun close() { closeStarted.countDown(); release.await() } // a provider that never returns from close() + } + + private class Recording : Closeable { + val closed = CountDownLatch(1) + override fun close() { closed.countDown() } + } + + @Test fun lateThreadOfAnAbortedRunCannotTouchTheNextRun() { + var now = 0L + val old = SftpRun(1, transfer = true) { now } + val oldCleanups = AtomicInteger() + old.onFailure { oldCleanups.incrementAndGet() } + val (stream, cleanup) = assertNotNull(old.abort()) + assertNull(stream) + cleanup!!.invoke() + assertNull(old.abort(), "resources are handed out once") + + val next = SftpRun(2, transfer = true) { now } + val nextStream = Recording() + val nextCleanups = AtomicInteger() + next.attach(nextStream) + next.onFailure { nextCleanups.incrementAndGet() } + + // The old thread finally returns from the provider: it opens its stream and runs its catch block. + val lateStream = Recording() + old.attach(lateStream) + old.cleanUp() + assertTrue(lateStream.closed.await(2, TimeUnit.SECONDS), "a stream attached after the abort is closed at once") + assertEquals(1, oldCleanups.get(), "the old clean-up ran exactly once") + assertEquals(1L, nextStream.closed.count, "the next run's stream is untouched") + assertEquals(0, nextCleanups.get()) + val (taken, nextCleanup) = assertNotNull(next.abort()) + assertSame(nextStream, taken) + nextCleanup!!.invoke() + assertEquals(1, nextCleanups.get(), "the next run still owns its clean-up") + } + + @Test fun cancelBelongsToItsTransferOnly() { + var now = 1_000L + val transfer = SftpRun(1, transfer = true) { now } + assertTrue(transfer.requestCancel()) + assertTrue(transfer.cancelled.get()) + now += 1_000 + assertNull(transfer.overdue(ioTimeoutMs = 30_000, cancelGraceMs = 2_000), "the copy loop gets its chance first") + // The loop stopped cooperatively and the run ended; the next operation starts clean. + transfer.completed() + val refresh = SftpRun(2, transfer = false) { now } + assertFalse(refresh.requestCancel(), "cancel never applies to a refresh, navigation or rename") + now += 10_000 + assertNull(refresh.overdue(ioTimeoutMs = 30_000, cancelGraceMs = 2_000), "no leftover cancel request") + now += 25_000 + assertEquals(SftpFailure.CONNECTION, refresh.overdue(ioTimeoutMs = 30_000, cancelGraceMs = 2_000)) + refresh.alive() + assertNull(refresh.overdue(ioTimeoutMs = 30_000, cancelGraceMs = 2_000), "activity resets the clock") + + val stuck = SftpRun(3, transfer = true) { now } + stuck.requestCancel() + now += 2_001 + assertEquals(SftpFailure.CANCELLED, stuck.overdue(ioTimeoutMs = 30_000, cancelGraceMs = 2_000)) + assertNotNull(stuck.abort()) + assertFalse(stuck.requestCancel(), "an aborted run takes no further requests") + } + + @Test fun hangingStreamCloseDoesNotBlockChannelCloseOrDocumentCleanup() { + val stream = Hanging() + val channelClosed = CountDownLatch(1) + val documentDeleted = CountDownLatch(1) + val started = System.nanoTime() + SftpAbandon.release(channel = { channelClosed.countDown() }, stream = stream, + cleanup = { documentDeleted.countDown() }, streamWaitMs = 200) + try { + assertTrue(stream.closeStarted.await(2, TimeUnit.SECONDS)) + assertTrue(channelClosed.await(1, TimeUnit.SECONDS), "the channel closes although the stream hangs") + assertTrue(documentDeleted.await(2, TimeUnit.SECONDS), "the half-written document is deleted after the wait") + assertTrue((System.nanoTime() - started) / 1_000_000 < 2_000) + } finally { stream.release.countDown() } + } + + @Test fun hangingChannelCloseDoesNotBlockStreamOrCleanup() { + val channelGate = CountDownLatch(1) + val stream = Recording() + val documentDeleted = CountDownLatch(1) + SftpAbandon.release(channel = { channelGate.await() }, stream = stream, cleanup = { documentDeleted.countDown() }) + try { + assertTrue(stream.closed.await(1, TimeUnit.SECONDS)) + assertTrue(documentDeleted.await(1, TimeUnit.SECONDS)) + } finally { channelGate.countDown() } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProductivityJvmTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProductivityJvmTest.kt new file mode 100644 index 0000000..5be8195 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProductivityJvmTest.kt @@ -0,0 +1,281 @@ +package cz.netkit.app.ssh + +import java.io.ByteArrayOutputStream +import java.net.InetAddress +import java.net.InetSocketAddress +import java.net.ServerSocket +import java.net.Socket +import java.time.OffsetDateTime +import java.time.ZoneOffset +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import kotlin.test.* + +class SshSessionLogTest { + private val clock = { OffsetDateTime.of(2026, 12, 1, 10, 0, 0, 0, ZoneOffset.ofHours(1)) } + + private fun record(limit: Long, block: (SshSessionLog) -> Unit): Pair = runBlocking { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + try { + val output = ByteArrayOutputStream() + val stopped = CompletableDeferred() + val log = SshSessionLog(scope, "Router\u001b[31m", open = { output }, onStopped = { stopped.complete(it) }, + limitBytes = limit, now = clock) + log.start() + block(log) + val reason = withTimeout(5000) { stopped.await() } + output.toString(Charsets.UTF_8) to reason + } finally { scope.cancel() } + } + + @Test fun plainTextWithHeaderAndFooter() { + val (text, reason) = record(1_000_000) { log -> + log.append("\u001b[1;32mNETKIT_FIXTURE_READY\u001b[0m\r\nfixture> ") + log.append("netkit-check\r\n\u001b[1;32mNETKIT_TEST_OK\u001b[0m\r\n") + log.stop(SshLogStop.USER) + } + assertEquals(SshLogStop.USER, reason) + assertFalse('\u001b' in text) + assertEquals(""" + # NetKit SSH log: Router[31m + # start: 2026-12-01T10:00:00+01:00 + NETKIT_FIXTURE_READY + fixture> netkit-check + NETKIT_TEST_OK + # end: 2026-12-01T10:00:00+01:00 + """.trimIndent() + "\n", text) + } + + @Test fun limitStopsWritingAndFooterStillFits() { + val (text, reason) = record(600) { log -> + repeat(100) { log.append("line $it with some padding text\r\n") } + log.stop(SshLogStop.USER) + } + assertEquals(SshLogStop.LIMIT, reason) + assertTrue(text.toByteArray().size <= 600, "size ${text.toByteArray().size}") + assertTrue(text.endsWith("(size limit 0 MiB reached)\n")) + assertFalse("line 99" in text) + } + + /** Review of 41 (P2): a provider that blocks must not keep the log registered forever. */ + private class HangingStream : java.io.OutputStream() { + val release = java.util.concurrent.CountDownLatch(1) + @Volatile var closed = false + var writes = 0 + override fun write(b: Int) { write(byteArrayOf(b.toByte()), 0, 1) } + override fun write(b: ByteArray, off: Int, len: Int) { + if (closed) throw java.io.IOException("closed") + if (++writes > 1) release.await() // header passes, then the provider hangs until closed + if (closed) throw java.io.IOException("closed") + } + override fun close() { closed = true; release.countDown() } + } + + @Test fun hangingWriteTimesOutClosesStreamAndReportsOnce() = runBlocking { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + try { + val stream = HangingStream() + val reasons = java.util.concurrent.CopyOnWriteArrayList() + val stopped = CompletableDeferred() + val log = SshSessionLog(scope, "x", open = { stream }, onStopped = { reasons += it; stopped.complete(it) }, ioTimeoutMs = 300) + log.start() + log.append("first line\r\n") + delay(100) + log.append("second line\r\n") + log.stop(SshLogStop.USER) // stop alone cannot finish: the writer is stuck in the provider + assertEquals(SshLogStop.WRITE_FAILED, withTimeout(5000) { stopped.await() }) + withTimeout(5000) { while (!stream.closed) delay(10) } + delay(400) // the released writer thread must not report a second time + assertEquals(listOf(SshLogStop.WRITE_FAILED), reasons.toList()) + log.append("late") // ignored, no exception + } finally { scope.cancel() } + } + + @Test fun hangingOpenIsCancelledAndReported() = runBlocking { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + try { + val cancelled = java.util.concurrent.CountDownLatch(1) + val late = HangingStream() + val stopped = CompletableDeferred() + val log = SshSessionLog(scope, "x", open = { cancelled.await(); late }, onStopped = { stopped.complete(it) }, + cancelOpen = { cancelled.countDown() }, ioTimeoutMs = 300) + log.start() + assertEquals(SshLogStop.WRITE_FAILED, withTimeout(5000) { stopped.await() }) + assertEquals(0L, cancelled.count, "the pending open was cancelled") + withTimeout(5000) { while (!late.closed) delay(10) } // a stream returned after the abort is closed, not used + } finally { scope.cancel() } + } + + /** Opravná dávka P3 (polish-p3), adapted to the 42 log API: a failing close is reported, closed once. */ + @Test fun closeFailureIsReportedBeforePublishingStop() = runBlocking { + var closes = 0 + val output = object : ByteArrayOutputStream() { + override fun close() { closes++; throw java.io.IOException("fixture") } + } + val stopped = CompletableDeferred() + val log = SshSessionLog(this, "fixture", open = { output }, onStopped = { stopped.complete(it) }) + log.start() + log.stop(SshLogStop.USER) + assertEquals(SshLogStop.WRITE_FAILED, withTimeout(5000) { stopped.await() }) + assertEquals(1, closes) + } + + @Test fun appendAfterStopIsIgnoredAndOpenFailureIsReported() { + val (_, reason) = runBlocking { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + try { + val stopped = CompletableDeferred() + val log = SshSessionLog(scope, "x", open = { throw java.io.IOException("denied") }, onStopped = { stopped.complete(it) }) + log.start() + log.append("data") + "" to withTimeout(5000) { stopped.await() } + } finally { scope.cancel() } + } + assertEquals(SshLogStop.WRITE_FAILED, reason) + val (text, ended) = record(1_000_000) { log -> log.stop(SshLogStop.SESSION_ENDED); log.append("late") } + assertEquals(SshLogStop.SESSION_ENDED, ended) + assertFalse("late" in text) + } +} + +class SshSessionLogStartTest { + @Test fun nothingRunsBeforeStartAndImmediateFailureReportsAfterRegistration() = runBlocking { + val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + try { + var opened = false + val registry = java.util.concurrent.ConcurrentHashMap() + val stopped = CompletableDeferred() + lateinit var log: SshSessionLog + log = SshSessionLog(scope, "x", open = { opened = true; throw java.io.IOException("denied") }, + onStopped = { stopped.complete(registry.remove("s", log)) }) + kotlinx.coroutines.delay(100) + assertFalse(opened, "construction must not start the writer") + registry["s"] = log + log.start() + assertTrue(withTimeout(5000) { stopped.await() }, "stopped log must be removed from the registry") + assertTrue(registry.isEmpty()) + assertFailsWith { log.start() } + } finally { scope.cancel() } + } +} + +class SshForwarderJvmTest { + @Test fun localForwardListensOnlyOnLoopback() { + LocalForwardServer(0, "127.0.0.1", 80, open = { _, _ -> error("unused") }, slots = java.util.concurrent.Semaphore(1)).use { server -> + assertTrue(server.address.address.isLoopbackAddress) + assertEquals(LOOPBACK_V4, server.address.address) + } + } + + private fun freePort(): Int = ServerSocket(0, 1, LOOPBACK_V4).use { it.localPort } + + @Test fun socksListensOnLoopbackAndRejectsBadHandshakesWithoutOpeningChannels() { + var opened = 0 + Socks5Server(freePort(), open = { _, _ -> opened++; error("must not open") }, credentials = null).use { server -> + server.start() + assertTrue(server.address.address.isLoopbackAddress) + fun exchange(vararg bytes: Int, expect: Int): ByteArray = Socket().use { socket -> + socket.soTimeout = 3000 + socket.connect(server.address, 3000) + socket.getOutputStream().write(ByteArray(bytes.size) { bytes[it].toByte() }) + val reply = ByteArray(expect) + var read = 0 + while (read < expect) { val n = socket.getInputStream().read(reply, read, expect - read); if (n < 0) break; read += n } + assertEquals(-1, socket.getInputStream().read(), "server must close after a rejected request") + reply.copyOf(read) + } + assertContentEquals(byteArrayOf(5, 0xFF.toByte()), exchange(5, 1, 2, expect = 2)) // only username/password offered + assertContentEquals(byteArrayOf(), exchange(4, 1, 0, expect = 0)) // SOCKS4: closed without reply + assertContentEquals(byteArrayOf(5, 0, 5, 7, 0, 1, 0, 0, 0, 0, 0, 0), exchange(5, 1, 0, 5, 2, 0, 1, 127, 0, 0, 1, 0, 80, expect = 12)) // BIND + assertContentEquals(byteArrayOf(5, 0, 5, 8, 0, 1, 0, 0, 0, 0, 0, 0), exchange(5, 1, 0, 5, 1, 0, 9, 0, 0, expect = 12)) // bad ATYP + } + assertEquals(0, opened) + } + + @Test fun socksRefusesNonLoopbackClientsByBindingOnlyToLoopback() { + val port = freePort() + Socks5Server(port, open = { _, _ -> error("unused") }, credentials = null).use { server -> + server.start() + val external = java.net.NetworkInterface.getNetworkInterfaces().toList().flatMap { it.inetAddresses.toList() } + .firstOrNull { !it.isLoopbackAddress && it is java.net.Inet4Address } + if (external != null) { + assertFailsWith { Socket().use { it.connect(InetSocketAddress(external, port), 1000) } } + } + } + } + + @Test fun socksCapsConcurrentClients() { + Socks5Server(freePort(), open = { _, _ -> error("unused") }, credentials = null, maxConnections = 2, handshakeMillis = 5000).use { server -> + server.start() + val held = List(2) { Socket().apply { connect(server.address, 3000) } } + try { + Thread.sleep(200) + Socket().use { extra -> + extra.soTimeout = 3000; extra.connect(server.address, 3000) + assertEquals(-1, extra.getInputStream().read(), "third client must be closed immediately") + } + } finally { held.forEach { it.close() } } + } + } + + @Test fun socksRequiresPerSessionLoginByDefault() { + var opened = 0 + val login = cz.netkit.shared.ssh.SshSocksCredentials("netkit", "s3cretValue") + Socks5Server(freePort(), open = { _, _ -> opened++; error("must not open") }, credentials = login).use { server -> + server.start() + fun exchange(vararg bytes: Int, expect: Int): ByteArray = Socket().use { socket -> + socket.soTimeout = 3000; socket.connect(server.address, 3000) + socket.getOutputStream().write(ByteArray(bytes.size) { bytes[it].toByte() }) + val reply = ByteArray(expect); var read = 0 + while (read < expect) { val n = socket.getInputStream().read(reply, read, expect - read); if (n < 0) break; read += n } + assertEquals(-1, socket.getInputStream().read(), "server must close") + reply.copyOf(read) + } + fun userPass(user: String, password: String): IntArray { + val u = user.encodeToByteArray(); val p = password.encodeToByteArray() + return (listOf(1, u.size) + u.map { it.toInt() and 0xFF } + listOf(p.size) + p.map { it.toInt() and 0xFF }).toIntArray() + } + // A client offering only "no authentication" is refused (05 FF). + assertContentEquals(byteArrayOf(5, 0xFF.toByte()), exchange(5, 1, 0, expect = 2)) + // Wrong password: method 02 chosen, then RFC 1929 failure and close, no channel. + assertContentEquals(byteArrayOf(5, 2, 1, 1), exchange(5, 2, 0, 2, *userPass("netkit", "s3cretValuX"), expect = 4)) + assertContentEquals(byteArrayOf(5, 2, 1, 1), exchange(5, 1, 2, *userPass("other", "s3cretValue"), expect = 4)) + // Correct login reaches the request parser (BIND is still refused without opening a channel). + assertContentEquals(byteArrayOf(5, 2, 1, 0, 5, 7, 0, 1, 0, 0, 0, 0, 0, 0), + exchange(5, 1, 2, *userPass("netkit", "s3cretValue"), 5, 2, 0, 1, 127, 0, 0, 1, 0, 80, expect = 14)) + } + assertEquals(0, opened) + assertFalse("s3cretValue" in login.toString()) + } + + @Test fun localForwardCapsActiveClientsAndReleasesSlots() { + val gate = java.util.concurrent.CountDownLatch(1) + val opens = java.util.concurrent.atomic.AtomicInteger() + val slots = java.util.concurrent.Semaphore(1) + LocalForwardServer(freePort(), "127.0.0.1", 80, open = { _, _ -> opens.incrementAndGet(); gate.await(); error("no SSH in JVM test") }, + slots = slots).use { server -> + server.start() + val first = Socket().apply { connect(server.address, 3000) } + val deadline = System.nanoTime() + 3_000_000_000L + while (opens.get() == 0 && System.nanoTime() < deadline) Thread.sleep(20) + assertEquals(1, opens.get()); assertEquals(0, slots.availablePermits()) + Socket().use { over -> + over.soTimeout = 3000; over.connect(server.address, 3000) + assertEquals(-1, over.getInputStream().read(), "client over the limit is closed before any channel") + } + assertEquals(1, opens.get()) + gate.countDown() // Channel open fails: the client is closed and its slot released. + first.soTimeout = 3000 + assertEquals(-1, first.getInputStream().read()) + while (slots.availablePermits() == 0 && System.nanoTime() < deadline + 3_000_000_000L) Thread.sleep(20) + assertEquals(1, slots.availablePermits()) + first.close() + } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt index c937b31..ce4b877 100644 --- a/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt +++ b/androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt @@ -12,6 +12,7 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.test.* import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive import kotlin.test.* @OptIn(ExperimentalCoroutinesApi::class) @@ -63,6 +64,30 @@ class SshProfileImportControllerTest { assertEquals(SshProfileImportState(), fixture.controller.state.value) } + @Test fun confirmReplaysIdsForSnippetsAndRowsSkippedForProxyJump() = runTest { + // Zadání 41 revize P1: the preview draws ids for every new row (also one later skipped for an + // unresolved ProxyJump) and for new snippets; confirmation must not run out of ids. + val document = """{"format":"netkit-ssh-profiles","schema":2,"source":"netkit-android","profiles":[ + {"alias":"bastion","host":"192.0.2.1","port":22,"username":"u","authentication":"PASSWORD","startupCommand":"","keepaliveSeconds":30}, + {"alias":"inner","host":"10.0.0.5","port":22,"username":"u","authentication":"PASSWORD","startupCommand":"","keepaliveSeconds":30,"proxyJump":"bastion"}, + {"alias":"lost","host":"10.0.0.6","port":22,"username":"u","authentication":"PASSWORD","startupCommand":"","keepaliveSeconds":30,"proxyJump":"nowhere"}], + "skipped":[],"snippets":[{"name":"ver","text":"show version","sendEnter":true}, + {"name":"own","text":"uptime","sendEnter":true,"profile":"inner"}]}""".encodeToByteArray() + val fixture = Fixture(this, SshData(snippets = listOf(SshSnippet("local", "ver", "show ver", sendEnter = true)))) + fixture.controller.preview { document }; advanceUntilIdle() + val plan = assertNotNull(fixture.controller.state.value.pendingProfileImport).plan + assertEquals(listOf("import-1", "import-2", "import-3", "import-4"), plan.generatedIds) + assertEquals(1, plan.newSnippets); assertEquals(1, plan.updatedSnippets) + fixture.controller.confirm(null); advanceUntilIdle() + assertNull(fixture.controller.state.value.failure) + assertEquals(1, fixture.writes) + assertEquals(listOf("bastion", "inner"), fixture.data.profiles.map { it.name }) + assertEquals("import-1", fixture.data.profiles[1].jumpProfileId) + assertEquals(listOf("local" to "show version", "import-4" to "uptime"), fixture.data.snippets.map { it.id to it.text }) + assertTrue(fixture.data.snippets.none { it.sendEnter }) // Imported/changed commands never send Enter on their own. + assertEquals("import-2", fixture.data.snippets[1].profileId) + } + @Test fun stalePlanAndFailedCommitNeverDeleteSecrets() = runTest { for (stale in listOf(true, false)) { val original = SshData(profiles = listOf(savedProfile())) @@ -96,7 +121,7 @@ class SshProfileImportControllerTest { val fixture = Fixture(this, SshData(profiles = listOf(original))) fixture.controller.preview { bytes }; advanceUntilIdle() fixture.controller.confirm(null); advanceUntilIdle() - assertEquals(original, fixture.data.profiles.single()) + assertEquals(original.copy(group = "Homelab"), fixture.data.profiles.single()) assertTrue(fixture.deleted.isEmpty()) assertEquals(SshProfileImportState(), fixture.controller.state.value) } @@ -287,13 +312,13 @@ class SshProfileImportControllerTest { store.update { it.copy(profiles = listOf(original)) } val plan = planSshProfileImport(store.read(), incoming, null) { "new-id" } val imported = store.update { applySshImportPlan(it, plan) } - assertEquals(original.copy(host = "192.168.0.10", username = "root", secretRef = null), imported.profiles.single()) + assertEquals(original.copy(host = "192.168.0.10", username = "root", secretRef = null, group = "Homelab"), imported.profiles.single()) assertEquals(imported, store.read()) val output = ByteArrayOutputStream() SshDataSerializer.writeTo(imported, output) val root = SshDataSerializer.json.parseToJsonElement(output.toString(Charsets.UTF_8.name())).jsonObject - assertEquals(setOf("schema", "profiles", "keys", "hostKeys", "rejectedHostKeys"), root.keys) - assertFalse(root.getValue("profiles").jsonArray.single().jsonObject.containsKey("group")) + assertEquals(setOf("schema", "profiles", "keys", "hostKeys", "rejectedHostKeys", "snippets"), root.keys) + assertEquals("Homelab", root.getValue("profiles").jsonArray.single().jsonObject.getValue("group").jsonPrimitive.content) val full = SshData(profiles = (1..200).map { SshProfile("id-$it", "host-$it", "host", username = "root") }) store.update { full } val before = file.readBytes() diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ssh/TelnetConsoleWireTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ssh/TelnetConsoleWireTest.kt new file mode 100644 index 0000000..774f862 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/ssh/TelnetConsoleWireTest.kt @@ -0,0 +1,37 @@ +package cz.netkit.app.ssh + +import java.io.File +import java.net.Socket +import java.util.concurrent.TimeUnit +import kotlin.test.* +import org.testng.annotations.Test + +class TelnetConsoleWireTest { + @Test(timeOut = 15000) fun loopbackFixture() = fixture(false) + @Test(timeOut = 15000) fun pipeFixture() = fixture(true) + + private fun fixture(pipe: Boolean) { + val file = listOf(File("../tools/testsrv/telnet_fixture.py"), File("tools/testsrv/telnet_fixture.py")).first { it.isFile } + val command = mutableListOf("python3", "-I", file.canonicalPath) + if (pipe) command += "--stdio" + val process = ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.INHERIT).start() + try { + val socket = if (pipe) object : Socket() { + override fun getInputStream() = process.inputStream + override fun getOutputStream() = process.outputStream + override fun close() { process.outputStream.close(); process.inputStream.close() } + } else Socket("127.0.0.1", process.inputStream.bufferedReader().readLine().toInt()).apply { soTimeout = 5000 } + TelnetWire(socket).use { wire -> + val reader = wire.input.bufferedReader() + assertEquals("Připraven", reader.readLine()) + wire.resize(120,40) + wire.write("ok") + wire.write("\r") + assertEquals("OK", reader.readLine()) + assertNull(reader.readLine()) + } + assertTrue(process.waitFor(5, TimeUnit.SECONDS)) + assertEquals(0, process.exitValue()) + } finally { process.destroyForcibly() } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ssh/UsbConsoleWireTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ssh/UsbConsoleWireTest.kt new file mode 100644 index 0000000..d0898ce --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/ssh/UsbConsoleWireTest.kt @@ -0,0 +1,166 @@ +package cz.netkit.app.ssh + +import com.hoho.android.usbserial.driver.UsbSerialPort +import cz.netkit.shared.ssh.* +import java.lang.reflect.Proxy +import java.util.EnumSet +import java.io.IOException +import java.io.InputStream +import java.util.concurrent.CountDownLatch +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import kotlinx.coroutines.* +import kotlin.test.* + +class UsbConsoleWireTest { + @Test fun closingTabUnblocksReaderAndReleasesWireOnce() = runBlocking { + val reading = CountDownLatch(1) + val released = CountDownLatch(1) + val closes = AtomicInteger() + val finished = CompletableDeferred() + val fake = object : ConsoleWire { + override val input = object : InputStream() { + override fun read(): Int { + reading.countDown() + check(released.await(5, TimeUnit.SECONDS)) + return -1 + } + } + override fun write(text: String) {} + override fun close() { closes.incrementAndGet(); released.countDown() } + } + val session = ConsoleConnection(this, { fake }, {}, {}, { finished.complete(it) }) + session.start() + try { + assertTrue(reading.await(5, TimeUnit.SECONDS)) + session.close() + assertFalse(withTimeout(5000) { finished.await() }) + assertFalse(session.send("after-close")) + assertEquals(1, closes.get()) + } finally { session.close() } + } + + @Test fun configuredPortReadsWritesBreaksAndEndsOnDetach() = runBlocking { + var attached = true + var released = 0 + val calls = mutableListOf() + val fake = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(UsbSerialPort::class.java)) { _, method, args -> + when (method.name) { + "setParameters", "setFlowControl", "setDTR", "setBreak" -> { calls += method.name + args.joinToString(); null } + "getSupportedControlLines" -> EnumSet.of(UsbSerialPort.ControlLine.DTR) + "read" -> if (attached) { (args[0] as ByteArray)[0] = 65; 1 } else 0 + "write" -> { calls += (args[0] as ByteArray).decodeToString(); null } + "close" -> { calls += "closed"; null } + else -> error(method.name) + } + } as UsbSerialPort + val wire = SerialWire(fake, { attached }, { released++ }) + wire.configure(SerialSettings(115200,7,SerialParity.EVEN,SerialStopBits.TWO,true)) + assertEquals(65, wire.input.read()) + wire.write("ok") + wire.sendBreak() + attached = false + assertEquals(-1, wire.input.read()) + wire.close() + wire.close() + assertEquals(listOf("setParameters115200, 7, 2, 2","setFlowControlRTS_CTS","setDTRtrue","ok", + "setBreaktrue","setBreakfalse","closed"), calls) + assertEquals(1, released) + } + /** Fake port for the cable-pull cases (review P3): a read blocks until the port closes, writes fail once detached. */ + private class PulledPort { + @Volatile var attached = true + @Volatile var closed = false + val released = AtomicInteger() + val port = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(UsbSerialPort::class.java)) { _, method, args -> + when (method.name) { + "setParameters", "setFlowControl", "setDTR", "setBreak" -> null + "getSupportedControlLines" -> EnumSet.of(UsbSerialPort.ControlLine.DTR) + "read" -> { while (!closed) Thread.sleep(10); throw IOException("closed") } + "write" -> { if (closed || !attached) throw IOException("USB write failed"); null } + "close" -> { closed = true; null } + else -> error(method.name) + } + } as UsbSerialPort + val wire = SerialWire(port, { attached }, { released.incrementAndGet() }) + } + + @Test fun writeAfterCablePullEndsTheWireAsEof() { + val pulled = PulledPort() + pulled.wire.write("before") + pulled.attached = false + pulled.wire.write("after pull") // no exception: the line is gone, not broken + assertTrue(pulled.closed, "the port is closed so a blocked read wakes up") + assertEquals(1, pulled.released.get()) + assertEquals(-1, pulled.wire.input.read()) + pulled.wire.write("late") // writes after the end are ignored + pulled.wire.close() + assertEquals(1, pulled.released.get()) + } + + @Test fun writeFailureWhileAttachedStaysAnError() { + val failing = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(UsbSerialPort::class.java)) { _, method, _ -> + if (method.name == "write") throw IOException("stall") else if (method.name == "close") null else error(method.name) + } as UsbSerialPort + val wire = SerialWire(failing, { true }, {}) + assertFailsWith { wire.write("x") } + wire.close() + } + + @Test fun sessionEndsCleanlyWhenTheCableIsPulledDuringWrite() = runBlocking { + val pulled = PulledPort() + val finished = CompletableDeferred() + val session = ConsoleConnection(this, { pulled.wire }, {}, {}, { finished.complete(it) }) + session.start() + try { + pulled.attached = false + assertTrue(session.send("show running-config\r")) + assertFalse(withTimeout(5000) { finished.await() }, "cable pull is EOF, not a failure") + assertEquals(1, pulled.released.get()) + } finally { session.close() } + } + /** Review P2: every driver read is one full packet-aligned buffer, and UTF-8 split across packets stays intact. */ + @Test fun readsArePacketAlignedAndUtf8SurvivesPacketBoundaries() { + val text = buildString { repeat(400) { append("Příliš žluťoučký kůň úpěl ďábelské ódy 🐴 #$it\r\n") } } + val bytes = text.encodeToByteArray() + val packets = ArrayDeque((bytes.indices step 64).map { bytes.copyOfRange(it, minOf(it + 64, bytes.size)) }) + val requested = mutableListOf() + var attached = true + val port = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(UsbSerialPort::class.java)) { _, method, args -> + when (method.name) { + "read" -> { + val dest = args[0] as ByteArray + val length = args[1] as Int + requested += length + check(length <= dest.size) + val packet = packets.removeFirstOrNull() + if (packet == null) { attached = false; 0 } else { packet.copyInto(dest); packet.size } + } + "close" -> null + else -> error(method.name) + } + } as UsbSerialPort + val wire = SerialWire(port, { attached }, {}, packetSize = 64) + // The same decoder as ConsoleConnection, with its 4096-char reads (odd byte lengths after split characters). + val reader = wire.input.reader(Charsets.UTF_8) + val chars = CharArray(4096) + val received = StringBuilder() + while (true) { val n = reader.read(chars); if (n < 0) break; received.appendRange(chars, 0, n) } + assertEquals(text, received.toString()) + assertTrue(requested.isNotEmpty()) + assertTrue(requested.all { it == alignedSerialReadSize(64) }, "requests: ${requested.distinct()}") + // A single-byte read also asks the driver for the full aligned buffer (FTDI rejects lengths <= 2). + val single = Proxy.newProxyInstance(javaClass.classLoader, arrayOf(UsbSerialPort::class.java)) { _, method, args -> + when (method.name) { + "read" -> { assertEquals(512 * 16, args[1] as Int); "AB".encodeToByteArray().copyInto(args[0] as ByteArray); 2 } + "close" -> null + else -> error(method.name) + } + } as UsbSerialPort + val one = SerialWire(single, { true }, {}, packetSize = 512) + assertEquals('A'.code, one.input.read()) + assertEquals('B'.code, one.input.read()) // served from the held-back bytes, no second driver read needed + wire.close(); one.close() + assertEquals(listOf(8192, 8192, 8000, 10000), listOf(64, 512, 1000, 10000).map(::alignedSerialReadSize)) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ui/AccessibilityTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ui/AccessibilityTest.kt new file mode 100644 index 0000000..b08c644 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/ui/AccessibilityTest.kt @@ -0,0 +1,116 @@ +package cz.netkit.app.ui + +import cz.netkit.app.R +import cz.netkit.app.lan.LanDeviceScan +import cz.netkit.app.lan.LanDevicesState +import cz.netkit.app.lan.LanTool +import cz.netkit.app.lan.keepsScreenOn +import cz.netkit.app.lan.LanUiState +import cz.netkit.app.speed.SpeedPhase +import cz.netkit.app.speed.SpeedUiState +import cz.netkit.app.ui.chart.SeriesReadings +import cz.netkit.app.ui.chart.seriesReadings +import cz.netkit.app.wifi.strongestTrace +import cz.netkit.shared.wifi.* +import cz.netkit.shared.lan.* +import cz.netkit.shared.speed.SpeedEngine +import cz.netkit.shared.speed.ThroughputSummary +import kotlin.test.* + +class AccessibilityTest { + private val finished = LanUiState(runStatus = LanRunStatus.FINISHED) + private val down = ThroughputSummary(22.5, 23.0, 0, 1000, 100) + private val up = down.copy(mbps = 8.5) + + private fun phrase(actual: ResultPhrase, id: Int, vararg args: Any) { + assertEquals(id, actual.resource) + assertEquals(args.toList(), actual.arguments.toList()) + } + + @Test fun pingCountsAllAttemptsAndAveragesRepliesInTheRetainedWindow() { + val ping = finished.copy(tool = LanTool.PING, sent = 3, received = 2, samples = listOf(2.0, null, 4.0)) + val summary = lanSummary(ping) + phrase(summary.first(), R.string.a11y_ping_done, 2, 3) + phrase(summary.last(), R.string.a11y_ping_average, 3.0) + phrase(lanSummary(ping.copy(sent = 605)).last(), R.string.a11y_ping_window_average, 3, 3.0) + phrase(pingSummary(2, 0, listOf(null, null)).single(), R.string.a11y_ping_done, 0, 2) + assertTrue(lanSummary(ping.copy(mtuSweep = true)).isEmpty()) + } + + @Test fun tcpPingSummarizesBothRepliesAndTimeouts() { + val ping = finished.copy(tool = LanTool.TCP_PING, sent = 4, received = 2, samples = listOf(3.0, null, 5.0)) + phrase(lanSummary(ping).first(), R.string.a11y_tcp_ping_done, 2, 4) + phrase(lanSummary(ping).last(), R.string.a11y_ping_window_average, 3, 4.0) + phrase(lanSummary(ping.copy(received = 0, samples = listOf(null))).single(), R.string.a11y_tcp_ping_done, 0, 4) + assertTrue(lanSummary(ping.copy(runStatus = LanRunStatus.CANCELLED)).isEmpty()) + } + + @Test fun longLanMeasurementsKeepDisplayOnOnlyWhileRunning() { + val tools = setOf(LanTool.PING, LanTool.TCP_PING, LanTool.TRACE, LanTool.PORTS) + for (status in LanRunStatus.entries) { + assertEquals(if (status == LanRunStatus.RUNNING) tools else emptySet(), + LanTool.entries.filter { finished.copy(tool = it, runStatus = status).keepsScreenOn }.toSet()) + } + } + + @Test fun tracePortsAndDnsCountTheirOwnResults() { + val rows = listOf(LanResult("192.0.2.1"), LanResult("")) + phrase(lanSummary(finished.copy(tool = LanTool.TRACE, results = rows)).single(), R.string.a11y_trace_done, 2, 1) + phrase(lanSummary(finished.copy(tool = LanTool.PORTS, probeCounts = ProbeCounts(open = 1, refused = 2), + progress = 3)).single(), R.string.a11y_ports_done, 1, 3) + phrase(lanSummary(finished.copy(tool = LanTool.DNS)).single(), R.string.a11y_dns_done, 0) + phrase(lanSummary(finished.copy(tool = LanTool.RECORDS, results = rows)).single(), R.string.a11y_records_done, 2) + phrase(lanSummary(finished.copy(tool = LanTool.DISCOVERY, results = rows.take(1))).single(), R.string.a11y_scan_done, 1) + } + + @Test fun deviceScanAnnouncesDisplayedCountIncludingSelfAndStaleEntries() { + val peer = LanDevice("192.0.2.1", firstSeenElapsedMs = 0, lastSeenElapsedMs = 1, method = LanAliveMethod.ICMP) + val state = LanDevicesState(scan = LanDeviceScan(LanRunStatus.FINISHED), + devices = listOf(peer, peer.copy(address = "192.0.2.2", stale = true), peer.copy(address = "192.0.2.3", isSelf = true))) + phrase(deviceScanSummary(state).single(), R.string.a11y_scan_done, 3) + phrase(deviceScanSummary(state.copy(devices = emptyList())).single(), R.string.a11y_scan_done, 0) + assertTrue(deviceScanSummary(state.copy(scan = LanDeviceScan(LanRunStatus.CANCELLED))).isEmpty()) + } + + @Test fun speedNamesOnlyMeasuredDirectionsIncludingZero() { + val state = SpeedUiState(phase = SpeedPhase.DONE, engine = SpeedEngine.NDT7, download = down, upload = up) + val both = speedSummary(state) + phrase(both[0], R.string.a11y_speed_done) + phrase(both[1], R.string.a11y_speed_download, 22.5) + phrase(both[2], R.string.a11y_speed_upload, 8.5) + val upload = speedSummary(state.copy(engine = SpeedEngine.IPERF3, download = null, upload = up.copy(mbps = 0.0))) + assertEquals(2, upload.size) + phrase(upload[0], R.string.a11y_iperf_done) + phrase(upload[1], R.string.a11y_speed_upload, 0.0) + phrase(speedSummary(state.copy(engine = SpeedEngine.IPERF3, upload = null)).last(), R.string.a11y_speed_download, 22.5) + } + + @Test fun partialResultsNeverAnnounceCompletion() { + (LanRunStatus.entries - LanRunStatus.FINISHED).forEach { + assertTrue(lanSummary(finished.copy(tool = LanTool.DNS, runStatus = it)).isEmpty()) + } + (SpeedPhase.entries - SpeedPhase.DONE).forEach { + assertTrue(speedSummary(SpeedUiState(phase = it, download = down)).isEmpty()) + } + } + + @Test fun strongestApUsesMeasuredPowerIndependentOfDrawingOrder() { + val connected = AccessPoint("Lab A", "02:00:00:00:49:01", -70, 2412, channel = 1, band = WifiBand.GHZ_2_4, + widthMhz = 20, security = WifiSecurity.WPA2, standard = null, ageMs = 0, locallyAdministered = true, isCurrent = true) + val hidden = connected.copy(ssid = null, bssid = "02:00:00:00:49:02", isCurrent = false, rssiDbm = -40) + val spectrum = requireNotNull(bandSpectrum(listOf(connected, hidden), WifiBand.GHZ_2_4)) + for (traces in listOf(spectrum.traces, spectrum.traces.reversed())) { + assertEquals(hidden, spectrum.copy(traces = traces).strongestTrace()?.accessPoint) + } + assertNull(spectrum.copy(traces = emptyList()).strongestTrace()) + } + + @Test fun graphUsesOnlyVisibleSlotsAndPreservesMissingLastSample() { + val values = listOf(90f, -70f, -60f, null, Float.NaN, 85f) + assertEquals(SeriesReadings(-70f, -60f, -60f), seriesReadings(values, 1..2)) + assertEquals(SeriesReadings(-70f, -60f, null), seriesReadings(values, 1..3)) + assertEquals(SeriesReadings(-70f, -60f, null), seriesReadings(values, 1..4)) + assertNull(seriesReadings(values, 3..4)) + assertNull(seriesReadings(values, IntRange.EMPTY)) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/ui/about/OssComponentsTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/ui/about/OssComponentsTest.kt index 0f38bd2..36cff18 100644 --- a/androidApp/src/test/kotlin/cz/netkit/app/ui/about/OssComponentsTest.kt +++ b/androidApp/src/test/kotlin/cz/netkit/app/ui/about/OssComponentsTest.kt @@ -41,6 +41,7 @@ class OssComponentsTest { component.license == "Apache-2.0" -> "Apache-2.0.txt" component.license == "MPL-2.0" -> "MPL-2.0.txt" component.license == "OFL-1.1" -> "OFL.txt" + component.license == "Unicode-3.0" -> "unicode-LICENSE.txt" else -> null } ?: continue assertTrue(component.texts.any { it.endsWith(expected) }, "${component.id} carries $expected") @@ -81,10 +82,15 @@ class OssComponentsTest { @Test fun copiedTextsAreIdenticalToTheirSources() { assertEquals(File(root, "NOTICE").readText(), File(assets, "NOTICE.txt").readText()) assertEquals(File(root, "LICENSE").readText(), File(assets, "Apache-2.0.txt").readText()) - for ((asset, source) in listOf("jsch-LICENSE.txt" to "jsch-META-INF_LICENSE.txt", "jzlib-LICENSE.txt" to "jsch-META-INF_LICENSE.JZlib.txt", - "jbcrypt-LICENSE.txt" to "jsch-META-INF_LICENSE.jBCrypt.txt")) { + for ((asset, source) in listOf("usb-serial-for-android-LICENSE.txt" to "usb-serial-for-android-LICENSE.txt", + "jsch-LICENSE.txt" to "jsch-META-INF_LICENSE.txt", "jzlib-LICENSE.txt" to "jsch-META-INF_LICENSE.JZlib.txt", + "jbcrypt-LICENSE.txt" to "jsch-META-INF_LICENSE.jBCrypt.txt", "protobuf-LICENSE.txt" to "protobuf-LICENSE.txt")) { assertEquals(File(root, "docs/licenses/$source").readText(), File(assets, asset).readText(), asset) } + // Unicode License V3 (D32): the asset is a short provenance note followed by the unchanged upstream text. + val unicode = File(root, "docs/licenses/unicode-LICENSE.txt").readText() + assertTrue(unicode.startsWith("UNICODE LICENSE V3"), "docs/licenses/unicode-LICENSE.txt is the upstream text") + assertTrue(File(assets, "unicode-LICENSE.txt").readText().endsWith("\n\n" + unicode), "unicode-LICENSE.txt carries the full licence") // The Bouncy Castle licence is HTML upstream; the asset is the same words without markup. val html = File(root, "docs/licenses/bouncycastle-LICENSE.html").readText().replace(Regex("<[^>]+>"), " ") assertEquals(words(html), words(File(assets, "bouncycastle-LICENSE.txt").readText())) diff --git a/androidApp/src/test/kotlin/cz/netkit/app/wifi/ExportSessionTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/wifi/ExportSessionTest.kt new file mode 100644 index 0000000..3d2935f --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/wifi/ExportSessionTest.kt @@ -0,0 +1,101 @@ +package cz.netkit.app.wifi + +import cz.netkit.shared.wifi.AccessPoint +import cz.netkit.shared.wifi.WalkRecorder +import cz.netkit.shared.wifi.WalkStopReason +import cz.netkit.shared.wifi.WifiAnalyzerState +import cz.netkit.shared.wifi.WifiBand +import cz.netkit.shared.wifi.WifiExportFormat +import cz.netkit.shared.wifi.WifiSecurity +import cz.netkit.shared.wifi.scanExportText +import cz.netkit.shared.wifi.walkExportText +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Codex revize kolo 1: the export flow both ViewModels delegate to — `prepareScanExport` = + * `ExportSession.prepare(scanExportText(state, …))`, `prepareWalkExport` = + * `prepare(walkExportText(log, …))`, `save*Export(uri)` = `ExportSession.save(uri)`. + */ +class ExportSessionTest { + private class FakeStore(var fail: Boolean = false) { + val written = mutableMapOf() + suspend fun write(document: String, text: String): Boolean { if (fail) return false; written[document] = text; return true } + } + + private fun ap(ssid: String) = AccessPoint(ssid, "02:00:00:00:38:01", -50, 2412, channel = 1, band = WifiBand.GHZ_2_4, + widthMhz = 20, security = WifiSecurity.WPA2, standard = "ax", ageMs = 0, locallyAdministered = true) + + @Test fun scanExportWritesTheSnapshotTakenWhenThePickerOpened() = runTest { + val store = FakeStore() + val session = ExportSession(store::write) + var state = WifiAnalyzerState(accessPoints = listOf(ap("Before")), lastUpdatedElapsedMs = 900) + assertTrue(session.prepare(scanExportText(state, WifiExportFormat.CSV, 1_000, 1_000))) + state = state.copy(accessPoints = listOf(ap("After"))) // a new scan arrives while the picker is open + session.save("content://doc/1") + val text = store.written.getValue("content://doc/1") + assertTrue("\"Before\"" in text && "After" !in text) + assertEquals(ExportNotice.SAVED, session.notice.value) + // The prepared text is consumed: a second picker result without prepare fails, writes nothing. + session.save("content://doc/2") + assertEquals(ExportNotice.FAILED, session.notice.value) + assertFalse("content://doc/2" in store.written) + assertEquals("After", state.accessPoints.single().ssid) + } + + @Test fun emptyDatasetDoesNotOpenThePicker() = runTest { + val session = ExportSession(FakeStore()::write) + assertNull(scanExportText(WifiAnalyzerState(), WifiExportFormat.JSON, 0, 0)) + assertFalse(session.prepare(scanExportText(WifiAnalyzerState(), WifiExportFormat.JSON, 0, 0))) + assertNull(session.notice.value) + } + + @Test fun cancelledPickerWritesNothingAndShowsNoNotice() = runTest { + val store = FakeStore() + val session = ExportSession(store::write) + session.prepare("x") + session.save(null) + assertTrue(store.written.isEmpty()) + assertNull(session.notice.value) + // …and the cancelled text is not reused by a later result. + session.save("content://doc/late") + assertEquals(ExportNotice.FAILED, session.notice.value) + } + + @Test fun writeFailureAndLaunchFailureReportFailedAndPrepareClearsTheOldNotice() = runTest { + val store = FakeStore(fail = true) + val session = ExportSession(store::write) + session.prepare("x") + session.save("content://doc/1") + assertEquals(ExportNotice.FAILED, session.notice.value) + store.fail = false + assertTrue(session.prepare("y")) + assertNull(session.notice.value) + session.launchFailed() + assertEquals(ExportNotice.FAILED, session.notice.value) + session.save("content://doc/2") // launch failed: nothing prepared any more + assertTrue(store.written.isEmpty()) + session.dismiss() + assertNull(session.notice.value) + } + + @Test fun walkExportOnlyAfterStop() = runTest { + val store = FakeStore() + val session = ExportSession(store::write) + val recorder = WalkRecorder() + recorder.start(0, 0) + recorder.sample(0, -55, "02:00:00:00:38:0a", 36, 866, 780) + assertFalse(session.prepare(walkExportText(recorder.snapshot(500), WifiExportFormat.CSV)), "still recording") + recorder.stop(1_000, WalkStopReason.USER) + assertTrue(session.prepare(walkExportText(recorder.snapshot(1_000), WifiExportFormat.JSON))) + session.save("content://walk") + assertTrue("\"netkit-wifi-walk\"" in store.written.getValue("content://walk")) + assertEquals(ExportNotice.SAVED, session.notice.value) + session.clear() + assertNull(session.notice.value) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/wifi/SpectrumAxisLabelsTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/wifi/SpectrumAxisLabelsTest.kt new file mode 100644 index 0000000..b5372dc --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/wifi/SpectrumAxisLabelsTest.kt @@ -0,0 +1,50 @@ +package cz.netkit.app.wifi + +import java.io.File +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** Zadání 34: axis labels (bod 6) and the CS/EN texts of the out-of-band and centre-unknown notes. */ +class SpectrumAxisLabelsTest { + @Test fun firstAndLastLabelAlwaysDrawnInnerOnesSkippedOnCollision() { + // Plenty of room: everything is drawn. + assertEquals(listOf(0, 1, 2, 3), spectrumAxisLabelIndices(listOf(0f, 20f, 40f, 60f), List(4) { 10f }, 4f)) + // Narrow chart: labels 10 wide every 12 px with a 4 px gap → every second inner one drops, + // and the inner label that would touch the last one is skipped too; the last is kept. + assertEquals(listOf(0, 2, 4, 7), spectrumAxisLabelIndices((0 until 8).map { it * 12f }, List(8) { 10f }, 4f)) + // Even when the last collides with the first, both edge labels stay. + assertEquals(listOf(0, 2), spectrumAxisLabelIndices(listOf(0f, 3f, 6f), List(3) { 10f }, 4f)) + assertEquals(listOf(0), spectrumAxisLabelIndices(listOf(5f), listOf(10f), 4f)) + assertEquals(emptyList(), spectrumAxisLabelIndices(emptyList(), emptyList(), 4f)) + } + + @Test fun axisLabels24OnPhoneWidthKeep1And14() { + // 2.4 GHz axis 2397–2499 MHz on a 300 px plot, 1–2 digit labels 14 px wide: 1 and 14 are drawn. + val centers = (1..13).map { 2407.0 + it * 5 } + 2484.0 + val starts = centers.map { ((it - 2397.0) / 102.0 * 300.0 - 7.0).toFloat().coerceIn(0f, 286f) } + val drawn = spectrumAxisLabelIndices(starts, List(starts.size) { 14f }, 4f) + assertEquals(0, drawn.first()) + assertEquals(13, drawn.last()) + assertTrue(drawn.zipWithNext().all { (a, b) -> starts[b] >= starts[a] + 14f + 4f || b == 13 }) + } + + @Test fun notesExistInCzechAndEnglish() { + val module = File(".").canonicalFile + val expected = mapOf( + "values" to mapOf( + "wifi_width_center_unknown" to "šířka %1\$d MHz, střed neznámý", + "wifi_spectrum_channel14_out_of_band" to "Kanál 14 je mimo pásmo povolené v EU.", + ), + "values-en" to mapOf( + "wifi_width_center_unknown" to "width %1\$d MHz, centre unknown", + "wifi_spectrum_channel14_out_of_band" to "Channel 14 is outside the band permitted in the EU.", + ), + ) + for ((folder, strings) in expected) { + val xml = File(module, "src/main/res/$folder/wifi_spectrum.xml").readText() + for ((name, value) in strings) assertTrue("$value" in xml, "$folder/$name") + assertTrue("" in xml, "$folder/wifi_width_center_unknown_detail") + } + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/wifi/live/LiveRadioSourceTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/wifi/live/LiveRadioSourceTest.kt index 93b6e60..e295978 100644 --- a/androidApp/src/test/kotlin/cz/netkit/app/wifi/live/LiveRadioSourceTest.kt +++ b/androidApp/src/test/kotlin/cz/netkit/app/wifi/live/LiveRadioSourceTest.kt @@ -1,5 +1,7 @@ package cz.netkit.app.wifi.live +import cz.netkit.shared.wifi.AssociatedLink +import cz.netkit.shared.wifi.mloConnection import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull @@ -37,4 +39,15 @@ class LiveRadioSourceTest { assertNull(liveLinkRate(0)) assertEquals(866, liveLinkRate(866)) } + + @Test fun mloUsesCurrentLinkMetricsAndFallsBackOnlyWhenRadioIsMissing() { + val cached = AssociatedLink(1, 8, 5, 5975, -71, 2) + val current = cached.copy(rssi = -48, state = 3) + fun read(link: AssociatedLink) = mloConnection(listOf(link), null, false, emptyList(), 1000) + + assertEquals(read(current), readLiveMlo(current, cached, ::read)) + assertEquals(read(current), readLiveMlo(current, null, ::read)) + assertEquals(read(cached), readLiveMlo(null, cached, ::read)) + assertNull(readLiveMlo(null, null, ::read)) + } } diff --git a/androidApp/src/test/kotlin/cz/netkit/app/wifi/live/WalkCardTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/wifi/live/WalkCardTest.kt new file mode 100644 index 0000000..1e4af72 --- /dev/null +++ b/androidApp/src/test/kotlin/cz/netkit/app/wifi/live/WalkCardTest.kt @@ -0,0 +1,15 @@ +package cz.netkit.app.wifi.live + +import kotlin.test.Test +import kotlin.test.assertEquals + +class WalkCardTest { + @Test fun durationIsMinutesSecondsOrHoursMinutesSeconds() { + assertEquals("0:00", walkDurationText(0)) + assertEquals("0:00", walkDurationText(-5_000)) + assertEquals("0:59", walkDurationText(59_999)) + assertEquals("5:09", walkDurationText(309_000)) + assertEquals("1:05:09", walkDurationText(3_909_000)) + assertEquals("2:00:00", walkDurationText(7_200_000)) + } +} diff --git a/androidApp/src/test/kotlin/cz/netkit/app/wol/UdpTransportTest.kt b/androidApp/src/test/kotlin/cz/netkit/app/wol/UdpTransportTest.kt index bbc9e8f..6acced0 100644 --- a/androidApp/src/test/kotlin/cz/netkit/app/wol/UdpTransportTest.kt +++ b/androidApp/src/test/kotlin/cz/netkit/app/wol/UdpTransportTest.kt @@ -67,6 +67,33 @@ class UdpTransportTest { assertEquals(address, fake.sentTarget) } + @Test fun guardDecidesAfterDnsAndBindRightBeforeTheWrite() = runTest { + // Revize kolo 3–4: DNS, open and bind happen first; the guard alone decides the write. + val fake = FakePlatform() + var eventsAtGuard: List? = null + val sent = BoundPacketSender(fake, StandardTestDispatcher(testScheduler)) + .sendUdp(Wifi, "host.example", 9009, payload) { _ -> eventsAtGuard = fake.events.toList(); false } + assertFalse(sent) + assertEquals(1, fake.dnsCount) + assertEquals(listOf("wifi", "open", "wifi", "broadcast", "bind"), eventsAtGuard) + assertNull(fake.sentPayload) + assertTrue("close" in fake.events, "socket closed after a refused write") + val allowed = FakePlatform() + assertTrue(BoundPacketSender(allowed, StandardTestDispatcher(testScheduler)).sendUdp(Wifi, "host.example", 9009, payload) { write -> write(); true }) + assertContentEquals(payload, allowed.sentPayload) + } + + @Test fun bindingChangedDuringBindWritesNothing() = runTest { + // The widget's device changes while the socket binds: the guard (run after bind) refuses. + var reservationHeld = true + val fake = FakePlatform().apply { onBind = { reservationHeld = false } } + val sent = BoundPacketSender(fake, StandardTestDispatcher(testScheduler)) + .sendUdp(Wifi, "192.0.2.9", 9009, payload) { write -> if (reservationHeld) { write(); true } else false } + assertFalse(sent) + assertNull(fake.sentPayload) + assertFalse("send" in fake.events) + } + @Test fun hostnameResolvesOnOriginalHandleAndDnsFailureNeverOpensSocket() = runTest { val fake = FakePlatform() BoundPacketSender(fake, StandardTestDispatcher(testScheduler)).sendUdp(Wifi, "host.example", 9009, payload) @@ -158,6 +185,7 @@ class UdpTransportTest { var sentPayload: ByteArray? = null var sentTarget: InetAddress? = null var sentPort = 0 + var onBind: () -> Unit = {} private var checks = 0 override fun isWifi(network: WifiNetworkHandle): Boolean { events += "wifi" @@ -173,7 +201,7 @@ class UdpTransportTest { events += "open" return object : UdpSocket { override fun enableBroadcast() { events += "broadcast" } - override fun bind(network: WifiNetworkHandle) { bound = network; events += "bind" } + override fun bind(network: WifiNetworkHandle) { bound = network; events += "bind"; onBind() } override fun send(target: InetAddress, port: Int, payload: ByteArray) { sentTarget = target if (socketFailure) throw IOException("socket failed") diff --git a/docs/architektura.md b/docs/architektura.md index ef9ebeb..34c4a3e 100644 --- a/docs/architektura.md +++ b/docs/architektura.md @@ -1,9 +1,8 @@ # NetKit — architektura -**Stav 2026-10-26:** popis pracovní implementace oprav M1 na větvi -`codex/m1-opravy`. Napsaný kód není přijetí M1. Buildy, skutečně provedené testy, -známé nedostatky a vazby na SHA APK eviduje report 08 (interní záznam). -Čeká nová nezávislá revize a fyzický test správce. +Základní popis vychází z M1. Životní cyklus terminálu, integrace nástrojů +a navigace odpovídají integrovanému Androidu 2.0.0 k 2. 12. 2026. +Stav testů a požadavky na fyzické zařízení uvádí [testování](testovani.md). ## 1. Moduly @@ -35,7 +34,7 @@ ani Android `Context` nepřecházejí do společné domény; WoL používá nepr **Odchylka od původního návrhu:** společný controller existuje pro WoL. LAN, Wi-Fi a SSH řídí Android ViewModely se `StateFlow`; port na iOS vyžaduje přesun nebo novou implementaci jejich orchestrace a životního cyklu. KMP zde neznamená -hotový multiplatformní backend. OUI databáze není součástí domény ani aplikace. +hotový multiplatformní backend. Offline seznam IEEE OUI je v Android assets. Společný kód přiřazuje výrobce k MAC adrese. ## 3. Síťové cesty @@ -67,12 +66,12 @@ je měření, nikoli vlastnost zaručená architekturou; konkrétní vzorek pat Přepnutí hlavní záložky ruší aktivní LAN/Wi-Fi práci. Rotace zachovává ViewModely. Wi-Fi UI odebírá stav podle lifecycle a časový tick běží pouze při `STARTED`. -SSH při `onStop` přechází do pětiminutové ochranné lhůty -(`SshBackgroundPolicy.BACKGROUND_GRACE_MILLIS`). Samotné otevření pickeru či -správce hesel relaci ani dialog okamžitě nezamítá. Návrat kontroluje vypršení lhůty; -po limitu se relace zavřou. Zavření nastává také explicitně, při ukončení aktivity -nebo `onCleared`. Foreground service není implementovaná; systém může proces ukončit. -Samostatné timeouty připojení a autentizačních výzev dál platí, viz [SSH](funkce/ssh.md). +SSH, Telnet a USB sériová konzole sdílejí jednu neveřejnou službu +`SshSessionService` typu `specialUse`. Při povolených oznámeních udržuje živé relace +na pozadí. Akce „Odpojit vše“ zavře relace všech tří transportů. Spojení vlastní `SshViewModel`. +Služba skončí s poslední relací. Pokud neběží (například po odmítnutí oznámení), +`onStop` spustí pětiminutovou lhůtu. Vypršení kontroluje časovač i návrat do popředí. +Samostatné timeouty připojení a autentizačních výzev platí dál. [SSH](funkce/ssh.md) Terminál serializuje odesílání a slučuje resize s přibližně 100ms prodlevou. Historie používá kompaktní řádky s limitem 8 MiB účtovaných dat na relaci a limitem @@ -105,16 +104,18 @@ nenahrazuje novým klíčem. Export SSH profilů nezahrnuje tajemství ani jejic Silné stránky a meze ochrany, algoritmy SSH i schválená výjimka ISC pro přibalený jBCrypt jsou popsány v [bezpecnost.md](bezpecnost.md) a [zavislosti.md](zavislosti.md). -Manifest deklaruje INTERNET, ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE, -CHANGE_WIFI_STATE, ACCESS_FINE_LOCATION a ACCESS_COARSE_LOCATION. Wi-Fi a location -hardware mají `required=false`. Interní signature oprávnění AndroidX zůstává; +Rozpis síťových, telefonních a polohových oprávnění i trojici oprávnění služby +terminálu uvádí [bezpečnostní dokumentace](bezpecnost.md#2-oprávnění-podle-funkce). +USB host je volitelný. Android uděluje dočasný přístup k vybranému převodníku. +Hardwarové požadavky na Wi-Fi a polohu mají `required=false`. Interní signature oprávnění AndroidX zůstává; jeho přítomnost není veřejné síťové oprávnění. Scan stále vyžaduje přesnou polohu podle použitých Android API; `NEARBY_WIFI_DEVICES` ji zde nenahrazuje, viz [Wi-Fi a zdroje](funkce/wifi-analyzer.md). Žádné nové oprávnění nelze přidat bez odůvodnění. ## 7. Navigace a UI -Čtyři záložky používají Material 3 a společné komponenty `ScreenHeader`, +Pět hlavních cílů používá od šířky 600 dp postranní navigaci. Aktivní terminál na šířku +navigaci skryje. Obrazovky používají Material 3 a společné komponenty `ScreenHeader`, `SectionCard`, `InfoNote`, `StatusBanner`, `EmptyState`, `LabeledValue` a škálu rozestupů 4/8/12/16/24 dp. `MainActivity` drží vybranou záložku a `SaveableStateHolder`; podobrazovky jsou stav Compose, nikoli samostatné navigační @@ -123,8 +124,7 @@ se do saveable stavu neukládají. Texty jsou v resources (výchozí CS a EN). SSH má vlastní `DirectTerminalInput`/`InputConnection` pro přímé odesílání znaků bez lokálního echo a záložní vstup pro vložení. Podporované VT režimy a klávesy -vyjmenovává [SSH](funkce/ssh.md); plný xterm, široké znaky a Unicode combining -nejsou v rozsahu. Ochrana snímků má přepínač, výchozí zapnuto v release a vypnuto +vyjmenovává [SSH](funkce/ssh.md); terminál podporuje široké a kombinující znaky, alternativní obrazovku a truecolor. Ochrana snímků má přepínač, výchozí zapnuto v release a vypnuto v debug. Screenshoty, IME, rotace, 200% písmo a dostupnost se ověřují na konkrétním APK; samotné použití komponent tento test nenahrazuje. @@ -138,9 +138,14 @@ Gradle parametr `netkitTestSuite=wol`. Historické otevřené IME E2E se nezamě s novým důkazem. Postupy a stav jsou v [testování](testovani.md) a reportu 08. Projekt nemá server, analytiku, reklamy, root požadavek, nativní raw sockety, -externí pluginy ani dynamické načítání kódu. Mimo M1 zůstává OUI databáze, -integrace mezi záložkami, SFTP/forwarding/jump host, foreground service, widget, -release podpis a iOS targety. Vydání a přijetí potvrzuje správce až po revizi a telefonu. +externí pluginy ani dynamické načítání kódu. +V Androidu 2.0.0 lze předat nalezené zařízení z LAN do WoL. Widget WoL spouští +probuzení, widget stavu sítě zobrazuje poslední měření. SSH používá JSch pro SFTP, +lokální přesměrování portů, SOCKS5 a ProxyJump. Telnet a USB konzole používají stejný +terminál, USB přes přibalené ovladače `com.hoho.android.usbserial`. +Nastavení spravuje také jazyk aplikace. Přehled sestavuje diagnostický report z dostupných +měření pro ruční sdílení nebo uložení přes SAF. Podpis vydání řeší [distribuce](distribuce.md) +a rozsah iOS popisuje [iOS MVP](ios.md). Uzavírací revize07 odděluje fázi odesílání WoL od zrušitelné kontroly odpovědi; diff --git a/docs/bezpecnost.md b/docs/bezpecnost.md index 1ac8dd5..a8beca7 100644 --- a/docs/bezpecnost.md +++ b/docs/bezpecnost.md @@ -7,7 +7,7 @@ zapisuje sem (se zdrojem a datem). Aplikace nemá server, účty ani telemetrii. | Hrozba | Dopad | Opatření | |---|---|---| -| Ztráta/odcizení telefonu | únik SSH klíčů a hesel | klíče a hesla jen v šifrovaném úložišti vázaném na Keystore; zamčený telefon; biometrika pro klíč v M2 | +| Ztráta/odcizení telefonu | únik SSH klíčů a hesel | klíče a hesla jen v šifrovaném úložišti vázaném na Keystore; zamčený telefon a volitelný zámek SSH podle zadání 50 | | Škodlivá aplikace na telefonu | čtení dat NetKitu | `allowBackup=false`, data v soukromém úložišti aplikace, žádné exportované komponenty bez důvodu, žádné světově čitelné soubory | | MITM při SSH | únik přihlášení | ověření host key (TOFU, tvrdé varování při změně), moderní algoritmy | | Zneužití skeneru | právní a etické riziko | výchozí jen vlastní podsíť, potvrzení pro cizí rozsahy, žádný brute force/exploit/flood | @@ -22,18 +22,21 @@ vyplňuje implementátor. | Oprávnění | Funkce | Proč | Stav | |---|---|---|---| -| `INTERNET` | WoL, LAN, SSH, rychlostní test, Přehled | UDP magic packet, síťové sondy, DNS, SSH transport; M2: HTTPS/WSS rychlostního testu; M4: veřejná IP (HTTPS na `1.1.1.1`) a poskytovatel (DNS TXT); F3: kontrola aktualizací (HTTPS GET `latest.json` z webu projektu), žádné nové oprávnění | M1: přidáno | +| `INTERNET` | WoL, LAN, SSH, rychlostní test, Přehled | UDP magic packet, síťové sondy, DNS, SSH a uživatelem vyžádaný Telnet; M2: HTTPS/WSS rychlostního testu; M4: veřejná IP (HTTPS na `1.1.1.1`) a poskytovatel (DNS TXT); F3: kontrola aktualizací (HTTPS GET `latest.json` z webu projektu), žádné nové oprávnění | M1: přidáno | | `ACCESS_WIFI_STATE` | Wi-Fi analyzér | stav a výsledky `WifiManager`; WoL samotný jej nepotřebuje | M1c: přidáno | | `ACCESS_NETWORK_STATE` | WoL, LAN, Wi-Fi | výběr `Network` a `LinkProperties`, shodná síť pro DNS i soket | M1: přidáno | | `cz.netkit.app.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION` | interní AndroidX ochrana | vlastní `signature` oprávnění pro neexportované dynamické receivery na API 29–32 | M1a: vráceno po schválení správce v revizi 02 | | `CHANGE_WIFI_STATE` | Wi-Fi | uživatelem vyžádané `startScan` | M1c: přidáno | -| `ACCESS_FINE_LOCATION` | Wi-Fi | `startScan` a výsledky skenu vyžadují přesnou polohu i na nových API; runtime žádost až po akci uživatele | M1c: přidáno | +| `ACCESS_FINE_LOCATION` | Wi-Fi | `startScan` a výsledky skenu vyžadují přesnou polohu i na nových API; runtime žádost až po akci uživatele. Od D31 i podmínka „Detailu buňky“ (`requestCellInfoUpdate`), viz § Detail buňky | M1c: přidáno; zadání 53: nové použití, žádné nové oprávnění | | `ACCESS_COARSE_LOCATION` | Wi-Fi | na Androidu 12+ se žádá společně s FINE; pouze přibližná poloha scan nepovolí | M1c: přidáno | | `NEARBY_WIFI_DEVICES` | Wi-Fi | použité scan API potřebuje FINE, toto oprávnění jej nenahrazuje | nepřidáno | | `CHANGE_WIFI_MULTICAST_STATE` | LAN | jen pro `WifiManager.MulticastLock` (příjem multicastu). Identifikace zařízení (M2) posílá mDNS a SSDP dotazy z efemérního portu a odpovědi přijímá unicastem (mDNS legacy unicast, RFC 6762 §6.7; SSDP odpověď na M-SEARCH), takže zámek nepotřebuje; nástroj Služby používá `NsdManager` (API 34+) | nepřidáno (2026-10-26 ověřeno pro identifikaci) | -| `READ_PHONE_STATE` | Přehled: mobilní síť | obě SIM (`getActiveSubscriptionInfoList`), typ sítě (`getDataNetworkType`, `getVoiceNetworkType`) a změna datové SIM; runtime dialog až z karty mobilní sítě (rozhodnutí O-4), viz § Mobilní síť | M4: přidáno | +| `READ_PHONE_STATE` | Přehled: mobilní síť | obě SIM (`getActiveSubscriptionInfoList`), typ sítě (`getDataNetworkType`, `getVoiceNetworkType`) a změna datové SIM; runtime dialog až z karty mobilní sítě (rozhodnutí O-4), viz § Mobilní síť; od D31 i podmínka „Detailu buňky“ | M4: přidáno; zadání 53: nové použití | +| `USE_BIOMETRIC` | Zámek SSH | systémové ověření uživatele, normální oprávnění bez runtime žádosti. Kompatibilní `USE_FINGERPRINT` z AndroidX odstraňuje manifest aplikace od API 29. | zadání 50: přidáno | | `READ_BASIC_PHONE_STATE` | Přehled: mobilní síť | API 33+, `normal` bez dialogu: jen `getDataNetworkType`/`getVoiceNetworkType` u datové SIM bez `READ_PHONE_STATE` | M4: přidáno | -| `POST_NOTIFICATIONS`, `FOREGROUND_SERVICE_*` | SSH relace na pozadí | **není v M1**; samostatné rozhodnutí v M2 | — | +| `FOREGROUND_SERVICE` | SSH (i SFTP), Telnet a USB konzole na pozadí | vlastní služba `SshSessionService` (D30) pro všechny terminálové relace; dříve odebrané z WorkManageru (zadání 36), viz § SSH na pozadí a § Telnet a USB konzole | zadání 42/44: přidáno | +| `FOREGROUND_SERVICE_SPECIAL_USE` | interaktivní terminál (SSH, Telnet, USB) | typ služby `specialUse` s `PROPERTY_SPECIAL_USE_FGS_SUBTYPE` (Android 14+ vyžaduje oprávnění k typu), viz § SSH na pozadí | zadání 42/44: přidáno | +| `POST_NOTIFICATIONS` | oznámení relací | trvalé oznámení služby s „Odpojit vše“ (API 33+ runtime); dotaz až při prvním připojení, při odmítnutí platí limit 5 min | zadání 42/44: přidáno | Nikdy nepřidávat (`READ_PHONE_STATE` je od M4 výjimka podle rozhodnutí O-4, viz § Mobilní síť): `READ_PHONE_NUMBERS`, `READ_PRIVILEGED_PHONE_STATE`, `READ_CONTACTS`, `QUERY_ALL_PACKAGES`, `MANAGE_EXTERNAL_STORAGE`, `ACCESS_BACKGROUND_LOCATION`, `REQUEST_INSTALL_PACKAGES`, `RECORD_AUDIO`, kamera, SMS. @@ -52,9 +55,51 @@ ruší DNS požadavek a uzavírá soket. Test emulátoru neprokazuje směrován - `android:allowBackup="false"`, `android:dataExtractionRules` vylučuje všechna data; `fullBackupContent` neposkytuje nic. - `android:usesCleartextTraffic="false"` a `networkSecurityConfig` bez výjimek. (SSH, WoL, ping - a TCP sondy nejsou HTTP a tuto politiku neovlivňují. Rychlostní test od M2 používá výhradně - HTTPS/WSS, viz § Rychlostní test.) Jediné nešifrované HTTP, které aplikace sama dělá, - je stažení UPnP popisu zařízení — viz výjimka níže; konfigurace se kvůli ní **nemění**. + a TCP sondy nejsou HTTP a tuto politiku neovlivňují. LibreSpeed a NDT7 používají + HTTPS/WSS. iperf3 používá přímo TCP, viz § Rychlostní test.) Nešifrované HTTP, které aplikace sama dělá, + je stažení UPnP popisu zařízení (viz výjimka níže) a výslovně spuštěná diagnostika Web/TLS + (viz § Ruční diagnostika); konfigurace se kvůli nim **nemění**. + +### Ruční diagnostika DNS, Web/TLS a RDAP + +Systémový resolver dostane jméno a typ na aktivní síti. Samostatné tlačítko s upozorněním +povoluje jeden dodatečný dotaz na podkladové Wi-Fi, kde může jméno uniknout mimo VPN. +DNS parser přijímá nejvýše 65 535 B, 64 otázek a 128 záznamů, u jmen nejvýše 32 skoků. + +Web/TLS používá DNS a socket vybrané aktivní sítě bez proxy. Přijímá jen HTTP(S) URL +bez přihlašovacích údajů a fragmentu. Před prvním spojením s hostem vybere z DNS odpovědi +pouze veřejné adresy, pokud jsou k dispozici. Selhání veřejného spojení tak nemůže poslat +zadanou cestu na router. Když jméno vrátí jen neveřejné adresy, sonda ukáže jméno a jednu +IP k potvrzení. Po souhlasu znovu ověří DNS a použije jen schválenou adresu. Změna IP +vyžádá nové rozhodnutí. Výslovně zadaný místní IP literál mimo fake-IP trasu lze měřit přímo. + +Pro NAT64 se veřejnost trasy určuje podle vložené IPv4. Sonda zná `64:ff9b::/96` a od +Android API 30 také překladový prefix vybrané sítě. Na API 29 systém vlastní prefix +nezpřístupňuje. Před spojením přes `198.18.0.0/15` (fake-IP) sonda vyžádá souhlas +a upozorní, že skutečný cíl za proxy nelze ověřit. Další krok na témž hostu smí znovu +použít přesnou místní nebo fake-IP adresu předchozího spojení. Pokud při přesměrování +na jiné jméno vrátí DNS pouze fake-IP adresy, sonda vyžádá nový souhlas i pro shodnou IP. +Ostatní přesměrování na jiný host vyžadují výhradně veřejné adresy. Kontrola trasy +se provádí i při změně schématu a opakování přes GET. +HTTP i HTTPS dostanou pouze povolené adresy, hostname zůstává pro Host, SNI a ověření +certifikátu. Každý dokončený krok ukáže IP použitého spojení. + +Sonda sleduje nejvýše pět přesměrování. Port smí zůstat stejný nebo přejít na 80 či 443. +Po první změně originu (schéma, host nebo port) používá sonda už jen HEAD. Pokud dostane +405/501, vysvětlí vynechání GET. V tomto případě i při blokaci cíle lze URL předvyplnit +pro nové měření. Odeslání vyžaduje samostatné klepnutí na Spustit. + +Každý kontaktovaný server vidí identifikátor `NetKit/` a požadovanou cestu včetně +parametrů, které mohou obsahovat citlivé údaje. HTTP používá vyhrazenou sondu HTTP/1.x +přes socket s limitem hlaviček 64 KiB. Nešifrovanou URL vidí i uzly po cestě. +Po hlavičkách klient odpověď zavře, tělo nepoužívá. HTTPS používá platformní důvěru +a kontrolu jména v OkHttp. Selhání se vrátí uživateli bez opakování s jiným trust managerem. + +RDAP jde po klepnutí přes HTTPS na rdap.org. Před odesláním se kontroluje veřejný +číselný cíl a nastavení zjišťování veřejné IP. Každé přesměrování znovu kontroluje vypínač +a povolí jen HTTPS na standardním portu známého RIR. Odpověď je omezená na 256 KiB a hloubku +16. U těchto nástrojů se do historie neukládá vstup, certifikáty ani kontakty z registru. +Přehled příjemců je v [evidenci toků](public/data-toky.md#d23). ### Výjimka: UPnP popis zařízení přes ruční HTTP/1.0 (M2, 2026-10-26) @@ -62,7 +107,7 @@ UPnP popis (`LOCATION` z odpovědi SSDP) existuje jen jako nešifrované `http:/ v LAN; TLS tam není k dispozici. Místo povolení cleartextu v `networkSecurityConfig` (to by platilo pro celou aplikaci a každou HTTP knihovnu) jde jediný požadavek ručně psaným `GET … HTTP/1.0` přes holý `Socket` z `Network.socketFactory` vybrané Wi-Fi. Politika -`cleartextTrafficPermitted="false"` tak dál chrání veškerý ostatní provoz aplikace; tento +`cleartextTrafficPermitted="false"` platí pro HTTP knihovny aplikace; tento socket ji záměrně obchází a je proto omezený takto (kód `UpnpProbe.describe`, pravidla `upnpDescriptionTarget` / `parseHttpResponseBody` / `parseUpnpDescription` v commonMain): @@ -338,10 +383,20 @@ Podrobnosti metody: [speedtest.md](funkce/speedtest.md). test odmítne; ztráta nebo výměna sítě během testu ho ukončí (`NETWORK_LOST`). Klient má `Proxy.NO_PROXY`: výchozí `ProxySelector` odpovídá výchozí síti, ne vázané; síť dostupná jen přes HTTP proxy test neprojde. Metoda: [speedtest.md](funkce/speedtest.md) §M4. -- **Cleartext zakázán.** Vlastní LibreSpeed URL projde `checkLibreSpeedUrl`: jen `https://` +- **HTTPS/WSS.** Vlastní LibreSpeed URL projde `checkLibreSpeedUrl`: jen `https://` (bez schématu se doplní https), bez jména/hesla, query, fragmentu a `..`. NDT7 přijímá z locate jen `wss://` na `*.measurement-lab.org`; `ws://` varianty se zahodí. Redirect locate API nesmí přejít z https na http. `network_security_config` beze změny. +- **Vlastní iperf3 server (Android).** Ruční start může vytížit celou trasu. Jméno se jednou přeloží + v aktivní síti. Před TCP spojením se na výslednou IP uplatní pravidla potvrzení cíle LAN. + Veřejný cíl, privátní adresa mimo připojenou IPv4 podsíť, IPv6 a neznámý prefix vyžadují + souhlas pro tento běh. Dialog ukazuje číselnou adresu a port. Kontrolní i datové sokety se připojí + ke stejné IP přes stejnou `Network`. Přechod na jinou výchozí síť měření zruší. + Protokol přenáší parametry, náhodný testovací obsah a výsledky otevřeným TCP. Cookie spojuje + streamy jednoho běhu. Server ani klient se jí neověřují. Na nedůvěryhodné trase lze měření + odposlechnout nebo pozměnit. Klient neposílá hesla ani klíče. + Limit je 8 streamů, 30 s, 10 s na řídicí krok a 64 KiB na JSON s kontrolou hloubky před dekódováním. + Funkce používá stávající oprávnění `INTERNET` a `ACCESS_NETWORK_STATE`. - **Souhlas M-Lab.** M-Lab ukládá a zveřejňuje každý NDT7 test jako otevřená data včetně veřejné IP klienta. Před prvním NDT7 testem aplikace zobrazí jednorázové upozornění; až po „Rozumím, spustit“ uloží čas potvrzení (`ndt7ConsentMs`) a test spustí. „Zpět“ nic @@ -357,7 +412,7 @@ Podrobnosti metody: [speedtest.md](funkce/speedtest.md). z testu nepíše. - **Úložiště.** `noBackupFilesDir/speedtest.json` (atomický zápis přes dočasný soubor): posledních 20 výsledků (rychlosti, latence, název serveru, SSID, frekvence, RSSI, PHY), - čas souhlasu M-Lab a vlastní URL. Mimo zálohu (`allowBackup=false` a no-backup adresář). + čas souhlasu M-Lab, vlastní URL a poslední uživatelem zadaný iperf3 host a port. Mimo zálohu (`allowBackup=false` a no-backup adresář). Poškozený soubor → výchozí stav a varování v UI, další zápis ho nahradí. - **Zdroje a zátěž.** Paměť ohraničená: těla odpovědí čte 64KiB buffer a zahazuje, upload opakuje 1MiB náhodný payload, NDT7 upload drží frontu OkHttp pod ~2× velikost @@ -397,9 +452,9 @@ jako WiFiman. Implementace: `androidApp/.../cellular/CellularMonitor.kt`, čist - **Co se nikdy nečte ani nevolá.** Telefonní čísla (`getLine1Number`, `SubscriptionInfo.getNumber`, `SubscriptionManager.getPhoneNumber`), IMEI/MEID (`getImei`, `getDeviceId`), IMSI (`getSubscriberId`), ICCID (`getSimSerialNumber`, `SubscriptionInfo.getIccId`), MCC/MNC, - Cell ID, TAC/LAC, PCI, kanál ani seznam buněk (`getAllCellInfo`, `requestCellInfoUpdate`), - stav hovorů a historie. Nic z mobilní karty se neukládá na disk ani neposílá ven; do logcatu - se nepíše. + stav hovorů a historie. Cell ID, TAC, PCI, kanál a seznam buněk čte od D31 jen rozbalený + „Detail buňky“ (§ Detail buňky níže), monitor karty je nečte. Nic z mobilní karty se neukládá + na disk ani neposílá ven; do logcatu se nepíše. - **Poloha.** Monitor polohu nežádá. S `ACCESS_FINE_LOCATION` (už je kvůli Wi-Fi) vrací `ServiceState` i jméno operátora ze sítě; bez polohy ho Android vynechá a použije se jméno z `getNetworkOperatorName`/SIM. `locationPermission` ve stavu je jen informace pro UI. @@ -414,6 +469,41 @@ jako WiFiman. Implementace: `androidApp/.../cellular/CellularMonitor.kt`, čist [TelephonyCallback.ServiceStateListener](https://developer.android.com/reference/android/telephony/TelephonyCallback.ServiceStateListener), [PhoneStateListener.LISTEN_DISPLAY_INFO_CHANGED](https://developer.android.com/reference/android/telephony/PhoneStateListener#LISTEN_DISPLAY_INFO_CHANGED). +### Detail buňky (zadání 53, D31, 2026-12-01) + +Rozhodnutí správce D31 mění dřívější „seznam buněk se nečte“: karta mobilní sítě má pro každou +SIM rozbalitelný „Detail buňky“ (pásmo, EARFCN/NR-ARFCN, PCI, ECI/NCI, TAC, šířka kanálu, timing +advance, RSRP/RSRQ/SINR obsluhující buňky a až 16 sousedních buněk). Kód +`androidApp/.../cellular/CellInfoReader.kt`, `CellDetailViewModel.kt`, UI +`androidApp/.../overview/CellDetailSection.kt`, logika `shared/.../cellular/CellDetail.kt`. + +- **Žádné nové oprávnění.** `TelephonyManager.requestCellInfoUpdate` (API 29+) vyžaduje + `ACCESS_FINE_LOCATION` (už je kvůli Wi-Fi); zadání navíc váže detail na `READ_PHONE_STATE` + (O-4, už je kvůli obou SIM). Detail se načte jen s **oběma už udělenými** oprávněními; bez nich + rozbalený detail vysvětlí proč a nabídne stávající toky (dialog polohy jako u Wi-Fi, dialog + telefonu jako „Zobrazit obě SIM“, po trvalém odmítnutí nastavení aplikace). Sám se neptá. +- **Proč je to citlivé.** Cell ID (ECI/NCI) s TAC a PLMN jde ve veřejných databázích převést + na polohu s přesností stovek metrů; PCI, ARFCN a timing advance polohu dál upřesňují. Proto + **jen lokálně**: data žijí jen ve stavu `CellDetailViewModel` (paměť procesu) a v UI; + nic se neukládá (DataStore, soubor, `SavedStateHandle`, `rememberSaveable` drží jen příznak + rozbalení), neexportuje, nesdílí, neposílá ani nepíše do logcatu. Sbalení, odscrollování + nebo pauza aplikace stav dané SIM zahodí. MCC/MNC buňky se nečtou. +- **Diagnostický report (zadání 47) údaje o buňkách NEobsahuje.** Detail je v samostatném + `CellDetailViewModel`, ne ve `WifiLiveState`/`CellularState`, ze kterých se čte Přehled + a rychlostní test; report ani export tento ViewModel nečte. Revize 47 to má ověřit. +- **Kdy se čte.** Jen když je rozbalený detail SIM na obrazovce a aplikace je v popředí + (`LifecycleResumeEffect` → `show`/`hide`), každá SIM nejvýš jednou za 5 s + (`cellDetailSchedule`), požadavek s limitem 4 s a zrušitelný. `getAllCellInfo` se nepoužívá + (míchá všechna rádia a pro target API 29+ vrací cache). +- **Co se nečte ani tady.** Telefonní čísla, IMEI, IMSI, ICCID, MCC/MNC, seznam hovorů, + `PhysicalChannelConfig` (`READ_PRECISE_PHONE_STATE` je privilegované). +- **Zdroje (ověřeno 2026-12-01):** + [TelephonyManager.requestCellInfoUpdate](https://developer.android.com/reference/android/telephony/TelephonyManager#requestCellInfoUpdate(java.util.concurrent.Executor,%20android.telephony.TelephonyManager.CellInfoCallback)), + [TelephonyManager.CellInfoCallback](https://developer.android.com/reference/android/telephony/TelephonyManager.CellInfoCallback), + [CellInfo](https://developer.android.com/reference/android/telephony/CellInfo), + [CellIdentityLte](https://developer.android.com/reference/android/telephony/CellIdentityLte), + [CellIdentityNr](https://developer.android.com/reference/android/telephony/CellIdentityNr). + ## Veřejná IP a poskytovatel (M4, 2026-10-27) Rozhodnutí správce O-1 (interní pracovní záznam F5): karta cesty v Přehledu ukáže veřejnou IP @@ -461,9 +551,9 @@ na bezpečnost a oprávnění: - **Co appka posílá ven (podklad pro privacy policy a Data safety).** DNS dotazy a sondy do cíle, který uživatel zadal; WoL a SSH jen na uživatelem zadané cíle; speedtest: LibreSpeed (uživatelem zvolený server, preset `rychlost.zelina.eu`) a M-Lab (`locate.measurementlab.net`, NDT7), kterým je vidět - veřejná IP; Přehled: Cloudflare `cdn-cgi/trace` a DNS TXT na `asn.cymru.com` (veřejná IP, vypínač, + veřejná IP; iperf3 posílá testovací provoz na uživatelem zadaný server; Přehled: Cloudflare `cdn-cgi/trace` a DNS TXT na `asn.cymru.com` (veřejná IP, vypínač, sekce Veřejná IP a poskytovatel výše); kontrola aktualizací: `GET latest.json` z webu projektu (IP, - čas, User-Agent s verzí; vypínač, sekce Kontrola aktualizací); UPnP popis zařízení přes nešifrované HTTP v LAN (viz výjimka v §3). Aplikace nemá + čas, User-Agent s verzí; vypínač, sekce Kontrola aktualizací); UPnP popis zařízení přes nešifrované HTTP v LAN (viz výjimka v §3). Ručně spuštěná diagnostika v §3 přidává webové cíle včetně přesměrování, RDAP a volitelný druhý resolver. Aplikace nemá telemetrii ani účty. **Nesmí tvrdit „nic neopouští zařízení“.** - **Co se ukládá lokálně.** DataStore (WoL, SSH metadata, uživatelé, cíle, příkazy, host keys), SSH tajemství AES-GCM v Android Keystore v no-backup úložišti, souhlasy LAN v SharedPreferences, @@ -509,7 +599,8 @@ logika `shared/.../update/UpdateInfo.kt` a `UpdateFetch.kt` (`nextRedirect`, `ch během čekajícího startu může připravit dialog. Dokončený pokus nebo použití cache start spotřebuje. Běžící dotaz se ruší při `onStop` a vypnutí vypínače. Ručně „Zkontrolovat teď“ v O aplikaci zůstává bez intervalu, i při vypnutém vypínači. Vypínač blokuje automatické kontroly, - dialog i kartu. Nic neběží na pozadí, žádný `WorkManager` ani služba. Dialog jen při + dialog i kartu. Kontrola aktualizací nepoužívá `WorkManager` ani službu; na pozadí běží jen aktualizace + WoL widgetu po akci uživatele (Glance přes WorkManager, zadání 36, § Zkratky, dlaždice a WoL widget). Dialog jen při kompatibilní dostupné verzi, bez chyby kontroly; Zavřít platí po celý proces, Nepřipomínat tuto verzi ukládá dosavadní skryté `versionCode`. - **Transport.** HTTPS přes výchozí síť a systémové nastavení proxy, certifikát ověřuje OkHttp proti @@ -617,3 +708,452 @@ Zdroje: [Keychain accessibility](https://developer.apple.com/documentation/secur [schránka localOnly](https://developer.apple.com/documentation/uikit/uipasteboard/optionskey/localonly), [NIOSSH 0.15.1](https://github.com/apple/swift-nio-ssh/tree/0.15.1). Stav testů a omezení jsou v [ios.md §10](ios.md#10-ssh-klient-a-terminál-p2-2026-10-31). + +## LAN rozšíření: IPv6, UDP sondy, SecureOn (zadání 39, 2026-12-01) + +**Žádné nové oprávnění ani závislost.** Vše jede přes stávající `INTERNET` a +`ACCESS_NETWORK_STATE`, sockety vázané na vybranou síť (`Network.bindSocket`). + +- **Info o síti** čte jen `LinkProperties` aktivní Wi-Fi (adresy, brána, DNS, doména hledání, + DHCP server na API 30+, MTU). Neodchází žádný paket. Hodnoty jsou nedůvěryhodné (DHCP/RA + je může nastavit kdokoli v síti): validují se jako číselné adresy / DNS jména, sanitizují a + na řádek je nejvýš 8 hodnot (`lanNetworkInfoRows`). +- **IPv6 v nástrojích** jen pro jeden cíl (ping, kontrola portů TCP, DNS A/AAAA). **Discovery + IPv6 podsítě neexistuje.** Potvrzení cíle platí stejně jako u IPv4: link-local a ULA/globální + adresa v on-link prefixu Wi-Fi bez otázky, ostatní (včetně `::1` a cizích prefixů) s + potvrzením; vše mimo link-local/ULA/loopback se navíc hlásí jako neprivátní. Link-local se + posílá jen se scope rozhraní vybrané trasy; zadaná zóna jiného rozhraní se odmítne. Ping + používá neprivilegovaný ICMPv6 datagram socket (`IPPROTO_ICMPV6`), traceroute a hledání + MTU zůstávají IPv4. +- **UDP sondy „Identifikovat služby“** (SNMP v2c, NTP, DNS `version.bind`) se spouští jen + ručně klepnutím v detailu jednoho zařízení z vlastního rozsahu (stejná kontrola jako u + portů: `targetConfirmationReasons(/32, vlastní podsíť)` musí být prázdné). Každá sonda nejvýš + 2 datagramy po 1,5 s, žádné hromadné ani periodické odesílání. DNS dotaz jde jen hostu, který + je DNS serverem Wi-Fi nebo má otevřený TCP 53 z kontroly portů. Odpovědi parsují ohraničené + parsery v `commonMain` (SNMP ≤ 4096 B, definitní délky, hloubka ≤ 8; NTP ≤ 1024 B; DNS ≤ 9000 B + se stávajícím kodekem), přijímají se jen z připojeného cíle a jen se shodným request ID / + nonce. Texty se sanitizují. +- **SNMP komunita je tajemství.** Pole je maskované (`PasswordVisualTransformation`, + klávesnice typu heslo bez autokorekce), výchozí prázdné; prázdné pole SNMP přeskočí — + aplikace nikdy nezkouší výchozí komunity typu `public` (to by bylo hádání přístupů). Hodnota + žije jen v kompozici (`remember`, ne `rememberSaveable` → nedostane se do saved-state + bundlu), do ViewModelu jde jen jako argument jednoho běhu, není ve stavu, logu ani exportu a + bajtové pole se po běhu přepíše nulami (best effort; `String` v paměti JVM nejde spolehlivě + vymazat). Agent se špatnou komunitou mlčí, výsledek je „neodpovídá“. +- **WoL SecureOn heslo** (4 nebo 6 B za magic packetem) je tajemství: **není součástí + `WolDevice`**, takže se strukturálně nedostane do JSON ani CSV exportu (sloupec `secure_on` + Webb CSV zůstává prázdný) a import JSON s polem `secureOn` odmítne jako neznámé pole. Ukládá + se šifrovaně přes `AndroidSecretStore` (AES-GCM, nevyexportovatelný klíč v Android Keystore, + StrongBox když je, `noBackupFilesDir`) ve vlastním jmenném prostoru `wol` (alias + `netkit.wol.aes.v1`), jako jeden šifrovaný slovník ID → (heslo, vazba na MAC + cíl + port). Heslo se + odešle jen zařízení se shodnou vazbou; import nahrazující zařízení heslo jeho ID po uložení seznamu + zahodí (revize 39/1). Chráněné zařízení, jehož heslo nejde použít, se neprobudí vůbec — nikdy + nejde paket bez hesla ani s heslem jiné karty (fail-closed, revize 39/2). Trvalý příznak `secureOnRequired` v seznamu + zařízení (netajný) drží ochranu i při ztrátě záznamu; widget ukládá jen hash konfigurace, ne cíl (revize 39/4). Formulář heslo nikdy nenačítá + zpět (jen příznak „uloženo“), pole je maskované a `WolDeviceDraft.toString()` ho maskuje. + Nečitelné úložiště (např. ztracený klíč) zablokuje odeslání u zařízení, které heslo mít + může (`SECURE_ON_UNAVAILABLE`), místo aby paket odešel bez hesla; nové zadání hesla úložiště nahradí. Heslo jde po síti + v otevřené podobě (tak SecureOn funguje): chrání jen proti náhodnému probuzení, ne proti + odposlechu v LAN. + +## Zkratky, dlaždice a WoL widget (zadání 36, 2026-12-01) + +Žádné nové runtime ani manifestové oprávnění. WorkManager (tranzitivně z Glance) deklaruje +`WAKE_LOCK`, `RECEIVE_BOOT_COMPLETED` a `FOREGROUND_SERVICE`; hlavní manifest je odebírá +(`tools:node="remove"`), protože NetKit nespouští práci na popředí ani po startu systému a Glance +session worker je nepotřebuje (zdroje v [zavislosti.md §11](zavislosti.md)). **Od zadání 42** se +odebírají jen `WAKE_LOCK` a `RECEIVE_BOOT_COMPLETED`; `FOREGROUND_SERVICE` je vlastní oprávnění +aplikace pro službu terminálových relací SSH, Telnet a USB (§ SSH na pozadí a SFTP, § Telnet a USB konzole). WorkManager ho dál nepoužívá +(`ForegroundInfo` ani expedited práce; `ManifestExportsTest` hlídá, že typ služby na popředí má jen +`SshSessionService`). Seznam oprávnění +a exportovaných komponent hlídá unit test `ManifestExportsTest` nad **sloučenými** manifesty, včetně knihovních +komponent. Manifesty jsou deklarované vstupy každé unit test úlohy (artefakt AGP `MERGED_MANIFEST`): debug +a dev vždy, release s `-PnetkitRequireReleaseManifest=true` (release workflow), kdy chybějící manifest test shodí. + +**Exportované komponenty a jejich ochrana** (sloučený manifest debug, dev a release, revize kolo 1): + +| Komponenta | Proč exportovaná | Ochrana | +|---|---|---| +| `MainActivity` | spouštěč; navigace ze zkratek, dlaždice a widgetu | explicitní intent s akcí `cz.netkit.app.action.OPEN` a jediným extra s cílem z whitelistu (`signal`, `spectrum`, `lan_tools/`, `ssh_profile/`, `wol_device/`); SSH ID je aplikací generované UUID (i u importu), WoL nese jen neprůhledný klíč zařízení (16 hex, FNV-1a z ID, MAC a času vytvoření), nikdy ID ze souboru, které může vypadat jako hostname nebo IP; záznam musí existovat, jinak výchozí záložka; v intentu nikdy host, MAC, příkaz ani heslo. Nic se nespustí bez klepnutí: SSH profil otevře obvyklé potvrzení připojení, WoL zařízení se jen zvýrazní. Pro akci `OPEN` není intent filter (implicitní intenty ji nenajdou). | +| `tile.SignalTileService` | dlaždice rychlého nastavení | `permission=BIND_QUICK_SETTINGS_TILE` (váže jen systémové UI), filtr `QS_TILE`; klepnutí jen otevře Přehled (na zamčené obrazovce až po odemčení, `unlockAndRun`); dlaždice nezobrazuje SSID, IP ani jiná data | +| `wol.widget.WolWidgetConfigActivity` | spouštěč ji volá přes `APPWIDGET_CONFIGURE` | ID widgetu, které nepatří `WolWidgetReceiver`, aktivitu hned zavře; zařízení vybírá uživatel, nic se neposílá | +| `androidx.glance.appwidget.GlanceRemoteViewsService` (knihovna) | seznamy ve widgetech | `BIND_REMOTEVIEWS` (jen systém) | +| `androidx.work.impl.background.systemjob.SystemJobService` (knihovna) | JobScheduler spouští práci Glance | `BIND_JOB_SERVICE` (jen systém) | + +`wol.widget.WolWidgetReceiver` je od revize kola 1 **neexportovaný** (`exported=false`): AppWidget +broadcasty posílá systém, který je doručí i neexportovanému receiveru (dokumentace Glance „Declare a widget +in the manifest“ ho tak deklaruje, , +přečteno 2026-12-01); cizí aplikace tak nemůže vyvolat zděděné obsluhy `GlanceAppWidgetReceiver` +(např. `DEBUG_UPDATE` s ID z intentu). Přidání, aktualizace a klepnutí ověřeny na emulátoru API 35. +Probuzení jde výhradně přes vlastní neexportovaný `wol.widget.WolWidgetWakeReceiver` (bez intent filtru) +explicitním broadcastem z `PendingIntent` widgetu (revize kola 3, dříve `actionRunCallback` Glance). +`androidx.work.impl.diagnostics.DiagnosticsReceiver` (exportovaný, chráněný `DUMP`) je z manifestu +odebrán. Neexportované knihovní komponenty (trampolíny a receivery Glance, `SystemForegroundService`, +`RescheduleReceiver` WorkManageru) zůstávají beze změny. + +Další služby z manifestů knihoven přidaných s widgety (kontrola proti AAR 2026-12-02): + +| Služba | Účel a přístup | +|---|---| +| `androidx.core.widget.RemoteViewsCompatService` | Adaptér kolekcí RemoteViews pro starší verze Androidu. Manifest modulu Core RemoteViews nemá intent filter ani explicitní export, služba je tedy interní. Deklaruje také `BIND_REMOTEVIEWS`. | +| `androidx.room.MultiInstanceInvalidationService` | Interní služba Room pro oznámení změn databáze mezi jejími instancemi, `exported=false`. | +| `androidx.work.impl.foreground.SystemForegroundService` | Interní služba WorkManageru pro práci na popředí, `exported=false`. Aktualizace widgetů tento režim nepoužívají. | + +**Data na ploše a v liště.** Widget ukazuje jen název zařízení, tlačítko a stav („Odesláno HH:MM“, +„Není Wi-Fi“, „Zařízení smazáno“); MAC ani cíl paketu ne. Stav widgetu (ID a klíč zařízení, název, stav, čas, token rezervace) +leží v soukromém úložišti aplikace (Glance preferences, `allowBackup=false`). Popisek pinned zkratky je +název profilu nebo zařízení, který zvolil uživatel (pokud v něm uvede hostname, bude na ploše). +Dlaždice žádná data nezobrazuje: na zamčené obrazovce by unikla a SSID by bez polohy na pozadí stejně +nedostala (WifiInfo bez viditelné aktivity vyžaduje polohu na pozadí; [Android: poloha na pozadí](https://developer.android.com/develop/sensors-and-location/location/background)). `ACCESS_BACKGROUND_LOCATION` zůstává zakázané. + +**Běh na pozadí.** Widget nemá periodickou aktualizaci (`updatePeriodMillis=0`). Překresluje se po +klepnutí uživatele a po změně seznamu WoL zařízení v aplikaci. Odeslání z widgetu běží v receiveru +`WolWidgetWakeReceiver` (goAsync) se společným limitem 8 s od vstupu do akce (čtení stavu, načtení zařízení, +SENDING, odeslání i zápis výsledku; 1,5 s rezerva na zápis; rozpětí opakování max. 4 s), bez kontroly +probuzení. Klepnutí nese v data URI intentu ID widgetu, klíč zařízení a revizi, se kterou bylo tlačítko +vykresleno. Android rozlišuje `PendingIntent` podle data URI, takže každé vykreslení má vlastní +`PendingIntent` a překreslení pro zařízení B nemůže přepsat extras `PendingIntent`u, který drží starší +vykreslení pro A (Glance je vytváří s `FLAG_UPDATE_CURRENT`; dříve sdílené `actionRunCallback`); v jedné transakci nad preferences widgetu se +rezervace přijme jen při shodě obojího a revize se zvýší. Druhý callback téhož vykreslení (dvojí klepnutí, +Android je doručuje postupně), opožděný callback staršího vykreslení i tlačítko vykreslené pro zařízení A +po výběru B se odmítnou a widget se jen překreslí. Odesílání se zastaví před dalším paketem, jakmile +rezervace zmizí (nový výběr, smazání). Na Androidu se socket nejdřív připraví (DNS, otevření, bind) a +poslední kontrola rezervace i zápis do socketu proběhnou v jedné transakci stavu widgetu +(`GuardedPacketSender`, `PacketWriteGuard`): změna vazby proběhne celá před zápisem (nic se nepošle), nebo +počká na jeho konec. Výsledek zapíše jen držitel tokenu do aktuálního stavu. Zápis výsledku +dostane skutečný zbývající čas (zápis před překreslením); bez času rezervace vyprší po 15 s (wall-clock, +posun hodin zpět ji uvolní hned) a další klepnutí ji převezme. +Odebrané `RECEIVE_BOOT_COMPLETED` má přijatý dopad: po restartu telefonu WorkManager nepřeplánuje +čekající práci (Glance relace se obnoví při příští aktualizaci widgetu); NetKit žádnou plánovanou práci nemá. + +**Smazání a nahrazení záznamu.** Smazaný profil nebo zařízení zakáže svou pinned zkratku s hláškou +(`disableShortcuts`); widget smazaného zařízení přejde do stavu „Zařízení smazáno, klepněte pro výběr“ +a nikdy se nepřepne na jiné zařízení. WoL zkratka i widget jsou vázané na klíč zařízení (ID + MAC + čas +vytvoření): zařízení se stejným ID, ale jinou MAC nebo časem (např. CSV import `webb-` po smazání) +je jiné zařízení — zkratka zůstane zakázaná a widget chce nový výběr. Změna MAC existujícího +zařízení se chová stejně (bezpečná varianta). + +## Widget stavu sítě (zadání 37, 2026-12-01) + +Žádné nové oprávnění ani závislost (Glance a WorkManager ze zadání 36). `ACCESS_BACKGROUND_LOCATION` +zůstává zakázané; widget ho nepotřebuje, protože SSID nikdy nečte sám. + +**Komponenty.** `netstatus.NetStatusWidgetReceiver` je neexportovaný (stejně jako WoL widget, AppWidget +broadcasty doručuje systém). Obnovení jde jen přes neexportovaný `netstatus.NetStatusRefreshReceiver` +bez intent filtru, explicitním broadcastem z `PendingIntent` widgetu; data URI +`netkit-netstatus://refresh/` dává každému widgetu vlastní identitu `PendingIntent`u a nenese +nic dalšího. Receiver ověří, že ID patří providerovi `NetStatusWidgetReceiver`. Exportovaná je jen +konfigurační aktivita (spouštěč ji volá přes `APPWIDGET_CONFIGURE`): + +| Komponenta | Proč exportovaná | Ochrana | +|---|---|---| +| `netstatus.NetStatusWidgetConfigActivity` | spouštěč ji volá přes `APPWIDGET_CONFIGURE` | ID widgetu, které nepatří `NetStatusWidgetReceiver`, aktivitu hned zavře; mění jen dvě volby widgetu, nic neposílá | + +Hlídá `ManifestExportsTest` (sloučené manifesty). + +**Lokální snímek.** `noBackupFilesDir/netstatus_widget.json` (atomický zápis přes dočasný soubor, mimo +zálohu, `allowBackup=false`, přísný kodek se schématem, limit 16 KiB; poškozený soubor = prázdný stav +s vypnutými volbami). Obsah: volby, čas a hodnoty posledního měření z popředí (frekvence → kanál a pásmo, +RSSI, link rx/tx), šířka kanálu z analyzátoru (jen pro stejnou primární frekvenci), RTT brány z Přehledu, +poslední speedtest (down/up/ping, čas) a volitelně SSID a veřejná IP. Každá část má vlastní čas. Zdroje: +Přehled (živá telemetrie), dokončený speedtest a analyzátor Wi-Fi — vždy jen při aplikaci v popředí. Zápis +měření nejvýš 1× za 30 s (první hned, zbytek jedním dozápisem v rozsahu procesu); volby, mazání a ruční +obnovení se zapisují hned. Starší část nikdy nepřepíše novější. Nic se neodesílá. +Revize kolo 1: každý zápis, mazání i změna volby běží pod jedním zámkem a kontrola soukromí (poloha, +zjišťování veřejné IP) se čte uvnitř něj těsně před zápisem — zápis, který kontrolu provedl dřív, už nemůže +přepsat smazání po odebrání oprávnění. Přehled smaže kopii veřejné IP až po uložení vypnutého nastavení. +Čekající části se slučují podle pořadí nabídnutí (monotónní čas), ne podle hodin; uložená část s časem +v budoucnosti (posun hodin zpět, tolerance 5 min) je nedůvěryhodná a další měření ji nahradí. + +**SSID (volba, výchozí vypnutá).** Ukládá se jen SSID přečtené Přehledem nebo speedtestem v popředí, +a jen když je volba zapnutá **a** aplikace má `ACCESS_FINE_LOCATION`. Měření v popředí bez čitelného SSID +uložené SSID smaže. Vypnutí volby nebo chybějící oprávnění k poloze uložené SSID **smaže**; kontrola běží +při každém startu procesu aplikace (`NetKitApplication.onCreate`), při každé aktualizaci widgetu +(`provideGlance`) a při každém zápisu. Odebrání oprávnění v systému proces aplikace ukončí, takže smazání +proběhne při příštím startu nebo aktualizaci widgetu (ověřeno na emulátoru, report 41). Na zamčené +obrazovce (hostitel s kategorií `keyguard`, Android 15+) widget SSID ani veřejnou IP nezobrazí nikdy. + +**Veřejná IP (volba, výchozí vypnutá).** Jen perzistentní kopie poslední hodnoty, kterou Přehled zjistil +v popředí (cache `PublicIpRepository` je jinak jen v paměti). Ukládá se jen při zapnuté volbě a zapnutém +zjišťování veřejné IP v Přehledu (`isLookupEnabled`); vypnutí zjišťování v Přehledu kopii hned smaže. +Widget sám nikdy nic nezjišťuje ani neposílá — nový datový tok ani změna privacy policy proto nevzniká +(evidence [D26](public/data-toky.md#d26)). + +**Obnovení z widgetu (bez polohy, bez provozu).** Ikona obnovení přečte jen RSSI, frekvenci a link rx/tx: +API 31+ jednorázovým `ConnectivityManager.getNetworkCapabilities` bez `NetworkCallback`, tedy bez +`FLAG_INCLUDE_LOCATION_INFO` — platforma SSID/BSSID redigovala bez kontroly polohy. API 29–30 +`NetworkCapabilities` `WifiInfo` nenese, zdrojem je `WifiManager.connectionInfo` (bere se jen rádiová část; +systém tam může svou kontrolu polohy provést — přijaté omezení starých verzí). Žádný soket, DNS ani HTTP; +SSID, brána, speedtest a veřejná IP zůstanou ze snímku s vlastním časem. Celé obnovení (čtení 3 s, zápis, +překreslení) má limit 8 s od vstupu do receiveru (`goAsync`, limit systému ~10 s). Na emulátoru ověřeno +bez záznamu kontroly polohy v AppOps a bez jediného paketu UID aplikace (fáze `netstatus-widget`). + +**Běh na pozadí.** `updatePeriodMillis=0`, žádná periodická práce, služba ani alarm. Widget se překreslí po +zápisu snímku a po obnovení. Stáří signálu je `Chronometer` v RemoteViews: počítá na ploše sám, bez +probouzení aplikace; ostatní části mají absolutní čas (relativní text by bez překreslování lhal). Snímek +starší 24 h ukáže při nejbližším překreslení šedý stav „Otevři NetKit pro měření“ s časem posledního měření. + +## Wi-Fi rozšíření (zadání 38, 2026-12-01) + +- **Žádné nové oprávnění.** Export skenu a záznamu obchůzky jde jen přes systémový výběr + souboru (`ACTION_CREATE_DOCUMENT`); kód země čte `TelephonyManager.getNetworkCountryIso()`, + které oprávnění nevyžaduje (`docs/zavislosti.md`, ověřeno 2026-12-01). +- Exportované soubory obsahují identifikátory okolních sítí (SSID, BSSID, výrobce) a u záznamu + obchůzky i značky míst. Před uložením je vždy dialog s varováním; nic se neodesílá. SSID a + značky jsou nedůvěryhodný text: CSV je uzavírá do uvozovek a text začínající `= + - @`, TAB + nebo CR dostane prefix `'` (CSV injection); JSON escapuje knihovna. Při selhání zápisu se právě + vytvořený dokument smaže. +- Záznam obchůzky běží jen při otevřeném Přehledu a aplikaci v popředí, data jsou jen v paměti + (max. 7200 vzorků), žádná služba ani práce na pozadí. Připnutí AP jsou také jen v paměti. + +## Cíle nástrojů, TCP ping, MAC → výrobce (zadání 48, 2026-12-02) + +- **Žádné nové oprávnění ani závislost.** TCP ping používá existující `INTERNET` a stejný + socket vázaný na síť jako kontrola portů; MAC → výrobce je offline nad přibaleným IEEE OUI. +- Historie (10) a oblíbené (30) cíle jsou jen v `files/datastore/lan-tools.json` + (`allowBackup=false`), nic se neodesílá. Automatická historie URL **neukládá query ani + fragment** (tokeny v URL); oblíbená URL se uloží celá, protože ji uživatel výslovně označil. + Hodnoty s řídicími/formátovacími znaky nebo mezerami se neuloží, popisek se sanitizuje. + „Vymazat historii“ maže jen historii, oblíbené ne. +- TCP ping je nástroj na jeden cíl: stejné potvrzení cíle mimo vlastní síť jako Ping, + nejvýše 1 spojení naráz a 1 pokus za sekundu, počet max. 1000 (prázdný = do zastavení + tlačítkem). Nejde o zátěžový test ani SYN flood; připomínka „jen vlastní síť“ platí dál. +- Vložený výpis MAC tabulky je nedůvěryhodný text: limit 64 KiB / 2000 řádků se kontroluje před + parsováním, výsledek obsahuje jen kanonické MAC; jména výrobců jdou do exportu přes stávající + CSV ochranu proti vzorcům. + +## SSH produktivita: snippety, log, `-L`/`-D`, ProxyJump (zadání 41, 2026-12-01) + +Žádné nové oprávnění ani závislost: forwardy používají existující `INTERNET` +(loopback `ServerSocket` a JSch kanály), log jde přes SAF (`ACTION_CREATE_DOCUMENT`, +bez přístupu k úložišti). + +- **Naslouchání jen na loopbacku.** `-L` (`LocalForwardServer`) i `-D` (`Socks5Server`) + bindují literál `127.0.0.1` (žádný wildcard ani překlad jména), jen po dobu relace; zavření relace porty uvolní. Na emulátoru ověřeno odmítnutím spojení na + externí IPv4 rozhraní (fáze `ssh-forward`). Riziko, které zůstává: **kterákoli aplikace + v telefonu** se může na loopback port během relace připojit (confused deputy). + `-D` proto ve výchozím stavu vyžaduje RFC 1929 přihlášení s náhodným heslem pro relaci + (20 znaků z `SecureRandom`, porovnání v konstantním čase, jen v paměti/stavu UI, kopie do + schránky jako citlivý obsah, nikdy uloženo ani exportováno); „bez přihlášení“ je výslovná + volba v profilu s varováním. `-L` autentizovat nelze (protokol cílové služby), proto editor + i stav relace jasně varují, že port je během relace dostupný všem aplikacím v telefonu, + a forward existuje jen po dobu relace; souběžných klientů je nejvýše 32. + Omezení na vlastní UID nejde: [`ConnectivityManager.getConnectionOwnerUid`](https://developer.android.com/reference/android/net/ConnectivityManager#getConnectionOwnerUid(int,%20java.net.InetSocketAddress,%20java.net.InetSocketAddress)) + (API 29+) podle oficiální dokumentace (ověřeno 2026-12-01) vyhazuje `SecurityException`, + pokud volající není aktivní `VpnService` aktuálního uživatele; běžná aplikace tedy vlastníka + příchozího loopback spojení zjistit nemůže. Remote `-R`, agent a X11 forwarding se + neimplementují. +- **SOCKS5 jako nedůvěryhodný vstup.** Parser v `commonMain` má pevné limity (pozdrav + ≤ 257 B, požadavek ≤ 262 B, doména ≤ 253 znaků jen `[A-Za-z0-9._-]`, port ≠ 0), jen + CONNECT bez autentizace; server má limit 32 klientů, handshake 10 s a vlastní vlákna. + Chybová hláška SSH serveru se klientovi nepředává (jen kód 05). +- **ProxyJump** ověřuje klíč serveru **pro každý skok zvlášť** stejnou politikou jako + přímé spojení (TOFU, změněný klíč vždy odmítnut a zaznamenán do `rejectedHostKeys`); + přihlášení k cíli nikdy neproběhne, pokud selže ověření klíče cíle. Každý skok má + vlastní instanci JSch a vlastní tajemství z Keystore; dialog hesla jmenuje skok. + Řetěz max. 3 skoky, cyklus a chybějící profil se odmítnou před spojením. +- **Log relace** je opt-in pro jednu relaci, s upozorněním na citlivý obsah; soubor + vybírá uživatel. Do logu jde jen výstup serveru (echo psaného textu včetně případně + vypsaných hesel), nikdy hesla z dialogů ověření. Escape sekvence se neukládají; limit + 50 MiB, zápis mimo hlavní vlákno, při zahlcení se log zastaví (paměť neroste). +- **Import snippetů** nesmí potichu změnit příkaz pod známým názvem: nové a změněné snippety + z importu mají `sendEnter = false`, náhled ukáže starý i nový text a změnu je nutné výslovně + potvrdit; stejný text zachová místní volbu Enter. +- **Snippety nejsou tajemství**: ukládají se nešifrovaně v `ssh.json` a exportují se. + Text, který vypadá jako heslo/community/token, vyvolá varování před uložením. Nesmí + obsahovat řídicí znaky (nevznikne skrytý Enter ani ESC sekvence); Enter přidá jen volba. +- Testy používají jen loopback fixture (`tools/testsrv/`) s klíči a heslem generovanými + za běhu; fixture povolí `direct-tcpip` jen na své vlastní loopback porty (echo 18084, + druhý SSH 22223) a nic nespouští. + +## Systém a nastavení (zadání 46, 2026-12-01) + +Žádné nové oprávnění ani knihovna (`ManifestExportsTest` hlídá seznam oprávnění beze změny). + +- **Displej zapnutý během měření** je `View.keepScreenOn` (příznak okna `FLAG_KEEP_SCREEN_ON`), + ne wake lock: platí jen pro zobrazené okno NetKitu v popředí, po skončení měření, odchodu + z obrazovky nebo vypnutí volby se uvolní. `WAKE_LOCK` z WorkManageru zůstává odebraný. +- **Jazyk aplikace** ukládá systém (`LocaleManager`, Android 13+); NetKit ho nikam neodesílá. + `android:localeConfig` generuje AGP jen s `cs` a `en`. +- **Predictive back** (`android:enableOnBackInvokedCallback="true"`) nemění exportované + komponenty; zpět z jiné záložky vede na Přehled, na Přehledu aplikaci jen odsune do pozadí. +- **Soubor nastavení** `filesDir/datastore/settings.json` (motiv, displej): bez osobních údajů, + mimo zálohy (`allowBackup=false`), přísný parser s limitem 4 KiB a hloubky JSON; poškozený + soubor nahradí výchozí hodnoty. +- **Resety souhlasů** mění jen lokální stav: zapomenutí souhlasů automatického hledání v LAN + smaže uložené odpovědi všech sítí (klíč instalace a časy hledání zůstávají), takže se aplikace + znovu zeptá; „Zobrazit znovu“ u NDT7 vrátí upozornění M-Lab před dalším testem. Online dotazy + (veřejná IP, poskytovatel) jsou přepínač se stejným úložištěm jako karta Přehledu; reset + na výchozí „zapnuto“ se záměrně nedělá, aby reset souhlasů nikdy nezapnul odesílání dat. +- **Mazání historie** (rychlost, iperf3) a zapomenutí posledního serveru iperf3 přepisuje + `speedtest.json` atomicky přes stávající `SpeedStore`; mazání historie vyžaduje potvrzení. +## SSH na pozadí a SFTP (zadání 42, 2026-12-02) + +**Typ služby na popředí.** Ověřeno v oficiální dokumentaci +[Foreground service types](https://developer.android.com/develop/background-work/services/fgs/service-types) +a [Android 15 behavior changes — dataSync timeout](https://developer.android.com/about/versions/15/behavior-changes-15#datasync-timeout) +(přečteno 2026-12-02): + +| Kandidát | Co dokumentace říká | Hodnocení pro interaktivní SSH terminál | +|---|---|---| +| `dataSync` | přenos dat (upload/download, záloha, import/export, fetch); aplikace s targetSdk 35 mají limit **6 h za 24 h**, pak `onTimeout` a služba musí skončit | terminál není přenos dat; NetKit má targetSdk 35, takže by relace po 6 h spadla; použití pro interaktivní relaci by bylo zavádějící vůči Google Play | +| `remoteMessaging` | „Transfer text messages from one device to another“ (kontinuita zpráv mezi zařízeními) | jiný účel (messaging), neodpovídá | +| `connectedDevice` | interakce s externími zařízeními přes Bluetooth/NFC/IR/USB **nebo síť**; předpoklad např. `CHANGE_WIFI_STATE` (NetKit ho má) | technicky splnitelné, ale účel je párované externí zařízení, ne vzdálený server v síti; posun významu riskuje zamítnutí | +| `shortService` | jen ~3 min | nestačí | +| **`specialUse`** | „Covers any valid foreground service use cases that aren't covered by the other types“; povinná `` s volným popisem, který **posuzuje Google Play při odeslání aplikace** | **zvoleno**: žádný jiný typ nepokrývá uživatelem otevřenou interaktivní relaci; bez časového limitu; bez runtime předpokladu | + +Manifest: `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_SPECIAL_USE`, `POST_NOTIFICATIONS`; služba +`.ssh.SshSessionService` `exported=false`, bez intent filtru, `foregroundServiceType="specialUse"`, +subtyp „Interactive terminal session opened by the user to their own server or device: SSH (and SFTP +transfer within it), Telnet or USB serial console…“ (po integraci zadání 44 jedna služba pro všechny transporty). `startForeground(…, FOREGROUND_SERVICE_TYPE_SPECIAL_USE)` na API 34+. + +**Dopad na Google Play (fáze 2, `publikace-play.md`).** Aplikace s targetSdk 34+ musí v Play Console +(Policy → App content) deklarovat typy služeb na popředí a pro `specialUse` popsat případ použití, obvykle +s videem; reviewer může typ odmítnout. Připravený text: služba běží jen během uživatelem otevřené SSH +relace k jeho serveru, ukazuje trvalé oznámení s počtem relací a „Odpojit vše“ a končí s poslední relací. +Pokud by Play `specialUse` odmítl, náhradou je bez služby (limit 5 min jako dřív); `dataSync` ne (6 h). +GitHub/web distribuce (D9) deklaraci nepotřebuje. + +**Kdy služba běží.** Po celou dobu, kdy existuje aspoň jedna živá relace (připojování nebo připojeno), +a jen když jsou povolená oznámení (`POST_NOTIFICATIONS` na API 33+ a oznámení aplikace zapnutá). +Zvoleno místo „jen na pozadí“: start služby na popředí z pozadí Android 12+ zakazuje +(`ForegroundServiceStartNotAllowedException`), kdežto relace vzniká vždy klepnutím ve viditelné aplikaci; +služba proto startuje při připojení a končí s poslední relací (`stopForeground` + `stopSelf`), také při +zániku ViewModelu. `START_NOT_STICKY`: smrt procesu ukončí všechna spojení, obnovená služba by nic nechránila. +Služba sama spojení nedrží; je to jen oznámení a priorita procesu (spojení vlastní `SshViewModel`). + +**Oprávnění k oznámením.** Runtime dotaz jen jednou, při prvním připojení (příznak v soukromých +preferencích). Odmítnutí: služba neběží, relace na pozadí končí po 5 min jako dřív a nad terminálem je +varování s odkazem do nastavení oznámení aplikace. Povolení později v nastavení se projeví při návratu +do aplikace. + +**Oznámení a zamčená obrazovka.** Kanál `ssh_sessions` s nízkou důležitostí, `VISIBILITY_PRIVATE` +a veřejná verze bez detailů („NetKit: relace terminálu běží“; od zadání 44 společné pro SSH, Telnet i USB). Soukromá verze ukazuje počet relací a názvy +profilů (zkrácené), **nikdy host, IP ani uživatele** — pozor: pokud uživatel pojmenuje profil adresou, +uvidí ji v odemčeném oznámení. Klepnutí otevře záložku SSH přes whitelist cíl `ssh` (`AppTarget.Ssh`, +nic nespouští). Akce „Odpojit vše“ je neměnný (`FLAG_IMMUTABLE`) explicitní `PendingIntent` na +neexportovanou službu; jiná aplikace ji vyvolat nemůže. + +**Zbývající omezení.** Zavření aplikace z přehledu posledních (nebo Zpět na kořenové obrazovce, které +aktivitu ukončí) relace ukončí — spojení patří aktivitě; služba tím také skončí. Výrobci (MIUI/HyperOS +na testovacím telefonu) mohou i službu na popředí agresivně omezovat; ověřuje fyzický checklist. + +**SFTP prohlížeč.** Kanál `sftp` na již ověřené relaci (stejná kontrola klíče serveru a přihlášení, +žádné nové spojení, žádné nové oprávnění; soubory jen přes SAF, který vybírá uživatel). + +- *Cesty:* každý zobrazený adresář je odpověď serveru na `realpath`; „o úroveň výš“ posílá `/..` + jen do `realpath`, nikdy do operace. Jméno ze serveru se použije jen jako jeden prvek cesty (bez `/`, + `.`, `..`, řídicích znaků; jinak se skryje a počet skrytých se ukáže). Řídicí a bidi znaky se na + obrazovce nahradí `?`. Symlinky se zobrazují jako odkazy; otevření a stažení je sleduje na serveru. +- *Glob:* JSch rozbaluje `*`/`?` ve většině cest; NetKit je escapuje, jinak by smazání souboru `*` + smazalo celý adresář (test na fixture). +- *Nahrání nikdy nepřepíše (bezpečnostní kontrola commitu, TOCTOU):* data jdou do náhodného + `.netkit-upload-<96 bit>.part` ve stejném adresáři, cílové jméno dostanou přes `hardlink@openssh.com` + (`link(2)` selže, když cíl existuje); bez hardlinku přes čisté `SSH_FXP_RENAME`, které SFTP v3 + definuje jako nepřepisující. **JSch 2.28.0 posílá místo RENAME rozšíření `posix-rename@openssh.com` + (přepisuje), kdykoli ho server nabízí** (ověřeno v bajtkódu `ChannelSftp.rename`/`sendRENAME` + 2026-12-02); server s posix-rename bez hardlinku se proto pro nahrání odmítne („nepodporováno“). + Zrušení nebo chyba maže jen vlastní dočasný soubor, nikdy cíl. **Přejmenování souboru i odkazu** + (revize kolo 1) jde stejnou cestou: hardlink + smazání starého jména, bez hardlinku čisté RENAME jen + na serveru bez posix-rename, jinak odmítnuto („nepodporováno“). Složku nelze hardlinkovat: má kontrolu + existence a na serveru s posix-rename může `rename(2)` v okně mezi kontrolou a přejmenováním nahradit + jen **prázdnou** složku (soubor ani neprázdnou složku ne) — zbytkový případ bez ztráty dat. + Přepsání existujícího souboru aplikace nenabízí. +- *Limity:* soubor max. 2 GiB (kontrola ohlášené velikosti i během kopírování), výpis max. 5000 položek, + přenos mimo hlavní vlákno, stažení při chybě smaže vytvořený dokument. +- *Zrušení a visící protistrana (revize kolo 1):* „Zrušit“ nejdřív požádá kopírovací smyčku (po 32 KiB); + když do 2 s neskončí, kanál SFTP i stream SAF se zavřou z jiného vlákna. Každá operace má hlídač + nečinnosti 30 s (žádný bajt ani odpověď) se stejným zásahem → „SFTP spojení selhalo“. Prohlížeč je + hned použitelný na novém kanálu; zaseknuté vlákno už nesmí měnit stav ani si ponechat kanál (generace). + Zavření prohlížeče během otevírání kanálu kanál otevřený po zavření hned uvolní. Stream, úklid + dokumentu, hodiny nečinnosti i požadavek „Zrušit“ patří jedné operaci (`SftpRun`), takže pozdě vrácené + vlákno nemůže sáhnout na další stahování a dokončené zrušení neukončí další obnovení výpisu; kanál, + stream a smazání dokumentu se po přerušení zavírají nezávisle (revize kolo 2). Zavřené kanály se + odregistrují z relace (`JschConnection.releaseSftp`), dlouhá relace se službou je nehromadí. Hláška serveru se nezobrazuje ani neloguje (pevné kategorie chyb). Přenos běží dál + na pozadí v rámci služby relace. +- *Mazání* vždy s potvrzením; složka jen prázdná (`rmdir`), u odkazu se maže odkaz, ne cíl. + +Testy: loopback fixture (`tools/testsrv/m1_fixture.py`) má SFTP sandbox s kořenem v soukromém +adresáři fixture; `realpath` a každá operace kontrolují, že skutečná cesta zůstává v kořeni (symlink +ven = `PERMISSION_DENIED`). Fixture nabízí `posix-rename` i `hardlink` jako OpenSSH. + +## Telnet a USB konzole na Androidu (44) + +Telnet používá TCP na cíl vybraný uživatelem. Odposlech nebo změna přenášených přihlašovacích údajů a příkazů +je možná po celé trase. Připojení i opětovné připojení zobrazí cílový host, port a varování. +Potlačení varování patří konkrétnímu profilu. Změna hostu či portu jej obnoví. Heslo se zadává +do živého terminálu při výzvě protistrany. Profil nemá pole pro heslo a Telnet nenabízí záznam relace do souboru. +Síťová politika HTTP ani kontrola certifikátů HTTPS ostatních nástrojů se kvůli Telnetu neuvolňuje. + +USB host je volitelná hardwarová feature. Uživatel vybírá převodník i port při každém otevření relace. +Android rozhoduje o přístupu ke konkrétnímu zařízení. Explicitní jednorázový immutable PendingIntent +míří na neexportovaný receiver. Výsledek probudí jen čekající žádost podle unikátního URI. Před otevřením +aplikace znovu kontroluje systémové oprávnění a přítomnost zařízení. Připojení kabelu samo relaci neotevře. +BREAK je ruční akce během otevřené sériové relace a může přerušit činnost připojeného zařízení. + +SSH, Telnet a sériová linka sdílejí jednu službu typu `specialUse` (§ SSH na pozadí a SFTP; subtyp v manifestu +jmenuje SSH včetně SFTP, Telnet i USB), společný limit čtyř živých relací a akci „Odpojit vše“. +SFTP je jen nad SSH relací (`JschConnection`); u Telnetu a sériové linky se nenabízí. +Ve veřejné verzi oznámení na zamčené obrazovce je jen informace o běžící relaci. Soukromá verze +může zobrazit názvy profilů. Bez služby platí dosavadní pětiminutový limit na pozadí. + +## Identita AP při Wi-Fi 7 MLO + +Přehled čte AP MLD jen s přesnou polohou a zapnutou službou polohy. Adresa a per-link údaje žijí v paměti. Poslední výsledky systémového skenu slouží pouze k přiřazení šířky podle stejného MLD, linky a frekvence. Tato data nevstupují do exportu obchůzky, logu ani historie. [Podmínky platformy](zavislosti.md#wi-fi-7-mlo) + +## Sdílení výsledků (zadání 47, 2026-12-02) + +- **Žádné nové oprávnění.** Kopírování jde do systémové schránky, sdílení přes `Intent.ACTION_SEND` + (`text/plain`, systémový výběr), ukládání přes `ACTION_CREATE_DOCUMENT` (SAF). Nic se neodesílá + samo; report se sestaví z hodnot, které Přehled už má (žádná nová sonda ani dotaz). +- **Diagnostický report:** SSID, BSSID a veřejná IP/ASN jsou ve výchozím stavu vypnuté. Přepínač + „Zahrnout veřejné adresy“ platí i pro veřejně směrovatelné adresy vlastního rozhraní (globální IPv6, + veřejná IPv4, veřejná brána, DHCP server a cíl latence brány); lokální rozsahy (RFC 1918, CGNAT, + link-local, loopback, ULA) zůstávají (revize kolo 1, P1). Při mobilních datech/VPN se chybějící + adresa aktivní sítě nedoplňuje z Wi-Fi (P2). Souhlas zahrnuje také jméno aktivního serveru Private DNS + a endpoint iperf3 (host i port). Bez souhlasu může v reportu zůstat endpoint s číselnou lokální adresou. + Přepínač je dostupný i při vypnutém online dotazu, pokud některý ze souhlasem chráněných údajů existuje. +- Report **neobsahuje** údaje o mobilní buňce (cell ID/ECI/NCI, TAC, PCI, ARFCN, operátora; D31 „jen + lokálně“) ani tajemství SSH/SecureOn. Pojistky: test sériového deskriptoru a klíčů JSON + (`DiagnosticReportTest.reportModelHasNoCellOrSecretFields`) a zdrojová kontrola, že soubory + reportu nečtou `CellDetailViewModel`, `CellularState`, Keystore ani úložiště tajemství + (`DiagnosticReportInputTest.reportSourcesDoNotReadCellDetailOrSecrets`). +- Texty jsou sanitizované jako LAN export (`sanitizeLanText`, adresy jen číselné, IPv6 kanonicky). +- **Kopírování dlouhým stiskem** (IP, brána, DNS, veřejná IP, BSSID, kanál): veřejná IP, BSSID a + report s identifikátory mají na API 33+ `ClipDescription.EXTRA_IS_SENSITIVE` (systém náhled skryje). + Schránku mohou číst jiné aplikace s fokusem nebo výchozí klávesnice — kopírování je volba uživatele. +- **Export seznamu zařízení:** varování v dialogu, sanitizace jmen/bannerů/UPnP, CSV buňky + v uvozovkách s prefixem `'` pro `= + - @` (řídicí znaky jako TAB/CR už sanitizace nahradí mezerou). + SSID do exportu nejde (jen rozsah sítě). +- **Sdílení výsledku měření:** SSID výchozí vypnuté; veřejná IP ani ISP v záznamu nejsou (D05). + +## Zámek SSH + +Volitelná brána před SSH, Telnetem, USB konzolí, správou klíčů a SFTP je při první instalaci vypnutá. Odemčení používá systémovou silnou biometrii nebo PIN, gesto či heslo obrazovky. Na API 29 AndroidX nepodporuje obě metody v jednom promptu. Aplikace zde používá samostatný prompt pro silnou biometrii a systémové potvrzení zámku zařízení. Zrušení, chyba nebo chybějící ověřovací metoda ponechá požadovanou akci neprovedenou. [Podporované kombinace na Androidu](https://developer.android.com/identity/sign-in/biometric-auth) + +Platnost oprávnění se měří monotónními hodinami od úspěchu. Po zániku procesu je nutné nové ověření. Zámek se kontroluje také při připojení ze zkratky, otevření SFTP, zobrazení a kopírování hesla SOCKS5 a při dokončení exportu po návratu z výběru souboru. Probíhající spojení, forwardy a uživatelsky spuštěné přenosy mohou pokračovat na pozadí. Zkratka na ploše stále obsahuje uživatelem zvolený název profilu. + +Brána chrání interakci v aplikaci. Existující AES klíč Android Keystore dál šifruje tajemství stejným způsobem. Navázáním tohoto klíče na autentizaci by změna registrace biometrie nebo systémového zámku mohla způsobit trvalou invalidaci klíče a ztrátu přístupu k uloženým heslům a privátním klíčům. Export profilů obsahuje jen povolená pole v2. + +## Přenos konfigurační zálohy + +Soubor vzniká na pokyn uživatele přes SAF. Čitelný dokument má identifikátor `netkit-backup-v1`, +šifrovaná obálka `netkit-backup-encrypted-v1`. PBKDF2-HMAC-SHA256 odvodí 256bitový klíč ze zadaného +hesla a náhodné 16B soli v 600 000 iteracích. AES-GCM používá čerstvé 12B IV, 128bitový tag +a ověřuje identifikátor formátu, KDF, počet iterací a šifru jako AAD. Čtečka před výpočtem KDF +vyžaduje přesné parametry verze 1. Špatné heslo a pozměněný ciphertext vedou ke stejné chybě. +Limit obálky je 6 MiB, rozbaleného JSON 4 MiB, vnořené SSH a WoL mají vlastní nižší limity. +Před parsováním se kontroluje UTF-8 a hloubka JSON. + +Export vybírá konfigurační pole. Trezory SSH a SecureOn, lokální reference, klientské klíče, SOCKS +přihlašovací údaje, SNMP community, historie měření a souhlasy do souboru nevstupují. `knownHosts.publicKey` +je ověřitelný veřejný klíč **serveru**. Příkazy, poznámky a názvy pocházejí od uživatele. Export odmítne +rozpoznatelné vložené údaje, například příkaz nastavující SNMP community. Libovolné heslo napsané jako +volný text nelze spolehlivě rozpoznat, proto obrazovka před exportem připomíná kontrolu těchto polí. + +Potvrzená obnova připraví nové soubory v soukromém `noBackupFilesDir/configuration-restore`. Při startu +se zkontrolují SHA-256 původních i připravených souborů. Jeden atomický přesun přepne mapu cest ještě +před vznikem vlastníků DataStore. Po přerušení se dokončí změna systémového jazyka a úklid odpojených +SSH hesel. U importovaných ID WoL se současně aktivuje seznam zneplatněných hesel, který respektuje +aplikace i widget. Před použitím trezoru se staré záznamy odstraní. Selhání tohoto kroku zabrání použití +starého hesla. Oprávnění a systémová politika `allowBackup=false` se řídí stávajícím manifestem. diff --git a/docs/design.md b/docs/design.md index a57e29b..2f7af12 100644 --- a/docs/design.md +++ b/docs/design.md @@ -22,6 +22,10 @@ a tento dokument liší, platí tento dokument. Hodnoty px z prototypu = dp/sp v Názvy tokenů v Compose zůstávají jako dnes, kde to jde. Nové tokeny jsou označené (nový). +Režim volí uživatel v Nastavení (zadání 46): Systém (výchozí, `isSystemInDarkTheme()`), Světlý, +Tmavý; `SettingsHost` předá výsledek do `NetKitTheme(darkTheme = …)` a ikonám systémových lišt. +WoL widget (Glance) dál sleduje systém. Vlastní barevné motivy nejsou. + | Token | Tmavý | Světlý | Použití | |---|---|---|---| | `background` | `#0C131A` | `#EEF3F6` | pozadí obrazovky | @@ -31,7 +35,7 @@ Názvy tokenů v Compose zůstávají jako dnes, kde to jde. Nové tokeny jsou o | `divider` (nový) | `#FFFFFF` 5 % | `#0C2D41` 6 % | oddělovač řádků, mřížka grafu | | `text` | `#E8F1F5` | `#0B1A24` | hlavní text, hodnoty | | `muted` | `#93A6B3` | `#4E6372` | popisky, sekundární text | -| `dim` | `#5F7380` | `#7C8E9A` ¹ | osy, neaktivní ikony, poznámky | +| `dim` | `#5F7380` | `#7C8E9A` ¹ | rysky os, doprovodné ikony, neaktivní prvky | | `accent` | `#2DD4BF` | `#0A7166` | primární akce, signál, vybraná záložka | | `accentInk` | `#04201C` | `#FFFFFF` | text na `accent` | | `accentSoft` | accent 12 % | accent 10 % | tonální tlačítko, indikátor v navigaci, štítek | @@ -47,10 +51,16 @@ Názvy tokenů v Compose zůstávají jako dnes, kde to jde. Nové tokeny jsou o 10 % (`0x1A`, stejně jako `accentSoft`). Světlý režim musí splnit kontrast WCAG AA: text 4,5:1 na `surface` i `background`, čáry grafů a ikony 3:1. Ověřuje `python3 -I tools/check_contrast.py` (parsuje tokeny z `Theme.kt`, nenulový návratový kód -při selhání): `text`/`muted` na `surface`, `background` a `surface2` ≥ 4,5; `dim` ≥ 3; +při selhání): `text`/`muted` na `surface`, `background` a `surface2` ≥ 4,5. Pro `dim` na `surface` a `background` platí ≥ 3:1. Dále se ověřují sémantické barvy jako text na `surface` ≥ 4,5 a jako čára ≥ 3; text štítku na jeho `*Soft` podkladu nad `surface` ≥ 4,5; `accentInk` na `accent` a terminál ≥ 4,5. +Při kontrole UI použij pro sekundární text nesoucí informaci `muted` (≥ 4,5:1). +Patří sem popisky hodnot a jednotek, čísla na stupnici měření, souhrny běhů, +nedostupné výsledky, vysvětlení chyb a popisky dostupných akcí. Chybový text může +použít také `err` na `surface`. Token `dim` slouží pro nepodstatné prvky, například +rysky os, doprovodné šipky a vypnuté ovládací prvky. + ¹ Upraveno v B1 (2026-10-27) proti prototypu, aby světlý režim prošel kontrolou. Původní hodnoty a důvod: `dim` `#7E909C` měl na `background` 2,96:1 (< 3); `warn` `#A86A00` měl jako text na `surface` 4,44:1; štítky `info`/`ok`/`warn`/`err` na 14–15% podkladu měly @@ -122,8 +132,8 @@ předsazené vlevo mimo centrování. Mínus má řez 500 a krytí 72 %. Znamén | `LiveBadge` | štítek „živě · 1 s“ v akcentu s pulzující tečkou (2 s, zvětšující se prstenec). | | `SignalGauge` | oblouk 240°, poloměr 62, tah 10, kulaté konce. Stopa `surface3`, hodnota v barvě kvality (ok/accent/warn/err). Uvnitř hodnota `gauge` + „dBm“, **pod obloukem** kvalita (13/700 v barvě kvality). Animace oblouku 800 ms. Stupnice `range` (M4): `GaugeRange.WIFI` −90…−30 dBm (RSSI), `GaugeRange.CELLULAR` −140…−44 dBm (RSRP). Bez `range` platí předané `fraction` jako dřív. Místo kvality smí být stav („Režim letadlo“, „Bez SIM“, „Bez služby“) v neutrální barvě. | | Mobilní měřidlo (M4) | `SignalGauge` s `GaugeRange.CELLULAR` a vedle něj SIM (`label`), operátor (`panelTitle`) a štítky: standard (accent s tečkou), „Data“ (jen při dvou SIM), „Roaming“ (warn). Pod tím dlaždice RSRQ, SINR (dB) a IPv4 mobilní sítě (mono). Další SIM jako řádky SIM. Kvalita podle RSRP: ≥ −80 výborný (ok), ≥ −90 dobrý (accent), ≥ −100 slabší (warn), jinak slabý (err). | -| Karta cesty (M4) | `SectionCard` „Připojení“, vpravo jen menu (ikona 40, `More`): „Obnovit“ a „Zjišťovat veřejnou IP“ se zaškrtávátkem. Uzly: poskytovatel (`Globe`: jméno, veřejná IPv4, IPv6, „AS…“ v `dim`), přístupový bod (`Router`, jen na Wi-Fi: pásmo a kanál), telefon (`Phone`: „Tento telefon“ a lokální IP). Uzel = kruh 40 na `surface2` s ikonou 20 `muted`, pod ním (nebo vedle něj ve sloupci) název `body` 600 a řádky `label`, IP v mono `text`. Spojovací linka 2 dp `surface3` vede středy ikon; na živé síti nad ní `accent` s krytím 35–75 %, které jemně dýchá (`rememberBreathing`, perioda 2 s, s omezením animací stojí). Stavy uzlu poskytovatele: načítání („zjišťuji veřejnou IP…“), veřejná IP, „za NAT operátora“ (štítek info), „veřejná IP nedostupná“, „zjišťování vypnuto“ a „Bez připojení“; v posledních třech je první úsek linky čárkovaný a nedýchá. IP se nikdy nezkracuje (viz §4). | -| Řádek se dvěma řádky (M4, Latence) | Jako řádek klíč–hodnota, ale pod popiskem (`body`, `muted`) jsou poznámky na samostatných řádcích: `label` v `dim`, strojové hodnoty mono (brána, cíl, resolver DNS, dotazované jméno). Hodnota vpravo nejvýš 55 % šířky, zarovnaná na účaří popisku; mezera 12 dp zůstává i při 360 dp a písmu 1,3. DNS: první poznámka je IP resolveru, nebo „Soukromé DNS · host“, druhá dotazované jméno. | +| Karta cesty (M4) | `SectionCard` „Připojení“, vpravo jen menu (ikona s cílem 48 dp, `More`): „Obnovit“ a „Zjišťovat veřejnou IP“ se zaškrtávátkem. Uzly: poskytovatel (`Globe`: jméno, veřejná IPv4, IPv6, „AS…“ v `muted`), přístupový bod (`Router`, jen na Wi-Fi: pásmo a kanál), telefon (`Phone`: „Tento telefon“ a lokální IP). Uzel = kruh 40 na `surface2` s ikonou 20 `muted`, pod ním (nebo vedle něj ve sloupci) název `body` 600 a řádky `label`, IP v mono `text`. Spojovací linka 2 dp `surface3` vede středy ikon; na živé síti nad ní `accent` s krytím 35–75 %, které jemně dýchá (`rememberBreathing`, perioda 2 s, s omezením animací stojí). Stavy uzlu poskytovatele: načítání („zjišťuji veřejnou IP…“), veřejná IP, „za NAT operátora“ (štítek info), „veřejná IP nedostupná“, „zjišťování vypnuto“ a „Bez připojení“; v posledních třech je první úsek linky čárkovaný a nedýchá. IP se nikdy nezkracuje (viz §4). | +| Řádek se dvěma řádky (M4, Latence) | Jako řádek klíč–hodnota, ale pod popiskem (`body`, `muted`) jsou poznámky na samostatných řádcích: `label` v `muted`, strojové hodnoty mono (brána, cíl, resolver DNS, dotazované jméno). Hodnota vpravo nejvýš 55 % šířky, zarovnaná na účaří popisku; mezera 12 dp zůstává i při 360 dp a písmu 1,3. DNS: první poznámka je IP resolveru, nebo „Soukromé DNS · host“, druhá dotazované jméno. | | Řádek SIM (M4) | „SIM 1 · operátor“ (`body` 600) a pod ním štítky standardu, „Data“ (accent) a „Roaming“ (warn); vpravo „−97 dBm“ (`body` 600) a kvalita (`label` v barvě kvality). Rytmus a oddělovač jako řádek klíč–hodnota. | | Řádek roamingu (M4) | Vlevo „před 12 s“ (`body`, `muted`) a štítky: změna pásma („2,4 → 5 GHz“), jinak změna kanálu („k. 36 → 100“), a „po výpadku“ (warn); štítky se při úzké šířce zalomí pod čas. Vpravo obě zkrácené BSSID mono na jednom řádku. Na 412 dp nejvýš dva řádky. | | Výběr metriky | 3 karty `surface2` (rádius 12) s názvem a živou hodnotou. U názvu krátká čárka v barvě série. Vybraná má okraj a podklad z barvy série 9–55 %. Nahrazuje vnitřní segment grafu. | @@ -131,9 +141,10 @@ předsazené vlevo mimo centrování. Mínus má řez 500 a krytí 72 %. Znamén | `SpeedDial` | půlkruh 180°, otočný bod dole uprostřed. Stopa tah 5 `surface3`, průběh v barvě fáze (stahování `info`, odesílání `violet`). 41 rysek (každá 5. hlavní), rozsvícené do aktuální hodnoty. Popisky 0, 10, 50, 100, 250, 500, 1000 na log. stupnici `log10(1+v)/log10(1001)` uvnitř rysek. Tenká ručička (2,2) a kroužek 7 na otočném bodu. **Hodnota pod ciferníkem** (`hero`) + „Mbit/s“ + fáze s barevnou tečkou. Pod tím 3 dlaždice fází (Latence, Stahování, Odesílání) s průběhovou linkou 2 dp dole u aktivní fáze. | | Tepelný pás kanálů | řada buněk (výška 44, rádius 6, mezera 3) v barvě skóre ok → warn → err. Mezery pásma (UNII) jako čárkovaný obrys. Připojený kanál má tečku nad buňkou. Pod pásem popisky vybraných kanálů a stupnice „volný → rušený“. Klepnutím se vybere kanál a pod pásem se zobrazí jeho detail (DFS, AP v dosahu s RSSI). Nahrazuje seznam desítek řádků. | | Mřížka portů | 3 sloupce, buňka `surface2` rádius 10: port 15/700 v akcentu + služba 12 `muted`. | -| Identifikace zařízení | řádky jen pro zjištěné údaje. Nezjištěné jedním řádkem „Nezjištěno: mDNS, reverzní DNS“ v `dim`. | +| Identifikace zařízení | řádky jen pro zjištěné údaje. Nezjištěné jedním řádkem „Nezjištěno: mDNS, reverzní DNS“ v `muted`. | | Tlačítko probuzení (WoL) | kruh 52, `accentSoft`/`accent`. Při čekání rotující prstenec, po úspěchu plný `accent` a štítek „odesláno · odpovídá na 22“. | -| Spodní navigace | `navBackground`, horní linka `divider`, 5 položek. Ikona 22 v pilulce 54×30, vybraná: pilulka `accentSoft` a ikona `accent`, popisek `text`. Ostatní `dim`. | +| Spodní navigace | `navBackground`, horní linka `divider`, 5 položek. Ikona 22 v pilulce 54×30, vybraná: pilulka `accentSoft` a ikona `accent`, popisek `text`. Ostatní položky mají ikonu `dim` a popisek `muted`. | +| Postranní navigace | Od šířky okna 600 dp `NavigationRail` se stejnými pěti cíli a barvami. Na nízké obrazovce se cíle svisle posouvají. Připojený SSH terminál na šířku využívá celou obsahovou plochu. | | `InfoNote` | ikona info `dim` + text 13 `muted`, rozbalení animované (`animateContentSize`). | | `EmptyState` | ikona 32 v kruhu `surface2`, krátká věta a primární akce pod ní (např. „Přidat zařízení“). | @@ -142,7 +153,7 @@ předsazené vlevo mimo centrování. Mínus má řez 500 a krytí 72 %. Znamén - **Osa x podle času**, ne podle indexu vzorku. Okno (výchozí 5 min) **vždy vyplní celou šířku**. Před začátkem dat je prázdno vlevo, nové vzorky přibývají vpravo. Popisky času dole: „teď“, „−1 min“, … -- **Osa y vlevo** s popisky v `dim` 11, mřížka jen vodorovná (`divider`). Jednotka je +- **Osa y vlevo** s popisky v `muted` 11, mřížka jen vodorovná (`divider`). Jednotka je v legendě nebo v hlavičce, ne pod osou. Rozsah: signál Wi-Fi −90…−30 dBm pevně, mobilní −140…−44 dBm, ostatní automaticky na „hezké“ maximum (1, 2, 2,5, 5 × 10ⁿ) s rezervou 15 %. @@ -198,6 +209,23 @@ předsazené vlevo mimo centrování. Mínus má řez 500 a krytí 72 %. Znamén - Všechny texty v resources, výchozí čeština, angličtina připravená. Při úpravě textu se upraví obě jazykové verze. +### TalkBack při měření + +Gestem pro nadpisy lze procházet názvy obrazovek a sekcí. Datové řádky výsledků DNS, Web/TLS a RDAP používají `SectionCard(heading = false)`. Banner a stav běhu +používají `LiveRegionMode.Polite`. Po dokončení TalkBack přečte výsledek v jazyce aplikace. +Číselný postup zůstává na obrazovce. Když uživatel přejde ve stejném seznamu k výsledkům +mimo stavový řádek, dokončení oznámí aktivní obrazovka jednou. + +Při zaměření časového grafu čte TalkBack minimum, maximum a hodnotu na pravém okraji +zobrazeného okna pro každou sérii včetně jednotek. Prázdná série a chybějící poslední +vzorek mají vlastní slovní popis. Přepínače a tlačítka ovládání grafu mají dotykovou plochu alespoň 48 × 48 dp. + +Výjimkou je souvislý pás zdraví kanálů. Buňky mají minimální šířku 8 dp, aby na telefonu +bylo vidět celé běžné pásmo a tažením šel vybrat kanál. Pokud se pás nevejde ani při +tomto minimu, lze jej vodorovně posunout a kanál vybrat klepnutím. TalkBack má pro každý +kanál samostatný sémantický uzel s číslem, hodnocením, stavem výběru a akcí pro výběr. +Uživatel může přejít gestem na sousední kanál a aktivovat jej dvojklepem. + ## 9. Ověření vzhledu Screenshoty z emulátoru `netkit-api35` (`artifacts/m3/shots/`) pro každou obrazovku: diff --git a/docs/funkce/lan-scanner.md b/docs/funkce/lan-scanner.md index 088188f..75a7e54 100644 --- a/docs/funkce/lan-scanner.md +++ b/docs/funkce/lan-scanner.md @@ -4,6 +4,12 @@ testy a runtime důkazy eviduje interní pracovní záznam; tento popis není přijetí M1. Fyzický checklist provádí správce, nikoli agent. +Při dokončení pingu TalkBack přečte počet odpovědí ze všech pokusů a průměr dostupných RTT. +U delší relace uvede také délku okna pro průměr. Traceroute hlásí počet testovaných +a odpovídajících skoků, sken portů otevřené a otestované porty, DNS počet vrácených adres. +Sken zařízení počítá protějšky potvrzené v aktuálním běhu. Telefon a dříve nalezené +položky označené „nedávno“ se do hlasového souhrnu nezapočítají. + ## 1. Implementované funkce - **Discovery IPv4 hostů:** výchozí rozsah obsahuje adresu telefonu a má prefix @@ -12,22 +18,37 @@ Fyzický checklist provádí správce, nikoli agent. Úspěšné sondy zobrazí IP, dostupné reverzní DNS jméno, odezvu a metodu ICMP/TCP; TCP odmítnutí značí živý endpoint metodou TCP-RST. mDNS je samostatný nástroj; jeho výsledky se automaticky neslučují do discovery seznamu. -- **Ping:** průběžné měření do zastavení nebo odchodu do pozadí. Odesláno/přijato/ztráta +- **Podsítě:** offline kalkulačka přijímá IPv4/prefix a tečkovou masku nebo wildcard za mezerou či lomítkem. + U `0.0.0.0` a `255.255.255.255` ukáže použitý výklad a prefix. Výchozí masku lze přepnout na wildcard. + Rozsah se určuje z celé podsítě. Částečný překryv se zvláštním blokem se zobrazí jako „Smíšený rozsah“. + Třída A–E se vztahuje k zadané adrese. Rozsah `/31` má dva použitelné hosty, `/32` jednoho. + Výpis rozdělení má strop 256 podsítí. Klepnutí nebo dlouhý stisk na řádku zkopíruje jeho hodnotu. + Před prvním vlastním vstupem se použije adresa a prefix Wi-Fi. +- **Ping:** výchozí měření běží po sekundě do zastavení nebo odchodu do pozadí. V pokročilých + volbách lze zadat 1–1000 sond, interval 0,2–10 s a payload 0–1472 B (výchozí 16 B). + Interval je minimální odstup mezi začátky sond. Při ztrátě se čeká na timeout předchozí sondy. + S vypnutým DF socket dovoluje fragmentaci. Případná chyba EMSGSIZE se započítá jako ztráta jedné sondy. + Volba DF a měření MTU se zobrazí po úspěšném nastavení socketové volby. Na potvrzené trase se nejprve + ověří 548 B, pak se binárně hledá největší průchozí payload do 1472 B. Každá sonda bez odpovědi se jednou zopakuje. + EMSGSIZE s DF potvrdí horní mez. Určí-li ji opakovaný timeout nad potvrzeným payloadem, výsledek upozorní + na možnou PMTUD black hole. Bez odpovědi už na výchozích 548 B zůstane výsledek neprůkazný. IPv4 paket má o 28 B více. + Nastavení pingu, vstup kalkulačky a porty zůstávají v samostatném DataStore nástrojů. Odesláno/přijato/ztráta platí pro celou relaci; min/průměr/max/jitter a export pro posledních 600 vzorků, graf a seznam pro posledních 120. Číslo vzorku a čas od startu (monotónní hodiny) se po odříznutí starých vzorků nenulují; export je dostupný i za běhu jako snímek. Jitter je průměr absolutních rozdílů sousedních úspěšných odpovědí; přes timeout se rozdíl nepočítá. - **Traceroute:** `/system/bin/ping` s TTL 1–30. Zobrazuje pouze údaje skutečně získané - z výstupu. Po pěti úvodních hopech bez adresy skončí s vysvětlením neúplné trasy; + z výstupu. Po pěti úvodních hopech bez adresy počká na „Pokračovat“ a pak naváže od TTL 6 na stejném cíli a síti; chybějící hopy ani jejich RTT nevymýšlí. Ověření výstupu HyperOS zůstává otevřené. -- **TCP port scan:** preset 105 běžných portů, seznam nebo vzestupné rozsahy +- **TCP port scan:** preset běžných portů včetně NETCONF a správy RouterOS, seznam nebo vzestupné rozsahy (např. `22,80,8000-8100`), názvy známých služeb a volitelný pasivní banner. Karty portů uvádějí úspěšná TCP spojení; souhrn rozlišuje otevřené, odmítnuté, timeoutované a chybové sondy. Timeout není důkaz uzavřeného portu. TCP se zde nepoužívá k přihlašování ani k posílání aplikačních požadavků. - **DNS:** A/AAAA přes Android resolver na vybrané Wi-Fi, bez Wi-Fi na aktivní síti (M4); IPv4 PTR přes binární IN/PTR DNS dotaz na témže `Network`. Samotné ICMP/TCP sondy jsou - pouze IPv4. + pouze IPv4. UI rozlišuje NXDOMAIN, prázdnou odpověď NOERROR, jiný RCODE, + chybu systémového resolveru a vypršení limitu. - **mDNS / Bonjour:** ručně zvolený typ služby, výchozí `_http._tcp.`, hledání po dobu 12 sekund, nejvýše 128 služeb, název/typ/adresa/port. V této implementaci vyžaduje Android 14 / API 34; na API 29–33 UI výslovně uvede nepodporu. @@ -242,7 +263,7 @@ neplatný FD explicitní nedostupnost ICMP. `Network.bindSocket` stále předch `connect`; oprava nemění výběr sítě ani nevytváří fallback. Čistá `matchesIcmpEchoReply` kontroluje délku, typ Echo Reply, kód0, sekvenci a -celý nonce payload. Nekontroluje shodu identifikátoru/checksum s původním bufferem, +celý dostupný nonce payload. Pouze při výslovně zvolené délce 0 B stačí na připojeném socketu shoda náhodné sekvence. Nekontroluje shodu identifikátoru/checksum s původním bufferem, protože je nastavuje kernel ping socketu. `IcmpEchoTest` ověřuje správnou a cizí odpověď, každý změněný bajt sekvence/nonce, chybný typ/kód, zkrácení, překročení bufferu a požadavek bez nonce; nepoužívá Android/JVM importy. @@ -342,7 +363,7 @@ zařízení ukáže IP, jména, živý ping se ztrátou a jedním klepnutím ryc stávající `LanBackend.ping` bez TTL, 1× za sekundu, 10 vzorků → ztráta %, min/průměr/max (`pingStatistics`). Odpověď aktualizuje RTT a `lastSeen` v seznamu. `closeDevice()` ping zastaví; opětovné `openDevice` jej spustí znovu. Pro tento telefon se ping nespouští. -- `scanPorts(address)`: přednastavených 105 portů (`commonPorts`), existující `tcpProbe`, +- `scanPorts(address)`: přednastavený seznam portů (`commonPorts`), existující `tcpProbe`, timeout 1000 ms, souběžnost 16, bez banneru. Otevřené porty se průběžně zapisují do zařízení; `portsScannedElapsedMs` jen po dokončení. Zavření detailu sken portů nezastaví, `cancel()` ano. @@ -437,3 +458,155 @@ TCP sondy), identifikace do seznamu nepřidává — to by vyžadovalo novou met | SSDP, pravidlo LOCATION, HTTP odpověď, XML čtečka, presentationURL | `UpnpIdentityTest` (commonTest) | | Model: služby, UPnP, zachování po novém hledání, priorita jmen | `LanDeviceIdentityTest` (commonTest) | | Sockety (legacy unicast, MULTICAST_IF, TTL), HTTP fetch, UI panel | NOT RUN — bez emulátoru; fyzický checklist M2-30 až M2-39 ([testovani.md §11](../testovani.md)) | + +## 7. Rozšíření LAN (zadání 39, 2026-12-01) + +### Seznam zařízení po řádcích + +`DeviceList` v `DevicesScreen.kt` už nemá jednu položku `LazyColumn` s `forEachIndexed`, ale +jednu položku na zařízení (`deviceRows`, klíč `device:`, `contentType = "device"`). +Komponují se jen viditelné řádky; pořadí (brána, pak IPv4), testTagy `devices_row_` / +`device_source_` a kotva posunu (první viditelný klíč) při průběžném doplňování zůstávají. +Vzhled jednoho panelu drží `PanelSegment` (první/poslední řez se zaoblením, stín jako `Panel`), +mezery mezi ostatními bloky dává každý blok sám. Měření prvního snímku (254 syntetických +zařízení, starý panel vs. lazy) je ve fázi `lan-list` a v reportu 43. + +### Info o síti + +Karta „Info o síti“ v Zařízení (nad seznamem, sbalená, rozbalená ukáže vše): rozhraní, +IPv4/prefix, brány (IPv4 i IPv6 výchozí trasy), DNS servery, doména hledání, DHCP server +(`LinkProperties.getDhcpServerAddress`, API 30+; na API 29 „nedostupné“, bez DHCP „žádné“), +MTU (`getMtu`, 0 = „neznámé“) a IPv6 adresy po rozsazích (globální, ULA, link-local; kanonicky +s prefixem). Jen `LinkProperties` při načtení Wi-Fi, žádný síťový provoz; formátování a +filtrování nedůvěryhodných hodnot v `commonMain` (`lanNetworkInfoRows`). + +### IPv6 v nástrojích (jeden cíl) + +- Vstup: IPv6 literál (`::`, zóna `%wlan0`, hranaté závorky, IPv4-mapped → bere se IPv4) nebo + hostname. Hostname: nejdřív A, jinak AAAA. Parser a klasifikace v `commonMain` + (`Ipv6Address`, `Ipv6Prefix`, `lanNumericAddress`, `validLanTarget`), bez `java.net`. +- **Ping** přes ICMPv6 datagram socket (`Os.socket(AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6)`, + `WifiIcmp6`), vázaný na síť trasy, echo 128/129 s kontrolou sekvence a nonce + (`matchesIcmpv6EchoReply`). Payload ≤ 1452 B, volba DF se u IPv6 neuplatní, hledání MTU a + traceroute k IPv6 cíli nástroj odmítne vlastní hláškou. +- **Kontrola portů TCP** stejná jako u IPv4 (`probeTcpSocket`), adresa bez DNS + (`toolInetAddress`); link-local dostane scope rozhraní trasy (`Os.if_nametoindex`), + protože Android váže sockety značkou sítě, ne zařízením. Zóna jiného rozhraní → chyba. +- **DNS**: lookup se ptá typově na A i AAAA (`DnsResolver.query(..., TYPE_A/TYPE_AAAA, ...)`, + API 29); dřívější netypový dotaz se na síti bez IPv6 na AAAA vůbec neptal. Řádky výsledku + mají metodu `A` / `AAAA`; PTR jen pro IPv4. +- Volba sítě: `chooseToolRoute` (IPv6 link-local/ULA jsou místní), „v podsíti Wi-Fi“ pro + IPv6 = link-local nebo on-link prefix Wi-Fi (`LanBackend.ipv6Prefixes`). +- Potvrzení: `ipv6TargetConfirmationReasons` (viz [bezpecnost.md](../bezpecnost.md)). +- **IPv6 discovery podsítě neexistuje** (mimo rozsah; /64 nejde prohledat a není to cíl). + +### Identifikovat služby (UDP) + +Nová sekce „Služby (UDP)“ v detailu zařízení (ne pro telefon): pole komunity SNMP (maskované, +nepovinné) a tlačítko „Identifikovat služby“. Tři sondy souběžně, každá nejvýš 2 pokusy po +1,5 s, socket vázaný na Wi-Fi a připojený na cíl (`DatagramUdpExchange`): + +| Sonda | Dotaz | Zobrazí | +|---|---|---| +| SNMP v2c (UDP 161) | GetRequest `sysDescr.0` + `sysName.0`, komunita od uživatele; prázdná = přeskočit | sysName, sysDescr; error-status jako chyba; špatná komunita = „neodpovídá“ | +| NTP (UDP 123) | 48 B, mode 3, VN 4, náhodný transmit timestamp | stratum, reference ID (kód u stratum 0/1, IPv4 upstreamu u 2–15), nesynchronizováno | +| DNS (UDP 53) | `version.bind` CH TXT, jen pro DNS server Wi-Fi nebo host s otevřeným TCP 53 | verze, nebo „odpovídá, verzi neuvádí (RCODE)“ | + +ICMP port unreachable se ukáže jako „port zavřený“. Kodeky (`SnmpBer.kt`, `NtpPacket.kt`, +`VersionBind.kt`) a orchestrace (`probeUdpServices`) jsou v `commonMain` s testy nad +syntetickými pakety; integrační test `UdpServicesFixtureTest` (JVM) a emulátorová fáze +`lan-udp` běží proti loopback fixture `tools/testsrv/udp_services.py` (stdlib, jen +`127.0.0.1`, syntetické hodnoty). + +| Ověření (zadání 39) | Kde | +|---|---| +| IPv6 parser, klasifikace, prefixy, potvrzení | `Ipv6Test` (commonTest) | +| ICMPv6 echo matcher | `Icmpv6EchoTest` (commonTest) | +| Info o síti: formátování, stavy, nedůvěryhodné hodnoty | `LanNetworkInfoTest` (commonTest) | +| BER/NTP/DNS: platné, zkrácené, příliš dlouhé, hluboké vnoření; orchestrace | `UdpServicesCodecTest` (commonTest) | +| A/AAAA sloučení, výběr cíle, potvrzení, odmítnutí trace/MTU | `LanIpv6ToolsTest` (JVM) | +| UDP sondy proti loopback fixture | `UdpServicesFixtureTest` (JVM), fáze `lan-udp` | +| Seznam, Info o síti, IPv6 ping/TCP/AAAA na emulátoru | fáze `lan-list`, `lan-v39` | +| Fyzický telefon | checklist L39-01 až L39-10 ([testovani.md §20](../testovani.md)) | + +## 8. Export seznamu zařízení (zadání 47, 2026-12-02) + +Ikona stažení v hlavičce „Síť“ (aktivní s neprázdným seznamem mimo běh skenu) otevře dialog +s varováním a volbou TXT/CSV/JSON; soubor se uloží přes SAF (`netkit-devices.*`), text je snímek +v okamžiku otevření výběru. Sloupce: adresa, zobrazované jméno a zdroj, NetBIOS/mDNS/PTR, skupina, +MAC z NetBIOS, brána/telefon, metoda, RTT, stale, „naposledy před s“, porty, služby mDNS, UPnP. +Sanitizace jako LAN export, ochrana CSV vzorců; SSID se neexportuje (JSON `network` = rozsah). +Kód: `shared/.../lan/LanDeviceExport.kt`, `androidApp/.../lan/DevicesExport.kt`; testy `LanDeviceExportTest`. + +## Diagnostika v Nástrojích (Android) + +- **DNS záznamy** pošlou jeden IN dotaz systémovému resolveru aktivní sítě. Lze zvolit + A, AAAA, CNAME, MX, NS, TXT, SOA, PTR, SRV a CAA. PTR přijímá i číselnou IPv4/IPv6. + Výstup obsahuje RCODE, AA/TC/RD/RA, jména, typy, TTL v sekundách a hodnoty ze všech sekcí. + Neznámé RDATA se zobrazí hexadecimálně. Výsledek lze uložit stávajícím LAN exportem. + Tlačítko porovnání se nabídne při aktivní VPN a dostupné samostatné Wi-Fi síti. Každé + porovnání vyžaduje nové klepnutí, které povolí odeslat tentýž dotaz také mimo VPN. +- **Web/TLS** změří zadanou HTTP(S) URL. Zachová každý status a Location, včetně pokusu HEAD, + na nějž server vrátí 405/501. GET zkusí jen do první změny schématu, hostu nebo portu. + Sleduje nejvýše pět přesměrování na stejný port nebo na 80/443. Trasu přes fake-IP proxy + je třeba potvrdit před prvním spojením. Pokud jiné jméno v přesměrování vrátí pouze fake-IP + adresy, sonda vyžádá nový souhlas a pokračuje od zobrazeného cíle. Přesměrování z veřejné + adresy na místní zůstává blokované. Blokovaný cíl lze předvyplnit pro nový běh. + Časy jsou v ms. TCP končí začátkem TLS, TTFB měří čekání po odeslání hlaviček. + Pomlčka značí fázi, která neproběhla, například DNS při opětovném použití spojení. + U HTTPS ukáže systémem ověřený řetězec, algoritmus a platnost certifikátů. Po chybě + handshake zobrazí důvod a další spojení se slabší validací neotevírá. +- **RDAP** přijímá veřejnou IP nebo číslo AS (s předponou AS i bez ní). V nabídce karty + veřejné IP lze vybrat zjištěnou adresu nebo ASN. Tato akce pouze předvyplní formulář. + Spuštění kontaktuje rdap.org a příslušný registr. Platí nastavení online dotazů z karty + veřejné IP. U registrů bez rozšíření cidr0 se přesné CIDR dopočítají z obou mezí rozsahu. + Chybějící údaje mají pomlčku. Výsledky diagnostiky se drží v paměti. + +## 9. Cíle nástrojů, TCP ping a MAC → výrobce (zadání 48, 2026-12-02) + +### Historie a oblíbené cíle + +- Jeden sdílený seznam pro Ping, TCP ping, Traceroute, Porty, DNS, DNS záznamy, Web/TLS a RDAP. + Ikona hodin u pole cíle otevře nabídku: nejdřív **oblíbené** (hvězdička, vlastní popisek), + pak **naposledy použité**. Každý nástroj nabízí jen položky, které přijme + (`targetFits` v `shared/.../lan/ToolTargets.kt`): host/IP pro Ping, TCP ping, Traceroute, + Porty a DNS; jméno nebo IP pro DNS záznamy; jen `http(s)://` URL pro Web/TLS; veřejná IP + nebo ASN pro RDAP. Text `AS…` se jako hostname nenabízí. +- Historie: posledních **10** cílů (MRU), zapisuje se při spuštění s platným vstupem (i když + uživatel pak potvrzení cíle zruší). Hostname a IP se porovnávají bez ohledu na velikost + písmen. U URL se do automatické historie **neukládá query ani fragment** (mohou nést tokeny); + oblíbená URL se uloží přesně tak, jak ji uživatel výslovně označil. +- Oblíbené: nejvýše **30**, popisek nejvýše 40 znaků (řídicí a formátovací znaky se nahradí). + Přejmenování existující oblíbené jde i na limitu; 31. cíl se odmítne hláškou. +- „Vymazat historii“ v nabídce maže jen naposledy použité, oblíbené zůstávají. Pro obrazovku + Nastavení (zadání 46) je připravené `LanToolStore.clearTargetHistory(context)`; ViewModel + nástrojů sleduje DataStore, takže se změna projeví hned. +- Úložiště: `files/datastore/lan-tools.json` (pole `targets` v `LanToolPreferences`), jen + v telefonu, `allowBackup=false`. Při čtení se data znovu normalizují (limity, duplicity, + nebezpečné znaky), poškozený soubor nahradí výchozí hodnoty jako dosud. + +### TCP ping + +- Nový nástroj „TCP ping“: opakovaný TCP connect na host:port (výchozí **443**), **1 s** mezi + začátky pokusů, počet 1–1000 nebo prázdné = do zastavení, časový limit z pole „Časový limit“. +- Odpověď = dokončený handshake (čas connect); **RST (odmítnuto), vypršení a chyba = ztráta**. + Statistika min/avg/max/jitter/ztráta je `pingStatistics` jako u pingu, graf a řádky vzorků + sdílí UI pingu; počty open/refused/timeout/error jsou pod stavem. +- Vždy **nejvýše 1 spojení naráz**: další pokus začne až po uzavření předchozího socketu. +- Cíl prochází stejnou cestou jako Ping: překlad jména, volba sítě (`chooseToolRoute`), + připnutí adresy, stejné potvrzení cíle mimo vlastní síť (počítá se 1 port), zrušitelné + tlačítkem Zastavit nebo změnou sítě. IPv6 funguje jako u kontroly portů. +- Export (TEXT/CSV/JSON) obsahuje u ztraceného vzorku stav `REFUSED`/`TIMEOUT`/`ERROR`. + +### MAC → výrobce + +- Nástroj „MAC → výrobce“: jedna MAC nebo vložený výpis `show mac address-table` (Cisco), + `display mac-address` (Huawei), `/interface bridge host print` (MikroTik). +- Tvary `xxxx.xxxx.xxxx`, `xxxx-xxxx-xxxx`, `xx:xx:xx:xx:xx:xx`, `xx-xx-xx-xx-xx-xx`. + Kandidát přilepený k další hex číslici nebo oddělovači (delší adresa, IPv6, hexdump) se + nebere. Holých 12 hex číslic se záměrně nebere (ve výpisech jde častěji o něco jiného). +- Limit vstupu **64 KiB (UTF-8) a 2000 řádků**; nad limitem se nic neparsuje a zobrazí se hláška. +- Tabulka: MAC (kanonicky `AA:BB:…`), výrobce z přibaleného IEEE OUI (MA-L/MA-M/MA-S, nejdelší + prefix), příznaky **lokální** (U/L bit) a **multicast** (I/G bit), počet výskytů. Lokálně + spravovaná a skupinová adresa výrobce nemá. Vše offline; tabulku lze exportovat stávajícím + LAN exportem (sloupec detail: `locally-administered`, `multicast`, `count=N`). diff --git a/docs/funkce/mobilni-sit.md b/docs/funkce/mobilni-sit.md index 984aa7b..d959c87 100644 --- a/docs/funkce/mobilni-sit.md +++ b/docs/funkce/mobilni-sit.md @@ -50,8 +50,9 @@ Celkový stav `CellularState`: `airplaneMode`, `noSim` (žádná aktivní SIM a nebo `READ_BASIC_PHONE_STATE` (API 33+), jinak `null`. Bez nich se použije `TelephonyDisplayInfo.getNetworkType()` (API 31+ bez oprávnění). Každé volání chrání `SecurityException` (i `UnsupportedOperationException` a chybu binderu) → neznámá hodnota. -- `requestCellInfoUpdate()` ani `getAllCellInfo()` se nepoužívají: signál je jen ze - `SignalStrength.getCellSignalStrengths()`. +- Monitor karty signál bere jen ze `SignalStrength.getCellSignalStrengths()`. Dřívější „seznam + buněk se nepoužívá“ zrušilo rozhodnutí **D31** ([plan.md](../plan.md)): `requestCellInfoUpdate()` + volá jen rozbalený „Detail buňky“ (§8); `getAllCellInfo()` se nepoužívá dál. ## 3. Standard (RAT) @@ -146,3 +147,40 @@ Kód: `androidApp/.../overview/OverviewCards.kt` (karty), `wifi/live/SignalScree - **Rychlost.** Test na mobilních datech uloží do kontextu operátora, standard a signál datové SIM na začátku (`SpeedCellularContext`), viz [speedtest.md](speedtest.md). +## 8. Detail buňky (zadání 53, D31, 2026-12-01) + +Pod každou SIM (kompaktní karta i hlavní mobilní karta) je řádek „Detail buňky ›“; po rozbalení: + +- **Obsluhující buňky** (`ServingCell`): hlavní (registrovaná / `CONNECTION_PRIMARY_SERVING`, v NSA + kotva LTE) a sekundární (`CONNECTION_SECONDARY_SERVING`: NR noha NSA, agregace LTE). Nadpis + „LTE · B3 · 1815 MHz“ / „5G NR · n78 · 3549,99 MHz“ a štítek Hlavní/Sekundární; řádky EARFCN / + NR-ARFCN, PCI, ID buňky (ECI s rozpadem „eNB · lokální ID“, NCI bez rozpadu, protože délka gNB ID + je proměnná), TAC, šířka kanálu (jen LTE `CellIdentityLte.getBandwidth`; NR šířku `CellInfoNr` + nemá a `PhysicalChannelConfig` vyžaduje privilegované oprávnění), timing advance (jen když je: + LTE 0..1282, NR surový index T_A 0..3846 od API 34), RSRP / RSRQ / SINR (NR SS s CSI zálohou + jako měřidlo). +- **Sousední buňky** (`NeighborCell`): technologie, pásmo, PCI, ARFCN a RSRP; seřazené od + nejsilnější, bez RSRP na konci, duplicity (tech, ARFCN, PCI) sloučené, nejvýš 16. Soused bez PCI + i ARFCN se vynechá. +- 2G/3G obsluhující buňka: jen věta „Připojeno přes 3G – detail je jen pro LTE a 5G“ (plus případní + LTE/NR sousedé). +- **Pásmo:** hlášené modemem (`getBands`, API 30+) má přednost; jinak odvozené z ARFCN + (`lteBandForEarfcn`, `nrBandsForArfcn`, tabulky a zdroje v [zavislosti.md](../zavislosti.md)). + U NR se pásma překrývají (n78 ⊂ n77, n1 ⊂ n65/n66, n20/n28/n14); bere se první podle preference + a UI ho označí „(odhad)“. Frekvence: LTE F_DL podle 36.101, NR globální rastr 38.104. +- **Oprávnění:** jen s již udělenou `ACCESS_FINE_LOCATION` i `READ_PHONE_STATE`. Bez nich rozbalený + detail vysvětlí proč a nabídne tlačítka stávajících toků („Povolit polohu“ = dialog jako u Wi-Fi, + „Povolit telefon“ = dialog „Zobrazit obě SIM“; po trvalém odmítnutí „Nastavení aplikace“). + Oprávnění se znovu přečtou po každém návratu do popředí. +- **Obnova:** `CellDetailViewModel.show/hide` z `LifecycleResumeEffect` rozbaleného detailu, takže + jen při viditelném detailu a aplikaci v popředí; `cellDetailSchedule` dovolí každé SIM nejvýš + jeden `requestCellInfoUpdate` za 5 s (i při rychlém sbalení a rozbalení), požadavek má limit 4 s + a je zrušitelný. Selhání nechá poslední odpověď na obrazovce. Prázdná odpověď (typicky vypnutá + služba polohy) = text „Systém nevrátil žádné buňky“. +- **Jen lokálně:** údaje drží jen `CellDetailViewModel` v paměti; sbalení / odscrollování / pauza je + zahodí. Nic se neukládá, neexportuje, nesdílí ani neposílá a diagnostický report (zadání 47) je + neobsahuje ([bezpečnost § Detail buňky](../bezpecnost.md#detail-buňky-zadání-53-d31-2026-12-01)). +- **Testy:** `shared/.../cellular/CellDetailTest.kt` (krajní hodnoty EARFCN a NR-ARFCN, frekvence, + preference a víceznačnost NR, validace všech polí včetně `UNAVAILABLE`/`UNAVAILABLE_LONG`, NSA, + řazení a limit sousedů, plánovač 5 s). Emulátor: fáze `cell-detail` (`tools/run_m1_checks.py`), + snímky CS/EN a stav bez oprávnění. Fyzický checklist: [testování](../testovani.md) (§19, M53-*). diff --git a/docs/funkce/nastaveni.md b/docs/funkce/nastaveni.md new file mode 100644 index 0000000..d021e85 --- /dev/null +++ b/docs/funkce/nastaveni.md @@ -0,0 +1,107 @@ +# Systém a nastavení (zadání 46) + +Stav: implementováno 2026-12-01, emulátorová evidence v interním +reportu 51, fyzický checklist v [testovani.md](../testovani.md) §22. + +## Obrazovka Nastavení + +Podobrazovka Přehledu jako O aplikaci (počet záložek se nemění): menu „⋯“ v hlavičce Přehledu → +**Nastavení** (nad „O aplikaci“); z O aplikaci vede na Nastavení řádek „Aktualizace“. Zpět vrací tam, +odkud se otevřela. Klepnutí na kteroukoli záložku podobrazovky zavře. + +| Sekce | Obsah | Kde je stav | +|---|---|---| +| Vzhled | Motiv: Systém / Světlý / Tmavý (`NetKitTheme(darkTheme = …)`), ikony systémových lišt podle motivu | `AppSettings.theme`, DataStore `filesDir/datastore/settings.json` | +| Jazyk | Systém / Čeština / English (Android 13+, `LocaleManager.applicationLocales`); odkaz na systémové nastavení jazyka aplikace. Pod Androidem 13 jen informace, že se jazyk řídí systémem | systém (per-app language), ne DataStore | +| Měření | „Displej zapnutý během měření“, výchozí zapnuto | `AppSettings.keepScreenOn` | +| Souhlasy a online dotazy | Přepínač Online dotazy (veřejná IP a poskytovatel v Přehledu, RDAP v Nástrojích a veřejná IP ve widgetu stavu sítě); Automatické hledání v LAN → Zapomenout (potvrzení, všechny sítě); Upozornění M-Lab (NDT7) → Zobrazit znovu | `overview` SharedPreferences, `lan-devices` SharedPreferences, `speedtest.json` | +| Historie a cíle | Historie rychlosti (LibreSpeed, NDT7) → Smazat; Historie iperf3 → Smazat (obojí s potvrzením a počtem záznamů); Poslední server iperf3 → Zapomenout; Vymazat historii cílů → potvrzení s počtem záznamů, oblíbené zůstávají | `speedtest.json` (`noBackupFilesDir`), `filesDir/datastore/lan-tools.json` | +| Aktualizace | Přesunutá karta z O aplikaci (přepínač, stav, Zkontrolovat teď, Stáhnout) a poznámka, co kontrola odesílá | beze změny (`update` SharedPreferences) | + +Každá akce jde přes ViewModel, který data vlastní (`LanDevicesViewModel.forgetAllConsents`, +`LanViewModel.clearTargetHistory`, `SpeedTestViewModel.clearHistory/forgetIperfTarget/resetNdt7Consent`, `WifiLiveViewModel.setPublicIpLookup`), +takže otevřené obrazovky vidí změnu hned. Celá akce (zápis, změna stavu, zrušení běžících operací) běží +ve `viewModelScope`; Nastavení jen čeká na výsledek, takže odchod z obrazovky nebo +rotace akci nepřeruší v půli (revize kolo 1). Řádek „Poslední server iperf3“ ukazuje uložený cíl +(`SpeedUiState.savedIperfTarget`), ne rozepsaný formulář. Výsledek akce („Hotovo“ / „Nepodařilo se uložit“) je pod +řádkem. Po potvrzení akce „Vymazat historii cílů“ vidí Nástroje změnu přes odběr z DataStore. + +Soubor nastavení: přísný JSON (`AppSettingsCodec` v `commonMain`, schéma 1, nejvýš 4 KiB, hloubka JSON +podle `JSON_MAX_DEPTH`); poškozený soubor DataStore nahradí výchozími hodnotami. UI se vykreslí až po +prvním přečtení souboru (`SettingsHost`), aby vynucený motiv neproblikl systémovým. + +## Jazyk aplikace (per-app language) + +- `androidResources { generateLocaleConfig = true }` + `res/resources.properties` + (`unqualifiedResLocale=cs`). AGP vygeneruje `LocaleConfig` s `cs` (výchozí) a `en` a doplní + `android:localeConfig` do sloučeného manifestu (kontroluje `ManifestExportsTest`). +- NetKit je v systémovém seznamu Nastavení → Aplikace → NetKit → Jazyk (Android 13+). +- Volba v aplikaci volá framework `LocaleManager` (bez AppCompat); systém aktivitu znovu vytvoří, + otevřené Nastavení zůstane (`rememberSaveable`). +- Po změně jazyka se překreslí oba widgety, přejmenuje se existující kanál relací a běžící služba aktualizuje text oznámení. +- Pod Androidem 13 se jazyk řídí systémem: anglický systém → EN, jinak výchozí CS. +- **Generované `values-cs`** (`generateCzechLocaleStrings` v `androidApp/build.gradle.kts`): + čeština je v nekvalifikovaném `values/`. Při seznamu jazyků (jazyk aplikace `cs` na anglickém systému = + `[cs,en_US]`, nebo systém `čeština, angličtina`) Android vezme řetězec z kvalifikované shody dalšího jazyka + (`values-en`) dřív než z výchozích zdrojů. Na emulátoru API 35 byla první aktivita v novém procesu česky, + ale každá znovu vytvořená (přepnutí jazyka z Nastavení, `CLEAR_TASK`) anglicky. Build proto kopíruje + všechny překládané `string`/`plurals`/`string-array` z `values/` do vygenerovaného `values-cs`; zdrojem + textů zůstává `values/`, `translatable="false"` (např. `app_name`, který přepisuje build `dev`) se nekopíruje. + Nový český text se tedy píše jen do `values/`. Kontrola: `CzechLocaleResourcesTest`. + +## Zpět (predictive back) + +- `android:enableOnBackInvokedCallback="true"` v `` (systémové animace zpět na Android 13+). +- Zpět z jiné záložky než Přehled přepne na Přehled (`tabBackTarget`); na Přehledu zpět patří systému + (aplikace odejde na pozadí, Android 12+ ji neukončí). +- Handler záložek se registruje před obrazovkami, takže všechny vnitřní `BackHandler` mají přednost: + formulář WoL, editor a správa klíčů/snippetů SSH, terminál (dotaz na zavření relace), detail zařízení, + O aplikaci, licence, Nastavení a dialogy. + +## Displej zapnutý během měření + +`ui/KeepScreenOn.kt`: `KeepScreenOn(running)` nastaví `View.keepScreenOn` view kompozice (okno aktivity +dostane `FLAG_KEEP_SCREEN_ON`), jen když běží měření, volba je zapnutá a obrazovka je zobrazená. Držitelé +se počítají (`screenOnHolders`), takže končící obrazovka nezruší jinou. Není to wake lock ani nové +oprávnění; funguje jen v popředí. Když displej zhasne (volba vypnutá), NetKit se zastaví a měření +skončí, protože na pozadí neběží (D29). + +| Obrazovka | Podmínka | +|---|---| +| Přehled — záznam obchůzky | `walk.status == RECORDING` | +| Rychlost (LibreSpeed, NDT7, iperf3) | `state.running` | +| Nástroje — ping, TCP ping, traceroute a porty | `runStatus == RUNNING`, u obou pingů včetně průběžného běhu | +| SSH | vybraná relace je připojená a terminál je vidět (ne editor, klíče, otisky, snippety) | + +## Testy + +- `commonTest`: `AppSettingsTest` (motiv, kodek a odmítnutí poškozeného souboru, jazyk z tagů, zpět, + podmínka a počítání držitelů), `SpeedHistoryClearTest` (mazání po skupinách, cíl iperf3, souhlas NDT7). +- JVM: `SettingsStoreTest` (DataStore, poškozený/přerostlý soubor, perzistence), `ManifestExportsTest` + (`enableOnBackInvokedCallback`, `localeConfig`, vygenerované `cs`, `en`), `CzechLocaleResourcesTest` + (vygenerované `values-cs` = všechny překládané položky `values/`, bez `translatable="false"` a přepisů `dev`). +- Emulátor: fáze `system-settings` (`tools/run_m1_checks.py --phase system-settings --language cs|en`). + +## Záloha konfigurace + +V Nastavení otevřete **Záloha konfigurace**. NetKit přes systémový výběr dokumentů uloží jeden JSON. +Šifrování heslem je předvolené. Vypnutí vyžaduje potvrzení, protože soubor obsahuje i adresy, +uživatelská jména, příkazy a veřejné otisky serverů. Ztracené heslo nelze obnovit. + +| Sekce v náhledu | Co se obnoví | +|---|---| +| SSH | Profily a skupiny, režim ověření, spouštěcí příkaz, keepalive a ProxyJump podle pravidel SSH v2. Shoda podle názvu, při změně cíle se odpojí uložené heslo. Export vyžaduje jedinečné názvy SSH profilů. | +| Telnet a sériové profily | Samostatná volba pro každý typ, identita podle ID, včetně skupiny a parametrů linky. Telnet se znovu ptá na přenos bez šifrování. | +| Snippety | Globální i vázané na profil. Nový nebo změněný příkaz vyžaduje ruční Enter. Při samostatné obnově musí odpovídat místní profil a cíl. | +| Přesměrování SSH | Lokální pravidla a dynamický port. Obnovený SOCKS vyžaduje ověření. | +| Důvěryhodné SSH servery | Samostatná volba, výchozí vypnutá. Náhled uvádí otisky. Existující konflikty a dříve odmítnuté endpointy se přeskočí. | +| Wake-on-LAN | Sloučení podle ID. Zůstává požadavek na SecureOn. Heslo pro importovanou kartu zadejte znovu. | +| Předvolby nástrojů a oblíbené cíle | Dvě volby. Parametry pingu, porty, vstup a interpretace masky kalkulátoru. Oblíbené adresy včetně štítků, URL bez query a fragmentu. | +| Servery | Vlastní URL LibreSpeed a poslední host a port iperf3. | +| Nastavení | Motiv, displej při měření a jazyk aplikace na systému podporujícím tuto volbu. | + +Při obnově otevřete soubor, u šifrovaného zadejte heslo a zkontrolujte počty nových, změněných +a přeskočených položek. U předvoleb, seznamu oblíbených, serverů a nastavení značí jedna změna +náhradu celé sekce. Před potvrzením lze sekce přepínat nebo operaci zrušit. Po potvrzení se +NetKit zavře. Při dalším spuštění přepne všechny vybrané soubory najednou. Změnu úložiště od náhledu +ohlásí v Nastavení a ponechá dosavadní konfiguraci. Brána SSH chrání také obrazovku zálohy. diff --git a/docs/funkce/speedtest.md b/docs/funkce/speedtest.md index 03e5180..a6c2dec 100644 --- a/docs/funkce/speedtest.md +++ b/docs/funkce/speedtest.md @@ -10,16 +10,21 @@ Signál), stejný vzor jako Zařízení | Nástroje. Kořenový tag `speed_scree **M4 (A1, A3, 2026-10-27):** test běží na **aktivní síti** (Wi-Fi, mobilní data, ethernet nebo VPN), ne už jen přes Wi-Fi. Na měřené síti (mobilní data, hotspot označený jako měřený) se před -startem vždy zobrazí odhad spotřeby dat a test běží až po potvrzení (rozhodnutí O-3, §4). +startem zobrazí upozornění na spotřebu dat a test běží až po potvrzení (rozhodnutí O-3, §4). Kontext výsledku na mobilních datech obsahuje operátora, standard a signál datové SIM (§3). +TalkBack oznámí změnu fáze měření. Po dokončení přečte naměřené směry a jejich rychlosti +v Mbit/s. U iperf3 pojmenuje také typ testu. V grafu průběhu lze odečíst minimum, maximum +a poslední hodnotu každé série. + ## 1. Cíl a rozhodnutí -Přesný a vypovídající test rychlosti aktivní sítě (Wi-Fi, mobilní data, VPN) → internet s dvěma nezávislými enginy: +Rychlost aktivní sítě lze měřit proti internetové službě nebo vlastnímu serveru v LAN či za VPN. | Engine | Server | Spojení | Proč | |---|---|---|---| | **LibreSpeed** (vlastní klient protokolu) | preset `https://rychlost.zelina.eu` (veřejný LibreSpeed kolegy na Proxmoxu), nebo vlastní `https://` URL | 6 souběžných stahování, 3 odesílání, HTTP/1.1 přes TLS | vícestreamový test podobný Ookla, server pod kontrolou, nízká latence v ČR | +| **iperf3** | vlastní host a port (výchozí 5201) | TCP, 1–8 streamů v jednom směru | měření konkrétní trasy, volitelný limit na stream | | **NDT7** (M-Lab) | nejbližší server z `locate.measurementlab.net/v2/nearest/ndt/ndt7` | 1 WebSocket přes TLS na směr | nezávislá reference, serverové `TCP_INFO`/BBR metriky | Proč ne Ookla / nPerf: obě vyžadují komerční SDK a licenční smlouvu (nelze otevřít repo, @@ -45,7 +50,7 @@ s `access_token` z locate, User-Agent `NetKit/ (Android)`, metadata locate → stahování → odesílání → uložení; NDT7 nemá vlastní ping, „latence bez zátěže“ je `MinRTT` z `TCP_INFO` serveru při stahování. -**Propustnost.** Čítač bajtů každého směru se vzorkuje po 250 ms. Výsledek +**Propustnost LibreSpeed a NDT7.** Čítač bajtů každého směru se vzorkuje po 250 ms. Výsledek = bajty po skončení náběhu / čas po náběhu (Mbit/s, dekadicky: `B × 8 / µs`). Náběh (TCP slow start, plnění bufferů) se nezapočítává: @@ -140,9 +145,13 @@ se uloží s příznakem „neúplný“; uživatelem zastavený běh se neuklá testu (např. zapnutí Wi-Fi na mobilních datech) → „Připojení se během testu odpojilo nebo změnilo“, výsledek neúplný. - **Potvrzení dat na měřené síti (O-3).** Chybí-li `NET_CAPABILITY_NOT_METERED`, test se - nespustí hned: dialog ukáže odhad spotřeby (z posledního výsledku na stejném typu sítě, - jinak výchozí) a plný test běží až po „Spustit test“. Potvrzení platí jen pro tu síť; - přepnutí na jinou měřenou síť vyžaduje nové potvrzení. Lehký režim se nedělá. + spustí až po výslovném potvrzení tlačítkem „Spustit test“. U iperf3 bez limitu dialog + upozorní na možný přenos několika GB. S limitem ukáže horní mez testovacích dat v desetinných MB + zaokrouhlenou nahoru. Při uploadu vychází z rychlosti na stream, počtu streamů a délky testu. + Při stahování používá stejnou mez jako přijímač (viz níže). Přenos probíhá + jedním směrem a síťová režie se přičítá zvlášť. Pro LibreSpeed a NDT7 vychází odhad z posledního + použitelného výsledku na stejném typu sítě, případně z výchozí hodnoty. Potvrzení platí jen + pro danou síť. Přepnutí na jinou měřenou síť vyžaduje nové potvrzení. Po potvrzení běží plný test. - **Životní cyklus.** Zastavit, odchod ze segmentu/záložky, pozadí aplikace zruší vše (zavře sokety přes `CallRegistry`); rotace test neruší. Žádná služba na pozadí. - **Souběh.** Během testu neběží živá telemetrie Signálu (segment není složený) a navigace @@ -154,7 +163,7 @@ se uloží s příznakem „neúplný“; uživatelem zastavený běh se neuklá (PAC/ruční), test proto neprojde (chyba spojení). Alternativa — číst `LinkProperties.httpProxy` měřené sítě — by měřila proxy; zatím záměrně ne. - **Spotřeba dat.** Podle linky stovky MB až jednotky GB na test; na mobilních datech jde - z tarifu, proto potvrzení s odhadem. + z tarifu, proto je na měřené síti nutné potvrzení. - **CPU telefonu.** OkHttp WebSocket alokuje každou přijatou NDT7 zprávu (≤ 1 MiB typicky); na gigabitu může být limitem CPU/GC telefonu — porovnat s LibreSpeed. - **Upload na straně klienta** měří bajty předané soketu; po náběhu odpovídá lince, krátké @@ -193,3 +202,41 @@ a malé `garbage.php` → „není LibreSpeed“, limit spojení → „funkčn NDT7 stahování/odesílání/tvrdý limit/porušení protokolu/locate 204, přechod na další server, bez opakování po protokolové chybě nebo po začátku přenosu, chybná URL → typovaná chyba. Navázání na aktivní `Network` JVM test neověří — patří do fyzického checklistu (M2-40 až M2-49, M4-06 až M4-08). + +## 7. iperf3 na Androidu + +V Přehledu → Rychlost vyberte **iperf3 (vlastní server)**. Zadejte DNS jméno nebo IP adresu a TCP port. +Výchozí běh odesílá jedním streamem po dobu 10 s. Přepínač směru zapíná stahování (`-R`). +Počet streamů odpovídá `-P` (1–8), délka `-t` (3–30 s). Limit v desetinných Mbit/s odpovídá +`-b` **na každý stream**. Minimální kladný limit je 0,01 Mbit/s. Prázdné pole nebo nula dovolí plnou rychlost. Čtyři streamy po +10 Mbit/s tedy zatíží trasu přibližně 40 Mbit/s plus režie. Při nastaveném limitu odpovídá +vyjednaný TCP blok zhruba 100 ms dat jednoho streamu, v rozmezí 1–128 KiB. + +Graf ukazuje součet klientských čítačů všech streamů po jedné sekundě. Hlavní hodnota a historie +vycházejí z přijímače za celý interval včetně náběhu. Při uploadu se sečtou bajty přijaté serverem +a vydělí se nejdelším serverovým `end_time` souběžných streamů. Pokud některému streamu chybí +platný počet bajtů či čas nebo jeho čas leží mimo 0,5–2násobek zvolené délky testu, aplikace +použije pro celý upload klientské čítače odeslaných bajtů a klientský čas. + +Při stahování počítá bajty i čas telefon do konce měření. Po `TEST_END` může dočíst nejvýše +celkem 8 MiB × počet sjednaných streamů, zatímco čeká na výměnu výsledků. Tyto bajty nezvyšují +naměřenou rychlost. Při nastaveném `-b` měření i dočítání společně čerpají z limitu pro příjem. +Mez v bajtech je `bit/s na stream × počet streamů × (1,1 × délka v sekundách + 1) / 8 + 2 × velikost bloku × počet streamů`. +Sekunda navíc pokrývá zpoždění řídicího spojení a bloková rezerva počítá s daty ve frontě. +Při prvním přečteném bajtu nad mez klient odešle `CLIENT_TERMINATE`, zavře spojení a zobrazí +„Server poslal víc dat, než odpovídá nastavenému limitu. Test byl ukončen.“ Limit se vztahuje na data přečtená aplikací. +Účtovaný síťový provoz může zahrnovat i data na cestě, data v TCP bufferech a režii. +Čítač TCP retransmisí se zobrazí, když server poskytne počet pro každý stream. +Chybějící údaje nemají hodnotu nula. Do historie se zapíše dokončený směr a poslední host a port +zůstanou v soukromých předvolbách. Tento klient podporuje TCP bez autentizace. + +Řízení používá `shared/.../Iperf3Protocol.kt`, síťový přenos `androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Client.kt`. +Původ popisu protokolu a postup testu s reálným serverem uvádějí +[závislosti](../zavislosti.md#protokol-iperf3) a [testování](../testovani.md#17-iperf3-na-loopbacku-a-v-emulátoru). + +## 8. Sdílení výsledku (zadání 47, 2026-12-02) + +Po doběhnutém běhu, který se uložil do historie, nabízí karta měření „Sdílet výsledek“: dialog +s náhledem textu (čas, typ sítě, server, engine, stahování/odesílání, latence, jitter, retransmise, +příznak neúplnosti) a přepínačem SSID (výchozí vypnuto); odeslání přes systémové sdílení. Text +sestavuje `speedShareText` v `shared/.../report/ReportText.kt`. diff --git a/docs/funkce/ssh.md b/docs/funkce/ssh.md index 14806a2..f4e7814 100644 --- a/docs/funkce/ssh.md +++ b/docs/funkce/ssh.md @@ -21,8 +21,12 @@ i UX; implementuje se poslední. - Port forwarding (local/remote/dynamic), SFTP/SCP, jump host/ProxyJump, agent forwarding, X11, mosh, Telnet, sériová konzole. Zapsat do roadmapy po M1. + *Doplněno zadáním 41 (2026-12-01):* local `-L`, dynamic `-D` (SOCKS5) a ProxyJump jsou + implementované (§10); `-R`, agent forwarding a X11 zůstávají mimo rozsah. - Foreground service je mimo M1. Podle rozhodnutí správce D-7 (2026-10-26) relace na pozadí přežívá nejvýše **5 minut**, pak se zavře; systém může proces ukončit dříve. + *Doplněno zadáním 42 (2026-12-02, D30):* s povolenými oznámeními drží relace služba na + popředí bez limitu; bez oznámení platí 5 minut (§11). SFTP prohlížeč je implementován; SCP ne. ## 3. Bezpečnostní požadavky @@ -38,7 +42,7 @@ i UX; implementuje se poslední. automaticky bez Enter (ochrana před paste-jackingem — vícerádkové vložení potvrdit). - `FLAG_SECURE` v SSH je přepínatelný; podle D-3 výchozí release zapnuto, debug vypnuto. Na API 33+ se při stejné volbě vypne i náhled v přehledu aplikací. -- Odemčení klíče biometrikou je M2. +- Volitelný zámek SSH vyžaduje ověření uživatele při přístupu k chráněným funkcím (zadání 50, viz níže). ## 4. Technické volby (rozhodne implementátor po rešerši, zápis do `zavislosti.md`) @@ -77,10 +81,10 @@ ani na správcově telefonu. | Klíče | Generování Ed25519, ECDSA P-256 a RSA 3072; import OpenSSH/PEM s passphrase; veřejný klíč lze zobrazit/kopírovat | Import RSA je konzervativně omezen také na nejméně 3072 bitů; privátní export není v UI | | Host key | SHA256 fingerprint, explicitní TOFU, atomické vložení nového klíče, přesné připnutí veřejného klíče pro `[host]:port` | Změněný klíč nelze přijmout v připojovacím dialogu. Po nezávislém ověření lze starý záznam explicitně zapomenout; tím se zavřou relace | | Autentizace | JSch password, publickey, keyboard-interactive; dialog identifikuje lokální profil a `uživatel@endpoint` odděleně od textu serveru | Interoperabilita vendorů a skutečného MFA zůstává fyzickému testu | -| Terminál | Vlastní VT subset: kurzor, mazání, vkládání/mazání znaků a řádků, scroll region, alternativní obrazovka, základní SGR/256/truecolor; PTY resize s debounce, nastavení písma, max. 5000 řádků a 8 MiB kompaktní historie | **Není úplný xterm emulátor:** široké znaky, kombinující Unicode, DEC kreslicí znaková sada a nevyjmenované režimy nejsou implementované. `nano`/`top`/`htop` nelze prohlásit za správně vykreslené pouze z unit testů parseru | +| Terminál | Vlastní parser podmnožiny xterm (zadání 43, oddíl „Terminál xterm-256color“ níže): `xterm-256color`, SGR 16/256/truecolor a atributy, alternativní obrazovka, scroll region, DECOM, vkládání/mazání znaků a řádků, široké a kombinující znaky, DEC čárová grafika, titulek OSC 0/2 (jen zobrazení), bracketed paste; PTY resize s debounce, nastavení písma, max. 5000 řádků a 8 MiB kompaktní historie | **Není úplný xterm:** myš, sixel/obrázky, OSC 52, dotazy na barvy/titulek, VT52, levý/pravý okraj (DECLRMM), dvojitá šířka/výška řádku a 8bitové C1 nejsou implementované; ZWJ emoji sekvence se kreslí po složkách. Skutečné `vim`/`htop`/`mc`/`tmux` ověřuje fyzický checklist | | Vstup | Přímý `InputConnection` bez lokálního echa; Enter, Backspace, Tab, Ctrl/Alt, DECCKM šipky, Home/End, PgUp/PgDn, Insert/Delete, F1–F12, Shift-Tab a Ctrl+šipky. Maskované pole „Text pro terminál“ zůstává jako rozbalitelná záloha | Nová přímá IME cesta musí projít instrumentací s reálným fokusem a viditelnou klávesnicí; interaktivní aplikace ověří správce | | Schránka | Výběr/kopírování a explicitní kopie výpisu; vložení nejprve do vstupního pole, potvrzení a nahrazení řídicích znaků/nových řádků mezerami | Vícerádkový skript nelze jedním vložením automaticky spustit; uživatel musí jednotlivé příkazy odeslat vědomě | -| Relace | Nejvýše čtyři aktivní relace, zavření jednotlivě/všech, reconnect; standardní Android route včetně VPN; `NetworkCallback` upozorní na možnou ztrátu spojení | Pozadí max. 5 minut, bez foreground service; stav „nejspíš ztraceno“ je varování podle změny sítě, nikoli důkaz TCP disconnect | +| Relace | Nejvýše čtyři aktivní relace, zavření jednotlivě/všech, reconnect; standardní Android route včetně VPN; `NetworkCallback` upozorní na možnou ztrátu spojení | Pozadí max. 5 minut bez oznámení; s oznámeními služba na popředí `specialUse` (zadání 42, §11); stav „nejspíš ztraceno“ je varování podle změny sítě, nikoli důkaz TCP disconnect | | Soukromí obrazovky | `FLAG_SECURE` + recents API33, no-learning/no-suggestions, bez ukládání vstupu do saved state | IME příznaky jsou žádost vůči klávesnici. Biometrika zůstává M2 | Vybráno `com.github.mwiede:jsch:2.28.0` s Bouncy Castle lightweight API pro moderní @@ -283,8 +287,9 @@ Android exportuje `netkit-ssh-profiles.json`: `format: "netkit-ssh-profiles"`, iOS používá stejný formát se zdrojem `netkit-ios`; import přijímá oba zdroje. Každý profil obsahuje `alias`, `host`, `port`, `username`, `authentication` (`PASSWORD`, `KEY`, `INTERACTIVE`), `startupCommand` a `keepaliveSeconds`. -Pořadí pole je pořadí v aplikaci. Import navíc přijímá volitelné `group` jako -metadata náhledu; skupiny se v aplikaci neukládají. +Pořadí pole odpovídá ručnímu pořadí SSH profilů. Export v2 přidá `group` jen u vyplněné skupiny. +Import v1/v2 uloží dodanou skupinu a při chybějícím poli zachová skupinu existujícího profilu. +Telnet, sériové profily a historie použití zůstávají v zařízení. Export neobsahuje lokální ID, `secretRef`, `keyRef`, klíče ani důvěru serverů. Obsahuje však cíle, uživatelská jména a startovací příkazy: před přenosem ověřte, @@ -337,3 +342,190 @@ promítne se do exportu a nemění se běžnou editací profilu. Implementační a testovací důkazy jsou v reportu 32 (interní záznam); fyzické přijetí zůstává v checklistu správce. + +## 10. Produktivita: snippety, log relace, `-L`/`-D`, ProxyJump (zadání 41, 2026-12-01) + +**Snippety.** Globální seznam (nejvýše 100) s volitelným omezením na jeden profil: název +(1–60 znaků), příkaz (jeden řádek, 1–4096 znaků, bez řídicích znaků včetně ESC a nového +řádku) a volba „Odeslat Enter“. Správa je v kartě *Snippety* na seznamu profilů, panel +v terminálu je vodorovný řádek nad přídavnými klávesami (nejdřív globální, pak snippety +profilu). Odeslání jde stejnou omezenou frontou zápisu jako psaní. Snippet není tajemství: +ukládá se nešifrovaně v `ssh.json` a exportuje se. Text se slovy typu `password`, +`secret`, `community`, `token`, `psk`, `heslo` vyvolá před uložením varování s volbou +„Uložit přesto“ (heuristika, neblokuje). Smazání profilu smaže i jeho snippety. Dvojice +(název, rozsah) musí být jedinečná — editor duplicitu odmítne s vysvětlením (jinak by +export selhal na `DUPLICATE_ALIAS`). + +**Log relace.** Menu relace → *Zaznamenávat do souboru*: nejdřív upozornění, že log může +obsahovat citlivé údaje, potom systémový dialog pro vytvoření souboru (SAF, `text/plain`). +Nikdy není zapnuté samo. Zapisuje se od okamžiku zapnutí: hlavička s názvem relace a +časem začátku, čistý text výstupu, patička s časem konce (a důvodem, pokud log zastavil +limit nebo přetečení). Filtr (`TerminalLogFilter`, `commonMain`) odstraní CSI/OSC/DCS, +volby znakové sady a C1; CR, backspace, posun kurzoru vlevo/vpravo a mazání řádku +aplikuje jako řádkový editor, takže editace v shellu a progress bary dají viditelný text. +Celoobrazovkové programy (cursor addressing) se nerekonstruují, jejich text zůstane v +pořadí příchodu. Zápis běží mimo hlavní vlákno přes frontu 512 bloků; když ji výstup +předběhne, log se zastaví (hláška), paměť neroste. Limit 50 MiB včetně hlavičky a patičky, +pak stop s hláškou. Log končí zastavením, koncem relace nebo zavřením záložky. + +**Local `-L`.** V profilu až 8 pravidel `místní port → host:port` (místní porty 1024–65535, +navzájem různé). Naslouchání **jen 127.0.0.1** (literál, vlastní `LocalForwardServer`; JSch +`setPortForwardingL` se nepoužívá, protože po EOF klienta kanál hned odpojí a zahodí odpověď) +a jen po dobu relace; cílový host překládá SSH server. Stav pravidel +je pod stavovým řádkem relace: *aktivní* s tlačítkem „Kopírovat 127.0.0.1:port“, nebo +*port obsazený* / *chyba* — chyba jednoho pravidla neruší shell ani ostatní pravidla. +Nejvýše 32 současně přesměrovaných klientů na relaci (klient nad limit se hned zavře, JSch +pro něj neotevře kanál ani vlákno). Editor upozorní, že port je během relace dostupný všem +aplikacím v telefonu. EOF jednoho směru jen polouzavře druhý (odpověď po EOF klienta dorazí). +`-R` není. + +**Dynamic `-D`.** Volitelný SOCKS5 na 127.0.0.1:port, jen CONNECT, IPv4/IPv6/doména (doménu +překládá SSH server). **Výchozí je přihlášení RFC 1929**: uživatel `netkit` a náhodné heslo +(20 znaků, `SecureRandom`) nové pro každou relaci, jen v paměti a ve stavu UI (u relace se +zobrazí a lze ho zkopírovat jako citlivý obsah schránky), nikam se neukládá. Volba „Bez +přihlášení (nedoporučeno)“ v profilu je výslovná a s varováním. Parser (`Socks5`, `commonMain`) bere +vstup jako nedůvěryhodný: doména 1–253 znaků jen `[A-Za-z0-9._-]`, port ≠ 0, typované +odpovědi (07 nepodporovaný příkaz, 08 typ adresy, 05 když server cíl odmítne). Server +nejvýše 32 souběžných klientů, handshake do 10 s, otevření kanálu do 15 s, vlastní vlákna +(nezatěžují `Dispatchers.IO`); kanál se odpojí při jakémkoli selhání před předáním tunelu. + +**ProxyJump.** Profil může odkazovat na jiný profil jako jump host; řetěz nejvýše 3 skoky, +cyklus i chybějící odkaz se odmítnou před jakýmkoli spojením (`resolveSshJumpChain`, +chyba *Řetěz jump hostů je neplatný*). Výběr v editoru nabízí jen profily, které cyklus +nevytvoří. Každý skok má vlastní instanci JSch, vlastní ověření klíče serveru proti +`hostKeys` pro svůj endpoint (stejné TOFU/změněný klíč jako přímé spojení) a vlastní +přihlášení; dialog ověření uvádí, pro který skok je (`jump · user@[host]:port → cíl`). +Další skok vede přes `direct-tcpip` kanál předchozí relace (vlastní `Proxy` nad +`getStreamForwarder`), takže host cíle překládá jump host jako u `ssh -J`. Keepalive +běží na prvním (socketovém) skoku; vnitřní skoky nemají vlastní socket timeout. +Startovací příkaz a forwardy patří jen cílovému profilu. Smazání profilu, který je jump +hostem, upozorní na závislé profily; ty pak ztratí odkaz a připojují se přímo. + +**Výměnný formát.** Export v2 přidává volitelná pole: u profilu `proxyJump` (alias jiného +profilu ze stejného souboru) a v kořeni `snippets` (`name`, `text`, `sendEnter`, volitelně +`profile` = alias). Bez snippetů a jump hostů je soubor bajtově stejný jako dřív, takže +ho přijme i starší verze aplikace; soubor s novými poli starší verze odmítne celý +(`UNKNOWN_FIELD`, nic se nezapíše). Forwardy se neexportují (zůstávají v telefonu; import +existujícího profilu je zachová). Import: `proxyJump` je povolený v1 (PC skript) i v2, +`snippets` jen v2. Alias se hledá nejdřív v souboru, pak mezi jednoznačnými jmény profilů +v telefonu; nenalezený, cyklus nebo řetěz delší než 3 skoky přesune řádek do +„Přeskočené“ (PROXY_JUMP), i tranzitivně. Řádek bez `proxyJump` místní odkaz zachová. +Snippety se slučují podle (název, profil); snippety přeskočeného profilu se vynechají. +Nový nebo textově změněný snippet z importu má vždy `sendEnter = false` (Enter zapne uživatel +ručně); stejný text zachová místní volbu. Náhled vypíše u každého snippetu nový text, u +změněného „před → po“, a změnu existujícího snippetu je nutné výslovně potvrdit +zaškrtnutím. Potvrzení importu přehrává všechna ID vygenerovaná v náhledu +(`SshImportPlan.generatedIds`: nové profily včetně řádků přeskočených kvůli ProxyJump a +nové snippety). +Starý (legacy) export toleruje nová pole úložiště jen v jejich výchozí hodnotě. +`tools/netkit_ssh_export.py` při exportu mapuje `ProxyJump` s jediným aliasem, který je +sám exportovaný, na `proxyJump`; `a,b`, `user@host:port`, cyklus nebo delší řetěz zůstávají +přeskočené s varováním. `install-pubkey` ProxyJump dál přeskakuje. + +iOS: sdílené modely a import/export jsou společné; UI pro snippety, log, forwardy a +ProxyJump na iOS není (mimo rozsah). Po změně sdíleného SSH API spustí koordinátor +workflow `iOS`. Důkazy: interní report 45. + +## 11. Relace na pozadí a SFTP (zadání 42, 2026-12-02) + +**Služba na popředí (`SshSessionService`, D30).** Typ `specialUse` (rozbor typů a zdroje: +[bezpecnost.md § SSH na pozadí a SFTP](../bezpecnost.md)). Běží od první živé relace do poslední, +jen s povolenými oznámeními; spojení dál vlastní `SshViewModel`, služba drží jen prioritu procesu +a oznámení. + +- **Oznámení:** počet relací a názvy profilů (bez hostu/IP/uživatele), na zamčené obrazovce jen + „NetKit: relace terminálu běží“ (od 44 společné pro SSH, Telnet a USB); klepnutí otevře záložku SSH (whitelist cíl `ssh`), akce **Odpojit vše** + zavře všechny relace a služba skončí. +- **Oprávnění `POST_NOTIFICATIONS`:** dotaz jednou při prvním připojení. Odmítnuto → relace na + pozadí končí po 5 minutách jako dřív a nad terminálem je varování s tlačítkem do nastavení + oznámení aplikace. Povolení později se projeví po návratu do aplikace. +- **Konec relace = konec služby:** poslední zavřená relace, „Odpojit vše“, zavření aplikace z + přehledu posledních (aktivita končí) i zánik procesu. +- Testovací hook: `NetKitApplication.sshBackgroundGraceMillis` (instrumentace zkracuje 5 min na 3 s). + +**SFTP prohlížeč.** Menu relace → **Soubory (SFTP)**: kanál `sftp` na stávající relaci (žádné nové +přihlášení). Výpis (složky první, symlinky jako odkazy), navigace do složky/odkazu na složku a o +úroveň výš, stažení do SAF, nahrání ze SAF, nová složka, přejmenování, smazání s potvrzením (složka jen +prázdná, u odkazu jen odkaz). Průběh s velikostí, zrušení; přenos pokračuje na pozadí, dokud žije +relace. Limit 2 GiB, výpis max. 5000 položek, jména s `/`, řídicími znaky nebo `.`/`..` se skryjí. + +- Cesty: zobrazený adresář je vždy odpověď serveru na `realpath`; `..` jde jen do `realpath`. +- Nahrání a přejmenování nikdy nepřepíše existující položku: dočasný `.netkit-upload-*.part` + + `hardlink@openssh.com`, jinak čisté RENAME; server s `posix-rename@openssh.com` bez hardlinku + nahrání i přejmenování souboru odmítne (JSch by jinak poslal přepisující posix-rename). Zbytkový + případ u přejmenování složek: bezpecnost.md. +- Zrušení zabere i u visícího serveru nebo poskytovatele SAF (po 2 s se kanál a stream zavřou), každá + operace má limit nečinnosti 30 s. +- Jeden prohlížeč najednou (na vybrané relaci); zavření relace zavře i prohlížeč. +- Mimo rozsah: SCP, synchronizace složek, editace souborů, přepsání existujícího souboru, iOS. + +Důkazy: interní report 46 (fáze `ssh-background`, `ssh-background-denied`, +`ssh-sftp`, `ssh-forwards-panel`). + +## 12. Terminál xterm-256color (zadání 43, 2026-12-02) + +**Parser a buffer** (`shared/.../ssh/TerminalBuffer.kt`, `commonMain`, převezme i iOS) jsou napsané +z veřejné specifikace xterm ctlseqs a ECMA-48 podle modelu DEC ANSI parseru (zdroje a data +v [evidenci závislostí](../zavislosti.md#15-terminál-xterm-zadání-43-ověřeno-2026-12-02)); kód +ConnectBotu ani Termuxu se nečetl. PTY hlásí `xterm-256color`, změna mřížky jde jako `window-change`. + +- **Podporováno:** SGR 0–9, 21–29, 30–37/90–97/40–47/100–107, 38/48 `;5;n`, `;2;r;g;b` i dvojtečkové + `38:2::r:g:b`; alternativní obrazovka `?47`/`?1047`/`?1049` (s DECSC/DECRC) bez scrollbacku; + DECSTBM, DECOM, IND/RI/NEL, IL/DL/ICH/DCH/ECH/EL/ED, IRM, REP, tabulátory (HTS/TBC/CHT/CBT), + DECSC/DECRC s atributy a znakovou sadou, DECCKM, DECAWM, DECTCEM, DECSTR, DECALN, DEC Special + Graphics (`ESC ( 0`, SO/SI), DSR/CPR, DA1/DA2. Mazání barví pozadí aktuální barvou (BCE). +- **Široké znaky:** šířka podle Unicode 18.0 East Asian Width (W/F = 2 buňky), Mn/Me/Cf = 0 + (připojí se k předchozí buňce, nejvýše 16 znaků). Široký znak se na pravém okraji nerozdělí; + přepsání poloviny vymaže i druhou. Tabulku generuje `tools/update_terminal_width.py` + z lokálních souborů UCD. Vykreslení: JetBrains Mono nemá CJK ani emoji, glyf ze záložního písma + nemá přesně dvě buňky, takže zbytek řádku za širokým znakem může být vodorovně mírně posunutý + (snímek `ssh-xterm-alt.png`); pozice v bufferu, kurzor a kopírování jsou správně. Přesné + zarovnání by vyžadovalo kreslení po buňkách (Canvas) — otevřený bod pro další řez. +- **Titulek OSC 0/2:** jen zobrazení v hlavičce za názvem profilu v uvozovkách (název profilu + zůstává první, server se tak nevydává za jiný profil); řídicí a bidi znaky se odstraní, nejvýše + 128 znaků. Titulek se nikdy neposílá zpět (`CSI 21 t` ignorováno). +- **Bracketed paste (`?2004`)** obalí běžné odeslání ze záložního pole značkami + `ESC[200~ … ESC[201~`. Řídicí znaky včetně ESC a nových řádků se před odesláním nahradí mezerou. + Při zapnutém Ctrl nebo Alt odešle pole odpovídající klávesovou sekvenci i v režimu `?2004`. +- **Limity a bezpečnost:** escape sekvence nejvýše 256 znaků (delší se zahodí bez účinku, + OSC/DCS se dočtou do ST/BEL), CAN/SUB ruší sekvenci, nejvýše 32 parametrů po 65535; neznámé + sekvence se tiše zahodí. OSC 52, dotazy na barvy, odkazy OSC 8, myš a obrázky se ignorují. +- **Výkon:** buffer vrací pro nezměněný řádek stejnou instanci `TerminalRow`, Compose díky strong + skipping překresluje jen změněné řádky a řádek kurzoru; historie se kopíruje jen při změně. + Propustnost parseru měří `TerminalXtermTest.throughputOfTypicalAndRandomOutput` (10 MB). +- **Paleta** (`TerminalPalette`): xterm 6×6×6 a šedá rampa, základních 16 barev laděných pro + tmavý povrch terminálu (kontrast ≥ 4,5:1, šedá 8 ≥ 3:1, test). Terminál je tmavý ve světlém + i tmavém režimu aplikace (design.md §2); dim = poloviční míchání s pozadím, hidden = barva pozadí. +- **Klávesová lišta:** Esc/Tab/Ctrl/Alt/šipky/Enter/Backspace, rozšíření Home/End/PgUp/PgDn/ + Insert/Delete/Shift-Tab/F1–F12 (beze změny proti zadání 41). Myš záměrně není. + +Ověření: `TerminalXtermTest` (JVM), emulátorová fáze `ssh-xterm` proti loopback fixture a fyzický +checklist SSH43 v [testování](../testovani.md). iOS UI zatím nové atributy (dim/italic/underline, +titulek) nekreslí; sdílené API zůstalo zpětně kompatibilní. + +## 13. Telnet a sériová konzole přes USB-OTG (Android, zadání 44) + +V záložce **Terminál** vytvoří tlačítko **SSH profil** stávající typ profilu. V nabídce **Další akce** +lze přidat profil Telnet nebo sériové linky. Všechny relace sdílejí záložky, mřížku terminálu, +klávesy, změny rozměru i akci „Odpojit vše“ v oznámení. Import a export „SSH profily“ pracuje s typem SSH. +Služba na popředí (§11) je jedna pro všechny transporty, limit čtyř živých relací i pětiminutový limit +bez oznámení platí stejně. SFTP prohlížeč (§11) je jen u SSH relace; Telnet ani sériová linka ho nenabízí. + +- **Telnet** standardně používá TCP/23. Klient přijímá vzdálené ECHO a SGA, místní SGA, NAWS a TTYPE. + Název terminálu je `xterm-256color`. Velikost okna se posílá po dohodě NAWS a při změně mřížky. + Obsah terminálu pochází z protistrany. Enter odesílá NVT CR LF. Přihlašovací údaje se zadávají do živé relace. +- **Sériová linka** nabízí 1200–921600 Bd, 5–8 datových bitů, paritu None/Odd/Even/Mark/Space, + 1/1,5/2 stop bity a řízení toku žádné nebo RTS/CTS. Dostupné kombinace určuje ovladač konkrétního čipu. + Chybu otevření uživatel uvidí v záložce relace. Presety pro Cisco/Huawei/Fortigate a MikroTik + obnovují celou konfiguraci na 9600 nebo 115200 Bd, 8N1, bez řízení toku. +- Při připojení vyberte port podle VID/PID, čísla USB zařízení a portu převodníku. Odebrání kabelu + ukončí relaci, její výpis zůstane v záložce. Nabídka klávesnice obsahuje „Odeslat BREAK (250 ms)“. +## 14. Připojený terminál na šířku (zadání 52) + +V připojené relaci dostane terminál na šířku prostor hlavní navigace i lišt relace. Přepočet řádků a sloupců po otočení a otevření IME používá rozměr výstupu a předává jej vzdálenému PTY. V nabídce u přímého vstupu otevře **Zobrazit relace a klávesy** přepínač relací, profily, snippety a speciální klávesy. Při sbaleném ovládání ho rozbalí také gesto **Zpět**. Další **Zpět** otevře dialog pro zavření relace. Přechodem na Profily se obnoví navigace a SSH spojení může běžet dál. + +## Zámek a seznam profilů na Androidu + +Přepínač **Zámek SSH** je v seznamu profilů u ochrany obrazovky. Zapnutí i vypnutí potvrzuje systém. Odemčení platí standardně pět minut od ověření. Uživatel může zvolit 0 až 15 minut. Při nule se ověřuje každý nový vstup do SSH a každá chráněná akce. Vypršení zakryje i otevřený terminál, dialog klíčů nebo SFTP. Běžící spojení může dál obsluhovat služba na pozadí. Připnutá zkratka po odemčení ukáže obvyklé potvrzení připojení. + +SSH, Telnet a USB konzole sdílejí seznam. Hledání odpovídá části aliasu, hostu, uživatelského jména nebo skupiny bez ohledu na velikost písmen. Skupina se nastavuje v editoru, maximum je 60 znaků. Ruční přesun vymění dvě zobrazené položky stejné skupiny. Abecední řazení a řazení podle posledního úspěšného připojení zachovávají uložené ruční pořadí. Nepoužité profily jsou v režimu podle použití poslední. diff --git a/docs/funkce/wifi-analyzer.md b/docs/funkce/wifi-analyzer.md index af50f7e..5271baa 100644 --- a/docs/funkce/wifi-analyzer.md +++ b/docs/funkce/wifi-analyzer.md @@ -288,24 +288,38 @@ jsou v reportu 08; zde se nepředjímá průchod nově napsaných testů ani př (`shared/.../wifi/Spectrum.kt`, `BssLoad.kt`, `SpectrumTest`) a čtení prvku BSS Load v mapování `ScanResult`. UI (composables) dodá jiný řez. Emulátor ani telefon: **NOT RUN**. +Při zaměření grafu přečte TalkBack nejsilnější AP ve vybraném pásmu, jeho kanál a RSSI +před výčtem vykreslených sítí. Připnutí a pořadí legendy výběr nejsilnějšího AP neovlivní. + ### Co se počítá -- **Spektrum:** pro každé pásmo lineární frekvenční osa v MHz. 2,4 GHz kanály 1–13 - (14 jen při AP na 2484 MHz), 5 GHz globální 20MHz kanály 36–64, 100–144 a 149–177, - 6 GHz 1–233 po 4 (zvláštní kanál 2 jen při AP na 5935 MHz). Osa jde od dolní hrany - prvního po horní hranu posledního kanálu; mezery bez kanálu (5 GHz: 5330–5490 a - 5730–5735 MHz) mají skutečnou šířku, osa tedy není index kanálů a spojené šířky - zachovávají poměr. Popisky: všechny kanály 2,4 GHz; 5 GHz 36, 52, 100, 116, 132, 149, 165; - 6 GHz 1, 33, 65, …, 225. Rastr není potvrzením regionálního povolení. -- **AP jako lichoběžník:** obsazený rozsah z `occupiedFrequencySegments` (střední - frekvence a šířka z `ScanResult`; bez středu primární kanál ±šířka/2; 80+80 dva - segmenty), vrchol = RSSI. Horní plošina je zúžena o 10 % šířky na každé straně, jde jen +- **Spektrum:** pro každé pásmo lineární frekvenční osa v MHz. 2,4 GHz (zadání 34, + „jako WiFiman“): kanály 1–14 vždy, rozsah 2397–2499 MHz (krajní 20MHz hrany ±5 MHz, + konstanty `SPECTRUM_24_*`), oblast nad 2483,5 MHz je `outOfBand` (stínovaná jako mezery, + popisek 14 tlumený, v popisu přístupnosti „Kanál 14 je mimo pásmo povolené v EU.“). + 5 GHz globální 20MHz kanály 36–64, 100–144 a 149–177, 6 GHz 1–233 po 4 (zvláštní + kanál 2 jen při AP na 5935 MHz); tam osa jde od dolní hrany prvního po horní hranu + posledního kanálu bez okraje. Mezery bez kanálu (5 GHz: 5330–5490 a 5730–5735 MHz) mají + skutečnou šířku, osa tedy není index kanálů a spojené šířky zachovávají poměr. Popisky: + všechny kanály 2,4 GHz; 5 GHz 36, 52, 100, 116, 132, 149, 165; 6 GHz 1, 33, 65, …, 225; + první a poslední popisek se vykreslí vždy, při kolizi se vynechávají vnitřní. Rastr + není potvrzením regionálního povolení. Zobrazovací osa ≠ rastr zdraví kanálů + (`channelHealthChannels`): ten má pro 2,4 GHz dál 1–13 a kanál 14 jen při AP na 2484 MHz. +- **AP jako lichoběžník:** obsazený rozsah z `occupiedLayout`/`occupiedFrequencySegments` + (střední frekvence a šířka z `ScanResult`; 80+80 dva segmenty), vrchol = RSSI. Bez + `centerFreq0` a se šířkou nad 20 MHz se střed bere z pevného rastru + (`bondingRasterCenterMhz`): 2,4 GHz 40 MHz primární 1–4 → +10 MHz (HT40+), 10–13 → + −10 MHz (HT40−); 5 a 6 GHz bloky 40/80/160 z `recommendationChannels`. Nejednoznačný + případ (2,4 GHz 5–9 a 14, primární mimo úplný blok, 6 GHz kanál 2 a 320 MHz) se kreslí + jen přes primární 20 MHz a nese `BondingCenterSource.UNKNOWN`; UI v legendě a detailu AP + píše „šířka 40 MHz, střed neznámý“. Hlášený střed má vždy přednost. Stejný model používá + `overlapScore`, zdraví kanálů i doporučení. Horní plošina je zúžena o 10 % šířky na každé straně, jde jen o vizuální tvar, ne o spektrální masku. Pořadí: nejsilnější první, remíza podle stabilního klíče `accessPointKey`. Spektrum nemá zobrazovací limit (graf obsazení dál kreslí nejvýše 6 AP) a stejně jako graf zůstává i po vypršení doporučení. - **Počty AP** pro přepínač Vše / 2,4 / 5 / 6 GHz: jen AP s platnou frekvencí (`snapshotAccessPoints`), z aktuální datové sady. -- **Zdraví kanálu** pro každý 20MHz primární kanál osy: +- **Zdraví kanálu** pro každý 20MHz primární kanál rastru (`channelHealthChannels`): - *Překryv* = `overlapScore` (součet výkonu sousedních AP v mW vážený podílem překryvu s 20MHz kanálem) převedený na dBm. Jedno AP přímo na kanálu s −70 dBm dá −70 dBm; AP překrývající kanál z poloviny se započte poloviční váhou. @@ -319,10 +333,10 @@ v mapování `ScanResult`. UI (composables) dodá jiný řez. Emulátor ani tele |---|---|---| | Výborný | pod −82 dBm nebo žádný překryv | pod 20 % | | Dobrý | −82 dBm | 20 % | -| Průměrný | −72 dBm | 40 % | -| Špatný | −62 dBm | 70 % | +| Slabší | −72 dBm | 40 % | +| Slabý | −62 dBm | 70 % | -Hranice patří vyšší kategorii (např. přesně −72 dBm = Průměrný). Překryv se před +Hranice patří vyšší kategorii (např. přesně −72 dBm = Slabší). Překryv se před porovnáním zaokrouhlí na 0,01 dB. Práh −82 dBm odpovídá obvyklé úrovni detekce preambule 20MHz kanálu (CCA); ostatní prahy jsou **politika aplikace** zvolená pro čitelnost, ne normativní hodnoty. Konstanty jsou v `Spectrum.kt` (`HEALTH_*`). @@ -380,8 +394,8 @@ testy viz níže; emulátor ani fyzický telefon zatím **NOT RUN**. Cílem je o `null` znamená „měřeno, ale ztraceno“ (timeout, bez Wi‑Fi) a počítá se do ztrátovosti; mezera v časech znamená „neměřeno“ (obrazovka pozastavena). Statistiky: poslední, min, průměr, max, počet, ztrátovost v % a jitter (průměr absolutních rozdílů po sobě jdoucích -platných vzorků; ztracené vzorky se přeskakují). Kvalita signálu: vynikající ≥ −55 dBm, -dobrý ≥ −67 dBm, uspokojivý ≥ −75 dBm, jinak slabý (konstanty `SIGNAL_*_MIN_DBM` +platných vzorků; ztracené vzorky se přeskakují). Kvalita signálu: výborný ≥ −55 dBm, +dobrý ≥ −67 dBm, slabší ≥ −75 dBm, jinak slabý (konstanty `SIGNAL_*_MIN_DBM` v `LiveTelemetry.kt`). Čistá logika je v `shared/.../wifi/LiveTelemetry.kt`, Android část v `androidApp/.../wifi/live/`. @@ -451,7 +465,7 @@ Mobilní část: [mobilni-sit.md §7](mobilni-sit.md#7-ui-v-přehledu-m4-a3). - **Řádek DNS (O-5):** pod popiskem „DNS“ je IP prvního resolveru aktivní sítě (`LinkProperties.getDnsServers`), nebo „Soukromé DNS · host“ při aktivním Private DNS (v oportunistickém režimu bez jména IP resolveru); na druhém řádku dotazované jméno. -- **Řádky Latence** mají poznámku na druhém řádku pod popiskem (mono `dim`); hodnota vpravo +- **Řádky Latence** mají poznámku na druhém řádku pod popiskem (mono `muted`); hodnota vpravo nejvýš 55 % šířky, mezera 12 dp zůstává i na 360 dp s písmem 1,3. Ztráta paketů a jitter ukazují bez Wi-Fi jen hodnotu internetu. - **Roaming:** čas vlevo, změna pásma („2,4 → 5 GHz“) nebo kanálu („k. 36 → 100“) jako štítek @@ -487,3 +501,101 @@ Mobilní část: [mobilni-sit.md §7](mobilni-sit.md#7-ui-v-přehledu-m4-a3). [Settings](https://developer.android.com/reference/android/provider/Settings), [zapnutí vývojářských voleb](https://developer.android.com/studio/debug/dev-options). API 29 a reálné RF/HyperOS chování čekají na fyzické ověření; automatické důkazy jsou v interním záznamu. + +## Rozšíření zadání 38 (2026-12-01) + +Kód: `shared/.../wifi/SpectrumPins.kt`, `EssGroups.kt`, `WifiScanExport.kt`, `WalkLog.kt`, +`RegionalRaster.kt` (bez `java.*`/`android.*`, testy `WifiExtensionsTest`, `WalkLogTest`); +UI `WifiScreen.kt`, `SpectrumChart.kt`, `WifiExportFiles.kt`, `live/WalkCard.kt`. Emulátorová +evidence fáze `wifi-extensions` (`docs/testovani.md` §10) je jen UI se syntetickými AP, ne RF. + +### Připnutí AP do spektra + +- Dlouhý stisk řádku AP nebo přepínač „Připnout do grafu“ v detailu AP. Nejvýš 3 připnuté, + podle BSSID; čtvrté připnutí se odmítne (hláška), nic se tiše nevyřadí. AP bez BSSID připnout nejde. +- Pořadí stop v grafu (a tím barva a značka): připojený AP → připnuté v pořadí připnutí → + nejsilnější ostatní, celkem nejvýš 6 (`WIFI_CHART_AP_LIMIT`). Připnuté jsou tedy vidět i jako + nejslabší v pásmu. +- Připnutí přežije nový sken (shoda BSSID, aktualizuje se SSID a pásmo), ne restart aplikace + (jen paměť ViewModelu). Připnutý AP, který v posledním skenu chybí úplně, je v legendě pásma, + kde byl naposledy vidět, jako „SSID · nenalezen v posledním skenu“ (bez stopy). Takový pin nemá řádek v seznamu, + proto má v kartě spektra vlastní tlačítko „Odepnout“ (podle BSSID); jinak by blokoval limit 3. AP, který jen + přešel do jiného pásma, „nenalezen“ není. + +### Skupiny podle SSID (ESS) + +- Přepínač „Seskupit podle SSID“ v hlavičce karty Sítě. Řádek skupiny: SSID, počet AP (BSSID), + pásma s kanály po pásmech („2,4 GHz k. 1 · 5 GHz k. 36“; samotné číslo kanálu je mezi pásmy + nejednoznačné), nejsilnější RSSI; klepnutí rozbalí jednotlivá AP (odsazená, s detailem). +- Seskupený seznam pokrývá **všechna pásma** (ESS má rádia ve více pásmech); filtr SSID a řazení + platí dál, graf spektra dál ukazuje vybrané pásmo. Shoda SSID je přesná (velikost písmen se liší + = jiná síť). Skrytá SSID se neseskupují, každé zůstává samostatným řádkem. + +### Export skenu + +- Ikona exportu v hlavičce karty Sítě → dialog s varováním, že soubor obsahuje identifikátory + sítí v okolí (SSID, BSSID, výrobce), volba CSV/JSON → systémový výběr souboru + (`ACTION_CREATE_DOCUMENT`, SAF). Bez nového oprávnění, nic se neodesílá; soubor zůstane jen tam, + kam ho uživatel uloží. Selhání zápisu smaže právě vytvořený dokument a ukáže chybu. +- Exportuje se celá poslední datová sada (všechna pásma, bez ohledu na filtr), řazená podle pásma, + kanálu a BSSID. Sloupce: `time` (ISO 8601 UTC času měření AP, jinak času skenu), `ssid`, `bssid`, + `vendor`, `band`, `channel`, `width_mhz`, `center_mhz`, `center2_mhz` (80+80), `frequency_mhz`, + `rssi_dbm`, `security`, `standard`, `bss_load_stations`, `bss_load_utilization_percent`, `connected`. + Střed je hodnota hlášená AP (`centerFreq0`), ne odhad z rastru; neznámé = prázdná buňka / `null`. +- CSV podle RFC 4180: textové buňky v uvozovkách, uvozovky zdvojené, čárky a konce řádků uvnitř + uvozovek zůstávají; text začínající `= + - @`, tabulátorem nebo CR dostane prefix `'` (ochrana + před vzorci v tabulkovém procesoru). Čísla (RSSI) jsou bez uvozovek a bez prefixu. JSON: + `{"format":"netkit-wifi-scan","version":1,"exportedAt",…,"accessPoints":[…]}`. Limit souboru 8 MiB + jako LAN export. + +### Záznam obchůzky (Přehled) + +- Karta „Záznam obchůzky“ v Přehledu (při Wi-Fi, nebo když záznam existuje): Spustit → každou + sekundu jeden vzorek ze stávající telemetrie: RSSI, BSSID, kanál, RX/TX link rate, ping brány + (echa podle času dokončení: každé dokončené echo — i timeout, který skončí až po vzorku své + sekundy — patří právě k prvnímu dalšímu vzorku; vzorek nese nejnovější odezvu a příznak, zda se + od předchozího vzorku některé echo ztratilo; echa dokončená po posledním vzorku se při zastavení + připíšou k němu). Události: roaming + (stávající `RoamingDetector`), změna kanálu téhož AP, značka místa (text 1–40 znaků, řídicí + znaky → mezera). +- Limit 2 h nebo 7200 vzorků, pak se záznam sám zastaví. Data jen v paměti do exportu nebo + zahození. Odchod z Přehledu nebo z aplikace (`setActive(false)`) záznam zastaví; žádná služba + na pozadí. +- Po zastavení souhrn: délka, vzorky, roamingy, změny kanálu, nejslabší RSSI, ztracené pingy + brány „N z M“ (jen odpovědi OK/ztráta, ne „bez Wi-Fi“), značky. Export CSV (jedna tabulka + `type,time,offset_s,…,detail`, typy `sample`, `roaming`, `channel_change`, `mark`) nebo JSON + (navíc souhrn), stejný dialog a SAF jako export skenu. +- UI uvádí, že přesnost je 1 s a délku handoveru z toho přesně určit nedá. +- Export skenu i záznamu sdílí `ExportSession` (`androidApp/.../wifi/ExportSession.kt`, bez Android typů): + text se serializuje při otevření výběru souboru a zapíše se přesně ten snímek; zrušení výběru nic + nezapíše ani nehlásí; výsledek bez připraveného textu (např. po smrti procesu) nebo selhání zápisu + = chyba. Pokryto `ExportSessionTest`. + +### Regionální rastr 2,4 GHz (informativně) + +- Kód země z `TelephonyManager.getNetworkCountryIso()` (API 1, bez oprávnění, jen funkce + telefonního rádia; prázdný bez registrace, např. v režimu letadlo). `WifiManager` veřejné + API pro kód země nemá (ověřeno 2026-12-01, `docs/zavislosti.md`). +- V detailu kanálu 2,4 GHz (zdraví kanálů): EU-27 1–13, US 1–11, JP 1–14 (14 jen 802.11b), a zda + je vybraný kanál mimo rastr. Bez kódu země nebo pro jinou zemi se nic nezobrazí. Skóre, + teplotní pás a doporučení se nemění (globální rastr 1/6/11). + +### Asociované linky Wi-Fi 7 v Přehledu + +Při spojení 802.11be na Androidu 14 a vyšším zobrazí Přehled kartu **Wi-Fi 7 · MLO**, pokud systém vrátí alespoň jednu asociovanou linku s platným ID. Každý řádek obsahuje ID, stav, pásmo, primární kanál, RSSI a šířku hlášenou AP. Aktivní linka má přiřazený provoz, nečinná je asociovaná bez přiřazeného provozu. Chybějící hodnotu značí pomlčka. + +Šířka pochází z posledních systémových výsledků skenu. Použije se nejnovější vzorek starý nejvýše 30 s se shodou AP MLD, ID linky a frekvence. Údaj popisuje šířku kanálu inzerovanou AP. Přehled kvůli němu nespouští sken. Adresa AP MLD a čtení šířky vyžadují udělenou přesnou polohu a zapnutou systémovou polohu. Telemetrie jednotlivých linek zůstává jen v paměti. [Ověření Android API](../zavislosti.md#17-wi-fi-7-mlo-zadání-52) +## Sdílení z Přehledu (zadání 47, 2026-12-02) + +- **Diagnostický report** (menu ⋮ → „Diagnostický report“): text nebo JSON s časem, verzí, typem + sítě, adresami, bránou, DNS, DHCP serverem a MTU (jsou-li známé), Wi-Fi link/kanál/šířkou + (z posledního systémového skenu, bez nového skenu)/standardem/RSSI, latencí a ztrátami brány + a internetu za poslední minutu (`pingStatistics` nad vzorky okna 60 s) a posledním speedtestem + a iperf3 z historie. SSID, BSSID a veřejná IP (včetně veřejně směrovatelných adres rozhraní) + jsou výchozí vypnuté. Akce Sdílet, Kopírovat, Uložit (SAF, `.txt`/`.json`); náhled ukazuje přesně + předávaný text. Formát JSON: `format = netkit-diagnostic-report`, `version = 1`. Čísla v textu + s desetinnou tečkou (technický zápis nezávislý na jazyku). Bez údajů o mobilní buňce. +- **Kopírování dlouhým stiskem:** dlaždice IPv4 a Brána, BSSID v kartě signálu, řádek DNS (adresa + resolveru/hostitel Soukromého DNS), uzly karty cesty (veřejná IP, kanál, IP telefonu). Zpětná + vazba: haptika, na API < 33 toast (od 33 systémové potvrzení), citlivé hodnoty skryté. +- Kód: `shared/.../report/`, `androidApp/.../overview/DiagnosticReport*.kt`, `androidApp/.../ui/ShareActions.kt`. diff --git a/docs/funkce/wol.md b/docs/funkce/wol.md index fa4a609..c61aaaf 100644 --- a/docs/funkce/wol.md +++ b/docs/funkce/wol.md @@ -13,8 +13,8 @@ - Přidání, úprava, smazání, řazení; export a import seznamu do JSON (bez tajemství) a import/export CSV ve formátu aplikace Wake On Lan (Mike Webb). -Mimo rozsah M1a: SecureOn heslo (6 B za paketem), zástupce na plochu a widget (M2), napojení -na LAN skener „probudit tento host“ (M2), WoL přes internet s port-forwardem (jde pokrýt tím, že +Zástupce na plochu, widget a napojení na LAN skener přibyly v zadání 36 (§ 7 níže); SecureOn heslo +(4/6 B za paketem) v zadání 39 (§ SecureOn níže). Mimo rozsah: WoL přes internet s port-forwardem (jde pokrýt tím, že cíl může být hostname/veřejná IP a port; dokumentace ovšem nic o veřejných adresách neobsahuje). ## 2. Technické detaily @@ -227,3 +227,89 @@ vytvoří pouze hlavičku, kterou import odmítne pro absenci zařízení. Napojení exportu do menu doplní Claude. Import výsledného souboru v aplikaci Wake On Lan na fyzickém telefonu musí ověřit správce; samotný round-trip v NetKitu kompatibilitu s aplikací Webb nedokazuje. + +## SecureOn (zadání 39, 2026-12-01) + +- Volitelné heslo karty za magic packetem: **6 B** zapsaných jako MAC (`11:22:33:44:55:66`, + i s `-`) nebo **4 B** jako IPv4 (`192.0.2.1`); paket má pak **108 B**, resp. 106 B + (`parseSecureOn`, `secureOnMagicPacket` v `commonMain`; původní `magicPacket` 102 B beze změny, + i kvůli Swift exportu). +- Heslo **není v `WolDevice`**: drží ho `WolSecureOnStore` (Android: `AndroidWolSecureOnStore` + nad `AndroidSecretStore`, jmenný prostor `wol`, AES-GCM, Keystore). Proto ho JSON ani Webb CSV + export nikdy neobsahuje a import JSON s polem `secureOn` skončí jako neznámé pole. CSV import + sloupec `secure_on` dál zahazuje a počet ukáže (stávající `secureOnDropped`). +- **Vazba na zařízení (revize 39/1):** záznam trezoru nese heslo a `secureOnBinding` zařízení + (normalizovaná MAC, režim cíle, vlastní cíl, port). Heslo se při odeslání použije jen při shodě + vazby (`secureOnPasswordFor`), takže zařízení nahrazené pod stejným ID cizí MAC/cílem staré heslo + nedostane. Import, který nahradí zařízení (nebo přidá ID už v trezoru), heslo těchto ID zahodí + **až po** uložení seznamu. Vlastní úprava MAC/cíle ve formuláři uložené heslo převáže **před** + uložením seznamu; selže-li pak uložení seznamu, převázání se vrátí (rollback). Formát trezoru je v2 + (v1 existovala jen v nevydané větvi). +- **Fail-closed (revize 39/2):** chráněné zařízení (v trezoru je pro jeho ID záznam, bylo chráněné při + posledním čtení, nebo trezor nejde přečíst), jehož heslo nejde získat nebo nesedí vazba, se + **neprobudí**: `SendFailure.SECURE_ON_UNAVAILABLE`, hláška „SecureOn heslo nedostupné — zadejte ho + znovu“. Formulář u záznamu s cizí vazbou upozorní; nové heslo ho nahradí, uložení bez hesla ho smaže. +- **Revize 39/3:** převázat lze jen heslo, jehož vazba odpovídala konfiguraci zařízení v okamžiku + otevření editoru (pozůstatek importu se nikdy nepřeváže). Po každém uloženém seznamu se příznaky + shody přepočítají z trezoru a nového seznamu, i když selže následná úprava trezoru. Zápis trezoru + + uložení seznamu + případný rollback běží `NonCancellable` s limitem 10 s na krok, takže zrušení + obrazovky nenechá trezor a seznam v rozporu. +- Formulář: sekce SecureOn s maskovaným polem. U uloženého hesla se hodnota nikdy nenačte + zpět: prázdné pole = ponechat, nové = nahradit, zaškrtnutí „Odebrat uložené heslo“ = smazat. + Smazání zařízení heslo odstraní až po úspěšném uložení seznamu (při chybě zůstane osiřelé heslo, + ne zařízení bez hesla); osiřelé záznamy se ořežou při dalším zápisu. +- Odeslání: `WolController.wake` načte heslo těsně před odesláním. Když šifrované úložiště + nejde přečíst a zařízení heslo mít může (bylo v seznamu při načtení, nebo úložiště nešlo + přečíst ani tehdy), odeslání skončí chybou (`SendFailure.IO`) místo paketu bez hesla. +- **Widget a společné odeslání (po sloučení zadání 36):** `sendWolWake` má parametr `secureOn` + (heslo se zjistí po výběru Wi-Fi, před prvním paketem; paket `secureOnMagicPacket`). Aplikace + (`WolController`) i widget (`runWolWidgetWake` → `secureOnPassword`) používají + `secureOnPasswordForSend` nad stejným šifrovaným úložištěm: vázané heslo → 108/106 B, cizí vazba → + `SECURE_ON_UNAVAILABLE` bez paketu (widget ukáže „SecureOn heslo nedostupné“). Widget nezná, která + zařízení jsou chráněná, proto při nečitelném úložišti blokuje vždy. Identita widgetu `wolDeviceKey` + (ID + MAC + čas vytvoření) a vazba hesla (MAC + cíl + port) se doplňují: import se stejným ID a jinou + MAC/časem widget odmítne jako jiné zařízení, změnu cíle/portu bez převázání zablokuje vazba hesla. +- **Revize 39/4:** `WolDevice.secureOnRequired` (netajný trvalý příznak v seznamu zařízení i v JSON + exportu/importu) říká, že zařízení heslo vyžaduje — nezávisle na tom, zda ho úložiště právě vydá. Nastaví + ho zadané heslo, zruší jen úmyslné „Odebrat uložené heslo“. Aplikace i widget s ním blokují i tehdy, + když záznam z čitelného úložiště zmizí. Nečitelné úložiště se novým heslem přepíše jen tehdy, když + žádné jiné zařízení heslo nevyžaduje (jinak chyba uložení, nic se tiše neztratí). Widget si při + odesílání drží otisk konfigurace (`wolDeviceBindingKey`, hash MAC/cíle/portu); změna cíle/portu během + série (synchronizace widgetu) zruší rezervaci, zvýší revizi a další zápis paketu guard odmítne. +- Ověření: `commonTest` `WolSecureOnTest` (108/106 B, parser, trezor, export/import bez hesla, + controller), loopback listener `tools/testsrv/wol_listener.py --secureon --count 1` + ověří 108 B a heslo netiskne; emulátorová fáze `wol-secureon`. + +## 7. Widget, pinned zkratka a WoL z LAN skeneru (zadání 36, 2026-12-01) + +**Use-case.** `sendWolWake` (`shared/.../wol/WolWake.kt`) dělá výběr Wi-Fi, cíl paketu +(auto broadcast / ruční cíl / `255.255.255.255`), opakování a odeslání; bez kontroly probuzení +a bez UI stavu. `WolController.wake` ho volá a předkontrolu „už odpovídá“ provádí v háčku +`beforeSend` na stejném místě jako dřív (stávající testy beze změny očekávání). + +**Widget (Jetpack Glance 1.2.0).** Po umístění na plochu se otevře výběr zařízení +(`WolWidgetConfigActivity`). Widget ukazuje název, tlačítko „Probudit“ a stav: „Připraveno“, +„Odesílám…“, „Odesláno HH:MM“, „Není Wi-Fi“, „Nelze určit broadcast“, „Odeslání selhalo“, +„Zařízení smazáno, klepněte pro výběr“ (bez tlačítka). MAC na plochu nejde. Klepnutí na název otevře +WoL záložku se zvýrazněným zařízením; u smazaného nebo nenastaveného widgetu výběr zařízení. +Odeslání běží v receiveru Glance se společným limitem 8 s od klepnutí (včetně načtení a zápisu stavu); +tlačítko nese v data URI vlastního `PendingIntent`u ID widgetu, klíč zařízení a revizi vykreslení, takže dvojí klepnutí pošle jednu sérii a tlačítko +vykreslené pro jiné zařízení se odmítne; po změně výběru během odesílání se série zastaví. Opakování se zkrátí na rozpětí nejvýš 4 s +(`wolWidgetRepeatCount`, např. 10× po 2 s → 3×). Kontrola probuzení se ve widgetu nedělá. +Bez periodické aktualizace; přejmenování a smazání zařízení v aplikaci widget překreslí. + +**Pinned zkratka.** Menu ⋮ na kartě zařízení → „Přidat na plochu“ (jen když spouštěč umí připnout). +Zkratka otevře WoL záložku se zvýrazněným zařízením, paket nepošle. Zkratka, widget i cíl navigace nesou +neprůhledný klíč zařízení (ID + MAC + čas vytvoření), ne ID. Smazání nebo nahrazení zařízení (stejné ID, +jiná MAC/čas, např. CSV import) zkratku zakáže s hláškou, přejmenování změní popisek. + +**Z LAN skeneru.** V detailu zařízení je „Probudit: “ pro uložené WoL zařízení s `probeHost` +rovným adrese hosta. Jen když žádné nemá přesnou adresu, rozhodují názvy hosta (NetBIOS/mDNS/PTR, bez +ohledu na velikost písmen a příponu `.local`) — jsou ze sítě a nesmí přebít adresu. Více kandidátů = +tlačítko pro každého s názvem skutečného cíle. Jinak „Přidat do WoL“ otevře formulář s názvem, IP v poli kontroly probuzení +a MAC z NetBIOS, pokud ji host poslal. **MAC z NetBIOS:** NBSTAT odpověď nese ve statistice 6B +UNIT_ID; Windows tam dává MAC adaptéru, Samba obvykle nuly. Nenulová unicast hodnota se nabídne, +uživatel ji potvrdí uložením formuláře. Jinak se MAC zadává ručně: Android 10+ aplikacím nedovolí +číst ARP tabulku ([změny soukromí Androidu 10](https://developer.android.com/about/versions/10/privacy/changes)). + +Bezpečnost a exportované komponenty: [bezpecnost.md § Zkratky, dlaždice a WoL widget](../bezpecnost.md). diff --git a/docs/licenses/protobuf-LICENSE.txt b/docs/licenses/protobuf-LICENSE.txt new file mode 100644 index 0000000..19b305b --- /dev/null +++ b/docs/licenses/protobuf-LICENSE.txt @@ -0,0 +1,32 @@ +Copyright 2008 Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Code generated by the Protocol Buffer compiler is owned by the owner +of the input file used when generating it. This code is not +standalone and requires a support library to be linked with it. This +support library is itself covered by the above license. diff --git a/docs/licenses/unicode-LICENSE.txt b/docs/licenses/unicode-LICENSE.txt new file mode 100644 index 0000000..56da589 --- /dev/null +++ b/docs/licenses/unicode-LICENSE.txt @@ -0,0 +1,39 @@ +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2026 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. diff --git a/docs/licenses/usb-serial-for-android-LICENSE.txt b/docs/licenses/usb-serial-for-android-LICENSE.txt new file mode 100644 index 0000000..98e65da --- /dev/null +++ b/docs/licenses/usb-serial-for-android-LICENSE.txt @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2011-2013 Google Inc. +Copyright (c) 2013 Mike Wakerly + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/docs/plan.md b/docs/plan.md index 7700b56..379e193 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -53,6 +53,10 @@ Kritérium úspěchu M1: správce týden nepoužije žádnou ze čtyř původní | D26 | (2026-10-31) **Mění D23 (spouštěč):** build webu spouští **Deploy Hook Workers Builds** (`osobni-web`, větev `main`), URL v secretu `OSOBNI_WEB_DEPLOY_HOOK` (environment `release`). `publish.yml` po ověření release hook zavolá a až 15 min čeká na `/latest.json` s novou verzí; první publikovaný release hook přeskočí (web přepne `netkitReleased` vlastním PR). `repository_dispatch` a `WEB_DISPATCH_TOKEN` odstraněny, žádný Cloudflare token v GitHubu. | Web nemá deploy job ani token v GitHubu (interní záznam). Rotace = smazat hook, vytvořit nový, vyměnit secret. | | D27 | (2026-10-31) **Výjimka z D16:** 1.0.0 vychází před fyzickým testem M3/M4; správce ho provede nad vydaným release APK a nález řeší opravná verze 1.0.x. | Rozhodnutí správce; aplikace prošla emulátorem, CI a revizemi, release podpis je potřeba ověřit stejně jen na vydaném APK. | | D28 | (2026-10-31) **Mění D12 (iOS):** iOS se začíná stavět. SwiftUI nad `:shared` (XCFramework), MVP včetně SSH (ping, porty, DNS, mDNS, info o Wi-Fi, speedtest, WoL, SSH), Android beze změny. Vývoj ve **veřejném** `Losminek/netkit-ios` (čistý export, jen syntetická data), protože standardní macOS runnery jsou ve veřejných repech zdarma; po auditu přenos do `netkit-dev` přes PR a archivace repa. Apple účet, TestFlight a test na zařízení mimo rozsah (rozhodne správce později). Zadání `prompty/28-ios-mvp.md`. | xtool (Linux) zamítnut: nepřeloží Kotlin `:shared`, Xcode SDK licencované jen pro Apple hardware, bez simulátoru (ověřeno 2026-10-31, `docs/ios.md` §7). Veřejné repo nejde zpětně „očistit“, proto čisté od začátku. | +| D29 | (2026-12-01) **Mění „mimo rozsah“ (widgety, zkratky):** widgety, zkratky aplikace a Quick Settings dlaždice jsou v rozsahu (vlna 1 podle interního návrhu vylepšení 37): WoL widget, statické a připnuté zkratky, dlaždice „Signál Wi-Fi“, widget stavu sítě z posledního měření v popředí. Hranice: bez `ACCESS_BACKGROUND_LOCATION` (SSID ve widgetu jen volitelně z popředí), bez síťového dotazu a periodické práce na pozadí, bez foreground service; akce z exportovaného intentu jen po klepnutí uživatele. Osa spektra 2,4 GHz vždy 1–14 s okrajem (jako WiFiman). Zadání `prompty/34–37`. | Rozhodnutí správce 2026-12-01. Android widgetům bez polohy na pozadí SSID nedá (ověřeno 2026-12-01, prace/37 §9); polohu na pozadí aplikace nežádá (bezpecnost.md). | +| D30 | (2026-12-01) **Výjimka z D16 (jako D27):** dokončit vlny 1–3 z interního návrhu vylepšení 37 včetně nezávislých revizí, emulátorových ověření a CI, a pak rovnou vydat release **bez předchozího fyzického testu**; správce testuje přímo oficiální vydané APK a nálezy řeší opravná verze. Podpis release a tag dělá správce (D22). | Rozhodnutí správce 2026-12-01. Riziko: chování HyperOS (widgety, pozadí, USB-OTG) se ověří až na vydané verzi. | +| D31 | (2026-12-01) **Release po vlnách 1–5:** verze **2.0.0** (versionCode 20000). Claude smí v noci dojít ve veřejném `Losminek/netkit` až po nepodepsaný draft: čistý export → PR → merge → tag `v2.0.0` → `release.yml` draft. Podpis (`tools/sign_release.sh … --upload`, hesla keystoru interaktivně) a publikaci draftu dělá správce. Vlna 5 navíc: detail mobilní buňky (`getAllCellInfo`) **jen lokálně** v UI (mění dřívější rozhodnutí `docs/funkce/mobilni-sit.md:53`), zadání 53. | Rozhodnutí správce 2026-12-01 večer před odchodem; audit funkcí interní záznam 50. | +| D32 | (2026-12-02) **Výjimka z D7 jen pro data Unicode:** tabulka šířek znaků terminálu (`TerminalWidth.kt`) odvozená z Unicode Character Database (`EastAsianWidth.txt`, `extracted/DerivedGeneralCategory.txt`) smí být v repu a v aplikaci pod **Unicode License V3** (SPDX `Unicode-3.0`, schválená OSI). Podmínky: atribuce v `NOTICE` (a jeho kopii v APK), plné znění licence v APK (`androidApp/src/main/assets/licenses/unicode-LICENSE.txt`, položka `unicode-data` v O aplikaci → Licence open source) a v iOS seznamu licencí, protože iOS terminál používá stejnou tabulku ze `:shared`. Výjimka se nevztahuje na kód ani jiná data Unicode, nová položka pod jinou licencí potřebuje vlastní rozhodnutí. | Rozhodnutí správce 2026-12-02 před vydáním 2.0.0. Licence je permisivní (podmínkou je přiložit copyright a povolení); bez tabulky by se terminál rozcházel s šířkami serveru u CJK a emoji. Evidence: [zavislosti.md §15](zavislosti.md#15-terminál-xterm-zadání-43-ověřeno-2026-12-02). | ## 3. Rozsah M1 @@ -80,7 +84,7 @@ Kritérium úspěchu M1: správce týden nepoužije žádnou ze čtyř původní - Zátěžové testy rychlosti (speedtest), IPv6 scan celé podsítě, Bluetooth, NFC. - Služba na pozadí / periodické skenování na pozadí / notifikace. - Cloudová synchronizace, účty, telemetrie, reklamy. -- iOS (viz [ios.md](ios.md)), widgety a zástupce na plochu před M2, vlastní ikona před M2. +- iOS (viz [ios.md](ios.md)), vlastní ikona před M2. Widgety a zástupce na plochu: plánováno od D29 (zadání 36, 37). - Google Play (fáze 2 podle D12, viz [publikace-play.md](publikace-play.md)). ## 4. Milníky diff --git a/docs/project-license-inventory.tsv b/docs/project-license-inventory.tsv index fcfb152..1de19a1 100644 --- a/docs/project-license-inventory.tsv +++ b/docs/project-license-inventory.tsv @@ -5,9 +5,12 @@ androidx.activity activity-ktx 1.10.1 Apache-2.0 (AndroidX POM) debugRuntimeClas androidx.annotation annotation 1.9.1 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/annotation/annotation/1.9.1/annotation-1.9.1.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.annotation annotation-experimental 1.4.1 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/annotation/annotation-experimental/1.4.1/annotation-experimental-1.4.1.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.annotation annotation-jvm 1.9.1 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/annotation/annotation-jvm/1.9.1/annotation-jvm-1.9.1.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.appcompat appcompat 1.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/appcompat/appcompat/1.2.0/appcompat-1.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.appcompat appcompat-resources 1.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/appcompat/appcompat-resources/1.2.0/appcompat-resources-1.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.arch.core core-common 2.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/arch/core/core-common/2.2.0/core-common-2.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.arch.core core-runtime 2.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/arch/core/core-runtime/2.2.0/core-runtime-2.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.autofill autofill 1.0.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/autofill/autofill/1.0.0/autofill-1.0.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.biometric biometric 1.1.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/biometric/biometric/1.1.0/biometric-1.1.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.collection collection 1.5.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/collection/collection/1.5.0/collection-1.5.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.collection collection-jvm 1.5.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/collection/collection-jvm/1.5.0/collection-jvm-1.5.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.collection collection-ktx 1.5.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/collection/collection-ktx/1.5.0/collection-ktx-1.5.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt @@ -45,19 +48,42 @@ androidx.compose.ui ui-unit-android 1.9.0 Apache-2.0 (AndroidX POM) debugRuntime androidx.compose.ui ui-util 1.9.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/compose/ui/ui-util/1.9.0/ui-util-1.9.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.compose.ui ui-util-android 1.9.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/compose/ui/ui-util-android/1.9.0/ui-util-android-1.9.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.concurrent concurrent-futures 1.1.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/concurrent/concurrent-futures/1.1.0/concurrent-futures-1.1.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.concurrent concurrent-futures-ktx 1.1.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/concurrent/concurrent-futures-ktx/1.1.0/concurrent-futures-ktx-1.1.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.core core 1.15.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/core/core/1.15.0/core-1.15.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.core core-ktx 1.15.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/core/core-ktx/1.15.0/core-ktx-1.15.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.core core-remoteviews 1.1.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/core/core-remoteviews/1.1.0/core-remoteviews-1.1.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.core core-viewtree 1.0.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/core/core-viewtree/1.0.0/core-viewtree-1.0.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.cursoradapter cursoradapter 1.0.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/cursoradapter/cursoradapter/1.0.0/cursoradapter-1.0.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.customview customview 1.0.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/customview/customview/1.0.0/customview-1.0.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.customview customview-poolingcontainer 1.0.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/customview/customview-poolingcontainer/1.0.0/customview-poolingcontainer-1.0.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.datastore datastore 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore/1.1.7/datastore-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.datastore datastore-android 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-android/1.1.7/datastore-android-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.datastore datastore-core 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-core/1.1.7/datastore-core-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.datastore datastore-core-android 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-core-android/1.1.7/datastore-core-android-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.datastore datastore-core-okio 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-core-okio/1.1.7/datastore-core-okio-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.datastore datastore-core-okio-jvm 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-core-okio-jvm/1.1.7/datastore-core-okio-jvm-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.datastore datastore-preferences 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences/1.1.7/datastore-preferences-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.datastore datastore-preferences-android 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences-android/1.1.7/datastore-preferences-android-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.datastore datastore-preferences-core 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences-core/1.1.7/datastore-preferences-core-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.datastore datastore-preferences-core-android 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences-core-android/1.1.7/datastore-preferences-core-android-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.datastore datastore-preferences-external-protobuf 1.1.7 BSD-3-Clause (AndroidX POM; repackaged Protocol Buffers lite) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences-external-protobuf/1.1.7/datastore-preferences-external-protobuf-1.1.7.pom https://github.com/protocolbuffers/protobuf/blob/v29.3/LICENSE +androidx.datastore datastore-preferences-proto 1.1.7 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences-proto/1.1.7/datastore-preferences-proto-1.1.7.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.drawerlayout drawerlayout 1.0.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/drawerlayout/drawerlayout/1.0.0/drawerlayout-1.0.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.emoji2 emoji2 1.4.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/emoji2/emoji2/1.4.0/emoji2-1.4.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.fragment fragment 1.8.9 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/fragment/fragment/1.8.9/fragment-1.8.9.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.glance glance 1.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/glance/glance/1.2.0/glance-1.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.glance glance-appwidget 1.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/glance/glance-appwidget/1.2.0/glance-appwidget-1.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.glance glance-appwidget-external-protobuf 1.2.0 BSD-3-Clause (AndroidX POM; repackaged Protocol Buffers lite) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/glance/glance-appwidget-external-protobuf/1.2.0/glance-appwidget-external-protobuf-1.2.0.pom https://github.com/protocolbuffers/protobuf/blob/v29.3/LICENSE +androidx.glance glance-appwidget-proto 1.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/glance/glance-appwidget-proto/1.2.0/glance-appwidget-proto-1.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.glance glance-material3 1.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/glance/glance-material3/1.2.0/glance-material3-1.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.graphics graphics-path 1.0.1 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/graphics/graphics-path/1.0.1/graphics-path-1.0.1.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.interpolator interpolator 1.0.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/interpolator/interpolator/1.0.0/interpolator-1.0.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-common 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-common/2.9.4/lifecycle-common-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-common-java8 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-common-java8/2.9.4/lifecycle-common-java8-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-common-jvm 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-common-jvm/2.9.4/lifecycle-common-jvm-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.lifecycle lifecycle-livedata 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-livedata/2.9.4/lifecycle-livedata-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-livedata-core 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-livedata-core/2.9.4/lifecycle-livedata-core-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.lifecycle lifecycle-livedata-core-ktx 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-livedata-core-ktx/2.9.4/lifecycle-livedata-core-ktx-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-process 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-process/2.9.4/lifecycle-process-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-runtime 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-runtime/2.9.4/lifecycle-runtime-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-runtime-android 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-runtime-android/2.9.4/lifecycle-runtime-android-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt @@ -65,20 +91,36 @@ androidx.lifecycle lifecycle-runtime-compose 2.9.4 Apache-2.0 (AndroidX POM) deb androidx.lifecycle lifecycle-runtime-compose-android 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-runtime-compose-android/2.9.4/lifecycle-runtime-compose-android-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-runtime-ktx 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-runtime-ktx/2.9.4/lifecycle-runtime-ktx-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-runtime-ktx-android 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-runtime-ktx-android/2.9.4/lifecycle-runtime-ktx-android-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.lifecycle lifecycle-service 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-service/2.9.4/lifecycle-service-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-viewmodel 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-viewmodel/2.9.4/lifecycle-viewmodel-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-viewmodel-android 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-viewmodel-android/2.9.4/lifecycle-viewmodel-android-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-viewmodel-ktx 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-viewmodel-ktx/2.9.4/lifecycle-viewmodel-ktx-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-viewmodel-savedstate 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-viewmodel-savedstate/2.9.4/lifecycle-viewmodel-savedstate-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.lifecycle lifecycle-viewmodel-savedstate-android 2.9.4 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-viewmodel-savedstate-android/2.9.4/lifecycle-viewmodel-savedstate-android-2.9.4.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.loader loader 1.0.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/loader/loader/1.0.0/loader-1.0.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.profileinstaller profileinstaller 1.4.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/profileinstaller/profileinstaller/1.4.0/profileinstaller-1.4.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.room room-common 2.7.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/room/room-common/2.7.0/room-common-2.7.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.room room-common-jvm 2.7.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/room/room-common-jvm/2.7.0/room-common-jvm-2.7.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.room room-runtime 2.7.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/room/room-runtime/2.7.0/room-runtime-2.7.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.room room-runtime-android 2.7.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/room/room-runtime-android/2.7.0/room-runtime-android-2.7.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.savedstate savedstate 1.3.1 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/savedstate/savedstate/1.3.1/savedstate-1.3.1.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.savedstate savedstate-android 1.3.1 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/savedstate/savedstate-android/1.3.1/savedstate-android-1.3.1.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.savedstate savedstate-compose 1.3.1 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/savedstate/savedstate-compose/1.3.1/savedstate-compose-1.3.1.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.savedstate savedstate-compose-android 1.3.1 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/savedstate/savedstate-compose-android/1.3.1/savedstate-compose-android-1.3.1.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.savedstate savedstate-ktx 1.3.1 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/savedstate/savedstate-ktx/1.3.1/savedstate-ktx-1.3.1.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.sqlite sqlite 2.5.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/sqlite/sqlite/2.5.0/sqlite-2.5.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.sqlite sqlite-android 2.5.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/sqlite/sqlite-android/2.5.0/sqlite-android-2.5.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.sqlite sqlite-framework 2.5.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/sqlite/sqlite-framework/2.5.0/sqlite-framework-2.5.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.sqlite sqlite-framework-android 2.5.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/sqlite/sqlite-framework-android/2.5.0/sqlite-framework-android-2.5.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.startup startup-runtime 1.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/startup/startup-runtime/1.2.0/startup-runtime-1.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.tracing tracing 1.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/tracing/tracing/1.2.0/tracing-1.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.tracing tracing-ktx 1.2.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/tracing/tracing-ktx/1.2.0/tracing-ktx-1.2.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.vectordrawable vectordrawable 1.1.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/vectordrawable/vectordrawable/1.1.0/vectordrawable-1.1.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.vectordrawable vectordrawable-animated 1.1.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/vectordrawable/vectordrawable-animated/1.1.0/vectordrawable-animated-1.1.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt androidx.versionedparcelable versionedparcelable 1.1.1 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/versionedparcelable/versionedparcelable/1.1.1/versionedparcelable-1.1.1.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.viewpager viewpager 1.0.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/viewpager/viewpager/1.0.0/viewpager-1.0.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.work work-runtime 2.12.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/work/work-runtime/2.12.0/work-runtime-2.12.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt +androidx.work work-runtime-ktx 2.12.0 Apache-2.0 (AndroidX POM) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://dl.google.com/dl/android/maven2/androidx/work/work-runtime-ktx/2.12.0/work-runtime-ktx-2.12.0.pom https://android.googlesource.com/platform/frameworks/support/+/androidx-main/LICENSE.txt com.github.mwiede jsch 2.28.0 BSD-3-Clause; bundled JZlib BSD-3-Clause; jBCrypt ISC debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://repo.maven.apache.org/maven2/com/github/mwiede/jsch/2.28.0/jsch-2.28.0.pom https://github.com/mwiede/jsch/blob/jsch-2.28.0/LICENSE.txt com.google.guava listenablefuture 1.0 Apache-2.0 (inherited from guava-parent 26.0-android) debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://repo.maven.apache.org/maven2/com/google/guava/listenablefuture/1.0/listenablefuture-1.0.pom https://repo.maven.apache.org/maven2/com/google/guava/guava-parent/26.0-android/guava-parent-26.0-android.pom com.squareup.okhttp3 okhttp 5.3.2 Apache-2.0 debugRuntimeClasspath,debugUnitTestRuntimeClasspath https://repo1.maven.org/maven2/com/squareup/okhttp3/okhttp/5.3.2/okhttp-5.3.2.pom https://github.com/lysine-dev/okhttp/blob/parent-5.3.2/LICENSE.txt diff --git a/docs/public-license-verification.tsv b/docs/public-license-verification.tsv index c43abd7..1bfed4b 100644 --- a/docs/public-license-verification.tsv +++ b/docs/public-license-verification.tsv @@ -5,9 +5,12 @@ androidx.activity:activity:1.10.1 The Apache Software License, Version 2.0 http: androidx.annotation:annotation-experimental:1.4.1 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/annotation/annotation-experimental/1.4.1/annotation-experimental-1.4.1.pom androidx.annotation:annotation-experimental:1.4.1 fe57b228417f4d7c677903dc61fb4a7cf993d603499de26d8d8113e477cc4f1b 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.annotation:annotation-jvm:1.9.1 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/annotation/annotation-jvm/1.9.1/annotation-jvm-1.9.1.pom androidx.annotation:annotation-jvm:1.9.1 89b99c218d60019316b50aab79816707bc21696c896a030e1b1ae038961bcb8e 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.annotation:annotation:1.9.1 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/annotation/annotation/1.9.1/annotation-1.9.1.pom androidx.annotation:annotation:1.9.1 c733881c2e17d5f7c8661cc02a9159cb160b7b2094a27d593916c87d3e250636 2026-10-28 official POM in local Gradle cache (no fresh download) +androidx.appcompat:appcompat-resources:1.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/appcompat/appcompat-resources/1.2.0/appcompat-resources-1.2.0.pom androidx.appcompat:appcompat-resources:1.2.0 149dd8cec3664bef8ffde86c396ba1e2ab156ea68793d29800d008bacbc9c0f8 2026-12-02 official POM downloaded from Google Maven (zadání 50) +androidx.appcompat:appcompat:1.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/appcompat/appcompat/1.2.0/appcompat-1.2.0.pom androidx.appcompat:appcompat:1.2.0 8eb3cbe823b609853b481646e3d2c1aa39dbde53dd269712fd844ffdef2ebb42 2026-12-02 official POM downloaded from Google Maven (zadání 50) androidx.arch.core:core-common:2.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/arch/core/core-common/2.2.0/core-common-2.2.0.pom androidx.arch.core:core-common:2.2.0 1e17d4af8d6425be2a69f8af4d654a87e0456259a9eef1542869bcb023547e28 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.arch.core:core-runtime:2.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/arch/core/core-runtime/2.2.0/core-runtime-2.2.0.pom androidx.arch.core:core-runtime:2.2.0 0f953706598140d9d8735cdd5aeb1fa35933f4e2f31c0bf3eb81a053a4c8c1a5 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.autofill:autofill:1.0.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/autofill/autofill/1.0.0/autofill-1.0.0.pom androidx.autofill:autofill:1.0.0 3677abead5d4e06cf76cbacb954151e051779c2274494451fb424e375aa9e450 2026-10-28 official POM in local Gradle cache (no fresh download) +androidx.biometric:biometric:1.1.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/biometric/biometric/1.1.0/biometric-1.1.0.pom androidx.biometric:biometric:1.1.0 aeb69e76988f43b06c84fca25efab2e418bb98b5aabcd03fa7913bd3ed1bcaa9 2026-12-02 official POM downloaded from Google Maven (zadání 50) androidx.collection:collection-jvm:1.5.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/collection/collection-jvm/1.5.0/collection-jvm-1.5.0.pom androidx.collection:collection-jvm:1.5.0 11c415864d3402f61d426e67210158dce1b04680412526a994f1823ecd3cb388 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.collection:collection-ktx:1.5.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/collection/collection-ktx/1.5.0/collection-ktx-1.5.0.pom androidx.collection:collection-ktx:1.5.0 983f8d0630d072d5bfcd166a498ac7213f3a44a98c09051004ce96429d867cea 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.collection:collection:1.5.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/collection/collection/1.5.0/collection-1.5.0.pom androidx.collection:collection:1.5.0 2d65c8d0b36d4b4faadc44aff9bade23d871d7159eedf2b3f02d802b34b77a57 2026-10-28 official POM in local Gradle cache (no fresh download) @@ -48,10 +51,14 @@ androidx.concurrent:concurrent-futures:1.1.0 The Apache Software License, Versio androidx.core:core-ktx:1.15.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/core/core-ktx/1.15.0/core-ktx-1.15.0.pom androidx.core:core-ktx:1.15.0 417c6aa0279ec78db02fe395d401a09bcaaa9d82d935148a3e2de90fdf38d94c 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.core:core-viewtree:1.0.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/core/core-viewtree/1.0.0/core-viewtree-1.0.0.pom androidx.core:core-viewtree:1.0.0 d4f2ed1176fa8c5612b80f74c952a8799142a9ed36022a1a238fde5b140580d9 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.core:core:1.15.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/core/core/1.15.0/core-1.15.0.pom androidx.core:core:1.15.0 e168ae56064b8e5a40bce415ef95ffd5a813abb5456d2775f0fef426ed49e35a 2026-10-28 official POM in local Gradle cache (no fresh download) +androidx.cursoradapter:cursoradapter:1.0.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/cursoradapter/cursoradapter/1.0.0/cursoradapter-1.0.0.pom androidx.cursoradapter:cursoradapter:1.0.0 62d95c89850af21030b19f14d5f7ecd6d8bcc9a3014c59002ec99624caac8100 2026-12-02 official POM downloaded from Google Maven (zadání 50) androidx.customview:customview-poolingcontainer:1.0.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/customview/customview-poolingcontainer/1.0.0/customview-poolingcontainer-1.0.0.pom androidx.customview:customview-poolingcontainer:1.0.0 9fa62196c4c4e79b6a58dbb38a8c022bef8db21989d7dae2da0f6f5b66289a9c 2026-10-28 official POM in local Gradle cache (no fresh download) +androidx.customview:customview:1.0.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/customview/customview/1.0.0/customview-1.0.0.pom androidx.customview:customview:1.0.0 ce9e47b87184f5bd5e139e9becd5b26476d42d78c31bf2fdedc37acb41b9ad49 2026-12-02 official POM downloaded from Google Maven (zadání 50) androidx.datastore:datastore-core-android:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-core-android/1.1.7/datastore-core-android-1.1.7.pom androidx.datastore:datastore-core-android:1.1.7 c85fbe122a236c82a2babe68e3ea862c49b7b38db336c1929ca8352ec9025646 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.datastore:datastore-core:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-core/1.1.7/datastore-core-1.1.7.pom androidx.datastore:datastore-core:1.1.7 b2284564c24f4d1bca9f1aabaa329e3ba45ff1d7e29e7bbeee37ca91fcadebfa 2026-10-28 official POM in local Gradle cache (no fresh download) +androidx.drawerlayout:drawerlayout:1.0.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/drawerlayout/drawerlayout/1.0.0/drawerlayout-1.0.0.pom androidx.drawerlayout:drawerlayout:1.0.0 da6733425a83f5ce850878fa7201082345fed7c668dd58550fdd19c0396c6fa4 2026-12-02 official POM downloaded from Google Maven (zadání 50) androidx.emoji2:emoji2:1.4.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/emoji2/emoji2/1.4.0/emoji2-1.4.0.pom androidx.emoji2:emoji2:1.4.0 1f67221484f7d1260eb6e2b490cd4e7046bf5cb536276d79f972ad3f198b474d 2026-10-28 official POM in local Gradle cache (no fresh download) +androidx.fragment:fragment:1.8.9 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/fragment/fragment/1.8.9/fragment-1.8.9.pom androidx.fragment:fragment:1.8.9 8135a58b3ec9379c8afb4acce863f35e7654fddf1c602191f8d3feec13afed36 2026-12-02 official POM downloaded from Google Maven (zadání 50) androidx.graphics:graphics-path:1.0.1 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/graphics/graphics-path/1.0.1/graphics-path-1.0.1.pom androidx.graphics:graphics-path:1.0.1 866fb357c7146f5f7678ad44e4bc6c2823d568defce1ed2805bb6c899606b228 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.interpolator:interpolator:1.0.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/interpolator/interpolator/1.0.0/interpolator-1.0.0.pom androidx.interpolator:interpolator:1.0.0 0ddc07cc39699f48ecd9ec894b5830c0f09e22e82959294edf37217224c88b7b 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.lifecycle:lifecycle-common-java8:2.9.4 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-common-java8/2.9.4/lifecycle-common-java8-2.9.4.pom androidx.lifecycle:lifecycle-common-java8:2.9.4 f7a0077f2b20312c30ea74c9fe77626fbe2ad09bb48922851cde20bcd1a33266 2026-10-28 official POM in local Gradle cache (no fresh download) @@ -70,6 +77,7 @@ androidx.lifecycle:lifecycle-viewmodel-ktx:2.9.4 The Apache Software License, Ve androidx.lifecycle:lifecycle-viewmodel-savedstate-android:2.9.4 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-viewmodel-savedstate-android/2.9.4/lifecycle-viewmodel-savedstate-android-2.9.4.pom androidx.lifecycle:lifecycle-viewmodel-savedstate-android:2.9.4 34ab8491e6b631123ce5f7f0ae06dfa238c211dcf3e71033ed61656f9d47718c 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.lifecycle:lifecycle-viewmodel-savedstate:2.9.4 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-viewmodel-savedstate/2.9.4/lifecycle-viewmodel-savedstate-2.9.4.pom androidx.lifecycle:lifecycle-viewmodel-savedstate:2.9.4 6912b55c745c579ec6fcbeb0065d5a17d8b5f06dd0a58788037d41e40db50202 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.lifecycle:lifecycle-viewmodel:2.9.4 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-viewmodel/2.9.4/lifecycle-viewmodel-2.9.4.pom androidx.lifecycle:lifecycle-viewmodel:2.9.4 054db6f92d9230103b3aca8b0dabcc0d63de26e440ff98eb5b19a2555d3eb037 2026-10-28 official POM in local Gradle cache (no fresh download) +androidx.loader:loader:1.0.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/loader/loader/1.0.0/loader-1.0.0.pom androidx.loader:loader:1.0.0 c978d550808b47434aa49a63164110a50b55b0bcc6160a93a2e37d5110df8c5e 2026-12-02 official POM downloaded from Google Maven (zadání 50) androidx.profileinstaller:profileinstaller:1.4.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/profileinstaller/profileinstaller/1.4.0/profileinstaller-1.4.0.pom androidx.profileinstaller:profileinstaller:1.4.0 d5fe39981a3b4b7c39585130da0bfc93835054c834a438d3e63e065e5f78be55 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.savedstate:savedstate-android:1.3.1 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/savedstate/savedstate-android/1.3.1/savedstate-android-1.3.1.pom androidx.savedstate:savedstate-android:1.3.1 8d9bbcd2f6c2d19e4c48178eb9bbea5ff20093c82363fbb2510b71feaf8e50d1 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.savedstate:savedstate-compose-android:1.3.1 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/savedstate/savedstate-compose-android/1.3.1/savedstate-compose-android-1.3.1.pom androidx.savedstate:savedstate-compose-android:1.3.1 28fe19199dc6919011bd4c62751891867e69171e5ff1041f2d00f3740d3c6033 2026-10-28 official POM in local Gradle cache (no fresh download) @@ -78,7 +86,10 @@ androidx.savedstate:savedstate-ktx:1.3.1 The Apache Software License, Version 2. androidx.savedstate:savedstate:1.3.1 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/savedstate/savedstate/1.3.1/savedstate-1.3.1.pom androidx.savedstate:savedstate:1.3.1 1a12e8ec533c6b552d497dfb47fad1a39cd0b996397b74b96037a8e1bade5b59 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.startup:startup-runtime:1.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/startup/startup-runtime/1.2.0/startup-runtime-1.2.0.pom androidx.startup:startup-runtime:1.2.0 69594163d8bb148df97a9fbb5aa8a92486bb8961db5f73871b8a84122616593b 2026-10-28 official POM in local Gradle cache (no fresh download) androidx.tracing:tracing:1.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/tracing/tracing/1.2.0/tracing-1.2.0.pom androidx.tracing:tracing:1.2.0 f34bec4eb58871d31002901377108aaa1ebfe77fa6d882b8b86200b158e26ea1 2026-10-28 official POM in local Gradle cache (no fresh download) +androidx.vectordrawable:vectordrawable-animated:1.1.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/vectordrawable/vectordrawable-animated/1.1.0/vectordrawable-animated-1.1.0.pom androidx.vectordrawable:vectordrawable-animated:1.1.0 276a20116b705fb75b9003ee9496c56f6fd3b32375fb232472811eba60a040bd 2026-12-02 official POM downloaded from Google Maven (zadání 50) +androidx.vectordrawable:vectordrawable:1.1.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/vectordrawable/vectordrawable/1.1.0/vectordrawable-1.1.0.pom androidx.vectordrawable:vectordrawable:1.1.0 5b0e2d5b2179e54804785cbc21ce5f473b5e1ddd55a57da482e94dcd39492bb2 2026-12-02 official POM downloaded from Google Maven (zadání 50) androidx.versionedparcelable:versionedparcelable:1.1.1 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/versionedparcelable/versionedparcelable/1.1.1/versionedparcelable-1.1.1.pom androidx.versionedparcelable:versionedparcelable:1.1.1 5f51e65873ca612de3838fa90d2ee95b8d040efd31b9c390a19bf94d615cdb2f 2026-10-28 official POM in local Gradle cache (no fresh download) +androidx.viewpager:viewpager:1.0.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/viewpager/viewpager/1.0.0/viewpager-1.0.0.pom androidx.viewpager:viewpager:1.0.0 1f72f836339d03c6eb013f65075e76ca87075a577578eb4f95f74a3a5d253128 2026-12-02 official POM downloaded from Google Maven (zadání 50) com.android.tools.build:gradle:8.9.2 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/8.9.2/gradle-8.9.2.pom com.android.tools.build:gradle:8.9.2 97719184aefa93d3c5e8296c39860532227b8801a34c73376c0d9d0db7aa5580 2026-10-28 official POM in local Gradle cache (no fresh download) com.github.mwiede:jsch:2.28.0 Revised BSD https://github.com/mwiede/jsch/blob/master/LICENSE.txt; Revised BSD https://github.com/mwiede/jsch/blob/master/LICENSE.JZlib.txt; ISC https://github.com/mwiede/jsch/blob/master/LICENSE.jBCrypt.txt https://repo.maven.apache.org/maven2/com/github/mwiede/jsch/2.28.0/jsch-2.28.0.pom com.github.mwiede:jsch:2.28.0 6e329c3b05f38b4f2fb2fb9d49cafd337a20aabcd2d8677f8e7d4e659839b2e2 2026-10-28 official POM in local Gradle cache (no fresh download) com.google.guava:guava-parent:26.0-android The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://repo.maven.apache.org/maven2/com/google/guava/guava-parent/26.0-android/guava-parent-26.0-android.pom com.google.guava:guava-parent:26.0-android f8698ab46ca996ce889c1afc8ca4f25eb8ac6b034dc898d4583742360016cc04 2026-10-28 official POM in local Gradle cache (no fresh download) @@ -116,3 +127,34 @@ com.squareup.okio:okio-jvm:3.16.4 The Apache Software License, Version 2.0 http: com.squareup.okio:okio:3.16.4 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://repo1.maven.org/maven2/com/squareup/okio/okio/3.16.4/okio-3.16.4.pom com.squareup.okio:okio:3.16.4 08fbe97e1e2e815a14caf16ff5ac8708511bef5dde739d60c0713951876da263 2026-10-28 official POM in local Gradle cache (no fresh download) org.jetbrains.kotlin:kotlin-compose-compiler-plugin-embeddable:2.2.20 Apache-2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-compose-compiler-plugin-embeddable/2.2.20/kotlin-compose-compiler-plugin-embeddable-2.2.20.pom org.jetbrains.kotlin:kotlin-compose-compiler-plugin-embeddable:2.2.20 59d98da18afe5c1bd322b584b0ad64b3b8d3458b14616712809127d42f497cf2 2026-10-28 official POM in local Gradle cache (no fresh download) org.jetbrains.kotlin:kotlin-gradle-plugin:2.2.20 Apache-2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/2.2.20/kotlin-gradle-plugin-2.2.20.pom org.jetbrains.kotlin:kotlin-gradle-plugin:2.2.20 b9c3fd2ebd5484d60c5fe0db7aa10878303eeddfc93f942f735c07ba998187cc 2026-10-28 official POM in local Gradle cache (no fresh download) +androidx.concurrent:concurrent-futures-ktx:1.1.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/concurrent/concurrent-futures-ktx/1.1.0/concurrent-futures-ktx-1.1.0.pom androidx.concurrent:concurrent-futures-ktx:1.1.0 c903f8f51e3f4ea5e7e1f0a6fe3be873c357221227d103d08d7fd042f4b7570c 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.core:core-remoteviews:1.1.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/core/core-remoteviews/1.1.0/core-remoteviews-1.1.0.pom androidx.core:core-remoteviews:1.1.0 3272accaf7e3ad43da3e14f3ee921e43089fe65de501480cec47c8280996e850 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.datastore:datastore-android:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-android/1.1.7/datastore-android-1.1.7.pom androidx.datastore:datastore-android:1.1.7 30a077aec57ed8931be7d97d8423f6ab6547264339c508e85958165d2f35bb77 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.datastore:datastore-core-okio-jvm:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-core-okio-jvm/1.1.7/datastore-core-okio-jvm-1.1.7.pom androidx.datastore:datastore-core-okio-jvm:1.1.7 09ceb29d3ee5462c76e2dd3fac657ab1c4c503738deccc3476dcfa8fe94d4d7f 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.datastore:datastore-core-okio:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-core-okio/1.1.7/datastore-core-okio-1.1.7.pom androidx.datastore:datastore-core-okio:1.1.7 b075b36b395c19246370f86f0d865f91914be8619e76083dc855ea8ce1c767cd 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.datastore:datastore-preferences-android:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences-android/1.1.7/datastore-preferences-android-1.1.7.pom androidx.datastore:datastore-preferences-android:1.1.7 a279688b852024be8dd1acbe59ae5a63a299a7da16a43b60b03eaf003a3167fe 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.datastore:datastore-preferences-core-android:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences-core-android/1.1.7/datastore-preferences-core-android-1.1.7.pom androidx.datastore:datastore-preferences-core-android:1.1.7 494d15645800d279dce7f00750bed1d9b50e8115787b1e43d9b603a3e6f82e77 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.datastore:datastore-preferences-core:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences-core/1.1.7/datastore-preferences-core-1.1.7.pom androidx.datastore:datastore-preferences-core:1.1.7 5281efaff017a7ea1655bad1bd3ce4f64645cec76cfbdde0281f76d6ceceb089 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.datastore:datastore-preferences-external-protobuf:1.1.7 BSD-3-Clause https://opensource.org/licenses/BSD-3-Clause https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences-external-protobuf/1.1.7/datastore-preferences-external-protobuf-1.1.7.pom androidx.datastore:datastore-preferences-external-protobuf:1.1.7 5ee57d2ba9659bee9ed1a51a2851880161b1d91917ec41973514a1d0b1266cd9 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.datastore:datastore-preferences-proto:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences-proto/1.1.7/datastore-preferences-proto-1.1.7.pom androidx.datastore:datastore-preferences-proto:1.1.7 a67ccf3b30ae474da732d37b19deac9a9c1e91a6adb91af15d6314f713abeed5 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.datastore:datastore-preferences:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore-preferences/1.1.7/datastore-preferences-1.1.7.pom androidx.datastore:datastore-preferences:1.1.7 ce31988f3ad73dffecad5b39d18571ffd9f4ddf2b9dfb52bbb56c32f8f6a2b36 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.datastore:datastore:1.1.7 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/datastore/datastore/1.1.7/datastore-1.1.7.pom androidx.datastore:datastore:1.1.7 1f7dc83fe4bc96d9fbd2b00e105d41a6f00d9a5302028edd30e2def424100770 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.glance:glance-appwidget-external-protobuf:1.2.0 BSD-3-Clause https://opensource.org/licenses/BSD-3-Clause https://dl.google.com/dl/android/maven2/androidx/glance/glance-appwidget-external-protobuf/1.2.0/glance-appwidget-external-protobuf-1.2.0.pom androidx.glance:glance-appwidget-external-protobuf:1.2.0 cb812781a9ef84421d706e83ac99ade9acc1793abfb4b8749086c99f999592f2 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.glance:glance-appwidget-proto:1.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/glance/glance-appwidget-proto/1.2.0/glance-appwidget-proto-1.2.0.pom androidx.glance:glance-appwidget-proto:1.2.0 dc705d28c0ac12716294b8add1543a14d7c768b3d21693a2a22d87a55dfad76a 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.glance:glance-appwidget:1.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/glance/glance-appwidget/1.2.0/glance-appwidget-1.2.0.pom androidx.glance:glance-appwidget:1.2.0 88f36b073e53458980438905ab3c36905146f49c73d273264a98265d548269e9 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.glance:glance-material3:1.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/glance/glance-material3/1.2.0/glance-material3-1.2.0.pom androidx.glance:glance-material3:1.2.0 3fcfb90ffb1fd850a2410e551508c55466367bba1ce90bc299b1973a23385f8f 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.glance:glance:1.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/glance/glance/1.2.0/glance-1.2.0.pom androidx.glance:glance:1.2.0 4cda4b69bcc4d4d4c9fdd9fb0cc2af02a4a6b655034477df9d27a9e04126c29c 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.lifecycle:lifecycle-livedata-core-ktx:2.9.4 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-livedata-core-ktx/2.9.4/lifecycle-livedata-core-ktx-2.9.4.pom androidx.lifecycle:lifecycle-livedata-core-ktx:2.9.4 ca2073ac46d364107fdf4d832c5b729e610cdc7d12e736d9151b5a5119be80b9 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.lifecycle:lifecycle-livedata:2.9.4 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-livedata/2.9.4/lifecycle-livedata-2.9.4.pom androidx.lifecycle:lifecycle-livedata:2.9.4 24f8b944549912ab683aa70e61d32b5e1aa83c2f1f9d42f09e8eda3237760ab1 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.lifecycle:lifecycle-service:2.9.4 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/lifecycle/lifecycle-service/2.9.4/lifecycle-service-2.9.4.pom androidx.lifecycle:lifecycle-service:2.9.4 94e595483076d88e6acee7cd1ba1e165d9b6aa9ff0dd54db8119d81f93342f6a 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.room:room-common-jvm:2.7.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/room/room-common-jvm/2.7.0/room-common-jvm-2.7.0.pom androidx.room:room-common-jvm:2.7.0 8ea01b5d78a7eee5697975ab5d0ef5b8aad1f9566dc915b1807858f6b9270be8 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.room:room-common:2.7.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/room/room-common/2.7.0/room-common-2.7.0.pom androidx.room:room-common:2.7.0 fcd1cc684505349166185be740015279331cfad6fc81ba7a0f0a9ce5b1d8be33 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.room:room-runtime-android:2.7.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/room/room-runtime-android/2.7.0/room-runtime-android-2.7.0.pom androidx.room:room-runtime-android:2.7.0 f592f541a9c19e506ab2b033d589a6124887aff58156ceb747db4cae4f1e83b0 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.room:room-runtime:2.7.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/room/room-runtime/2.7.0/room-runtime-2.7.0.pom androidx.room:room-runtime:2.7.0 9ff1c390ac3cd0818c23a011676b9b83e3e2ddbd1b64a45761f05d0013f11af0 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.sqlite:sqlite-android:2.5.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/sqlite/sqlite-android/2.5.0/sqlite-android-2.5.0.pom androidx.sqlite:sqlite-android:2.5.0 e5dc07ce1a335bcd127c3d04b594dd2a83f61887a5e933327373866cc4edbf30 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.sqlite:sqlite-framework-android:2.5.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/sqlite/sqlite-framework-android/2.5.0/sqlite-framework-android-2.5.0.pom androidx.sqlite:sqlite-framework-android:2.5.0 8d1f2657347e05d7145990bdc84d091a296a2ce1eccc007c25e71ebaef02ceec 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.sqlite:sqlite-framework:2.5.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/sqlite/sqlite-framework/2.5.0/sqlite-framework-2.5.0.pom androidx.sqlite:sqlite-framework:2.5.0 51fcf2f5947198fc738527301d4d489a6537fb8947eef47998d981c9e105f197 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.sqlite:sqlite:2.5.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/sqlite/sqlite/2.5.0/sqlite-2.5.0.pom androidx.sqlite:sqlite:2.5.0 ad3f6e8f4aac2428d2fec6dc99876004a98b788d0410a8f4b169ab57826d563f 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.tracing:tracing-ktx:1.2.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/tracing/tracing-ktx/1.2.0/tracing-ktx-1.2.0.pom androidx.tracing:tracing-ktx:1.2.0 8958b5a0153c1a82cb133703d3d11155898738280a354e92ca1817d7ca6f4cb7 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.work:work-runtime-ktx:2.12.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/work/work-runtime-ktx/2.12.0/work-runtime-ktx-2.12.0.pom androidx.work:work-runtime-ktx:2.12.0 f19d2d7fceb36ce076f9777e9924cc0643da62918bfbb8e4aa71a72f799a289a 2026-12-01 official POM downloaded from Google Maven (zadání 36) +androidx.work:work-runtime:2.12.0 The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt https://dl.google.com/dl/android/maven2/androidx/work/work-runtime/2.12.0/work-runtime-2.12.0.pom androidx.work:work-runtime:2.12.0 68544d4ed7062252edc5cbc2540b3e071a31ab045baea017c6684c150d357379 2026-12-01 official POM downloaded from Google Maven (zadání 36) diff --git a/docs/public/data-safety-podklad.md b/docs/public/data-safety-podklad.md index c09bb5c..6cd3ebb 100644 --- a/docs/public/data-safety-podklad.md +++ b/docs/public/data-safety-podklad.md @@ -1,7 +1,7 @@ # NetKit — podklad pro Google Play Data safety -**Pracovní podklad, nikoli vyplněné nebo schválené prohlášení.** Stav 2026-10-28; -stejný HEAD a omezení jako [evidence datových toků](data-toky.md). Play je budoucí +**Pracovní podklad, nikoli vyplněné nebo schválené prohlášení.** Původní inventura z 2026-10-28, +doplněná pro připravovaný Android 2.0.0 dne 2026-12-02. Viz [evidence datových toků](data-toky.md). Play je budoucí fáze. Před odesláním posoudit skutečnou distribuovanou variantu včetně F3 a všech SDK. ## Jak používat podklad @@ -21,9 +21,9 @@ jsou podklady ke kontrole v konzoli, ne rozhodnutí o jejich povinném zaškrtnu | Otázka | Podklad k odpovědi | Stav | |---|---|---| -| Sbírá aplikace některý z požadovaných typů uživatelských dat? | Nelze vyplnit globální „ne“ jen proto, že NetKit nemá účty a analytiku. Existují přenosy D09–D18. **Je veřejná IP odeslaná speedtest serverům sbíraná data? OTEVŘENO — ověřit v Play Console, nerozhodnuto.** Stejně ověřit Cloudflare trace, Cymru, živé sondy a web aktualizací. | OTEVŘENO | -| Sdílí aplikace data s třetími stranami? | Technickými příjemci jsou DNS resolvery, zvolené servery, Cloudflare (trace i hosting webu), Team Cymru, GitHub (záloha kontroly aktualizací, D22), LibreSpeed, M-Lab a příjemci ručního exportu. Výjimku „user-initiated transfer“ ověřit pro konkrétní tok; nepřenášet ji na automatický Přehled nebo kontrolu aktualizací. | OTEVŘENO | -| Jsou všechna sbíraná uživatelská data šifrována při přenosu? | HTTPS/WSS a SSH ano pro svůj obsah; UPnP HTTP, WoL, ICMP/TCP sondy, mDNS/SSDP/NetBIOS ne. DNS nemá univerzální garanci šifrování. **Globální „ano“ není doložené.** Konečná odpověď vyžaduje přiřadit deklarované datové typy ke konkrétním přenosům. | OTEVŘENO; technická inventura PASS | +| Sbírá aplikace některý z požadovaných typů uživatelských dat? | Nelze vyplnit globální „ne“ jen proto, že NetKit nemá účty a analytiku. Existují přenosy D09–D18, ruční sdílení a terminálové relace (D27–D31) a ruční diagnostika D23–D25 (jméno mimo VPN, URL s parametry, veřejná IP/ASN pro rdap.org a RIR). **Je veřejná IP odeslaná speedtest serverům sbíraná data? OTEVŘENO — ověřit v Play Console, nerozhodnuto.** Stejně ověřit Cloudflare trace, Cymru, živé sondy a web aktualizací. | OTEVŘENO | +| Sdílí aplikace data s třetími stranami? | Technickými příjemci jsou DNS resolvery, zvolené servery, Cloudflare (trace i hosting webu), Team Cymru, GitHub (záloha kontroly aktualizací, D22), LibreSpeed, M-Lab, zvolený iperf3 server, SSH skoky a cíle tunelů, Telnet server (D28, D30, D31) a poskytovatelé souborů při SFTP, logování, ručním exportu či konfigurační záloze. Výjimku „user-initiated transfer“ ověřit pro konkrétní tok; nepřenášet ji na automatický Přehled nebo kontrolu aktualizací. | OTEVŘENO | +| Jsou všechna sbíraná uživatelská data šifrována při přenosu? | HTTPS/WSS a SSH ano pro svůj obsah; UPnP HTTP, WoL, ICMP/TCP sondy, mDNS/SSDP/NetBIOS, Telnet a iperf3 používají nešifrovaný přenos. DNS nemá univerzální garanci šifrování. **Globální „ano“ není doložené.** Konečná odpověď vyžaduje přiřadit deklarované datové typy ke konkrétním přenosům. | OTEVŘENO; technická inventura PASS | | Lze požádat o smazání dat? | Lokální data lze smazat (D21), exporty zvlášť. Není zavedený serverový mazací endpoint autora. Nelze slíbit smazání M-Lab výsledků ani logů cizích serverů. Před „ano“ ověřit, na jaká deklarovaná data se otázka vztahuje, a uvést funkční kontakt/postup. | OTEVŘENO pro vzdálená data | | Vytváří aplikace účty? | NetKit účet nevytváří (D01). SSH profil je připojení k cizímu serveru, nikoli účet u autora. | Podklad: ne | | Je sběr povinný, nebo volitelný? | Ruční nástroje a speedtest jsou volitelné. Veřejná IP je výchozí zapnutá s vypínačem, živý Přehled spouští sondy při otevření. F3 plánuje zapnuté kontroly s vypínačem. V konzoli posoudit podle konkrétního datového typu, nikoli jednou odpovědí za aplikaci. | OTEVŘENO | @@ -35,13 +35,31 @@ jsou podklady ke kontrole v konzoli, ne rozhodnutí o jejich povinném zaškrtnu | Data / možné kategorie k ověření | Technický podklad: sbírá/sdílí | Přenos / uchování / smazání | Evidence | |---|---|---|---| | WoL seznam, SSH metadata, lokální historie rychlosti a souhlasy | Běžné ukládání je pouze místní. Přenosy při použití funkce a exportu posoudit zvlášť. | Metadata nejsou šifrována aplikací; privátní úložiště, systémové zálohy zakázané; smazání lokálně. | [D02–D06](data-toky.md#d02), [D19](data-toky.md#d19), [D21](data-toky.md#d21) | -| Wi-Fi identifikátory a mobilní stav; případně „Device or other IDs“ / „Location“ podle skutečného použití | Mobilní karta nic neodesílá. Wi-Fi seznam se neuploaduje; SSID může být v místní historii. GPS poloha se nezjišťuje. Nevydávat oprávnění FINE za sběr GPS. | RAM; historie rychlosti místně. Pozor na uživatelem vytvořený export, nikoli analytický upload. | [D05](data-toky.md#d05), [D07–D08](data-toky.md#d07), [D20](data-toky.md#d20) | -| IP, hostname, MAC, uživatelské jméno, příkazy, autentizace; případně „Personal info“, „Device or other IDs“ a obsah dle akce | Cíle sond, DNS resolvery, WoL příjemci a SSH server dostávají nezbytná data. Konkrétní kategorii a výjimky pro přímý přenos ověřit. | SSH šifrovaně, ostatní viz souhrn. Serverové logy neřídí NetKit. Privátní SSH klíč není odesílán jako soubor. | [D09–D12](data-toky.md#d09) | -| Veřejná IP a měření rychlosti; možné „Device or other IDs“, „App info and performance“, případně „Approximate location“ pouze dle skutečného použití IP | **Klasifikace IP odeslané speedtest serverům jako „collected“ zůstává otevřená v Play Console.** Příjemci LibreSpeed/M-Lab existují bez ohledu na klasifikaci. | HTTPS/WSS; ruční test. M-Lab publikuje IP a výsledky. Smazání místní historie neodstraní vzdálená data. | [D13](data-toky.md#d13), [D14](data-toky.md#d14) | -| Veřejná IP, ASN, verze klienta, provozní metadata | Cloudflare trace a resolver/Team Cymru; kategorie IP i „collection/sharing“ otevřené. Živý ping a DNS nejsou řízené vypínačem IP. | HTTPS trace, DNS dle cesty, ICMP bez šifrování. Vypínač IP vyčistí místní cache, ne cizí logy. | [D15–D16](data-toky.md#d15) | +| Wi-Fi identifikátory a mobilní stav; případně „Device or other IDs“ / „Location“ podle skutečného použití | Mobilní karta nic neodesílá. Wi-Fi seznam se neuploaduje; SSID může být v místní historii. GPS poloha se nezjišťuje. Nevydávat oprávnění FINE za sběr GPS. | RAM, místní historie rychlosti a snímek pro widget (viz doplnění níže). Pozor na uživatelem vytvořený export, nikoli analytický upload. | [D05](data-toky.md#d05), [D07–D08](data-toky.md#d07), [D20](data-toky.md#d20) | +| IP, hostname, MAC, uživatelské jméno, příkazy, autentizace; případně „Personal info“, „Device or other IDs“ a obsah dle akce | Cíle sond, DNS resolvery, WoL příjemci a SSH server dostávají nezbytná data. Konkrétní kategorii a výjimky pro přímý přenos ověřit. | SSH šifrovaně, ostatní viz souhrn. Serverové logy neřídí NetKit. Privátní SSH klíč není odesílán jako soubor. SFTP (zadání 42) přenáší jen soubory, které uživatel sám vybere, mezi telefonem (SAF) a jeho SSH serverem. | [D09–D12](data-toky.md#d09) | +| Veřejná IP a měření rychlosti; možné „Device or other IDs“, „App info and performance“, případně „Approximate location“ pouze dle skutečného použití IP | **Klasifikace IP odeslané speedtest serverům jako „collected“ zůstává otevřená v Play Console.** Příjemcem je LibreSpeed, M-Lab nebo zvolený iperf3 server. | Ruční test přes HTTPS/WSS u LibreSpeed/NDT7 nebo nešifrované TCP u iperf3 (D28). M-Lab publikuje IP a výsledky. Smazání místní historie neodstraní vzdálená data. | [D13](data-toky.md#d13), [D14](data-toky.md#d14) | +| Veřejná IP, ASN, verze klienta, provozní metadata | Cloudflare trace a resolver/Team Cymru; kategorie IP i „collection/sharing“ otevřené. Živý ping a DNS nejsou řízené vypínačem IP. | HTTPS trace, DNS dle cesty, ICMP bez šifrování. Vypínač IP vyčistí místní cache i případnou kopii IP pro widget. Cizí logy spravují příjemci. | [D15–D16](data-toky.md#d15) | | F3: IP, verze klienta, čas/cesta požadavku | Web autora `www.daniel.losak.cz` a hosting Cloudflare (Workers Logs vypnuté); záloha GitHub jen při chybě webu (D22). | Plán HTTPS GET při startu procesu nejvýš 1×/60 min, při dalších návratech nejvýš 1×/24 h automaticky, vypínač; ruční kontrola. Žádný doložený vzdálený mazací mechanismus. | [D17](data-toky.md#d17), ověřeno nad kódem 2026-10-29 | | Exportované soubory, sdílený text, schránka; „Files and docs“ / obsah dle exportu | Příjemce volí uživatel, může to být i cloud. Prověřit výjimku pro uživatelem vyžádaný přenos. | Soubor či IPC, šifrování/retenci příjemce nelze zaručit. Kopie maže uživatel i u příjemce. | [D18](data-toky.md#d18) | -| Reklamní identifikátor, analytika používání, automatické hlášení pádů, telefonní číslo, IMEI, IMSI, ICCID, Cell ID | V prověřené implementaci se nečtou/neodesílají; nedeklarovat pouze na základě širokého názvu oprávnění. | Statická inventura, ne kompletní audit binárních závislostí. | [D01](data-toky.md#d01), [D08](data-toky.md#d08), [D20](data-toky.md#d20) | +| Reklamní identifikátor, analytika používání, automatické hlášení pádů, telefonní číslo, IMEI, IMSI, ICCID; Cell ID/TAC jen lokálně | V prověřené implementaci se nečtou/neodesílají; Cell ID a TAC čte od D31 jen rozbalený „Detail buňky“ a zpracuje je výhradně v zařízení (bez uložení, exportu a odeslání), což podle Play není „collection“; nedeklarovat pouze na základě širokého názvu oprávnění. | Statická inventura, ne kompletní audit binárních závislostí. | [D01](data-toky.md#d01), [D08](data-toky.md#d08), [D20](data-toky.md#d20) | + +### Doplnění pro Android 2.0.0 + +| Funkce | Příjemce, uchování a význam pro formulář | +|---|---| +| Widget stavu sítě | Snímek v soukromém úložišti obsahuje poslední rádiové údaje, odezvu brány a rychlost. SSID a veřejnou IP ukládá jen při zapnutí jednotlivých voleb, SSID navíc potřebuje udělenou polohu a IP zapnuté zjišťování v Přehledu. Na zamčené obrazovce se tyto dvě hodnoty skryjí. Obnovení čte rádio bez síťového provozu. Jde o místní uchování a zobrazení launcherem. Původní online příjemce IP z Přehledu posuzovat podle D15. | +| Zkratky, dlaždice a WoL widget | Launcher zobrazí uživatelský název profilu či zařízení. Dlaždice otevře Přehled. Stisk Probudit předá lokálnímu cíli stejný nešifrovaný paket jako aplikace (D11), včetně volitelného SecureOn. Heslo SecureOn je na disku šifrované a export je vynechá. | +| Ruční UDP sondy | Příjemcem je zvolené zařízení v LAN. NTP, DNS a SNMPv2c používají nešifrované UDP. Zadanou komunitu SNMP přijme agent v otevřené podobě, v NetKitu žije jen v paměti. Zohlednit v otázce šifrování. | +| Ruční iperf3 | Server zvolený uživatelem dostane zdrojovou IP, parametry, testovací provoz a výsledek přes nešifrované TCP. Hostitel a port se pamatují pro další běh. Naměřený výsledek včetně cíle zůstává v místní historii. Obě položky lze samostatně vymazat v Nastavení (D21, D28). Kategorie IP a měření a retenci u provozovatele posoudit samostatně vedle LibreSpeed/M-Lab. | +| SSH tunely, snippety a log | Zvolené skoky ProxyJump a koncový SSH server jsou příjemci spojení. Lokální přesměrování (`-L`) nebo dynamický SOCKS5 (`-D`) přenese data aplikace připojené na místní port k vybrané službě, šifrování posledního úseku záleží na jejím protokolu. Snippety jsou v nešifrovaných metadatech i exportu. Ruční log ukládá výstup včetně případně vypsaných tajemství do souboru u zvoleného poskytovatele, jímž může být cloud. Posoudit obsah a uživatelem vyžádaný přenos podle D12, D18 a D30. | +| Cíle nástrojů | IP, DNS jména, ASN, URL a popisky zůstávají v soukromém souboru `lan-tools.json`. Historie ukládá až 10 cílů, u URL vynechá parametry a fragment. Až 30 ručně označených oblíbených může obsahovat celou URL. Smazání historie zachová oblíbené. Síťový přenos vzniká při použití konkrétního nástroje. [D29](data-toky.md#d29) | +| SFTP, Telnet a USB | SFTP přenáší názvy a obsah souborů mezi SSH serverem a úložištěm zvoleným přes SAF, včetně cloudu („Files and docs“). Retenci u poskytovatele řešit zvlášť. Telnet zpřístupňuje příkazy a hesla na celé nešifrované trase. Sériový vstup dostane vybrané zařízení po USB. Soukromé oznámení služby zobrazuje v telefonu počet relací a názvy profilů. [D12](data-toky.md#d12), [D20](data-toky.md#d20), [D31](data-toky.md#d31) | +| Diagnostický report | Sestavení v Přehledu je místní. Kopírování, předání jiné aplikaci nebo zápis TXT/JSON přes SAF spouští uživatel. SSID, BSSID a zjištěná veřejná IP/ASN jsou výchozí vypnuté. Veřejně směrovatelné adresy, server iperf3 mimo místní adresy a jméno privátního DNS přidá jen volba „Zahrnout veřejné adresy“. Retenci kopie řeší zvolený příjemce. [D27](data-toky.md#d27) | +| Konfigurační záloha | Soubor vzniká jen na pokyn uživatele v Nastavení a ukládá se přes SAF, i do cloudu („Files and docs“). Ve výchozím stavu je šifrovaný heslem (AES-256-GCM, PBKDF2-HMAC-SHA256). Obsahuje profily, snippety, přesměrování, důvěru serverům, WoL zařízení, předvolby a oblíbené cíle nástrojů, servery rychlosti a nastavení vzhledu; SSH hesla, privátní klíče, hesla SecureOn, SOCKS údaje, SNMP community, historie měření a souhlasy v něm nejsou. Nešifrovanou variantu čte každý, kdo soubor získá. [D18](data-toky.md#d18) | +| Wi-Fi, split DNS, Web/TLS, RDAP a detail buňky | Export skenu/obchůzky zpřístupní zvolenému příjemci SSID, BSSID a případné značky míst (D18). DNS porovnání mimo VPN, URL a přesměrování a dotazy na veřejnou IP/ASN mají samostatné příjemce (D23–D25). Cell ID/TAC zůstávají jen v paměti otevřeného detailu (D08). | + +Technické důvody a rozsah přenosů popisují [bezpečnostní dokumentace](../bezpecnost.md) +a [síťové toky](data-toky.md). Odpovědi v Play Console se uzavírají až nad distribuovanou variantou. ## Co zbývá před odesláním diff --git a/docs/public/data-toky.md b/docs/public/data-toky.md index f63a804..4c9958e 100644 --- a/docs/public/data-toky.md +++ b/docs/public/data-toky.md @@ -4,7 +4,7 @@ Ověřeno statickým čtením 2026-10-28 (D17 a D22 znovu 2026-10-29). Odkazy js tomuto repozitáři; čísla řádků se mohou s dalšími změnami kódu posunout. Nejde o síťový záznam z běžícího APK. Toto je interní podklad k [CS policy](privacy-cs.md), [EN policy](privacy-en.md) a -[Data safety](data-safety-podklad.md). Identifikátory D01–D22 mapují tvrzení policy na důkazy. +[Data safety](data-safety-podklad.md). Pro Android 2.0.0 doplněno 2026-12-02. Identifikátory D01–D31 mapují tvrzení policy na důkazy. „Ne“ u automatického uploadu nepopírá ruční export ani obsah zadaný uživatelem do SSH. Příjemce každého síťového spojení vidí jeho zdrojovou IP (v internetu typicky veřejnou adresu NAT/VPN), čas a provozní metadata. Retenci cizích serverů klientský kód nedokazuje. @@ -19,24 +19,32 @@ Workers Logs vypnuté, předání do USA). | D02 | WoL: jméno, MAC, cíl/port, poznámka, nastavení opakování a kontroly | Soukromý nešifrovaný DataStore; případně archiv po obnově poškozeného souboru | Seznam sám ne; MAC při probouzení (D11), export (D18) | Uživatelův cíl / zvolený příjemce | Uložená zařízení | [DeviceStore.kt:92](../../androidApp/src/main/kotlin/cz/netkit/app/wol/DeviceStore.kt#L92); [WolModels.kt:9](../../shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolModels.kt#L9); [DeviceStore.kt:153](../../androidApp/src/main/kotlin/cz/netkit/app/wol/DeviceStore.kt#L153) | | D03 | SSH: profily, uživatel, adresa, port, startovací příkaz, veřejné klíče a důvěra serverům | Soukromý nešifrovaný DataStore; případně archiv poškozených metadat | Při spojení příslušné údaje (D12); export profilů (D18) | Zvolený SSH server / příjemce exportu | Připojení a ověření serveru; do názvu či příkazu nepatří tajemství | [SshStorage.kt:63](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt#L63); [SshModels.kt:13](../../shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt#L13); [SshStorage.kt:91](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt#L91) | | D04 | Uložená SSH hesla a privátní klíče | AES-256-GCM soubory v noBackupFilesDir; šifrovací klíč v Android Keystore; dočasně také paměť | Heslo nebo odpověď na výzvu serveru přes SSH; privátní klíč slouží lokálně k autentizaci | Zvolený SSH server | Volitelné zapamatování hesla, import/generování klíčů. StrongBox dle zařízení, možný software fallback; bez záruky vymazání všech kopií z RAM | [SshStorage.kt:130](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt#L130); [SshViewModel.kt:151](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L151); [JschConnection.kt:71](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt#L71) | -| D05 | Historie rychlosti: posledních 20 výsledků, čas, server, typ sítě, dostupné SSID/frekvence/RSSI/PHY; souhlas NDT7 a vlastní URL | Nešifrovaný noBackupFilesDir/speedtest.json | Historie ani SSID se automaticky neposílají; samotný test viz D13/D14 | — pro uloženou historii | Porovnání měření; veřejná IP, BSSID a token nejsou v záznamu | [SpeedTestViewModel.kt:170](../../androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt#L170); [SpeedTestViewModel.kt:579](../../androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt#L579); [SpeedHistory.kt:28](../../shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt#L28); [SpeedMeasure.kt:30](../../shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedMeasure.kt#L30) | +| D05 | Historie rychlosti: posledních 20 výsledků, čas, server, typ sítě, dostupné SSID/frekvence/RSSI/PHY; souhlas NDT7, vlastní URL LibreSpeed a poslední hostitel a port iperf3 | Nešifrovaný noBackupFilesDir/speedtest.json | Historie ani SSID se automaticky neposílají; samotný test viz D13/D14/D28 | — pro uloženou historii | Porovnání měření; záznam neobsahuje BSSID, token ani výsledek zjištění veřejné IP. Zadaný server iperf3 může sám být veřejná IP | [SpeedTestViewModel.kt:170](../../androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt#L170); [SpeedTestViewModel.kt:579](../../androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt#L579); [SpeedHistory.kt:28](../../shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt#L28); [SpeedMeasure.kt:30](../../shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedMeasure.kt#L30) | | D06 | Souhlasy automatického LAN hledání, čas posledního hledání, nastavení veřejné IP a příznak žádosti o Wi-Fi oprávnění | Soukromé SharedPreferences; identita LAN jako HMAC SSID/brána/podsíť s lokálním náhodným klíčem | Ne; identita sítě pro souhlas není uložena jako čitelné SSID | — | Zapamatování voleb; SSID v historii rychlosti je samostatný D05 | [LanDeviceNetwork.kt:88](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanDeviceNetwork.kt#L88); [PublicIpRepository.kt:91](../../androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt#L91); [WifiViewModel.kt:98](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt#L98) | | D07 | Wi-Fi SSID/BSSID, kanál, zabezpečení, signál, lokální IP; výsledky LAN; živé grafy a počítadla přenosu | Paměť a stav UI; živá historie ohraničená, nikoli trvalý záznam provozu | Žádný automatický upload seznamu sítí či výsledků; sondy D09–D10, export D18, SSID D05 | — pro samotný stav UI | Zobrazení sítě, signálu a rychlosti provozu bez čtení obsahu paketů | [WifiViewModel.kt:74](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt#L74); [WifiLiveViewModel.kt:495](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L495); [LiveTelemetry.kt:43](../../shared/src/commonMain/kotlin/cz/netkit/shared/wifi/LiveTelemetry.kt#L43); [LanDevicesViewModel.kt:195](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt#L195) | -| D08 | Mobilní karta: operátor, lokální index SIM/slot, typ sítě, signál, roaming/stav služby, režim letadlo | Paměť monitoru a grafu, ne disk | Ne | — | Zobrazení jedné/obou SIM. Bez telefonního čísla, IMEI/MEID, IMSI, ICCID, Cell ID či seznamu buněk; bez obsahu a historie hovorů | [CellularMonitor.kt:114](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt#L114); [CellularMonitor.kt:195](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt#L195); [CellularMonitor.kt:225](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt#L225); [WifiLiveViewModel.kt:580](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L580); negativní kontrola API v reportu | -| D09 | DNS jméno či reverzní IP; ICMP/TCP sondy, porty, cílové adresy | Paměť, výsledky případně ruční export | Ano; resolver vidí dotaz, cíle vidí zdrojovou IP, port a sondy | Resolver vybrané sítě a jeho navazující DNS servery; uživatelem zvolený cíl | DNS, ping, traceroute, porty a LAN sken; běžné sondy nejsou šifrované, DNS šifrování závisí na cestě | [LanBackend.kt:113](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt#L113); [LanBackend.kt:147](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt#L147); [LanBackend.kt:184](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt#L184); [LanBackend.kt:220](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt#L220); [LanViewModel.kt:338](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt#L338) | +| D08 | Mobilní karta: operátor, lokální index SIM/slot, typ sítě, signál, roaming/stav služby, režim letadlo | Paměť monitoru a grafu, ne disk | Ne | — | Zobrazení jedné/obou SIM. Bez telefonního čísla, IMEI/MEID, IMSI, ICCID; bez obsahu a historie hovorů. Od D31 (zadání 53, ověřeno 2026-12-01) rozbalený „Detail buňky“: obsluhující a max. 16 sousedních buněk (pásmo, ARFCN, PCI, ECI/NCI, TAC, šířka, TA, RSRP/RSRQ/SINR) přes `requestCellInfoUpdate`, jen s udělenou přesnou polohou a READ_PHONE_STATE, jen v paměti `CellDetailViewModel` po dobu viditelného detailu; neukládá se, neexportuje, nesdílí, není v diagnostickém reportu, MCC/MNC se nečte | [CellInfoReader.kt](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellInfoReader.kt); [CellDetailViewModel.kt](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellDetailViewModel.kt); [CellularMonitor.kt:114](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt#L114); [CellularMonitor.kt:195](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt#L195); [CellularMonitor.kt:225](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt#L225); [WifiLiveViewModel.kt:580](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L580); negativní kontrola API v reportu | +| D09 | DNS jméno či reverzní IP; ICMP/TCP sondy, porty, cílové adresy | Výsledky sond jsou v paměti nebo ručním exportu. Cíle nástrojů přetrvají v historii a oblíbených v `lan-tools.json` (D29) | Ano; resolver vidí dotaz, cíle vidí zdrojovou IP, port a sondy | Resolver vybrané sítě a jeho navazující DNS servery; uživatelem zvolený cíl | DNS, ping, traceroute, porty a LAN sken; běžné sondy nejsou šifrované, DNS šifrování závisí na cestě | [LanBackend.kt:113](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt#L113); [LanBackend.kt:147](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt#L147); [LanBackend.kt:184](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt#L184); [LanBackend.kt:220](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt#L220); [LanViewModel.kt:338](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt#L338) | | D10 | mDNS, SSDP, NetBIOS dotazy a UPnP GET; odpovědi obsahují jména a popis zařízení | Paměť výsledků | Ano, nešifrované discovery a HTTP GET bez těla a hlaviček s údaji uživatele | Vlastní Wi-Fi LAN, multicast a nalezená zařízení; UPnP jen ověřená adresa odpovídajícího hosta v podsíti | Identifikace zařízení; automatické hledání až po souhlasu pro síť, jinak ručně | [MdnsProbe.kt:53](../../androidApp/src/main/kotlin/cz/netkit/app/lan/MdnsProbe.kt#L53); [NetBios.kt:30](../../androidApp/src/main/kotlin/cz/netkit/app/lan/NetBios.kt#L30); [UpnpProbe.kt:56](../../androidApp/src/main/kotlin/cz/netkit/app/lan/UpnpProbe.kt#L56); [UpnpProbe.kt:102](../../androidApp/src/main/kotlin/cz/netkit/app/lan/UpnpProbe.kt#L102); [UpnpIdentity.kt:75](../../shared/src/commonMain/kotlin/cz/netkit/shared/lan/UpnpIdentity.kt#L75); [LanDevicesViewModel.kt:266](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt#L266) | | D11 | WoL magic packet s MAC, DNS vlastního cíle, volitelné TCP/ICMP ověření | Profil na disku (D02), výsledek v paměti | Ano; nešifrovaný UDP a sondy | Zadaný cíl/broadcast a DNS resolver podkladové Wi-Fi, mimo VPN | Probuzení na výslovnou akci; ne mobilní fallback | [UdpTransport.kt:25](../../androidApp/src/main/kotlin/cz/netkit/app/wol/UdpTransport.kt#L25); [UdpTransport.kt:55](../../androidApp/src/main/kotlin/cz/netkit/app/wol/UdpTransport.kt#L55); [WolDomain.kt:21](../../shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolDomain.kt#L21); [AndroidWakeProber.kt:19](../../androidApp/src/main/kotlin/cz/netkit/app/wol/AndroidWakeProber.kt#L19) | -| D12 | SSH jméno, autentizace, příkazy a vstup/výstup terminálu; DNS hostname | Profily/tajemství D03–D04; terminál v paměti | Ano; SSH šifrovaně, hostname přes systémový DNS; privátní klíč se neposílá jako soubor | Uživatelem zvolený SSH server (může vést vlastní logy); DNS resolver | Interaktivní správa. Používá systémovou trasu včetně VPN; ověřuje host key | [JschConnection.kt:71](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt#L71); [JschConnection.kt:130](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt#L130); [SshDns.kt:14](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshDns.kt#L14); [SshViewModel.kt:47](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L47) | +| D12 | SSH jméno, autentizace, příkazy a vstup/výstup terminálu; DNS hostname; SFTP: výpis adresářů a soubory, které uživatel stáhne nebo nahraje (zadání 42) | Profily/tajemství D03–D04, terminál v paměti, volitelný soubor s logem D30. Pro SFTP soubor u poskytovatele zvoleného přes SAF | Ano; SSH šifrovaně, hostname přes systémový DNS; privátní klíč se neposílá jako soubor | Uživatelem zvolený SSH server (může vést vlastní logy); DNS resolver a při přenosu SFTP zvolený poskytovatel souboru (i cloud) | Interaktivní správa. Používá systémovou trasu včetně VPN; ověřuje host key | [JschConnection.kt:71](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt#L71); [JschConnection.kt:130](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt#L130); [SshDns.kt:14](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshDns.kt#L14); [SshViewModel.kt:47](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L47) | | D13 | LibreSpeed: veřejná zdrojová IP, čas/provoz testu, User-Agent/verze, testovací payload | Test v paměti, lokální historie D05; serverové logy mimo kontrolu aplikace | Ano, HTTPS, až po spuštění testu | Zvolený server, včetně presetu rychlost.zelina.eu (D20), nebo vlastní HTTPS URL | Rychlost/latence; garbage.php, empty.php, getIP.php bez isp=true; nevolá telemetry.php. Ze zdrojového klienta nelze slíbit nulové serverové logování | [LibreSpeedClient.kt:73](../../androidApp/src/main/kotlin/cz/netkit/app/speed/LibreSpeedClient.kt#L73); [LibreSpeedClient.kt:136](../../androidApp/src/main/kotlin/cz/netkit/app/speed/LibreSpeedClient.kt#L136); [LibreSpeed.kt:24](../../shared/src/commonMain/kotlin/cz/netkit/shared/speed/LibreSpeed.kt#L24); [LibreSpeed.kt:44](../../shared/src/commonMain/kotlin/cz/netkit/shared/speed/LibreSpeed.kt#L44) | | D14 | M-Lab NDT7: veřejná IP, měření a metadata spojení, klient/verze a čas | Lokálně D05; u M-Lab zveřejněná data, ne jen dočasná paměť | Ano, HTTPS locate a WSS test, po jednorázovém upozornění a ručním spuštění | locate.measurementlab.net a vybraný *.measurement-lab.org | Měření; M-Lab publikuje výsledky včetně IP. Zásady příjemce potvrzují i dlouhodobé uchování | [Ndt7Client.kt:78](../../androidApp/src/main/kotlin/cz/netkit/app/speed/Ndt7Client.kt#L78); [Ndt7Client.kt:123](../../androidApp/src/main/kotlin/cz/netkit/app/speed/Ndt7Client.kt#L123); [Ndt7.kt:147](../../shared/src/commonMain/kotlin/cz/netkit/shared/speed/Ndt7.kt#L147); [SpeedTestViewModel.kt:247](../../androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt#L247); [M-Lab NDT](https://www.measurementlab.net/tests/ndt/) a [privacy](https://www.measurementlab.net/privacy/) (ověřeno 2026-10-28) | -| D15 | Veřejná IPv4/IPv6 a User-Agent NetKit/verze (Android); DNS TXT se zakódovanou veřejnou IP a ASN | Výsledek/cache jen RAM (čerstvá 10 min), nastavení D06 | Ano: HTTPS GET /cdn-cgi/trace; TXT přes resolver aktivní sítě | Cloudflare: 1.1.1.1 a [2606:4700:4700::1111]; resolver a Team Cymru: origin[6].asn.cymru.com a AS…asn.cymru.com | Veřejná IP a poskytovatel. Výchozí zapnuto, jen otevřený Přehled v popředí/změna sítě/obnova; vypnutí zruší dotaz a vymaže výsledek/cache. Bez cookies a identifikátoru instalace | [PublicIpRepository.kt:43](../../androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt#L43); [PublicIpRepository.kt:138](../../androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt#L138); [PublicIpRepository.kt:172](../../androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt#L172); [PublicIp.kt:66](../../shared/src/commonMain/kotlin/cz/netkit/shared/publicip/PublicIp.kt#L66); [WifiLiveViewModel.kt:292](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L292) | +| D15 | Veřejná IPv4/IPv6 a User-Agent NetKit/verze (Android); DNS TXT se zakódovanou veřejnou IP a ASN | Cache Přehledu v RAM (čerstvá 10 min), volitelná místní kopie veřejné IP pro widget D26, nastavení D06 | Ano: HTTPS GET /cdn-cgi/trace; TXT přes resolver aktivní sítě | Cloudflare: 1.1.1.1 a [2606:4700:4700::1111]; resolver a Team Cymru: origin[6].asn.cymru.com a AS…asn.cymru.com | Veřejná IP a poskytovatel. Výchozí zapnuto, jen otevřený Přehled v popředí/změna sítě/obnova; vypnutí zruší dotaz a vymaže cache Přehledu a případnou kopii IP pro widget. Bez cookies a identifikátoru instalace | [PublicIpRepository.kt:43](../../androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt#L43); [PublicIpRepository.kt:138](../../androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt#L138); [PublicIpRepository.kt:172](../../androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt#L172); [PublicIp.kt:66](../../shared/src/commonMain/kotlin/cz/netkit/shared/publicip/PublicIp.kt#L66); [WifiLiveViewModel.kt:292](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L292) | | D16 | Živé ICMP sondy na bránu a internet; DNS jméno pro měření latence | Paměť grafu | Ano automaticky při aktivním živém Přehledu; vypínač D15 je nevypíná | Wi-Fi brána, internetový cíl (výchozí Cloudflare 1.1.1.1); resolver aktivní sítě (výchozí jméno one.one.one.one) | Latence, ztráty a DNS odezva; ICMP nešifrovaně, DNS podle resolveru. Odchod z živého Přehledu/přechod do pozadí zastaví session | [WifiLiveViewModel.kt:200](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L200); [WifiLiveViewModel.kt:250](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L250); [WifiLiveViewModel.kt:428](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L428); [WifiLiveViewModel.kt:468](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L468); [LiveTelemetry.kt:537](../../shared/src/commonMain/kotlin/cz/netkit/shared/wifi/LiveTelemetry.kt#L537); [SignalScreen.kt:160](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/SignalScreen.kt#L160) | | D17 | Kontrola aktualizací (F3, záloha D22): GET latest.json, veřejná zdrojová IP, čas, cesta, User-Agent NetKit/verze; lokální stav kontroly | SharedPreferences `update`: vypínač, čas posledního pokusu a úspěchu, zdroj poslední odpovědi (web/github), poslední platný latest.json, skrytá verze | HTTPS GET bez cookies a identifikátorů; při startu procesu v popředí nejvýš 1×/60 min, při dalších návratech nejvýš 1×/24 h, výchozí zapnuto, vypínač a ruční kontrola; nejdřív web, při chybě GitHub; přesměrování jen na povolené hosty, nejvýš 3, 5 s na zdroj | Web autora https://www./netkit/latest.json (hosting Cloudflare); záloha github.com/Losminek/netkit/releases/latest/download/latest.json → release-assets.githubusercontent.com | Oznámení aktualizace; APK nestahuje/neinstaluje. DNS k webu a GitHubu vidí resolver. Logování a retenci hostingu nelze odvodit z klienta | [UpdateFetch.kt:17](../../shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateFetch.kt#L17); [UpdateFetch.kt:47](../../shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateFetch.kt#L47); [UpdateFetch.kt:116](../../shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateFetch.kt#L116); [UpdateChecker.kt:39](../../androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt#L39); [UpdateChecker.kt:152](../../androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt#L152); [UpdateChecker.kt:165](../../androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt#L165); emulátor PASS | -| D18 | Ruční import/export WoL JSON/CSV, SSH profilů, LAN výsledků; kopírování/sdílení terminálu a veřejného SSH klíče | Soubor u zvoleného poskytovatele, schránka či jiná aplikace | Jen na akci uživatele; poskytovatel může být cloudový a data synchronizovat | Uživatelem vybrané úložiště/aplikace/příjemce | Přenos dat; SSH export vynechává tajemství, reference a důvěru serverům, ale obsahuje startovací příkaz. Původní importovaný klíč zůstává u poskytovatele | [WolViewModel.kt:111](../../androidApp/src/main/kotlin/cz/netkit/app/wol/WolViewModel.kt#L111); [SshViewModel.kt:181](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L181); [SshViewModel.kt:202](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L202); [SshModels.kt:56](../../shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt#L56); [LanViewModel.kt:179](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt#L179); [LanScreen.kt:513](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanScreen.kt#L513); [SshScreen.kt:671](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt#L671) | +| D18 | Ruční import/export WoL JSON/CSV, SSH profilů, LAN výsledků; export skenu Wi-Fi a záznamu obchůzky CSV/JSON (SSID, BSSID, výrobce, RSSI, kanál, link rate, ping brány, značky míst; zadání 38); kopírování/sdílení terminálu a veřejného SSH klíče | Soubor u zvoleného poskytovatele, schránka či jiná aplikace | Jen na akci uživatele; poskytovatel může být cloudový a data synchronizovat | Uživatelem vybrané úložiště/aplikace/příjemce | Přenos dat. SSH export vynechává tajemství, jejich reference a důvěru serverům. Zahrnuje startovací příkaz, čitelné globální i profilové snippety, pravidla `-L`/`-D` a volbu ProxyJump (D30). Konfigurační záloha z Nastavení (výchozí šifrovaná heslem, AES-256-GCM s PBKDF2) obsahuje profily SSH/Telnet/sériové linky, snippety, přesměrování, důvěru serverům, WoL zařízení, předvolby nástrojů, oblíbené cíle, servery rychlosti a nastavení vzhledu; SSH hesla, privátní klíče, hesla SecureOn, přihlašovací údaje SOCKS, SNMP community, historie měření ani souhlasy do ní nevstupují. Původní importovaný klíč zůstává u poskytovatele | [WolViewModel.kt:111](../../androidApp/src/main/kotlin/cz/netkit/app/wol/WolViewModel.kt#L111); [SshViewModel.kt:181](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L181); [SshViewModel.kt:202](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L202); [SshModels.kt:56](../../shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt#L56); [LanViewModel.kt:179](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt#L179); [LanScreen.kt:513](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanScreen.kt#L513); [SshScreen.kt:671](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt#L671); [WifiViewModel.kt:114](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt#L114); [WifiLiveViewModel.kt:431](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L431); [WifiExportFiles.kt:51](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiExportFiles.kt#L51); [ConfigurationBackup.kt](../../shared/src/commonMain/kotlin/cz/netkit/shared/backup/ConfigurationBackup.kt) | | D19 | Všechny soukromé soubory, preference a tajemství aplikace | Lokální úložiště | Zálohování a přenos dat aplikace Androidem jsou v manifestu/XML zakázané; neplatí pro ruční exporty | — pro systémovou zálohu | allowBackup=false; cloud-backup i device-transfer vylučují všechny domény; statické ověření konfigurace, nikoli záruka chování každého výrobce telefonu | [AndroidManifest.xml:23](../../androidApp/src/main/AndroidManifest.xml#L23); [backup_rules.xml:2](../../androidApp/src/main/res/xml/backup_rules.xml#L2); [data_extraction_rules.xml:2](../../androidApp/src/main/res/xml/data_extraction_rules.xml#L2) | -| D20 | Oprávnění síť/Wi-Fi, poloha pro Wi-Fi, základní/rozšířený stav telefonu | Přístup k systémovým informacím, bez GPS souřadnic | Samotné oprávnění nic neodesílá; konkrétní toky viz výše | — | FINE/COARSE pro Wi-Fi scan/identitu AP; READ_PHONE_STATE pro obě SIM a typ sítě, READ_BASIC_PHONE_STATE pro základní typ sítě. Již udělená poloha může zpřístupnit i jméno operátora v ServiceState; monitor ji sám nežádá | [AndroidManifest.xml:4](../../androidApp/src/main/AndroidManifest.xml#L4); [WifiViewModel.kt:92](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt#L92); [WifiViewModel.kt:227](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt#L227); [CellularMonitor.kt:195](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt#L195); [CellularMonitor.kt:232](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt#L232) | -| D21 | Mazání a kontrola uživatelem | UI aplikace a systémová správa dat | Mazání lokálních dat neodvolá data u příjemců ani exporty | Lokální zařízení; o vzdálená data žádá uživatel jejich provozovatele | Smazání WoL/SSH profilů, klíčů a historie rychlosti; odvolání souhlasu LAN a vypnutí veřejné IP; úplné vymazání dat přes Android odstraní i archivy a preference | [WolController.kt:114](../../shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolController.kt#L114); [SshViewModel.kt:166](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L166); [SshViewModel.kt:198](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L198); [SpeedTestViewModel.kt:288](../../androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt#L288); [LanDevicesViewModel.kt:234](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt#L234); [WifiLiveViewModel.kt:292](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L292); systémové vymazání je uživatelský postup, na zařízení zde NOT RUN | -| D22 | Otevření webu zařízení nebo stránky/stažení aktualizace | Externí prohlížeč, jeho historie a případné stažené soubory | Na uživatelovo otevření odkazu | Web zařízení; plán F3 web autora nebo GitHub a infrastruktura stahování | Prohlížeč se řídí vlastními zásadami; NetKit tím neprovádí instalaci | [DevicesScreen.kt:470](../../androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesScreen.kt#L470); zadání F3 (interní záznam) (F3 po sloučení ověřit) | +| D20 | Oprávnění síť/Wi-Fi, poloha pro Wi-Fi, základní/rozšířený stav telefonu | Přístup k systémovým informacím, bez GPS souřadnic | Samotné oprávnění nic neodesílá; konkrétní toky viz výše | — | FINE/COARSE pro Wi-Fi scan/identitu AP; READ_PHONE_STATE pro obě SIM a typ sítě, READ_BASIC_PHONE_STATE pro základní typ sítě. FOREGROUND_SERVICE a FOREGROUND_SERVICE_SPECIAL_USE umožňují službu SSH, Telnetu a USB na popředí, POST_NOTIFICATIONS zobrazení oznámení (počet a zvolené názvy profilů v soukromém oznámení, veřejná verze bez detailů); USE_BIOMETRIC pro volitelný zámek SSH (systémové ověření, výsledek zůstává v telefonu); nic neodesílá. Již udělená poloha může zpřístupnit i jméno operátora v ServiceState; monitor ji sám nežádá | [AndroidManifest.xml:4](../../androidApp/src/main/AndroidManifest.xml#L4); [WifiViewModel.kt:92](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt#L92); [WifiViewModel.kt:227](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt#L227); [CellularMonitor.kt:195](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt#L195); [CellularMonitor.kt:232](../../androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt#L232) | +| D21 | Mazání a kontrola uživatelem | UI aplikace a systémová správa dat | Mazání lokálních dat neodvolá data u příjemců ani exporty | Lokální zařízení; o vzdálená data žádá uživatel jejich provozovatele | Smazání WoL/SSH profilů, snippetů a klíčů. V Nastavení zvlášť historie speedtestu, historie iperf3, poslední hostitel/port iperf3 a historie cílů nástrojů; historii cílů smaže i nabídka u pole cíle. Smazání historie ponechá oblíbené, které lze odebrat jednotlivě (D29); odvolání souhlasu LAN a vypnutí veřejné IP; úplné vymazání dat přes Android odstraní i archivy a preference | [WolController.kt:114](../../shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolController.kt#L114); [SshViewModel.kt:166](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L166); [SshViewModel.kt:198](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt#L198); [SpeedTestViewModel.kt:288](../../androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt#L288); [LanDevicesViewModel.kt:234](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt#L234); [WifiLiveViewModel.kt:292](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L292); systémové vymazání je uživatelský postup, na zařízení zde NOT RUN || D22 | Otevření webu zařízení nebo stránky/stažení aktualizace | Externí prohlížeč, jeho historie a případné stažené soubory | Na uživatelovo otevření odkazu | Web zařízení; plán F3 web autora nebo GitHub a infrastruktura stahování | Prohlížeč se řídí vlastními zásadami; NetKit tím neprovádí instalaci | [DevicesScreen.kt:470](../../androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesScreen.kt#L470); zadání F3 (interní záznam) (F3 po sloučení ověřit) | +| D23 | DNS jméno nebo reverzní IP, typ RR | RAM, ruční LAN export | Po spuštění | Systémový resolver aktivní sítě, po zvláštní volbě i Wi-Fi mimo VPN | Porovnání může odkrýt interní jméno | [Výběr sítí a rawQuery](../../androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticLookup.kt) | +| D24 | URL včetně cesty a parametrů, zdrojová IP, čas a User-Agent `NetKit/` | RAM | Po spuštění HEAD, při 405/501 také GET do první změny originu | Zadaný server, nejvýše pět přesměrování, DNS resolver jmen | HTTP je nešifrované, HTTPS používá systémovou validaci. Přesměrování zachová port nebo přejde na 80/443. Po veřejném spojení vyžaduje automatické pokračování výhradně veřejné adresy. Přesměrování na jiné jméno s výhradně fake-IP odpovědí vyžaduje samostatný souhlas. Blokovaný cíl lze předvyplnit a zvlášť spustit | [Web/TLS](../../androidApp/src/main/kotlin/cz/netkit/app/lan/WebDiagnostic.kt) | +| D25 | Hledaná veřejná IP nebo ASN, zdrojová IP, čas a User-Agent `NetKit/` | RAM | Ruční dotaz při zapnuté volbě zjišťování veřejné IP | rdap.org, příslušný RIR a DNS resolver jmen služeb | HTTPS. Podle soukromého provozovatele rdap.org se jednotlivé dotazy nelogují. Statistiky agreguje podle sítě (/24 pro IPv4, /48 pro IPv6), User-Agentu, kódu odpovědi a HTTP originu. Retenci u RIR klient neověřuje. [Informace provozovatele](https://about.rdap.org/) | [Brána a transport RDAP](../../androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticLookup.kt) | +| D26 | Widget stavu sítě (zadání 37): poslední měření z popředí — kanál/frekvence, RSSI, link, RTT brány, poslední speedtest, šířka kanálu; volitelně SSID a veřejná IP (obě výchozí vypnuté) | Nešifrovaný noBackupFilesDir/netstatus_widget.json; zobrazení na ploše (na zamčené obrazovce bez SSID a IP) | Ne. Widget nic neodesílá ani nezjišťuje; obnovení čte jen rádiové hodnoty bez polohy a bez síťového provozu | — | Lokální kopie hodnot už zobrazených v aplikaci (D05, D07, D15, D16). SSID jen s volbou a oprávněním k poloze, veřejná IP jen s volbou a zapnutým zjišťováním; vypnutí volby, odebrání polohy nebo vypnutí zjišťování uloženou hodnotu smaže | [NetStatusService.kt:50](../../androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusService.kt#L50); [NetStatus.kt:100](../../shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatus.kt#L100); [NetStatusService.kt:151](../../androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusService.kt#L151); [WifiLiveViewModel.kt:688](../../androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt#L688) | +| D27 | Sdílení výsledků (zadání 47): diagnostický report z Přehledu (čas, verze, typ sítě, adresy rozhraní, brána, DNS, DHCP, MTU, Wi-Fi link/kanál/šířka/standard/RSSI, latence a ztráty za minutu, poslední speedtest/iperf3; volitelně SSID, BSSID, veřejná IP/ASN a veřejně směrovatelné adresy rozhraní, jméno privátního DNS a server iperf3 mimo místní adresy — vše výchozí vypnuté); kopírování hodnot dlouhým stiskem; export seznamu zařízení TXT/CSV/JSON; text výsledku měření (SSID výchozí vypnuté) | Report jen v paměti dialogu; soubor u zvoleného poskytovatele, schránka či jiná aplikace | Jen na akci uživatele (Kopírovat / Sdílet `ACTION_SEND` / Uložit přes SAF); sestavení reportu nic neodesílá ani neměří, čte jen hodnoty Přehledu, historii rychlosti (D05) a poslední systémový sken (šířka kanálu) | Uživatelem vybraný příjemce/úložiště | Diagnostika pro podporu či kolegu. Veřejně směrovatelné adresy, jméno privátního DNS a server iperf3 mimo místní adresy jsou v reportu jen s volbou „Zahrnout veřejné adresy“, jinak se vynechají nebo nahradí `?`. Bez údajů o mobilní buňce (D08, rozhodnutí D31), bez tajemství SSH/SecureOn (test modelu a zdrojová pojistka); citlivé kopie (veřejná IP, BSSID, report s identifikátory) se značkou `EXTRA_IS_SENSITIVE` (API 33+) | [DiagnosticReport.kt](../../shared/src/commonMain/kotlin/cz/netkit/shared/report/DiagnosticReport.kt); [DiagnosticReportViewModel.kt](../../androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportViewModel.kt); [ShareActions.kt](../../androidApp/src/main/kotlin/cz/netkit/app/ui/ShareActions.kt); [LanDeviceExport.kt](../../shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDeviceExport.kt); [SpeedShare.kt](../../androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedShare.kt); emulátor PASS (report 52) | +| D28 | iperf3 (zadání 45): host nebo IP a port vlastního serveru, parametry testu, poslední použitý server, výsledky v historii rychlosti; měřený TCP provoz se zdrojovou IP | Poslední hostitel a port pro další běh a výsledky ve společné historii `noBackupFilesDir/speedtest.json` (společný limit 20 záznamů s D05) | Ano, nešifrované TCP (řídicí kanál a 1–8 datových proudů) na výslovné spuštění | Uživatelem zadaný server iperf3; DNS resolver aktivní sítě | Měření vlastní linky. Server vidí zdrojovou IP, čas a provoz, retenci na serveru určuje provozovatel. V diagnostickém reportu (D27) je veřejná adresa nebo jméno serveru jen se souhlasem „Zahrnout veřejné adresy“; sdílení jednoho výsledku je výslovná volba. Místní výsledek a zapamatovaný cíl lze smazat zvlášť (D21) | [Iperf3Client.kt](../../androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Client.kt); [SpeedTestViewModel.kt:345](../../androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt#L345); [SpeedHistory.kt](../../shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt); [DiagnosticReport.kt](../../shared/src/commonMain/kotlin/cz/netkit/shared/report/DiagnosticReport.kt); [SettingsScreen.kt](../../androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsScreen.kt) | +| D29 | Cíle nástrojů pro jeden cíl (zadání 48): posledních 10 IP adres, hostitelů/DNS jmen, ASN nebo URL a až 30 oblíbených s názvem | Soukromý nešifrovaný DataStore `filesDir/datastore/lan-tools.json` | Ne (samotná historie); spuštění nástroje viz D09, D23–D25 | — (při použití konkrétního cíle příjemce daného nástroje) | Opakované zadání cílů. Historie ponechá cestu URL a odstraní query a fragment; URL s přihlašovacími údaji (`@`) se neuloží vůbec. Výslovně uložená oblíbená URL je celá. Historie se maže v Nastavení nebo v nabídce u pole cíle a zachová oblíbené, ty se odebírají jednotlivě | [ToolTargets.kt](../../shared/src/commonMain/kotlin/cz/netkit/shared/lan/ToolTargets.kt); [LanToolPreferences.kt](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanToolPreferences.kt); [TargetHistory.kt](../../androidApp/src/main/kotlin/cz/netkit/app/lan/TargetHistory.kt); [LanViewModel.kt:257](../../androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt#L257) | +| D30 | SSH produktivita (zadání 41): snippety, pravidla `-L`, SOCKS5 `-D`, skoky ProxyJump; záznam výstupu relace do souboru | Snippety a volby v nešifrovaných metadatech profilů SSH (D03) i v exportu profilů v2. Volitelný log zapisuje výstup včetně případně opakovaného vstupu do souboru vybraného přes SAF | Na pokyn uživatele. Snippet jen na klepnutí do relace. `-L`/`-D` naslouchají jen na `127.0.0.1` a provoz jde kanálem SSH; `-L` předává spojení na pevný cíl, `-D` na cíl vyžádaný klientem SOCKS5. K portu se mohou připojit i jiné aplikace telefonu. ProxyJump otevře spojení přes přeskokové servery | Vybrané SSH skoky (vidí cíl a port), koncový SSH server, cílová služba; pro export nebo log uživatelem vybrané úložiště (i cloud) | SSH šifruje tunel do SSH serveru, poslední úsek k cílové službě chrání její vlastní protokol. Snippety nemají být heslem (UI varuje). Záznam relace Telnet nenabízí. Kopie logu a exportu zůstávají u příjemce | [SshSnippets.kt](../../shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshSnippets.kt); [SshProfileExchange.kt:39](../../shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt#L39); [SshForwarders.kt](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshForwarders.kt); [JschConnection.kt:56](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt#L56); [SshSessionLog.kt](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionLog.kt) | +| D31 | Telnet a USB sériová konzole, vstup a výstup terminálu | Profil ukládá název, u Telnetu hostitele, port a volbu varování, u USB parametry sériové linky. Telnetové heslo uživatel zadává do živé relace | Po připojení. Telnet přenáší příkazy, hesla i odpovědi nešifrovaně přes TCP. Sériová data jdou po USB kabelu | Zvolený Telnet server nebo zařízení na zvoleném USB portu | Android uděluje dočasný přístup ke konkrétnímu USB zařízení. Soukromé oznámení může zobrazit názvy profilů (D20) | [ConsoleProfile.kt](../../shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ConsoleProfile.kt) · [ConsoleConnection.kt](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleConnection.kt) · [UsbConsole.kt](../../androidApp/src/main/kotlin/cz/netkit/app/ssh/UsbConsole.kt) | ## Rozpory se starší dokumentací diff --git a/docs/public/privacy-cs.md b/docs/public/privacy-cs.md index 63051cb..1b0f1a7 100644 --- a/docs/public/privacy-cs.md +++ b/docs/public/privacy-cs.md @@ -3,8 +3,8 @@ **Závazné znění je na webu: , účinné od 31. 10. 2026.** Správce a kontakt: Daniel Lošák, info@losak.cz. -Tento soubor je technická předloha webové stránky. Oddíly 1–9 web převzal beze změny -(revize `5178db9`), oddíl 10 zde zrcadlí text webu. Odkazy D01–D22 vedou na technickou +Tento soubor je technická předloha s navrhovanými změnami pro Android 2.0.0. +Oddíl 10 zde zrcadlí text webu. Odkazy s číslem D vedou na technickou evidenci a na webu nejsou. Změna chování aplikace, která mění oddíly 1–9, se musí předat webu (repo `Losminek/osobni-web`) a vydat tam s novým datem účinnosti dřív, než vyjde verze aplikace s novým chováním. Při rozporu platí web. @@ -34,17 +34,37 @@ dočasně v paměti. Původní soubor importovaného klíče aplikace nemaže. Historie rychlosti uchovává posledních 20 výsledků, čas, server, typ sítě a dostupné údaje Wi-Fi včetně názvu sítě (SSID), frekvence, signálu a rychlosti linky. Ukládá -se také vlastní adresa serveru, potvrzení upozornění M-Lab a nastavení aplikace. +se také vlastní URL LibreSpeed, poslední hostitel a port iperf3, potvrzení upozornění M-Lab +a nastavení aplikace. Souhlas s automatickým hledáním zařízení je přiřazen k síti pomocí lokálního HMAC otisku; samotné SSID v této evidenci souhlasů není čitelné. [D05](data-toky.md#d05), [D06](data-toky.md#d06) -Výsledky Wi-Fi a LAN hledání, živé grafy, veřejná IP a údaje mobilní karty jsou -běžně v paměti, ne v trvalé historii. Výjimkou jsou výše uvedené údaje Wi-Fi -u rychlostních testů a vámi vytvořené exporty. NetKit čte počítadla přenesených +Nástroje pro jeden cíl sdílejí místní historii posledních 10 cílů (IP adresy, názvy hostitelů +a DNS, ASN nebo URL) a až 30 oblíbených s volitelným názvem. U URL se do historie ukládá i cesta. +Parametry a fragment se uchovají jen při výslovném přidání celé URL mezi oblíbené. Historii lze +vymazat v Nastavení nebo v nabídce u pole cíle. Oblíbené cíle odeberete jednotlivě. +[D29](data-toky.md#d29) + +Historie rychlosti zahrnuje i měření iperf3 včetně jména nebo adresy vašeho serveru +a portu. Poslední server iperf3 i obě historie lze v Nastavení samostatně smazat. K SSH profilům se ukládají také snippety (pojmenované texty k odeslání +do terminálu), pravidla přesměrování portů (`-L`), volba SOCKS proxy (`-D`) a volba +přeskokového serveru (ProxyJump). Ani tyto údaje aplikace nešifruje, do snippetů proto +nevkládejte hesla. +[D28](data-toky.md#d28), [D30](data-toky.md#d30) + +Seznamy zařízení nalezených při Wi-Fi a LAN skenu, živé grafy, veřejná IP a údaje mobilní karty jsou +běžně v paměti. Údaje zůstávají také v historii rychlosti, ve vámi vytvořených +exportech a v místním snímku pro widget stavu sítě. NetKit čte počítadla přenesených bajtů pro graf provozu, nikoli obsah cizích paketů. [D07](data-toky.md#d07), [D08](data-toky.md#d08), [D15](data-toky.md#d15) +Widget stavu sítě zobrazuje na ploše poslední údaje o signálu a lince, odezvu brány +a poslední měření rychlosti. Název Wi-Fi a veřejnou IP do snímku uloží jen po zapnutí +příslušné volby. Na zamčené obrazovce je skryje. Obnovení widgetu přečte rádiové +údaje telefonu bez síťového dotazu. WoL widget a připnuté zkratky ukazují vámi zvolené +názvy zařízení či profilů lidem, kteří vidí plochu. Dlaždice signálu jen otevře Přehled. + ## 3. Diagnostika sítě, Wake-on-LAN a SSH DNS dotazy obsahují hledané jméno nebo IP a dostává je resolver příslušné sítě @@ -67,6 +87,12 @@ zvolený cíl nebo broadcast. Volitelně ověřuje odpověď zařízení. Paket používají podkladovou Wi-Fi mimo VPN. [D11](data-toky.md#d11) +Klepnutí na Probudit ve widgetu odešle stejný WoL paket. Pokud zařízení používá +SecureOn, jeho heslo se v telefonu ukládá šifrovaně pomocí Android Keystore. +WoL paket obsahuje heslo v čitelné podobě. Při exportu zařízení se heslo vynechá. Ruční identifikace služeb +posílá zvolenému místnímu zařízení nešifrované sondy NTP, DNS nebo SNMPv2c. +Komunita SNMP se odesílá čitelně, jen když ji zadáte, a v aplikaci se neukládá. + SSH předává zvolenému serveru uživatelské jméno, autentizační údaje podle metody, příkazy a vstup terminálu přes šifrované SSH spojení s kontrolou klíče serveru. Privátní klíč slouží k autentizaci lokálně a neposílá se jako soubor serveru. @@ -74,8 +100,47 @@ SSH používá systémovou síťovou trasu včetně případné VPN. Provozovate může vést vlastní záznamy relace. [D12](data-toky.md#d12) +Pro ProxyJump volíte i mezilehlé (přeskokové) SSH servery; každý z nich vidí adresu a port +dalšího cíle. Místní přesměrování portu (`-L`) a SOCKS5 (`-D`) naslouchají po dobu relace jen +na adrese `127.0.0.1` telefonu a provoz z nich jde šifrovaně přes SSH server, který pak navazuje +spojení k vybranému cíli. Na místní port se mohou připojit také jiné aplikace v telefonu. Šifrování +mezi SSH serverem a cílem závisí na protokolu cílové služby. + +Uložené příkazy (snippety) jsou v aplikaci i v exportu SSH profilů čitelné. Volitelný log zapisuje výstup serveru včetně toho, co terminál vypíše zpět, +do souboru, který vyberete. Může obsahovat citlivé údaje. [D30](data-toky.md#d30) + +SFTP přenáší jen soubory, které sami vyberete. Jejich názvy a obsah jdou šifrovaně mezi vaším SSH +serverem a úložištěm vybraným v systémovém dialogu. Vybrat můžete místní soubor +i cloudové úložiště. [D12](data-toky.md#d12) + +Telnet odesílá veškerý vstup včetně hesla a příkazů zvolenému serveru v čitelné podobě. +Profil ukládá název, cíl, port a volbu zobrazení varování. Přihlašovací údaje se zadávají +až v živé relaci. U sériové konzole dostává vstup zařízení na vybraném USB portu. +Android řídí přístup ke konkrétnímu USB převodníku. [D31](data-toky.md#d31) + +Při spuštění nástroje DNS záznamy dostane jméno a typ záznamu resolver aktivní sítě. +Volba porovnání odešle stejný dotaz také resolveru Wi-Fi mimo VPN a může mu prozradit +interní název. Ve Web/TLS dostane zadaný server a případné cíle přesměrování zdrojovou +IP, čas, označení klienta `NetKit/` a požadovanou cestu včetně parametrů. HTTP přenáší tyto údaje nešifrovaně. +Spuštění RDAP odešle zadanou veřejnou IP nebo ASN službě rdap.org a regionálnímu +registru přes HTTPS. Oba dostanou také označení klienta `NetKit/`. +Službu rdap.org provozuje soukromá osoba. Podle provozovatele se jednotlivé dotazy +nelogují. Souhrnné statistiky člení podle zdrojové sítě (/24 u IPv4, /48 u IPv6), +User-Agentu, kódu odpovědi a HTTP originu. Jak dlouho uchovává údaje příslušný +regionální registr, NetKit neověřuje. [Informace provozovatele](https://about.rdap.org/) + +RDAP lze vypnout společně se zjišťováním veřejné IP. Výsledky +zůstávají v paměti, DNS záznamy můžete sami exportovat. +[D23](data-toky.md#d23), [D24](data-toky.md#d24), [D25](data-toky.md#d25) + ## 4. Rychlostní test +Při ručním testu iperf3 vidí vámi zvolený server zdrojovou IP, parametry a výsledek +měření. Parametry, testovací data a výsledky se přenášejí nešifrovaným TCP. +Poslední hostitel a port se ukládají pro další test. Výsledek včetně cíle je také ve společné +historii měření. Do diagnostického reportu se veřejná adresa nebo jméno serveru dostane jen +s vaším souhlasem. Délku uchování na serveru určuje jeho provozovatel. [D28](data-toky.md#d28) + Test začíná na vaši akci a může přenést velké množství dat i přes mobilní síť. Vybraný LibreSpeed server (preset `rychlost.zelina.eu` nebo vaše vlastní HTTPS URL) vidí veřejnou zdrojovou IP, čas a provoz testu a identifikaci klienta/verze. @@ -101,9 +166,10 @@ User-Agent `NetKit/ (Android)`. Požadavek nepřidává cookies ani ident Pro zjištění poskytovatele posílá NetKit DNS TXT dotazy do `asn.cymru.com`. Dotaz obsahuje veřejnou IP v obráceném zápisu a následně číslo autonomního systému (ASN). Tyto údaje tedy získává resolver aktivní sítě a služba Team Cymru. -Výsledek zůstává jen v paměti, cache je čerstvá 10 minut. Volba +Přehled uchovává výsledek v paměti, cache je čerstvá 10 minut. Volba „Zjišťovat veřejnou IP“ v menu karty Připojení funkci vypne, zruší probíhající -dotazy a vymaže výsledek z paměti. Nevymaže záznamy u příjemců. +dotazy, vymaže výsledek z paměti a smaže případnou kopii veřejné IP pro widget. +Nevymaže záznamy u příjemců. [D15](data-toky.md#d15) ## 6. Kontrola aktualizací a otevření webů @@ -135,23 +201,57 @@ NetKit nezjišťuje GPS souřadnice ani nesleduje polohu na pozadí. Již uděle oprávnění může v systémovém stavu mobilní sítě zpřístupnit také jméno operátora. [D20](data-toky.md#d20) +Při prvním připojení si NetKit na podporovaných verzích Androidu vyžádá oprávnění +k oznámením. Služba na popředí udržuje otevřené relace SSH, Telnetu a USB konzole. +Z oznámení je můžete všechny odpojit. Soukromé oznámení ukazuje počet a názvy profilů. +Pokud jste profil pojmenovali adresou serveru, zobrazí se i ta. Veřejná verze na zamčené +obrazovce ukazuje jen běžící relaci. Bez služby platí pětiminutový limit na pozadí. +[D20](data-toky.md#d20) + +Volitelný zámek SSH (od verze 2.0.0, výchozí vypnutý) používá systémové ověření biometrií +nebo zámkem obrazovky. NetKit dostane jen výsledek ověření, ne biometrické údaje, a nic +se kvůli tomu neodesílá. [D20](data-toky.md#d20) + `READ_PHONE_STATE` slouží k zobrazení obou SIM a typu sítě; žádá se z mobilní karty. `READ_BASIC_PHONE_STATE` slouží k základnímu typu sítě bez samostatného dialogu. Mobilní karta používá jméno operátora, lokální index SIM/slot, typ sítě, sílu -signálu, roaming a stav služby. **Nečte telefonní čísla, IMEI, IMSI, ICCID ani -Cell ID**, obsah či historii hovorů. Údaje mobilní karty se neposílají ven -ani neukládají na disk. +signálu, roaming a stav služby. **Nečte telefonní čísla, IMEI, IMSI ani ICCID**, +obsah či historii hovorů. Údaje mobilní karty se neposílají ven ani neukládají na disk. [D08](data-toky.md#d08), [D20](data-toky.md#d20) +Rozbalený „Detail buňky“ (od verze 2.0.0) čte s již udělenou přesnou polohou +a oprávněním k telefonu údaje o obsluhující a sousedních buňkách: pásmo, kanál +(EARFCN/NR-ARFCN), PCI, ID buňky, TAC, šířku kanálu, timing advance a sílu signálu. +ID buňky s TAC může prozradit přibližnou polohu, proto se tyto údaje **zpracují jen +v zařízení**: zobrazí se, drží se jen v paměti po dobu otevřeného detailu a nikdy se +neukládají, neexportují, nesdílejí, neposílají ven ani nejsou v diagnostickém reportu. +[D08](data-toky.md#d08) + ## 8. Exporty a zálohy Data se předávají do souboru, schránky nebo jiné aplikace, když použijete export, kopírování či sdílení. Vybrané úložiště může být cloudové. Exporty WoL a LAN mohou -obsahovat adresy a názvy zařízení; export SSH profilů neobsahuje uložená hesla ani -privátní klíče, ale obsahuje údaje profilů včetně startovacích příkazů. +obsahovat adresy a názvy zařízení; export skenu Wi-Fi a záznamu obchůzky obsahuje +názvy a identifikátory (SSID, BSSID) okolních sítí, signál a vaše značky míst; export SSH profilů neobsahuje uložená hesla ani +privátní klíče, ale obsahuje údaje profilů včetně startovacích příkazů, čitelného textu snippetů, +přesměrování a volby přeskokového serveru. Sdílený obsah terminálu může obsahovat citlivé údaje. Cíl vybíráte vy. [D18](data-toky.md#d18) +Diagnostický report z Přehledu obsahuje údaje o připojení a posledních měřeních. +Teprve na váš pokyn jej NetKit zkopíruje do schránky, předá vybrané aplikaci nebo uloží +jako text či JSON. Volby pro SSID, BSSID a veřejné adresy jsou výchozí vypnuté. +Veřejnou IP/ASN, veřejně směrovatelné adresy, jméno serveru privátního DNS a adresu +vlastního serveru iperf3 mimo místní síť report obsahuje jen se zapnutou volbou +„Zahrnout veřejné adresy“. [D27](data-toky.md#d27) + +Konfigurační zálohu vytvoříte v Nastavení jen na svůj pokyn do souboru, který vyberete. +Ve výchozím stavu je šifrovaná heslem, které zadáte. Obsahuje profily připojení, snippety, +přesměrování, ověřené klíče serverů, WoL zařízení, předvolby a oblíbené cíle nástrojů, servery +pro měření rychlosti a nastavení vzhledu. Uložená SSH hesla, privátní klíče, hesla SecureOn, +přihlašovací údaje SOCKS, historie měření ani souhlasy do ní nevstupují. Pokud šifrování vypnete, +soubor přečte každý, kdo k němu získá přístup. [D18](data-toky.md#d18) + NetKit v konfiguraci Androidu zakazuje systémové zálohování i přenos soukromých dat aplikace na jiné zařízení. Toto omezení se nevztahuje na soubory, které sami exportujete do jiného úložiště. @@ -161,8 +261,10 @@ exportujete do jiného úložiště. Můžete odebrat oprávnění v nastavení Androidu, odvolat souhlas s automatickým hledáním v LAN, vypnout veřejnou IP i kontrolu aktualizací. -Uložená WoL zařízení, SSH profily, nepoužívané SSH klíče a historii rychlosti lze -mazat v aplikaci. Pro odstranění všech místních dat včetně nastavení a archivů +Uložená WoL zařízení, SSH profily a snippety, nepoužívané SSH klíče a historii rychlosti lze +mazat v aplikaci. V Nastavení můžete zvlášť smazat výsledky iperf3, zapomenout posledního +hostitele a port a vymazat historii cílů nástrojů; historii cílů smaže i nabídka u pole cíle. +Oblíbené cíle odeberete jednotlivě zrušením hvězdičky. Pro odstranění všech místních dat včetně nastavení a archivů použijte vymazání úložiště aplikace v Androidu nebo odinstalaci. [D21](data-toky.md#d21), [D17](data-toky.md#d17) diff --git a/docs/public/privacy-en.md b/docs/public/privacy-en.md index 309134d..d96638e 100644 --- a/docs/public/privacy-en.md +++ b/docs/public/privacy-en.md @@ -4,9 +4,9 @@ , effective from 31 October 2026.** Controller and contact: Daniel Lošák, info@losak.cz. -This file is the technical source of the web page. Sections 1–9 translate the template the -website took over unchanged (revision `5178db9`); section 10 mirrors the website. References -D01–D22 link to the technical evidence and are not on the website. If this translation and +This file is the technical source for the website, with proposed changes for Android 2.0.0. +Section 10 mirrors the website. Numbered D references link to the technical evidence. +If this translation and the Czech website differ, the website prevails. ## 1. Why NetKit uses data @@ -36,17 +36,38 @@ file when you import a key. Speed history retains the latest 20 results, time, server, network type and available Wi-Fi details including network name (SSID), frequency, signal and link rate. -The custom server address, acknowledgement of the M-Lab notice and app settings +The custom LibreSpeed URL, the last iperf3 host and port, acknowledgement of the M-Lab notice and app settings are also stored. Automatic LAN discovery consent is associated with a network using a local HMAC fingerprint; the SSID itself is not readable in that consent record. [D05](data-toky.md#d05), [D06](data-toky.md#d06) +Single-target tools share a local history of up to 10 recent targets (IP addresses, +hostnames, DNS names, ASNs or URLs) and up to 30 favourites with optional labels on the phone. +URL history includes the path. Saving a full URL as a favourite also keeps its query and fragment. +You can clear the history in Settings or from the menu next to the target field, and remove +individual favourites. [D29](data-toky.md#d29) + +Speed history also includes iperf3 measurements with the name or address and port +of your server. In Settings you can separately forget the last iperf3 server and delete +both histories. SSH profiles also store snippets (named text to send to +the terminal), port forwarding rules (`-L`), the SOCKS proxy option (`-D`) and the jump +host choice (ProxyJump). The app does not encrypt these either, so do not put passwords +in snippets. +[D28](data-toky.md#d28), [D30](data-toky.md#d30) + Wi-Fi and LAN discovery results, live charts, public IP and mobile network card -details are normally held in memory, not in permanent history. Exceptions are -the Wi-Fi details in speed history described above and exports you create. +details are normally held in memory. Some details are also kept in speed history, +in files you export and in the local snapshot for the network status widget. NetKit reads byte counters for its traffic chart, not other users' packet contents. [D07](data-toky.md#d07), [D08](data-toky.md#d08), [D15](data-toky.md#d15) +The network status widget shows the latest signal and link readings, gateway latency +and speed test result on your home screen. It saves the Wi-Fi name and public IP +to its snapshot only if you enable the respective options. It hides both on the +lock screen. Refreshing the widget reads radio information without sending network +requests. People who can see your home screen can see the names you chose for your +Wake-on-LAN widget and pinned device or profile shortcuts. The signal tile opens Overview. + ## 3. Network diagnostics, Wake-on-LAN and SSH DNS queries contain the name or IP being looked up and go to the relevant network's @@ -72,6 +93,12 @@ a response. Both the packet and target DNS lookup use the underlying Wi-Fi outsi the VPN. [D11](data-toky.md#d11) +Tapping Wake in the widget sends the same Wake-on-LAN packet. If the device uses +SecureOn, its password is stored encrypted using Android Keystore. The packet carries +the password in cleartext and device exports omit it. Manual service identification +sends unencrypted NTP, DNS or SNMPv2c probes to the local device you select. An SNMP +community is sent in cleartext only if you enter one. The app does not save it. + SSH sends the username, authentication data required by the selected method, commands and terminal input to the selected server over an encrypted SSH connection with server key verification. The private key is used locally for @@ -80,8 +107,49 @@ network route, including a VPN if present. The server operator may keep its own session records. [D12](data-toky.md#d12) +With ProxyJump, you also choose the intermediate (jump) SSH servers; each of them sees the +address and port of the next hop. Local port forwarding (`-L`) and SOCKS5 (`-D`) listen only on +the phone's `127.0.0.1` for the duration of the session, and their traffic is carried encrypted +to the SSH server, which then connects to the selected destination. Other apps on the phone can +connect to the local port. Encryption from the SSH server to the destination depends on the destination service. + +Saved commands (snippets) are readable in +the app and in SSH profile exports. Optional session logging writes server output, including +any input echoed by the terminal, to a file you select. It may contain sensitive data. [D30](data-toky.md#d30) + +SFTP transfers only files you select. File names and contents travel over an encrypted connection +between your phone and your SSH server. +For uploads and downloads, you select the file or storage provider in the system file picker. +The provider may be a cloud service. [D12](data-toky.md#d12) + +Telnet sends all terminal input, including passwords and commands, to the selected server in clear text. +The profile stores its name, destination, port and warning preference. You enter credentials in the live session. +For serial consoles, the device on the selected USB port receives the input. Android controls access to the selected USB adapter. [D31](data-toky.md#d31) + +Starting DNS records sends the name and record type to the active network’s resolver. +Choosing to compare sends the same query to the Wi-Fi resolver outside the VPN and may +disclose an internal name to that resolver. In Web/TLS the chosen server and redirect +destinations receive your source IP, request time, the client identifier `NetKit/` and the requested path including query +parameters. HTTP sends these details in cleartext. Starting RDAP sends the public IP +or ASN you entered to rdap.org and the regional registry over HTTPS. Both also receive the client identifier `NetKit/`. +A private individual operates rdap.org. The operator says the service does not log individual +queries. It aggregates statistics by source network (/24 for IPv4, /48 for IPv6), user agent, +HTTP response code and HTTP origin. NetKit does not verify how long regional registries +retain data. [Operator’s privacy information](https://about.rdap.org/) + +Disabling public IP +lookup also disables RDAP. Results stay in memory. You can export DNS records yourself. +[D23](data-toky.md#d23), [D24](data-toky.md#d24), [D25](data-toky.md#d25) + ## 4. Speed tests +When you start an iperf3 test, the server you select sees the source IP, test +parameters and results. Parameters, test traffic and results travel over unencrypted +TCP. The app saves the last host and port for your next test. The result and its +destination also appear in local measurement history. A diagnostic report includes a public +address or name of the server only with your consent. The server operator determines +what it retains. [D28](data-toky.md#d28) + A test starts on your action and may transfer large amounts of data, including over a mobile network. The selected LibreSpeed server (the `rychlost.zelina.eu` preset or your own HTTPS URL) sees the public source IP, test time and traffic, @@ -109,9 +177,10 @@ User-Agent `NetKit/ (Android)`. The request adds no cookies or installa To identify the provider, NetKit sends DNS TXT queries to `asn.cymru.com`. The query contains the public IP in reverse notation and then the autonomous system number (ASN). The active network's resolver and Team Cymru therefore -receive those details. Results stay in memory only, with a cache freshness of +receive those details. Overview keeps results in memory, with a cache freshness of 10 minutes. “Look up public IP” in the Connection card menu disables the feature, -cancels ongoing queries and clears the result from memory. It does not delete +cancels ongoing queries, clears the result from memory and deletes any public IP +saved for the widget. It does not delete records held by recipients. [D15](data-toky.md#d15) @@ -145,23 +214,60 @@ An already granted location permission may also expose the operator name in the system's mobile network service state. [D20](data-toky.md#d20) +On supported Android versions, NetKit requests notification permission on the first +connection. A foreground service keeps SSH, Telnet and USB serial sessions connected. +You can disconnect them all from the notification. The private notification shows the +count and profile names, including a server address if you used it as a profile name. +The public lock screen notification only indicates a running session. Without the service, +a five-minute background limit applies. +[D20](data-toky.md#d20) + +The optional SSH lock (since version 2.0.0, off by default) uses system authentication with +biometrics or your screen lock. NetKit receives only the result, never biometric data, and +nothing is sent anywhere for it. [D20](data-toky.md#d20) + `READ_PHONE_STATE` supports displaying both SIMs and the network type; it is requested from the mobile card. `READ_BASIC_PHONE_STATE` supports basic network type information without a separate dialog. The mobile card uses the operator name, local SIM index/slot, network type, signal strength, roaming and service -state. **It does not read phone numbers, IMEI, IMSI, ICCID or Cell ID**, or call -contents or history. Mobile card details are neither sent out nor saved to disk. +state. **It does not read phone numbers, IMEI, IMSI or ICCID**, or call contents +or history. Mobile card details are neither sent out nor saved to disk. [D08](data-toky.md#d08), [D20](data-toky.md#d20) +The expanded "Cell detail" (from version 2.0.0) uses the already granted precise +location and phone permissions to read the serving and neighbour cells: band, +channel (EARFCN/NR-ARFCN), PCI, cell ID, TAC, channel bandwidth, timing advance and +signal strength. A cell ID with its TAC can reveal an approximate location, so this +data is **processed on the device only**: it is shown, kept in memory only while the +detail is open and never stored, exported, shared, sent out or included in the +diagnostic report. +[D08](data-toky.md#d08) + ## 8. Exports and backups Data is passed to a file, clipboard or another app when you export, copy or share. The selected storage provider may be a cloud service. WoL and LAN exports can -contain device addresses and names; SSH profile exports contain no saved passwords -or private keys, but do include profile details and startup commands. Shared +contain device addresses and names; Wi-Fi scan and walk log exports contain names +and identifiers (SSID, BSSID) of nearby networks, signal levels and your place marks; SSH profile exports contain no saved passwords +or private keys, but do include profile details, startup commands, readable command snippets, +forwarding rules and the jump host choice. Shared terminal contents may include sensitive information. You choose the destination. [D18](data-toky.md#d18) +The diagnostic report in Overview includes connection details and recent measurements. +Only when you choose to copy, share or save the report does NetKit send it to the +clipboard, the app you select or a text or JSON file. The options to include the SSID, +BSSID and public addresses are off by default. The public IP/ASN, publicly routable +addresses, the private DNS hostname and the address of your own iperf3 server outside the +local network are included only when you turn on "Include public addresses". [D27](data-toky.md#d27) + +You can create a configuration backup in Settings, only on your request, in a file you select. +By default it is encrypted with a password you enter. It contains connection profiles, snippets, +forwarding rules, trusted server keys, WoL devices, tool presets and favourite targets, speed test +servers and appearance settings. Saved SSH passwords, private keys, SecureOn passwords, SOCKS +credentials, measurement history and consents are not included. If you turn encryption off, +anyone who gets the file can read it. [D18](data-toky.md#d18) + NetKit's Android configuration disables system backup and transfer of the app's private data to another device. This does not cover files you export to other storage. [D19](data-toky.md#d19) @@ -170,8 +276,10 @@ private data to another device. This does not cover files you export to other st You can revoke permissions in Android settings, revoke automatic LAN discovery consent, disable public IP lookup and update checks. -You can delete saved WoL devices, SSH profiles, unused SSH keys and speed history -in the app. To remove all local data including settings and archives, clear the +You can delete saved WoL devices, SSH profiles and snippets, unused SSH keys and speed history +in the app. In Settings you can separately clear iperf3 results, forget the last host +and port and clear the tool target history; the target field menu clears it too. Remove favourites individually +by unchecking their stars. To remove all local data including settings and archives, clear the app's storage in Android or uninstall it. [D21](data-toky.md#d21), [D17](data-toky.md#d17) diff --git a/docs/publikace-play.md b/docs/publikace-play.md index d8ef985..d35b6f5 100644 --- a/docs/publikace-play.md +++ b/docs/publikace-play.md @@ -1,6 +1,6 @@ # NetKit — publikace na Google Play (fáze 2) -**Stav 2026-10-27:** příprava, nic se neprovádí. Podle D12 přichází Play až po veřejném vydání v1 +**Stav 2026-10-27, doplněno 2026-11-02 (§7):** příprava, nic se neprovádí. Podle D12 přichází Play až po veřejném vydání v1 ([distribuce.md](distribuce.md)) a po výslovném správcově pokynu. Fakta ověřena 2026-10-27; **[P]** = prokázáno zdrojem, **[O]** = odhad. @@ -10,8 +10,8 @@ |---|---|---| | `applicationId` | `cz.netkit.app` | `androidApp/build.gradle.kts` | | minSdk / targetSdk / compileSdk | 29 / **35** / 35 | tamtéž | -| Oprávnění | INTERNET, ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE, CHANGE_WIFI_STATE, FINE a COARSE location, READ_PHONE_STATE, READ_BASIC_PHONE_STATE (M4, mobilní signál obou SIM) | `AndroidManifest.xml` | -| Nepřítomné | `QUERY_ALL_PACKAGES`, `REQUEST_INSTALL_PACKAGES`, foreground service, `NEARBY_WIFI_DEVICES` | tamtéž | +| Oprávnění | INTERNET, ACCESS_NETWORK_STATE, ACCESS_WIFI_STATE, CHANGE_WIFI_STATE, FINE a COARSE location, READ_PHONE_STATE, READ_BASIC_PHONE_STATE (M4, mobilní signál obou SIM); od zadání 42 FOREGROUND_SERVICE, FOREGROUND_SERVICE_SPECIAL_USE, POST_NOTIFICATIONS (služba SSH relací typu `specialUse`) | `AndroidManifest.xml` | +| Nepřítomné | `QUERY_ALL_PACKAGES`, `REQUEST_INSTALL_PACKAGES`, `NEARBY_WIFI_DEVICES` | tamtéž | | Release build | bez `signingConfig`, R8 a flavorů | audit Codex 2026-10-27 | ## 2. Co je potřeba @@ -62,6 +62,12 @@ runtime oprávnění. ICMP dokumentace nezmiňuje, nejistota zůstává. 8. **Doba review:** „až 7 dní, výjimečně déle“ **[P]** ([9859751](https://support.google.com/googleplay/android-developer/answer/9859751)). +**Doplněno zadáním 42 (2026-12-02): služba na popředí `specialUse`.** Play Console → Policy → App content +→ Foreground service permissions: deklarovat `specialUse` s popisem (SSH relace otevřená uživatelem k jeho +serveru, trvalé oznámení s „Odpojit vše“, konec s poslední relací) a obvykle video. Reviewer může typ +odmítnout; mitigace = build pro Play bez služby (limit 5 min jako dřív). `dataSync` není náhrada (limit +6 h / 24 h od targetSdk 35). Zdroje a rozbor: [bezpecnost.md § SSH na pozadí a SFTP](bezpecnost.md). **[O]** + ## 4. Flavory a aktualizace - `play`: bez update-checkeru, bez odkazu na GitHub APK; aktualizace přes Play. Případně in-app @@ -90,7 +96,19 @@ Huawei AppGallery, Samsung Galaxy Store a Amazon Appstore se pro osobní nástroj nevyplatí (další účty, jiný ekosystém) **[O]**, nic z toho se neověřovalo. F-Droid viz [distribuce.md](distribuce.md) §7. -## 7. Otevřené otázky na správce +## 7. Ověření vývojáře i mimo Play (Android developer verification) + +Ověřeno 2026-11-02 ([přehled](https://developer.android.com/developer-verification), [FAQ](https://developer.android.com/developer-verification/guides/faq)). + +- Od 2026-09-30 se instalace na certifikovaných zařízeních s Androidem 7+ kontrolují jen v Brazílii, Indonésii, Singapuru a Thajsku a jen z vyjmenovaných obchodů. **Globálně se kontrola rozšíří v roce 2027 a bude platit i pro APK stažené z webu** **[P]**. Přesné datum pro EU zdroj neuvádí. +- **Účty v Android Developer Console** (pro distribuci jen mimo Play) **[P]**: + - Full Distribution: 25 USD, s ověřením identity. + - Limited Distribution: zdarma, bez dokladu, nejvýš 20 konkrétních zařízení. +- **Účet v Play Console** stačí i pro registraci aplikací distribuovaných mimo Play. K jednomu balíčku jde registrovat víc podpisových klíčů **[P]**. +- **Neregistrovaná aplikace** se dá nainstalovat nebo aktualizovat jen přes ADB, nebo když uživatel jednou nastaví „advanced flow“: vývojářský režim, restart, čekání 24 h, biometrie **[P]**. +- **Dopad na NetKit:** od roku 2027 bude potřeba zaregistrovat `cz.netkit.app` s certifikátem release klíče (`74f395fd…cb8c`), i když Play nebude. Jinak se APK z GitHubu běžným uživatelům nenainstaluje. Registrační poplatek 25 USD je tedy pravděpodobně potřeba tak jako tak. Účet v Play Console pokryje obojí. + +## 8. Otevřené otázky na správce 1. Osobní účet na jméno, nebo organizační přes živnost? Existuje 12 testerů, kteří vydrží 14 dní? 2. Je appka striktně zdarma bez příjmů a reklam (trader/non-trader)? diff --git a/docs/testovani.md b/docs/testovani.md index 0d1a53c..6b59b26 100644 --- a/docs/testovani.md +++ b/docs/testovani.md @@ -428,9 +428,24 @@ tabulce. Žádný takový přesun není telefonní PASS. ## 10. Izolovaný M1 runner na emulátoru `tools/run_m1_checks.py` spouští jednu fázi na explicitním emulátoru: -`ui`, `wifi-denied`, `wifi`, `wifi-freshness`, `lan`, `lan-confirm`, `lan-discovery`, +`ui`, `wifi-denied`, `wifi`, `wifi-freshness`, `wifi-spectrum`, `wifi-extensions`, `lan`, `lan-confirm`, `lan-discovery`, `lan-icmp-rtt`, `ssh`, `ssh-ui`, `ssh-reconnect`, `ssh-rotated`, `ssh-legacy`, `ssh-lifecycle`, -`wol-e2e`, `wol-ime-matrix`. Poslední dvě fáze podléhají rozpočtu R2 v §7. +`wol-e2e`, `wol-ime-matrix`, `wol-widget-intent`, `netstatus-widget`, `cell-detail`. Fáze `wol-e2e` a `wol-ime-matrix` podléhají rozpočtu R2 v §7. +`cell-detail` (zadání 53) jako jediná fáze před instrumentací odebere aplikaci na emulátoru +`READ_PHONE_STATE`, `ACCESS_FINE_LOCATION` a `ACCESS_COARSE_LOCATION` (`pm revoke`, zapsáno v `adb-commands.log`; +odebrání uvnitř instrumentace by zabilo její proces). Fáze ověří rozbalený „Detail buňky“ bez oprávnění +(vysvětlení, obě tlačítka, žádný dotaz), oprávnění udělí přes `UiAutomation`, a na syntetické LTE buňce modemu +emulátoru (skutečné `requestCellInfoUpdate`, žádná podvržená data) pořídí snímky CS a EN; sbalení údaje SIM zahodí. +Po fázi zůstanou oprávnění udělená. +`wol-widget-intent` (zadání 36, revize kola 3) vyžaduje na ploše emulátoru umístěný WoL widget: drží +PendingIntent starého vykreslení pro zařízení A, překreslí widget na B a ověří, že starý intent nepošle nic +a aktuální pošle 3 pakety B (posluchač v testu na vlastní Wi-Fi adrese emulátoru). + +`netstatus-widget` (zadání 37) nepotřebuje umístěný widget: ověří obnovení widgetu stavu sítě (žádný záznam +kontroly polohy v `dumpsys appops`, žádný paket UID aplikace, pod 10 s, nové RSSI/kanál a nezměněné SSID; +obě kontroly mají pozitivní kontrolu) a složí skutečný widget přes Glance pro malý/střední layout a stavy +čerstvé, staré, bez dat, SSID zapnuto/vypnuto a zamčená obrazovka (PNG v `m1-evidence`). Fáze uděluje +aplikaci `ACCESS_FINE_LOCATION` (jen emulátor). Výchozí `m1_provision.py run-all --phases` je přesně `ui,lan,lan-confirm,wifi,wifi-denied,ssh,ssh-ui,ssh-rotated,ssh-legacy,wol-e2e`. @@ -481,7 +496,15 @@ jen s důvodem a markerem `THROTTLED_CONFIRMED`; aktuální instrumentace nemá spolehlivý důkaz throttlingu, proto prázdná data/chyba scanu vedou k FAIL. `wifi-freshness` vykresluje produkční UI nad označenými syntetickými daty (pět stavů stáří/cache, šest grafických stylů a řádek výrobce OUI pod SSID se syntetickým -seznamem a BSSID, od 1.1.0); není důkaz RF scanu ani OEM throttlingu. +seznamem a BSSID, od 1.1.0); není důkaz RF scanu ani OEM throttlingu. `wifi-spectrum` (zadání 34) +vykresluje kartu spektra 2,4 GHz se syntetickými AP na kanálech 1, 13, 13/40 MHz a 6/40 MHz bez středu +a detail AP se „střed neznámý“ (osa 1–14 s okrajem, stín nad 2483,5 MHz); také jen UI. +`wifi-extensions` (zadání 38) vykresluje se syntetickými AP spektrum s připojeným, dvěma připnutými +a jedním připnutým AP mimo sken, detail připnutého AP, regionální poznámku CZ, kartu Sítě seskupenou +podle SSID, kartu záznamu obchůzky (dialog značky, souhrn) a exportuje CSV i JSON přes **skutečný +systémový výběr souboru** (DocumentsUI, tlačítko Uložit); soubor přečte zpět, porovná, zkontroluje +escapování SSID s čárkou, uvozovkami a novým řádkem a smaže ho. Zápis volá stejné +`exportWifiScan` a `writeExportDocument` jako aplikace, ViewModel se neověřuje. Jen UI, ne RF. `lan-icmp-rtt` měří dvacet ICMP odpovědí hostu a uvádí jednotlivé RTT i min/avg/max. `lan-confirm` ověřuje skutečný ViewModel, zamítnutí změněného cíle a sondu až po potvrzení; `lan-discovery` měří 127.0.0.0/24, nikoli fyzickou LAN. `ssh-ui` @@ -612,13 +635,22 @@ Testovací telefon (Android 15, HyperOS), tmavý i světlý režim systému. Vý | M3-08 | Rychlost: Spustit test (zelina). | Ciferník s ryskami, ručička nepřekrývá popisky, hodnota **pod** ciferníkem; fáze latence → stahování → odesílání s linkou průběhu; po testu latence pod zátěží a Průběh. | NOT RUN | | M3-09 | Spektrum: 2,4 a 5 GHz, Zdraví kanálů, klepněte na buňku. | Čipy pásem se vejdou; tečka u pásma připojeného AP; tepelný pás místo seznamu, detail kanálu pod pásem; klepnutí na síť ji rozbalí (BSSID, OUI, Moje AP jen v rozbalení). | NOT RUN | | M3-10 | Spektrum: vyberte jiné pásmo, pak znovu pásmo s tečkou. | Návrat k automatické volbě pásma připojeného AP. | NOT RUN | -| M3-11 | Zařízení: seznam a detail NASu. | Porty jako mřížka „N ze 105“, identifikace jen zjištěné údaje + „Nezjištěno: …“, akce Trasa a SSH. | NOT RUN | +| M3-11 | Zařízení: seznam a detail NASu. | Porty jako mřížka „N ze 110“, identifikace jen zjištěné údaje + „Nezjištěno: …“, akce Trasa a SSH. | NOT RUN | | M3-12 | SSH: profily, klíč, relace s barevným výstupem (`ls --color`). | Terminál JetBrains Mono, tmavý i ve světlém režimu; „Připojit“ funguje jako dřív. | NOT RUN | | M3-13 | WoL: ⋮ → Importovat, vyberte CSV z aplikace Wake On Lan (Mike Webb). | Náhled 9 zařízení, poznámka „Skupina: Frýdek/doma“, případné varování SecureOn; po potvrzení se zařízení probudí a kontrola portu odpovídá nastavení. | NOT RUN | | M3-14 | Nastavení → Displej → Velikost písma na maximum, šířka displeje / zobrazení „větší“. | Nic se neořízne: popisky spodní lišty celé, karty metrik se přepnou na řádky, „Wake-on-LAN“ se neláme uprostřed slova. | NOT RUN | | M3-15 | Vývojářské možnosti → Měřítko animace = vypnuto. | Hodnoty skočí rovnou na cíl, pulz „živě“ ani prstenec WoL neběží, aplikace funguje. | NOT RUN | | M3-16 | Venku na slunci (jas max). | Čitelné hodnoty a stavy ve světlém i tmavém režimu. | NOT RUN | +#### Síťařské nástroje na telefonu ve vlastní síti + +| # | Krok | Očekávání | Výsledek | +|---|---|---|---| +| LAN-35-01 | Přes vlastní PPPoE nebo tunel se známým IPv4 MTU a odpovídajícím cílem zkuste s DF payload `MTU − 28`, poté o bajt více. Spusťte hledání MTU. Porovnejte s trasou, kde se zpráva ICMP frag-needed filtruje. | Na první trase projde hraniční velikost a další sonda ohlásí příliš velký paket. Na druhé trase ukáže měření po opakovaných timeoutech nad potvrzeným payloadem odhad s upozorněním na možnou PMTUD black hole. | NOT RUN | +| LAN-35-02 | Na stejné trase s MTU pod 1500 spusťte sérii pingů s vypnutým DF a payloadem 1472 B. | Při povolené fragmentaci a průchodu fragmentů přichází echo. Při jejich zahození se započítá ztráta a běh pokračuje další sondou. | NOT RUN | +| LAN-35-03 | Na vlastní trase s pěti úvodními filtrovanými hopy a další odpovídající bránou spusťte traceroute. Vyčkejte, klepněte na Pokračovat a při druhém běhu během pauzy na Zastavit. | Po TTL 5 trasa počká. Pokračování přidá TTL 6 ke stejným pěti řádkům. Zastavení ponechá dosavadní hopy. | NOT RUN | +| LAN-35-04 | Na vlastním resolveru porovnejte neexistující doménu, existující jméno bez A/AAAA a řízenou odpověď SERVFAIL. | UI rozliší NXDOMAIN (3), NOERROR bez záznamu a SERVFAIL (2), pokud resolver RCODE předá. Při chybě resolveru bez DNS odpovědi ukáže samostatnou diagnostiku. | NOT RUN | + Doplnění 1.1.0 (výrobce z offline IEEE OUI): | # | Krok | Očekávání | Výsledek | @@ -723,7 +755,8 @@ verzi/commit APK, jazyk, písmo/zobrazení, výsledek a případný screenshot. ## 1.1.0 — dialog aktualizace a limit skenů (2026-11-02) Automatické výsledky a přesné příkazy jsou v interním záznamu. -Fyzické testy provádí Daniel; následující body jsou **NOT RUN**: + +**Orientační test na telefonu 2026-11-02 (správce): PASS.** Vydaná 1.1.0 (APK SHA-256 `5852618b…3031`) je nainstalovaná přes 1.0.x na testovacím telefonu. Vše vypadá dobře a funguje. Jednotlivé kroky níže a OUI-01–04 nebyly potvrzené zvlášť, proto zůstávají **NOT RUN**: - [ ] Testovací telefon (HyperOS): 4 přijaté ruční skeny, postupné ubývání odhadu a obnova po 120 s; při nule tlačítko stále funguje, „asi“ odpovídá odhadu, nikoli příslibu systému. @@ -743,3 +776,460 @@ Fyzické testy provádí Daniel; následující body jsou **NOT RUN**: Start do 60 min používá platnou cache; další návrat z pozadí po 24 h obnoví kartu bez dialogu. - [ ] Přerušit start přechodem do pozadí; start zůstane čekající, úspěšná ruční kontrola ho dokončí. Při posunu hodin zpět je automatická kontrola opět splatná. + +## 15. Zkratky, dlaždice a WoL widget — fyzický checklist (zadání 36) + +Emulátorové ověření a jeho limity jsou v interním reportu 40 (zadání 36). Na telefonu +(HyperOS launcher, testovací telefon) zbývá: + +- [ ] Dlouhý stisk ikony NetKit ukáže zkratky Signál, Spektrum, Ping a Podsítě (kalkulačka) a každá otevře správnou obrazovku. +- [ ] SSH profil → ⋮ → „Přidat na plochu“: HyperOS nabídne připnutí; zkratka otevře potvrzení + připojení a bez „Potvrdit“ se nepřipojí. Totéž pro WoL zařízení (otevře WoL se zvýrazněním). +- [ ] Smazání profilu / zařízení: zkratka na ploše zešedne a klepnutí ukáže hlášku launcheru. +- [ ] Dlaždice „Signál Wi-Fi“ v liště: přidání v editaci lišty, klepnutí otevře Přehled; na zamčené + obrazovce nejdřív odemknutí; dlaždice neukazuje SSID ani jiná data. +- [ ] Widget „Probudit (WoL)“: přidání na plochu otevře výběr zařízení; „Probudit“ probudí PC + v domácí síti; stav „Odesláno HH:MM“; při vypnuté Wi-Fi „Není Wi-Fi“; tmavý režim čitelný. +- [ ] Widget po přejmenování zařízení ukáže nový název; po smazání „Zařízení smazáno, klepněte pro výběr“. +- [ ] Zařízení → detail Windows PC v LAN: „Přidat do WoL“ předvyplní MAC z NetBIOS (porovnat + s `ipconfig /all`); u zařízení s uloženým WoL (`probeHost` = IP) „Probudit (WoL)“ PC probudí. + +## 16. Zadání 38 — Wi-Fi rozšíření: fyzický checklist (2026-12-01) + +Automatické výsledky a emulátorová evidence jsou v interním záznamu. Vše níže **NOT RUN**. +Jen vlastní síť a vlastní AP. + +- [ ] Spektrum: dlouhý stisk slabého AP → hláška „Připnuto do grafu“, AP je v grafu hned za + připojeným i když je nejslabší; v legendě „připnuto“. Přepínač v detailu AP dělá totéž. + Čtvrté připnutí ohlásí limit 3 a nic nevyřadí. +- [ ] Nový sken (ruční i pasivní): připnutí zůstává podle BSSID. Vypnout připnutý AP (nebo odejít + z dosahu) a skenovat: legenda pásma ukáže „SSID · nenalezen v posledním skenu“. Zavření aplikace + (odstranění z posledních) připnutí zruší. +- [ ] Připnutý AP mimo poslední sken: v kartě spektra „Odepnout“ ho odebere a uvolní místo pro další připnutí. +- [ ] „Seskupit podle SSID“ na domácí síti s více AP / pásmy (mesh): řádek skupiny ukazuje počet AP, + pásma s kanály a nejsilnější RSSI; rozbalení ukáže jednotlivá AP. Skryté sítě zůstanou zvlášť. + Filtr SSID a řazení platí, graf ukazuje dál vybrané pásmo. +- [ ] Export skenu: ikona v kartě Sítě → dialog s varováním o identifikátorech sítí → CSV do + Stažených; soubor otevřít v tabulkovém procesoru (LibreOffice / Google Sheets): diakritika, SSID + s čárkou nebo uvozovkami v jedné buňce, RSSI jako číslo. Totéž JSON. Zrušení výběru souboru nic + nevytvoří a nehlásí chybu. +- [ ] Záznam obchůzky v Přehledu: Spustit, projít byt/dům (aspoň jeden roaming mezi AP), přidat + 2 značky (diakritika, 40 znaků je maximum), Zastavit: souhrn sedí (roamingy, nejslabší RSSI, + ztracené pingy brány). Export CSV i JSON, kontrola časů (UTC) a značek. + Odpojit bránu (nebo odejít z dosahu) na pár sekund: každý ztracený ping v souhrnu má v CSV + vzorek s `gateway_lost=true` (timeout se zapíše do následujícího vzorku). +- [ ] Během záznamu přepnout na jinou záložku nebo aplikaci → záznam se zastaví s hláškou + o odchodu z Přehledu; nic neběží na pozadí (žádná notifikace, žádná služba). +- [ ] Zdraví kanálů 2,4 GHz se SIM v síti (CZ): poznámka „Region CZ (EU): kanály 2,4 GHz 1–13“; + výběr kanálu 14 ukáže „není povolen“. V režimu letadlo / bez SIM poznámka chybí. Doporučení + kanálu se nemění. +- [ ] Rotace a tmavý režim: dialog exportu, dialog značky, karta záznamu a skupiny čitelné. + +## 17. iperf3 na loopbacku a v emulátoru + +1. **JVM a vlastní server.** Z kořene repa spusťte + `./gradlew --no-daemon --dependency-verification strict :androidApp:testDebugUnitTest --tests '*Iperf3ClientTest'`. + Běžný přenos testuje Python fixture na dynamickém portu 127.0.0.1. + Upload i reverse trvají 3 s, mají dva streamy a limit 2 Mbit/s na stream. Test porovná souhrn + uploadu s počtem bajtů a časem přijímače. Při Stop očekává fixture CLIENT_TERMINATE. Další testy + pokrývají timeout, EOF, neplatný stav a neúplné údaje po SERVER_ERROR. JVM fixture zkontroluje + CLIENT_TERMINATE při překročení limitu o jediný bajt během reverse i po TEST_END. + Při uploadu se 100 kbit/s očekává celý blok do první sekundy a vrátí souhrn bez end_time, + aby test ověřil přechod na klientské čítače. Testy rámování Python fixture lze spustit přímo + příkazem `python3 -I tools/testsrv/test_iperf3_fixture.py`. +2. **Interop.** Na build-hostu ověřte `command -v iperf3`. Chybějící binárku zaznamenejte jako + NOT RUN. Pokud je přítomná, zaznamenejte verzi a spusťte v samostatném terminálu + `iperf3 -s -B 127.0.0.1 -p 55201`. Test ověří upload, Stop uprostřed uploadu a následný reverse. Poté zopakuje Stop uprostřed reverse + bez limitu s 8 streamy a dokončí nový běh se stejnými 8 streamy. Spusťte + `NETKIT_IPERF3_INTEROP_PORT=55201 ./gradlew --no-daemon --dependency-verification strict :androidApp:testDebugUnitTest --tests '*Iperf3ClientTest.installedServerInterop' --rerun-tasks`. + Na konci ukončete vlastní testovací server. Porovnejte počty streamů, Mbit/s a retransmise s výstupem serveru. +3. **Emulátor.** Použijte vlastní AVD podle [toolchainu §6](toolchain.md), port 5556. + V aplikaci vyberte Přehled → Rychlost → iperf3. Nastavte host `10.0.2.2`, port 55201, + dva streamy, 10 s a limit 2 Mbit/s na stream. Na hostu spusťte + `python3 -I tools/testsrv/iperf3_fixture.py --port 55201` a do 30 s stiskněte Spustit test. + Ověřte graf s jednosekundovými vzorky, výsledek kolem 4 Mbit/s a jediný směr v historii. + Fixture obsluhuje jeden běh. Pro reverse jej spusťte znovu a přepněte směr. V souhrnu reverse + očekávejte tři syntetické retransmise. Uložte graf a souhrn, podle potřeby po posunu obrazovky, + pomocí `adb -s emulator-5556 exec-out screencap -p` do dvou PNG v `artifacts/`. +4. **Potvrzení cíle bez síťové zátěže.** Zadejte dokumentační adresu `192.0.2.1`, stiskněte + Spustit test a v dialogu s IP a portem zvolte Zrušit. Ověřte zastavený test a historii. + Po novém otevření aplikace má formulář obsahovat poslední spuštěný server a port. + +### Fyzický checklist iperf3 (správce, vlastní server) + +- [ ] Spusťte měření postupně přes Wi-Fi, mobilní data a VPN pokrývající aplikaci. Na směrovači nebo serveru podle rozhraní, trasy či zdrojové adresy ověřte, že řídicí spojení i všechny datové streamy používají zvolenou síť. +- [ ] Porovnejte upload i reverse proti skutečnému `iperf3 -s` s údajem `receiver` z iperf3 CLI na stejné trase. Zachovejte směr, počet streamů, délku i limit a zapište obě rychlosti a verzi serveru. +- [ ] Během přenosu stiskněte Stop a spusťte další běh proti stejnému serveru. Ověřte dokončení nového běhu a jediný nový záznam v historii. +- [ ] Na vlastní Wi-Fi spusťte reverse s 8 streamy a prázdným limitem. Ověřte ukončení po zvolené době, výměnu výsledků bez timeoutu a hodnotu stahování v historii. +- [ ] Při výsledku ≥ 1 000 Mbit/s (rychlá Wi-Fi nebo LAN k vlastnímu serveru) ověřte, že dlaždice Latence/Stahování/Odesílání přejdou do sloupce bez oříznutí čísla. Při ~4 Mbit/s (limit 2 × 2 Mbit/s) zůstanou tři vedle sebe. Emulátor dá jen ~480 Mbit/s. +- [ ] LibreSpeed nebo NDT7 na rychlé lince: jakmile se hodnota stahování během fáze odesílání nevejde do řádku, karta přejde do sloupce a do konce běhu se nevrací do řádku (žádné poskakování). U iperf3 dlaždice během běhu ukazují „—“, takže tuto hysterezi neověří. + +## 18. SSH produktivita — snippety, log, `-L`/`-D`, ProxyJump (zadání 41) + +**Emulátor (izolované AVD `netkit-api35`, `emulator-5556`, loopback fixture):** fáze +`ssh-forward` (`-L` echo přes tunel, naslouchání jen 127.0.0.1 ověřené odmítnutím na +externím IPv4, obsazený port → stav *port obsazený*, SOCKS5 IPv4/doména/BIND/odmítnutý +cíl, uvolnění portů po zavření, ProxyJump s TOFU pro každý skok, změněný klíč cíle, +cyklus) a `ssh-snippet-log` (odeslání snippetu z panelu UI, log přes výsledek +`CREATE_DOCUMENT`, čistý text bez escape sekvencí). Spuštění: +`tools/m1_provision.py provision|run-all|cleanup` s `--phases ssh-forward,ssh-snippet-log` +(fixture: echo 18084, druhý SSH 22223, `direct-tcpip` jen na tyto porty). Výsledky a SHA APK: +interní report 45. Emulátor neověří skutečný systémový dialog +výběru souboru (nahrazen monitorem instrumentace), použití proxy jinou aplikací, reálný +jump host ani výkon logu na telefonu — to je níže. + +Pouze správce na fyzickém telefonu, jen vlastní servery. Zapsat verzi/commit APK, jazyk, +výsledek a případný screenshot. + +| # | Krok | Očekávání | Výsledek | +|---|---|---|---| +| SSH41-01 | Snippety: vytvořit globální snippet (s Enter) a snippet jen pro jeden profil (bez Enter); připojit oba profily. | Panel nad klávesami ukazuje globální + vlastní snippety daného profilu; klepnutí pošle text, Enter jen u zapnuté volby; IME ani Ctrl/Alt se nerozbijí. | NOT RUN | +| SSH41-02 | Uložit snippet s textem `snmp-server community …`. | Varování „Vypadá jako heslo“ s volbou Uložit přesto / Zrušit. | NOT RUN | +| SSH41-03 | Menu relace → Zaznamenávat do souboru → upozornění → vybrat soubor v systémovém dialogu (Stažené/NAS přes SAF); spustit pár příkazů, `ls --color`, progress (např. `wget`) a Zastavit záznam. | Soubor má hlavičku a patičku s časem, čistý text bez barev a `^[[`; progress bar jako poslední stav řádku. | NOT RUN | +| SSH41-04 | Log nechat běžet a ukončit relaci (`exit`); v jiném běhu cílový soubor během zápisu smazat. | Konec relace log uzavře s patičkou; chyba zápisu ukáže hlášku, relace běží dál. | NOT RUN | +| SSH41-05 | Profil s `-L 8080 → router:80` (vlastní router); připojit, Kopírovat 127.0.0.1:8080, otevřít v prohlížeči telefonu. | Webové rozhraní routeru přes tunel; po zavření relace adresa nefunguje. | NOT RUN | +| SSH41-06 | Stejný místní port ve dvou profilech, připojit oba. | Druhá relace ukáže *port obsazený*, shell funguje. | NOT RUN | +| SSH41-07 | Profil s `-D 1080`; v aplikaci se SOCKS5 proxy s přihlášením nastavit 127.0.0.1:1080, uživatele `netkit` a heslo zkopírované u relace. Zkusit i špatné heslo a aplikaci bez přihlášení. | Se správným heslem se stránky z vnitřní sítě načtou; špatné heslo nebo klient bez přihlášení je odmítnut. Nové spojení relace má nové heslo. | NOT RUN | +| SSH41-12 | Import souboru, který mění text existujícího snippetu. | Náhled ukáže před → po, Importovat je aktivní až po zaškrtnutí; snippet po importu nemá Enter. | NOT RUN | +| SSH41-08 | ProxyJump: profil bastion + vnitřní server s jump hostem = bastion; první připojení. | Dva dialogy otisku (nejdřív bastion, pak cíl s jeho endpointem); dialog hesla jmenuje skok; shell cíle funguje. | NOT RUN | +| SSH41-09 | Ve vlastní síti změnit klíč vnitřního serveru (nebo zapomenout jen bastion) a připojit znovu. | Změněný klíč cíle → tvrdé varování, žádné přihlášení k cíli; zapomenutý bastion → nové TOFU jen pro bastion. | NOT RUN | +| SSH41-10 | Export profilů se snippety a jump hostem, import do čisté testovací instalace; import PC skriptem s `ProxyJump bastion`. | Jump odkaz i snippety obnoveny; `ProxyJump a,b` nebo `user@host` v PC configu je „Přeskočené (ProxyJump…)“. | NOT RUN | +| SSH41-11 | CS i EN, velké písmo: editor profilu (jump, -L, -D), karta Snippety, stav forwardů, dialog logu. | Vše čitelné, akce dostupné, nic za klávesnicí. | NOT RUN | + +## 19. Zadání 53 — detail mobilní buňky: fyzický checklist (2026-12-01) + +Emulátorová evidence (syntetická LTE buňka, CS/EN, bez oprávnění) je v reportu 58. Vše níže **NOT RUN**. +Testovací telefon, dual SIM; data, která detail ukáže (ID buňky, TAC), nikam nefotit ani nesdílet mimo test. + +- [ ] M53-1 Bez polohy nebo bez oprávnění k telefonu: rozbalit „Detail buňky“ → vysvětlení a tlačítka + „Povolit polohu“ / „Povolit telefon“; systémové dialogy se otevřou až po klepnutí. Po povolení + a návratu do aplikace se detail načte sám. Po trvalém odmítnutí tlačítko „Nastavení aplikace“. +- [ ] M53-2 LTE (SIM 1): obsluhující buňka „LTE · Bx · frekvence“ se štítkem Hlavní; EARFCN, PCI, ECI + s rozpadem eNB, TAC, šířka kanálu, TA (při datech), RSRP/RSRQ/SINR. Porovnat s jinou aplikací + (např. NetMonster / Network Cell Info) nebo servisním menu `*#*#4636#*#*`: pásmo a EARFCN sedí, + RSRP v rozmezí ±3 dB. +- [ ] M53-3 5G NSA: hlavní LTE kotva + sekundární „5G NR · n78 …“ (je-li modem hlásí jako + `SECONDARY_SERVING`); jinak NR v sousedních buňkách. Zapsat, co HyperOS reálně vydá (PCI, NR-ARFCN, + NCI často chybí v NSA). +- [ ] M53-4 5G SA (pokud operátor nabízí): hlavní „5G NR · n…“ s NR-ARFCN, PCI, NCI, TAC, SS-RSRP/RSRQ/SINR; + TA jen na Androidu 14+ při aktivních datech. Pásmo „(odhad)“ jen bez `getBands`. +- [ ] M53-5 Sousední buňky: seřazené od nejsilnější, nejvýš 16, bez duplicit; při chůzi se pořadí mění. +- [ ] M53-6 Druhá SIM (bez dat): vlastní „Detail buňky“ s jejími buňkami (ne kopie SIM 1). +- [ ] M53-7 Obnova a zátěž: detail se mění nejvýš jednou za ~5 s; po sbalení, přechodu na jinou záložku + nebo do pozadí se dotazy zastaví (logcat bez chyb, žádné zahřívání). Rychlé sbalení/rozbalení + nevyvolá častější dotazy. +- [ ] M53-8 Vypnutá služba polohy (oprávnění zůstává): text „Systém nevrátil žádné buňky…“, nic nespadne. +- [ ] M53-9 Jen lokálně: po zavření a novém otevření aplikace je detail sbalený bez starých hodnot; + export / sdílení / diagnostický report (zadání 47) cell ID, TAC ani PCI neobsahují. +- [ ] M53-10 Režim letadlo a hlavní mobilní karta (bez Wi-Fi): detail pod měřidlem i u druhé SIM; v letadle + se řádek „Detail buňky“ neukáže. Rotace a tmavý režim čitelné, TalkBack přečte „Detail buňky, Sbaleno/Rozbaleno“. + +## 20. LAN rozšíření a SecureOn — fyzický checklist (zadání 39) + +Pouze správce na fyzickém telefonu (testovací telefon) ve **vlastní** síti a na vlastních zařízeních. +Zapsat verzi/commit APK, jazyk, síť (IPv4/IPv6 od ISP, router) a výsledek. Emulátor neumí +skutečný DHCP server ani IPv6 od routeru, reálnou SNMP/NTP/DNS infrastrukturu ani SecureOn kartu. + +| # | Krok | Očekávání | Výsledek | +|---|---|---|---| +| L39-01 | Zařízení v síti na /24 s desítkami hostů: rychle posouvat během hledání a po něm. | Plynulý posun; řádek pod prstem neposkakuje, když hledání doplňuje hosty nad ním; detail se otevře na klepnutí. | NOT RUN | +| L39-02 | Rozbalit „Info o síti“ na domácí Wi-Fi (Android 15). | IPv4/prefix, brána, DNS, doména (pokud ji DHCP dává), DHCP server = router, MTU (číslo nebo „neznámé“), IPv6 adresy podle rozsahu, pokud síť IPv6 má. Porovnat s routerem (Winbox, DHCP lease). | NOT RUN | +| L39-03 | Na IPv6 síti: Nástroje → Ping na link-local routeru (`fe80::…%wlan0` z Winboxu) a na globální adresu routeru. | Link-local bez potvrzení, odpovědi; globální adresa v prefixu Wi-Fi bez důvodu „mimo Wi-Fi“ (jen „neprivátní“). | NOT RUN | +| L39-04 | Kontrola portů na IPv6 adresu routeru (22, 80, 443, 8291). | Otevřené porty jako u IPv4; s cizí zónou (`%rmnet0`) chybová hláška, žádný pád. | NOT RUN | +| L39-05 | DNS nástroj na jméno s A i AAAA (vlastní doména nebo router). | Řádky `A` i `AAAA`; na síti bez IPv6 se AAAA i tak zobrazí. Traceroute na IPv6 → hláška „jen IPv4“. | NOT RUN | +| L39-06 | Detail routeru (MikroTik se zapnutým SNMP v2c, vlastní komunita): Identifikovat služby s komunitou. | sysName a sysDescr (RouterOS); NTP stratum/ref, pokud router běží jako NTP server; DNS verze nebo „neuvádí“. Pole komunity je maskované. | NOT RUN | +| L39-07 | Totéž se špatnou komunitou a s prázdným polem. | Špatná → „neodpovídá“ po ≈ 3 s; prázdná → „přeskočeno (bez komunity)“. Po zavření a otevření detailu je pole prázdné (komunita se neukládá). | NOT RUN | +| L39-08 | Identifikovat služby u hosta, který není DNS server a nemá TCP 53. | DNS „přeskočeno …“; žádný dotaz na port 53 (volitelně ověřit Torch na routeru). | NOT RUN | +| L39-09 | WoL zařízení s kartou se SecureOn (pokud je k dispozici): nastavit heslo, probudit z aplikace i z widgetu na ploše. | Karta se probudí; s chybným heslem ne. Bez karty aspoň ověřit sniffrem, že paket má 108 B. | NOT RUN | +| L39-10 | Export WoL JSON i Webb CSV se zařízením se SecureOn; otevřít soubory. | Heslo v souboru není (ani hex); úprava zařízení heslo neukáže, jen „uložené“; odebrání funguje. | NOT RUN | + +## 21. Widget stavu sítě — fyzický checklist (zadání 37) + +Emulátorová evidence je v reportu 41. Na telefonu (HyperOS launcher, testovací telefon) vše **NOT RUN**: + +- [ ] Přidání widgetu „Stav sítě“ otevře nastavení (SSID a veřejná IP vypnuté); bez měření ukáže + „Zatím bez měření / Otevři NetKit pro měření“. Velikost 2×1 i po roztažení na 4×2 čitelná, nic se neořezává. +- [ ] Otevřít Přehled na domácí Wi-Fi, po ≥ 30 s odejít: widget ukáže RSSI, kanál, pásmo, link, + bránu a „Signál před mm:ss“; stáří na ploše běží samo (bez otevření aplikace). +- [ ] Zabít aplikaci (odstranit z posledních / HyperOS „vyčistit“), pak klepnout na ikonu obnovení: + do pár sekund nové RSSI a „Obnoveno před 00:0x“, SSID se nezmění; v liště **nesvítí** indikátor polohy + a Nastavení → Soukromí → Správce oprávnění / historie polohy NetKit neukazuje přístup v tu chvíli. +- [ ] Klepnutí na tělo widgetu otevře Přehled. +- [ ] Doběhnutý speedtest se do widgetu (4×2) propíše s časem. +- [ ] Volba SSID: zapnout v nastavení widgetu (dlouhý stisk → nastavení, pokud HyperOS rekonfiguraci + nabízí), otevřít Přehled → SSID v hlavičce. Pak v systému odebrat NetKitu polohu → při + nejbližším obnovení/otevření SSID zmizí a nevrátí se ani po návratu do Přehledu bez polohy. + Vypnutí volby SSID smaže hned. +- [ ] Volba veřejné IP: zobrazí poslední IP z Přehledu; vypnutí zjišťování v Přehledu ji z widgetu smaže. +- [ ] Restart telefonu: widget po startu ukáže poslední snímek (stáří od měření, ne od restartu); + bez otevření aplikace se nic neměří. Po 24 h bez měření šedý stav „Otevři NetKit pro měření“ + (při nejbližším překreslení, např. klepnutím na obnovení). +- [ ] Tmavý režim: texty i stáří čitelné. Jazyk widgetu odpovídá jazyku aplikace (emulátor: + systém EN, aplikace CS — widget kreslený launcherem byl anglicky, viz report 41). +## 22. Systém a nastavení — jazyk, zpět, Nastavení, displej (zadání 46) + +Emulátor (fáze `system-settings`, CS i EN, `tools/run_m1_checks.py --phase system-settings +--language cs|en`): zpět ze záložek na Přehled, z formuláře WoL, editoru SSH, O aplikaci a licencí, +Nastavení a odchod z Přehledu; Nastavení — motiv (pixel pozadí + soubor), displej během měření, +online dotazy, zapomenutí souhlasů LAN a NDT7, mazání historií a cíle iperf3 proti skutečným +úložištím, karta aktualizací, odkaz z O aplikaci, přepnutí jazyka z UI (aktivita se znovu vytvoří); +`KeepScreenOn` pod produkčním `SettingsHost` (příznak view i `KEEP_SCREEN_ON` okna v `dumpsys`). +Emulátor neověří systémové gesto zpět s animací (test posílá klávesu Zpět), skutečné zhasnutí +displeje po časovém limitu ani systémovou stránku jazyka aplikace na HyperOS. Emulátor +našel a po opravě ověřil češtinu znovu vytvořené aktivity při jazyku aplikace `cs` na systému `en_US` +(generované `values-cs`, `docs/funkce/nastaveni.md`). Výsledky +a SHA APK: interní report 51. + +Pouze správce na fyzickém telefonu (testovací telefon). Zapsat verzi/commit APK, jazyk systému, výsledek. + +| # | Krok | Očekávání | Výsledek | +|---|---|---|---| +| SYS46-01 | Přehled → ⋯ → Nastavení → Jazyk: English; pak Čeština; pak Systém. | Aplikace se přepne hned (krátké znovuvytvoření), Nastavení zůstane otevřené; „Systém“ vrátí jazyk telefonu. | NOT RUN | +| SYS46-02 | Systémové Nastavení → Aplikace → NetKit → Jazyk (nebo tlačítko „Systémové nastavení jazyka“). | NetKit nabízí jen Čeština a English; volba se projeví v aplikaci a v segmentu jazyka v Nastavení. | NOT RUN | +| SYS46-03 | Gesto zpět (tah od okraje) na záložkách Spektrum, Zařízení, SSH, WoL. | Náhled animace zpět, přepne na Přehled; aplikace se nezavře. Na Přehledu gesto ukáže animaci „domů“ a aplikace odejde. | NOT RUN | +| SYS46-04 | Gesto zpět ve formuláři WoL (i s otevřenou klávesnicí), v editoru SSH, v detailu zařízení LAN, v O aplikaci → licence, v Nastavení, v připojeném terminálu SSH. | Vždy zavře jen danou podobrazovku/klávesnici (terminál se zeptá na zavření relace), teprve další zpět jde na Přehled. | NOT RUN | +| SYS46-05 | Nastavení → Motiv: Tmavý, Světlý, Systém; přepnout systémový tmavý režim. | Barvy celé aplikace i ikony stavové a navigační lišty odpovídají volbě; „Systém“ sleduje telefon. Po restartu aplikace zůstane volba bez probliknutí. | NOT RUN | +| SYS46-06 | Displej zapnutý během měření = zapnuto; systémový limit zhasnutí 15 s; spustit rychlostní test (LibreSpeed) a iperf3 na vlastní server, ping s počtem 60, průběžný TCP ping, delší traceroute a kontrolu portů ve vlastní síti, záznam obchůzky, připojený terminál bez psaní. | Displej po celou dobu běhu nezhasne; po skončení/zastavení zhasne podle limitu. | NOT RUN | +| SYS46-07 | Totéž s vypnutou volbou. | Displej zhasne po 15 s a běžící měření skončí (aplikace na pozadí neměří). | NOT RUN | +| SYS46-08 | Nastavení → Automatické hledání v LAN → Zapomenout; otevřít Zařízení ve vlastní Wi-Fi. | Dotaz „Je to vaše síť?“ se zobrazí znovu. | NOT RUN | +| SYS46-09 | Zobrazit znovu u M-Lab (NDT7), pak test NDT7. | Před testem se znovu zobrazí upozornění M-Lab. | NOT RUN | +| SYS46-10 | Smazat historii rychlosti a historii iperf3, zapomenout server iperf3. | Potvrzení s počtem záznamů; v Rychlosti zmizí jen odpovídající záznamy; formulář iperf3 je prázdný. | NOT RUN | +| SYS46-11 | Online dotazy vypnout v Nastavení, vrátit na Přehled. | Karta cesty neukazuje veřejnou IP ani poskytovatele; zapnutí v Nastavení i na kartě je jedna volba. | NOT RUN | +| SYS46-12 | O aplikaci → Aktualizace → Nastavení; Zkontrolovat teď. | Karta aktualizací je v Nastavení a funguje jako dřív. | NOT RUN | +| SYS46-13 | CS i EN, velké písmo (systém 130 %): celé Nastavení. | Segmenty čitelné, texty se nezalamují do nečitelna, tlačítka dostupná. | NOT RUN | +| SYS46-14 | Systémový jazyk telefonu English (jen angličtina); v NetKitu Nastavení → Jazyk: Čeština; pak otočit telefon, odejít na plochu a vrátit se, zavřít NetKit zpět z Přehledu a otevřít znovu. | Celá aplikace zůstane česky ve všech krocích (žádné anglické texty po znovuvytvoření obrazovky). | NOT RUN | +| SYS46-15 | Systémové jazyky Čeština + English (dva jazyky v seznamu), v NetKitu Jazyk: Systém. | NetKit je česky (dřív hrozilo, že druhý jazyk seznamu přebije češtinu). | NOT RUN | +| SYS46-16 | Uložit dva cíle v Nástrojích, jeden označit jako oblíbený. V Nastavení zvolit Vymazat historii cílů, poprvé zrušit a podruhé potvrdit. | Po zrušení oba cíle zůstanou v historii. Po potvrzení je počet nula a oblíbený cíl zůstane i po opětovném otevření Nástrojů. | NOT RUN | +| SYS46-17 | Umístit oba widgety, připojit relaci s názvem shodným s hostem a přepnout jazyk CS ↔ EN při běžící relaci. | Texty widgetů, název a popis kanálu i běžící oznámení včetně akce mají nový jazyk. Místo adresy se zobrazí „Relace 1“ / „Session 1“. | NOT RUN | +## 23. SSH na pozadí a SFTP (zadání 42) a opravy kódu 41 + +**Emulátor (izolované AVD `netkit-api35`, `emulator-5556`, loopback fixture):** + +- `ssh-background` — `POST_NOTIFICATIONS` udělené runnerem (`m1_provision.py` předem smaže + příznaky user-set/user-fixed): služba `SshSessionService` na popředí, oznámení `VISIBILITY_PRIVATE` + s veřejnou verzí bez hostu/uživatele/názvu, aplikace na pozadí 3× déle než zkrácený limit (hook + 3 s místo 5 min), relace žije a odpoví na `netkit-check`, „Odpojit vše“ z lišty (záloha: + `PendingIntent` akce) ukončí relace, službu i oznámení. +- `ssh-background-denied` — oprávnění odebrané: dotaz se objeví při prvním připojení, test ho + odmítne; varování o limitu, žádná služba, po zkráceném limitu na pozadí se relace zavře. +- `ssh-sftp` — `SftpClient` nad skutečnou relací JSch proti SFTP sandboxu fixture (realpath, + `..` normalizace serverem, symlink ven odmítnut, stažení se SHA-256, zrušení, nahrání a zpět, + existující cíl nedotčen, zrušené nahrání uklidí dočasný soubor, publish bez přepsání, přejmenování, + složky, mazání přesné položky včetně `star*.txt`), pak prohlížeč v UI (výpis, odkaz na složku, + nahoru, stažení přes výsledek `CREATE_DOCUMENT`, smazání s potvrzením) se screenshoty. +- `ssh-forwards-panel` — oprava 41: profil s 8× `-L` a `-D`, s otevřenou klávesnicí má terminál + výšku a nekryje ho IME; rozbalení detailů tunelů zavře klávesnici, detaily mají max. 120 dp a vlastní scroll a psaní je znovu sbalí. + +Spuštění: `tools/m1_provision.py provision|run-all|cleanup` s +`--phases ssh-background,ssh-background-denied,ssh-sftp,ssh-forwards-panel`. Výsledky a SHA APK: +interní report 46. Emulátor neověří chování výrobce (HyperOS omezování služeb), +skutečný systémový výběr souboru, OpenSSH server s reálným souborovým systémem ani velké přenosy. + +Pouze správce na fyzickém telefonu (testovací telefon), jen vlastní servery. Zapsat verzi/commit APK, +jazyk, výsledek a případný screenshot. + +| # | Krok | Očekávání | Výsledek | +|---|---|---|---| +| SSH42-01 | Čistá instalace, první připojení k vlastnímu serveru. | Po potvrzení připojení systémový dotaz na oznámení (jen jednou). | NOT RUN | +| SSH42-02 | Povolit oznámení; připojit 2 relace; zamknout telefon, podívat se na zamčenou obrazovku. | Oznámení „2 aktivní relace terminálu“; na zamčené obrazovce jen „NetKit: relace terminálu běží“, žádný host/IP/uživatel. | NOT RUN | +| SSH42-03 | Relace otevřená, aplikace na pozadí **≥ 15 min** (displej zhasnutý, telefon na baterii, bez nabíječky); pak zpět. | Relace stále připojená, příkaz projde. Zapsat, zda HyperOS službu neukončil (případně nastavení baterie „Bez omezení“). | NOT RUN | +| SSH42-04 | V oznámení klepnout na text; jindy na „Odpojit vše“. | Text otevře záložku SSH (nic nespustí); „Odpojit vše“ zavře relace a oznámení zmizí. | NOT RUN | +| SSH42-05 | Zamítnout oznámení (nastavení aplikace), připojit, aplikace na pozadí > 5 min. | Nad terminálem varování o 5min limitu s tlačítkem do nastavení; po 5 min na pozadí relace zavřená. | NOT RUN | +| SSH42-06 | Zavřít aplikaci z přehledu posledních s otevřenou relací. | Relace i oznámení skončí (známé omezení). | NOT RUN | +| SSH42-07 | SFTP na vlastní server (OpenSSH): menu relace → Soubory; procházet, symlink na složku, o úroveň výš až do `/`. | Cesta se mění podle serveru, odkazy označené, `/` je konec. | NOT RUN | +| SSH42-08 | Stáhnout soubor ~100 MB do Stažené a na NAS přes SAF; během stahování přepnout do jiné aplikace. | Průběh, dokončení i na pozadí, kontrolní součet souhlasí (`sha256sum` na serveru vs. telefon). | NOT RUN | +| SSH42-09 | Nahrát soubor; nahrát znovu stejný název; nahrávání zrušit uprostřed. | 1. projde; 2. „Položka s tímto názvem už existuje“, původní soubor beze změny; 3. na serveru nezůstane `.netkit-upload-*.part` ani částečný soubor. | NOT RUN | +| SSH42-10 | Přejmenovat soubor na existující název; vytvořit složku, smazat neprázdnou a prázdnou složku. | Přejmenování odmítnuto bez přepsání; neprázdná složka chyba, prázdná smazána (vždy s potvrzením). | NOT RUN | +| SSH42-11 | SFTP na MikroTik RouterOS (vlastní) a případně vlastní NAS. | Výpis a stažení fungují; pokud server nenabízí hardlink a nabízí posix-rename, nahrání hlásí „nepodporováno“ (zapsat, který server). | NOT RUN | +| SSH42-12 | CS i EN, velké písmo: prohlížeč, dialogy, oznámení. | Čitelné, nic za klávesnicí. | NOT RUN | +| SSH41-13 | Oprava 41: profil s 8× `-L` a `-D`, připojit, otevřít klávesnici. | Nad terminálem jen řádek „9 tunelů“; terminál viditelný; rozbalení ukáže detaily ve scrollovatelném panelu; varování „SOCKS bez přihlášení“ viditelné i sbalené. | NOT RUN | +| SSH41-14 | Oprava 41: log relace do cloudového poskytovatele (např. Disk Google) bez sítě. | Do ~15 s hláška o chybě zápisu, nový log lze spustit. | NOT RUN | +## 24. Terminál xterm-256color (zadání 43) + +**Automaticky (JVM, `commonTest`):** `TerminalXtermTest` — SGR 16/256/truecolor (i `38:2::r:g:b`), +atributy, alternativní obrazovka `?47`/`?1047`/`?1049` s obnovou kurzoru a atributů, DECSTBM +a DECOM, IL/DL/ICH/DCH/ECH, široké a kombinující znaky, resize, DEC Special Graphics, titulek +OSC 0/2, bracketed paste, limit sekvence 256 znaků, fuzz (náhodné znaky, osamocené surrogate, +změny velikosti) a propustnost 10 MB (řádek `TERMINAL_THROUGHPUT` ve výstupu testu). + +**Emulátor:** fáze `ssh-xterm` (`tools/m1_provision.py run-all --phases ssh-xterm`): skutečná +relace přes UI a JSch proti loopback fixture; příkazy fixture `netkit-xterm-colors`, +`netkit-xterm-alt` a `netkit-xterm-main` posílají předpřipravené bajty (ekvivalent `printf`, +fixture nic nespouští). Ověří se snímek bufferu buňku po buňce (256 pozadí, truecolor, atributy), +alternativní obrazovka s titulkem, čárovou grafikou, scroll regionem a širokými znaky, titulek +v hlavičce a návrat primární obrazovky; snímky `ssh-xterm-colors.png`, `ssh-xterm-alt.png`, +`ssh-xterm-main.png`. Emulátor neověří skutečné aplikace (`vim`, `htop`, `mc`, `tmux`), čitelnost +na displeji telefonu ani výkon dlouhého výpisu na telefonu — to je níže. + +Pouze správce na fyzickém telefonu, jen vlastní servery. Zapsat verzi APK, jazyk, +výsledek a případný screenshot. + +| # | Krok | Očekávání | Výsledek | +|---|---|---|---| +| SSH43-01 | Na vlastním serveru `echo $TERM`, `tput colors`; skript s `printf '\e[48;5;%dm ' {0..255}` a řádkem truecolor (`printf '\e[38;2;255;100;0mTRUE\e[0m'`). | `xterm-256color`, `256`; mřížka 256 barev bez posunu, truecolor oranžová. | NOT RUN | +| SSH43-02 | `vim` (syntax on, `:split`, `:q`), `less` dlouhého souboru, `man ls`. | Celoobrazovkový režim bez zbytků; po ukončení se vrátí původní výpis a prompt; PgUp/PgDn a šipky fungují. | NOT RUN | +| SSH43-03 | `htop` a `mc` (F1–F12 z lišty Další klávesy, rámečky). | Rámečky jsou souvislé čáry (ne písmena `q`/`x`), barvy sedí, F-klávesy reagují. | NOT RUN | +| SSH43-04 | `tmux` se dvěma panely pod sebou, v jednom `top`, ve druhém psát; `printf '\e]2;test-titulek\a'`. | Panely se nepřepisují (scroll region); titulek je v hlavičce terminálu za názvem profilu v uvozovkách. | NOT RUN | +| SSH43-05 | `echo $'čeština 中文 😀 é'`, ve `vim` vložit široké znaky a mazat je. | Široké znaky zabírají dvě buňky, kurzor a mazání nesedí mimo; diakritika se neztratí. | NOT RUN | +| SSH43-06 | V běžícím `vim`/`htop` otočit telefon a otevřít/zavřít klávesnici. | Obsah se překreslí na nový rozměr (window-change), nic nezamrzne. | NOT RUN | +| SSH43-07 | V bash 5+ (bracketed paste zapnutý) vložit přes menu Vložit `echo a; echo b` a odeslat záložním polem. | Text se objeví na řádku a nespustí se do stisku Enter; víceřádkový text se dál potvrzuje a nové řádky se nahradí mezerou. | NOT RUN | +| SSH43-08 | Velikost písma (menu ⋮ menší/větší) v `htop`. | Mřížka (sloupce × řádky v hlavičce) se přepočítá a `htop` se překreslí. | NOT RUN | +| SSH43-09 | `seq 1 2000000` nebo `cat` souboru ~10 MB; během výpisu posouvat a Ctrl+C. | Aplikace reaguje, Ctrl+C výpis zastaví, historie nejvýše 5000 řádků. | NOT RUN | +| SSH43-10 | Světlý i tmavý režim aplikace, CS i EN. | Terminál zůstává tmavý a čitelný (paleta s kontrastem), lišta kláves čitelná. | NOT RUN | + +## 25. Telnet a USB-OTG — fyzický checklist (zadání 44) + +JVM test `TelnetConsoleWireTest.loopbackFixture` spouští stdlib fixture na 127.0.0.1 s efemérním portem. +Stejnou výměnu lze v sandboxu pustit přes roury testem `pipeFixture`. `UsbConsoleWireTest` používá falešný +port. Elektrické chování převodníků a systémový dialog USB patří na telefon. + +| Kontrola na vlastním zařízení | Očekávaný výsledek | Stav | +|---|---|---| +| Telnet, dvě uložené konfigurace, reconnect, následná změna hostu/portu | Varování se potlačí jen pro potvrzený profil na původním cíli. Heslo zadat až při výzvě protistrany. | NOT RUN | +| USB OTG, postupně FTDI / CP210x / CH34x / PL2303 / CDC-ACM, také víceportový adaptér | Správný port, zamítnutí oprávnění zavře pokus, nové připojení s povolením umožní číst i psát. | NOT RUN | +| Oba presety na odpovídající konzoli, parita, stop bity, RTS/CTS na podporovaném a nepodporovaném adaptéru | Čitelný obousměrný přenos, nepodporovaná konfigurace otevření odmítne. | NOT RUN | +| BREAK na izolované testovací lince s analyzátorem nebo druhým adaptérem | Viditelný přibližně 250ms impuls, linka se uvolní a opět přenáší data. | NOT RUN | +| Vytáhnout kabel během čtení i zápisu a opět připojit | Relace skončí čistě jako konec spojení (EOF), bez chybového banneru „Chyba USB“ — i při psaní (oprava P3 při integraci 2.0); záložka zachová výstup. Nový pokus znovu vybírá zařízení. | NOT RUN | +| Souvislý výpis ze zařízení při 115200 Bd a 921600 Bd, postupně FTDI a CP210x (např. `show running-config` / `export verbose` / `dmesg` ≥ 100 kB, nebo generátor znaků na druhém adaptéru) | Výpis je úplný a bez ztracených či zdvojených znaků (porovnat se zdrojem, např. kontrolním součtem); riziko ztráty dat u `bulkTransfer` s časovým limitem. | NOT RUN | +| Souběžně SSH, Telnet, USB; přepnout na pozadí s povoleným a zamítnutým oznámením | Společný počet relací, „Odpojit vše“ zavře všechny transporty. Bez služby se uplatní limit 5 minut. | NOT RUN | +## 26. TalkBack při měření — fyzický checklist (zadání 49) + +Všechny fyzické kroky pro testovací telefon mají stav **NOT RUN**. Vyzkoušet s TalkBack v CS i EN, +ve světlém i tmavém motivu a se zvětšeným písmem. Síťové testy směřovat na vlastní zařízení. + +- [ ] V Přehledu a v Nástrojích přejít gestem po nadpisech mezi pojmenovanými kartami. Ověřit, že gesto přeskočí datové řádky DNS, Web/TLS a RDAP. Akci v záhlaví zaměřit a aktivovat samostatně. +- [ ] Spustit konečný ping, traceroute, DNS a sken portů. Počkat na dokončení i při čtení výsledků níže v seznamu. Porovnat oznámené počty a průměr s obrazovkou. Zkusit také ping bez odpovědi a zrušený běh. +- [ ] Ve skenu zařízení porovnat oznámený počet s počtem ve štítku, včetně telefonu a ponechaných starších položek. Vyzkoušet ping a sken portů v detailu zařízení. Zaměřit chybový banner. +- [ ] U rychlostního testu a iperf3 (běžný i reverzní směr) ověřit, že se ozve dokončení s hodnotou každého měřeného směru. Zkontrolovat nulu a chybějící směr, pokud nastanou. +- [ ] Zaměřit graf signálu, rychlosti a spektra. Posunout okno rozbaleného grafu a porovnat jeho krajní hodnoty. U spektra porovnat nejsilnější AP v pásmu při připnutí slabší sítě. +- [ ] Zkontrolovat přepínače, sousední kanály v pásu zdraví a tlačítka rozbaleného grafu. V pásmu 2,4 GHz vybrat sousední kanál gestem TalkBack a dvojklepem. Po vypnutí TalkBack vyzkoušet výběr tažením v celém pásu bez posunu. U širšího pásma, které přesahuje displej, vybrat kanál i po vodorovném posunu. Zkontrolovat čitelnost popisků os. + +Emulátorová fáze `accessibility` přepíná jazyk pouze uvnitř testovací kompozice. Ověřuje uzly +Compose ve stromu přístupnosti Androidu. Runner stáhne 12 PNG (šest scén v každém jazyce) +do adresáře zadaného přes `--output-dir`. Poslech skutečného hlasového výstupu patří k fyzickému checklistu. + +## 27. Adaptivní navigace a Wi-Fi 7 MLO (zadání 52) + +Fáze `landscape-mlo` vyžaduje izolovaný emulátor API 35 s běžící M1 SSH fixture a oběma debug APK odpovídajícími ověřovanému commitu. Na build-hostu pod stávajícím zámkem `/tmp/netkit-emu.lock` ji spusť pro každý jazyk s vlastním run ID a cílovým adresářem. Ověřené snímky se z privátního úložiště aplikace kopírují do `--output-dir`. + +```bash +( +set -e +for lang in cs en; do + run_id=$(python3 -I -c 'import uuid; print(uuid.uuid4().hex)') + python3 -I tools/run_m1_checks.py --adb "$ANDROID_HOME/platform-tools/adb" --serial emulator-5556 \ + --phase landscape-mlo --language "$lang" --run-id "$run_id" --git-sha "$(git rev-parse HEAD)" \ + --output-dir "artifacts/landscape-mlo/$lang-$run_id" +done +) +``` + +Na emulátoru zkontroluj 13 PNG pro každý jazyk. Portrét telefonu má spodní navigaci. Telefon na šířku i tablet mají postranní navigaci a dostupných všech pět cílů. Snímek terminálu používá připojenou SSH fixture. MLO snímek vykresluje produkční kartu se dvěma syntetickými linkami. Fáze obnovuje původní přepis rozlišení, zámek otáčení a jazyk aplikace. + +**Fyzický checklist pro správce (testovací telefon)** + +- [ ] Otočit telefon ve všech pěti cílech v CS a EN. Zkontrolovat zachování výběru, čitelnost popisků a dostupnost poslední položky postranní navigace. +- [ ] Během SSH relace otočit telefon, otevřít a zavřít IME, porovnat `stty size` na vlastním hostu s rozměry v titulku. Přes nabídku zobrazit klávesy a přejít na Profily. Připojení musí zůstat použitelné. +- [ ] Na vlastním MLO AP porovnat s řadičem ID linek, pásma, kanály a jejich stav. Zkontrolovat RSSI po jednotlivých linkách a šířku proti čerstvému výsledku skenu. Při chybějícím výsledku má být u šířky pomlčka. +- [ ] Odebrat přesnou polohu, potom samostatně vypnout systémovou polohu. Po návratu do Přehledu musí zmizet AP MLD i šířka. Po obnovení ověřit návrat dostupných údajů. +- [ ] Přepnout na AP bez MLO a odpojit Wi-Fi. Karta předchozího spojení musí zmizet. Zapsat model AP, verzi Androidu a rozdíly proti řadiči. + +## 28. Sdílení výsledků — fyzický checklist (zadání 47) + +Emulátorová evidence (fáze `share-results`) je v reportu 52. Na telefonu (testovací telefon) vše **NOT RUN**: + +- [ ] Přehled → ⋮ → Diagnostický report: přepínače SSID/BSSID/veřejná IP vypnuté; náhled bez SSID, + BSSID, veřejné IP a bez globální IPv6 telefonu (domácí síť s IPv6 od ISP). Zapnutí „Zahrnout + veřejnou IP“ je doplní. +- [ ] Sdílet → např. Gmail/Telegram: dorazí stejný text jako v náhledu; Uložit → soubor `.txt` i `.json` + ve Stažených (HyperOS výběr souborů), obsah sedí. +- [ ] Na mobilních datech (Wi-Fi vypnutá): report bez sekce Wi-Fi a bez brány; s VPN nad Wi-Fi se + IPv4 aktivní sítě nebere z Wi-Fi. +- [ ] Report neobsahuje nic z „Detailu buňky“ (ECI/TAC/PCI/EARFCN), ani když je detail rozbalený. +- [ ] Dlouhý stisk IPv4, Brány, DNS, BSSID, uzlu veřejné IP a AP (kanál): HyperOS ukáže potvrzení + schránky; u BSSID a veřejné IP náhled skrytý (tečky); vložení do jiné aplikace funguje. +- [ ] Zařízení → ikona stažení → varování → CSV/JSON/TXT do Stažených; CSV otevřít v tabulce (žádný vzorec). +- [ ] Rychlost: po doběhnutém LibreSpeed/NDT7 i iperf3 „Sdílet výsledek“ → SSID výchozí vypnuté, + zapnutí přidá řádek SSID; text dorazí do zvolené aplikace. +- [ ] CS i EN (jazyk aplikace): texty dialogů a popisky reportu přeložené. + +## 29. Cíle nástrojů, TCP ping, MAC → výrobce — fyzický checklist (zadání 48) + +Pouze správce na fyzickém telefonu (testovací telefon) ve **vlastní** síti a na vlastních zařízeních. +Emulátor (fáze `tools-targets`) ověřil UI v CS/EN, TCP ping na loopback a tabulku MAC se +syntetickými daty; neověřil reálnou Wi-Fi, mobilní data ani skutečné výpisy prvků. + +| # | Krok | Očekávání | Výsledek | +|---|---|---|---| +| T48-01 | Ping na bránu, pak Traceroute, Porty a TCP ping: otevřít ikonu hodin u pole cíle. | Brána je v „Naposledy použité“ ve všech čtyřech; Web/TLS ji nenabízí, RDAP jen veřejné IP/ASN. | NOT RUN | +| T48-02 | Přidat bránu k oblíbeným s popiskem, zavřít a znovu spustit aplikaci. | Oblíbená s popiskem zůstává nahoře; „Vymazat historii“ smaže jen naposledy použité. | NOT RUN | +| T48-03 | Web/TLS na URL s `?token=…`, pak otevřít historii. | V historii je URL bez query; po výslovném přidání k oblíbeným zůstane celá URL. | NOT RUN | +| T48-04 | TCP ping na router port 8291 (Winbox) a 443 na veřejný web, počet 10, na Wi-Fi i mobilních datech. | ≈1 vzorek/s, min/avg/max/jitter odpovídají PC (`tcping`/`hping3 -S`), štítek sítě odpovídá; veřejný cíl vyžádá potvrzení. | NOT RUN | +| T48-05 | TCP ping na zavřený port routeru a na firewallem zahazovaný port. | Zavřený: „odmítnuto“ (RST) jako ztráta; zahazovaný: „vypršelo“ po časovém limitu; Zastavit ukončí běh hned. | NOT RUN | +| T48-06 | Na routeru firewall log / Torch během TCP pingu s počtem 5. | Vždy nejvýše jedno spojení naráz, 5 SYN celkem, nic po Zastavit. | NOT RUN | +| T48-07 | Vložit skutečný výpis `/interface bridge host print` (MikroTik) a `show mac address-table` (Cisco/Huawei, pokud je k dispozici). | Všechny MAC z výpisu, výrobce u známých OUI, telefony s náhodnou MAC jako „lokální“, multicast označený; export CSV otevřít v tabulkovém editoru. | NOT RUN | +| T48-08 | Vložit text větší než 64 KiB nebo s více než 2000 řádky. | Hláška o limitu, žádné zamrznutí UI. | NOT RUN | + +## 30. Zámek SSH a skupiny profilů (zadání 50) + +Fáze `ssh-lock` runneru M1 vyžaduje AVD API 35 s již nastaveným zámkem obrazovky. Ověřuje vstup zkratkou, zrušení skutečné systémové výzvy, odepřené akce, hledání a řazení. Ukládá snímky zámku, výsledku hledání a řazení v CS i EN. Pro následný průchod aplikací instrumentace simuluje úspěšný výsledek ověření. Následující kroky ověří systémový dialog a transporty na zařízení. + +| Krok pro správce | Očekávaný výsledek | Stav | +|---|---|---| +| Zapnout Zámek SSH, potvrdit otiskem. Poté zopakovat odemčení přes PIN a se zrušením výzvy. | Úspěch otevře SSH. Zrušení uchová zámek. Správa klíčů i přepnutí zámku jsou chráněné. | NOT RUN | +| Nastavit 0 minut. Vyzkoušet SSH včetně zkratky, Telnet, USB konzoli a návrat přes oznámení relace. | Každé připojení vyžádá ověření. Zkratka navíc vyžádá potvrzení cíle. | NOT RUN | +| Nastavit 1 minutu. Překročit limit s otevřeným terminálem a znovu během výběru cíle exportu nebo přenosu SFTP. | Obsah se skryje. Další akce a zápis exportu vyžádají odemčení. Autorizovaný přenos může doběhnout. | NOT RUN | +| Otevřít správu klíčů a detail SOCKS5. Vyzkoušet kopírování po vypršení, rotaci v dialogu a opětovné spuštění aplikace po zániku procesu. | Citlivé údaje jsou přístupné až po ověření. Rotace nebo zrušení promptu samy neudělí přístup. | NOT RUN | +| Přiřadit stejnou skupinu SSH, Telnet a USB profilu. Hledat podle hostu, uživatele a skupiny. Přesunout dva řádky při aktivním filtru, úspěšně se připojit a změnit řazení. | Ruční pořadí i poslední použití přežijí restart. Export/import v2 přenese skupinu SSH profilu. | NOT RUN | + +## 31. Konfigurační záloha (zadání 51) + +Správce na testovacím telefonu s vlastní testovací konfigurací: + +- [ ] V CS i EN otevřít Nastavení → Záloha. Ověřit biometrickou bránu včetně expirace při návratu ze SAF. +- [ ] Vytvořit šifrovanou zálohu přes systémový výběr souboru, vyzkoušet zrušení dialogu, nesprávné heslo a následně správné heslo. +- [ ] Vyzkoušet varování před čitelným exportem. Zkontrolovat sekce, příznak SecureOn a absenci lokálních referencí, hesel, komunit a privátních klíčů. +- [ ] Ověřit náhled na druhé testovací instalaci, volbu jednotlivých sekcí a zrušení bez zápisu. U důvěry zkontrolovat otisk nezávisle. +- [ ] Potvrdit obnovu, znovu otevřít aplikaci a ověřit skupiny, terminály, snippety, forwardy, místní historii, servery, motiv, jazyk a displej. Zopakovat s jedinou vybranou sekcí. +- [ ] Ověřit odmítnutí konfliktního otisku a zabezpečení SOCKS. U obnovené WoL karty vyžadující SecureOn ověřit aplikaci i widget před a po novém zadání hesla. +- [ ] Zkusit nedostupný dokument a poškozený JSON. U probíhající terminálové relace ověřit blokování potvrzení a zachování relace. +- [ ] Otočit telefon hned po „Vytvořit zálohu“ (během odvození klíče): výběr souboru se otevře jednou a bez pádu (revize 51, kolo 1). + +## 2.0.0 — souhrnný fyzický test vydaného APK (D30, 2026-12-02) + +2.0.0 vychází bez předchozího fyzického testu (D30). Správce testuje oficiální podepsané APK +z GitHub Releases na testovacím telefonu (HyperOS, Android 15), jen ve vlastní síti a na vlastních +zařízeních. Nález řeší opravná verze 2.0.x. Emulátorové a automatické výsledky jsou v interním +záznamu. Podrobné kroky jsou v odkazovaných oddílech; zde jen pořadí a minimum. Vše **NOT RUN**. + +**Instalace a vydání** + +- [ ] Na telefonu s 1.1.0: startovní dialog nabídne 2.0.0 s českou i anglickou poznámkou; + „Stáhnout“ otevře ověřenou stránku (dosud otevřený bod oddílu 1.1.0). +- [ ] APK nainstalovat přes 1.1.0 (stejný podpisový certifikát, viz `docs/distribuce.md` §2); + WoL zařízení, SSH profily, uložená hesla a klíče i historie rychlosti zůstanou. +- [ ] O aplikaci ukazuje verzi 2.0.0 (20000); Licence open source obsahují položku Unicode + Character Database s plným zněním Unicode License V3 (D32) a NOTICE s její atribucí. + +**Nejdřív to, co emulátor neověří (HyperOS, pozadí, hardware)** + +- [ ] Zkratky, dlaždice Signál Wi-Fi a WoL widget: §15. +- [ ] Widget stavu sítě: §21. +- [ ] SSH na pozadí, oznámení, odpojení všech relací a SFTP: §23. +- [ ] Telnet a USB-OTG konzole (vlastní převodník): §25. +- [ ] Zámek SSH s otiskem a PIN, skupiny profilů: §30. +- [ ] Konfigurační záloha a obnova: §31. +- [ ] Detail mobilní buňky (dual SIM, nic nesdílet): §19. + +**Funkce s reálnou sítí** + +- [ ] Wi-Fi rozšíření (připnutí, skupiny SSID, export, obchůzka): §16; MLO a adaptivní navigace: §27. +- [ ] LAN rozšíření, info o síti, SecureOn: §20; cíle nástrojů, TCP ping, výrobce podle MAC: §29. +- [ ] iperf3 proti vlastnímu serveru: §17 (fyzický checklist iperf3). +- [ ] SSH produktivita (snippety, log, `-L`/`-D`, ProxyJump): §18; terminál xterm-256color: §24. +- [ ] Systém a nastavení (jazyk, Zpět, displej, mazání historií): §22. +- [ ] Sdílení výsledků a diagnostický report (veřejné adresy jen s volbou): §28. +- [ ] TalkBack při měření: §26. + +**Zápis.** Ke každému bodu verze, SHA-256 instalovaného APK (z `SHA256SUMS` releasu) a PASS / FAIL; +FAIL s krokem a snímkem bez identifikátorů sítě (SSID, BSSID, veřejná IP, ID buňky). diff --git a/docs/zavislosti.md b/docs/zavislosti.md index 52edfcd..aa6e3d1 100644 --- a/docs/zavislosti.md +++ b/docs/zavislosti.md @@ -9,6 +9,8 @@ jednotlivého licenčního ověření není tvrzení o novém sestavení celého - Závislosti jen s permisivní licencí (Apache-2.0, MIT, BSD-2/3). Copyleft (GPL, LGPL, AGPL, MPL a obdobné licence) vyžaduje výslovné rozhodnutí správce; do té doby nepřidávat. + Výjimka D32 (2026-12-02): data Unicode, tj. jen tabulka šířek znaků odvozená z UCD pod + Unicode License V3 (§15). - Evidovat každou **přímou** závislost v §2 s verzí, licencí z POM / LICENSE, veřejným zdrojem a datem ověření. Odkaz na poznámky k vydání sám o sobě licenci nedokládá. - Po přidání závislosti zkontrolovat celý vyřešený strom včetně tranzitivních knihoven, @@ -31,6 +33,8 @@ a původní Gradle grafy v lokálním logu `artifacts/review-fixes/dependency-gr | Přímá závislost / plugin | Verze | Licence | Oficiální POM / LICENSE | Modul / účel | Přidal | |---|---:|---|---|---|---| +| `androidx.biometric:biometric` | 1.1.0 | Apache-2.0 | [POM Google Maven](https://dl.google.com/dl/android/maven2/androidx/biometric/biometric/1.1.0/biometric-1.1.0.pom), [metadata verzí](https://dl.google.com/android/maven2/androidx/biometric/biometric/maven-metadata.xml), [poznámky k vydání](https://developer.android.com/jetpack/androidx/releases/biometric) | Android, systémový zámek SSH (zadání 50) | 2026-12-02: nejnovější stabilní v `maven-metadata.xml`, licence z POM; detail v §18 | +| `androidx.fragment:fragment` | 1.8.9 | Apache-2.0 | [POM Google Maven](https://dl.google.com/dl/android/maven2/androidx/fragment/fragment/1.8.9/fragment-1.8.9.pom), [metadata verzí](https://dl.google.com/android/maven2/androidx/fragment/fragment/maven-metadata.xml) | Android, `FragmentActivity` pro `BiometricPrompt`; připnutí nad tranzitivní 1.2.5 | 2026-12-02, build-host; detail v §18 | | Gradle Wrapper | 8.11.1 | Apache-2.0 | [Gradle 8.11.1](https://docs.gradle.org/8.11.1/release-notes.html), [kompatibilita Javy](https://docs.gradle.org/8.11.1/userguide/compatibility.html#java), [licence Gradlu](https://github.com/gradle/gradle/blob/v8.11.1/LICENSE) | sestavení projektu | Codex, fáze A | | Android Gradle Plugin (`com.android.application`, `com.android.library`) | 8.9.2 | Apache-2.0 | [POM Google Maven](https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/8.9.2/gradle-8.9.2.pom), [kompatibilita AGP](https://developer.android.com/build/releases/about-agp) | sestavení Android aplikace a sdílené knihovny | Codex, fáze A | | Kotlin Android plugin (`org.jetbrains.kotlin.android`) | 2.2.20 | Apache-2.0 | [POM Maven Central](https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-gradle-plugin/2.2.20/kotlin-gradle-plugin-2.2.20.pom), [licence Kotlinu](https://github.com/JetBrains/kotlin/blob/v2.2.20/license/README.md) | Kotlin v `androidApp` | Codex, fáze A | @@ -647,3 +651,280 @@ Pravidla: NFKC, odstranění řídicích a neviditelných znaků (tabulátor, ze nejvýše 120 znaků; záznamy „Private“ a MA-L bloky „IEEE Registration Authority“ (kontejnery MA-M/MA-S) se vynechávají; prefix uvedený vícekrát (historická data IEEE) nese všechny různé názvy seřazené a spojené ` / `. Výstup je seřazený a deterministický; první řádek je komentář s datem a počty. + +### IPv4 ping s DF (ověřeno 2026-12-01) + +Android SDK poskytuje `Os.setsockoptInt`. Pro ICMP datagramový socket používáme úroveň +`IPPROTO_IP`, volbu `IP_MTU_DISCOVER = 10` a podle přepínače DF hodnotu `IP_PMTUDISC_DO = 2` (zapnuto) +nebo `IP_PMTUDISC_DONT = 0` (vypnuto, lze fragmentovat). Hodnoty +odpovídají také souboru `usr/include/linux/in.h` v lokálním Android NDK. Schopnost +nastavit DF ověřuje aplikace lokálně otevřením socketu bez odeslání paketu. +[Android Os](https://developer.android.com/reference/android/system/Os#setsockoptInt(java.io.FileDescriptor,int,int,int)), +[Linux UAPI in.h](https://github.com/torvalds/linux/blob/master/include/uapi/linux/in.h). + +### LAN rozšíření: IPv6, Info o síti, UDP sondy (zadání 39, ověřeno 2026-12-01) + +Žádná nová knihovna ani verze. Použitá Android API (minSdk 29): + +| API | Zdroj a poznámka | +|---|---| +| `OsConstants.IPPROTO_ICMPV6`, `AF_INET6`, `SOCK_DGRAM` | [OsConstants](https://developer.android.com/reference/android/system/OsConstants) (stránka konstantu uvádí; úroveň API v přehledu stránky nebyla ve staženém úseku, lint s minSdk 29 nehlásí NewApi). Neprivilegovaný ICMPv6 „ping“ socket ověřen na emulátoru API 35 (fáze `lan-v39`, ping `::1` a vlastní link-local). | +| `LinkProperties.getDhcpServerAddress()` | [LinkProperties](https://developer.android.com/reference/android/net/LinkProperties#getDhcpServerAddress()) — „Added in API level 30“; na API 29 karta ukazuje „nedostupné“. | +| `LinkProperties.getMtu()`, `getDomains()`, `getDnsServers()`, `getLinkAddresses()`, `getRoutes()` | [LinkProperties](https://developer.android.com/reference/android/net/LinkProperties); `getMtu` = „non-default MTU“, 0 = nenastaveno. | +| `DnsResolver.query(Network, String, int nsType, int flags, …)` s `TYPE_A` / `TYPE_AAAA` | [DnsResolver](https://developer.android.com/reference/android/net/DnsResolver) (API 29, stejně jako stávající netypový dotaz). | +| `Os.if_nametoindex`, `Inet6Address.getByAddress(String, byte[], int)` | [Os](https://developer.android.com/reference/android/system/Os), [Inet6Address](https://developer.android.com/reference/java/net/Inet6Address) — scope link-local cíle. | + +Protokoly (bez knihovny, vlastní ohraničené kodeky v `commonMain`): SNMPv2c GetRequest/Response +(RFC 3416, BER podle X.690 jen definitní délky), NTPv4 klientský dotaz mode 3 (RFC 5905 §7.3), +DNS `version.bind` CH TXT (třída CH = 3, RFC 1035), ICMPv6 echo 128/129 (RFC 4443). + +### Protokol iperf3 + +Ověřeno 2026-12-01. NetKit má vlastní implementaci TCP klienta v Kotlinu a vlastní testovací server v Pythonu. +Do aplikace se nepřidává knihovna, binárka ani nativní kód. + +| Zdroj popisu chování | Použití | +|---|---| +| [ESnet – The Iperf3 Protocol and State Machine](https://github.com/esnet/iperf/wiki/IperfProtocolStates) | Cookie na řídicím i datových spojeních, pořadí stavů, délka JSON v síťovém pořadí, směr výměny výsledků, IPERF_DONE po dokončení, CLIENT_TERMINATE při předčasném ukončení a SERVER_ERROR s dvojicí diagnostických čísel. | +| [ESnet – Invoking iperf3](https://software.es.net/iperf/invoking.html) | TCP 5201, reverse, délka běhu a limit bit/s na každý paralelní stream. | +| [Pozorování z odposlechu TCP řídicího kanálu](https://github.com/DmitryMaksakov/samsung-tv-iperf3/blob/main/docs/PROTOCOL.md) | Číselné stavy, pořadí ID streamů 1, 3, 4…, výsledková pole a nedostupné retransmise. Pozorování autora na několika verzích serveru vyžaduje místní interop ověření. | + +## RDAP pro ruční diagnostiku + +| Služba | Použití | Stav zdrojů | +|---|---|---| +| rdap.org a regionální registry (RIR) | HTTPS bootstrap pro veřejnou IPv4/IPv6 a ASN, následně registrační data z RIR | Ověřeno 2026-12-01 (build-host, Claude). **rdap.org** ([about.rdap.org](https://about.rdap.org/)): formát `https://rdap.org//` (mj. `ip`, `autnum`); 302 s `Location` na autoritativní server registrovaný u IANA, 404 bez známého serveru, 400 nepodporovaný typ, 403 blokace za zneužití; limit Cloudflare 10 požadavků za 10 s, překročení HTTP 429; formální podmínky použití stránka neuvádí; služba vede agregované statistiky (síť /24 resp. /48, User-Agent, kód odpovědi, origin), jednotlivé dotazy podle provozovatele neloguje; provozuje soukromá osoba ve vlastním čase a nákladu. Ruční zkouška `curl` 2026-12-01: `ip/`, `ip/`, `autnum/15169` → 302 `https://rdap.arin.net/registry/…`, `ip/` → 302 `https://rdap.db.ripe.net/ip/…`. **IANA bootstrap** (RFC 9224) staženo 2026-12-01 ([IPv4](https://data.iana.org/rdap/ipv4.json), publikace 2019-06-07; [IPv6](https://data.iana.org/rdap/ipv6.json), 2024-11-01; [ASN](https://data.iana.org/rdap/asn.json), 2026-06-01): HTTPS báze jen `rdap.arin.net/registry/`, `rdap.db.ripe.net/`, `rdap.apnic.net/`, `rdap.lacnic.net/rdap/`, `rdap.afrinic.net/rdap/` — shodné s whitelistem `rirHosts` v `DiagnosticLookup.kt`; ARIN a AFRINIC mají navíc `http://` varianty, které aplikace odmítá. | + +## NAT64 ve Web/TLS (ověřeno 2026-12-01) + +Od API 30 vrací `LinkProperties.getNat64Prefix()` překladový prefix konkrétní sítě, pokud je +známý. Na API 29 sonda rozpoznává standardní prefix `64:ff9b::/96`. Umístění vložené IPv4 +odpovídá délkám prefixu /32, /40, /48, /56, /64 a /96. +[Android LinkProperties](https://developer.android.com/reference/android/net/LinkProperties#getNat64Prefix()), +[RFC 6052 §2.2](https://www.rfc-editor.org/rfc/rfc6052.html#section-2.2). + +## 11. WoL widget: Glance a WorkManager (zadání 36, ověřeno 2026-12-01) + +Přímé závislosti `androidApp` (katalog `glance`, `work`). Verze ověřeny v `maven-metadata.xml` +Google Maven 2026-12-01, licence přečteny z oficiálních POM téhož dne, `minCompileSdk` +z `META-INF/com/android/build/gradle/aar-metadata.properties` v AAR. + +| Přímá závislost | Verze | Licence | Zdroj | Účel | +|---|---:|---|---|---| +| `androidx.glance:glance-appwidget` | 1.2.0 (stabilní, vydáno 2026-08-26) | Apache-2.0 | [POM Google Maven](https://dl.google.com/dl/android/maven2/androidx/glance/glance-appwidget/1.2.0/glance-appwidget-1.2.0.pom), [metadata verzí](https://dl.google.com/android/maven2/androidx/glance/glance-appwidget/maven-metadata.xml), [poznámky k vydání](https://developer.android.com/jetpack/androidx/releases/glance) | WoL widget na ploše (Compose pro RemoteViews); AAR `minCompileSdk=35`, AGP ≥ 8.6.0 | +| `androidx.glance:glance-material3` | 1.2.0 | Apache-2.0 | [POM Google Maven](https://dl.google.com/dl/android/maven2/androidx/glance/glance-material3/1.2.0/glance-material3-1.2.0.pom) | `ColorProviders(light, dark)` z tokenů aplikace (bez dynamických barev) | +| `androidx.work:work-runtime-ktx` | 2.12.0 (nejnovější stabilní; metadata `lastUpdated` 2026-09-23) | Apache-2.0 | [POM Google Maven](https://dl.google.com/dl/android/maven2/androidx/work/work-runtime-ktx/2.12.0/work-runtime-ktx-2.12.0.pom), [metadata verzí](https://dl.google.com/android/maven2/androidx/work/work-runtime-ktx/maven-metadata.xml) | připnutí nad tranzitivní 2.7.1 z Glance; `work-runtime` 2.12.0 AAR `minCompileSdk=35`, AGP ≥ 8.6.0 | + +Zamítnuto: Glance **1.3.0-alpha01/02** (alfa; AAR 1.3.0-alpha02 má `minCompileSdk=37`, AGP ≥ 9.1.0, ověřeno 2026-12-01); +ponechat tranzitivní WorkManager **2.7.1** (stará větev, bez oprav posledních let); widget bez knihovny +přes `RemoteViews` ručně (méně závislostí, ale vlastní layouty, stav a obsluha PendingIntentů pro +každý stav — větší riziko chyb; rozhodnutí zadání 36 je Glance). + +Celkem přibylo v `debugRuntimeClasspath` 31 souřadnic (3 přímé výše a 28 tranzitivních níže), všechny jsou v +[licenčním inventáři](project-license-inventory.tsv) a [evidenci POM](public-license-verification.tsv) +se SHA-256 staženého POM. Při kontrole 2026-12-02 odpovídalo všech 31 otisků oficiálním POM v místní +Gradle cache. Z nich 29 deklaruje Apache-2.0 a dvě přebalené varianty Protocol Buffers lite BSD-3-Clause. + +| Skupina | Artefakty a verze | Licence (POM) | +|---|---|---| +| `androidx.glance` | `glance`, `glance-appwidget-proto` 1.2.0 | Apache-2.0 | +| `androidx.glance` | `glance-appwidget-external-protobuf` 1.2.0 | **BSD-3-Clause** (přebalený Protocol Buffers lite) | +| `androidx.datastore` | `datastore`, `datastore-android`, `datastore-core-okio(-jvm)`, `datastore-preferences(-android)`, `datastore-preferences-core(-android)`, `datastore-preferences-proto` 1.1.7 | Apache-2.0 | +| `androidx.datastore` | `datastore-preferences-external-protobuf` 1.1.7 | **BSD-3-Clause** (přebalený Protocol Buffers lite) | +| `androidx.work` | `work-runtime` 2.12.0 | Apache-2.0 | +| `androidx.room` | `room-common(-jvm)`, `room-runtime(-android)` 2.7.0 | Apache-2.0 | +| `androidx.sqlite` | `sqlite(-android)`, `sqlite-framework(-android)` 2.5.0 | Apache-2.0 | +| `androidx.lifecycle` | `lifecycle-livedata`, `lifecycle-livedata-core-ktx`, `lifecycle-service` 2.9.4 | Apache-2.0 | +| ostatní AndroidX | `concurrent-futures-ktx` 1.1.0, `core-remoteviews` 1.1.0, `tracing-ktx` 1.2.0 | Apache-2.0 | + +DataStore Glance (1.0.0) projektová 1.1.7 přebije; stávající verze ostatních knihoven se nezměnily +(porovnání vyřešených grafů `debugRuntimeClasspath` 133 a `debugUnitTestRuntimeClasspath` 141 souřadnic +s inventářem). BSD-3-Clause je povolená licence (§1); text licence Protocol Buffers je přibalen +v O aplikaci (`assets/licenses/protobuf-LICENSE.txt`, kopie [docs/licenses/protobuf-LICENSE.txt](licenses/protobuf-LICENSE.txt) +z tagu [v29.3](https://github.com/protocolbuffers/protobuf/blob/v29.3/LICENSE), staženo 2026-12-01; +AAR obsahuje stejný text bez řádku copyrightu) a v `NOTICE`. + +**Manifest:** WorkManager deklaruje `WAKE_LOCK`, `RECEIVE_BOOT_COMPLETED` a `FOREGROUND_SERVICE`. +*Zadání 42 (2026-12-02):* `FOREGROUND_SERVICE` už se neodebírá — je to vlastní oprávnění služby SSH +relací (§14); odebrané zůstávají `WAKE_LOCK` a `RECEIVE_BOOT_COMPLETED`. +NetKit nespouští práci na popředí ani po startu systému a Glance session worker je nepotřebuje +(zdroje `work-runtime` 2.12.0: zámek probuzení jen v `Processor` pro foreground práci; Glance 1.2.0 +nepoužívá expedited práci ani `ForegroundInfo`), proto je hlavní manifest odebírá (`tools:node="remove"`), +stejně jako exportovaný `DiagnosticsReceiver` (chráněný `DUMP`, jen diagnostika). Zůstávají +exportované knihovní služby chráněné systémovým oprávněním: `SystemJobService` (`BIND_JOB_SERVICE`) +a `GlanceRemoteViewsService` (`BIND_REMOTEVIEWS`); viz [bezpecnost.md](bezpecnost.md). +Přijatý dopad odebraného `RECEIVE_BOOT_COMPLETED` (revize kolo 1): `RescheduleReceiver` WorkManageru +po restartu telefonu nepřeplánuje čekající práci. Pro API 29–30 revize jiný problém nenašla; NetKit +plánovanou práci nemá a Glance relaci vytvoří znovu při příští aktualizaci widgetu. + +**Ověření metadat:** `gradle/verification-metadata.xml` doplněn o SHA-256 41 nových komponent +(`--write-verification-metadata sha256` nad kompilací debug/dev/unit/androidTest; do souboru převzaty +jen nové komponenty, stávající záznamy a jejich původ beze změny), poté build +`--dependency-verification strict testDebugUnitTest lintDebug assembleDebug` prošel. + +`ShortcutManagerCompat` / `ShortcutInfoCompat` / `IconCompat` (pinned zkratky) jsou z již přítomného +`androidx.core:core` 1.15.0; `TileService` a `AppWidgetManager` jsou platformní API (API 24+ / 3+). + +## 12. Android API — zadání 38, Wi-Fi rozšíření (ověřeno 2026-12-01) + +Žádná nová knihovna, změna verze ani oprávnění. Serializace CSV/JSON používá stávající +`kotlinx-serialization-json`; čas ISO 8601 UTC počítá vlastní funkce v `commonMain` (bez +`kotlinx-datetime`). + +| API / chování | Použití a zdroj | +|---|---| +| `TelephonyManager.getNetworkCountryIso()` | [Reference](https://developer.android.com/reference/android/telephony/TelephonyManager#getNetworkCountryIso()): API 1, bez oprávnění; vyžaduje `FEATURE_TELEPHONY_RADIO_ACCESS`, bez ní `UnsupportedOperationException`; vrací ISO-3166-1 alpha-2 malými písmeny nebo prázdný řetězec. Regionální poznámka 2,4 GHz; aplikace kontroluje `FEATURE_TELEPHONY` a výjimky zachytí. | +| Kód země Wi-Fi v `WifiManager` | Veřejné API ho nemá: `javap` proti `platforms/android-35/android.jar` toolchainu nenašel žádnou metodu s `CountryCode` (2026-12-01), [reference WifiManager](https://developer.android.com/reference/android/net/wifi/WifiManager) ji neuvádí. | +| `ActivityResultContracts.CreateDocument` / `ACTION_CREATE_DOCUMENT`, `DocumentsContract.deleteDocument` | Stejný vzor jako LAN export (zadání 27); bez oprávnění k úložišti. | + +## 13. Android API — zadání 46, systém a nastavení (ověřeno 2026-12-01) + +Žádná nová knihovna, změna verze ani oprávnění. Nastavení ukládá stávající `datastore-core` +(JSON serializer jako u LAN nástrojů), jazyk framework `LocaleManager` bez AppCompat. + +| API / chování | Použití a zdroj | +|---|---| +| `androidResources { generateLocaleConfig = true }` + `res/resources.properties` (`unqualifiedResLocale`) | [App languages — automatic per-app language support](https://developer.android.com/guide/topics/resources/app-languages#auto-localeconfig) (2026-12-01): od AGP 8.1, `compileSdk` ≥ 33, výchozí locale tvaru `en-US`; ručně vytvořený `LocaleConfig` build pak odmítne. NetKit (AGP 8.9.2): `unqualifiedResLocale=cs`, vygenerováno `cs` + `en` (`build/generated/res/localeConfig/…`), sloučený manifest má `android:localeConfig` (kontrola v `ManifestExportsTest`). | +| Výběr zdrojů při seznamu jazyků (Android 7+) | [Language and locale resolution](https://developer.android.com/guide/topics/resources/multilingual-support) (2026-12-02), tabulka 3: když první jazyk seznamu nemá shodu, systém zkouší další jazyk a jeho kvalifikované zdroje dřív než výchozí `values/`. NetKit má češtinu ve výchozích zdrojích, proto build generuje `values-cs` (`generateCzechLocaleStrings`, `docs/funkce/nastaveni.md`); chování pro `[cs,en_US]` ověřeno na emulátoru API 35 (report 51). Bez nové knihovny. | +| `LocaleManager.setApplicationLocales` / `getApplicationLocales`, `LocaleList.getEmptyLocaleList()` | Tamtéž, § Implement using the Android framework APIs a § reset na systémový jazyk: API 33+, nastavení znovu vytvoří aktivitu; prázdný seznam = jazyk systému. Pod API 33 nic (bez AppCompat by zpětná kompatibilita vyžadovala vlastní úložiště a `attachBaseContext`; zadání ji nežádá). | +| `Intent.ACTION_LOCALE_CHANGED` | Změna efektivního jazyka aplikace dorazí i přijímači deklarovanému v manifestu. NetKit obnoví texty obou widgetů a existujícího kanálu relací. [Android Intent, ověřeno 2026-12-02](https://developer.android.com/reference/android/content/Intent#ACTION_LOCALE_CHANGED) | +| `Settings.ACTION_APP_LOCALE_SETTINGS` | [Settings reference](https://developer.android.com/reference/android/provider/Settings#ACTION_APP_LOCALE_SETTINGS): API 33+, data `package:` otevře stránku jazyka dané aplikace (2026-12-01). Dokumentace u této akce chybějící aktivitu nezmiňuje; NetKit ji přesto zachytí (`ActivityNotFoundException`, upravené ROM). | +| `android:enableOnBackInvokedCallback`, Compose `BackHandler` | [Predictive back gesture](https://developer.android.com/guide/navigation/custom-back/predictive-back-gesture) (2026-12-01): `OnBackPressedCallback` (AndroidX Activity 1.6+, NetKit 1.10.1) funguje dál; callbacky se vyhodnocují od posledně přidaného (vnitřní composable) k vnějšímu; od Androidu 15 systémové animace bez vývojářské volby. | +| `View.setKeepScreenOn` | [View reference](https://developer.android.com/reference/android/view/View#KEEP_SCREEN_ON) (2026-12-01): „screen should remain on while the window containing this view is visible to the user“; dokumentace neuvádí žádné oprávnění (není to wake lock). Na emulátoru ověřeno příznakem `KEEP_SCREEN_ON` okna v `dumpsys window`. | +| `SystemBarStyle.auto` / `ComponentActivity.enableEdgeToEdge(…)` | AndroidX Activity 1.10.1 (beze změny verze): ikony systémových lišt podle motivu aplikace, mřížky navigační lišty jako výchozí styl knihovny. | +## 14. Android API a JSch — zadání 42, SSH na pozadí a SFTP (ověřeno 2026-12-02) + +Žádná nová knihovna ani změna verze. SFTP používá `ChannelSftp` z již přítomného +`com.github.mwiede:jsch:2.28.0` (BSD-3-Clause, §2). + +| API / chování | Použití a zdroj | +|---|---| +| Typy služeb na popředí, `specialUse` + `PROPERTY_SPECIAL_USE_FGS_SUBTYPE`, oprávnění `FOREGROUND_SERVICE_SPECIAL_USE`, `startForeground(id, n, FOREGROUND_SERVICE_TYPE_SPECIAL_USE)` | [Foreground service types](https://developer.android.com/develop/background-work/services/fgs/service-types) (přečteno 2026-12-02): `specialUse` „covers any valid foreground service use cases that aren't covered by the other types“, popis v `` posuzuje Google Play; bez runtime předpokladu. Rozbor kandidátů v [bezpecnost.md](bezpecnost.md). | +| Limit `dataSync` 6 h / 24 h (targetSdk 35) | [Android 15 behavior changes](https://developer.android.com/about/versions/15/behavior-changes-15#datasync-timeout) (přečteno 2026-12-02); důvod, proč ne `dataSync`. | +| `ForegroundServiceStartNotAllowedException` (start z pozadí, API 31+) | Služba se startuje jen z viditelné aplikace; výjimka (podtřída `IllegalStateException`) se zachytí a platí limit 5 min. | +| `POST_NOTIFICATIONS` (API 33+), `NotificationManagerCompat.areNotificationsEnabled`, `NotificationCompat.setPublicVersion`, `VISIBILITY_PRIVATE`, `FOREGROUND_SERVICE_IMMEDIATE` | `androidx.core` 1.15.0 (již v projektu); platformní API. | +| `ContentResolver.openFileDescriptor(uri, mode, CancellationSignal)` | API 19; log relace (oprava kódu 41) ruší visící otevření dokumentu. | +| JSch `ChannelSftp.rename` | Bajtkód 2.28.0 (`javap -c`, 2026-12-02): `sendRENAME` posílá `posix-rename@openssh.com` (přepisuje cíl), kdykoli ho server ve verzi SFTP nabídne s hodnotou „1“; jinak `SSH_FXP_RENAME`. Volba, jak to vypnout, neexistuje. | +| JSch `ChannelSftp.hardlink`, `getExtension("hardlink@openssh.com")` | Totéž ověření: `hardlink@openssh.com` (OpenSSH, `link(2)` selže s EEXIST) — základ nahrání bez přepsání. Oba argumenty procházejí glob/unquote jako `rename`. | +| JSch glob (`*`, `?`, `\`) | `rm`, `rmdir`, `ls`, `stat`, `lstat`, `get`, `put`, `rename`, `hardlink` cesty rozbalují; `mkdir` a `realpath` ne (ověřeno týmž `javap`). NetKit escapuje cesty pro rozbalující metody. | + +## Android API — zadání 53, detail mobilní buňky (ověřeno 2026-12-01) + +Žádná nová knihovna, změna verze ani oprávnění (D31). Zdroj: developer.android.com, staženo a čteno +2026-12-01; tabulky pásem z 3GPP přes zdrojový přepis AOSP. + +| API / chování | Použití a zdroj | +|---|---| +| `TelephonyManager.requestCellInfoUpdate(Executor, CellInfoCallback)` | [Reference](https://developer.android.com/reference/android/telephony/TelephonyManager#requestCellInfoUpdate(java.util.concurrent.Executor,%20android.telephony.TelephonyManager.CellInfoCallback)): API 29; „Requests all available cell information from the current subscription“; vyžaduje `ACCESS_FINE_LOCATION` a `FEATURE_TELEPHONY_RADIO_ACCESS` (jinak `UnsupportedOperationException`). Voláno na `createForSubscriptionId(subId)`, takže jedna SIM. | +| `TelephonyManager.CellInfoCallback` | [Reference](https://developer.android.com/reference/android/telephony/TelephonyManager.CellInfoCallback): API 29; `onCellInfo(List)` (prázdný seznam = nic), `onError(int, Throwable)` s `ERROR_TIMEOUT` = 1, `ERROR_MODEM_ERROR` = 2. | +| `TelephonyManager.getAllCellInfo()` | **Nepoužívá se.** [Reference](https://developer.android.com/reference/android/telephony/TelephonyManager#getAllCellInfo()): „from all radios on the device“; aplikace s target API 29+ dostanou jen cache, obnova přes `requestCellInfoUpdate`, „updates will be rate-limited and are not guaranteed“. | +| `CellInfo` | [Reference](https://developer.android.com/reference/android/telephony/CellInfo): `isRegistered()`, `getCellConnectionStatus()` (API 28; `CONNECTION_NONE` 0, `PRIMARY_SERVING` 1, `SECONDARY_SERVING` 2, `UNKNOWN` 0x7fffffff), `UNAVAILABLE` = 0x7fffffff, `UNAVAILABLE_LONG` = 0x7fffffffffffffff. | +| `CellIdentityLte` | [Reference](https://developer.android.com/reference/android/telephony/CellIdentityLte): `getEarfcn` 18 bit (API 24), `getPci` 0..503, `getCi` 28 bit, `getTac` 16 bit, `getBandwidth` kHz bez rozsahu (API 28; validace 1400..20000 podle kanálů LTE TS 36.101 §5.6), `getBands` API 30. | +| `CellIdentityNr` | [Reference](https://developer.android.com/reference/android/telephony/CellIdentityNr): API 29; `getNrarfcn` 0..3279165, `getPci` 0..1007, `getNci` 0..68719476735 nebo `UNAVAILABLE_LONG`, `getTac` 0..16777215, `getBands` API 30. | +| `CellSignalStrengthLte.getTimingAdvance()` | [Reference](https://developer.android.com/reference/android/telephony/CellSignalStrengthLte#getTimingAdvance()): 0..1282, `UNAVAILABLE` bez RRC spojení. | +| `CellSignalStrengthNr.getTimingAdvanceMicros()` | [Reference](https://developer.android.com/reference/android/telephony/CellSignalStrengthNr#getTimingAdvanceMicros()): API 34; přes název jde o surový index T_A (TS 38.213 §4.2) 0..3846; na API < 34 se nečte. | +| Pásmo LTE z EARFCN | 3GPP TS 36.101 Table 5.7.3-1 (F_DL = F_DL_low + 0,1 × (N_DL − N_Offs-DL)); hodnoty shodné s AOSP `AccessNetworkConstants.EutranBandArfcnFrequency` a `AccessNetworkUtils.getOperatingBandForEarfcn` (android.googlesource.com, `platform/frameworks/base`, větev main, staženo 2026-12-01). SDL pásma 29, 32, 67, 69, 75, 76 doplněna z 36.101 (AOSP je vynechává); souvislost rozsahů s okolními pásmy ověřena. | +| Pásmo NR z NR-ARFCN | 3GPP TS 38.104 §5.4.2: tabulky „NR-ARFCN parameters for the global frequency raster“ a „Applicable NR-ARFCN per operating band“ (FR1, FR2); rozsahy shodné s AOSP `AccessNetworkUtils.getOperatingBandForNrarfcn` (stejný zdroj a datum). Překryvy pásem řeší pořadí preference (n78 před n77, n1 před n65/n66, n20 před n28 před n14); takto odvozené víceznačné pásmo UI označí „(odhad)“, pásmo hlášené modemem (`getBands`) má přednost. | + +## 15. Terminál xterm (zadání 43, ověřeno 2026-12-02) + +Žádná nová knihovna. Parser je vlastní, napsaný z veřejných specifikací; GPL kód (ConnectBot, +Termux) se nečetl ani nepřebíral. + +| Zdroj | Verze / stav | Použití | Ověřeno | +|---|---|---|---| +| [XTerm Control Sequences](https://invisible-island.net/xterm/ctlseqs/ctlseqs.html) (T. E. Dickey) | stránka pro xterm patch #413, datovaná 2026/12/01 | CSI/OSC/DEC private režimy, SGR včetně `38:2::r:g:b`, `?1049`, `?2004`, DA2, chování alternativní obrazovky | 2026-12-02 | +| [ECMA-48](https://ecma-international.org/publications-and-standards/standards/ecma-48/) | 5th edition, June 1991 | struktura CSI (parametry, mezilehlé a koncové bajty), CAN/SUB, IL/DL/ICH/DCH/ECH, SGR 0–29 | 2026-12-02 | +| [DEC ANSI parser](https://vt100.net/emu/dec_ansi_parser) (P. Williams, vt100.net) | veřejný popis stavového automatu | stavy ground/escape/CSI/CSI ignore/OSC/řetězce | 2026-12-02 | +| Unicode UCD [`EastAsianWidth.txt`](https://www.unicode.org/Public/UCD/latest/ucd/EastAsianWidth.txt) | 18.0.0 (Date 2026-06-29), SHA-256 `a0cf29eacd00cfcaec4381c6b7c281685f18dbb4e7ff82b4076ccb342ca839aa` | W/F → 2 buňky (`TerminalWidth.kt`) | 2026-12-02 | +| Unicode UCD [`extracted/DerivedGeneralCategory.txt`](https://www.unicode.org/Public/UCD/latest/ucd/extracted/DerivedGeneralCategory.txt) | 18.0.0 (Date 2026-06-29), SHA-256 `d6b151d2d40ee9b1876d26f417980f45ffae47b6055ccf7203cb31f07a030f94` | Mn/Me/Cf → 0 buněk (mimo U+00AD) | 2026-12-02 | +| [Unicode License V3](https://www.unicode.org/license.txt) | SHA-256 `e7a93b009565cfce55919a381437ac4db883e9da2126fa28b91d12732bc53d96` | licence odvozené tabulky; text v `androidApp/src/main/assets/licenses/unicode-LICENSE.txt`, položka `unicode-data` v O aplikaci | 2026-12-02 | + +**Výjimka D32 (rozhodnutí správce 2026-12-02, [plán](plan.md)).** Unicode License V3 (SPDX +`Unicode-3.0`, schválená OSI) je povolena jen pro tuto odvozenou tabulku. Splnění podmínek: +atribuce s původem a odkazem na plné znění v kořenovém `NOTICE` a jeho kopii +`androidApp/src/main/assets/licenses/NOTICE.txt`; plné znění v `unicode-LICENSE.txt` (assets, +krátký úvod o původu a pak nezměněný text, ověřeno proti `https://www.unicode.org/license.txt` +2026-12-02, SHA-256 výše) s položkou `unicode-data` v `components.json` (O aplikaci → Licence open +source); upstream kopie `docs/licenses/unicode-LICENSE.txt`; iOS terminál používá tutéž tabulku ze +`:shared`, proto je text licence i v `iosApp/NetKit/OpenSourceLicenses.txt`. Shodu hlídá +`OssComponentsTest` (Android) a `NetKitTests.testPrivacyUrlsAndOfflineLicenses` (iOS). Tabulku obnoví +`python3 -I tools/update_terminal_width.py EastAsianWidth.txt DerivedGeneralCategory.txt` +z ručně stažených souborů (skript nic nestahuje); při obnově zapsat sem verzi, datum a SHA-256. +Šířky serveru (glibc `wcwidth`) mohou u nejnovějších emoji zaostávat — pak se řádek může posunout +o buňku; je to vlastnost kombinace verzí, ne chyba parseru. + +## 16. Telnet a ovladače USB konzole (zadání 44) + +| Součást | Verze a licence | Původ a ověření | +|---|---|---| +| usb-serial-for-android | 3.12.0, MIT. Pomocná třída HexDump z AOSP má Apache-2.0. | 2026-12-02, [tag](https://github.com/mik3y/usb-serial-for-android/releases/tag/3.12.0), [zdrojový strom](https://github.com/mik3y/usb-serial-for-android/tree/4cb9e82cdcfa095eb2fe0b0bea9605f50bd8e2f2), [licence](https://github.com/mik3y/usb-serial-for-android/blob/4cb9e82cdcfa095eb2fe0b0bea9605f50bd8e2f2/LICENSE.txt) | + +Tag odkazoval přímo na commit `4cb9e82cdcfa095eb2fe0b0bea9605f50bd8e2f2`. Při stažení přes GitHub +Git Database API se pro každý převzatý soubor porovnal výstup `git hash-object` s SHA blobu ve stromě. +Balíček `androidApp/src/main/java/com/hoho/android/usbserial` obsahuje pět ovladačů, společná rozhraní, +základní port a pomocné třídy. Výběr ovladače volá přímo jejich veřejné tabulky VID/PID a CDC probe. +Dvě změny importu v Ch34xSerialDriver a ProlificSerialDriver odkazují na vygenerovaný +`cz.netkit.app.BuildConfig`. Licence je v `docs/licenses/usb-serial-for-android-LICENSE.txt`, +v assets, O aplikaci i NOTICE. Gradle žádný USB artefakt nestahuje. + +Telnet je vlastní implementace. Ověřeno 2026-12-02 podle [RFC 854](https://www.rfc-editor.org/rfc/rfc854), +[RFC 855](https://www.rfc-editor.org/rfc/rfc855), [RFC 1073](https://www.rfc-editor.org/rfc/rfc1073) +a [RFC 1091](https://www.rfc-editor.org/rfc/rfc1091). Výčet USB zařízení, dočasné oprávnění a přístup +k portu využívají [Android USB host API](https://developer.android.com/develop/connectivity/usb/host). +## 17. Wi-Fi 7 MLO (zadání 52) + +Ověřeno 2026-12-02 v Android Developers a příkazem `javap -constants` nad `platforms/android-35/android.jar`. Implementace používá stávající Android SDK a Material 3. + +| Rozhraní | Použití | +|---|---| +| `WifiInfo.getAssociatedMloLinks()` | Od API 34 vrací linky asociované s aktuálním Wi-Fi 7 AP. Seznam přidružených rádií AP dostupný od API 33 může zahrnovat i další linky. [WifiInfo](https://developer.android.com/reference/android/net/wifi/WifiInfo#getAssociatedMloLinks()) | +| `MloLink` | ID 0–15, pásmo, číslo kanálu a stav od API 33. RSSI od API 34. Ve veřejném SDK 35 chybí getter pro šířku. [MloLink](https://developer.android.com/reference/android/net/wifi/MloLink) | +| `WifiInfo.getApMldMacAddress()` | Od API 33. Údaj podléhá lokalizační redakci, systém může vrátit `null`. NetKit používá stávající callback s `FLAG_INCLUDE_LOCATION_INFO` a kontroluje přesnou polohu i systémový přepínač. [WifiInfo](https://developer.android.com/reference/android/net/wifi/WifiInfo#getApMldMacAddress()) | +| `ScanResult` | `getApMldMacAddress()` a `getApMloLinkId()` identifikují rádio v MLD. `frequency`, `timestamp` v µs od startu a `channelWidth` umožňují přiřadit čerstvou šířku hlášenou AP. [ScanResult](https://developer.android.com/reference/android/net/wifi/ScanResult) | +| `WifiManager.getScanResults()` | Pro target NetKitu vyžaduje `ACCESS_WIFI_STATE`, `ACCESS_FINE_LOCATION` a zapnutou polohu. Čte poslední výsledky již provedených skenů. [Wi-Fi scanning permissions](https://developer.android.com/develop/connectivity/wifi/wifi-scan#permissions) | + +## 18. Zámek SSH: Biometric a Fragment (zadání 50, ověřeno 2026-12-02) + +Ověřeno na build-hostu 2026-12-02: verze z `maven-metadata.xml` Google Maven, licence z oficiálních POM +téhož dne, `minCompileSdk` z `META-INF/com/android/build/gradle/aar-metadata.properties` v AAR. + +| Přímá závislost | Verze | Licence | Zdroj | Účel | +|---|---:|---|---|---| +| `androidx.biometric:biometric` | 1.1.0 (nejnovější stabilní; metadata `lastUpdated` 2026-11-18, novější jen 1.2.0-alpha05 a 1.4.0-rc01) | Apache-2.0 | [POM](https://dl.google.com/dl/android/maven2/androidx/biometric/biometric/1.1.0/biometric-1.1.0.pom) (SHA-256 `aeb69e76…bcaa9`), [metadata verzí](https://dl.google.com/android/maven2/androidx/biometric/biometric/maven-metadata.xml) | `BiometricPrompt` s `BIOMETRIC_STRONG or DEVICE_CREDENTIAL` (API 30+); AAR bez `minCompileSdk` | +| `androidx.fragment:fragment` | 1.8.9 (poslední stabilní řady 1.8; nejnovější stabilní je 1.9.1) | Apache-2.0 | [POM](https://dl.google.com/dl/android/maven2/androidx/fragment/fragment/1.8.9/fragment-1.8.9.pom) (SHA-256 `8135a58b…afed36`), [metadata verzí](https://dl.google.com/android/maven2/androidx/fragment/fragment/maven-metadata.xml) | `MainActivity : FragmentActivity`; AAR `minCompileSdk=34` | + +**Proč připnutý Fragment:** Biometric 1.1.0 deklaruje `androidx.fragment:fragment:1.2.5`. Jeho +`FragmentActivity.startActivityForResult(Intent, int, Bundle)` volá `checkForValidRequestCode` (ověřeno +`javap -c` nad AAR 1.2.5) a odmítne kód nad 16 bitů. `ActivityResultRegistry` z Activity 1.10.1 generuje +kódy `Random.nextInt(2147418112) + 65536` (ověřeno `javap -c`), takže by každý `rememberLauncherForActivityResult` +(SAF exporty, výběr souborů, runtime oprávnění) v `MainActivity` skončil `IllegalArgumentException`. +Fragment ≥ 1.3.0 kontrolu nemá. Zvolena 1.8.9: její závislosti (Activity 1.8.1, Lifecycle 2.6.1, Core KTX 1.2.0) +přebijí projektové verze, vyřešený graf ostatních knihoven se nezmění. +Zamítnuto: **1.9.1** (nejnovější stabilní) vytahuje Lifecycle 2.10.0 a Tracing 2.0.0, tedy povýšení Lifecycle +pro celou aplikaci mimo rozsah zadání 50; ponechat **1.2.5** (pád ActivityResult API). Lint `GradleDependency` +proto u `fragment` hlásí novější 1.9.1, stejně jako u připnutých `activity` a `lifecycle`. + +Nové tranzitivní artefakty v `debugRuntimeClasspath` a `debugUnitTestRuntimeClasspath` (11 souřadnic včetně +obou přímých, všechny Apache-2.0 podle POM, doplněné do [licenčního inventáře](project-license-inventory.tsv) +a [evidence POM](public-license-verification.tsv) se SHA-256 staženého POM): +`androidx.appcompat:appcompat` a `appcompat-resources` 1.2.0 (runtime závislost Biometric 1.1.0), +`androidx.cursoradapter:cursoradapter`, `customview`, `drawerlayout`, `loader`, `viewpager` 1.0.0, +`androidx.vectordrawable:vectordrawable` a `vectordrawable-animated` 1.1.0. Vyřešený graf má 144 (runtime) +a 152 (unit test) souřadnic; ostatní verze beze změny. V O aplikaci je přidána položka `androidx-fragment`, +tranzitivní AndroidX kryje vzor `androidx.*`. + +**Manifest:** AAR Biometric deklaruje `USE_BIOMETRIC` a `USE_FINGERPRINT`; hlavní manifest odebírá +`USE_FINGERPRINT` (`tools:node="remove"`, minSdk 29), viz [bezpecnost.md](bezpecnost.md#zámek-ssh). + +**Ověření metadat:** `--write-verification-metadata sha256 --dry-run help` (resoluce všech konfigurací); +do `gradle/verification-metadata.xml` převzaty jen nové komponenty (22) a chybějící artefakt +`lifecycle-viewmodel-2.9.4.aar` u existující komponenty; stávající záznamy a jejich původ beze změny. +SHA-256 AAR `biometric-1.1.0.aar` a `fragment-1.8.9.aar` shodné s nezávisle staženými soubory +(`270c7b7d…dfc1f`, `12de5b89…ac492`). Poté build `--dependency-verification strict testDebugUnitTest lintDebug +assembleDebug assembleDebugAndroidTest` prošel. + +## 19. Konfigurační záloha (zadání 51, ověřeno 2026-12-02) + +Implementace používá platformní `javax.crypto` a stávající Kotlin serialization. Pro verzi 1 +bylo 2026-12-02 ověřeno doporučení 600 000 iterací PBKDF2-HMAC-SHA256. [OWASP Password Storage Cheat Sheet, PBKDF2](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#pbkdf2) diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index c9a18f0..b7f1a5e 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -3,6 +3,10 @@ agp = "8.9.2" kotlin = "2.2.20" compose-bom = "2025.08.00" activity = "1.10.1" +biometric = "1.1.0" +# Zadání 50: biometric 1.1.0 brings fragment 1.2.5, whose FragmentActivity rejects request codes +# above 16 bits that ActivityResultRegistry (activity 1.10.1) generates. 1.8.9 keeps lifecycle 2.9.4. +fragment = "1.8.9" lifecycle = "2.9.4" testng = "7.11.0" coroutines = "1.10.2" @@ -12,11 +16,20 @@ profileinstaller = "1.4.0" jsch = "2.28.0" bcprov = "1.83" okhttp = "5.3.2" +# WoL widget (zadání 36): Glance 1.2.0 needs compileSdk 35 / AGP 8.6+; 1.3.x needs compileSdk 37. +glance = "1.2.0" +# Pinned over Glance's transitive work-runtime-ktx 2.7.1 (latest stable on Google Maven, 2026-12-01). +work = "2.12.0" [libraries] +biometric = { module = "androidx.biometric:biometric", version.ref = "biometric" } +fragment = { module = "androidx.fragment:fragment", version.ref = "fragment" } jsch = { module = "com.github.mwiede:jsch", version.ref = "jsch" } bcprov = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bcprov" } okhttp = { module = "com.squareup.okhttp3:okhttp", version.ref = "okhttp" } +glance-appwidget = { module = "androidx.glance:glance-appwidget", version.ref = "glance" } +glance-material3 = { module = "androidx.glance:glance-material3", version.ref = "glance" } +work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "work" } profileinstaller = { module = "androidx.profileinstaller:profileinstaller", version.ref = "profileinstaller" } coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "coroutines" } coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "coroutines" } diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 239699f..1da136a 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -5,6 +5,11 @@ false + + + + + @@ -13,6 +18,11 @@ + + + + + @@ -81,6 +91,22 @@ + + + + + + + + + + + + + + + + @@ -94,6 +120,11 @@ + + + + + @@ -429,6 +460,11 @@ + + + + + @@ -453,6 +489,22 @@ + + + + + + + + + + + + + + + + @@ -493,6 +545,14 @@ + + + + + + + + @@ -551,6 +611,16 @@ + + + + + + + + + + @@ -637,6 +707,9 @@ + + + @@ -659,6 +732,11 @@ + + + + + @@ -675,6 +753,14 @@ + + + + + + + + @@ -792,6 +878,27 @@ + + + + + + + + + + + + + + + + + + + + + @@ -3560,5 +3667,336 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/iosApp/NetKit/Localizable.xcstrings b/iosApp/NetKit/Localizable.xcstrings index b015266..9695cfd 100644 --- a/iosApp/NetKit/Localizable.xcstrings +++ b/iosApp/NetKit/Localizable.xcstrings @@ -2625,6 +2625,22 @@ } } }, + "ssh.proxyjump.unsupported": { + "localizations": { + "cs": { + "stringUnit": { + "state": "translated", + "value": "iOS verze nepodporuje ProxyJump; profil s jump hostem se nepřipojí přímo." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The iOS version does not support ProxyJump; a profile with a jump host is never connected directly." + } + } + } + }, "ssh.interactive.unsupported": { "localizations": { "cs": { diff --git a/iosApp/NetKit/OpenSourceLicenses.txt b/iosApp/NetKit/OpenSourceLicenses.txt index 989d26b..8d38aad 100644 --- a/iosApp/NetKit/OpenSourceLicenses.txt +++ b/iosApp/NetKit/OpenSourceLicenses.txt @@ -3259,3 +3259,51 @@ FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + +===== Unicode Character Database 18.0.0 (NetKit terminal cell widths) ===== + +Unicode Character Database (UCD) 18.0.0 + +NetKit derives the terminal cell width table (shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt) +from EastAsianWidth.txt and extracted/DerivedGeneralCategory.txt, downloaded on 2026-12-02 from +https://www.unicode.org/Public/UCD/latest/ucd/. License text from https://www.unicode.org/license.txt: + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2026 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. diff --git a/iosApp/NetKit/SshView.swift b/iosApp/NetKit/SshView.swift index 26762d2..29906cf 100644 --- a/iosApp/NetKit/SshView.swift +++ b/iosApp/NetKit/SshView.swift @@ -69,6 +69,7 @@ func errorKey(_ error: SshViewModel.ErrorKind) -> String { case .algorithm: "ssh.error.algorithm" case .unsupportedCredential: "ssh.error.unsupported_credential" case .interactiveUnsupported: "ssh.interactive.unsupported" + case .proxyJumpUnsupported: "ssh.proxyjump.unsupported" case .hostChanged: "ssh.error.host.changed" case .hostRejected: "ssh.error.host.rejected" case .timeout: "ssh.error.timeout" diff --git a/iosApp/NetKit/SshViewModel.swift b/iosApp/NetKit/SshViewModel.swift index c1f9118..fb59583 100644 --- a/iosApp/NetKit/SshViewModel.swift +++ b/iosApp/NetKit/SshViewModel.swift @@ -22,7 +22,7 @@ final class SshViewModel: ObservableObject { let reply: (Bool) -> Void } struct ChangedHost { let endpoint: String; let saved: String; let offered: String } - enum ErrorKind: Equatable { case storage, invalid, credentials, keyInUse, connection, algorithm, unsupportedCredential, interactiveUnsupported, hostChanged, hostRejected, timeout, inputOverflow, importFailure(SshImportFailure) } + enum ErrorKind: Equatable { case storage, invalid, credentials, keyInUse, connection, algorithm, unsupportedCredential, interactiveUnsupported, proxyJumpUnsupported, hostChanged, hostRejected, timeout, inputOverflow, importFailure(SshImportFailure) } @Published var data: SshData? @Published var error: ErrorKind? @Published var hostPrompt: HostPrompt? @@ -152,6 +152,8 @@ final class SshViewModel: ObservableObject { profileUnavailable = true; keySelectionRequired = nil; return } profileUnavailable = false + // The iOS transport connects only to the target: a jump-host profile must never go direct (review of 41). + guard profile.jumpProfileId == nil else { keySelectionRequired = nil; error = .proxyJumpUnsupported; return } if domain.needsKeySelection(profile: profile, data: current) { keySelectionRequired = profile; error = nil; return } diff --git a/iosApp/NetKitTests/LanTests.swift b/iosApp/NetKitTests/LanTests.swift index 17d221d..720d0e7 100644 --- a/iosApp/NetKitTests/LanTests.swift +++ b/iosApp/NetKitTests/LanTests.swift @@ -337,7 +337,7 @@ final class WolPersistenceTests: XCTestCase { targetMode: .custom, customTarget: "192.0.2.1", port: 9, probeHost: "192.0.2.2", probePort: KotlinInt(value: 22), note: "Test", createdAt: 1000, updatedAt: 2000, repeatCount: 3, repeatIntervalMs: 250, - probeEnabled: true, probeDelaySeconds: 20) + probeEnabled: true, probeDelaySeconds: 20, secureOnRequired: false) XCTAssertTrue(store.save(devices: [device])) let result = store.load() XCTAssertNil(result.failure) diff --git a/iosApp/NetKitTests/NetKitTests.swift b/iosApp/NetKitTests/NetKitTests.swift index cc5ad39..3fc90f1 100644 --- a/iosApp/NetKitTests/NetKitTests.swift +++ b/iosApp/NetKitTests/NetKitTests.swift @@ -13,7 +13,8 @@ final class NetKitTests: XCTestCase { for component in ["swift-nio-ssh 0.15.1", "swift-nio 2.84.0", "swift-crypto 3.12.3", "swift-atomics 1.3.0", "swift-collections 1.2.0", "swift-system 1.5.0", "swift-asn1 1.4.0", "Kotlin 2.2.20", "kotlinx-coroutines 1.10.2", - "kotlinx-serialization 1.9.0", "kotlinx-atomicfu 0.26.1"] { + "kotlinx-serialization 1.9.0", "kotlinx-atomicfu 0.26.1", + "Unicode Character Database 18.0.0", "UNICODE LICENSE V3"] { XCTAssertTrue(licenses.contains(component), component) } XCTAssertTrue(licenses.contains("Apache License")) diff --git a/iosApp/NetKitTests/SshMetadataStoreTests.swift b/iosApp/NetKitTests/SshMetadataStoreTests.swift index 60fe847..f8cbddb 100644 --- a/iosApp/NetKitTests/SshMetadataStoreTests.swift +++ b/iosApp/NetKitTests/SshMetadataStoreTests.swift @@ -668,6 +668,22 @@ final class SshProfileExchangeTests: XCTestCase { model.disconnect() } } + + /// Review of 41 (P2): iOS has no ProxyJump transport, so a jump row is skipped, never imported as a direct profile. + func testProxyJumpRowsAreSkippedOnIos() throws { + try withStorage { root, _ in + let store = try SshMetadataStore(directory: root) + let document = Data(""" + {"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"jump","host":"192.0.2.1","port":22,"username":"u"},{"alias":"db","host":"192.0.2.9","port":22,"username":"u","proxyJump":"jump"}],"skipped":[]} + """.utf8) + let plan = try store.previewImport(document) + XCTAssertEqual(plan.newProfiles.map { $0.after.name }, ["jump"]) + XCTAssertTrue(plan.newProfiles.allSatisfy { $0.after.jumpProfileId == nil }) + XCTAssertEqual(plan.skipped.map { $0.alias }, ["db"]) + XCTAssertEqual(plan.skipped.map { $0.reason.name }, ["PROXY_JUMP"]) + XCTAssertNotEqual(errorKey(.proxyJumpUnsupported), errorKey(.interactiveUnsupported)) + } + } } private final class ImportPlanningStoreDouble: SshImportPlanning { diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/backup/ConfigurationBackup.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/backup/ConfigurationBackup.kt new file mode 100644 index 0000000..b7604b5 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/backup/ConfigurationBackup.kt @@ -0,0 +1,159 @@ +package cz.netkit.shared.backup + +import cz.netkit.shared.json.JSON_MAX_DEPTH +import cz.netkit.shared.json.jsonNestingDepth +import cz.netkit.shared.lan.* +import cz.netkit.shared.settings.AppLanguage +import cz.netkit.shared.settings.ThemeMode +import cz.netkit.shared.speed.* +import cz.netkit.shared.ssh.* +import cz.netkit.shared.wol.* +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.* + +const val BACKUP_FORMAT = "netkit-backup-v1" +const val BACKUP_BYTES = 4 * 1024 * 1024 +const val BACKUP_FILE_BYTES = 6 * 1024 * 1024 + +const val BACKUP_ENCRYPTED_FORMAT = "netkit-backup-encrypted-v1" +const val BACKUP_KDF = "PBKDF2-HMAC-SHA256" +const val BACKUP_CIPHER = "AES-256-GCM" +const val BACKUP_ROUNDS = 600_000 + +@Serializable +data class BackupEnvelope(val format: String, val kdf: String, val iterations: Int, val cipher: String, + val salt: String, val iv: String, val ciphertext: String) + +fun encryptedBackup(bytes: ByteArray): Boolean = when (backupDocument(bytes, BACKUP_FILE_BYTES)["format"]) { + JsonPrimitive(BACKUP_ENCRYPTED_FORMAT) -> true + JsonPrimitive(BACKUP_FORMAT) -> false + else -> throw IllegalArgumentException("format") +} + +fun encodeEnvelope(salt: String, iv: String, ciphertext: String) = Json.encodeToString(BackupEnvelope( + BACKUP_ENCRYPTED_FORMAT, BACKUP_KDF, BACKUP_ROUNDS, BACKUP_CIPHER, salt, iv, ciphertext)).encodeToByteArray() + +fun decodeEnvelope(bytes: ByteArray): BackupEnvelope { + val envelope = Json.decodeFromJsonElement(backupDocument(bytes, BACKUP_FILE_BYTES)) + require(envelope.format == BACKUP_ENCRYPTED_FORMAT && envelope.kdf == BACKUP_KDF && + envelope.iterations == BACKUP_ROUNDS && envelope.cipher == BACKUP_CIPHER) + require(envelope.salt.length == 24 && envelope.iv.length == 16 && + envelope.ciphertext.length in 24..((BACKUP_BYTES + 16 + 2) / 3 * 4)) + return envelope +} + +enum class BackupSection { SSH, TELNET, SERIAL, SNIPPETS, FORWARDS, KNOWN_HOSTS, WOL, TOOLS, FAVORITES, SERVERS, SETTINGS } + +@Serializable +data class ForwardSettings(val profile: String, val local: List, val dynamicPort: Int?) + +// Only these fields cross the backup boundary. Never serialize a whole application store. +@Serializable +data class BackupTools(val count: String, val seconds: String, val payload: String, val df: Boolean, + val subnetInput: String?, val ports: String, val mask: MaskInterpretation) +@Serializable +data class BackupServers(val libreSpeed: String?, val iperfHost: String, val iperfPort: Int) +@Serializable +data class BackupSettings(val theme: ThemeMode, val language: AppLanguage, val keepScreenOn: Boolean) + +@Serializable +data class ConfigurationBackup( + val format: String, + val ssh: JsonObject, // Existing SSH v2 schema, including alias-scoped snippets. + val consoles: List, + val forwards: List, + val knownHosts: List, + val wol: JsonObject, + val tools: BackupTools, + val favorites: List, + val servers: BackupServers, + val settings: BackupSettings, +) + +private val wire = Json { encodeDefaults = true } + +fun backupDocument(bytes: ByteArray, limit: Int): JsonObject { + require(bytes.size <= limit) + val text = bytes.decodeToString(throwOnInvalidSequence = true) + require(jsonNestingDepth(text) <= JSON_MAX_DEPTH) + return wire.parseToJsonElement(text).jsonObject +} + +class BackupContainsCredential : IllegalArgumentException() + +// Free-text fields may contain pasted configuration. Catch recognizable credential assignments +// in addition to the wire field allowlists. A bare arbitrary string cannot be classified reliably. +private val credentialText = Regex( + """-----BEGIN [^-]*PRIVATE KEY-----|\b(?:password|passwd|passphrase|api[_-]?key|token|community|secret)\s*[:=]\s*\S|\bsnmp-server\s+community\s+\S|\bauthorization:\s*(?:basic|bearer)\s+\S""", + RegexOption.IGNORE_CASE, +) + +private fun checkPortableText(backup: ConfigurationBackup) { + fun check(value: JsonElement) { + when (value) { + is JsonObject -> value.values.forEach(::check) + is JsonArray -> value.forEach(::check) + is JsonPrimitive -> if (value.isString) { + val text = value.content + val authority = text.substringAfter("://", "").takeWhile { it != '/' && !it.isWhitespace() } + if (credentialText.containsMatchIn(text) || '@' in authority && ':' in authority.substringBefore('@')) + throw BackupContainsCredential() + } + } + } + check(wire.encodeToJsonElement(backup)) +} + +fun configurationBackup(ssh: SshData, devices: List, tools: BackupTools, favorites: List, + servers: BackupServers, settings: BackupSettings): ConfigurationBackup { + require(ssh.profiles.all { resolveSshJumpChain(ssh.profiles, it) is SshJumpResolution.Chain }) + val ids = ssh.profiles.map { it.id }.toSet() + require(ssh.snippets.all { it.profileId == null || it.profileId in ids }) + // Query strings and fragments of manually starred URLs can contain access tokens. + val portable = favorites.map { it.copy(value = it.value.substringBefore('?').substringBefore('#')) } + return ConfigurationBackup(BACKUP_FORMAT, + backupDocument(encodeSshProfileExport(ssh, "netkit-backup"), SSH_PROFILE_IMPORT_LIMIT), + ssh.consoles.map { it.copy(skipTelnetWarning = false) }, + ssh.profiles.map { ForwardSettings(it.name, it.localForwards, it.dynamicForwardPort) }, + ssh.hostKeys, backupDocument(encodeWolExport(devices), WOL_TRANSFER_LIMIT), tools, + ToolTargets(favorites = portable).normalized().favorites, servers, settings) +} + +fun encodeBackup(backup: ConfigurationBackup): ByteArray = + wire.encodeToString(backup).encodeToByteArray().also { decodeBackup(it) } + +class ValidatedBackup internal constructor(val file: ConfigurationBackup, val profiles: SshProfileImport, val devices: List) + +fun decodeBackup(bytes: ByteArray): ValidatedBackup { + val root = backupDocument(bytes, BACKUP_BYTES) + val file = wire.decodeFromJsonElement(root) + require(file.format == BACKUP_FORMAT && file.ssh["format"] == JsonPrimitive("netkit-ssh-profiles") && + file.ssh["schema"] == JsonPrimitive(2)) + val profiles = decodeSshProfileImport(file.ssh.toString().encodeToByteArray()) + require(profiles.skipped.isEmpty()) + val aliases = profiles.profiles.map { it.alias }.toSet() + require(profiles.profiles.all { it.proxyJump == null || it.proxyJump in aliases }) + require(file.forwards.map { it.profile }.toSet() == aliases && file.forwards.size == aliases.size) + require(file.forwards.all { validSshForwards(it.local, it.dynamicPort) }) + require(SshData(consoles = file.consoles, hostKeys = file.knownHosts).valid()) + require(file.consoles.none { it.skipTelnetWarning }) + require(file.knownHosts.all { it.fingerprint.length <= 128 && it.algorithm.length in 1..64 && it.endpoint.none(Char::isISOControl) && + it.publicKey.all { c -> c.isLetterOrDigit() && c.code < 128 || c in "+/=" } }) + require(file.favorites == ToolTargets(favorites = file.favorites).normalized().favorites && + file.favorites.none { '?' in it.value || '#' in it.value }) + with(file.servers) { + require(libreSpeed == null || checkLibreSpeedUrl(libreSpeed) is LibreSpeedUrlCheck.Valid) + require((iperfHost.isEmpty() || validIperf3Host(iperfHost)) && iperfPort in 1..65535) + } + // Tool preferences include partially edited forms. Preserve bounded numeric drafts as entered. + with(file.tools) { + require(count.length <= 8 && count.all { it in '0'..'9' }) + require(payload.length <= 8 && payload.all { it in '0'..'9' }) + require(seconds.length <= 16 && seconds.all { it in "0123456789.," }) + require(ports.length <= 4096 && ports.all { it in "0123456789,- " }) + require(subnetInput == null || subnetInput.length <= 128 && subnetInput.all { it in "0123456789./ " }) + } + val devices = decodeWolImport(file.wol.toString().encodeToByteArray()) + checkPortableText(file) + return ValidatedBackup(file, profiles, devices) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/backup/RestorePlan.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/backup/RestorePlan.kt new file mode 100644 index 0000000..4638402 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/backup/RestorePlan.kt @@ -0,0 +1,111 @@ +package cz.netkit.shared.backup + +import cz.netkit.shared.lan.FavoriteTarget +import cz.netkit.shared.ssh.* +import cz.netkit.shared.wol.* + +data class ConfigurationState(val ssh: SshData, val devices: List, val tools: BackupTools, + val favorites: List, val servers: BackupServers, val settings: BackupSettings) + +data class SectionChanges(val added: Int = 0, val changed: Int = 0, val skipped: Int = 0) +/** [keyless]: aliases of restored key-authenticated profiles that end up without a local key (revize 51, kolo 2). */ +data class RestorePlan(val state: ConfigurationState, val changes: Map, val forgetSecureOn: Set, + val keyless: Set = emptySet()) + +/** Use the same validated import plans as the standalone SSH v2 and WoL controllers. */ +fun planRestore(current: ConfigurationState, backup: ValidatedBackup, selected: Set, newId: () -> String): RestorePlan { + val file = backup.file + val changes = mutableMapOf() + var ssh = current.ssh + var keyless = emptySet() + if (BackupSection.SSH in selected || BackupSection.SNIPPETS in selected) { + val restoreProfiles = BackupSection.SSH in selected + // When only snippets were selected, bind aliases to existing local profiles without editing them. + val existing = ssh.profiles.groupBy { it.name } + val rows = if (restoreProfiles) backup.profiles.profiles else backup.profiles.profiles.mapNotNull { row -> + existing[row.alias]?.singleOrNull()?.takeIf { + it.host == row.host && it.port == row.port && it.username == row.username + }?.let { SshImportProfile(it.name, it.host, it.port, it.username) } + } + val aliases = rows.map { it.alias }.toSet() + val snippets = if (BackupSection.SNIPPETS in selected) backup.profiles.snippets.filter { + it.profile == null || it.profile in aliases + } else emptyList() + // A full backup describes direct connections too: drop a local jump link before validating chains (revize 51, kolo 1). + val transaction = PendingSshProfileImport.prepare(ssh, backup.profiles.copy(profiles = rows, snippets = snippets), newId, + replaceJumps = restoreProfiles) + val plan = transaction.plan + val applied = transaction.apply(ssh) + if (restoreProfiles) { + val accepted = (plan.newProfiles + plan.updatedProfiles + plan.unchangedProfiles).associateBy { it.after.id } + val profiles = applied.profiles.map { profile -> + val row = accepted[profile.id] ?: return@map profile + val old = row.before + val moved = old != null && (old.host != profile.host || old.port != profile.port || old.username != profile.username) + // A full backup also describes an ungrouped profile (direct connections are planned above). + profile.copy(group = row.incoming.group, keyRef = profile.keyRef.takeUnless { moved }) + } + ssh = applied.copy(profiles = profiles) + // Keys never leave the device: a new or moved key profile needs its key assigned again. + keyless = profiles.filter { it.id in accepted && it.authentication == SshAuthentication.KEY && it.keyRef == null } + .map { it.name }.toSet() + val changed = profiles.count { profile -> accepted[profile.id]?.before?.let { it != profile } == true } + changes[BackupSection.SSH] = SectionChanges(plan.newProfiles.size, changed, plan.skipped.size) + } else ssh = ssh.copy(snippets = applied.snippets) + if (BackupSection.SNIPPETS in selected) { + val accepted = (plan.newProfiles + plan.updatedProfiles + plan.unchangedProfiles).map { it.after.name }.toSet() + changes[BackupSection.SNIPPETS] = SectionChanges(plan.newSnippets, plan.updatedSnippets, + backup.profiles.snippets.count { it.profile != null && it.profile !in accepted }) + } + } + for ((section, kind) in listOf(BackupSection.SERIAL to ConsoleKind.SERIAL, BackupSection.TELNET to ConsoleKind.TELNET)) { + if (section !in selected) continue + val before = ssh.consoles.associateBy { it.id } + val incoming = file.consoles.filter { it.kind == kind } + val accepted = incoming.filter { before[it.id]?.kind in listOf(null, kind) }.associateBy { it.id } + ssh = ssh.copy(consoles = ssh.consoles.map { accepted[it.id] ?: it } + accepted.values.filter { it.id !in before }) + changes[section] = SectionChanges(accepted.keys.count { it !in before }, accepted.values.count { it.id in before && before[it.id] != it }, + incoming.size - accepted.size) + } + if (BackupSection.FORWARDS in selected) { + val aliases = ssh.profiles.groupBy { it.name } + val destinations = backup.profiles.profiles.associateBy { it.alias } + val accepted = file.forwards.mapNotNull { forward -> + val local = aliases[forward.profile]?.singleOrNull() ?: return@mapNotNull null + val endpoint = destinations.getValue(forward.profile) + if (local.host != endpoint.host || local.port != endpoint.port || local.username != endpoint.username) return@mapNotNull null + local.id to local.copy(localForwards = forward.local, dynamicForwardPort = forward.dynamicPort, dynamicForwardNoAuth = false) + }.toMap() + changes[BackupSection.FORWARDS] = SectionChanges(changed = ssh.profiles.count { it.id in accepted && accepted[it.id] != it }, + skipped = file.forwards.size - accepted.size) + ssh = ssh.copy(profiles = ssh.profiles.map { accepted[it.id] ?: it }) + } + if (BackupSection.KNOWN_HOSTS in selected) { + val pinned = ssh.hostKeys.associateBy { it.endpoint } + val rejected = ssh.rejectedHostKeys.map { it.endpoint }.toSet() + val additions = file.knownHosts.filter { it.endpoint !in pinned && it.endpoint !in rejected } + val conflicts = file.knownHosts.count { it.endpoint in rejected || it.endpoint in pinned && pinned[it.endpoint] != it } + changes[BackupSection.KNOWN_HOSTS] = SectionChanges(added = additions.size, skipped = conflicts) + ssh = ssh.copy(hostKeys = ssh.hostKeys + additions) + } + require(ssh.valid()) + var devices = current.devices + var forgetSecureOn = emptySet() + if (BackupSection.WOL in selected) { + val before = devices.associateBy { it.id } + val incoming = backup.devices.map { it.copy(secureOnRequired = it.secureOnRequired || before[it.id]?.secureOnRequired == true) } + val plan = WolController.prepareImport(devices, incoming) + devices = plan.devices + forgetSecureOn = plan.forgetSecureOn + changes[BackupSection.WOL] = SectionChanges(incoming.count { it.id !in before }, incoming.count { it.id in before && before[it.id] != it }) + } + fun replace(section: BackupSection, before: T, after: T): T { + if (section !in selected) return before + changes[section] = SectionChanges(changed = if (before == after) 0 else 1) + return after + } + return RestorePlan(ConfigurationState(ssh, devices, replace(BackupSection.TOOLS, current.tools, file.tools), + replace(BackupSection.FAVORITES, current.favorites, file.favorites), + replace(BackupSection.SERVERS, current.servers, file.servers), + replace(BackupSection.SETTINGS, current.settings, file.settings)), changes, forgetSecureOn, keyless) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/cellular/CellDetail.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/cellular/CellDetail.kt new file mode 100644 index 0000000..2a5ad7c --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/cellular/CellDetail.kt @@ -0,0 +1,359 @@ +package cz.netkit.shared.cellular + +/* + * Cell detail of one SIM (zadání 53, D31): serving LTE/NR cells and up to 16 neighbours, from + * `TelephonyManager.requestCellInfoUpdate` (built by the Android layer). Pure logic, no `android.*`. + * Cell ID + TAC are a location hint: the result lives only in UI memory, it is never stored, + * exported, shared or sent (docs/bezpecnost.md § Detail buňky). + * + * Value ranges (developer.android.com, verified 2026-12-01): + * - CellIdentityLte: EARFCN 18 bit (0..262143), PCI 0..503, CI 28 bit (0..268435455), TAC 16 bit + * (0..65535), getBandwidth in kHz (no documented range; LTE channels are 1.4..20 MHz, TS 36.101 §5.6), + * getBands API 30+. + * - CellIdentityNr: NR-ARFCN 0..3279165, PCI 0..1007, NCI 36 bit (0..68719476735, unknown + * = CellInfo.UNAVAILABLE_LONG), TAC 24 bit (0..16777215), getBands API 30+. + * - CellSignalStrengthLte.getTimingAdvance 0..1282; CellSignalStrengthNr.getTimingAdvanceMicros + * (API 34) raw TS 38.213 §4.2 T_A index 0..3846 despite the name. + * - CellInfo.CONNECTION_NONE 0, PRIMARY_SERVING 1, SECONDARY_SERVING 2, UNKNOWN Int.MAX_VALUE. + * + * Band tables: 3GPP TS 36.101 Table 5.7.3-1 (E-UTRA DL EARFCN: F_DL = F_DL_low + 0.1 (N_DL - N_Offs-DL)), + * 3GPP TS 38.104 §5.4.2 tables "NR-ARFCN parameters for the global frequency raster" and "Applicable NR-ARFCN per operating band" (FR1, FR2), + * cross-checked against AOSP `android.telephony.AccessNetworkUtils` / `AccessNetworkConstants` + * (main, 2026-12-01). LTE SDL bands 29, 32, 67, 69, 75, 76 (only carrier aggregation SCells) are + * added from TS 36.101; AOSP leaves them out. + */ + +/** Mirror of `android.telephony.CellInfo.UNAVAILABLE_LONG` (Long.MAX_VALUE). */ +const val CELL_UNAVAILABLE_LONG: Long = Long.MAX_VALUE + +/** At most this many neighbour cells are listed (strongest first). */ +const val CELL_DETAIL_MAX_NEIGHBORS = 16 + +/** Shortest interval between two cell info requests of one SIM. */ +const val CELL_DETAIL_INTERVAL_MS = 5_000L + +/** Mirror of `android.telephony.CellInfo.CONNECTION_*`. */ +object CellConnection { + const val NONE = 0 + const val PRIMARY_SERVING = 1 + const val SECONDARY_SERVING = 2 + const val UNKNOWN = Int.MAX_VALUE +} + +/** Radio of a cell with a full detail. */ +enum class CellTech { LTE, NR } + +/** + * Operating band. [derived] = computed from the ARFCN (the modem did not report `getBands`); + * [ambiguous] = the ARFCN lies in more than one band (NR, e.g. n78 inside n77) and [number] is + * the preferred one. + */ +data class CellBand(val tech: CellTech, val number: Int, val derived: Boolean = false, val ambiguous: Boolean = false) + +// --- Raw readings (mirror of CellInfo* getters, built by the Android layer) -------------------- + +/** Raw getter values of one `CellInfo`, before validation. */ +sealed interface CellInfoReading { + val registered: Boolean + val connectionStatus: Int + + data class Lte( + override val registered: Boolean, + override val connectionStatus: Int, + val earfcn: Int, + val pci: Int, + val ci: Int, + val tac: Int, + val bandwidthKhz: Int, + val bands: List, + val signal: CellStrengthReading.Lte, + val timingAdvance: Int, + ) : CellInfoReading + + data class Nr( + override val registered: Boolean, + override val connectionStatus: Int, + val nrarfcn: Int, + val pci: Int, + val nci: Long, + val tac: Int, + val bands: List, + val signal: CellStrengthReading.Nr, + val timingAdvance: Int, + ) : CellInfoReading + + /** 2G / 3G cell: only its standard is shown (the detail covers LTE and NR). */ + data class Other(override val registered: Boolean, override val connectionStatus: Int, val rat: CellRat) : CellInfoReading +} + +// --- Validated detail --------------------------------------------------------------------------- + +/** + * One serving cell. [primary] = registered / PRIMARY_SERVING (LTE anchor in NSA), otherwise a + * SECONDARY_SERVING cell (NR leg in NSA, LTE carrier aggregation). [downlinkKhz] is the DL centre + * frequency of the ARFCN; [cellId] is the ECI (LTE) or NCI (NR); [timingAdvance] the raw TA + * (LTE 0..1282, NR T_A index 0..3846). + */ +data class ServingCell( + val tech: CellTech, + val primary: Boolean, + val band: CellBand?, + val arfcn: Int?, + val downlinkKhz: Int?, + val pci: Int?, + val cellId: Long?, + val tac: Int?, + val bandwidthKhz: Int?, + val timingAdvance: Int?, + val rsrpDbm: Int?, + val rsrqDb: Int?, + val sinrDb: Int?, +) + +data class NeighborCell(val tech: CellTech, val pci: Int?, val arfcn: Int?, val band: CellBand?, val rsrpDbm: Int?) + +/** + * Detail of one SIM. [otherRat] is set when the registered cell is 2G/3G (no LTE/NR serving cell). + * [neighbors] are sorted strongest first, unique per (tech, ARFCN, PCI), at most [CELL_DETAIL_MAX_NEIGHBORS]. + */ +data class CellDetail(val serving: List, val neighbors: List, val otherRat: CellRat?) { + val isEmpty: Boolean get() = serving.isEmpty() && neighbors.isEmpty() && otherRat == null +} + +// Documented ranges (see file header). +private val LTE_EARFCN = 0..262_143 +private val LTE_PCI = 0..503 +private val LTE_CI = 0..268_435_455 +private val LTE_TAC = 0..65_535 +private val LTE_BANDWIDTH_KHZ = 1_400..20_000 +private val LTE_TA = 0..1_282 +private val NR_ARFCN = 0..3_279_165 +private val NR_PCI = 0..1_007 +private val NR_NCI = 0L..68_719_476_735L +private val NR_TAC = 0..16_777_215 +private val NR_TA = 0..3_846 + +private fun cellLong(raw: Long, range: LongRange): Long? = raw.takeIf { it != CELL_UNAVAILABLE_LONG && it in range } + +// --- Band tables ------------------------------------------------------------------------------- + +/** One E-UTRA band row of TS 36.101 Table 5.7.3-1: DL low edge (kHz) and the DL EARFCN range. */ +private class LteBandRow(val band: Int, val downlinkLowKhz: Int, val first: Int, val last: Int) + +private val LTE_BANDS = listOf( + LteBandRow(1, 2_110_000, 0, 599), LteBandRow(2, 1_930_000, 600, 1_199), + LteBandRow(3, 1_805_000, 1_200, 1_949), LteBandRow(4, 2_110_000, 1_950, 2_399), + LteBandRow(5, 869_000, 2_400, 2_649), LteBandRow(6, 875_000, 2_650, 2_749), + LteBandRow(7, 2_620_000, 2_750, 3_449), LteBandRow(8, 925_000, 3_450, 3_799), + LteBandRow(9, 1_844_900, 3_800, 4_149), LteBandRow(10, 2_110_000, 4_150, 4_749), + LteBandRow(11, 1_475_900, 4_750, 4_949), LteBandRow(12, 729_000, 5_010, 5_179), + LteBandRow(13, 746_000, 5_180, 5_279), LteBandRow(14, 758_000, 5_280, 5_379), + LteBandRow(17, 734_000, 5_730, 5_849), LteBandRow(18, 860_000, 5_850, 5_999), + LteBandRow(19, 875_000, 6_000, 6_149), LteBandRow(20, 791_000, 6_150, 6_449), + LteBandRow(21, 1_495_900, 6_450, 6_599), LteBandRow(22, 3_510_000, 6_600, 7_399), + LteBandRow(23, 2_180_000, 7_500, 7_699), LteBandRow(24, 1_525_000, 7_700, 8_039), + LteBandRow(25, 1_930_000, 8_040, 8_689), LteBandRow(26, 859_000, 8_690, 9_039), + LteBandRow(27, 852_000, 9_040, 9_209), LteBandRow(28, 758_000, 9_210, 9_659), + LteBandRow(29, 717_000, 9_660, 9_769), LteBandRow(30, 2_350_000, 9_770, 9_869), + LteBandRow(31, 462_500, 9_870, 9_919), LteBandRow(32, 1_452_000, 9_920, 10_359), + LteBandRow(33, 1_900_000, 36_000, 36_199), LteBandRow(34, 2_010_000, 36_200, 36_349), + LteBandRow(35, 1_850_000, 36_350, 36_949), LteBandRow(36, 1_930_000, 36_950, 37_549), + LteBandRow(37, 1_910_000, 37_550, 37_749), LteBandRow(38, 2_570_000, 37_750, 38_249), + LteBandRow(39, 1_880_000, 38_250, 38_649), LteBandRow(40, 2_300_000, 38_650, 39_649), + LteBandRow(41, 2_496_000, 39_650, 41_589), LteBandRow(42, 3_400_000, 41_590, 43_589), + LteBandRow(43, 3_600_000, 43_590, 45_589), LteBandRow(44, 703_000, 45_590, 46_589), + LteBandRow(45, 1_447_000, 46_590, 46_789), LteBandRow(46, 5_150_000, 46_790, 54_539), + LteBandRow(47, 5_855_000, 54_540, 55_239), LteBandRow(48, 3_550_000, 55_240, 56_739), + LteBandRow(49, 3_550_000, 56_740, 58_239), LteBandRow(50, 1_432_000, 58_240, 59_089), + LteBandRow(51, 1_427_000, 59_090, 59_139), LteBandRow(52, 3_300_000, 59_140, 60_139), + LteBandRow(53, 2_483_500, 60_140, 60_254), LteBandRow(65, 2_110_000, 65_536, 66_435), + LteBandRow(66, 2_110_000, 66_436, 67_335), LteBandRow(67, 738_000, 67_336, 67_535), + LteBandRow(68, 753_000, 67_536, 67_835), LteBandRow(69, 2_570_000, 67_836, 68_335), + LteBandRow(70, 1_995_000, 68_336, 68_585), LteBandRow(71, 617_000, 68_586, 68_935), + LteBandRow(72, 461_000, 68_936, 68_985), LteBandRow(73, 460_000, 68_986, 69_035), + LteBandRow(74, 1_475_000, 69_036, 69_465), LteBandRow(75, 1_432_000, 69_466, 70_315), + LteBandRow(76, 1_427_000, 70_316, 70_365), LteBandRow(85, 728_000, 70_366, 70_545), + LteBandRow(87, 420_000, 70_546, 70_595), LteBandRow(88, 422_000, 70_596, 70_645), +) + +/** E-UTRA band of a downlink EARFCN (TS 36.101 Table 5.7.3-1); null outside every DL range. */ +fun lteBandForEarfcn(earfcn: Int): Int? = LTE_BANDS.firstOrNull { earfcn in it.first..it.last }?.band + +/** DL centre frequency in kHz: F_DL = F_DL_low + 0.1 MHz × (N_DL − N_Offs-DL); null for no band. */ +fun lteDownlinkKhz(earfcn: Int): Int? = + LTE_BANDS.firstOrNull { earfcn in it.first..it.last }?.let { it.downlinkLowKhz + 100 * (earfcn - it.first) } + +/** + * NR DL NR-ARFCN ranges of TS 38.104 §5.4.2 ("Applicable NR-ARFCN per operating band", FR1 and FR2), in PREFERENCE order: + * where bands overlap, the first row wins (European use first: n1 before n65/n66, n20 before + * n28 before n14, n7/n38 before n41/n90, n75/n76 before n50/n51/n74/n91–n94, n78 before n77/n48). + */ +private val NR_BANDS: List> = listOf( + 1 to 422_000..434_000, 3 to 361_000..376_000, 7 to 524_000..538_000, 8 to 185_000..192_000, + 20 to 158_200..164_200, 28 to 151_600..160_600, 38 to 514_000..524_000, 40 to 460_000..480_000, + 75 to 286_400..303_400, 76 to 285_400..286_400, 78 to 620_000..653_333, 77 to 620_000..680_000, + 79 to 693_334..733_333, 2 to 386_000..398_000, 25 to 386_000..399_000, 5 to 173_800..178_800, + 18 to 172_000..175_000, 26 to 171_800..178_800, 12 to 145_800..149_200, 14 to 151_600..153_600, + 29 to 143_400..145_600, 30 to 470_000..472_000, 34 to 402_000..405_000, 39 to 376_000..384_000, + 41 to 499_200..537_999, 46 to 743_334..795_000, 48 to 636_667..646_666, 50 to 286_400..303_400, + 51 to 285_400..286_400, 53 to 496_700..499_000, 65 to 422_000..440_000, 66 to 422_000..440_000, + 70 to 399_000..404_000, 71 to 123_400..130_400, 74 to 295_000..303_600, 90 to 499_200..538_000, + 91 to 285_400..286_400, 92 to 286_400..303_400, 93 to 285_400..286_400, 94 to 286_400..303_400, + 96 to 795_000..875_000, + 258 to 2_016_667..2_070_832, 257 to 2_054_166..2_104_165, 261 to 2_070_833..2_084_999, + 260 to 2_229_166..2_279_165, +) + +/** Every NR band whose DL NR-ARFCN range contains [nrarfcn], preferred band first (see [NR_BANDS]). */ +fun nrBandsForArfcn(nrarfcn: Int): List = NR_BANDS.filter { nrarfcn in it.second }.map { it.first } + +/** + * NR-ARFCN → frequency in kHz on the global raster (TS 38.104 §5.4.2, "NR-ARFCN parameters for the global frequency raster"): + * F_REF = F_REF-Offs + ΔF_Global × (N_REF − N_REF-Offs); 0..599999: 5 kHz from 0 MHz, + * 600000..2016666: 15 kHz from 3000 MHz, 2016667..3279165: 60 kHz from 24250.08 MHz. + */ +fun nrFrequencyKhz(nrarfcn: Int): Int? = when (nrarfcn) { + in 0..599_999 -> 5 * nrarfcn + in 600_000..2_016_666 -> 3_000_000 + 15 * (nrarfcn - 600_000) + in 2_016_667..3_279_165 -> 24_250_080 + 60 * (nrarfcn - 2_016_667) + else -> null +} + +/** Band of a cell: the first plausible band the modem reported, otherwise derived from the ARFCN. */ +fun cellBand(tech: CellTech, reported: List, arfcn: Int?): CellBand? { + val valid = if (tech == CellTech.LTE) 1..88 else 1..1_024 + reported.firstOrNull { it in valid }?.let { return CellBand(tech, it) } + arfcn ?: return null + return when (tech) { + CellTech.LTE -> lteBandForEarfcn(arfcn)?.let { CellBand(tech, it, derived = true) } + CellTech.NR -> nrBandsForArfcn(arfcn).let { bands -> + bands.firstOrNull()?.let { CellBand(tech, it, derived = true, ambiguous = bands.size > 1) } + } + } +} + +/** LTE ECI = eNB ID (20 bit) × 256 + local cell ID (8 bit). */ +fun lteEnodeb(eci: Long): Long = eci shr 8 + +fun lteLocalCellId(eci: Long): Int = (eci and 0xFF).toInt() + +// --- Building the detail ----------------------------------------------------------------------- + +private fun CellInfoReading.isPrimary(): Boolean = registered || connectionStatus == CellConnection.PRIMARY_SERVING + +private fun CellInfoReading.isServing(): Boolean = isPrimary() || connectionStatus == CellConnection.SECONDARY_SERVING + +private fun servingOf(reading: CellInfoReading): ServingCell? = when (reading) { + is CellInfoReading.Lte -> { + val arfcn = cellValue(reading.earfcn, LTE_EARFCN) + val signal = cellSignalOf(reading.signal) + ServingCell( + tech = CellTech.LTE, primary = reading.isPrimary(), + band = cellBand(CellTech.LTE, reading.bands, arfcn), arfcn = arfcn, downlinkKhz = arfcn?.let(::lteDownlinkKhz), + pci = cellValue(reading.pci, LTE_PCI), cellId = cellValue(reading.ci, LTE_CI)?.toLong(), + tac = cellValue(reading.tac, LTE_TAC), bandwidthKhz = cellValue(reading.bandwidthKhz, LTE_BANDWIDTH_KHZ), + timingAdvance = cellValue(reading.timingAdvance, LTE_TA), + rsrpDbm = signal?.rsrpDbm, rsrqDb = signal?.rsrqDb, sinrDb = signal?.sinrDb, + ) + } + is CellInfoReading.Nr -> { + val arfcn = cellValue(reading.nrarfcn, NR_ARFCN) + val signal = cellSignalOf(reading.signal) + ServingCell( + tech = CellTech.NR, primary = reading.isPrimary(), + band = cellBand(CellTech.NR, reading.bands, arfcn), arfcn = arfcn, downlinkKhz = arfcn?.let(::nrFrequencyKhz), + pci = cellValue(reading.pci, NR_PCI), cellId = cellLong(reading.nci, NR_NCI), + tac = cellValue(reading.tac, NR_TAC), bandwidthKhz = null, + timingAdvance = cellValue(reading.timingAdvance, NR_TA), + rsrpDbm = signal?.rsrpDbm, rsrqDb = signal?.rsrqDb, sinrDb = signal?.sinrDb, + ) + } + is CellInfoReading.Other -> null +} + +private fun neighborOf(reading: CellInfoReading): NeighborCell? { + val cell = when (reading) { + is CellInfoReading.Lte -> cellValue(reading.earfcn, LTE_EARFCN).let { arfcn -> + NeighborCell(CellTech.LTE, cellValue(reading.pci, LTE_PCI), arfcn, cellBand(CellTech.LTE, reading.bands, arfcn), + cellSignalOf(reading.signal)?.rsrpDbm) + } + is CellInfoReading.Nr -> cellValue(reading.nrarfcn, NR_ARFCN).let { arfcn -> + NeighborCell(CellTech.NR, cellValue(reading.pci, NR_PCI), arfcn, cellBand(CellTech.NR, reading.bands, arfcn), + cellSignalOf(reading.signal)?.rsrpDbm) + } + is CellInfoReading.Other -> return null + } + // A neighbour without PCI and ARFCN identifies nothing. + return cell.takeIf { it.pci != null || it.arfcn != null } +} + +/** Strongest first (no RSRP last), then LTE before NR, ARFCN and PCI; duplicates keep the strongest. */ +fun sortNeighbors(cells: List, limit: Int = CELL_DETAIL_MAX_NEIGHBORS): List = + cells.sortedWith( + compareBy { it.rsrpDbm == null } + .thenByDescending { it.rsrpDbm ?: Int.MIN_VALUE } + .thenBy { it.tech } + .thenBy { it.arfcn ?: Int.MAX_VALUE } + .thenBy { it.pci ?: Int.MAX_VALUE }, + ).distinctBy { Triple(it.tech, it.arfcn, it.pci) }.take(limit.coerceAtLeast(0)) + +/** + * Detail of one `requestCellInfoUpdate` answer: serving cells (primary first, then LTE before NR, + * then by ARFCN), neighbours ([sortNeighbors]) and, without an LTE/NR serving cell, the standard + * of a registered 2G/3G cell. + */ +fun cellDetailOf(readings: List): CellDetail { + val serving = readings.filter { it.isServing() }.mapNotNull(::servingOf) + .sortedWith(compareBy { !it.primary }.thenBy { it.tech }.thenBy { it.arfcn ?: Int.MAX_VALUE }) + val neighbors = sortNeighbors(readings.filterNot { it.isServing() }.mapNotNull(::neighborOf)) + val otherRat = if (serving.isEmpty()) { + readings.filterIsInstance().firstOrNull { it.isPrimary() }?.rat + } else null + return CellDetail(serving, neighbors, otherRat) +} + +/** + * Throttle of the refresh loop: which of the [visible] SIMs are due now (last request at least + * [intervalMs] ago, or never) and how long to wait for the next one (≥ 0; [intervalMs] when + * nothing is visible). [lastRequestMs] maps subscription id → time of its last request. + */ +fun cellDetailSchedule(visible: Set, lastRequestMs: Map, nowMs: Long, + intervalMs: Long = CELL_DETAIL_INTERVAL_MS): Pair, Long> { + if (visible.isEmpty()) return emptyList() to intervalMs + val due = visible.filter { id -> lastRequestMs[id]?.let { nowMs - it >= intervalMs || nowMs < it } ?: true }.sorted() + val next = visible.minOf { id -> + if (id in due) intervalMs else (lastRequestMs.getValue(id) + intervalMs - nowMs).coerceIn(0, intervalMs) + } + return due to next +} + +/** + * One refresh pass of the loop: requests every due SIM of [visible] in order. The time of each + * request is read from [clock] right before THAT request (an earlier read of the same pass may + * take seconds), so a SIM read late in the pass is not credited with the pass start time and its + * next request still waits a full [intervalMs] (revize kolo 1). Returns how long to wait for the + * next due SIM (0 when one is already due, [intervalMs] when nothing is visible). + */ +suspend fun cellDetailRefreshPass( + visible: () -> Set, + lastRequestMs: MutableMap, + clock: () -> Long, + intervalMs: Long = CELL_DETAIL_INTERVAL_MS, + request: suspend (Int) -> Unit, +): Long { + val (due, _) = cellDetailSchedule(visible(), lastRequestMs, clock(), intervalMs) + for (id in due) { + if (id !in visible()) continue + val now = clock() + val last = lastRequestMs[id] + if (last != null && now >= last && now - last < intervalMs) continue + lastRequestMs[id] = now + request(id) + } + val now = clock() + val shown = visible() + if (shown.isEmpty()) return intervalMs + return shown.minOf { id -> + lastRequestMs[id]?.let { last -> if (now < last) 0L else (last + intervalMs - now).coerceIn(0, intervalMs) } ?: 0L + } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/ConsentResetGate.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/ConsentResetGate.kt new file mode 100644 index 0000000..8152ffd --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/ConsentResetGate.kt @@ -0,0 +1,35 @@ +package cz.netkit.shared.lan + +/** + * Guards the auto-discovery consent read while a network loads against "forget all consents" + * (zadání 46, revize kolo 2). A load can read the old ALLOWED before the reset deletes it and + * publish it afterwards; the reset itself cannot fix a network that was still loading. Every load + * takes a [loadStarted] stamp; [begin] and [end] of a reset both advance the epoch, so a load that + * overlapped a reset in any way (started before, or started during it) publishes UNKNOWN, which is + * the value the reset leaves anyway. Loads started after the reset publish what they read. + * + * Not thread-safe: the owner (LanDevicesViewModel) uses it on the main thread only. + */ +class ConsentResetGate { + private var epoch = 0 + private var running = 0 + + /** Token for a network load starting now. */ + fun loadStarted(): Int = epoch + + /** A reset starts; call [end] when it finished (also when it failed or was cancelled). */ + fun begin() { + epoch++ + running++ + } + + fun end() { + check(running > 0) { "end() without begin()" } + epoch++ + running-- + } + + /** The consent a load with [stamp] may publish. */ + fun publishable(stamp: Int, loaded: DiscoveryConsent): DiscoveryConsent = + if (stamp != epoch || running > 0) DiscoveryConsent.UNKNOWN else loaded +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsMessage.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsMessage.kt index 1627f6a..75c88e0 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsMessage.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsMessage.kt @@ -121,14 +121,47 @@ fun parseDnsMessage(packet: ByteArray, length: Int = packet.size, maxRecords: In return try { reader.message(maxRecords.coerceIn(0, DNS_MAX_RECORDS)) } catch (_: MalformedDns) { null } } -private class MalformedDns : Exception() +internal class MalformedDns : Exception() -private class DnsReader(private val packet: ByteArray, private val length: Int) { - private fun fail(): Nothing = throw MalformedDns() - private fun u8(index: Int): Int { if (index !in 0 until length) fail(); return packet[index].toInt() and 255 } - private fun u16(index: Int): Int = (u8(index) shl 8) or u8(index + 1) - private fun u32(index: Int): Long = (u16(index).toLong() shl 16) or u16(index + 2).toLong() +internal open class DnsWireReader(protected val packet: ByteArray, protected val length: Int) { + protected fun fail(): Nothing = throw MalformedDns() + protected fun u8(index: Int): Int { if (index !in 0 until length) fail(); return packet[index].toInt() and 255 } + protected fun u16(index: Int): Int = (u8(index) shl 8) or u8(index + 1) + protected fun u32(index: Int): Long = (u16(index).toLong() shl 16) or u16(index + 2).toLong() + /** Returns the name and the offset just after its in-place encoding. */ + fun name(start: Int): Pair { + val labels = ArrayList() + var cursor = start + var next = -1 + var hops = 0 + var wire = 1 + while (true) { + val size = u8(cursor) + when { + size == 0 -> { if (next < 0) next = cursor + 1; break } + size and 0xC0 == 0xC0 -> { + val target = ((size and 0x3F) shl 8) or u8(cursor + 1) + // Strictly backward: every hop moves to a smaller offset, so no cycle can exist. + if (target >= cursor || ++hops > DNS_MAX_POINTER_HOPS) fail() + if (next < 0) next = cursor + 2 + cursor = target + } + size and 0xC0 != 0 -> fail() // 0x40 / 0x80: extended / reserved label types + else -> { + if (cursor + 1 + size > length) fail() + wire += 1 + size + if (wire > DNS_MAX_NAME_BYTES) fail() + labels += packet.decodeToString(cursor + 1, cursor + 1 + size) + cursor += 1 + size + } + } + } + return DnsName(labels) to next + } +} + +private class DnsReader(packet: ByteArray, length: Int) : DnsWireReader(packet, length) { fun message(maxRecords: Int): DnsMessage { val id = u16(0) val flags = u16(2) @@ -190,37 +223,6 @@ private class DnsReader(private val packet: ByteArray, private val length: Int) } else -> DnsRecordData.Other(end - start) } - - /** Returns the name and the offset just after its in-place encoding. */ - fun name(start: Int): Pair { - val labels = ArrayList() - var cursor = start - var next = -1 - var hops = 0 - var wire = 1 - while (true) { - val size = u8(cursor) - when { - size == 0 -> { if (next < 0) next = cursor + 1; break } - size and 0xC0 == 0xC0 -> { - val target = ((size and 0x3F) shl 8) or u8(cursor + 1) - // Strictly backward: every hop moves to a smaller offset, so no cycle can exist. - if (target >= cursor || ++hops > DNS_MAX_POINTER_HOPS) fail() - if (next < 0) next = cursor + 2 - cursor = target - } - size and 0xC0 != 0 -> fail() // 0x40 / 0x80: extended / reserved label types - else -> { - if (cursor + 1 + size > length) fail() - wire += 1 + size - if (wire > DNS_MAX_NAME_BYTES) fail() - labels += packet.decodeToString(cursor + 1, cursor + 1 + size) - cursor += 1 + size - } - } - } - return DnsName(labels) to next - } } private class ByteBuilder { diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRcode.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRcode.kt new file mode 100644 index 0000000..a88cf4d --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRcode.kt @@ -0,0 +1,26 @@ +package cz.netkit.shared.lan + +/** IANA DNS RCODEs. Unassigned values keep their number in the caller's diagnostic. */ +fun dnsRcodeName(code: Int): String? = when (code) { + 0 -> "NOERROR" + 1 -> "FORMERR" + 2 -> "SERVFAIL" + 3 -> "NXDOMAIN" + 4 -> "NOTIMP" + 5 -> "REFUSED" + 6 -> "YXDOMAIN" + 7 -> "YXRRSET" + 8 -> "NXRRSET" + 9 -> "NOTAUTH" + 10 -> "NOTZONE" + 11 -> "DSOTYPENI" + 16 -> "BADVERS/BADSIG" + 17 -> "BADKEY" + 18 -> "BADTIME" + 19 -> "BADMODE" + 20 -> "BADNAME" + 21 -> "BADALG" + 22 -> "BADTRUNC" + 23 -> "BADCOOKIE" + else -> null +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRecords.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRecords.kt new file mode 100644 index 0000000..256525f --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRecords.kt @@ -0,0 +1,103 @@ +package cz.netkit.shared.lan + +import cz.netkit.shared.publicip.ipv6Text +import cz.netkit.shared.publicip.parseIp + +enum class RecordType(val code: Int) { + A(1), AAAA(28), CNAME(5), MX(15), NS(2), TXT(16), SOA(6), PTR(12), SRV(33), CAA(257) +} + +/** A PTR lookup accepts either the reverse owner name or a numeric address, including IPv6. */ +fun recordQueryName(input: String, type: RecordType): String? { + val value = input.trim() + if (type == RecordType.PTR) parseIp(value)?.let { ip -> + return if (ip.words.size == 2) ip.text().split('.').reversed().joinToString(".") + ".in-addr.arpa" + else ip.words.joinToString("") { it.toString(16).padStart(4, '0') }.reversed().toList().joinToString(".") + ".ip6.arpa" + } + if (value == ".") return value + if (value.length > 254 || !value.all { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it in "._-" }) return null + return dnsName(value)?.let { value } +} + +data class RecordAnswer(val owner: String, val type: Int, val ttl: Long, val value: String) +data class RecordReply(val rcode: Int, val flags: Int, val records: List) + +/** Strict unicast response. Read all declared sections, or reject the packet as a whole. */ +fun parseRecordReply(packet: ByteArray): RecordReply? { + if (packet.size !in 12..65535) return null + return try { RecordReader(packet).reply() } catch (_: MalformedDns) { null } +} + +private class RecordReader(bytes: ByteArray) : DnsWireReader(bytes, bytes.size) { + private fun displayName(value: DnsName) = sanitizeLanText(value.text.ifEmpty { "." }) + private fun exactName(start: Int, end: Int): String { + val (target, next) = name(start) + if (next != end) fail() + return displayName(target) + } + + fun reply(): RecordReply { + val flags = u16(2) + val count = u16(6) + u16(8) + u16(10) + if (flags and 0xf800 != 0x8000 || u16(4) > DNS_MAX_QUESTIONS || count > DNS_MAX_RECORDS) fail() + var cursor = 12 + repeat(u16(4)) { + cursor = name(cursor).second + 4 + if (cursor > length) fail() + } + var rcode = flags and 15 + val records = List(count) { + val (owner, next) = name(cursor) + val type = u16(next) + val ttl = u32(next + 4) + val start = next + 10 + cursor = start + u16(next + 8) + if (cursor > length) fail() + if (type == 41) rcode = ((ttl ushr 24).toInt() shl 4) or (flags and 15) + RecordAnswer(displayName(owner), type, ttl, data(type, start, cursor)) + } + if (cursor != length) fail() + return RecordReply(rcode, flags, records) + } + + private fun data(type: Int, start: Int, end: Int): String { + val size = end - start + return when (type) { + 1 -> { + if (size != 4) fail() + (start until end).joinToString(".") { u8(it).toString() } + } + 28 -> { + if (size != 16) fail() + ipv6Text(List(8) { u16(start + it * 2) }) + } + 2, 5, 12 -> exactName(start, end) + 15 -> "${u16(start)} ${exactName(start + 2, end)}" + 33 -> "${u16(start)} ${u16(start + 2)} ${u16(start + 4)} ${exactName(start + 6, end)}" + 6 -> { + val (ns, second) = name(start) + val (mailbox, fields) = name(second) + if (fields + 20 != end) fail() + val numbers = List(5) { u32(fields + it * 4) } + "${displayName(ns)} ${displayName(mailbox)} ${numbers.joinToString(" ")}" + } + 16 -> buildString { + var cursor = start + while (cursor < end) { + val next = cursor + 1 + u8(cursor) + if (next > end) fail() + if (isNotEmpty()) append(' ') + append('"').append(sanitizeLanText(packet.decodeToString(cursor + 1, next))).append('"') + cursor = next + } + } + 257 -> { + if (size < 3) fail() + val value = start + 2 + u8(start + 1) + if (value <= start + 2 || value > end) fail() + "${u8(start)} ${sanitizeLanText(packet.decodeToString(start + 2, value))} ${sanitizeLanText(packet.decodeToString(value, end), size)}" + } + else -> (start until end).joinToString("") { u8(it).toString(16).padStart(2, '0') } + } + } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/IcmpEcho.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/IcmpEcho.kt index 02f7038..f1547a7 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/IcmpEcho.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/IcmpEcho.kt @@ -4,10 +4,32 @@ package cz.netkit.shared.lan * Match an IPv4 ICMP datagram reply without an IP header. Linux ping sockets own * identifier/checksum; sequence and the entire nonce payload must match our request. */ -fun matchesIcmpEchoReply(request: ByteArray, reply: ByteArray, receivedBytes: Int): Boolean { - // Require data beyond the 8-byte header so matching never loses the nonce. - if (request.size <= 8 || request[0] != 8.toByte() || request[1] != 0.toByte()) return false +fun matchesIcmpEchoReply(request: ByteArray, reply: ByteArray, receivedBytes: Int): Boolean = + matchesIcmpEchoReply(request, reply, receivedBytes, allowEmptyPayload = false) + +/** With an explicitly empty payload the connected ping socket and randomized sequence identify the reply. */ +fun matchesIcmpEchoReply(request: ByteArray, reply: ByteArray, receivedBytes: Int, allowEmptyPayload: Boolean): Boolean { + val minimum = if (allowEmptyPayload) 8 else 9 + if (request.size < minimum || request[0] != 8.toByte() || request[1] != 0.toByte()) return false if (receivedBytes != request.size || receivedBytes > reply.size) return false if (reply[0] != 0.toByte() || reply[1] != 0.toByte()) return false return (6 until request.size).all { reply[it] == request[it] } } + +/** ICMPv6 Echo Request type (RFC 4443 4.1). */ +const val ICMPV6_ECHO_REQUEST = 128 +/** ICMPv6 Echo Reply type (RFC 4443 4.2). */ +const val ICMPV6_ECHO_REPLY = 129 + +/** + * ICMPv6 variant of [matchesIcmpEchoReply] for an `IPPROTO_ICMPV6` datagram (ping) socket: the + * kernel owns identifier and checksum; type 129/code 0, same length, and sequence + payload + * equal to our type 128 request. + */ +fun matchesIcmpv6EchoReply(request: ByteArray, reply: ByteArray, receivedBytes: Int, allowEmptyPayload: Boolean = false): Boolean { + val minimum = if (allowEmptyPayload) 8 else 9 + if (request.size < minimum || request[0] != ICMPV6_ECHO_REQUEST.toByte() || request[1] != 0.toByte()) return false + if (receivedBytes != request.size || receivedBytes > reply.size) return false + if (reply[0] != ICMPV6_ECHO_REPLY.toByte() || reply[1] != 0.toByte()) return false + return (6 until request.size).all { reply[it] == request[it] } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/Ipv6.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/Ipv6.kt new file mode 100644 index 0000000..0cf768e --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/Ipv6.kt @@ -0,0 +1,167 @@ +package cz.netkit.shared.lan + +import cz.netkit.shared.net.ipv6Bytes + +/* + * IPv6 literals for the LAN tools (zadání 39 §2.3): parsing, classification and prefix checks in + * pure Kotlin, never DNS and never java.net. The strict parser itself is shared with + * cz.netkit.shared.net (RFC 4291 text forms, brackets, zone, embedded IPv4). + */ + +/** Scope of an IPv6 address as the tools treat it; the order is not meaningful. */ +enum class Ipv6Scope { + /** `::` */ + UNSPECIFIED, + /** `::1` */ + LOOPBACK, + /** `::ffff:a.b.c.d`; the tools use the embedded IPv4 instead. */ + IPV4_MAPPED, + /** `fe80::/10` */ + LINK_LOCAL, + /** Unique local `fc00::/7` (ULA). */ + UNIQUE_LOCAL, + /** `ff00::/8` */ + MULTICAST, + /** `2001:db8::/32` (RFC 3849): never a real target. */ + DOCUMENTATION, + /** Everything else, including global unicast. */ + GLOBAL, +} + +/** A parsed IPv6 address: 16 [bytes] and an optional [zone] (`%wlan0`) exactly as typed. */ +class Ipv6Address private constructor(private val octets: ByteArray, val zone: String?) { + val bytes: ByteArray get() = octets.copyOf() + + val scope: Ipv6Scope get() = when { + (0 until 16).all { octets[it].toInt() == 0 } -> Ipv6Scope.UNSPECIFIED + (0 until 15).all { octets[it].toInt() == 0 } && octets[15].toInt() == 1 -> Ipv6Scope.LOOPBACK + (0 until 10).all { octets[it].toInt() == 0 } && u8(10) == 0xff && u8(11) == 0xff -> Ipv6Scope.IPV4_MAPPED + u8(0) == 0xfe && u8(1) and 0xc0 == 0x80 -> Ipv6Scope.LINK_LOCAL + u8(0) and 0xfe == 0xfc -> Ipv6Scope.UNIQUE_LOCAL + u8(0) == 0xff -> Ipv6Scope.MULTICAST + u8(0) == 0x20 && u8(1) == 0x01 && u8(2) == 0x0d && u8(3) == 0xb8 -> Ipv6Scope.DOCUMENTATION + else -> Ipv6Scope.GLOBAL + } + + /** Embedded IPv4 of an [Ipv6Scope.IPV4_MAPPED] address, otherwise null. */ + val mappedIpv4: String? get() = if (scope == Ipv6Scope.IPV4_MAPPED) (12 until 16).joinToString(".") { u8(it).toString() } else null + + /** RFC 5952 text: lower case, leading zeros dropped, the longest run (≥ 2) of zero groups as `::`; no zone. */ + val canonical: String get() { + val groups = IntArray(8) { (u8(it * 2) shl 8) or u8(it * 2 + 1) } + var bestStart = -1; var bestLength = 0; var index = 0 + while (index < 8) { + if (groups[index] != 0) { index++; continue } + val start = index + while (index < 8 && groups[index] == 0) index++ + if (index - start > bestLength) { bestStart = start; bestLength = index - start } + } + if (bestLength < 2) return groups.joinToString(":") { it.toString(16) } + val head = (0 until bestStart).joinToString(":") { groups[it].toString(16) } + val tail = (bestStart + bestLength until 8).joinToString(":") { groups[it].toString(16) } + return "$head::$tail" + } + + /** [canonical] plus `%zone` when one was given. */ + override fun toString(): String = canonical + (zone?.let { "%$it" } ?: "") + override fun equals(other: Any?): Boolean = other is Ipv6Address && octets.contentEquals(other.octets) && zone == other.zone + override fun hashCode(): Int = octets.contentHashCode() * 31 + (zone?.hashCode() ?: 0) + + private fun u8(index: Int): Int = octets[index].toInt() and 0xff + + companion object { + /** + * Strict literal (optionally in brackets, optionally with a zone of 1–15 ASCII letters, + * digits, `.`, `-` or `_`); null for anything else, a hostname included. + */ + fun parse(input: String): Ipv6Address? { + val text = input.trim() + if (text.length > 64) return null + val bytes = ipv6Bytes(text) ?: return null + val inner = text.removePrefix("[").removeSuffix("]") + val zone = inner.substringAfter('%', "").takeIf { '%' in inner } + if (zone != null && (zone.length !in 1..15 || zone.any { !(it.isAsciiLetterOrDigit() || it in "._-") })) return null + return Ipv6Address(bytes, zone) + } + internal fun of(bytes: ByteArray, zone: String? = null): Ipv6Address { + require(bytes.size == 16) + return Ipv6Address(bytes.copyOf(), zone) + } + } +} + +private fun Char.isAsciiLetterOrDigit() = this in 'a'..'z' || this in 'A'..'Z' || this in '0'..'9' + +/** An IPv6 prefix such as an on-link `2001:db8:1::/64` of the active Wi-Fi. */ +data class Ipv6Prefix(val network: Ipv6Address, val length: Int) { + init { require(length in 0..128) } + fun contains(address: Ipv6Address): Boolean { + val a = network.bytes; val b = address.bytes + val full = length / 8; val rest = length % 8 + if ((0 until full).any { a[it] != b[it] }) return false + if (rest == 0) return true + val mask = (0xff shl (8 - rest)) and 0xff + return (a[full].toInt() and mask) == (b[full].toInt() and mask) + } + override fun toString(): String = "${network.canonical}/$length" + companion object { + /** `addr/len`; the address is masked to the prefix. */ + fun parse(input: String): Ipv6Prefix? { + val parts = input.trim().split('/') + if (parts.size != 2 || parts[1].isEmpty() || parts[1].length > 3 || parts[1].any { it !in '0'..'9' }) return null + val length = parts[1].toInt().takeIf { it in 0..128 } ?: return null + val address = Ipv6Address.parse(parts[0])?.takeIf { it.zone == null } ?: return null + val bytes = address.bytes + for (index in 0 until 16) { + val keep = (length - index * 8).coerceIn(0, 8) + bytes[index] = (bytes[index].toInt() and ((0xff shl (8 - keep)) and 0xff)).toByte() + } + return Ipv6Prefix(Ipv6Address.of(bytes), length) + } + } +} + +/** Numeric target of a LAN tool: IPv4 dotted quad or an IPv6 literal; never DNS. */ +sealed interface LanNumericAddress { + /** Address text the tools store and show: dotted IPv4, or canonical IPv6 with its zone. */ + val text: String + data class V4(override val text: String) : LanNumericAddress + data class V6(val address: Ipv6Address) : LanNumericAddress { override val text: String get() = address.toString() } +} + +/** IPv4 first; an IPv4-mapped IPv6 literal becomes its IPv4. Null for a hostname or an invalid literal. */ +fun lanNumericAddress(input: String): LanNumericAddress? { + val text = input.trim() + if (ipv4Number(text) != null) return LanNumericAddress.V4(text) + val v6 = Ipv6Address.parse(text) ?: return null + v6.mappedIpv4?.let { return LanNumericAddress.V4(it) } + return LanNumericAddress.V6(v6) +} + +/** A hostname (no DNS here) or a numeric IPv4/IPv6 literal acceptable as a single tool target. */ +fun validLanTarget(host: String): Boolean { + val text = host.trim() + if (text.isEmpty() || text.length > 253) return false + val numeric = lanNumericAddress(text) + if (numeric is LanNumericAddress.V6) { + // Unspecified and multicast are never a single host. + return numeric.address.scope !in setOf(Ipv6Scope.UNSPECIFIED, Ipv6Scope.MULTICAST) + } + return numeric != null || validLanHost(text) +} + +/** + * Confirmation reasons for one IPv6 target, matching the IPv4 rules: link-local addresses and + * ULA/global addresses inside an on-link prefix of the active Wi-Fi ([own]) run without a + * question; everything else is OUTSIDE_WIFI, and anything that is not link-local, ULA or + * loopback is also NON_PRIVATE_ADDRESS. [portCount] above 254 adds LARGE_PORT_SET. + */ +fun ipv6TargetConfirmationReasons(target: Ipv6Address, own: List?, portCount: Int = 0): Set = buildSet { + val scope = target.scope + val onLink = scope == Ipv6Scope.LINK_LOCAL || + // Documentation space behaves like global unicast (test networks use it as their prefix). + (own != null && scope in setOf(Ipv6Scope.UNIQUE_LOCAL, Ipv6Scope.GLOBAL, Ipv6Scope.DOCUMENTATION) && own.any { it.contains(target) }) + if (!onLink) add(TargetConfirmationReason.OUTSIDE_WIFI) + if (scope !in setOf(Ipv6Scope.LINK_LOCAL, Ipv6Scope.UNIQUE_LOCAL, Ipv6Scope.LOOPBACK)) add(TargetConfirmationReason.NON_PRIVATE_ADDRESS) + if (portCount > 254) add(TargetConfirmationReason.LARGE_PORT_SET) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDeviceExport.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDeviceExport.kt new file mode 100644 index 0000000..bea1a90 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDeviceExport.kt @@ -0,0 +1,131 @@ +package cz.netkit.shared.lan + +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +/* + * Zadání 47 §3: export of the "Zařízení" list as TXT, CSV or JSON, sanitized like the LAN export + * (every text through sanitizeLanText, CSV cells guarded against spreadsheet formulas). Names, + * banners and UPnP fields come from other devices on the network and are untrusted. + */ + +const val LAN_DEVICES_EXPORT_FORMAT = "netkit-lan-devices" +const val LAN_DEVICES_EXPORT_VERSION = 1 +private const val FIELD_MAX = 128 +private const val BANNER_MAX = 256 + +@Serializable +data class LanDeviceExportPort(val port: Int, val service: String, val banner: String? = null) + +/** One exported device; [lastSeenAgoS] is relative to the export time (the list has no wall clock). */ +@Serializable +data class LanDeviceExportRow( + val address: String, + val name: String?, + val nameSource: String?, + val netbios: String?, + val mdns: String?, + val ptr: String?, + val netbiosGroup: String?, + val mac: String?, + val gateway: Boolean, + val self: Boolean, + val method: String, + val rttMs: Double?, + val stale: Boolean, + val lastSeenAgoS: Long, + val openPorts: List, + val mdnsServices: List, + val upnpName: String?, + val upnpManufacturer: String?, + val upnpModel: String?, +) + +@Serializable +data class LanDevicesExportDocument( + val format: String = LAN_DEVICES_EXPORT_FORMAT, + val version: Int = LAN_DEVICES_EXPORT_VERSION, + val exportedAt: String, + val network: String?, + val devices: List, +) + +private val CSV_HEADER = listOf("address", "name", "nameSource", "netbios", "mdns", "ptr", "netbiosGroup", "mac", "gateway", "self", + "method", "rttMs", "stale", "lastSeenAgoS", "openPorts", "mdnsServices", "upnpName", "upnpManufacturer", "upnpModel") + +/** Sanitized rows in list order (gateway first, then numeric IPv4). */ +fun lanDeviceExportRows(devices: List, nowElapsedMs: Long): List = sortLanDevices(devices).map { d -> + fun text(value: String?, max: Int = FIELD_MAX) = value?.let { sanitizeLanText(it, max).trim() }?.ifEmpty { null } + fun name(source: LanNameSource) = text(d.names.firstOrNull { it.source == source }?.value) + val display = d.displayName + LanDeviceExportRow( + address = d.address, + name = text(display.text).takeIf { display.source != null }, + nameSource = display.source?.name?.lowercase(), + netbios = name(LanNameSource.NETBIOS), + mdns = name(LanNameSource.MDNS), + ptr = name(LanNameSource.PTR), + netbiosGroup = text(d.netBiosGroup), + mac = d.netBiosMac?.let { cz.netkit.shared.wol.parseMac(it)?.toString() }, + gateway = d.isGateway, + self = d.isSelf, + method = d.method.name.lowercase(), + rttMs = d.lastRttMs?.takeIf { it.isFinite() && it >= 0 }?.let { kotlin.math.round(it * 10) / 10 }, + stale = d.stale, + lastSeenAgoS = ((nowElapsedMs - d.lastSeenElapsedMs).coerceAtLeast(0)) / 1000, + openPorts = d.openPorts.map { LanDeviceExportPort(it.port, text(it.service) ?: "", text(it.banner, BANNER_MAX)) }, + mdnsServices = d.mdnsServices.mapNotNull { text(it) }, + upnpName = text(d.upnp?.friendlyName), + upnpManufacturer = text(d.upnp?.manufacturer), + upnpModel = listOfNotNull(text(d.upnp?.modelName), text(d.upnp?.modelNumber)).joinToString(" ").ifEmpty { null }, + ) +} + +private val exportJson = Json { prettyPrint = true; encodeDefaults = true } + +/** + * Export text. [exportedAt] is an ISO time from the caller (wall clock); [network] an optional + * network label (e.g. `192.168.1.0/24`), never the SSID. + */ +fun exportLanDevices(devices: List, format: LanExport, nowElapsedMs: Long, exportedAt: String, network: String? = null): String { + val rows = lanDeviceExportRows(devices, nowElapsedMs) + val label = network?.let { sanitizeLanText(it, 64).trim() }?.ifEmpty { null } + return when (format) { + LanExport.JSON -> exportJson.encodeToString(LanDevicesExportDocument.serializer(), + LanDevicesExportDocument(exportedAt = exportedAt, network = label, devices = rows)) + LanExport.CSV -> (listOf(CSV_HEADER.joinToString(",")) + rows.map { r -> + listOf(r.address, r.name.orEmpty(), r.nameSource.orEmpty(), r.netbios.orEmpty(), r.mdns.orEmpty(), r.ptr.orEmpty(), + r.netbiosGroup.orEmpty(), r.mac.orEmpty(), r.gateway.toString(), r.self.toString(), r.method, r.rttMs?.toString().orEmpty(), + r.stale.toString(), r.lastSeenAgoS.toString(), r.openPorts.joinToString(" ") { "${it.port}/${it.service}" }, + r.mdnsServices.joinToString(" "), r.upnpName.orEmpty(), r.upnpManufacturer.orEmpty(), r.upnpModel.orEmpty()) + .joinToString(",", transform = ::deviceCsvCell) + }).joinToString("\n") + "\n" + LanExport.TEXT -> buildString { + append("NetKit devices · ").append(exportedAt) + label?.let { append(" · ").append(it) } + append('\n') + rows.forEach { r -> + append('\n') + append(listOfNotNull(r.address, r.name, "gateway".takeIf { r.gateway }, "self".takeIf { r.self }, "stale".takeIf { r.stale }) + .joinToString(" · ")).append('\n') + fun field(key: String, value: String?) { if (!value.isNullOrEmpty()) append(" ").append(key).append(": ").append(value).append('\n') } + field("method", r.method + (r.rttMs?.let { " · $it ms" } ?: "")) + field("netbios", listOfNotNull(r.netbios, r.netbiosGroup).joinToString(" / ")) + field("mdns", r.mdns) + field("ptr", r.ptr) + field("mac", r.mac) + field("ports", r.openPorts.joinToString(", ") { "${it.port}/${it.service}" }) + r.openPorts.filter { it.banner != null }.forEach { field("banner ${it.port}", it.banner) } + field("services", r.mdnsServices.joinToString(", ")) + field("upnp", listOfNotNull(r.upnpName, r.upnpManufacturer, r.upnpModel).joinToString(" · ")) + field("lastSeen", "${r.lastSeenAgoS} s") + } + } + } +} + +private fun deviceCsvCell(value: String): String { + // Same guard as the LAN export: untrusted names must not become spreadsheet formulas. + val safe = if (value.trimStart().firstOrNull() in listOf('=', '+', '-', '@')) "'" + value else value + return "\"${safe.replace("\"", "\"\"")}\"" +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDevices.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDevices.kt index 98cb3d7..4920a73 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDevices.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDevices.kt @@ -44,6 +44,8 @@ data class LanDevice( val mdnsServices: List = emptyList(), /** SSDP reply and, if fetched, the UPnP device description; null = no SSDP reply seen. */ val upnp: LanUpnpInfo? = null, + /** MAC from the NetBIOS node status UNIT_ID (unicast, non-zero); only a suggestion for "Add to WoL". */ + val netBiosMac: String? = null, ) { init { require(ipv4Number(address) != null) } /** Display text and its source; source null means the IPv4 address itself. */ @@ -106,11 +108,13 @@ fun upsertLanDevice( } /** Merge late-arriving names (PTR, NetBIOS, mDNS). Unknown address: unchanged. */ -fun updateLanDeviceNames(devices: List, address: String, names: List, netBiosGroup: String? = null): List = +fun updateLanDeviceNames(devices: List, address: String, names: List, netBiosGroup: String? = null, + netBiosMac: String? = null): List = devices.map { device -> if (device.address != address) device else device.copy(names = mergeLanDeviceNames(device.names, names), - netBiosGroup = netBiosGroup?.let { sanitizeLanText(it, LAN_DEVICE_NAME_MAX).trim().ifEmpty { null } } ?: device.netBiosGroup) + netBiosGroup = netBiosGroup?.let { sanitizeLanText(it, LAN_DEVICE_NAME_MAX).trim().ifEmpty { null } } ?: device.netBiosGroup, + netBiosMac = netBiosMac?.let { cz.netkit.shared.wol.parseMac(it)?.toString() } ?: device.netBiosMac) } /** A reply from live ping in the detail: refresh RTT and lastSeen without a full scan. */ diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDomain.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDomain.kt index 61052ba..3e2d2fc 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDomain.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDomain.kt @@ -1,6 +1,7 @@ package cz.netkit.shared.lan import kotlinx.serialization.Serializable +import kotlinx.serialization.Transient import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json @@ -46,7 +47,7 @@ fun isLocalAddress(ip: String): Boolean { /** Whole range must be within one allowed block, not merely its first address. */ fun requiresScanConfirmation(range: Ipv4Subnet, own: Ipv4Subnet?): Boolean = requiresTargetConfirmation(range, own) -val commonPorts: List = listOf(7,9,13,21,22,23,25,37,53,79,80,81,88,110,111,113,119,123,135,137,138,139,143,161,179,389,427,443,445,465,500,512,513,514,515,548,554,587,631,636,873,902,989,990,993,995,1025,1080,1194,1433,1434,1521,1701,1723,1883,1900,2049,2082,2083,2086,2087,2181,2222,2375,2376,2483,2484,3000,3128,3268,3306,3389,3690,4369,5000,5001,5060,5222,5432,5672,5900,5985,5986,6379,6443,6667,7001,8000,8008,8080,8081,8088,8090,8443,8883,8888,9000,9090,9100,9200,9418,9999,10000,11211,27017) +val commonPorts: List = listOf(7,9,13,21,22,23,25,37,53,79,80,81,88,110,111,113,119,123,135,137,138,139,143,161,179,389,427,443,445,465,500,512,513,514,515,548,554,587,631,636,830,873,902,989,990,993,995,1025,1080,1194,1433,1434,1521,1701,1723,1883,1900,2049,2082,2083,2086,2087,2181,2222,2375,2376,2483,2484,3000,3128,3268,3306,3389,3690,4369,5000,5001,5060,5222,5432,5672,5900,5985,5986,6379,6443,6667,7001,8000,8008,8080,8081,8088,8090,8291,8443,8728,8729,8883,8888,9000,9090,9100,9200,9418,9999,10000,10443,11211,27017) fun parsePorts(input: String, maximum: Int = 4096): List? { val result = mutableSetOf() for (piece in input.split(',')) { @@ -60,7 +61,7 @@ fun parsePorts(input: String, maximum: Int = 4096): List? { } return result.sorted() } -fun portService(port: Int): String = mapOf(21 to "FTP",22 to "SSH",23 to "Telnet",25 to "SMTP",53 to "DNS",80 to "HTTP",110 to "POP3",123 to "NTP",139 to "NetBIOS",143 to "IMAP",161 to "SNMP",389 to "LDAP",443 to "HTTPS",445 to "SMB",465 to "SMTPS",587 to "SMTP",631 to "IPP",636 to "LDAPS",873 to "rsync",993 to "IMAPS",995 to "POP3S",1883 to "MQTT",2049 to "NFS",2375 to "Docker",3306 to "MySQL",3389 to "RDP",5432 to "PostgreSQL",5900 to "VNC",6379 to "Redis",8080 to "HTTP-alt",8443 to "HTTPS-alt",9100 to "Printing")[port].orEmpty() +fun portService(port: Int): String = mapOf(21 to "FTP",22 to "SSH",23 to "Telnet",25 to "SMTP",53 to "DNS",80 to "HTTP",110 to "POP3",123 to "NTP",139 to "NetBIOS",143 to "IMAP",161 to "SNMP",389 to "LDAP",443 to "HTTPS",445 to "SMB",465 to "SMTPS",587 to "SMTP",631 to "IPP",636 to "LDAPS",830 to "NETCONF",873 to "rsync",993 to "IMAPS",995 to "POP3S",1883 to "MQTT",2049 to "NFS",2375 to "Docker",3306 to "MySQL",3389 to "RDP",5432 to "PostgreSQL",5900 to "VNC",6379 to "Redis",8080 to "HTTP-alt",8291 to "Winbox",8443 to "HTTPS-alt",8728 to "RouterOS API",8729 to "RouterOS API-SSL",10443 to "HTTPS-alt",9100 to "Printing")[port].orEmpty() data class PingReply(val milliseconds: Double?, val hop: String? = null, val ttlExceeded: Boolean = false) /** Tolerates iputils/toybox text and malformed/unsupported output without claiming a reply. */ @@ -84,10 +85,27 @@ fun pingStatistics(samples: List): PingStatistics { valid.minOrNull(), valid.takeIf { it.isNotEmpty() }?.average(), valid.maxOrNull(), differences.takeIf { it.isNotEmpty() }?.average()) } @Serializable -data class LanResult(val address: String, val name: String = "", val method: String = "", val milliseconds: Double? = null, val port: Int? = null, val detail: String = "", val sequence: Long? = null, val elapsedMs: Long? = null, val routeMayBeOutsideWifi: Boolean = false) +data class LanResult( + val address: String, + val name: String = "", + val method: String = "", + val milliseconds: Double? = null, + val port: Int? = null, + val detail: String = "", + val sequence: Long? = null, + val elapsedMs: Long? = null, + val routeMayBeOutsideWifi: Boolean = false, + // Exports describe the failure in the existing detail column. + @Transient val dfTooLarge: Boolean = false, +) enum class LanExport { TEXT, CSV, JSON } fun exportLan(results: List, format: LanExport): String { - val rows = results.map { row -> row.copy(milliseconds = row.milliseconds?.let { kotlin.math.round(it * 1000.0) / 1000.0 }) } + val rows = results.map { row -> + row.copy( + milliseconds = row.milliseconds?.let { kotlin.math.round(it * 1000.0) / 1000.0 }, + detail = if (row.dfTooLarge) "Packet too large with DF set" else row.detail, + ) + } return when(format) { LanExport.JSON -> Json { prettyPrint = true; encodeDefaults = true }.encodeToString(rows) LanExport.CSV -> "address,name,method,milliseconds,port,detail,sequence,elapsedMs,routeMayBeOutsideWifi\n" + rows.joinToString("\n") { row -> diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanNetworkInfo.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanNetworkInfo.kt new file mode 100644 index 0000000..70926b4 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanNetworkInfo.kt @@ -0,0 +1,81 @@ +package cz.netkit.shared.lan + +/* + * "Info o síti" (zadání 39 §2.2): what the system already knows about the Wi-Fi link, shown as + * rows. Pure data from LinkProperties; reading it sends no packet. + */ + +/** + * Raw link facts. [dhcpServer] is null both when Android does not expose it ([dhcpServerSupported] + * false, API < 30) and when the lease has none (static address). [mtu] 0 means "not set by the + * network" (LinkProperties.getMtu). [ipv6] holds `address/prefixLength` strings as reported. + */ +data class LanNetworkInfo( + val interfaceName: String?, + val ipv4: String?, + val ipv4Prefix: Int?, + val gateways: List, + val dnsServers: List, + val searchDomains: String?, + val dhcpServerSupported: Boolean, + val dhcpServer: String?, + val mtu: Int, + val ipv6: List, +) + +enum class LanNetworkInfoField { INTERFACE, IPV4, GATEWAY, DNS, DOMAINS, DHCP, MTU, IPV6_GLOBAL, IPV6_ULA, IPV6_LINK_LOCAL } + +/** How a row is filled; the UI turns the non-value states into localized text. */ +enum class LanNetworkInfoValue { VALUES, NONE, UNKNOWN, UNAVAILABLE } + +/** One row; [values] are already sanitized, deduplicated, bounded and in monospace-ready form. */ +data class LanNetworkInfoRow(val field: LanNetworkInfoField, val state: LanNetworkInfoValue, val values: List = emptyList()) + +/** At most this many values per row; a hostile DHCP/RA server cannot flood the card. */ +const val LAN_NETWORK_INFO_MAX_VALUES = 8 + +/** + * Rows in a fixed order. IPv6 addresses are grouped by scope (global, ULA, link-local) and shown + * in canonical form with the prefix; an unparsable entry is dropped, never shown raw. IPv6 rows + * without an address are omitted, the other rows always appear (NONE / UNKNOWN / UNAVAILABLE). + */ +fun lanNetworkInfoRows(info: LanNetworkInfo): List { + fun row(field: LanNetworkInfoField, values: List, empty: LanNetworkInfoValue = LanNetworkInfoValue.NONE): LanNetworkInfoRow { + val clean = values.map { sanitizeLanText(it.trim(), 128) }.filter(String::isNotEmpty).distinct().take(LAN_NETWORK_INFO_MAX_VALUES) + return if (clean.isEmpty()) LanNetworkInfoRow(field, empty) else LanNetworkInfoRow(field, LanNetworkInfoValue.VALUES, clean) + } + val ipv4 = info.ipv4?.takeIf { ipv4Number(it) != null }?.let { address -> address + (info.ipv4Prefix?.takeIf { it in 0..32 }?.let { "/$it" } ?: "") } + val v6 = info.ipv6.mapNotNull(::ipv6WithPrefix) + fun scoped(vararg scopes: Ipv6Scope) = v6.filter { it.first.scope in scopes }.map { (address, length) -> "${address.canonical}/$length" } + val domains = info.searchDomains.orEmpty().split(' ', ',', '\t', '\n').filter(String::isNotEmpty) + return buildList { + add(row(LanNetworkInfoField.INTERFACE, listOfNotNull(info.interfaceName), LanNetworkInfoValue.UNKNOWN)) + add(row(LanNetworkInfoField.IPV4, listOfNotNull(ipv4))) + add(row(LanNetworkInfoField.GATEWAY, info.gateways.mapNotNull(::numericText))) + add(row(LanNetworkInfoField.DNS, info.dnsServers.mapNotNull(::numericText))) + add(row(LanNetworkInfoField.DOMAINS, domains.filter { safePtrName(it) != null })) + add(if (!info.dhcpServerSupported) LanNetworkInfoRow(LanNetworkInfoField.DHCP, LanNetworkInfoValue.UNAVAILABLE) + else row(LanNetworkInfoField.DHCP, listOfNotNull(info.dhcpServer?.takeIf { ipv4Number(it) != null && it != "0.0.0.0" }))) + add(if (info.mtu > 0) LanNetworkInfoRow(LanNetworkInfoField.MTU, LanNetworkInfoValue.VALUES, listOf(info.mtu.toString())) + else LanNetworkInfoRow(LanNetworkInfoField.MTU, LanNetworkInfoValue.UNKNOWN)) + listOf(LanNetworkInfoField.IPV6_GLOBAL to scoped(Ipv6Scope.GLOBAL, Ipv6Scope.DOCUMENTATION), + LanNetworkInfoField.IPV6_ULA to scoped(Ipv6Scope.UNIQUE_LOCAL), + LanNetworkInfoField.IPV6_LINK_LOCAL to scoped(Ipv6Scope.LINK_LOCAL)) + .filter { it.second.isNotEmpty() }.forEach { (field, values) -> add(row(field, values)) } + } +} + +/** Numeric IPv4/IPv6 in display form (IPv6 canonical, zone dropped); null for anything else. */ +private fun numericText(value: String): String? = when (val numeric = lanNumericAddress(value.substringBefore('%'))) { + is LanNumericAddress.V4 -> numeric.text + is LanNumericAddress.V6 -> numeric.address.canonical + null -> null +} + +private fun ipv6WithPrefix(value: String): Pair? { + val parts = value.trim().split('/') + if (parts.size != 2 || parts[1].length !in 1..3 || parts[1].any { it !in '0'..'9' }) return null + val length = parts[1].toInt().takeIf { it in 0..128 } ?: return null + val address = Ipv6Address.parse(parts[0].substringBefore('%')) ?: return null + return address to length +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt index 1c53561..3c2988c 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt @@ -73,9 +73,9 @@ fun safePtrName(value: String): String? { enum class LanRunStatus { IDLE, RUNNING, FINISHED, CANCELLED, FAILED } /** Keeps sequence and elapsed time independent of the bounded display window. */ -fun appendPingResult(previous: List, address: String, sequence: Long, elapsedMs: Long, rtt: Double?): List { +fun appendPingResult(previous: List, address: String, sequence: Long, elapsedMs: Long, rtt: Double?, dfTooLarge: Boolean = false): List { require(sequence > (previous.lastOrNull()?.sequence ?: 0) && elapsedMs >= (previous.lastOrNull()?.elapsedMs ?: 0)) - return (previous + LanResult(address, method = "ICMP", milliseconds = rtt, sequence = sequence, elapsedMs = elapsedMs)).takeLast(600) + return (previous + LanResult(address, method = "ICMP", dfTooLarge = dfTooLarge, milliseconds = rtt, sequence = sequence, elapsedMs = elapsedMs)).takeLast(600) } /** Loopback, this-network, multicast and reserved addresses have no remote LAN PTR lookup. */ diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanWol.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanWol.kt new file mode 100644 index 0000000..22c7b28 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanWol.kt @@ -0,0 +1,52 @@ +package cz.netkit.shared.lan + +import cz.netkit.shared.wol.WolDevice +import cz.netkit.shared.wol.WolDeviceDraft +import cz.netkit.shared.wol.parseMac +import cz.netkit.shared.wol.parseIpv4 + +/* + * Wake-on-LAN from the LAN device detail (zadání 36 §2.7). A saved WoL device whose probe host is the + * scanned address gets "Wake"; only when no saved device has exactly that address do the host's names + * count (they come from the network and are not trusted to outrank an address). More candidates are all + * offered, each button named after its real target, and the user picks. Otherwise "Add to WoL" opens the WoL form with + * the address, the name and, when NetBIOS reported one, the MAC prefilled. The user confirms by saving; + * Android 10+ apps cannot read the ARP table, so without NetBIOS the MAC is typed by hand. + */ + +/** A saved WoL device the user can wake from the LAN detail; [name] is shown on its button. */ +data class LanWolCandidate(val deviceId: String, val name: String) + +sealed interface LanWolAction { + /** Non-empty; one button per candidate. */ + data class Wake(val candidates: List) : LanWolAction + data class Add(val draft: WolDeviceDraft) : LanWolAction +} + +private fun normalizedHost(value: String) = value.trim().lowercase().removeSuffix(".").removeSuffix(".local") + +/** + * Null for the phone itself; Wake for exact-address matches (both sides parsed as IPv4, no name + * normalization), else for hostname matches; otherwise Add. Values that look like IPv4 never take part + * in the name fallback (e.g. a profile `192.0.2.11.local` or a host announcing the name `192.0.2.11`). + */ +fun lanWolAction(device: LanDevice, wolDevices: List): LanWolAction? { + if (device.isSelf) return null + // Canonical dotted form (Ipv4Address has no value equality). + val address = parseIpv4(device.address)?.toString() + fun ipLike(value: String) = parseIpv4(value) != null || parseIpv4(normalizedHost(value)) != null + val byAddress = wolDevices.filter { wol -> address != null && wol.probeHost?.trim()?.let(::parseIpv4)?.toString() == address } + val names = device.names.map { it.value }.filterNot(::ipLike).map(::normalizedHost).filter { it.isNotEmpty() }.toSet() + val byName = wolDevices.filter { wol -> + val host = wol.probeHost?.trim()?.takeIf { it.isNotEmpty() && !ipLike(it) } ?: return@filter false + normalizedHost(host) in names + } + val matches = byAddress.ifEmpty { byName } + if (matches.isNotEmpty()) return LanWolAction.Wake(matches.map { LanWolCandidate(it.id, it.name) }) + val display = lanDeviceDisplayName(device) + return LanWolAction.Add(WolDeviceDraft( + name = (if (display.source != null) display.text else device.address).take(100), + mac = device.netBiosMac?.let { parseMac(it)?.toString() }.orEmpty(), + probeHost = device.address, + )) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/MacAddressTable.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/MacAddressTable.kt new file mode 100644 index 0000000..148d52b --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/MacAddressTable.kt @@ -0,0 +1,124 @@ +package cz.netkit.shared.lan + +/** + * Zadání 48: MAC addresses from one address or pasted switch/router output + * (`show mac address-table`, `display mac-address`, `/interface bridge host print`). + * + * Accepted forms: `xxxx.xxxx.xxxx` (Cisco), `xxxx-xxxx-xxxx` (Huawei), `xx:xx:xx:xx:xx:xx` and + * `xx-xx-xx-xx-xx-xx` (one separator kind). A candidate glued to another hex digit or to a + * separator followed by a hex digit (a longer address, an IPv6 literal, a hex dump) is not a MAC. + * Bare 12-digit hex is not accepted: in pasted output it is far more often something else. + */ +const val MAC_INPUT_MAX_BYTES = 64 * 1024 +const val MAC_INPUT_MAX_LINES = 2000 + +enum class MacInputError { TOO_LARGE, TOO_MANY_LINES } + +data class MacFound( + /** Canonical `AA:BB:CC:DD:EE:FF`. */ + val text: String, + val value: Long, + /** U/L bit (0x02 of the first octet): randomised or assigned locally, no IEEE owner. */ + val locallyAdministered: Boolean, + /** I/G bit (0x01 of the first octet): group address, no IEEE owner of a device. */ + val multicast: Boolean, + /** How many times the address occurs in the input. */ + val occurrences: Int, +) + +data class MacExtraction(val macs: List, val error: MacInputError? = null) + +/** Unique MACs in order of first occurrence; over the limits nothing is parsed. */ +fun extractMacAddresses(input: String): MacExtraction { + // Every char is at least one UTF-8 byte, so a longer string is over the limit without encoding it. + if (input.length > MAC_INPUT_MAX_BYTES || input.encodeToByteArray().size > MAC_INPUT_MAX_BYTES) + return MacExtraction(emptyList(), MacInputError.TOO_LARGE) + val lines = input.count { it == '\n' } + if (input.isEmpty() || input.endsWith('\n')) 0 else 1 + if (lines > MAC_INPUT_MAX_LINES) return MacExtraction(emptyList(), MacInputError.TOO_MANY_LINES) + val found = LinkedHashMap() + var index = 0 + while (index < input.length) { + val length = macAt(input, index) + if (length == 0) { index++; continue } + val value = macValue(input, index, length) + found[value] = (found[value] ?: 0) + 1 + index += length + } + return MacExtraction(found.map { (value, count) -> + val first = (value ushr 40).toInt() + MacFound(macText(value), value, first and 0x02 != 0, first and 0x01 != 0, count) + }) +} + +private fun Char.isHex() = this in '0'..'9' || this in 'a'..'f' || this in 'A'..'F' +private fun Char.isMacSeparator() = this == ':' || this == '-' || this == '.' + +/** Length of a MAC starting exactly at [start] (with clean boundaries on both sides), or 0. */ +private fun macAt(text: String, start: Int): Int { + if (!text[start].isHex()) return 0 + // Left boundary: not inside a longer hex run or a longer separated group. + if (start > 0) { + val before = text[start - 1] + if (before.isHex()) return 0 + // A separator glued to more address text (`1:`, `::` of compressed IPv6) continues something longer. + if (before.isMacSeparator() && start > 1 && (text[start - 2].isHex() || text[start - 2].isMacSeparator())) return 0 + } + val length = when { + groups(text, start, 4, 3, '.') -> 14 + groups(text, start, 4, 3, '-') -> 14 + groups(text, start, 2, 6, ':') -> 17 + groups(text, start, 2, 6, '-') -> 17 + else -> return 0 + } + val end = start + length + if (end < text.length) { + val after = text[end] + if (after.isHex()) return 0 + if (after.isMacSeparator() && end + 1 < text.length && (text[end + 1].isHex() || text[end + 1].isMacSeparator())) return 0 + } + return length +} + +/** [count] groups of [width] hex digits joined by [separator], starting at [start]. */ +private fun groups(text: String, start: Int, width: Int, count: Int, separator: Char): Boolean { + val length = width * count + count - 1 + if (start + length > text.length) return false + for (offset in 0 until length) { + val char = text[start + offset] + val isSeparator = (offset + 1) % (width + 1) == 0 + if (isSeparator) { if (char != separator) return false } else if (!char.isHex()) return false + } + return true +} + +private fun macValue(text: String, start: Int, length: Int): Long { + var value = 0L + for (offset in 0 until length) { + val char = text[start + offset] + if (!char.isHex()) continue + value = (value shl 4) or char.digitToInt(16).toLong() + } + return value +} + +private fun macText(value: Long): String = + (5 downTo 0).joinToString(":") { ((value ushr (it * 8)) and 0xff).toString(16).padStart(2, '0').uppercase() } + +/** A found MAC with its IEEE owner (null: unknown, locally administered or multicast). */ +data class MacVendorRow(val mac: MacFound, val vendor: String?) + +fun macVendorRows(macs: List, database: cz.netkit.shared.wifi.OuiDatabase): List = + macs.map { MacVendorRow(it, database.vendorFor(it.text)) } + +/** + * Rows for the shared LAN export (text/CSV/JSON): the MAC as address, the vendor as name and the + * flags as stable English tokens in the detail column (not localized, so exports stay comparable). + */ +fun macExportRows(rows: List): List = rows.map { row -> + val flags = listOfNotNull( + "locally-administered".takeIf { row.mac.locallyAdministered }, + "multicast".takeIf { row.mac.multicast }, + "count=${row.mac.occurrences}".takeIf { row.mac.occurrences > 1 }, + ) + LanResult(row.mac.text, name = row.vendor.orEmpty(), method = "OUI", detail = flags.joinToString(" ")) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/NetBiosParser.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/NetBiosParser.kt index f0614ec..e0c0e49 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/NetBiosParser.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/NetBiosParser.kt @@ -17,8 +17,18 @@ private const val NAME_ENTRY_BYTES = 18 /** One NODE_NAME entry. [suffix] is the 16th byte (0x00 workstation, 0x20 server, ...). */ data class NetBiosName(val name: String, val suffix: Int, val group: Boolean) -/** [name] = unique workstation (0x00) or server (0x20) name; [group] = workgroup/domain (group 0x00). */ -data class NetBiosInfo(val name: String?, val group: String?, val names: List) +/** + * [name] = unique workstation (0x00) or server (0x20) name; [group] = workgroup/domain (group 0x00). + * [mac] = UNIT_ID of the statistics (RFC 1002 4.2.18), `AA:BB:CC:DD:EE:FF`, only when present, + * non-zero and unicast; Windows reports the adapter MAC there, Samba usually zeros. + */ +data class NetBiosInfo(val name: String?, val group: String?, val names: List, val mac: String? = null) + +/** UNIT_ID bytes as a unicast MAC, or null for all zeros, a multicast/broadcast bit or a wrong length. */ +fun netBiosUnitIdMac(bytes: ByteArray): String? { + if (bytes.size != 6 || bytes.all { it.toInt() == 0 } || bytes[0].toInt() and 1 != 0) return null + return bytes.joinToString(":") { (it.toInt() and 255).toString(16).padStart(2, '0').uppercase() } +} /** 50-byte NBSTAT query for the wildcard name `*` (unicast, no recursion). */ fun netBiosNodeStatusRequest(transactionId: Int): ByteArray { @@ -70,6 +80,7 @@ fun parseNetBiosNodeStatus(packet: ByteArray, transactionId: Int, length: Int = if (u16(cursor) != NBSTAT_TYPE || u16(cursor + 2) != IN_CLASS) return null val rdLength = u16(cursor + 8) cursor += 10 + val rdataEnd = cursor + rdLength if (rdLength < 1 || cursor + rdLength > length) return null val count = u8(cursor) if (count == 0 || 1 + count * NAME_ENTRY_BYTES > rdLength) return null @@ -95,5 +106,8 @@ fun parseNetBiosNodeStatus(packet: ByteArray, transactionId: Int, length: Int = val workstation = names.firstOrNull { !it.group && it.suffix == 0x00 } ?: names.firstOrNull { !it.group && it.suffix == 0x20 } val group = names.firstOrNull { it.group && it.suffix == 0x00 } if (workstation == null && group == null) return null - return NetBiosInfo(workstation?.name, group?.name, names) + // STATISTICS start with the 6-byte UNIT_ID; a response cut inside RDATA keeps its names but no MAC. + val statistics = cursor + count * NAME_ENTRY_BYTES + val mac = if (statistics + 6 <= rdataEnd) netBiosUnitIdMac(packet.copyOfRange(statistics, statistics + 6)) else null + return NetBiosInfo(workstation?.name, group?.name, names, mac) } diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/NtpPacket.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/NtpPacket.kt new file mode 100644 index 0000000..75da239 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/NtpPacket.kt @@ -0,0 +1,51 @@ +package cz.netkit.shared.lan + +/* + * NTP client request and server reply (zadání 39 §2.4, RFC 5905 §7.3): only stratum, reference ID + * and leap state are shown; no clock is set. The reply is untrusted and bounded. + */ + +const val NTP_PACKET_BYTES = 48 +/** Header plus extension fields/MAC; anything longer is rejected as a whole. */ +const val NTP_MAX_DATAGRAM_BYTES = 1024 + +/** How the reference ID is to be read, which depends on the stratum (RFC 5905 §7.3). */ +enum class NtpReferenceKind { KISS_CODE, SOURCE, UPSTREAM_ADDRESS, NONE } + +/** + * @property stratum 0 = kiss-o'-death, 1 = primary, 2–15 secondary, 16 = unsynchronized. + * @property reference ASCII code (stratum 0/1, printable only) or dotted IPv4 of the upstream + * (stratum 2–15; for an IPv6 upstream the server puts a hash there, which reads like IPv4). + */ +data class NtpReply(val version: Int, val stratum: Int, val leapUnsynchronized: Boolean, val referenceKind: NtpReferenceKind, val reference: String?) + +/** Mode 3 (client), version 4; the 8-byte [transmit] nonce must come back as the origin timestamp. */ +fun ntpRequest(transmit: ByteArray): ByteArray { + require(transmit.size == 8) + return ByteArray(NTP_PACKET_BYTES).also { + it[0] = 0x23 // LI 0, VN 4, mode 3 + transmit.copyInto(it, 40) + } +} + +/** Server (mode 4) reply to [transmit]; null for a short/long datagram, other modes or a foreign origin. */ +fun parseNtpReply(packet: ByteArray, length: Int, transmit: ByteArray): NtpReply? { + if (transmit.size != 8 || length < NTP_PACKET_BYTES || length > packet.size || length > NTP_MAX_DATAGRAM_BYTES) return null + val first = packet[0].toInt() and 0xff + val mode = first and 7 + val version = (first shr 3) and 7 + if (mode != 4 || version !in 1..4) return null + if ((0 until 8).any { packet[24 + it] != transmit[it] }) return null + val stratum = packet[1].toInt() and 0xff + if (stratum > 16) return null + val id = packet.copyOfRange(12, 16) + fun ascii(): String? = id.takeWhile { it != 0.toByte() }.map { it.toInt() and 0xff } + .takeIf { codes -> codes.isNotEmpty() && codes.all { it in 0x20..0x7e } }?.joinToString("") { it.toChar().toString() } + val (kind, reference) = when (stratum) { + 0 -> NtpReferenceKind.KISS_CODE to ascii() + 1 -> NtpReferenceKind.SOURCE to ascii() + 16 -> NtpReferenceKind.NONE to null + else -> NtpReferenceKind.UPSTREAM_ADDRESS to id.joinToString(".") { (it.toInt() and 0xff).toString() } + } + return NtpReply(version, stratum, first shr 6 == 3, kind, reference) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/SnmpBer.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/SnmpBer.kt new file mode 100644 index 0000000..fbd69f2 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/SnmpBer.kt @@ -0,0 +1,180 @@ +package cz.netkit.shared.lan + +/* + * Minimal BER for one SNMPv2c GetRequest/GetResponse (zadání 39 §2.4, RFC 3416 / X.690). + * The response is untrusted: definite lengths only (short form or 1–2 length bytes), single-byte + * tags, every element inside its parent, a bounded nesting depth and a bounded datagram. A + * malformed packet yields null, never an exception. + */ + +/** Largest SNMP datagram the probe reads; a longer reply is rejected as a whole. */ +const val SNMP_MAX_DATAGRAM_BYTES = 4096 +/** Message → PDU → varbind list → varbind → value: 5 levels are enough; 8 leaves room. */ +const val BER_MAX_DEPTH = 8 +/** sysDescr can be long on real devices; the UI shows at most this many characters. */ +const val SNMP_MAX_TEXT = 255 + +val SNMP_SYS_DESCR: List = listOf(1, 3, 6, 1, 2, 1, 1, 1, 0) +val SNMP_SYS_NAME: List = listOf(1, 3, 6, 1, 2, 1, 1, 5, 0) + +private const val TAG_INTEGER = 0x02 +private const val TAG_OCTET_STRING = 0x04 +private const val TAG_NULL = 0x05 +private const val TAG_OID = 0x06 +private const val TAG_SEQUENCE = 0x30 +private const val TAG_GET_REQUEST = 0xA0 +private const val TAG_GET_RESPONSE = 0xA2 +private const val SNMP_V2C = 1 + +/** One varbind of a response: [text] for an OCTET STRING value, null for NULL/noSuchObject/… */ +data class SnmpVarBind(val oid: List, val text: String?) +data class SnmpResponse(val requestId: Int, val errorStatus: Int, val errorIndex: Int, val varBinds: List) + +/** SNMPv2c GetRequest for [oids]; [community] is used only in this packet and never stored. */ +fun encodeSnmpGet(community: ByteArray, requestId: Int, oids: List>): ByteArray { + require(community.size in 1..255 && oids.size in 1..8) + val bindings = oids.map { tlv(TAG_SEQUENCE, tlv(TAG_OID, encodeOid(it)) + tlv(TAG_NULL, ByteArray(0))) } + val pdu = tlv(TAG_GET_REQUEST, integer(requestId) + integer(0) + integer(0) + tlv(TAG_SEQUENCE, bindings.fold(ByteArray(0)) { a, b -> a + b })) + return tlv(TAG_SEQUENCE, integer(SNMP_V2C) + tlv(TAG_OCTET_STRING, community) + pdu) +} + +/** + * GetResponse of version 2c whose community and request ID match; null for anything else, + * including a datagram over [SNMP_MAX_DATAGRAM_BYTES], trailing bytes or nesting over [BER_MAX_DEPTH]. + */ +fun parseSnmpResponse(packet: ByteArray, length: Int, community: ByteArray, requestId: Int): SnmpResponse? { + if (length <= 0 || length > packet.size || length > SNMP_MAX_DATAGRAM_BYTES) return null + return try { + val reader = BerReader(packet, length) + val message = reader.element(0, 0) + if (message.tag != TAG_SEQUENCE || message.end != length) return null + val parts = reader.children(message, 1) + if (parts.size != 3) return null + if (reader.integer(parts[0]) != SNMP_V2C.toLong()) return null + if (parts[1].tag != TAG_OCTET_STRING || !reader.bytes(parts[1]).contentEquals(community)) return null + val pdu = parts[2] + if (pdu.tag != TAG_GET_RESPONSE) return null + val fields = reader.children(pdu, 2) + if (fields.size != 4 || fields[3].tag != TAG_SEQUENCE) return null + val id = reader.integer(fields[0]) + if (id != requestId.toLong()) return null + val status = reader.integer(fields[1]).takeIf { it in 0..18 } ?: return null + val index = reader.integer(fields[2]).takeIf { it in 0..8 } ?: return null + val bindings = reader.children(fields[3], 3).map { binding -> + if (binding.tag != TAG_SEQUENCE) return null + val pair = reader.children(binding, 4) + if (pair.size != 2 || pair[0].tag != TAG_OID) return null + val oid = reader.oid(pair[0]) ?: return null + val value = pair[1] + // A constructed value would add a level; nothing in a scalar Get needs it. + if (value.tag and 0x20 != 0) return null + SnmpVarBind(oid, if (value.tag == TAG_OCTET_STRING) sanitizeLanText(reader.bytes(value).decodeToString(), SNMP_MAX_TEXT).trim() else null) + } + if (bindings.size > 8) return null + SnmpResponse(id.toInt(), status.toInt(), index.toInt(), bindings) + } catch (_: MalformedBer) { null } +} + +private class MalformedBer : Exception() +private data class BerElement(val tag: Int, val start: Int, val end: Int) + +/** Flat cursor over one datagram; [depth] is passed explicitly so nesting is bounded without recursion on data. */ +private class BerReader(private val packet: ByteArray, private val length: Int) { + private fun fail(): Nothing = throw MalformedBer() + private fun u8(index: Int): Int { if (index !in 0 until length) fail(); return packet[index].toInt() and 0xff } + + fun element(offset: Int, depth: Int, limit: Int = length): BerElement { + if (depth > BER_MAX_DEPTH) fail() + val tag = u8(offset) + if (tag and 0x1f == 0x1f) fail() // multi-byte tag numbers are not used by SNMP + val first = u8(offset + 1) + var cursor = offset + 2 + val size = when { + first < 0x80 -> first + first == 0x80 -> fail() // indefinite length is not allowed in SNMP (X.690 indefinite form, RFC 3417) + first - 0x80 > 2 -> fail() + else -> { + var value = 0 + repeat(first - 0x80) { value = (value shl 8) or u8(cursor++) } + value + } + } + val end = cursor + size + if (end > limit || end < cursor) fail() + return BerElement(tag, cursor, end) + } + + /** Direct children of a constructed [parent]; at most 16, all exactly inside it. */ + fun children(parent: BerElement, depth: Int): List { + if (depth > BER_MAX_DEPTH) fail() + val out = ArrayList() + var cursor = parent.start + while (cursor < parent.end) { + if (out.size == 16) fail() + val child = element(cursor, depth, parent.end) + out += child + cursor = child.end + } + if (cursor != parent.end) fail() + return out + } + + fun integer(element: BerElement): Long { + if (element.tag != TAG_INTEGER) fail() + val size = element.end - element.start + if (size !in 1..4) fail() + var value = (packet[element.start].toLong()) // sign-extended first byte + for (index in element.start + 1 until element.end) value = (value shl 8) or (u8(index).toLong()) + return value + } + + fun bytes(element: BerElement): ByteArray = packet.copyOfRange(element.start, element.end) + + fun oid(element: BerElement): List? { + val size = element.end - element.start + if (size !in 1..64) return null + val arcs = ArrayList() + val first = u8(element.start).takeIf { it < 0x80 } ?: return null + arcs += minOf(first / 40, 2); arcs += first - arcs[0] * 40 + var value = 0L + var digits = 0 + for (index in element.start + 1 until element.end) { + val byte = u8(index) + value = (value shl 7) or (byte and 0x7f).toLong() + if (++digits > 5 || value > Int.MAX_VALUE) return null + if (byte and 0x80 == 0) { arcs += value.toInt(); value = 0; digits = 0 } + } + return arcs.takeIf { digits == 0 && it.size <= 32 } + } +} + +private fun encodeOid(oid: List): ByteArray { + require(oid.size >= 2 && oid[0] in 0..2 && oid[1] in 0..39 && oid.all { it >= 0 }) + val out = ArrayList() + out += (oid[0] * 40 + oid[1]).toByte() + for (arc in oid.drop(2)) { + val groups = ArrayList() + var value = arc + do { groups += value and 0x7f; value = value ushr 7 } while (value != 0) + for (index in groups.indices.reversed()) out += (groups[index] or if (index > 0) 0x80 else 0).toByte() + } + return out.toByteArray() +} + +private fun integer(value: Int): ByteArray { + // Minimal two's complement, as X.690 8.3.2 requires. + var bytes = byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte()) + while (bytes.size > 1 && ((bytes[0].toInt() == 0 && bytes[1].toInt() and 0x80 == 0) || (bytes[0].toInt() == -1 && bytes[1].toInt() and 0x80 != 0))) + bytes = bytes.copyOfRange(1, bytes.size) + return tlv(TAG_INTEGER, bytes) +} + +private fun tlv(tag: Int, content: ByteArray): ByteArray { + val size = content.size + val header = when { + size < 0x80 -> byteArrayOf(tag.toByte(), size.toByte()) + size <= 0xff -> byteArrayOf(tag.toByte(), 0x81.toByte(), size.toByte()) + else -> { require(size <= 0xffff); byteArrayOf(tag.toByte(), 0x82.toByte(), (size shr 8).toByte(), size.toByte()) } + } + return header + content +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/SubnetCalculator.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/SubnetCalculator.kt new file mode 100644 index 0000000..a970bb9 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/SubnetCalculator.kt @@ -0,0 +1,86 @@ +package cz.netkit.shared.lan + +enum class AddressRange { PRIVATE, CGNAT, LINK_LOCAL, LOOPBACK, MULTICAST, DOCUMENTATION, MIXED, OTHER } + +private val specialRanges = mapOf( + AddressRange.PRIVATE to listOf("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"), + AddressRange.CGNAT to listOf("100.64.0.0/10"), + AddressRange.LINK_LOCAL to listOf("169.254.0.0/16"), + AddressRange.LOOPBACK to listOf("127.0.0.0/8"), + AddressRange.MULTICAST to listOf("224.0.0.0/4"), + AddressRange.DOCUMENTATION to listOf("192.0.2.0/24", "198.51.100.0/24", "203.0.113.0/24"), +).mapValues { (_, blocks) -> blocks.map { requireNotNull(Ipv4Subnet.parse(it)) } } + +enum class MaskInterpretation { NETMASK, WILDCARD } +enum class AddressClass { A, B, C, D, E } + +data class SubnetDetails( + val subnet: Ipv4Subnet, + val range: AddressRange, + val addressClass: AddressClass, + val ambiguousInterpretation: MaskInterpretation?, +) { + val wildcard = ipv4Text(subnet.size - 1) + val mask = ipv4Text(0xffffffffL - (subnet.size - 1)) + private val last = subnet.network + subnet.size - 1 + val broadcast = if (subnet.prefix < 31) ipv4Text(last) else null + val firstHost = ipv4Text(if (broadcast == null) subnet.network else subnet.network + 1) + val lastHost = ipv4Text(if (broadcast == null) last else last - 1) + + fun split(prefix: Int): SubnetSplit? { + if (prefix !in subnet.prefix..32) return null + val count = 1L shl (prefix - subnet.prefix) + val step = 1L shl (32 - prefix) + val rows = List(minOf(256L, count).toInt()) { Ipv4Subnet(subnet.network + it * step, prefix) } + return SubnetSplit(rows, count - rows.size) + } +} + +data class SubnetSplit(val rows: List, val remaining: Long) + +private fun classifySubnet(subnet: Ipv4Subnet): AddressRange { + val end = subnet.network + subnet.size + var range = AddressRange.OTHER + for ((label, blocks) in specialRanges) { + for (block in blocks) { + val blockEnd = block.network + block.size + if (subnet.network >= block.network && end <= blockEnd) return label + if (subnet.network < blockEnd && block.network < end) range = AddressRange.MIXED + } + } + return range +} + +fun calculateSubnet(input: String, ambiguousMask: MaskInterpretation = MaskInterpretation.NETMASK): SubnetDetails? { + val text = input.trim() + val parts = if ('/' in text) text.split('/', limit = 2) else text.split(Regex("\\s+"), limit = 2) + if (parts.size != 2) return null + val (address, suffix) = parts + val ip = ipv4Number(address) ?: return null + var interpretation: MaskInterpretation? = null + val subnet = if ('/' in text && '.' !in suffix) { + Ipv4Subnet.parse(text) + } else { + val bits = ipv4Number(suffix) ?: return null + val inverse = bits xor 0xffffffffL + fun lowOnes(n: Long) = n and (n + 1) == 0L + val prefix = when { + bits == 0L || inverse == 0L -> { + interpretation = ambiguousMask + if (ambiguousMask == MaskInterpretation.NETMASK) bits.countOneBits() else inverse.countOneBits() + } + lowOnes(inverse) -> bits.countOneBits() + lowOnes(bits) -> inverse.countOneBits() + else -> return null + } + Ipv4Subnet.parse("$address/$prefix") + } ?: return null + val addressClass = when ((ip shr 24).toInt()) { + in 0..127 -> AddressClass.A + in 128..191 -> AddressClass.B + in 192..223 -> AddressClass.C + in 224..239 -> AddressClass.D + else -> AddressClass.E + } + return SubnetDetails(subnet, classifySubnet(subnet), addressClass, interpretation) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/TcpPing.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/TcpPing.kt new file mode 100644 index 0000000..cfca3ad --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/TcpPing.kt @@ -0,0 +1,33 @@ +package cz.netkit.shared.lan + +/** + * Zadání 48: TCP ping — repeated TCP connects to host:port, one connection at a time, one attempt + * per [TCP_PING_INTERVAL_MS]. A completed handshake is a reply with its connect time; a refusal + * (RST), a timeout or an error is a lost sample. Statistics are [pingStatistics] over the samples. + */ +const val TCP_PING_INTERVAL_MS = 1000L +const val TCP_PING_DEFAULT_PORT = 443 +const val TCP_PING_MAX_COUNT = 1000 + +/** [count] null = until stopped (like ping without a count). */ +data class TcpPingOptions(val port: Int, val count: Int?) + +fun tcpPingOptions(port: String, count: String): TcpPingOptions? { + val number = port.trim().takeIf { text -> text.isNotEmpty() && text.length <= 5 && text.all { it in '0'..'9' } } + ?.toInt()?.takeIf { it in 1..65535 } ?: return null + val countText = count.trim() + val limit = if (countText.isEmpty()) null else countText.takeIf { text -> text.length <= 4 && text.all { it in '0'..'9' } } + ?.toInt()?.takeIf { it in 1..TCP_PING_MAX_COUNT } ?: return null + return TcpPingOptions(number, limit) +} + +/** Result rows as for ping: newest 600 kept, sequence and elapsed time strictly growing. */ +fun appendTcpPingResult(previous: List, address: String, port: Int, sequence: Long, elapsedMs: Long, + rtt: Double?, status: ProbeStatus): List { + require(sequence > (previous.lastOrNull()?.sequence ?: 0) && elapsedMs >= (previous.lastOrNull()?.elapsedMs ?: 0)) + val reply = if (status == ProbeStatus.OPEN) rtt else null + // The status names the reason of a lost sample in the export; a reply needs none. + val detail = if (reply != null) "" else status.name + return (previous + LanResult(address, method = "TCP", milliseconds = reply, port = port, detail = detail, + sequence = sequence, elapsedMs = elapsedMs)).takeLast(600) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/ToolTargets.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/ToolTargets.kt new file mode 100644 index 0000000..ffeefb8 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/ToolTargets.kt @@ -0,0 +1,140 @@ +package cz.netkit.shared.lan + +import cz.netkit.shared.publicip.parseIp +import cz.netkit.shared.publicip.rdapPath +import kotlinx.serialization.Serializable + +/** + * Zadání 48: shared history and favourite targets of the single-target tools (Ping, TCP ping, + * Traceroute, Ports, DNS, DNS records, Web/TLS, RDAP). Only local (the tool DataStore). + * + * One list is shared by all tools; each tool offers only the entries its input accepts + * ([targetFits]), so a host pinged earlier is offered to Traceroute or TCP ping, an IP address + * to RDAP, and a URL only to Web/TLS. + */ +enum class TargetField { HOST, DNS_NAME, URL, RDAP } + +const val TARGET_RECENT_LIMIT = 10 +const val TARGET_FAVORITE_LIMIT = 30 +const val TARGET_LABEL_LIMIT = 40 +const val TARGET_VALUE_LIMIT = 2048 + +@Serializable +data class FavoriteTarget(val value: String, val label: String = "") + +/** One entry of the menu at a tool's target field. */ +data class TargetSuggestion(val value: String, val label: String, val favorite: Boolean) + +sealed interface FavoriteChange { + data class Updated(val targets: ToolTargets) : FavoriteChange + /** [TARGET_FAVORITE_LIMIT] favourites exist and [value] is not one of them. */ + data object Limit : FavoriteChange + /** The value is not a target of any tool (empty, too long, control characters). */ + data object Invalid : FavoriteChange +} + +@Serializable +data class ToolTargets( + /** Most recently used first, at most [TARGET_RECENT_LIMIT]. */ + val recent: List = emptyList(), + /** In the order they were starred, at most [TARGET_FAVORITE_LIMIT]. */ + val favorites: List = emptyList(), +) { + /** A run started with [value]: it moves to the top of the history (a URL without query and fragment). */ + fun remember(value: String): ToolTargets { + val clean = cleanTarget(value)?.let(::historyForm) ?: return this + val key = targetKey(clean) + return copy(recent = (listOf(clean) + recent.filterNot { targetKey(it) == key }).take(TARGET_RECENT_LIMIT)) + } + + fun isFavorite(value: String): Boolean { + val key = cleanTarget(value)?.let(::targetKey) ?: return false + return favorites.any { targetKey(it.value) == key } + } + + /** Stars [value] (exactly as entered) or renames an existing favourite. */ + fun star(value: String, label: String = ""): FavoriteChange { + val clean = cleanTarget(value) ?: return FavoriteChange.Invalid + val key = targetKey(clean) + val name = cleanLabel(label) + val index = favorites.indexOfFirst { targetKey(it.value) == key } + if (index >= 0) return FavoriteChange.Updated(copy(favorites = favorites.toMutableList().also { it[index] = it[index].copy(label = name) })) + if (favorites.size >= TARGET_FAVORITE_LIMIT) return FavoriteChange.Limit + return FavoriteChange.Updated(copy(favorites = favorites + FavoriteTarget(clean, name))) + } + + fun unstar(value: String): ToolTargets { + val key = cleanTarget(value)?.let(::targetKey) ?: return this + return copy(favorites = favorites.filterNot { targetKey(it.value) == key }) + } + + /** "Vymazat historii": the recent list only; favourites are kept, they were starred on purpose. */ + fun clearHistory(): ToolTargets = copy(recent = emptyList()) + + /** Favourites first (in their order), then recent entries that are not favourites. */ + fun suggestions(field: TargetField): List { + val starred = favorites.filter { targetFits(field, it.value) } + val keys = favorites.mapTo(HashSet()) { targetKey(it.value) } + return starred.map { TargetSuggestion(it.value, it.label, true) } + + recent.filter { targetKey(it) !in keys && targetFits(field, it) }.map { TargetSuggestion(it, "", false) } + } + + /** + * Stored data is re-checked when read: a damaged or hand-edited file can carry too many, + * duplicated or unsafe entries; the limits and cleaning of [remember]/[star] hold again. + */ + fun normalized(): ToolTargets { + val recentKeys = HashSet() + val cleanRecent = recent.asSequence().mapNotNull { cleanTarget(it)?.let(::historyForm) } + .filter { recentKeys.add(targetKey(it)) }.take(TARGET_RECENT_LIMIT).toList() + val favoriteKeys = HashSet() + val cleanFavorites = favorites.asSequence().mapNotNull { favorite -> + cleanTarget(favorite.value)?.let { FavoriteTarget(it, cleanLabel(favorite.label)) } + }.filter { favoriteKeys.add(targetKey(it.value)) }.take(TARGET_FAVORITE_LIMIT).toList() + return ToolTargets(cleanRecent, cleanFavorites) + } +} + +/** Whether [value] is an input of a tool with [field] (no DNS, no network). */ +fun targetFits(field: TargetField, value: String): Boolean { + val text = value.trim() + return when (field) { + TargetField.HOST -> !asnText(text) && validLanTarget(text) + TargetField.DNS_NAME -> !asnText(text) && (recordQueryName(text, RecordType.A) != null || parseIp(text) != null) + TargetField.URL -> webTargetUrl(text) + TargetField.RDAP -> rdapPath(text) != null + } +} + +/** Trimmed [value] if it can be a target at all; control and format characters are refused, not replaced. */ +internal fun cleanTarget(value: String): String? { + val text = value.trim() + if (text.isEmpty() || text.length > TARGET_VALUE_LIMIT) return null + if (text.any { it.isWhitespace() } || sanitizeLanText(text, TARGET_VALUE_LIMIT) != text) return null + return text.takeIf { candidate -> TargetField.entries.any { targetFits(it, candidate) } } +} + +/** `AS64496` style text is an RDAP autonomous system, not a hostname, in the shared list. */ +private fun asnText(text: String): Boolean = + text.length > 2 && text.startsWith("AS", ignoreCase = true) && text.drop(2).all { it in '0'..'9' } + +private fun cleanLabel(label: String): String = sanitizeLanText(label.trim(), TARGET_LABEL_LIMIT).trim() + +/** http(s) URL with a host; the Web tool itself parses it strictly (OkHttp) before any request. */ +private fun webTargetUrl(text: String): Boolean { + val lower = text.lowercase() + val rest = when { + lower.startsWith("https://") -> text.substring(8) + lower.startsWith("http://") -> text.substring(7) + else -> return false + } + val authority = rest.substringBefore('/').substringBefore('?').substringBefore('#') + return authority.isNotEmpty() && '@' !in authority +} + +/** Query strings and fragments can carry tokens; the automatic history keeps scheme, host and path. */ +private fun historyForm(value: String): String = + if (webTargetUrl(value)) value.substringBefore('#').substringBefore('?') else value + +/** Hostnames and addresses compare without case; URL paths are case-sensitive, so URLs compare exactly. */ +private fun targetKey(value: String): String = if (webTargetUrl(value)) value else value.lowercase() diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/UdpServices.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/UdpServices.kt new file mode 100644 index 0000000..513ed21 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/UdpServices.kt @@ -0,0 +1,121 @@ +package cz.netkit.shared.lan + +import kotlinx.coroutines.async +import kotlinx.coroutines.coroutineScope + +/* + * "Identifikovat služby" (zadání 39 §2.4): SNMPv2c sysDescr/sysName, NTP stratum/reference and + * DNS version.bind for ONE host of the own network. The platform supplies [UdpExchange] (an + * Android socket bound to the Wi-Fi, a JVM socket in tests); this file owns packets, retries + * and the result model. Each probe: at most [UDP_PROBE_ATTEMPTS] datagrams, [UDP_PROBE_TIMEOUT_MS] each. + */ + +const val UDP_PROBE_TIMEOUT_MS = 1_500L +const val UDP_PROBE_ATTEMPTS = 2 + +data class UdpServicePorts(val snmp: Int = 161, val ntp: Int = 123, val dns: Int = 53) + +/** Result of one datagram exchange. */ +sealed interface UdpReply { + /** First datagram from the target that the caller's filter accepted. */ + class Data(val bytes: ByteArray) : UdpReply + data object Timeout : UdpReply + /** ICMP port unreachable (connected socket: ECONNREFUSED): nothing listens there. */ + data object Refused : UdpReply +} + +fun interface UdpExchange { + /** Sends [payload] to [port] of the fixed target and waits up to [timeoutMs] for a datagram that [accept]s. */ + suspend fun exchange(port: Int, payload: ByteArray, timeoutMs: Long, accept: (ByteArray, Int) -> Boolean): UdpReply +} + +enum class UdpProbeOutcome { + /** Valid answer. */ + OK, + /** Answered, but with an error (SNMP error-status, DNS refusal is still OK with a code). */ + ERROR, + NO_REPLY, + /** Port closed (ICMP unreachable). */ + CLOSED, + /** Not attempted: no community entered, or DNS not known to run on this host. */ + SKIPPED, +} + +data class SnmpProbeResult(val outcome: UdpProbeOutcome, val sysName: String? = null, val sysDescr: String? = null, val errorStatus: Int? = null) +data class NtpProbeResult(val outcome: UdpProbeOutcome, val reply: NtpReply? = null) +data class DnsVersionProbeResult(val outcome: UdpProbeOutcome, val reply: VersionBindReply? = null) +data class UdpServicesResult(val snmp: SnmpProbeResult, val ntp: NtpProbeResult, val dns: DnsVersionProbeResult) + +/** + * Runs the three probes concurrently. [community] null or empty skips SNMP (no default such as + * "public" is ever tried); [dnsAllowed] false skips DNS. [randomBytes] supplies request IDs and the + * NTP nonce (use a CSPRNG on the platform). + */ +suspend fun probeUdpServices( + exchange: UdpExchange, + community: ByteArray?, + dnsAllowed: Boolean, + randomBytes: (Int) -> ByteArray, + ports: UdpServicePorts = UdpServicePorts(), +): UdpServicesResult = coroutineScope { + val snmp = async { if (community == null || community.isEmpty()) SnmpProbeResult(UdpProbeOutcome.SKIPPED) else probeSnmp(exchange, community, randomBytes, ports.snmp) } + val ntp = async { probeNtp(exchange, randomBytes, ports.ntp) } + val dns = async { if (!dnsAllowed) DnsVersionProbeResult(UdpProbeOutcome.SKIPPED) else probeVersionBind(exchange, randomBytes, ports.dns) } + UdpServicesResult(snmp.await(), ntp.await(), dns.await()) +} + +private suspend fun attempts(exchange: UdpExchange, port: Int, payload: ByteArray, accept: (ByteArray, Int) -> Boolean): UdpReply { + repeat(UDP_PROBE_ATTEMPTS) { + when (val reply = exchange.exchange(port, payload, UDP_PROBE_TIMEOUT_MS, accept)) { + is UdpReply.Data, UdpReply.Refused -> return reply + UdpReply.Timeout -> Unit + } + } + return UdpReply.Timeout +} + +private fun Int.positive(): Int = this and 0x7fffffff + +private fun idFrom(bytes: ByteArray): Int = bytes.fold(0) { value, byte -> (value shl 8) or (byte.toInt() and 0xff) } + +private suspend fun probeSnmp(exchange: UdpExchange, community: ByteArray, randomBytes: (Int) -> ByteArray, port: Int): SnmpProbeResult { + val requestId = idFrom(randomBytes(4)).positive() + val request = encodeSnmpGet(community, requestId, listOf(SNMP_SYS_DESCR, SNMP_SYS_NAME)) + return when (val reply = attempts(exchange, port, request) { bytes, length -> parseSnmpResponse(bytes, length, community, requestId) != null }) { + UdpReply.Timeout -> SnmpProbeResult(UdpProbeOutcome.NO_REPLY) + UdpReply.Refused -> SnmpProbeResult(UdpProbeOutcome.CLOSED) + is UdpReply.Data -> { + val response = parseSnmpResponse(reply.bytes, reply.bytes.size, community, requestId) ?: return SnmpProbeResult(UdpProbeOutcome.ERROR) + if (response.errorStatus != 0) return SnmpProbeResult(UdpProbeOutcome.ERROR, errorStatus = response.errorStatus) + fun text(oid: List) = response.varBinds.firstOrNull { it.oid == oid }?.text?.takeIf(String::isNotEmpty) + SnmpProbeResult(UdpProbeOutcome.OK, sysName = text(SNMP_SYS_NAME), sysDescr = text(SNMP_SYS_DESCR), errorStatus = 0) + } + } +} + +private suspend fun probeNtp(exchange: UdpExchange, randomBytes: (Int) -> ByteArray, port: Int): NtpProbeResult { + val nonce = randomBytes(8).also { require(it.size == 8) } + return when (val reply = attempts(exchange, port, ntpRequest(nonce)) { bytes, length -> parseNtpReply(bytes, length, nonce) != null }) { + UdpReply.Timeout -> NtpProbeResult(UdpProbeOutcome.NO_REPLY) + UdpReply.Refused -> NtpProbeResult(UdpProbeOutcome.CLOSED) + is UdpReply.Data -> parseNtpReply(reply.bytes, reply.bytes.size, nonce)?.let { NtpProbeResult(UdpProbeOutcome.OK, it) } + ?: NtpProbeResult(UdpProbeOutcome.ERROR) + } +} + +private suspend fun probeVersionBind(exchange: UdpExchange, randomBytes: (Int) -> ByteArray, port: Int): DnsVersionProbeResult { + val id = idFrom(randomBytes(2)) and 0xffff + return when (val reply = attempts(exchange, port, versionBindQuery(id)) { bytes, length -> parseVersionBind(bytes, length, id) != null }) { + UdpReply.Timeout -> DnsVersionProbeResult(UdpProbeOutcome.NO_REPLY) + UdpReply.Refused -> DnsVersionProbeResult(UdpProbeOutcome.CLOSED) + is UdpReply.Data -> parseVersionBind(reply.bytes, reply.bytes.size, id)?.let { DnsVersionProbeResult(UdpProbeOutcome.OK, it) } + ?: DnsVersionProbeResult(UdpProbeOutcome.ERROR) + } +} + +/** + * The DNS `version.bind` question goes only to a host that is known to run DNS: one of the Wi-Fi's + * DNS servers ([info]) or a host whose TCP port 53 was found open by the port check. + */ +fun lanDnsProbeAllowed(address: String, info: LanNetworkInfo?, openPorts: List): Boolean = + openPorts.any { it.port == 53 } || info?.dnsServers.orEmpty().any { it.substringBefore('%') == address } diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/lan/VersionBind.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/VersionBind.kt new file mode 100644 index 0000000..d8b9056 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/lan/VersionBind.kt @@ -0,0 +1,29 @@ +package cz.netkit.shared.lan + +/* + * `version.bind` CH TXT (zadání 39 §2.4): the version string a DNS server may disclose. Encoding + * and the bounded parser are the existing DnsMessage codec; this only adds the CHAOS question. + */ + +const val DNS_CLASS_CH = 3 +private val VERSION_BIND = DnsName(listOf("version", "bind")) + +/** Standard query, RD clear, one question `version.bind. CH TXT`. */ +fun versionBindQuery(id: Int): ByteArray = encodeDnsQuery(id, listOf(DnsQuestion(VERSION_BIND, DNS_TYPE_TXT, dnsClass = DNS_CLASS_CH))) + +/** + * @property rcode DNS response code (0 = answered; 5 REFUSED / 4 NOTIMP are common and mean "not disclosed"). + * @property version first TXT answer for version.bind in class CH, sanitized; null when none. + */ +data class VersionBindReply(val rcode: Int, val version: String?) + +/** A response to our [id] and question; null for anything else (wrong ID, a query, malformed). */ +fun parseVersionBind(packet: ByteArray, length: Int, id: Int): VersionBindReply? { + val message = parseDnsMessage(packet, length) ?: return null + if (!message.isResponse || message.id != id || message.opcode != 0) return null + if (message.questions.size != 1 || !message.questions[0].name.matches(VERSION_BIND.labels)) return null + val text = message.records.firstOrNull { it.type == DNS_TYPE_TXT && it.dnsClass == DNS_CLASS_CH && it.name.matches(VERSION_BIND.labels) } + ?.let { (it.data as? DnsRecordData.Txt)?.entries?.joinToString("") } + ?.let { sanitizeLanText(it, 128).trim() }?.takeIf { it.isNotEmpty() } + return VersionBindReply(message.rcode, text) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/nav/AdaptiveNavigation.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/nav/AdaptiveNavigation.kt new file mode 100644 index 0000000..5819a9c --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/nav/AdaptiveNavigation.kt @@ -0,0 +1,9 @@ +package cz.netkit.shared.nav + +enum class NavigationPlacement { BOTTOM, RAIL, HIDDEN } + +fun navigationPlacement(widthDp: Int, landscape: Boolean, activeTerminalVisible: Boolean): NavigationPlacement = when { + landscape && activeTerminalVisible -> NavigationPlacement.HIDDEN + widthDp >= 600 -> NavigationPlacement.RAIL + else -> NavigationPlacement.BOTTOM +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/nav/AppTarget.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/nav/AppTarget.kt new file mode 100644 index 0000000..4b705dd --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/nav/AppTarget.kt @@ -0,0 +1,130 @@ +package cz.netkit.shared.nav + +/* + * Navigation targets that may arrive from outside the app (zadání 36 §2.1): launcher shortcuts, + * pinned shortcuts, the Quick Settings tile, the WoL widget and the SSH session notification (zadání 42). MainActivity is exported, so any + * app can send these intents; the parser therefore accepts only a fixed whitelist and a bounded + * local record ID. A target never carries a hostname, MAC, command or password, and opening a + * target never starts an action by itself (the user still confirms SSH or taps "Wake"). + */ + +/** Intent action for every external navigation request. */ +const val APP_TARGET_ACTION = "cz.netkit.app.action.OPEN" + +/** The single string extra with the encoded target, e.g. `spectrum` or `ssh_profile/`. */ +const val APP_TARGET_EXTRA = "cz.netkit.app.extra.TARGET" + +/** Longest accepted local record ID (UUIDs have 36 characters). */ +const val APP_TARGET_ID_MAX = 64 + +/** Longest accepted encoded target; anything longer is ignored without parsing. */ +const val APP_TARGET_MAX = 96 + +/** Tools of the LAN "Nástroje" segment that a target may open. Names match `LanTool` lowercased. */ +enum class AppLanTool(val key: String) { PING("ping"), TRACE("trace"), PORTS("ports"), DNS("dns"), MDNS("mdns"), SUBNET("subnet") } + +sealed interface AppTarget { + /** Přehled (Signal tab). */ + data object Signal : AppTarget + data object Spectrum : AppTarget + /** SSH tab (session notification, zadání 42); opens the tab only, never a session or profile. */ + data object Ssh : AppTarget + data class LanTools(val tool: AppLanTool) : AppTarget + /** Opens the SSH tab with the connect confirmation of this profile; never connects by itself. */ + data class SshProfile(val id: String) : AppTarget + /** + * Opens the WoL tab with this device highlighted; never sends a packet by itself. [key] is the opaque + * `wolDeviceKey` (16 hex digits), not the device ID: an imported ID may look like a hostname or IPv4 + * address, and a key also stops matching when another device later reuses the ID. + */ + data class WolDevice(val key: String) : AppTarget +} + +/** ID of an existing local record: ASCII letters, digits, `-`, `_` and `.`, at most [APP_TARGET_ID_MAX]. */ +fun isValidAppTargetId(id: String): Boolean = + id.length in 1..APP_TARGET_ID_MAX && id != "." && id != ".." && + id.all { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '-' || it == '_' || it == '.' } + +/** Opaque WoL device key: exactly 16 lowercase hex digits (see `cz.netkit.shared.wol.wolDeviceKey`). */ +fun isWolDeviceKey(value: String): Boolean = value.length == 16 && value.all { it in '0'..'9' || it in 'a'..'f' } + +/** Strict parser; null for anything outside the whitelist (the caller then shows the default tab). */ +fun parseAppTarget(raw: String?): AppTarget? { + if (raw == null || raw.isEmpty() || raw.length > APP_TARGET_MAX) return null + when (raw) { + "signal" -> return AppTarget.Signal + "spectrum" -> return AppTarget.Spectrum + "ssh" -> return AppTarget.Ssh + } + val slash = raw.indexOf('/') + if (slash <= 0 || raw.indexOf('/', slash + 1) >= 0) return null + val kind = raw.substring(0, slash) + val value = raw.substring(slash + 1) + return when (kind) { + "lan_tools" -> AppLanTool.entries.firstOrNull { it.key == value }?.let(AppTarget::LanTools) + "ssh_profile" -> value.takeIf(::isValidAppTargetId)?.let(AppTarget::SshProfile) + "wol_device" -> value.takeIf(::isWolDeviceKey)?.let(AppTarget::WolDevice) + else -> null + } +} + +/** Inverse of [parseAppTarget]; requires a valid ID (callers check [isValidAppTargetId] first). */ +fun AppTarget.encode(): String = when (this) { + AppTarget.Signal -> "signal" + AppTarget.Spectrum -> "spectrum" + AppTarget.Ssh -> "ssh" + is AppTarget.LanTools -> "lan_tools/${tool.key}" + is AppTarget.SshProfile -> { require(isValidAppTargetId(id)); "ssh_profile/$id" } + is AppTarget.WolDevice -> { require(isWolDeviceKey(key)); "wol_device/$key" } +} + +/** + * Keeps a record target only when the record still exists; static targets always pass. + * `null` record lists mean "could not be read" and drop the record target too. + */ +fun resolveAppTarget(target: AppTarget?, sshProfileIds: Collection?, wolDeviceKeys: Collection?): AppTarget? = + when (target) { + is AppTarget.SshProfile -> target.takeIf { sshProfileIds?.contains(it.id) == true } + is AppTarget.WolDevice -> target.takeIf { wolDeviceKeys?.contains(it.key) == true } + else -> target + } + +/** Shortcut ID of a pinned record shortcut; equal to the encoded target, so it is unique per record. */ +fun AppTarget.shortcutId(): String = encode() + +/** A pinned shortcut as the launcher reports it. */ +data class PinnedShortcut(val id: String, val enabled: Boolean, val label: String) + +/** What to change on pinned record shortcuts so they match the stored records. */ +data class PinnedShortcutPlan(val disable: List, val enable: List, val relabel: Map) { + val isEmpty: Boolean get() = disable.isEmpty() && enable.isEmpty() && relabel.isEmpty() +} + +/** Record kinds that can have pinned shortcuts; [target] is null for a value outside the whitelist. */ +enum class AppRecordKind(internal val prefix: String) { + /** Record value = SSH profile ID (app-generated UUID, also for imported profiles). */ + SSH_PROFILE("ssh_profile/"), + /** Record value = opaque `wolDeviceKey`, never the device ID. */ + WOL_DEVICE("wol_device/"); + fun target(value: String): AppTarget? = parseAppTarget(prefix + value) +} + +/** + * Syncs pinned shortcuts of one record kind with a successfully read record list: a deleted (or, for + * WoL, replaced) record disables its shortcut (with a message, the app cannot remove it from the home + * screen), the same record restored enables it again and a renamed one gets the new label. + * Shortcuts of other kinds, static shortcuts and values outside the whitelist are left alone. + * [records] maps record value (see [AppRecordKind]) to its current label. + */ +fun planPinnedShortcutSync(kind: AppRecordKind, pinned: List, records: Map): PinnedShortcutPlan { + val wanted = records.entries.mapNotNull { (value, label) -> kind.target(value)?.let { it.shortcutId() to label } }.toMap() + val own = pinned.filter { it.id.startsWith(kind.prefix) && parseAppTarget(it.id) != null } + return PinnedShortcutPlan( + disable = own.filter { it.enabled && it.id !in wanted }.map { it.id }, + enable = own.filter { !it.enabled && it.id in wanted }.map { it.id }, + relabel = own.mapNotNull { shortcut -> wanted[shortcut.id]?.takeIf { it != shortcut.label }?.let { shortcut.id to it } }.toMap(), + ) +} + +/** The only extras a NetKit shortcut, tile or widget intent may carry. */ +fun appTargetExtras(target: AppTarget): Map = mapOf(APP_TARGET_EXTRA to target.encode()) diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatus.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatus.kt new file mode 100644 index 0000000..343c125 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatus.kt @@ -0,0 +1,222 @@ +package cz.netkit.shared.netstatus + +import cz.netkit.shared.publicip.IpFamily +import cz.netkit.shared.publicip.classifyPublicAddress +import cz.netkit.shared.wifi.validRssiDbm +import kotlinx.serialization.SerializationException +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.intOrNull +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/* + * Network status widget snapshot (zadání 37). The widget shows only what the app measured in the + * foreground (Přehled, speed test, Wi-Fi analyzer) plus what a tap on its refresh icon reads without + * location and without network traffic. Every part keeps its own wall-clock time, so the widget can + * show an honest age per part. SSID and public IP are opt-in (default off) and removed again when the + * option or the permission behind them goes away. + */ + +const val NET_STATUS_SCHEMA = 1 +/** The file is tiny; anything bigger is not ours. */ +const val NET_STATUS_MAX_BYTES = 16 * 1024 +/** Throttling of foreground measurements: at most one snapshot write per this interval. */ +const val NET_STATUS_WRITE_INTERVAL_MS = 30_000L +/** Older than this (newest part), the widget switches to the grey "open NetKit" state. */ +const val NET_STATUS_STALE_AFTER_MS = 24L * 60 * 60 * 1000 +/** A timestamp more than this in the future (clock moved back) has no trustworthy age: treated as stale. */ +const val NET_STATUS_FUTURE_TOLERANCE_MS = 5L * 60 * 1000 +/** A part measured further apart from the signal than this shows its own time on the widget. */ +const val NET_STATUS_SAME_MEASUREMENT_MS = 60_000L +/** Longest SSID kept (an SSID has at most 32 bytes; UTF-8 text is at most that many characters). */ +const val NET_STATUS_SSID_MAX = 32 +private const val PUBLIC_IP_MAX = 45 + +/** Where the radio values of [NetStatusRadio] come from. */ +@Serializable +enum class NetStatusRadioSource { + /** Přehled (live telemetry) or the Wi-Fi context of a finished speed test. */ + FOREGROUND, + /** The widget's refresh icon: RSSI, frequency and link rate without location. */ + WIDGET_REFRESH, +} + +/** + * Connected Wi-Fi link at [atMs] (wall clock). [wifi] = false: no Wi-Fi network at that time (all values null). + * Channel and band are derived from [frequencyMhz] (primary 20 MHz channel). + */ +@Serializable +data class NetStatusRadio( + val atMs: Long, + val wifi: Boolean, + val frequencyMhz: Int? = null, + val rssiDbm: Int? = null, + val rxLinkMbps: Int? = null, + val txLinkMbps: Int? = null, + val source: NetStatusRadioSource = NetStatusRadioSource.FOREGROUND, +) + +/** Channel width of the connected AP from a foreground Wi-Fi scan; shown only while the primary frequency matches. */ +@Serializable +data class NetStatusWidth(val atMs: Long, val frequencyMhz: Int, val widthMhz: Int) + +/** ICMP RTT to the Wi-Fi default gateway from Přehled. */ +@Serializable +data class NetStatusGateway(val atMs: Long, val latencyMs: Double) + +/** The last finished speed test (start time, results, unloaded latency). */ +@Serializable +data class NetStatusSpeed(val atMs: Long, val downloadMbps: Double? = null, val uploadMbps: Double? = null, val pingMs: Double? = null) + +/** A text value with its measurement time (SSID, public IP). */ +@Serializable +data class NetStatusLabel(val atMs: Long, val value: String) + +/** Widget options (configuration activity); both default off. They apply to every status widget. */ +@Serializable +data class NetStatusSettings(val showSsid: Boolean = false, val showPublicIp: Boolean = false) + +/** The whole file: options + snapshot parts. */ +@Serializable +data class NetStatusData( + val schema: Int = NET_STATUS_SCHEMA, + val settings: NetStatusSettings = NetStatusSettings(), + val radio: NetStatusRadio? = null, + val width: NetStatusWidth? = null, + val gateway: NetStatusGateway? = null, + val speed: NetStatusSpeed? = null, + val ssid: NetStatusLabel? = null, + val publicIp: NetStatusLabel? = null, +) + +/** + * What may be kept right now: SSID only with location permission (the only way the app could read it), + * public IP only while its lookup is enabled in Přehled. + */ +data class NetStatusPrivacy(val locationGranted: Boolean, val publicIpLookupEnabled: Boolean) + +/** Drops SSID and public IP whenever their option or the permission/setting behind them is off. */ +fun NetStatusData.sanitized(privacy: NetStatusPrivacy): NetStatusData = copy( + ssid = ssid.takeIf { settings.showSsid && privacy.locationGranted }, + publicIp = publicIp.takeIf { settings.showPublicIp && privacy.publicIpLookupEnabled }, +) + +/** The SSID state of one foreground reading: [value] null = none readable (redacted, no Wi-Fi). */ +data class NetStatusSsidReport(val atMs: Long, val value: String?) + +/** + * New foreground or refresh values. Only non-null parts change the snapshot, and a part replaces the + * stored one only when it is not older (a delayed foreground write never overwrites a newer refresh). + * Pending patches are merged by offer order inside [NetStatusRecorder], not by wall time. + */ +data class NetStatusPatch( + val radio: NetStatusRadio? = null, + val width: NetStatusWidth? = null, + val gateway: NetStatusGateway? = null, + val speed: NetStatusSpeed? = null, + val ssid: NetStatusSsidReport? = null, + val publicIp: NetStatusLabel? = null, +) + +private inline fun newest(old: T?, new: T?, at: (T) -> Long): T? = when { + new == null -> old + old == null -> new + at(new) >= at(old) -> new + else -> old +} + +/** + * Applies [patch] (invalid values dropped) at wall time [nowMs] and then the privacy rules. + * + * Revize kolo 1: a time later than [nowMs] + [NET_STATUS_FUTURE_TOLERANCE_MS] has no trustworthy order or age + * (the clock was moved backwards since). Such a stored part is dropped, so a new measurement replaces it + * instead of losing the time comparison forever; such a patch part is not stored. + */ +fun NetStatusData.applied(patch: NetStatusPatch, privacy: NetStatusPrivacy, nowMs: Long): NetStatusData { + val limit = nowMs + NET_STATUS_FUTURE_TOLERANCE_MS + fun trusted(value: T?, at: (T) -> Long): T? = value?.takeIf { at(it) <= limit } + val storedSsid = trusted(ssid) { it.atMs } + val reportedSsid = trusted(patch.ssid) { it.atMs } + val ssidNext = when { + reportedSsid == null -> storedSsid + storedSsid != null && reportedSsid.atMs < storedSsid.atMs -> storedSsid + else -> reportedSsid.value?.let { NetStatusLabel(reportedSsid.atMs, it) }?.takeIf(::validSsid) + } + return copy( + radio = newest(trusted(radio) { it.atMs }, trusted(patch.radio?.takeIf(::validRadio)) { it.atMs }) { it.atMs }, + width = newest(trusted(width) { it.atMs }, trusted(patch.width?.takeIf(::validWidth)) { it.atMs }) { it.atMs }, + gateway = newest(trusted(gateway) { it.atMs }, trusted(patch.gateway?.takeIf(::validGateway)) { it.atMs }) { it.atMs }, + speed = newest(trusted(speed) { it.atMs }, trusted(patch.speed?.takeIf(::validSpeed)) { it.atMs }) { it.atMs }, + ssid = ssidNext, + publicIp = newest(trusted(publicIp) { it.atMs }, trusted(patch.publicIp?.takeIf(::validPublicIp)) { it.atMs }) { it.atMs }, + ).sanitized(privacy) +} + +/** Radio values as the platform reports them, normalised (unknown = null). */ +fun netStatusRadio(atMs: Long, frequencyMhz: Int?, rssiDbm: Int?, rxLinkMbps: Int?, txLinkMbps: Int?, + source: NetStatusRadioSource): NetStatusRadio = NetStatusRadio( + atMs = atMs, wifi = true, + frequencyMhz = frequencyMhz?.takeIf { it in 1..100_000 }, + rssiDbm = validRssiDbm(rssiDbm), + rxLinkMbps = rxLinkMbps?.takeIf { it in 1..100_000 }, + txLinkMbps = txLinkMbps?.takeIf { it in 1..100_000 }, + source = source, +) + +private fun okTime(atMs: Long) = atMs > 0 +private fun okRate(value: Double?) = value == null || (value.isFinite() && value in 0.0..1_000_000.0) +private fun okMs(value: Double?) = value == null || (value.isFinite() && value in 0.0..600_000.0) + +internal fun validRadio(r: NetStatusRadio): Boolean = okTime(r.atMs) && + (r.frequencyMhz == null || r.frequencyMhz in 1..100_000) && (r.rssiDbm == null || validRssiDbm(r.rssiDbm) != null) && + (r.rxLinkMbps == null || r.rxLinkMbps in 1..100_000) && (r.txLinkMbps == null || r.txLinkMbps in 1..100_000) && + (r.wifi || listOf(r.frequencyMhz, r.rssiDbm, r.rxLinkMbps, r.txLinkMbps).all { it == null }) +internal fun validWidth(w: NetStatusWidth) = okTime(w.atMs) && w.frequencyMhz in 1..100_000 && w.widthMhz in setOf(20, 40, 80, 160, 320) +internal fun validGateway(g: NetStatusGateway) = okTime(g.atMs) && g.latencyMs.isFinite() && g.latencyMs in 0.0..600_000.0 +internal fun validSpeed(s: NetStatusSpeed) = okTime(s.atMs) && okRate(s.downloadMbps) && okRate(s.uploadMbps) && okMs(s.pingMs) && + (s.downloadMbps != null || s.uploadMbps != null) +internal fun validSsid(l: NetStatusLabel) = okTime(l.atMs) && l.value.isNotBlank() && l.value.length <= NET_STATUS_SSID_MAX && + l.value.none { it.isISOControl() } +/** A public address as the lookup classified it (numeric, global); never a host name. */ +internal fun validPublicIp(l: NetStatusLabel) = okTime(l.atMs) && l.value.length <= PUBLIC_IP_MAX && + IpFamily.entries.any { classifyPublicAddress(l.value, it).address != null } + +class NetStatusCorrupt(message: String) : Exception(message) + +/** Strict JSON codec of the snapshot file (`noBackupFilesDir`, never in a backup). */ +object NetStatusCodec { + private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true } + + /** Invalid parts are dropped before writing; the result always decodes again. */ + fun encode(data: NetStatusData): String { + val clean = data.copy( + schema = NET_STATUS_SCHEMA, + radio = data.radio?.takeIf(::validRadio), width = data.width?.takeIf(::validWidth), + gateway = data.gateway?.takeIf(::validGateway), speed = data.speed?.takeIf(::validSpeed), + ssid = data.ssid?.takeIf(::validSsid), publicIp = data.publicIp?.takeIf(::validPublicIp), + ) + val text = json.encodeToString(NetStatusData.serializer(), clean) + require(text.length <= NET_STATUS_MAX_BYTES) { "net status too large" } + return text + } + + /** Unknown schema, oversize, malformed JSON or an invalid part = [NetStatusCorrupt]. */ + fun decode(text: String): NetStatusData { + if (text.length > NET_STATUS_MAX_BYTES) throw NetStatusCorrupt("size") + try { + val schema = json.parseToJsonElement(text).jsonObject["schema"]?.jsonPrimitive?.intOrNull + if (schema != NET_STATUS_SCHEMA) throw NetStatusCorrupt("schema") + val data = json.decodeFromString(NetStatusData.serializer(), text) + val valid = data.radio?.let(::validRadio) != false && data.width?.let(::validWidth) != false && + data.gateway?.let(::validGateway) != false && data.speed?.let(::validSpeed) != false && + data.ssid?.let(::validSsid) != false && data.publicIp?.let(::validPublicIp) != false + if (!valid) throw NetStatusCorrupt("values") + return data + } catch (_: SerializationException) { + throw NetStatusCorrupt("json") + } catch (_: IllegalArgumentException) { + throw NetStatusCorrupt("json") + } + } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRecorder.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRecorder.kt new file mode 100644 index 0000000..f37c735 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRecorder.kt @@ -0,0 +1,131 @@ +package cz.netkit.shared.netstatus + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** The snapshot file: atomic read-modify-write. */ +interface NetStatusStore { + suspend fun read(): NetStatusData + /** Applies [transform] to the current data, stores it (if it changed) and returns it. */ + suspend fun update(transform: (NetStatusData) -> NetStatusData): NetStatusData +} + +/** + * Writes foreground measurements into the widget snapshot (zadání 37 §2.1–2.5). + * + * - [offer] (Přehled at 1 Hz, speed test, Wi-Fi analyzer): parts are merged in memory and written at most + * once per [intervalMs] (the first offer after a quiet period at once, the rest as one trailing write + * when the interval has passed). The trailing write runs in [scope] (process lifetime), not in a screen. + * - [update] (options, deletions, the widget's refresh tap): written at once; privacy deletions are never delayed. + * - Every write, deletion and option change runs under one write lock, and the [NetStatusPrivacy] check + * happens inside it right before the store write (revize kolo 1): a write that read "allowed" can never + * land after a deletion that followed the revocation. A revoked location permission or a disabled public + * IP lookup therefore removes the stored value on the next write as well. + * - Pending parts are merged by offer order (monotonic [elapsedMs], taken when [offer] is called), not by + * wall-clock time, so a clock moved backwards cannot make a later measurement lose. Against the stored + * snapshot, a part whose wall time lies in the future ([nowMs] + tolerance) is untrusted and replaced. + * - [onChanged] runs after a write that changed the data (redraw the widgets). + */ +class NetStatusRecorder( + private val scope: CoroutineScope, + private val store: NetStatusStore, + private val privacy: suspend () -> NetStatusPrivacy, + private val elapsedMs: () -> Long, + private val nowMs: () -> Long, + private val onChanged: suspend (NetStatusData) -> Unit, + private val intervalMs: Long = NET_STATUS_WRITE_INTERVAL_MS, +) { + private val mutex = Mutex() + /** Serializes privacy check + store write of every change (throttled, immediate, deletion). */ + private val writeLock = Mutex() + private var pending = PendingPatch() + private var lastWriteElapsedMs: Long? = null + private var writer: Job? = null + + /** Queues foreground values; returns at once (the write happens in [scope]). */ + fun offer(patch: NetStatusPatch) { + val order = elapsedMs() + scope.launch { + mutex.withLock { + pending = pending.with(patch, order) + if (writer == null) writer = scope.launch { writeLoop() } + } + } + } + + private suspend fun writeLoop() { + while (true) { + val wait = mutex.withLock { lastWriteElapsedMs?.let { it + intervalMs - elapsedMs() } ?: 0L } + if (wait > 0) delay(wait) + val patch = mutex.withLock { pending.toPatch().also { pending = PendingPatch() } } + if (patch != null) { + try { + write { data, access -> data.applied(patch, access, nowMs()) } + } catch (cancel: CancellationException) { + throw cancel + } catch (_: Exception) { + // Storage failure: these values are lost; the next offer tries again after the interval. + } + } + mutex.withLock { + lastWriteElapsedMs = elapsedMs() + if (pending.isEmpty) { writer = null; return } + } + } + } + + /** Immediate, unthrottled change (options, deletions); privacy applied after [transform]. */ + suspend fun update(transform: (NetStatusData) -> NetStatusData): NetStatusData = + write { data, access -> transform(data).sanitized(access) } + + /** Immediate, unthrottled measurement (the widget's refresh tap). */ + suspend fun applyNow(patch: NetStatusPatch): NetStatusData = write { data, access -> data.applied(patch, access, nowMs()) } + + /** Deletes SSID / public IP the current options or permissions no longer allow (app start, widget update). */ + suspend fun enforcePrivacy(): NetStatusData = update { it } + + private suspend fun write(transform: (NetStatusData, NetStatusPrivacy) -> NetStatusData): NetStatusData { + var changed = false + val result = writeLock.withLock { + // Read inside the lock, right before the write: no other change can interleave. + val access = privacy() + store.update { before -> transform(before, access).also { changed = it != before } } + } + if (changed) onChanged(result) + return result + } +} + +/** Pending parts with the offer order each came with; a later offer wins per part, whatever its wall time. */ +private class PendingPatch( + val radio: Pair? = null, + val width: Pair? = null, + val gateway: Pair? = null, + val speed: Pair? = null, + val ssid: Pair? = null, + val publicIp: Pair? = null, +) { + val isEmpty get() = listOf(radio, width, gateway, speed, ssid, publicIp).all { it == null } + + fun with(patch: NetStatusPatch, order: Long) = PendingPatch( + radio = pick(radio, patch.radio, order), width = pick(width, patch.width, order), + gateway = pick(gateway, patch.gateway, order), speed = pick(speed, patch.speed, order), + ssid = pick(ssid, patch.ssid, order), publicIp = pick(publicIp, patch.publicIp, order), + ) + + fun toPatch(): NetStatusPatch? = if (isEmpty) null else NetStatusPatch( + radio = radio?.second, width = width?.second, gateway = gateway?.second, + speed = speed?.second, ssid = ssid?.second, publicIp = publicIp?.second, + ) + + private fun pick(old: Pair?, new: T?, order: Long): Pair? = when { + new == null -> old + old == null || order >= old.first -> order to new + else -> old + } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRefresh.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRefresh.kt new file mode 100644 index 0000000..a6843c4 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRefresh.kt @@ -0,0 +1,72 @@ +package cz.netkit.shared.netstatus + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.withTimeoutOrNull + +/** Whole refresh tap: read, write and redraw, inside the receiver's ~10 s (zadání 37 §2.2). */ +const val NET_STATUS_REFRESH_BUDGET_MS = 8_000L +/** The radio read alone (binder calls); the rest of the budget is for the write and the redraw. */ +const val NET_STATUS_REFRESH_READ_MS = 3_000L + +/** + * What the refresh tap may read: radio values only. There is deliberately no SSID/BSSID here — the + * platform reader runs without location (no `FLAG_INCLUDE_LOCATION_INFO`) and without network traffic. + */ +data class NetStatusRadioReading(val frequencyMhz: Int?, val rssiDbm: Int?, val rxLinkMbps: Int?, val txLinkMbps: Int?) + +fun interface NetStatusRadioReader { + /** The connected Wi-Fi link, or `null` without a Wi-Fi network. Must be cancellable. */ + suspend fun read(): NetStatusRadioReading? +} + +enum class NetStatusRefreshResult { UPDATED, NO_WIFI, TIMEOUT, FAILED } + +/** + * The widget's refresh tap: reads the current radio values and stores them as a new + * [NetStatusRadioSource.WIDGET_REFRESH] radio part; everything else (SSID, gateway, speed test, + * public IP, width) stays from the snapshot with its own time. No Wi-Fi = a radio part with `wifi=false`. + * The whole call ends within [budgetMs] even if the reader or the store hangs (then nothing changes). + */ +suspend fun refreshNetStatus( + reader: NetStatusRadioReader, + recorder: NetStatusRecorder, + nowMs: () -> Long, + budgetMs: Long = NET_STATUS_REFRESH_BUDGET_MS, + readMs: Long = NET_STATUS_REFRESH_READ_MS, +): NetStatusRefreshResult = withTimeoutOrNull(budgetMs) { + val reading = try { + withTimeoutOrNull(minOf(readMs, budgetMs)) { Result.success(reader.read()) } + } catch (cancel: CancellationException) { + throw cancel + } catch (_: Exception) { + Result.failure(IllegalStateException("read failed")) + } ?: return@withTimeoutOrNull NetStatusRefreshResult.TIMEOUT + if (reading.isFailure) return@withTimeoutOrNull NetStatusRefreshResult.FAILED + val value = reading.getOrNull() + val at = nowMs() + val radio = if (value == null) NetStatusRadio(atMs = at, wifi = false, source = NetStatusRadioSource.WIDGET_REFRESH) + else netStatusRadio(at, value.frequencyMhz, value.rssiDbm, value.rxLinkMbps, value.txLinkMbps, NetStatusRadioSource.WIDGET_REFRESH) + try { + recorder.applyNow(NetStatusPatch(radio = radio)) + } catch (cancel: CancellationException) { + throw cancel + } catch (_: Exception) { + return@withTimeoutOrNull NetStatusRefreshResult.FAILED + } + if (value == null) NetStatusRefreshResult.NO_WIFI else NetStatusRefreshResult.UPDATED +} ?: NetStatusRefreshResult.TIMEOUT + +private const val REFRESH_DATA_PREFIX = "netkit-netstatus://refresh/" + +/** + * Data URI of one widget's refresh broadcast: it gives every widget its own PendingIntent identity and + * carries nothing but the app widget ID. + */ +fun netStatusRefreshData(appWidgetId: Int): String = REFRESH_DATA_PREFIX + appWidgetId + +/** The app widget ID of [netStatusRefreshData], or `null` for anything else. */ +fun parseNetStatusRefreshData(data: String?): Int? { + val id = data?.removePrefix(REFRESH_DATA_PREFIX)?.takeIf { it != data } ?: return null + if (id.isEmpty() || id.length > 10 || !id.all { it in '0'..'9' }) return null + return id.toIntOrNull()?.takeIf { it > 0 } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusView.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusView.kt new file mode 100644 index 0000000..34972a7 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusView.kt @@ -0,0 +1,90 @@ +package cz.netkit.shared.netstatus + +import cz.netkit.shared.wifi.SignalQuality +import cz.netkit.shared.wifi.WifiBand +import cz.netkit.shared.wifi.bandForFrequency +import cz.netkit.shared.wifi.channelForFrequency +import cz.netkit.shared.wifi.signalQuality +import kotlin.math.abs + +/** Small = 2×1 (RSSI, channel, age), medium = 4×2 (+ link, gateway, speed test, opt-in SSID / public IP). */ +enum class NetStatusWidgetSize { SMALL, MEDIUM } + +enum class NetStatusState { + /** Some part is younger than [NET_STATUS_STALE_AFTER_MS]. */ + FRESH, + /** Everything is older (or its time lies in the future): grey "Open NetKit to measure" with the last time. */ + STALE, + /** Nothing measured yet. */ + NO_DATA, +} + +/** A value and, when it was not measured together with the signal, its own time to show next to it. */ +data class NetStatusStamped(val value: T, val ownTimeMs: Long?) + +/** + * Everything one widget drawing shows, decided without Android (zadání 37 §2.3–2.6). + * + * @property radioAtMs time of the signal values; the widget shows its age live ("před …") from it. + * @property lastAtMs newest part (stale state: "naposledy …"). + * @property wifi the radio part says Wi-Fi was connected; `false` = "Bez Wi-Fi"; `null` = no radio part. + * @property ssid / [publicIp] only with their option on, never on the lock screen. + */ +data class NetStatusView( + val size: NetStatusWidgetSize, + val state: NetStatusState, + val radioAtMs: Long? = null, + val lastAtMs: Long? = null, + val wifi: Boolean? = null, + val fromRefresh: Boolean = false, + val rssiDbm: Int? = null, + val quality: SignalQuality = SignalQuality.UNKNOWN, + val channel: Int? = null, + val band: WifiBand = WifiBand.UNKNOWN, + val widthMhz: Int? = null, + val rxLinkMbps: Int? = null, + val txLinkMbps: Int? = null, + val gatewayMs: NetStatusStamped? = null, + val speed: NetStatusSpeed? = null, + val ssid: NetStatusStamped? = null, + val publicIp: NetStatusStamped? = null, +) + +/** + * The widget content for [data] at [nowMs]. On the lock screen ([lockscreen], Android 15+ keyguard host) + * SSID and public IP are never shown, whatever the options say. + */ +fun netStatusView(data: NetStatusData, nowMs: Long, size: NetStatusWidgetSize, lockscreen: Boolean): NetStatusView { + val radio = data.radio + val times = listOfNotNull(radio?.atMs, data.gateway?.atMs, data.speed?.atMs) + val last = times.maxOrNull() ?: return NetStatusView(size, NetStatusState.NO_DATA) + val age = nowMs - last + if (age > NET_STATUS_STALE_AFTER_MS || age < -NET_STATUS_FUTURE_TOLERANCE_MS) { + return NetStatusView(size, NetStatusState.STALE, radioAtMs = radio?.atMs, lastAtMs = last) + } + fun own(atMs: Long): Long? = atMs.takeIf { radio == null || abs(it - radio.atMs) > NET_STATUS_SAME_MEASUREMENT_MS } + val frequency = radio?.frequencyMhz.takeIf { radio?.wifi == true } + val base = NetStatusView( + size = size, + state = NetStatusState.FRESH, + radioAtMs = radio?.atMs, + lastAtMs = last, + wifi = radio?.wifi, + fromRefresh = radio?.source == NetStatusRadioSource.WIDGET_REFRESH, + rssiDbm = radio?.rssiDbm.takeIf { radio?.wifi == true }, + quality = radio?.rssiDbm?.takeIf { radio.wifi }?.let(::signalQuality) ?: SignalQuality.UNKNOWN, + channel = frequency?.let(::channelForFrequency), + band = frequency?.let(::bandForFrequency) ?: WifiBand.UNKNOWN, + ) + if (size == NetStatusWidgetSize.SMALL) return base + val showPrivate = !lockscreen + return base.copy( + widthMhz = data.width?.takeIf { frequency != null && it.frequencyMhz == frequency }?.widthMhz, + rxLinkMbps = radio?.rxLinkMbps.takeIf { radio?.wifi == true }, + txLinkMbps = radio?.txLinkMbps.takeIf { radio?.wifi == true }, + gatewayMs = data.gateway?.let { NetStatusStamped(it.latencyMs, own(it.atMs)) }, + speed = data.speed, + ssid = data.ssid?.takeIf { showPrivate && data.settings.showSsid }?.let { NetStatusStamped(it.value, own(it.atMs)) }, + publicIp = data.publicIp?.takeIf { showPrivate && data.settings.showPublicIp }?.let { NetStatusStamped(it.value, own(it.atMs)) }, + ) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/publicip/PublicIp.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/publicip/PublicIp.kt index 25a70e8..2de62ad 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/publicip/PublicIp.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/publicip/PublicIp.kt @@ -160,11 +160,11 @@ private fun cymruFields(line: String): List? { return text.split('|').map { it.trim() }.takeIf { it.size == 5 } } -private data class NumericIp(val family: IpFamily, val words: List) { +internal data class NumericIp(val family: IpFamily, val words: List) { fun text(): String = if (family == IpFamily.V4) ipv4Text((words[0].toLong() shl 16) or words[1].toLong()) else ipv6Text(words) } -private fun parseIp(text: String): NumericIp? { +internal fun parseIp(text: String): NumericIp? { if (text.isEmpty() || text.length > 45) return null if (':' !in text) { val value = ipv4Number(text) ?: return null @@ -192,7 +192,7 @@ private fun parseIp(text: String): NumericIp? { } /** RFC 5952 §4: longest zero run, first on ties, never compress a single zero. */ -private fun ipv6Text(words: List): String { +internal fun ipv6Text(words: List): String { var bestStart = -1 var bestLength = 1 var i = 0 diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/publicip/Rdap.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/publicip/Rdap.kt new file mode 100644 index 0000000..439814a --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/publicip/Rdap.kt @@ -0,0 +1,108 @@ +package cz.netkit.shared.publicip + +import cz.netkit.shared.json.JSON_MAX_DEPTH +import cz.netkit.shared.json.jsonNestingDepth +import cz.netkit.shared.lan.sanitizeLanText +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.* + +const val RDAP_MAX_BYTES = 256 * 1024 + +/** This outbound gate also excludes documentation and protocol-assignment ranges. */ +fun rdapPath(input: String): String? { + val value = input.trim() + if (value.length > 45) return null + val digits = if (value.startsWith("AS", ignoreCase = true)) value.drop(2) else value + if (digits.isNotEmpty() && digits.all { it in '0'..'9' }) { + val asn = digits.toLongOrNull() ?: return null + if (asn !in 1..4294967294L || asn == 23456L || asn in 64496..65551 || asn >= 4200000000L) return null + return "autnum/$asn" + } + val ip = parseIp(value) ?: return null + return if (ip.isPublicDiagnosticTarget()) "ip/${ip.text()}" else null +} + +/** Numeric public targets for RDAP queries and automatic Web/TLS redirects. */ +fun isPublicDiagnosticAddress(value: String): Boolean = parseIp(value)?.isPublicDiagnosticTarget() == true + +private fun NumericIp.isPublicDiagnosticTarget(): Boolean { + if (classifyPublicAddress(text(), family).address == null) return false + val w = words + val reserved = if (family == IpFamily.V4) { + val prefix = text().substringBeforeLast('.') + prefix in setOf("192.0.0", "192.0.2", "192.88.99", "198.51.100", "203.0.113") + } else { + w[0] == 0x2001 && (w[1] < 0x200 || w[1] == 0xdb8) || + w[0] == 0x2002 || w[0] == 0x3fff && w[1] < 0x1000 + } + return !reserved +} + +data class RdapInfo( + val network: String?, val name: String?, val country: String?, val organization: String?, + val abuseEmail: String?, val asn: String?, +) + +private fun JsonElement?.scalar() = (this as? JsonPrimitive)?.contentOrNull?.let { sanitizeLanText(it) }?.takeIf { it.isNotBlank() } +private fun JsonObject.field(key: String) = this[key].scalar() +private fun JsonElement?.items() = this as? JsonArray ?: emptyList() + +/** Prefer the registry's CIDR extension. Some registries supply only inclusive endpoints. */ +private fun cidrs(root: JsonObject): String? { + val prefixes = root["cidr0_cidrs"].items().mapNotNull { item -> + val entry = item as? JsonObject ?: return@mapNotNull null + val ip = parseIp(entry.field("v4prefix") ?: entry.field("v6prefix") ?: "") ?: return@mapNotNull null + val length = entry.field("length")?.toIntOrNull()?.takeIf { it in 0..ip.words.size * 16 } ?: return@mapNotNull null + "${ip.text()}/$length" + } + if (prefixes.isNotEmpty()) return prefixes.joinToString(", ") + val first = parseIp(root.field("startAddress") ?: "") ?: return null + val last = parseIp(root.field("endAddress") ?: "") ?: return null + if (first.family != last.family) return null + fun bits(ip: NumericIp) = ip.words.joinToString("") { it.toString(2).padStart(16, '0') } + var cursor = bits(first) + val end = bits(last) + if (cursor > end) return null + // Largest aligned block starting at cursor whose last address still fits in the range. + return buildList { + while (true) { + var prefix = cursor.trimEnd('0') + while (prefix.padEnd(end.length, '1') > end) prefix += '0' + val words = cursor.chunked(16).map { it.toInt(2) } + add("${NumericIp(first.family, words).text()}/${prefix.length}") + val upper = prefix.padEnd(end.length, '1') + if (upper == end) break + cursor = (upper.substringBeforeLast('0') + "1").padEnd(end.length, '0') + } + }.joinToString(", ") +} + +fun parseRdap(text: String): RdapInfo? { + if (text.length > RDAP_MAX_BYTES || text.encodeToByteArray().size > RDAP_MAX_BYTES || + jsonNestingDepth(text) > JSON_MAX_DEPTH) return null + val root = try { Json.parseToJsonElement(text) as? JsonObject } catch (_: SerializationException) { null } ?: return null + var org: String? = null + var abuse: String? = null + // JSON_MAX_DEPTH bounds nested entity/vCard traversal before tree construction. + fun entities(parent: JsonObject) { + for (element in parent["entities"].items()) { + val entity = element as? JsonObject ?: continue + val roles = entity["roles"].items().mapNotNull { it.scalar() } + val fields = entity["vcardArray"].items().getOrNull(1).items() + fun card(key: String) = fields.firstNotNullOfOrNull { field -> + val row = field.items() + row.getOrNull(3).scalar()?.takeIf { row.firstOrNull().scalar() == key } + } + if (org == null && "registrant" in roles) org = card("org") ?: card("fn") ?: entity.field("handle") + if (abuse == null && "abuse" in roles) abuse = card("email") + entities(entity) + } + } + entities(root) + val start = root.field("startAutnum") + val end = root.field("endAutnum") + val asn = if (start != null) "AS$start" + (end?.takeIf { it != start }?.let { "–AS$it" } ?: "") + else root["arin_originas0_originautnums"].items().mapNotNull { it.scalar()?.toLongOrNull() } + .joinToString(", ") { "AS$it" }.ifEmpty { null } + return RdapInfo(cidrs(root), root.field("name"), root.field("country"), org, abuse, asn) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/report/DiagnosticReport.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/report/DiagnosticReport.kt new file mode 100644 index 0000000..fb8e3ae --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/report/DiagnosticReport.kt @@ -0,0 +1,312 @@ +package cz.netkit.shared.report + +import cz.netkit.shared.lan.LanNumericAddress +import cz.netkit.shared.lan.lanNumericAddress +import cz.netkit.shared.lan.pingStatistics +import cz.netkit.shared.lan.sanitizeLanText +import cz.netkit.shared.net.NetKind +import cz.netkit.shared.net.isPrivateOrLocalTarget +import cz.netkit.shared.speed.SpeedEngine +import cz.netkit.shared.speed.SpeedRecord +import cz.netkit.shared.wifi.WifiBand +import cz.netkit.shared.wifi.isoUtc +import cz.netkit.shared.wifi.usableBssid +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +/* + * Zadání 47 §1: the diagnostic report of Přehled. Pure model and serialization; the app collects + * the input from what Přehled already measures and shows. The report never holds mobile cell + * identity (cell ID, TAC, PCI, EARFCN: location data, D31 "local only"), SSH or SecureOn secrets, + * or anything else outside [DiagnosticReportInput]; SSID, BSSID and the public IP are omitted + * unless the user switches them on ([DiagnosticReportOptions], default all off). + */ + +const val DIAGNOSTIC_REPORT_FORMAT = "netkit-diagnostic-report" +const val DIAGNOSTIC_REPORT_VERSION = 1 +/** Latency and loss cover this window before [DiagnosticReportInput.generatedAtMs]. */ +const val DIAGNOSTIC_LATENCY_WINDOW_S = 60 +private const val TEXT_MAX = 128 +private const val SSID_MAX = 64 +private const val DNS_MAX = 8 + +/** Wi-Fi link as Přehled reads it; [standard] is display text such as `802.11ax`. */ +data class DiagnosticWifiInput( + val ssid: String?, + val bssid: String?, + val rssiDbm: Int?, + val rxLinkMbps: Int?, + val txLinkMbps: Int?, + val frequencyMhz: Int?, + val channel: Int?, + val band: WifiBand, + val widthMhz: Int?, + val standard: String?, +) + +/** ICMP samples of one target inside the report window; `null` sample = lost echo. */ +data class DiagnosticLatencyInput(val target: String?, val samples: List) + +data class DiagnosticPublicIpInput(val ipv4: String?, val ipv6: String?, val asn: Long?, val provider: String?) + +/** + * Everything the report may contain. Deliberately no cellular field: Přehled's mobile card and + * the cell detail stay out of the report. [lastSpeedTest] is the newest LibreSpeed/NDT7 record, + * [lastIperf3] the newest iperf3 record of the speed-test history. + */ +data class DiagnosticReportInput( + val generatedAtMs: Long, + val appVersion: String, + val networkKind: NetKind?, + val metered: Boolean?, + val interfaceName: String?, + val ipv4: String?, + val ipv6: String?, + val gateway: String?, + val dnsServers: List, + val privateDns: Boolean, + val privateDnsHost: String?, + val dhcpServer: String?, + val mtu: Int?, + val wifi: DiagnosticWifiInput?, + val gatewayLatency: DiagnosticLatencyInput?, + val internetLatency: DiagnosticLatencyInput?, + val publicIp: DiagnosticPublicIpInput?, + val lastSpeedTest: SpeedRecord?, + val lastIperf3: SpeedRecord?, +) + +/** + * Identifying values are opt-in; the defaults share nothing that names the network or the line. + * [includePublicIp] also covers public link addresses, the Private DNS hostname and non-local iperf3 endpoints. + */ +data class DiagnosticReportOptions( + val includeSsid: Boolean = false, + val includeBssid: Boolean = false, + val includePublicIp: Boolean = false, +) + +@Serializable +data class ReportNetwork( + val type: String?, + val metered: Boolean?, + val interfaceName: String?, + val ipv4: String?, + val ipv6: String?, + val gateway: String?, + val dns: List, + val privateDns: Boolean, + val privateDnsHost: String?, + val dhcpServer: String?, + val mtu: Int?, +) + +@Serializable +data class ReportWifi( + val ssid: String?, + val bssid: String?, + val rssiDbm: Int?, + val rxLinkMbps: Int?, + val txLinkMbps: Int?, + val frequencyMhz: Int?, + val channel: Int?, + val band: String?, + val widthMhz: Int?, + val standard: String?, +) + +/** ICMP statistics of one target over the window; times in ms, rounded to 0.1. */ +@Serializable +data class ReportLatency( + val target: String?, + val sent: Int, + val received: Int, + val lossPercent: Double?, + val minMs: Double?, + val avgMs: Double?, + val maxMs: Double?, + val jitterMs: Double?, +) + +@Serializable +data class ReportPublicIp(val ipv4: String?, val ipv6: String?, val asn: Long?, val provider: String?) + +/** One speed-test or iperf3 result; never the SSID of the measured network. */ +@Serializable +data class ReportSpeed( + val time: String, + val engine: String, + val server: String, + val networkType: String, + val downloadMbps: Double?, + val uploadMbps: Double?, + val latencyMs: Double?, + val jitterMs: Double?, + val retransmits: Long?, + val retransPercent: Double?, + val partial: Boolean, +) + +@Serializable +data class DiagnosticReport( + val format: String = DIAGNOSTIC_REPORT_FORMAT, + val version: Int = DIAGNOSTIC_REPORT_VERSION, + val generatedAt: String, + val appVersion: String, + val network: ReportNetwork, + val wifi: ReportWifi?, + val latencyWindowSeconds: Int = DIAGNOSTIC_LATENCY_WINDOW_S, + val gatewayLatency: ReportLatency?, + val internetLatency: ReportLatency?, + val publicIp: ReportPublicIp?, + val speedTest: ReportSpeed?, + val iperf3: ReportSpeed?, +) + +/** Validated, sanitized, rounded and redacted by [options]. */ +fun buildDiagnosticReport(input: DiagnosticReportInput, options: DiagnosticReportOptions = DiagnosticReportOptions()): DiagnosticReport { + val wifi = input.wifi?.let { w -> + ReportWifi( + ssid = if (options.includeSsid) w.ssid?.let { clean(it, SSID_MAX) } else null, + bssid = if (options.includeBssid) usableBssid(w.bssid) else null, + rssiDbm = w.rssiDbm?.takeIf { it in -126..-1 }, + rxLinkMbps = w.rxLinkMbps?.takeIf { it in 0..100_000 }, + txLinkMbps = w.txLinkMbps?.takeIf { it in 0..100_000 }, + frequencyMhz = w.frequencyMhz?.takeIf { it in 1..100_000 }, + channel = w.channel?.takeIf { it in 1..233 }, + band = bandName(w.band), + widthMhz = w.widthMhz?.takeIf { it in setOf(20, 40, 80, 160, 320) }, + standard = w.standard?.let { clean(it, 32) }, + ) + } + val publicIp = if (!options.includePublicIp) null else input.publicIp?.let { p -> + ReportPublicIp(numeric(p.ipv4), numeric(p.ipv6), p.asn?.takeIf { it in 1..4_294_967_295L }, p.provider?.let { clean(it, TEXT_MAX) }) + }?.takeIf { it.ipv4 != null || it.ipv6 != null || it.asn != null || it.provider != null } + return DiagnosticReport( + generatedAt = isoUtc(input.generatedAtMs), + appVersion = clean(input.appVersion, 32) ?: "?", + network = ReportNetwork( + type = input.networkKind?.let(::netKindName), + metered = input.metered, + interfaceName = input.interfaceName?.let { clean(it, 32) }, + ipv4 = consented(numeric(input.ipv4), options), + ipv6 = consented(numeric(input.ipv6), options), + gateway = consented(numeric(input.gateway), options), + dns = input.dnsServers.mapNotNull(::numeric).distinct().take(DNS_MAX), + privateDns = input.privateDns, + privateDnsHost = if (options.includePublicIp) input.activePrivateDnsHost() else null, + dhcpServer = consented(numeric(input.dhcpServer)?.takeIf { it != "0.0.0.0" }, options), + mtu = input.mtu?.takeIf { it in 68..65_535 }, + ), + wifi = wifi, + gatewayLatency = input.gatewayLatency?.let { latency(it)?.let { l -> l.copy(target = consented(l.target, options)) } }, + internetLatency = input.internetLatency?.let(::latency), + publicIp = publicIp, + speedTest = input.lastSpeedTest?.takeIf { it.engine != SpeedEngine.IPERF3 }?.let(::reportSpeed), + iperf3 = input.lastIperf3?.takeIf { it.engine == SpeedEngine.IPERF3 }?.let { record -> + val speed = reportSpeed(record) + if (options.includePublicIp || !record.serverNeedsConsent()) speed else speed.copy(server = "?") + }, + ) +} + +private val reportJson = Json { prettyPrint = true; encodeDefaults = true; explicitNulls = true } + +fun diagnosticReportJson(report: DiagnosticReport): String = reportJson.encodeToString(DiagnosticReport.serializer(), report) + +/** Speed record as it appears in the report (also used by the speed-test share text). */ +fun reportSpeed(record: SpeedRecord): ReportSpeed = ReportSpeed( + time = isoUtc(record.timestampMs), + engine = engineName(record.engine), + server = clean(record.serverName, TEXT_MAX) ?: "?", + networkType = netKindName(record.measuredKind), + downloadMbps = round(record.downloadMbps, 1), + uploadMbps = round(record.uploadMbps, 1), + latencyMs = round(record.idleLatencyMs, 1), + jitterMs = round(record.idleJitterMs, 1), + retransmits = record.retransmits?.takeIf { it >= 0 }, + retransPercent = round(record.retransPercent, 2), + partial = record.partial, +) + +private fun latency(input: DiagnosticLatencyInput): ReportLatency? { + if (input.samples.isEmpty()) return null + val stats = pingStatistics(input.samples.map { v -> v?.takeIf { it.isFinite() && it >= 0.0 } }) + return ReportLatency( + target = numeric(input.target), + sent = stats.sent, + received = stats.received, + lossPercent = round(stats.lossPercent, 1), + minMs = round(stats.minimum, 1), + avgMs = round(stats.average, 1), + maxMs = round(stats.maximum, 1), + jitterMs = round(stats.jitter, 1), + ) +} + +internal fun netKindName(kind: NetKind): String = when (kind) { + NetKind.WIFI -> "wifi" + NetKind.CELLULAR -> "cellular" + NetKind.ETHERNET -> "ethernet" + NetKind.VPN -> "vpn" + NetKind.OTHER -> "other" +} + +internal fun engineName(engine: SpeedEngine): String = when (engine) { + SpeedEngine.LIBRESPEED -> "librespeed" + SpeedEngine.NDT7 -> "ndt7" + SpeedEngine.IPERF3 -> "iperf3" +} + +private fun bandName(band: WifiBand): String? = when (band) { + WifiBand.GHZ_2_4 -> "2.4" + WifiBand.GHZ_5 -> "5" + WifiBand.GHZ_6 -> "6" + WifiBand.UNKNOWN -> null +} + +/** + * Revize kolo 1 (P1): an address of the phone's own link that is publicly routable (global IPv6, + * a public IPv4 on the interface, a public gateway) identifies the line just like the public IP, + * so it needs the same consent ([DiagnosticReportOptions.includePublicIp]). Local scopes + * (RFC 1918, CGNAT, link-local, loopback, ULA) stay; DNS resolvers are not the user's address. + */ +internal fun consented(address: String?, options: DiagnosticReportOptions): String? = + address?.takeIf { options.includePublicIp || isPrivateOrLocalTarget(it) } + +private fun DiagnosticReportInput.activePrivateDnsHost(): String? = + if (privateDns) privateDnsHost?.let { clean(it, 253) } else null + +/** iperf3 history stores host:port or [IPv6]:port. Only a verified local literal can pass without consent. */ +private fun SpeedRecord.serverNeedsConsent(): Boolean { + if (engine != SpeedEngine.IPERF3 || serverName == "?") return false + val host = serverName.substringBeforeLast(':', "") + val port = serverName.substringAfterLast(':') + if (port.isEmpty() || port.any { it !in '0'..'9' } || port.toIntOrNull() !in 1..65535) return true + val literal = lanNumericAddress(host) ?: return true + return !isPrivateOrLocalTarget(literal.text) +} + +/** The switch stays available when local measurements contain identifiers, even with online lookups off. */ +fun hasConsentableAddresses(input: DiagnosticReportInput): Boolean { + val publicIp = input.publicIp?.let { numeric(it.ipv4) != null || numeric(it.ipv6) != null || it.asn != null || !it.provider.isNullOrBlank() } == true + val own = listOf(input.ipv4, input.ipv6, input.gateway, input.dhcpServer, input.gatewayLatency?.target) + .mapNotNull(::numeric).any { it != "0.0.0.0" && !isPrivateOrLocalTarget(it) } + return publicIp || own || input.activePrivateDnsHost() != null || input.lastIperf3?.serverNeedsConsent() == true +} + +/** Numeric IPv4 / canonical IPv6 (zone dropped); anything else (a name, garbage) is omitted. */ +internal fun numeric(value: String?): String? = when (val parsed = value?.let { lanNumericAddress(it.substringBefore('%')) }) { + is LanNumericAddress.V4 -> parsed.text + is LanNumericAddress.V6 -> parsed.address.canonical + null -> null +} + +internal fun clean(value: String, max: Int): String? = sanitizeLanText(value.trim(), max).trim().ifEmpty { null } + +internal fun round(value: Double?, decimals: Int): Double? { + if (value == null || !value.isFinite()) return null + var factor = 1.0 + repeat(decimals) { factor *= 10.0 } + return kotlin.math.round(value * factor) / factor +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/report/ReportText.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/report/ReportText.kt new file mode 100644 index 0000000..a037353 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/report/ReportText.kt @@ -0,0 +1,182 @@ +package cz.netkit.shared.report + +import cz.netkit.shared.speed.SpeedRecord + +/* + * Plain-text forms of the diagnostic report (zadání 47 §1) and of one speed-test / iperf3 result + * (§4). Labels come from the app's string resources through [ReportLabels]; values are the same + * validated, sanitized values as in the JSON. Numbers use a dot and fixed decimals, so the text + * reads the same in a ticket whatever the phone's locale. + */ + +/** Every label of the text forms; [ReportLabels.english] is the fallback and the test reference. */ +enum class ReportLabel { + TITLE, SPEED_TITLE, TIME, APP_VERSION, SECTION_NETWORK, NETWORK_TYPE, METERED, INTERFACE, IPV4, IPV6, GATEWAY, DNS, + PRIVATE_DNS, DHCP_SERVER, MTU, SECTION_WIFI, SSID, BSSID, SIGNAL, LINK_RATE, CHANNEL, BAND, WIDTH, STANDARD, + SECTION_LATENCY, LATENCY_GATEWAY, LATENCY_INTERNET, LOSS, NO_DATA, SECTION_PUBLIC_IP, PUBLIC_IP, ASN, PROVIDER, + SECTION_SPEED, SECTION_IPERF3, SERVER, ENGINE, DOWNLOAD, UPLOAD, LATENCY, JITTER, RETRANSMITS, PARTIAL, + YES, NO, NET_WIFI, NET_CELLULAR, NET_ETHERNET, NET_VPN, NET_OTHER, +} + +fun interface ReportLabels { + fun label(key: ReportLabel): String + + companion object { + val english = ReportLabels { key -> + when (key) { + ReportLabel.TITLE -> "NetKit diagnostic report" + ReportLabel.SPEED_TITLE -> "NetKit speed test" + ReportLabel.TIME -> "Time" + ReportLabel.APP_VERSION -> "App version" + ReportLabel.SECTION_NETWORK -> "Network" + ReportLabel.NETWORK_TYPE -> "Network type" + ReportLabel.METERED -> "Metered" + ReportLabel.INTERFACE -> "Interface" + ReportLabel.IPV4 -> "IPv4" + ReportLabel.IPV6 -> "IPv6" + ReportLabel.GATEWAY -> "Gateway" + ReportLabel.DNS -> "DNS" + ReportLabel.PRIVATE_DNS -> "Private DNS" + ReportLabel.DHCP_SERVER -> "DHCP server" + ReportLabel.MTU -> "MTU" + ReportLabel.SECTION_WIFI -> "Wi-Fi" + ReportLabel.SSID -> "SSID" + ReportLabel.BSSID -> "BSSID" + ReportLabel.SIGNAL -> "Signal" + ReportLabel.LINK_RATE -> "Link rate RX/TX" + ReportLabel.CHANNEL -> "Channel" + ReportLabel.BAND -> "Band" + ReportLabel.WIDTH -> "Channel width" + ReportLabel.STANDARD -> "Standard" + ReportLabel.SECTION_LATENCY -> "Latency (last minute)" + ReportLabel.LATENCY_GATEWAY -> "Gateway" + ReportLabel.LATENCY_INTERNET -> "Internet" + ReportLabel.LOSS -> "loss" + ReportLabel.NO_DATA -> "no data" + ReportLabel.SECTION_PUBLIC_IP -> "Public IP" + ReportLabel.PUBLIC_IP -> "Address" + ReportLabel.ASN -> "ASN" + ReportLabel.PROVIDER -> "Provider" + ReportLabel.SECTION_SPEED -> "Last speed test" + ReportLabel.SECTION_IPERF3 -> "Last iperf3" + ReportLabel.SERVER -> "Server" + ReportLabel.ENGINE -> "Engine" + ReportLabel.DOWNLOAD -> "Download" + ReportLabel.UPLOAD -> "Upload" + ReportLabel.LATENCY -> "Latency" + ReportLabel.JITTER -> "Jitter" + ReportLabel.RETRANSMITS -> "Retransmits" + ReportLabel.PARTIAL -> "incomplete result" + ReportLabel.YES -> "yes" + ReportLabel.NO -> "no" + ReportLabel.NET_WIFI -> "Wi-Fi" + ReportLabel.NET_CELLULAR -> "Mobile data" + ReportLabel.NET_ETHERNET -> "Ethernet" + ReportLabel.NET_VPN -> "VPN" + ReportLabel.NET_OTHER -> "Other" + } + } + } +} + +/** Text form of [report]; sections without data are left out, the latency section always appears. */ +fun diagnosticReportText(report: DiagnosticReport, labels: ReportLabels = ReportLabels.english): String = buildString { + fun l(key: ReportLabel) = labels.label(key) + fun line(key: ReportLabel, value: String?) { if (value != null) append(l(key)).append(": ").append(value).append('\n') } + fun section(key: ReportLabel) { append('\n').append("== ").append(l(key)).append(" ==\n") } + append(l(ReportLabel.TITLE)).append('\n') + line(ReportLabel.TIME, report.generatedAt) + line(ReportLabel.APP_VERSION, report.appVersion) + + val net = report.network + section(ReportLabel.SECTION_NETWORK) + line(ReportLabel.NETWORK_TYPE, net.type?.let { netLabel(it, labels) } ?: l(ReportLabel.NO_DATA)) + line(ReportLabel.METERED, net.metered?.let { l(if (it) ReportLabel.YES else ReportLabel.NO) }) + line(ReportLabel.INTERFACE, net.interfaceName) + line(ReportLabel.IPV4, net.ipv4) + line(ReportLabel.IPV6, net.ipv6) + line(ReportLabel.GATEWAY, net.gateway) + line(ReportLabel.DNS, net.dns.takeIf { it.isNotEmpty() }?.joinToString(", ")) + if (net.privateDns) line(ReportLabel.PRIVATE_DNS, net.privateDnsHost ?: l(ReportLabel.YES)) + line(ReportLabel.DHCP_SERVER, net.dhcpServer) + line(ReportLabel.MTU, net.mtu?.toString()) + + report.wifi?.let { w -> + section(ReportLabel.SECTION_WIFI) + line(ReportLabel.SSID, w.ssid) + line(ReportLabel.BSSID, w.bssid) + line(ReportLabel.SIGNAL, w.rssiDbm?.let { "$it dBm" }) + if (w.rxLinkMbps != null || w.txLinkMbps != null) + line(ReportLabel.LINK_RATE, "${w.rxLinkMbps ?: "–"} / ${w.txLinkMbps ?: "–"} Mb/s") + line(ReportLabel.CHANNEL, w.channel?.let { channel -> w.frequencyMhz?.let { "$channel ($it MHz)" } ?: "$channel" }) + line(ReportLabel.BAND, w.band?.let { "$it GHz" }) + line(ReportLabel.WIDTH, w.widthMhz?.let { "$it MHz" }) + line(ReportLabel.STANDARD, w.standard) + } + + section(ReportLabel.SECTION_LATENCY) + fun latencyLine(key: ReportLabel, value: ReportLatency?) { + val text = if (value == null || value.received == 0 && value.sent == 0) l(ReportLabel.NO_DATA) else buildString { + value.target?.let { append(it).append(": ") } + if (value.received > 0) append("${num(value.minMs)}/${num(value.avgMs)}/${num(value.maxMs)} ms, ") + append(l(ReportLabel.LOSS)).append(' ').append(num(value.lossPercent)).append(" % (") + append(value.received).append('/').append(value.sent).append(')') + value.jitterMs?.let { append(", ").append(l(ReportLabel.JITTER).lowercase()).append(' ').append(num(it)).append(" ms") } + } + line(key, text) + } + if (report.gatewayLatency != null || report.wifi != null) latencyLine(ReportLabel.LATENCY_GATEWAY, report.gatewayLatency) + latencyLine(ReportLabel.LATENCY_INTERNET, report.internetLatency) + + report.publicIp?.let { p -> + section(ReportLabel.SECTION_PUBLIC_IP) + line(ReportLabel.PUBLIC_IP, listOfNotNull(p.ipv4, p.ipv6).takeIf { it.isNotEmpty() }?.joinToString(", ")) + line(ReportLabel.ASN, p.asn?.let { "AS$it" }) + line(ReportLabel.PROVIDER, p.provider) + } + report.speedTest?.let { section(ReportLabel.SECTION_SPEED); speedLines(it, labels, ::line) } + report.iperf3?.let { section(ReportLabel.SECTION_IPERF3); speedLines(it, labels, ::line) } +}.trimEnd('\n') + "\n" + +/** + * Share text of one speed-test or iperf3 result (§4): time, network type, server and engine, + * download/upload, latency, jitter and retransmits. The SSID only when [includeSsid]. + */ +fun speedShareText(record: SpeedRecord, labels: ReportLabels = ReportLabels.english, includeSsid: Boolean = false): String = buildString { + fun line(key: ReportLabel, value: String?) { if (value != null) append(labels.label(key)).append(": ").append(value).append('\n') } + append(labels.label(ReportLabel.SPEED_TITLE)).append('\n') + speedLines(reportSpeed(record), labels, ::line) + if (includeSsid) line(ReportLabel.SSID, record.ssid?.let { clean(it, 64) }) +}.trimEnd('\n') + "\n" + +private fun speedLines(speed: ReportSpeed, labels: ReportLabels, line: (ReportLabel, String?) -> Unit) { + line(ReportLabel.TIME, speed.time) + line(ReportLabel.NETWORK_TYPE, netLabel(speed.networkType, labels)) + line(ReportLabel.SERVER, speed.server) + line(ReportLabel.ENGINE, when (speed.engine) { "librespeed" -> "LibreSpeed"; "ndt7" -> "M-Lab NDT7"; else -> "iperf3" }) + line(ReportLabel.DOWNLOAD, speed.downloadMbps?.let { "${num(it)} Mb/s" }) + line(ReportLabel.UPLOAD, speed.uploadMbps?.let { "${num(it)} Mb/s" }) + line(ReportLabel.LATENCY, speed.latencyMs?.let { "${num(it)} ms" }) + line(ReportLabel.JITTER, speed.jitterMs?.let { "${num(it)} ms" }) + line(ReportLabel.RETRANSMITS, listOfNotNull(speed.retransmits?.toString(), speed.retransPercent?.let { "${num(it)} %" }) + .takeIf { it.isNotEmpty() }?.joinToString(" · ")) + if (speed.partial) line(ReportLabel.PARTIAL, labels.label(ReportLabel.YES)) +} + +private fun netLabel(name: String, labels: ReportLabels): String = labels.label(when (name) { + "wifi" -> ReportLabel.NET_WIFI + "cellular" -> ReportLabel.NET_CELLULAR + "ethernet" -> ReportLabel.NET_ETHERNET + "vpn" -> ReportLabel.NET_VPN + else -> ReportLabel.NET_OTHER +}) + +/** `12.3`, `0`, `1500`: at most one decimal, no exponent, `–` for null. */ +internal fun num(value: Double?): String { + val rounded = round(value, 1) ?: return "–" + val whole = rounded.toLong() + if (rounded == whole.toDouble()) return whole.toString() + val tenths = kotlin.math.abs(kotlin.math.round(rounded * 10).toLong() % 10) + val sign = if (rounded < 0 && whole == 0L) "-" else "" + return "$sign$whole.$tenths" +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/settings/AppSettings.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/settings/AppSettings.kt new file mode 100644 index 0000000..9b66b9c --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/settings/AppSettings.kt @@ -0,0 +1,97 @@ +package cz.netkit.shared.settings + +import cz.netkit.shared.json.JSON_MAX_DEPTH +import cz.netkit.shared.json.jsonNestingDepth +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.intOrNull +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** App theme (zadání 46 §3): follow the system, or force the light or dark palette. */ +@Serializable +enum class ThemeMode { SYSTEM, LIGHT, DARK } + +/** Whether the dark palette applies for [this] mode when the system is in dark mode ([systemDark]). */ +fun ThemeMode.isDark(systemDark: Boolean): Boolean = when (this) { + ThemeMode.SYSTEM -> systemDark + ThemeMode.LIGHT -> false + ThemeMode.DARK -> true +} + +/** + * App settings kept in the app-private settings file (Android: DataStore `datastore/settings.json`). + * The language is not here: on Android 13+ the system stores the per-app language itself. + * + * @property keepScreenOn keep the display on while a measurement runs (walk log, speed test, + * iperf3, ping, connected SSH terminal in the foreground). Default on: without it the display + * turns off, the app stops and the running measurement ends (no background work, D29). + */ +@Serializable +data class AppSettings( + val schema: Int = APP_SETTINGS_SCHEMA, + val theme: ThemeMode = ThemeMode.SYSTEM, + val keepScreenOn: Boolean = true, +) + +const val APP_SETTINGS_SCHEMA = 1 +const val APP_SETTINGS_MAX_BYTES = 4 * 1024 + +class AppSettingsCorrupt(message: String) : Exception(message) + +object AppSettingsCodec { + private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true } + + fun encode(settings: AppSettings): String = + json.encodeToString(AppSettings.serializer(), settings.copy(schema = APP_SETTINGS_SCHEMA)) + + /** Strict: oversize, deep nesting, another schema, unknown enum values or broken JSON are [AppSettingsCorrupt]. */ + fun decode(text: String): AppSettings { + if (text.length > APP_SETTINGS_MAX_BYTES) throw AppSettingsCorrupt("size") + if (jsonNestingDepth(text) > JSON_MAX_DEPTH) throw AppSettingsCorrupt("depth") + try { + val schema = json.parseToJsonElement(text).jsonObject["schema"]?.jsonPrimitive?.intOrNull + if (schema != APP_SETTINGS_SCHEMA) throw AppSettingsCorrupt("schema") + return json.decodeFromString(AppSettings.serializer(), text) + } catch (_: SerializationException) { + throw AppSettingsCorrupt("json") + } catch (_: IllegalArgumentException) { + throw AppSettingsCorrupt("json") + } + } +} + +/** + * App language choice (zadání 46 §1). [tag] is the BCP 47 tag given to the system + * (`LocaleManager.applicationLocales`); `null` = follow the system language. + * Czech is the default resource locale, English the translation. + */ +enum class AppLanguage(val tag: String?) { SYSTEM(null), CS("cs"), EN("en") } + +/** + * Choice shown for the system's per-app locales ([tags] = `LocaleList.toLanguageTags()`, + * comma separated, empty = none). Only the first locale counts; a language the app does not + * ship (set by another tool) is shown as [AppLanguage.SYSTEM], which the resources also fall back to. + */ +fun appLanguageFromTags(tags: String): AppLanguage { + val language = tags.split(',').firstOrNull().orEmpty().trim().substringBefore('-').substringBefore('_').lowercase() + return AppLanguage.entries.firstOrNull { it.tag != null && it.tag == language } ?: AppLanguage.SYSTEM +} + +/** + * Tab-level back (zadání 46 §2): from any tab other than [start] back opens [start]; + * on [start] it returns `null` and the system handles back (leaves the app). Subscreens and + * dialogs of a tab register their own handlers, which take precedence. + */ +fun tabBackTarget(current: Int, start: Int = 0): Int? = if (current != start) start else null + +/** The display is held on only while a measurement runs and the user left the setting on. */ +fun keepScreenOnActive(setting: Boolean, running: Boolean): Boolean = setting && running + +/** + * Reference count of the screens holding the display on through one view: [acquire] true adds + * one, false removes one (never below zero). The flag stays on while the result is above zero, + * so two overlapping holders (for example a closing and an opening tab) do not clear each other. + */ +fun screenOnHolders(current: Int, acquire: Boolean): Int = if (acquire) current + 1 else (current - 1).coerceAtLeast(0) diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/speed/Iperf3Protocol.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/speed/Iperf3Protocol.kt new file mode 100644 index 0000000..7ec3525 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/speed/Iperf3Protocol.kt @@ -0,0 +1,168 @@ +package cz.netkit.shared.speed + +import cz.netkit.shared.lan.validLanHost +import cz.netkit.shared.net.ipv6Bytes +import cz.netkit.shared.json.JSON_MAX_DEPTH +import cz.netkit.shared.json.jsonNestingDepth +import kotlinx.serialization.json.* + +fun validIperf3Host(host: String): Boolean = validLanHost(host) || + (host.length <= 45 && '%' !in host && '[' !in host && ipv6Bytes(host) != null) + +data class Iperf3Options(val streams: Int = 1, val seconds: Int = 10, val reverse: Boolean = false, val bitsPerSecond: Long = 0) { + /** Aim for a tenth of a second per TCP block at the negotiated per-stream rate. */ + val blockBytes: Int get() = if (bitsPerSecond == 0L) Iperf3Protocol.BLOCK_BYTES + else (bitsPerSecond / 80).coerceIn(1024L, Iperf3Protocol.BLOCK_BYTES.toLong()).toInt() + + /** Reverse allows for pacing (10%), control RTT (1 s) and two buffered blocks per stream. */ + val payloadLimitBytes: Long? get() { + if (bitsPerSecond == 0L) return null + val aggregateRate = bitsPerSecond * streams + if (!reverse) return aggregateRate * seconds / 8 + val windowTenths = seconds * 11 + 10 + return aggregateRate * windowTenths / 80 + 2L * blockBytes * streams + } + + init { + require(streams in 1..8 && seconds in 3..30 && bitsPerSecond in 0..1_000_000_000_000L) + } +} + +enum class Iperf3State(val wire: Int) { + PARAM_EXCHANGE(9), CREATE_STREAMS(10), TEST_START(1), TEST_RUNNING(2), TEST_END(4), + EXCHANGE_RESULTS(13), DISPLAY_RESULTS(14), IPERF_DONE(16), + ACCESS_DENIED(-1), SERVER_ERROR(-2), SERVER_TERMINATE(11), CLIENT_TERMINATE(12) +} + +class Iperf3ServerFailure(val state: Iperf3State) : Exception(state.name) + +data class Iperf3Receiver(val bytes: Long, val elapsedMs: Double, val workingStreams: Int) { + val mbps: Double get() = requireNotNull(megabitsPerSecond(bytes.toDouble(), elapsedMs)) +} + +/** A single-use session. The client owns TEST_END and IPERF_DONE in both directions. */ +class Iperf3Handshake { + private val sequence = listOf(Iperf3State.PARAM_EXCHANGE, Iperf3State.CREATE_STREAMS, Iperf3State.TEST_START, + Iperf3State.TEST_RUNNING, Iperf3State.TEST_END, Iperf3State.EXCHANGE_RESULTS, Iperf3State.DISPLAY_RESULTS, Iperf3State.IPERF_DONE) + private var next = 0 + fun receive(byte: Byte): Iperf3State { + val state = Iperf3State.entries.firstOrNull { it.wire == byte.toInt() } + if (state == Iperf3State.ACCESS_DENIED || state == Iperf3State.SERVER_TERMINATE || state == Iperf3State.SERVER_ERROR) { + next = sequence.size + throw Iperf3ServerFailure(state) + } + require(state != null && state != Iperf3State.TEST_END && state != Iperf3State.IPERF_DONE && sequence.getOrNull(next) == state) + next++ + return state + } + + fun send(state: Iperf3State): Byte { + require((state == Iperf3State.TEST_END || state == Iperf3State.IPERF_DONE) && sequence.getOrNull(next) == state) + next++ + return state.wire.toByte() + } +} + +object Iperf3Protocol { + const val BLOCK_BYTES = 128 * 1024 + const val MAX_JSON_BYTES = 64 * 1024 + + fun cookie(identifier: String): ByteArray { + require(identifier.length == 36 && identifier.all { it in '!'..'~' }) + return identifier.encodeToByteArray() + 0.toByte() + } + + fun parameters(options: Iperf3Options): JsonObject = buildJsonObject { + put("tcp", true) + put("omit", 0) + put("time", options.seconds) + put("parallel", options.streams) + put("len", options.blockBytes) + if (options.reverse) put("reverse", true) + if (options.bitsPerSecond > 0) put("bandwidth", options.bitsPerSecond) + } + + fun frame(json: JsonObject): ByteArray { + val payload = json.toString().encodeToByteArray() + require(payload.size in 1..MAX_JSON_BYTES) + return ByteArray(4) { (payload.size ushr (24 - 8 * it)).toByte() } + payload + } + + /** Validate before allocating or reading the payload, including unsigned lengths above 2 GiB. */ + fun payloadLength(header: ByteArray): Int { + require(header.size == 4) + return header.fold(0) { n, b -> (n shl 8) or (b.toInt() and 255) }.also { require(it in 1..MAX_JSON_BYTES) } + } + + fun decode(payload: ByteArray): JsonObject { + require(payload.size in 1..MAX_JSON_BYTES) + val text = payload.decodeToString(throwOnInvalidSequence = true) + require(jsonNestingDepth(text) <= JSON_MAX_DEPTH) + return Json.parseToJsonElement(text).jsonObject + } + + // IDs assigned in stream creation order, as observed on the control channel. + private fun streamId(index: Int) = if (index == 0) 1 else index + 2 + + fun results(options: Iperf3Options, bytes: LongArray, elapsedMs: Long): JsonObject = buildJsonObject { + require(bytes.size == options.streams && elapsedMs > 0) + // No portable per-connection TCP_INFO or process CPU measurement on this client. + put("cpu_util_total", 0) + put("cpu_util_user", 0) + put("cpu_util_system", 0) + put("sender_has_retransmits", if (options.reverse) -1 else 0) + putJsonArray("streams") { + bytes.forEachIndexed { index, count -> + addJsonObject { + put("id", streamId(index)) + put("bytes", count) + put("start_time", 0) + put("end_time", elapsedMs / 1000.0) + put("retransmits", -1) + put("jitter", 0) + put("errors", 0) + put("omitted_errors", 0) + put("packets", 0) + put("omitted_packets", 0) + } + } + } + } + + /** Parallel streams share the test epoch. Unusable receiver data falls back to the client's samples. */ + fun receiver(result: JsonObject, options: Iperf3Options): Iperf3Receiver? { + val streams = result["streams"] as? JsonArray ?: return null + if (streams.size != options.streams) return null + val validTimes = options.seconds * 0.5..options.seconds * 2.0 + var total = 0L + var endSeconds = 0.0 + var workingStreams = 0 + for (stream in streams) { + val row = stream as? JsonObject ?: return null + val bytes = (row["bytes"] as? JsonPrimitive)?.takeUnless { it.isString }?.longOrNull ?: return null + val end = (row["end_time"] as? JsonPrimitive)?.takeUnless { it.isString }?.doubleOrNull ?: return null + if (bytes !in 0..(Long.MAX_VALUE - total) || end !in validTimes) return null + total += bytes + if (bytes > 0) workingStreams++ + endSeconds = maxOf(endSeconds, end) + } + return Iperf3Receiver(total, endSeconds * 1000, workingStreams) + } + + /** Count only when every expected stream supplies a counter. -1 denotes unavailable. */ + fun retransmits(result: JsonObject, count: Int): Long? { + require(count in 1..8) + val streams = result["streams"] as? JsonArray ?: return null + if (streams.size != count) return null + val expected = (0 until count).map(::streamId).toSet() + val ids = streams.map { ((it as? JsonObject)?.get("id") as? JsonPrimitive)?.intOrNull } + if (ids.toSet() != expected) return null + var total = 0L + for (stream in streams) { + val value = (stream.jsonObject["retransmits"] as? JsonPrimitive)?.longOrNull ?: return null + if (value !in 0..(Long.MAX_VALUE - total)) return null + total += value + } + return total + } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedDataEstimate.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedDataEstimate.kt index a1ce349..9f119b9 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedDataEstimate.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedDataEstimate.kt @@ -9,26 +9,36 @@ const val SPEED_DATA_FALLBACK_MB = 200 private const val SPEED_DATA_MARGIN = 1.2 private const val SPEED_DATA_STEP_MB = 10 -/** Data estimate shown before a full test on a metered network; [fromHistory] = based on a past result. */ -data class SpeedDataEstimate(val megabytes: Int, val fromHistory: Boolean) +/** Information shown before starting a test on a metered network. */ +sealed interface SpeedDataEstimate { + data class Approximate(val megabytes: Int, val fromHistory: Boolean) : SpeedDataEstimate + data class PayloadUpperBound(val megabytes: Int) : SpeedDataEstimate + data object Unlimited : SpeedDataEstimate +} /** - * Data a full test of [engine] will transfer, from the newest stored result on [kind] - * (history is newest first). Rate × phase length per direction: LibreSpeed 10 s each way, NDT7 - * download up to its 15 s hard cap and 10 s upload. A missing upload rate counts as the download - * rate (upper bound). Rounded up to 10 MB; [SPEED_DATA_FALLBACK_MB] without a usable result. + * iperf3 runs in one direction with an optional per-stream limit. For LibreSpeed and NDT7, + * estimate both phases from the newest usable internet result on [kind] (history is newest first). */ -fun estimateSpeedTestData(engine: SpeedEngine, history: List, kind: NetKind): SpeedDataEstimate { - val last = history.firstOrNull { it.measuredKind == kind && it.downloadMbps?.let { v -> v.isFinite() && v > 0.0 } == true } - ?: return SpeedDataEstimate(SPEED_DATA_FALLBACK_MB, fromHistory = false) +fun estimateSpeedTestData(engine: SpeedEngine, history: List, kind: NetKind, + iperf: Iperf3Options = Iperf3Options()): SpeedDataEstimate { + if (engine == SpeedEngine.IPERF3) { + val bytes = iperf.payloadLimitBytes ?: return SpeedDataEstimate.Unlimited + val bytesPerMB = 1_000_000L + return SpeedDataEstimate.PayloadUpperBound(((bytes + bytesPerMB - 1) / bytesPerMB).toInt()) + } + // A private server (possibly paced with -b) does not measure internet access capacity. + val internetHistory = history.asSequence().filter { it.engine != SpeedEngine.IPERF3 && it.measuredKind == kind } + val last = internetHistory.firstOrNull { it.downloadMbps?.let { v -> v.isFinite() && v > 0.0 } == true } + ?: return SpeedDataEstimate.Approximate(SPEED_DATA_FALLBACK_MB, fromHistory = false) val down = last.downloadMbps!! val up = last.uploadMbps?.takeIf { it.isFinite() && it >= 0.0 } ?: down val (downMs, upMs) = when (engine) { SpeedEngine.LIBRESPEED -> SPEED_PHASE_MS to SPEED_PHASE_MS - SpeedEngine.NDT7 -> Ndt7Protocol.HARD_CAP_MS to Ndt7Protocol.UPLOAD_SEND_MS + else -> Ndt7Protocol.HARD_CAP_MS to Ndt7Protocol.UPLOAD_SEND_MS } // Mbit/s × s / 8 = MB (decimal megabytes). The epsilon keeps an exact 180.0000001 at 180. val megabytes = (down * downMs + up * upMs) / 1000.0 / 8.0 * SPEED_DATA_MARGIN val rounded = (ceil(megabytes / SPEED_DATA_STEP_MB - 1e-9) * SPEED_DATA_STEP_MB).coerceIn(SPEED_DATA_STEP_MB.toDouble(), 100_000.0) - return SpeedDataEstimate(rounded.toInt(), fromHistory = true) + return SpeedDataEstimate.Approximate(rounded.toInt(), fromHistory = true) } diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt index c6c2777..0c0b8c9 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt @@ -1,6 +1,7 @@ package cz.netkit.shared.speed import cz.netkit.shared.net.NetKind +import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.SerializationException import kotlinx.serialization.json.Json @@ -9,10 +10,10 @@ import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive @Serializable -enum class SpeedEngine { LIBRESPEED, NDT7 } +enum class SpeedEngine { LIBRESPEED, NDT7, @SerialName("iperf3") IPERF3 } /** - * One stored result. No IP address, ISP string, access token or BSSID is kept; the SSID is + * One stored result. A user-entered iperf3 endpoint may be numeric. No public-IP lookup result, ISP string, access token or BSSID is kept; the SSID is * stored because the result is meaningless without knowing which network was measured. * * @property timestampMs wall-clock time of the start (epoch ms). @@ -49,6 +50,7 @@ data class SpeedRecord( val plannedDownloadStreams: Int? = null, val plannedUploadStreams: Int? = null, val networkKind: NetKind? = null, + val retransmits: Long? = null, ) { /** Records without [networkKind] come from versions that tested over Wi-Fi only. */ val measuredKind: NetKind get() = networkKind ?: NetKind.WIFI @@ -68,6 +70,8 @@ data class SpeedStoreData( val ndt7ConsentMs: Long? = null, val customUrl: String? = null, val records: List = emptyList(), + val iperfHost: String = "", + val iperfPort: Int = 5201, ) const val SPEED_STORE_SCHEMA = 1 @@ -76,6 +80,30 @@ private const val TEXT_MAX = 128 class SpeedStoreCorrupt(message: String) : Exception(message) +/** History groups the Settings screen clears separately (zadání 46 §3). */ +enum class SpeedHistoryKind { SPEED_TEST, IPERF3 } + +fun SpeedRecord.historyKind(): SpeedHistoryKind = if (engine == SpeedEngine.IPERF3) SpeedHistoryKind.IPERF3 else SpeedHistoryKind.SPEED_TEST + +/** Number of stored records of [kind]. */ +fun List.countOf(kind: SpeedHistoryKind): Int = count { it.historyKind() == kind } + +/** Removes the records of [kind]; the other group, consent, custom server and iperf3 target stay. */ +fun SpeedStoreData.withoutHistory(kind: SpeedHistoryKind): SpeedStoreData = copy(records = records.filter { it.historyKind() != kind }) + +/** Forgets the last iperf3 server (host and port back to the defaults). */ +fun SpeedStoreData.withoutIperfTarget(): SpeedStoreData = copy(iperfHost = "", iperfPort = 5201) + +/** + * The stored iperf3 server as `host:port` (`[v6]:port` for an IPv6 literal), null when none is kept. + * Settings shows this, not the form being edited (zadání 46, revize kolo 1). + */ +fun SpeedStoreData.savedIperfTarget(): String? = iperfHost.takeIf { it.isNotBlank() } + ?.let { host -> if (':' in host) "[$host]:$iperfPort" else "$host:$iperfPort" } + +/** The M-Lab notice is shown again before the next NDT7 run. */ +fun SpeedStoreData.withoutNdt7Consent(): SpeedStoreData = copy(ndt7ConsentMs = null) + /** Newest first, capped at [max]. */ fun SpeedStoreData.withRecord(record: SpeedRecord, max: Int = SPEED_HISTORY_MAX): SpeedStoreData = copy(records = (listOf(record) + records).take(max)) @@ -98,7 +126,8 @@ object SpeedStoreCodec { val data = json.decodeFromString(SpeedStoreData.serializer(), text) if (!data.records.all(::validRecord)) throw SpeedStoreCorrupt("values") val custom = data.customUrl?.let { (checkLibreSpeedUrl(it) as? LibreSpeedUrlCheck.Valid)?.server?.baseUrl } - return data.copy(records = data.records.take(SPEED_HISTORY_MAX), customUrl = custom) + return data.copy(iperfHost = data.iperfHost.takeIf(::validIperf3Host).orEmpty(), + iperfPort = data.iperfPort.takeIf { it in 1..65535 } ?: 5201, records = data.records.take(SPEED_HISTORY_MAX), customUrl = custom) } catch (_: SerializationException) { throw SpeedStoreCorrupt("json") } catch (_: IllegalArgumentException) { @@ -115,7 +144,7 @@ object SpeedStoreCodec { private fun validRecord(r: SpeedRecord): Boolean { fun okRate(v: Double?) = v == null || (v.isFinite() && v in 0.0..1_000_000.0) fun okMs(v: Double?) = v == null || (v.isFinite() && v in 0.0..600_000.0) - return r.timestampMs > 0 && r.serverName.length in 1..TEXT_MAX && (r.ssid?.length ?: 0) <= TEXT_MAX && + return (r.retransmits == null || r.retransmits >= 0) && r.timestampMs > 0 && r.serverName.length in 1..TEXT_MAX && (r.ssid?.length ?: 0) <= TEXT_MAX && okRate(r.downloadMbps) && okRate(r.uploadMbps) && okRate(r.serverDownloadMbps) && okRate(r.serverUploadMbps) && okMs(r.idleLatencyMs) && okMs(r.idleJitterMs) && okMs(r.loadedDownloadMs) && okMs(r.loadedUploadMs) && (r.retransPercent == null || (r.retransPercent.isFinite() && r.retransPercent in 0.0..100.0)) && diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ConsoleProfile.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ConsoleProfile.kt new file mode 100644 index 0000000..3e4703e --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ConsoleProfile.kt @@ -0,0 +1,38 @@ +package cz.netkit.shared.ssh + +import kotlinx.serialization.Serializable + +@Serializable +enum class ConsoleKind { TELNET, SERIAL } + +@Serializable +enum class SerialParity { NONE, ODD, EVEN, MARK, SPACE } + +@Serializable +enum class SerialStopBits { ONE, ONE_AND_HALF, TWO } + +@Serializable +data class SerialSettings( + val baud: Int = 9600, val dataBits: Int = 8, val parity: SerialParity = SerialParity.NONE, + val stopBits: SerialStopBits = SerialStopBits.ONE, val rtsCts: Boolean = false, +) { + fun valid() = baud in 1200..921600 && dataBits in 5..8 + companion object { + val enterprise = SerialSettings() + val mikrotik = SerialSettings(baud = 115200) + } +} + +/** Local profile. USB ports are selected on each connection. No credential fields. */ +@Serializable +data class ConsoleProfile( + override val id: String, override val name: String, val kind: ConsoleKind, override val host: String = "", val port: Int = 23, + val serial: SerialSettings = SerialSettings(), val skipTelnetWarning: Boolean = false, + override val group: String? = null, +) : TerminalProfile { + fun valid() = validReference(id) && validProfileGroup(group) && name.isNotBlank() && name.length <= 100 && name.none { it.isISOControl() } && + serial.valid() && port in 1..65535 && when (kind) { + ConsoleKind.SERIAL -> host.isEmpty() && !skipTelnetWarning + ConsoleKind.TELNET -> host.length in 1..253 && host.none { it.isWhitespace() || it.isISOControl() || it in "/\\@?#[]" } + } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ProfileDirectory.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ProfileDirectory.kt new file mode 100644 index 0000000..ecbd159 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ProfileDirectory.kt @@ -0,0 +1,58 @@ +package cz.netkit.shared.ssh + +sealed interface TerminalProfile { + val id: String + val name: String + val host: String + val group: String? +} + +val TerminalProfile.listKey: String get() = if (this is SshProfile) "ssh:$id" else "console:$id" + +fun validProfileGroup(group: String?) = group == null || + (group.isNotBlank() && group.length <= 60 && group.none(Char::isISOControl)) + +internal fun validProfileKeys(keys: List) = keys.size <= 400 && keys.distinct().size == keys.size && + keys.all { (it.startsWith("ssh:") || it.startsWith("console:")) && validReference(it.substringAfter(':')) } + +enum class ProfileSort { MANUAL, ALPHABETICAL, RECENT } + +private fun SshData.manualProfiles(): List { + val profilesByKey = (consoles + profiles).associateBy { it.listKey }.toMutableMap() + return profileOrder.mapNotNull(profilesByKey::remove) + profilesByKey.values +} + +fun SshData.profileGroups(query: String, sort: ProfileSort): Map> { + val needle = query.trim() + val matching = manualProfiles().filter { profile -> + listOfNotNull(profile.name, profile.host, (profile as? SshProfile)?.username, profile.group) + .any { it.contains(needle, ignoreCase = true) } + } + val ordered = when (sort) { + ProfileSort.MANUAL -> matching + ProfileSort.ALPHABETICAL -> matching.sortedBy { it.name.lowercase() } + ProfileSort.RECENT -> { + val ranks = recentProfiles.withIndex().associate { it.value to it.index } + matching.sortedBy { ranks[it.listKey] ?: Int.MAX_VALUE } + } + } + return ordered.groupBy { it.group } +} + +/** Swap adjacent visible rows within a group. Hidden rows retain their slots. */ +fun SshData.swapProfiles(key: String, neighbor: String): SshData { + val rows = manualProfiles().toMutableList() + val a = rows.indexOfFirst { it.listKey == key } + val b = rows.indexOfFirst { it.listKey == neighbor } + if (a < 0 || b < 0 || rows[a].group != rows[b].group) return this + val first = rows[a] + rows[a] = rows[b] + rows[b] = first + return copy(profileOrder = rows.map { it.listKey }, profiles = rows.filterIsInstance(), + consoles = rows.filterIsInstance()) +} + +fun SshData.profileUsed(key: String): SshData { + if ((profiles + consoles).none { it.listKey == key }) return this + return copy(recentProfiles = listOf(key) + (recentProfiles - key)) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Sftp.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Sftp.kt new file mode 100644 index 0000000..cc39abf --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Sftp.kt @@ -0,0 +1,70 @@ +package cz.netkit.shared.ssh + +/* + * SFTP browser rules (zadání 42 §2.3). Names come from the server and are untrusted: a name is used to + * build a path only when it is a single path element. Moving up or into a symlink is never computed + * on the phone: the request path (which may contain `..`) is always resolved by the server + * (`realpath`), and only the server's answer becomes the current directory. + */ + +/** Largest file the browser downloads or uploads (2 GiB). */ +const val SFTP_MAX_FILE_BYTES: Long = 2L * 1024 * 1024 * 1024 + +/** Directory listings stop after this many entries (memory bound); the UI says the list is cut. */ +const val SFTP_MAX_ENTRIES = 5000 + +/** Longest accepted name (bytes of a typical POSIX NAME_MAX, counted in chars here). */ +const val SFTP_MAX_NAME = 255 + +enum class SftpEntryKind { DIRECTORY, FILE, LINK, OTHER } + +/** One listing row; [name] is the raw server name, already checked by [isValidSftpName]. */ +data class SftpEntry(val name: String, val kind: SftpEntryKind, val size: Long, val modifiedEpochSeconds: Long) + +/** Why an SFTP operation failed; the UI maps each to a fixed text, never to a server message. */ +enum class SftpFailure { NOT_FOUND, PERMISSION, EXISTS, FAILURE, TOO_LARGE, INVALID_NAME, CONNECTION, UNSUPPORTED, CANCELLED } + +/** SFTP v3 status codes (draft-ietf-secsh-filexfer-02 §7) to [SftpFailure]. */ +fun sftpFailureForStatus(status: Int): SftpFailure = when (status) { + 2 -> SftpFailure.NOT_FOUND // SSH_FX_NO_SUCH_FILE + 3 -> SftpFailure.PERMISSION // SSH_FX_PERMISSION_DENIED + 6, 7 -> SftpFailure.CONNECTION // SSH_FX_NO_CONNECTION, SSH_FX_CONNECTION_LOST + 8 -> SftpFailure.UNSUPPORTED // SSH_FX_OP_UNSUPPORTED + else -> SftpFailure.FAILURE // SSH_FX_FAILURE (e.g. rmdir of a non-empty directory), EOF, bad message +} + +/** A single path element: not empty, not `.`/`..`, no `/`, NUL or other control characters. */ +fun isValidSftpName(name: String): Boolean = + name.length in 1..SFTP_MAX_NAME && name != "." && name != ".." && name.none { it == '/' || it.code < 0x20 || it.code == 0x7f } + +/** [directory] is a server-resolved absolute path; [name] must pass [isValidSftpName]. */ +fun sftpChild(directory: String, name: String): String { + require(directory.startsWith("/")) { "not absolute" } + require(isValidSftpName(name)) { "invalid name" } + return if (directory.endsWith("/")) directory + name else "$directory/$name" +} + +/** Request path for "up"; it contains `..` and must only ever be passed to the server's `realpath`. */ +fun sftpParentRequest(directory: String): String { + require(directory.startsWith("/")) { "not absolute" } + return if (directory.endsWith("/")) "$directory.." else "$directory/.." +} + +/** Server names may carry control or bidi characters that disguise the real name on screen. */ +fun displaySftpName(name: String): String = buildString { + for (char in name.take(SFTP_MAX_NAME)) append( + if (char.code < 0x20 || char.code == 0x7f || char.code in 0x80..0x9f || char.code in 0x202a..0x202e || + char.code in 0x2066..0x2069 || char.code == 0x200e || char.code == 0x200f) '?' else char) +} + +/** Directories first, then by name ignoring case, then by exact name (stable for case-only differences). */ +fun sortSftpEntries(entries: List): List = + entries.sortedWith(compareBy { if (it.kind == SftpEntryKind.DIRECTORY) 0 else 1 } + .thenBy { it.name.lowercase() }.thenBy { it.name }) + +/** A size from the server or the document provider: unknown (null/negative) passes, limit is enforced while copying. */ +fun sftpSizeAllowed(size: Long?): Boolean = size == null || size < 0 || size <= SFTP_MAX_FILE_BYTES + +/** Progress 0..1 or null when the total is unknown. */ +fun sftpProgress(done: Long, total: Long?): Float? = + if (total == null || total <= 0) null else (done.toDouble() / total).coerceIn(0.0, 1.0).toFloat() diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Socks5.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Socks5.kt new file mode 100644 index 0000000..de45b77 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Socks5.kt @@ -0,0 +1,144 @@ +package cz.netkit.shared.ssh + +/** + * Minimal SOCKS5 (RFC 1928) parser for the local `-D` listener: CONNECT only, IPv4/IPv6/domain, method + * either username/password (RFC 1929, default; per-session random secret) or explicitly no authentication. + * Input is untrusted (any local app can connect to 127.0.0.1); every length is bounded. + */ +object Socks5 { + const val VERSION = 5 + const val METHOD_NO_AUTH = 0 + const val METHOD_USERNAME_PASSWORD = 2 + const val USERPASS_VERSION = 1 + /** RFC 1929 maximum (1 + 1 + 255 + 1 + 255). */ + const val MAX_USERPASS = 513 + const val METHOD_NONE_ACCEPTABLE = 0xFF + const val COMMAND_CONNECT = 1 + const val ATYP_IPV4 = 1 + const val ATYP_DOMAIN = 3 + const val ATYP_IPV6 = 4 + /** DNS name limit; a SOCKS length byte could otherwise announce up to 255. */ + const val MAX_DOMAIN = 253 + /** Largest valid greeting (2 + 255 methods) and request (7 + 255 domain bytes). */ + const val MAX_GREETING = 257 + const val MAX_REQUEST = 262 + + val NO_AUTH_REPLY = byteArrayOf(VERSION.toByte(), METHOD_NO_AUTH.toByte()) + val USERNAME_PASSWORD_REPLY = byteArrayOf(VERSION.toByte(), METHOD_USERNAME_PASSWORD.toByte()) + val AUTH_SUCCESS_REPLY = byteArrayOf(USERPASS_VERSION.toByte(), 0) + val AUTH_FAILURE_REPLY = byteArrayOf(USERPASS_VERSION.toByte(), 1) + val NO_ACCEPTABLE_METHOD_REPLY = byteArrayOf(VERSION.toByte(), METHOD_NONE_ACCEPTABLE.toByte()) + + /** Reply with BND.ADDR 0.0.0.0:0; the real local address of the tunnel is not meaningful to the client. */ + fun reply(code: Socks5Reply): ByteArray = byteArrayOf(VERSION.toByte(), code.code.toByte(), 0, ATYP_IPV4.toByte(), 0, 0, 0, 0, 0, 0) + + /** Done only when the client offers [method] (the single method this listener accepts). */ + fun parseGreeting(bytes: ByteArray, length: Int = bytes.size, method: Int = METHOD_NO_AUTH): Socks5Parse { + val size = length.coerceIn(0, bytes.size) + if (size < 1) return Socks5Parse.NeedMore + if (bytes.u(0) != VERSION) return Socks5Parse.Invalid(Socks5Reply.PROTOCOL) + if (size < 2) return Socks5Parse.NeedMore + val methods = bytes.u(1) + if (methods == 0) return Socks5Parse.Invalid(Socks5Reply.PROTOCOL) + if (size < 2 + methods) return Socks5Parse.NeedMore + val offered = (0 until methods).map { bytes.u(2 + it) } + if (method !in offered) return Socks5Parse.Invalid(Socks5Reply.NO_ACCEPTABLE_METHOD) + return Socks5Parse.Done(Unit, 2 + methods) + } + + fun parseRequest(bytes: ByteArray, length: Int = bytes.size): Socks5Parse { + val size = length.coerceIn(0, bytes.size) + if (size < 1) return Socks5Parse.NeedMore + if (bytes.u(0) != VERSION) return Socks5Parse.Invalid(Socks5Reply.PROTOCOL) + if (size < 4) return Socks5Parse.NeedMore + if (bytes.u(1) != COMMAND_CONNECT) return Socks5Parse.Invalid(Socks5Reply.COMMAND_NOT_SUPPORTED) + if (bytes.u(2) != 0) return Socks5Parse.Invalid(Socks5Reply.GENERAL_FAILURE) + val type = bytes.u(3) + val addressLength: Int + val addressStart: Int + when (type) { + ATYP_IPV4 -> { addressStart = 4; addressLength = 4 } + ATYP_IPV6 -> { addressStart = 4; addressLength = 16 } + ATYP_DOMAIN -> { + if (size < 5) return Socks5Parse.NeedMore + addressStart = 5; addressLength = bytes.u(4) + if (addressLength == 0 || addressLength > MAX_DOMAIN) return Socks5Parse.Invalid(Socks5Reply.GENERAL_FAILURE) + } + else -> return Socks5Parse.Invalid(Socks5Reply.ADDRESS_TYPE_NOT_SUPPORTED) + } + val total = addressStart + addressLength + 2 + if (size < total) return Socks5Parse.NeedMore + val port = bytes.u(total - 2) shl 8 or bytes.u(total - 1) + if (port == 0) return Socks5Parse.Invalid(Socks5Reply.GENERAL_FAILURE) + val host = when (type) { + ATYP_IPV4 -> (0 until 4).joinToString(".") { bytes.u(addressStart + it).toString() } + ATYP_IPV6 -> (0 until 8).joinToString(":") { + (bytes.u(addressStart + it * 2) shl 8 or bytes.u(addressStart + it * 2 + 1)).toString(16) + } + else -> { + val name = CharArray(addressLength) { bytes.u(addressStart + it).toChar() }.concatToString() + // Hostname characters only: no spaces, controls, `@`, `%` or bytes above ASCII. + if (!name.all { it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9' || it == '.' || it == '-' || it == '_' } || + name.startsWith('.') || name.startsWith('-')) return Socks5Parse.Invalid(Socks5Reply.GENERAL_FAILURE) + name + } + } + return Socks5Parse.Done(Socks5Request(host, port, type), total) + } + + /** RFC 1929 sub-negotiation; credentials are raw bytes, compared by the caller in constant time. */ + fun parseUserPass(bytes: ByteArray, length: Int = bytes.size): Socks5Parse { + val size = length.coerceIn(0, bytes.size) + if (size < 1) return Socks5Parse.NeedMore + if (bytes.u(0) != USERPASS_VERSION) return Socks5Parse.Invalid(Socks5Reply.PROTOCOL) + if (size < 2) return Socks5Parse.NeedMore + val userLength = bytes.u(1) + if (userLength == 0) return Socks5Parse.Invalid(Socks5Reply.PROTOCOL) + if (size < 3 + userLength) return Socks5Parse.NeedMore + val passwordLength = bytes.u(2 + userLength) + if (passwordLength == 0) return Socks5Parse.Invalid(Socks5Reply.PROTOCOL) + val total = 3 + userLength + passwordLength + if (size < total) return Socks5Parse.NeedMore + return Socks5Parse.Done(Socks5Credentials(bytes.copyOfRange(2, 2 + userLength), bytes.copyOfRange(3 + userLength, total)), total) + } + + /** Length-independent comparison of the whole arrays (no early exit on the first difference). */ + fun constantTimeEquals(a: ByteArray, b: ByteArray): Boolean { + var diff = a.size xor b.size + for (index in 0 until maxOf(a.size, b.size)) diff = diff or ((a.getOrElse(index) { 0 }.toInt()) xor (b.getOrElse(index) { 0 }.toInt())) + return diff == 0 + } + + private fun ByteArray.u(index: Int): Int = this[index].toInt() and 0xFF +} + +enum class Socks5Reply(val code: Int) { + SUCCEEDED(0), GENERAL_FAILURE(1), NOT_ALLOWED(2), NETWORK_UNREACHABLE(3), HOST_UNREACHABLE(4), + CONNECTION_REFUSED(5), TTL_EXPIRED(6), COMMAND_NOT_SUPPORTED(7), ADDRESS_TYPE_NOT_SUPPORTED(8), + /** Not a reply code: the greeting/request is malformed, close without a reply. */ + PROTOCOL(-1), + /** Not a reply code: answer the greeting with method 0xFF and close. */ + NO_ACCEPTABLE_METHOD(-2), +} + +data class Socks5Request(val host: String, val port: Int, val addressType: Int) + +class Socks5Credentials(val username: ByteArray, val password: ByteArray) + +/** Per-session `-D` login. Lives only in memory and in UI state while the session runs; never stored. */ +data class SshSocksCredentials(val username: String, val password: String) { + override fun toString(): String = "SshSocksCredentials(username=$username, password=***)" + companion object { + const val USERNAME = "netkit" + private const val ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789" + /** [randomIndex] must be a CSPRNG (platform supplies SecureRandom); 20 symbols ≈ 117 bits. */ + fun generate(randomIndex: (bound: Int) -> Int): SshSocksCredentials = + SshSocksCredentials(USERNAME, CharArray(20) { ALPHABET[randomIndex(ALPHABET.length)] }.concatToString()) + } +} + +sealed interface Socks5Parse { + data class Done(val value: T, val consumed: Int) : Socks5Parse + data object NeedMore : Socks5Parse + data class Invalid(val reply: Socks5Reply) : Socks5Parse +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt index 761b44d..74c2001 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt @@ -1,11 +1,27 @@ package cz.netkit.shared.ssh -/** Monotonic clock, including device sleep. Re-entering the foreground also checks an expired deadline. */ -class SshBackgroundPolicy(private val nowMillis: () -> Long) { +/** + * Monotonic clock, including device sleep. Re-entering the foreground also checks an expired deadline. + * [graceMillis] is [BACKGROUND_GRACE_MILLIS] in the app; instrumentation shortens it (zadání 42 AC-001). + */ +class SshBackgroundPolicy(private val graceMillis: Long, private val nowMillis: () -> Long) { + /** The pre-42 signature, `SshBackgroundPolicy(nowMillis)`, used by iOS (`IosSshLifecycle`) and tests. */ + constructor(nowMillis: () -> Long) : this(BACKGROUND_GRACE_MILLIS, nowMillis) + init { require(graceMillis > 0) } private var deadline: Long? = null - fun background() { if (deadline == null) deadline = nowMillis() + BACKGROUND_GRACE_MILLIS } + fun background() { if (deadline == null) deadline = nowMillis() + graceMillis } fun remainingMillis(): Long? = deadline?.let { (it - nowMillis()).coerceAtLeast(0L) } fun expired(): Boolean = remainingMillis() == 0L fun foreground(): Boolean = expired().also { deadline = null } companion object { const val BACKGROUND_GRACE_MILLIS = 5 * 60 * 1000L } } + +/** + * Zadání 42: the foreground service runs for the whole time at least one session is live (connecting or + * connected), never without one, and only when the user allows notifications. Without it the sessions + * keep the 5-minute background limit of [SshBackgroundPolicy]. + */ +fun sshServiceWanted(liveSessions: Int, notificationsAllowed: Boolean): Boolean = liveSessions > 0 && notificationsAllowed + +/** An expired background deadline closes sessions only when the foreground service does not keep them. */ +fun sshBackgroundCloses(expired: Boolean, serviceForeground: Boolean): Boolean = expired && !serviceForeground diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshForwarding.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshForwarding.kt new file mode 100644 index 0000000..e2f69bc --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshForwarding.kt @@ -0,0 +1,69 @@ +package cz.netkit.shared.ssh + +import kotlinx.serialization.Serializable + +const val SSH_MAX_LOCAL_FORWARDS = 8 +const val SSH_MAX_JUMP_HOPS = 3 +/** Unprivileged ports only: Android apps cannot bind below 1024 and the listener is local anyway. */ +val SSH_FORWARD_LOCAL_PORTS = 1024..65535 + +/** `-L 127.0.0.1:localPort:host:port`. [host] is resolved by the SSH server, as OpenSSH does. */ +@Serializable +data class SshLocalForward(val localPort: Int, val host: String, val port: Int) { + fun valid(): Boolean = localPort in SSH_FORWARD_LOCAL_PORTS && port in 1..65535 && validForwardHost(host) + /** `host:port` with brackets for IPv6 literals. */ + val target: String get() = (if (':' in host) "[$host]" else host) + ":$port" +} + +internal fun validForwardHost(host: String): Boolean = host.isNotBlank() && host.length <= 253 && + host.none { it.isWhitespace() || it.code < 32 || it.code in 127..159 || it in "/\\@?#[]" } + +/** Distinct local ports across all rules, including the dynamic SOCKS listener. */ +fun validSshForwards(local: List, dynamicPort: Int?): Boolean { + if (local.size > SSH_MAX_LOCAL_FORWARDS || local.any { !it.valid() }) return false + if (dynamicPort != null && dynamicPort !in SSH_FORWARD_LOCAL_PORTS) return false + val ports = local.map { it.localPort } + listOfNotNull(dynamicPort) + return ports.distinct().size == ports.size +} + +enum class SshForwardKind { LOCAL, DYNAMIC } +enum class SshForwardState { ACTIVE, PORT_IN_USE, FAILED } + +/** Runtime state of one listener of an open session (never persisted). */ +data class SshForwardStatus(val kind: SshForwardKind, val localPort: Int, val target: String?, val state: SshForwardState, + /** `-D` with authentication: the per-session login to show/copy; null for `-L` or no-auth SOCKS. */ + val credentials: SshSocksCredentials? = null) { + /** What the user pastes into another app; always loopback. */ + val localAddress: String get() = "127.0.0.1:$localPort" +} + +sealed interface SshJumpResolution { + /** Jump hosts in connection order (first hop first); the target is not included. */ + data class Chain(val hops: List) : SshJumpResolution + data class Missing(val profileId: String) : SshJumpResolution + data object Cycle : SshJumpResolution + data object TooLong : SshJumpResolution +} + +/** Follows jump references from [target]; at most [SSH_MAX_JUMP_HOPS] jump hosts, cycles and dangling ids fail closed. */ +fun resolveSshJumpChain(profiles: List, target: SshProfile): SshJumpResolution { + val byId = profiles.associateBy { it.id } + val visited = mutableSetOf(target.id) + val hops = ArrayDeque() + var next = target.jumpProfileId + while (next != null) { + if (!visited.add(next)) return SshJumpResolution.Cycle + val hop = byId[next] ?: return SshJumpResolution.Missing(next) + if (hops.size == SSH_MAX_JUMP_HOPS) return SshJumpResolution.TooLong + hops.addFirst(hop) + next = hop.jumpProfileId + } + return SshJumpResolution.Chain(hops.toList()) +} + +/** Profiles that [profile] may use as its jump host without creating a cycle or an over-long chain. */ +fun SshData.jumpCandidates(profile: SshProfile): List = profiles.filter { candidate -> + // The target id is visited first, so a chain leading back to the edited profile is a cycle. + candidate.id != profile.id && + resolveSshJumpChain(profiles, profile.copy(jumpProfileId = candidate.id)) is SshJumpResolution.Chain +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt index eaff35d..7f836d6 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt @@ -1,5 +1,7 @@ package cz.netkit.shared.ssh +import kotlinx.serialization.EncodeDefault +import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.Serializable @Serializable @@ -8,9 +10,9 @@ enum class SshAuthentication { PASSWORD, KEY, INTERACTIVE } /** Only references, never credentials, are serialised or exported. */ @Serializable data class SshProfile( - val id: String, - val name: String, - val host: String, + override val id: String, + override val name: String, + override val host: String, val port: Int = 22, val username: String, val authentication: SshAuthentication = SshAuthentication.PASSWORD, @@ -18,14 +20,26 @@ data class SshProfile( val keyRef: String? = null, val startupCommand: String = "", val keepaliveSeconds: Int = 30, -) { - fun valid(): Boolean = validReference(id) && name.isNotBlank() && name.length <= 100 && + /** ProxyJump: another profile used as the jump host (chain resolved by [resolveSshJumpChain]). */ + val jumpProfileId: String? = null, + /** `-L`: listens only on 127.0.0.1 while the session is open. */ + val localForwards: List = emptyList(), + /** `-D`: local SOCKS5 (CONNECT only) on 127.0.0.1:port while the session is open. */ + val dynamicForwardPort: Int? = null, + /** Explicit opt-out of the per-session SOCKS5 username/password (any local app could then use the tunnel). */ + val dynamicForwardNoAuth: Boolean = false, + @OptIn(ExperimentalSerializationApi::class) + @EncodeDefault(EncodeDefault.Mode.NEVER) + override val group: String? = null, +) : TerminalProfile { + fun valid(): Boolean = validReference(id) && validProfileGroup(group) && name.isNotBlank() && name.length <= 100 && host.isNotBlank() && host.length <= 253 && host.none { it.isWhitespace() || it.code < 32 || it.code == 127 } && host.none { it in "/\\@?#[]" } && port in 1..65535 && username.isNotBlank() && username.length <= 128 && username.none { it.isWhitespace() || it.code < 32 } && (secretRef == null || validReference(secretRef)) && (keyRef == null || validReference(keyRef)) && startupCommand.length <= 4096 && startupCommand.none { it.code < 32 || it.code == 127 } && - keepaliveSeconds in 0..300 + keepaliveSeconds in 0..300 && (jumpProfileId == null || validReference(jumpProfileId) && jumpProfileId != id) && + validSshForwards(localForwards, dynamicForwardPort) val endpoint: String get() = "[${host.lowercase()}]:$port" } @@ -40,8 +54,21 @@ data class SshKeyInfo(val id: String, val name: String, val publicKey: String) @Serializable data class SshData(val schema: Int = 1, val profiles: List = emptyList(), val hostKeys: List = emptyList(), val keys: List = emptyList(), - val rejectedHostKeys: List = emptyList()) { - fun valid(): Boolean = schema == 1 && profiles.size <= 200 && keys.size <= 100 && hostKeys.size <= 500 && + val rejectedHostKeys: List = emptyList(), + val snippets: List = emptyList(), + // Keep the existing on-disk and legacy export shape for an SSH-only installation. + @OptIn(ExperimentalSerializationApi::class) + @EncodeDefault(EncodeDefault.Mode.NEVER) + val consoles: List = emptyList(), + @OptIn(ExperimentalSerializationApi::class) + @EncodeDefault(EncodeDefault.Mode.NEVER) + val profileOrder: List = emptyList(), + @OptIn(ExperimentalSerializationApi::class) + @EncodeDefault(EncodeDefault.Mode.NEVER) + val recentProfiles: List = emptyList()) { + fun valid(): Boolean = schema == 1 && validProfileKeys(profileOrder) && validProfileKeys(recentProfiles) && profiles.size <= 200 && consoles.size <= 200 && consoles.all { it.valid() } && + consoles.map { it.id }.distinct().size == consoles.size && keys.size <= 100 && hostKeys.size <= 500 && + snippets.size <= SSH_MAX_SNIPPETS && snippets.all { it.valid() } && snippets.map { it.id }.distinct().size == snippets.size && profiles.all { it.valid() } && profiles.map { it.id }.distinct().size == profiles.size && keys.all { validReference(it.id) && it.name.length in 1..100 && it.publicKey.length <= 16384 } && keys.map { it.id }.distinct().size == keys.size && @@ -54,7 +81,7 @@ data class SshData(val schema: Int = 1, val profiles: List = emptyLi /** Legacy export sanitizer retained for compatibility tests. Application files use encodeSshProfileExport (v2). */ fun exportSshProfiles(data: SshData): SshData = SshData( - profiles = data.profiles.map { it.copy(secretRef = null, keyRef = null) }, + profiles = data.profiles.map { it.copy(secretRef = null, keyRef = null, group = null) }, ) enum class HostKeyDecision { TRUSTED, UNKNOWN, CHANGED } @@ -101,4 +128,6 @@ interface SshSession { enum class SshFailure { HOST_KEY_CHANGED, HOST_KEY_REJECTED, AUTHENTICATION, ALGORITHMS, DNS, TIMEOUT, CONNECTION, IMPORT_RSA_SMALL, IMPORT_DSA, IMPORT_PASSPHRASE, IMPORT_FORMAT, SECRET_UNAVAILABLE, STORAGE, UNKNOWN, + /** ProxyJump chain is missing a profile, cyclic or longer than [SSH_MAX_JUMP_HOPS]; nothing was connected. */ + JUMP_CHAIN, } diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt index 93def78..919ea7a 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt @@ -13,6 +13,10 @@ fun encodeSshProfileExport(data: SshData, source: String): ByteArray { require(data.valid()) val duplicates = data.profiles.groupingBy { it.name }.eachCount().filterValues { it > 1 }.keys.toList() if (duplicates.isNotEmpty()) throw SshProfileExportException(SshProfileExportError.DuplicateNames(duplicates)) + val names = data.profiles.associate { it.id to it.name } + // Snippets of a profile travel with its alias; both optional fields are omitted when empty, so a file + // without them stays byte-compatible with importers that predate them. + val snippets = data.snippets.filter { it.profileId == null || it.profileId in names } val document = buildJsonObject { put("format", "netkit-ssh-profiles") put("schema", 2) @@ -21,16 +25,28 @@ fun encodeSshProfileExport(data: SshData, source: String): ByteArray { data.profiles.forEach { profile -> addJsonObject { put("alias", profile.name) + profile.group?.let { put("group", it) } put("host", profile.host) put("port", profile.port) put("username", profile.username) put("authentication", profile.authentication.name) put("startupCommand", profile.startupCommand) put("keepaliveSeconds", profile.keepaliveSeconds) + profile.jumpProfileId?.let(names::get)?.let { put("proxyJump", it) } } } } putJsonArray("skipped") { } + if (snippets.isNotEmpty()) putJsonArray("snippets") { + snippets.forEach { snippet -> + addJsonObject { + put("name", snippet.name) + put("text", snippet.text) + put("sendEnter", snippet.sendEnter) + snippet.profileId?.let { put("profile", names.getValue(it)) } + } + } + } }.toString().encodeToByteArray() if (document.size > SSH_PROFILE_IMPORT_LIMIT) throw SshProfileExportException(SshProfileExportError.TooLarge) // Never report a successful export of a file the importer cannot accept. diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt index c38b8d2..40fe182 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt @@ -8,6 +8,7 @@ import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull import kotlinx.serialization.json.intOrNull const val SSH_PROFILE_IMPORT_LIMIT = 256 * 1024 @@ -24,13 +25,20 @@ enum class SshImportSkipReason { PROXY_JUMP, PROXY_COMMAND, MATCH, WILDCARD, MIS data class SshImportSkipped(val alias: String, val reason: SshImportSkipReason) data class SshImportProfile(val alias: String, val host: String, val port: Int, val username: String, val group: String? = null, // null means v1: preserve local settings; v2/legacy always carry all three settings. - val authentication: SshAuthentication? = null, val startupCommand: String = "", val keepaliveSeconds: Int = 30) -data class SshProfileImport(val profiles: List, val skipped: List, val source: String? = null) + val authentication: SshAuthentication? = null, val startupCommand: String = "", val keepaliveSeconds: Int = 30, + /** ProxyJump as an alias of another profile (this file or already on the device); null keeps the local link. */ + val proxyJump: String? = null) +/** [profile] is an alias of a profile in the same file; null means a global snippet. */ +data class SshImportSnippet(val name: String, val text: String, val sendEnter: Boolean, val profile: String? = null) +data class SshProfileImport(val profiles: List, val skipped: List, val source: String? = null, + val snippets: List = emptyList()) -/** Group/source/skipped are preview metadata only, never persisted in SshData. */ +/** Source/skipped are preview metadata only, never persisted in SshData. */ data class SshImportEntry(val incoming: SshImportProfile, val before: SshProfile?, val after: SshProfile) { val detachedSecretRef: String? get() = before?.secretRef?.takeIf { after.secretRef == null } } +/** [before] null means a new snippet. Imported snippets never send Enter until the user enables it. */ +data class SshSnippetChange(val before: SshSnippet?, val after: SshSnippet) class SshImportPlan internal constructor( internal val baselineProfiles: List, val newProfiles: List, @@ -38,6 +46,19 @@ class SshImportPlan internal constructor( val unchangedProfiles: List, val skipped: List, val source: String?, + internal val baselineSnippets: List = emptyList(), + /** Complete snippet list after the import (local snippets plus added/replaced ones). */ + internal val snippetsAfter: List = baselineSnippets, + val newSnippets: Int = 0, + val updatedSnippets: Int = 0, + /** Every added or changed snippet with its previous version (null = new), for an explicit preview. */ + val snippetChanges: List = emptyList(), + /** + * Every id [planSshProfileImport] drew from its generator, in call order. Re-planning the same + * incoming file against the same (fresh) data draws ids in the same order, so a confirmation can + * replay exactly these ids (profiles, including rows later skipped for ProxyJump, and snippets). + */ + val generatedIds: List = emptyList(), ) { val detachedSecretRefs: List = updatedProfiles.mapNotNull { it.detachedSecretRef }.distinct() } @@ -46,15 +67,23 @@ private fun fail(reason: SshProfileImportFailure): Nothing = throw SshProfileImp private fun validAlias(alias: String) = alias.isNotBlank() && alias.length <= 100 && alias.none { it.code < 32 || it.code in 127..159 } private fun SshImportProfile.profile(id: String) = SshProfile(id, alias, host, port, username, authentication ?: SshAuthentication.PASSWORD, - startupCommand = startupCommand, keepaliveSeconds = keepaliveSeconds) + startupCommand = startupCommand, keepaliveSeconds = keepaliveSeconds, group = group) +private const val MAX_IMPORT_SNIPPETS = SSH_MAX_SNIPPETS private fun validateIncoming(incoming: SshProfileImport) { if (incoming.profiles.size > MAX_IMPORT_ROWS || incoming.skipped.size > MAX_IMPORT_ROWS) fail(SshProfileImportFailure.LIMIT) if ((incoming.source?.length ?: 0) > 64) fail(SshProfileImportFailure.FORMAT) val aliases = incoming.profiles.map { it.alias } + incoming.skipped.map { it.alias } if (aliases.distinct().size != aliases.size) fail(SshProfileImportFailure.DUPLICATE_ALIAS) - if (incoming.profiles.any { !validAlias(it.alias) || (it.group?.length ?: 0) > 60 || !it.profile("validation").valid() } || + if (incoming.profiles.any { !validAlias(it.alias) || !it.profile("validation").valid() || + it.proxyJump != null && (!validAlias(it.proxyJump) || it.proxyJump == it.alias) } || incoming.skipped.any { !validAlias(it.alias) }) fail(SshProfileImportFailure.INVALID_PROFILE) + if (incoming.snippets.size > MAX_IMPORT_SNIPPETS) fail(SshProfileImportFailure.LIMIT) + val profileAliases = incoming.profiles.map { it.alias }.toSet() + if (incoming.snippets.any { !validSnippetName(it.name) || !validSnippetText(it.text) || it.profile != null && it.profile !in profileAliases }) + fail(SshProfileImportFailure.INVALID_PROFILE) + val snippetKeys = incoming.snippets.map { it.name to it.profile } + if (snippetKeys.distinct().size != snippetKeys.size) fail(SshProfileImportFailure.DUPLICATE_ALIAS) } private fun JsonObject.allowOnly(fields: Set) { @@ -76,23 +105,28 @@ fun decodeSshProfileImport(bytes: ByteArray): SshProfileImport { try { val root = Json.parseToJsonElement(text) as? JsonObject ?: fail(SshProfileImportFailure.FORMAT) if (!root.containsKey("format")) return decodeLegacyProfiles(root).also(::validateIncoming) - root.allowOnly(setOf("format", "schema", "source", "profiles", "skipped")) + root.allowOnly(setOf("format", "schema", "source", "profiles", "skipped", "snippets")) if (root.string("format") != "netkit-ssh-profiles") fail(SshProfileImportFailure.FORMAT) val schema = root.integer("schema", SshProfileImportFailure.SCHEMA) if (schema !in 1..2) fail(SshProfileImportFailure.SCHEMA) + // Optional v2 extension (zadání 41); absent in older files, which therefore import unchanged. + if (schema != 2 && root.containsKey("snippets")) fail(SshProfileImportFailure.UNKNOWN_FIELD) + val snippets = if (root.containsKey("snippets")) root.rows("snippets") else JsonArray(emptyList()) + if (snippets.size > MAX_IMPORT_SNIPPETS) fail(SshProfileImportFailure.LIMIT) val profiles = root.rows("profiles") val skipped = root.rows("skipped") if (profiles.size > MAX_IMPORT_ROWS || skipped.size > MAX_IMPORT_ROWS) fail(SshProfileImportFailure.LIMIT) return SshProfileImport( profiles.map { element -> val row = element as? JsonObject ?: fail(SshProfileImportFailure.FORMAT) - row.allowOnly(setOf("alias", "group", "host", "port", "username") + + row.allowOnly(setOf("alias", "group", "host", "port", "username", "proxyJump") + if (schema == 2) setOf("authentication", "startupCommand", "keepaliveSeconds") else emptySet()) SshImportProfile(row.string("alias"), row.string("host"), row.integer("port", SshProfileImportFailure.INVALID_PROFILE), row.string("username"), row.optionalString("group"), authentication = if (schema == 2) row.authentication() else null, startupCommand = if (schema == 2) row.string("startupCommand") else "", - keepaliveSeconds = if (schema == 2) row.integer("keepaliveSeconds", SshProfileImportFailure.INVALID_PROFILE) else 30) + keepaliveSeconds = if (schema == 2) row.integer("keepaliveSeconds", SshProfileImportFailure.INVALID_PROFILE) else 30, + proxyJump = row.optionalString("proxyJump")) }, skipped.map { element -> val row = element as? JsonObject ?: fail(SshProfileImportFailure.FORMAT) @@ -101,6 +135,13 @@ fun decodeSshProfileImport(bytes: ByteArray): SshProfileImport { SshImportSkipped(row.string("alias"), SshImportSkipReason.entries.find { it.name == reason } ?: fail(SshProfileImportFailure.FORMAT)) }, root.optionalString("source"), + snippets.map { element -> + val row = element as? JsonObject ?: fail(SshProfileImportFailure.FORMAT) + row.allowOnly(setOf("name", "text", "sendEnter", "profile")) + val enter = (row["sendEnter"] as? JsonPrimitive)?.takeUnless { it.isString }?.booleanOrNull + ?: fail(SshProfileImportFailure.FORMAT) + SshImportSnippet(row.string("name"), row.string("text"), enter, row.optionalString("profile")) + }, ).also(::validateIncoming) } catch (error: SshProfileImportException) { throw error } catch (_: SerializationException) { fail(SshProfileImportFailure.FORMAT) } @@ -114,21 +155,26 @@ private fun JsonObject.authentication(): SshAuthentication = /** Only the credential-free export of the old serializer, never a device backup. */ private fun decodeLegacyProfiles(root: JsonObject): SshProfileImport { - root.allowOnly(setOf("schema", "profiles", "hostKeys", "keys", "rejectedHostKeys")) + // Store fields added later (zadání 41) are tolerated only at their empty defaults: never data to import. + root.allowOnly(setOf("schema", "profiles", "hostKeys", "keys", "rejectedHostKeys", "snippets")) if (!root.containsKey("schema")) fail(SshProfileImportFailure.FORMAT) if (root.integer("schema", SshProfileImportFailure.SCHEMA) != 1) fail(SshProfileImportFailure.SCHEMA) for (field in listOf("hostKeys", "keys", "rejectedHostKeys")) { if (root.rows(field).isNotEmpty()) fail(SshProfileImportFailure.FORMAT) } + if (root.containsKey("snippets") && root.rows("snippets").isNotEmpty()) fail(SshProfileImportFailure.FORMAT) val rows = root.rows("profiles") if (rows.size > MAX_IMPORT_ROWS) fail(SshProfileImportFailure.LIMIT) return SshProfileImport(rows.map { element -> val row = element as? JsonObject ?: fail(SshProfileImportFailure.FORMAT) row.allowOnly(setOf("id", "name", "host", "port", "username", "authentication", - "secretRef", "keyRef", "startupCommand", "keepaliveSeconds")) - for (field in listOf("secretRef", "keyRef")) { + "secretRef", "keyRef", "startupCommand", "keepaliveSeconds", "jumpProfileId", "localForwards", "dynamicForwardPort", "dynamicForwardNoAuth")) + for (field in listOf("secretRef", "keyRef", "jumpProfileId", "dynamicForwardPort")) { if (row.containsKey(field) && row[field] != JsonNull) fail(SshProfileImportFailure.FORMAT) } + if (row.containsKey("localForwards") && row.rows("localForwards").isNotEmpty()) fail(SshProfileImportFailure.FORMAT) + if (row.containsKey("dynamicForwardNoAuth") && (row["dynamicForwardNoAuth"] as? JsonPrimitive)?.takeUnless { it.isString }?.booleanOrNull != false) + fail(SshProfileImportFailure.FORMAT) row.string("id") // Ignore the old identity; the planner generates a new local one. SshImportProfile(row.string("name"), row.string("host"), row.integer("port", SshProfileImportFailure.INVALID_PROFILE), row.string("username"), @@ -137,51 +183,140 @@ private fun decodeLegacyProfiles(root: JsonObject): SshProfileImport { }, emptyList()) } -/** Exact alias match. v1 preserves local settings; v2/legacy replace portable settings; a changed endpoint detaches its saved password. */ -fun planSshProfileImport(current: SshData, incoming: SshProfileImport, keyRef: String?, generateId: () -> String): SshImportPlan { +/** + * Exact alias match. v1 preserves local settings; v2/legacy replace portable settings; a changed endpoint detaches its saved password. + * ProxyJump aliases resolve against this file first, then unique local names; an unresolved alias, a cycle or a chain over + * [SSH_MAX_JUMP_HOPS] moves the row to skipped (PROXY_JUMP). A row without proxyJump keeps the local jump link. + * Without [supportsProxyJump] (iOS: its transport connects only to the target) every row with a proxyJump, + * or updating a local profile that has a jump host, is skipped as PROXY_JUMP: never a silent direct connection. + */ +fun planSshProfileImport(current: SshData, incoming: SshProfileImport, keyRef: String?, generateId: () -> String): SshImportPlan = + planSshProfileImport(current, incoming, keyRef, supportsProxyJump = true, generateId = generateId) + +/** + * As above; [supportsProxyJump] = false for a platform whose transport has no jump hosts (iOS). + * [replaceJumps] = true (configuration restore of whole profiles): a row without proxyJump means a direct + * connection, so the local jump link is dropped before the chains are validated. + */ +fun planSshProfileImport(current: SshData, incoming: SshProfileImport, keyRef: String?, supportsProxyJump: Boolean, + generateId: () -> String, replaceJumps: Boolean = false): SshImportPlan { if (!current.valid()) fail(SshProfileImportFailure.INVALID_DATA) + val drawn = mutableListOf() + @Suppress("NAME_SHADOWING") val generateId: () -> String = { generateId().also { drawn += it } } validateIncoming(incoming) if (keyRef != null && !validReference(keyRef)) fail(SshProfileImportFailure.INVALID_REFERENCE) val byName = current.profiles.groupBy { it.name } val ids = current.profiles.map { it.id }.toMutableSet() - val added = mutableListOf() - val updated = mutableListOf() - val unchanged = mutableListOf() - for (row in incoming.profiles) { + class Row(val incoming: SshImportProfile, val before: SshProfile?, val id: String) + val rows = incoming.profiles.map { row -> val matches = byName[row.alias].orEmpty() if (matches.size > 1) fail(SshProfileImportFailure.AMBIGUOUS_ALIAS) val before = matches.singleOrNull() - if (before == null) { - val id = generateId() + val id = before?.id ?: generateId().also { id -> if (!validReference(id)) fail(SshProfileImportFailure.INVALID_REFERENCE) if (!ids.add(id)) fail(SshProfileImportFailure.DUPLICATE_ID) - added += SshImportEntry(row, null, row.profile(id).copy( - authentication = row.authentication ?: if (keyRef == null) SshAuthentication.PASSWORD else SshAuthentication.KEY, - keyRef = keyRef.takeIf { row.authentication == null || row.authentication == SshAuthentication.KEY })) - } else { + } + Row(row, before, id) + } + val aliasIds = byName.filterValues { it.size == 1 }.mapValues { it.value.single().id } + rows.associate { it.incoming.alias to it.id } + val jumpSkipped = mutableListOf() + var entries = rows.mapNotNull { item -> + val row = item.incoming + if (!supportsProxyJump && (row.proxyJump != null || item.before?.jumpProfileId != null)) { + jumpSkipped += SshImportSkipped(row.alias, SshImportSkipReason.PROXY_JUMP); return@mapNotNull null + } + val jump = if (row.proxyJump == null) item.before?.jumpProfileId.takeUnless { replaceJumps } + else aliasIds[row.proxyJump] ?: run { jumpSkipped += SshImportSkipped(row.alias, SshImportSkipReason.PROXY_JUMP); return@mapNotNull null } + val before = item.before + val after = if (before == null) row.profile(item.id).copy( + authentication = row.authentication ?: if (keyRef == null) SshAuthentication.PASSWORD else SshAuthentication.KEY, + keyRef = keyRef.takeIf { row.authentication == null || row.authentication == SshAuthentication.KEY }, + jumpProfileId = jump) + else { val targetChanged = before.host != row.host || before.port != row.port || before.username != row.username val authentication = row.authentication ?: before.authentication val authenticationChanged = authentication != before.authentication - val after = before.copy(host = row.host, port = row.port, username = row.username, + before.copy(group = row.group ?: before.group, host = row.host, port = row.port, username = row.username, authentication = authentication, startupCommand = if (row.authentication == null) before.startupCommand else row.startupCommand, keepaliveSeconds = if (row.authentication == null) before.keepaliveSeconds else row.keepaliveSeconds, secretRef = if (targetChanged || authenticationChanged && authentication != SshAuthentication.PASSWORD) null else before.secretRef, - keyRef = if (authenticationChanged && authentication != SshAuthentication.KEY) null else before.keyRef) - val entry = SshImportEntry(row, before, after) - if (before == after) unchanged += entry else updated += entry + keyRef = if (authenticationChanged && authentication != SshAuthentication.KEY) null else before.keyRef, + jumpProfileId = jump) + } + SshImportEntry(row, before, after) + } + // Dropping a row can break a chain that pointed at it, so validate until stable. + while (true) { + val replacements = entries.associate { it.after.id to it.after } + val result = current.profiles.map { replacements[it.id] ?: it } + entries.filter { it.before == null }.map { it.after } + val broken = entries.filter { it.incoming.proxyJump != null && resolveSshJumpChain(result, it.after) !is SshJumpResolution.Chain } + if (broken.isEmpty()) break + entries = entries - broken.toSet() + jumpSkipped += broken.map { SshImportSkipped(it.incoming.alias, SshImportSkipReason.PROXY_JUMP) } + } + val acceptedIds = entries.associate { it.incoming.alias to it.after.id } + val snippets = current.snippets.toMutableList() + val snippetIds = snippets.map { it.id }.toMutableSet() + val changes = mutableListOf() + // A file must not turn a familiar snippet into a different command that one tap sends with Enter: + // new and text-changed snippets arrive with sendEnter = false; the preview lists old → new text. + for (snippet in incoming.snippets) { + val profileId = snippet.profile?.let { acceptedIds[it] } + if (snippet.profile != null && profileId == null) continue // Its profile was skipped. + val index = snippets.indexOfFirst { it.name == snippet.name && it.profileId == profileId } + if (index >= 0) { + val before = snippets[index] + if (before.text == snippet.text) continue // Same command: keep the local Enter choice. + val replaced = before.copy(text = snippet.text, sendEnter = false) + snippets[index] = replaced; changes += SshSnippetChange(before, replaced) + } else { + val id = generateId() + if (!validReference(id)) fail(SshProfileImportFailure.INVALID_REFERENCE) + if (!snippetIds.add(id)) fail(SshProfileImportFailure.DUPLICATE_ID) + val added = SshSnippet(id, snippet.name, snippet.text, sendEnter = false, profileId = profileId) + snippets += added; changes += SshSnippetChange(null, added) } } - return SshImportPlan(current.profiles.toList(), added.toList(), updated.toList(), unchanged.toList(), incoming.skipped.toList(), incoming.source) + if (snippets.size > SSH_MAX_SNIPPETS) fail(SshProfileImportFailure.LIMIT) + val added = entries.filter { it.before == null } + val updated = entries.filter { it.before != null && it.before != it.after } + val unchanged = entries.filter { it.before != null && it.before == it.after } + return SshImportPlan(current.profiles.toList(), added, updated, unchanged, incoming.skipped.toList() + jumpSkipped, incoming.source, + current.snippets.toList(), snippets.toList(), changes.count { it.before == null }, changes.count { it.before != null }, + changes.toList(), drawn.toList()) } /** Compare before applying: never overwrite edits made after the user saw the preview. */ fun applySshImportPlan(current: SshData, plan: SshImportPlan): SshData { if (!current.valid()) fail(SshProfileImportFailure.INVALID_DATA) - if (current.profiles != plan.baselineProfiles) fail(SshProfileImportFailure.STALE_PLAN) + if (current.profiles != plan.baselineProfiles || current.snippets != plan.baselineSnippets) fail(SshProfileImportFailure.STALE_PLAN) if (current.profiles.size + plan.newProfiles.size > MAX_IMPORT_ROWS) fail(SshProfileImportFailure.LIMIT) val replacements = plan.updatedProfiles.associate { it.after.id to it.after } - val result = current.copy(profiles = current.profiles.map { replacements[it.id] ?: it } + plan.newProfiles.map { it.after }) + val result = current.copy(profiles = current.profiles.map { replacements[it.id] ?: it } + plan.newProfiles.map { it.after }, + snippets = plan.snippetsAfter) if (!result.valid()) fail(SshProfileImportFailure.INVALID_DATA) return result } + + +/** Prepared SSH v2 controller transaction. Preview IDs and credential detachment are shared + * by the individual importer and the configuration restore. */ +class PendingSshProfileImport private constructor(val incoming: SshProfileImport, val plan: SshImportPlan, + private val replaceJumps: Boolean) { + companion object { + fun prepare(current: SshData, incoming: SshProfileImport, generateId: () -> String, replaceJumps: Boolean = false) = + PendingSshProfileImport(incoming, planSshProfileImport(current, incoming, null, supportsProxyJump = true, + generateId = generateId, replaceJumps = replaceJumps), replaceJumps) + } + + fun apply(current: SshData, keyRef: String? = null): SshData { + val result = applySshImportPlan(current, plan) + if (keyRef == null) return result + val ids = plan.generatedIds.iterator() + val withKey = planSshProfileImport(current, incoming, keyRef, supportsProxyJump = true, generateId = { + if (ids.hasNext()) ids.next() else throw SshProfileImportException(SshProfileImportFailure.STALE_PLAN) + }, replaceJumps = replaceJumps) + return applySshImportPlan(current, withKey) + } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshSnippets.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshSnippets.kt new file mode 100644 index 0000000..06cb715 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshSnippets.kt @@ -0,0 +1,73 @@ +package cz.netkit.shared.ssh + +import kotlinx.serialization.Serializable + +const val SSH_MAX_SNIPPETS = 100 +const val SSH_SNIPPET_NAME_LIMIT = 60 +const val SSH_SNIPPET_TEXT_LIMIT = 4096 + +/** + * Saved command for the terminal snippet bar. Not a secret: stored in plain app data and exported. + * [profileId] null means a global snippet; otherwise it is shown only in sessions of that profile. + */ +@Serializable +data class SshSnippet( + val id: String, + val name: String, + val text: String, + val sendEnter: Boolean = true, + val profileId: String? = null, +) { + fun valid(): Boolean = validReference(id) && validSnippetName(name) && validSnippetText(text) && + (profileId == null || validReference(profileId)) + + /** Exactly what the terminal receives; one line, Enter only when requested. */ + fun payload(): String = text + if (sendEnter) "\r" else "" +} + +internal fun validSnippetName(name: String): Boolean = name.isNotBlank() && name.length <= SSH_SNIPPET_NAME_LIMIT && + name.none { it.code < 32 || it.code in 127..159 } + +/** A snippet is one command line: control characters (including newline and ESC) are refused, not translated. */ +internal fun validSnippetText(text: String): Boolean = text.isNotEmpty() && text.length <= SSH_SNIPPET_TEXT_LIMIT && + text.none { it.code < 32 || it.code in 127..159 } + +/** Global snippets first, then the profile's own, each in saved order. */ +fun SshData.snippetsFor(profileId: String?): List = + snippets.filter { it.profileId == null } + snippets.filter { profileId != null && it.profileId == profileId } + +private val secretMarkers = listOf( + "password", "passwd", "secret", "community", "token", "apikey", "api_key", "api-key", + "pre-shared", "preshared", "psk", "credential", "heslo", "private-key", "privatekey", +) + +/** Heuristic warning only (never blocks): snippet text that looks like it carries a credential. */ +fun snippetLooksSecret(text: String): Boolean { + val lower = text.lowercase() + return secretMarkers.any { it in lower } +} + +/** + * (name, scope) identifies a snippet in the export and in import merging; a second snippet with the same + * pair would make the profile export fail (DUPLICATE_ALIAS), so saving one is refused up front. + */ +fun snippetNameTaken(data: SshData, snippet: SshSnippet): Boolean = + data.snippets.any { it.id != snippet.id && it.name == snippet.name && it.profileId == snippet.profileId } + +/** Insert or replace by id, keeping order. Returns null when the result would be invalid, duplicate or over the limit. */ +fun upsertSnippet(data: SshData, snippet: SshSnippet): SshData? { + if (!snippet.valid() || snippetNameTaken(data, snippet)) return null + if (snippet.profileId != null && data.profiles.none { it.id == snippet.profileId }) return null + val replaced = data.snippets.any { it.id == snippet.id } + val list = if (replaced) data.snippets.map { if (it.id == snippet.id) snippet else it } else data.snippets + snippet + if (list.size > SSH_MAX_SNIPPETS) return null + return data.copy(snippets = list).takeIf { it.valid() } +} + +/** Removing a profile also removes its own snippets and clears jump references to it. */ +fun removeSshProfile(data: SshData, id: String): SshData = data.copy( + profileOrder = data.profileOrder - "ssh:$id", + recentProfiles = data.recentProfiles - "ssh:$id", + profiles = data.profiles.filterNot { it.id == id }.map { if (it.jumpProfileId == id) it.copy(jumpProfileId = null) else it }, + snippets = data.snippets.filterNot { it.profileId == id }, +) diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshUnlock.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshUnlock.kt new file mode 100644 index 0000000..6201f26 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshUnlock.kt @@ -0,0 +1,28 @@ +package cz.netkit.shared.ssh + +/** In-memory grant. Zero authorizes the current view, but never a subsequent protected action. */ +data class SshUnlock(val enabled: Boolean = false, val minutes: Int = 5, val authenticatedAt: Long? = null) { + init { require(minutes in 0..15) } + + fun remaining(now: Long): Long { + val start = authenticatedAt ?: return 0 + if (now < start) return 0 + return (minutes * 60_000L - (now - start)).coerceAtLeast(0) + } + + fun canReuse(now: Long) = !enabled || remaining(now) > 0 + fun canView(now: Long) = canReuse(now) || (minutes == 0 && authenticatedAt != null && now >= authenticatedAt) + + /** + * Settings changed while this grant is held. The authentication is kept and judged by the new + * limit: a shorter limit that has already passed locks now; zero keeps the current view and + * only the next protected action asks again. + */ + fun reconfigure(enabled: Boolean, minutes: Int, now: Long): SshUnlock { + val next = copy(enabled = enabled, minutes = minutes) + return if (next.authenticatedAt != null && !next.canView(now)) next.copy(authenticatedAt = null) else next + } + + /** Delay until the view locks, or null when no timer is needed (disabled, not authenticated, zero minutes). */ + fun expiresIn(now: Long): Long? = if (!enabled || minutes == 0 || authenticatedAt == null) null else remaining(now) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TelnetCodec.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TelnetCodec.kt new file mode 100644 index 0000000..596f15f --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TelnetCodec.kt @@ -0,0 +1,120 @@ +package cz.netkit.shared.ssh + +/** One passive Telnet negotiator per TCP connection. Callers serialize receive, resize and writes. */ +class TelnetCodec { + data class Received(val data: ByteArray, val reply: ByteArray) + private enum class State { DATA, COMMAND, OPTION, SUB_OPTION, SUB_DATA, SUB_COMMAND } + private var state = State.DATA + private var verb = 0 + private val local = mutableSetOf() + private val remote = mutableSetOf() + private var columns = 80 + private var rows = 24 + private var afterCr = false + // TTYPE SEND is exactly one byte. Skip arbitrarily long or unknown SBs in constant space. + private var terminalType = false + private var subLength = 0 + private var subByte = 0 + + fun receive(bytes: ByteArray, length: Int = bytes.size): Received { + require(length in 0..bytes.size) + val data = ByteArray(length) + var size = 0 + val replies = mutableListOf() + fun dataByte(value: Int) { + if (!(afterCr && value == 0)) data[size++] = value.toByte() + afterCr = value == 13 + } + fun sub(value: Int) { + subLength = (subLength + 1).coerceAtMost(2) + subByte = value + } + for (i in 0 until length) { + val value = bytes[i].toInt() and 255 + when (state) { + State.DATA -> if (value == IAC) state = State.COMMAND else dataByte(value) + State.COMMAND -> { + state = when (value) { + WILL, WONT, DO, DONT -> { verb = value; State.OPTION } + SB -> State.SUB_OPTION + else -> { if (value == IAC) dataByte(IAC); State.DATA } + } + } + State.OPTION -> { negotiate(value, replies); state = State.DATA } + State.SUB_OPTION -> { terminalType = value == TTYPE; subLength = 0; state = State.SUB_DATA } + State.SUB_DATA -> if (value == IAC) state = State.SUB_COMMAND else sub(value) + State.SUB_COMMAND -> { + if (value == SE && terminalType && TTYPE in local && subLength == 1 && subByte == 1) + replies.addAll(frame(TTYPE, byteArrayOf(0) + "xterm-256color".encodeToByteArray()).asList()) + if (value != SE) sub(if (value == IAC) IAC else -1) + state = if (value == SE) State.DATA else State.SUB_DATA + } + } + } + return Received(data.copyOf(size), replies.toByteArray()) + } + + private fun negotiate(option: Int, replies: MutableList) { + fun answer(command: Int) { replies.addAll(byteArrayOf(IAC.toByte(), command.toByte(), option.toByte()).asList()) } + when (verb) { + WILL -> if (option != ECHO && option != SGA) answer(DONT) else if (remote.add(option)) answer(DO) + WONT -> if (remote.remove(option)) answer(DONT) + DO -> if (option != NAWS && option != TTYPE && option != SGA) answer(WONT) + else if (local.add(option)) { + answer(WILL) + if (option == NAWS) replies.addAll(window().asList()) + } + DONT -> if (local.remove(option)) answer(WONT) + } + } + + fun resize(columns: Int, rows: Int): ByteArray { + require(columns in 0..65535 && rows in 0..65535) + if (this.columns == columns && this.rows == rows) return byteArrayOf() + this.columns = columns + this.rows = rows + return if (NAWS in local) window() else byteArrayOf() + } + + private fun window() = frame(NAWS, byteArrayOf((columns ushr 8).toByte(), columns.toByte(), (rows ushr 8).toByte(), rows.toByte())) + private fun frame(option: Int, payload: ByteArray) = + byteArrayOf(IAC.toByte(), SB.toByte(), option.toByte()) + escape(payload) + byteArrayOf(IAC.toByte(), SE.toByte()) + + companion object { + private const val IAC = 255 + private const val DONT = 254 + private const val DO = 253 + private const val WONT = 252 + private const val WILL = 251 + private const val SB = 250 + private const val SE = 240 + private const val ECHO = 1 + private const val SGA = 3 + private const val TTYPE = 24 + private const val NAWS = 31 + + private fun escape(bytes: ByteArray): ByteArray { + val output = ByteArray(bytes.size + bytes.count { it == IAC.toByte() }) + var i = 0 + for (b in bytes) { output[i++] = b; if (b == IAC.toByte()) output[i++] = b } + return output + } + + /** NVT CR LF for newline, CR NUL for literal carriage return, doubled IAC in data. */ + fun encode(bytes: ByteArray): ByteArray { + val output = ByteArray(bytes.size * 2) + var i = 0 + var n = 0 + while (i < bytes.size) { + val b = bytes[i++] + when (b.toInt()) { + 13 -> { output[n++] = 13; output[n++] = if (bytes.getOrNull(i) == 10.toByte()) bytes[i++] else 0 } + 10 -> { output[n++] = 13; output[n++] = 10 } + -1 -> { output[n++] = -1; output[n++] = -1 } + else -> output[n++] = b + } + } + return output.copyOf(n) + } + } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt index 706a361..fcd4c8d 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt @@ -1,56 +1,195 @@ package cz.netkit.shared.ssh -/** Original bounded VT subset. No OSC commands, clipboard access, links, images or device execution. */ -data class TerminalRun(val text: String, val foreground: Int = 7, val background: Int = 0, val bold: Boolean = false) -/** Immutable compact row. Materialize styled runs only when the renderer requests a visible row. */ +/** + * Styled run of one row. Colours: 0–255 xterm palette index or `0x1000000 or rgb` truecolor; 7 and 0 are the + * theme defaults (SGR 39/49), inverse video is already applied. [columns] counts terminal cells (wide = 2). + */ +data class TerminalRun( + val text: String, val foreground: Int = 7, val background: Int = 0, val bold: Boolean = false, + val dim: Boolean = false, val italic: Boolean = false, val underline: Boolean = false, + val strikethrough: Boolean = false, val hidden: Boolean = false, val columns: Int = text.length, +) + +/** + * Immutable compact row. Styled runs are materialized only when a renderer asks for a row. A row that + * did not change between two snapshots is the same instance, so renderers can skip it by identity. + */ class TerminalRow internal constructor( - private val chars: CharArray, private val fg: IntArray, private val bg: IntArray, private val bold: BooleanArray, + internal val cells: IntArray, internal val fg: IntArray, internal val bg: IntArray, + internal val attrs: ByteArray, internal val extras: Array?, ) { - val text: String get() = chars.concatToString() - // Conservative retained-size accounting: payload is 11 bytes/cell; allowance covers array/object headers and references. - val retainedBytes: Int get() = chars.size * 16 + 256 + val columns: Int get() = cells.size + val text: String get() = buildString(cells.size) { for (i in cells.indices) appendCell(i) } + // Conservative retained-size accounting: payload is 13 bytes/cell; allowance covers array/object headers. + val retainedBytes: Int get() = cells.size * 16 + 256 + (extras?.sumOf { if (it == null) 8 else 48 + it.length * 2 } ?: 0) val runs: List get() { val result = mutableListOf(); var from = 0 - while (from < chars.size) { + while (from < cells.size) { var end = from + 1 - while (end < chars.size && fg[end] == fg[from] && bg[end] == bg[from] && bold[end] == bold[from]) end++ - result += TerminalRun(chars.concatToString(from, end), fg[from], bg[from], bold[from]); from = end + while (end < cells.size && fg[end] == fg[from] && bg[end] == bg[from] && attrs[end] == attrs[from]) end++ + val text = buildString(end - from) { for (i in from until end) appendCell(i) } + val a = attrs[from].toInt() + result += TerminalRun(text, fg[from], bg[from], a and BOLD != 0, a and DIM != 0, a and ITALIC != 0, + a and UNDERLINE != 0, a and STRIKE != 0, a and HIDDEN != 0, end - from) + from = end } return result } + + /** UTF-16 offset in [text] where [column] starts; the right half of a wide character maps to its start. */ + fun offsetOf(column: Int): Int { + val limit = column.coerceIn(0, cells.size) + var offset = 0 + for (i in 0 until limit) offset += cellLength(i) + if (limit in 1 until cells.size && cells[limit] == WIDE_TAIL) offset -= cellLength(limit - 1) + return offset + } + + private fun cellLength(i: Int): Int = + (if (cells[i] == WIDE_TAIL) 0 else if (cells[i] >= 0x10000) 2 else 1) + (extras?.get(i)?.length ?: 0) + + private fun StringBuilder.appendCell(i: Int) { + val code = cells[i] + if (code != WIDE_TAIL) appendCodePoint(code) + extras?.get(i)?.let { append(it) } + } + override fun equals(other: Any?): Boolean = this === other || other is TerminalRow && - chars.contentEquals(other.chars) && fg.contentEquals(other.fg) && bg.contentEquals(other.bg) && bold.contentEquals(other.bold) - override fun hashCode(): Int = 31 * chars.contentHashCode() + fg.contentHashCode() + bg.contentHashCode() + bold.contentHashCode() + cells.contentEquals(other.cells) && fg.contentEquals(other.fg) && bg.contentEquals(other.bg) && + attrs.contentEquals(other.attrs) && (extras ?: NO_EXTRAS).contentEquals(other.extras ?: NO_EXTRAS) + override fun hashCode(): Int = 31 * cells.contentHashCode() + fg.contentHashCode() + bg.contentHashCode() + attrs.contentHashCode() + + internal companion object { + const val WIDE_TAIL = -1 + const val BOLD = 1; const val DIM = 2; const val ITALIC = 4; const val UNDERLINE = 8 + const val STRIKE = 16; const val HIDDEN = 32 + private val NO_EXTRAS = emptyArray() + } } -data class TerminalSnapshot(val history: List, val screen: List, val cursorRow: Int, - val cursorColumn: Int, val cursorVisible: Boolean, val applicationCursorKeys: Boolean = false) +data class TerminalSnapshot( + val history: List, val screen: List, val cursorRow: Int, + val cursorColumn: Int, val cursorVisible: Boolean, val applicationCursorKeys: Boolean = false, + /** OSC 0/2 window title: display only, control and bidi characters removed, at most 128 characters. */ + val title: String = "", + /** DECSET 2004: pastes are wrapped in ESC[200~ … ESC[201~ (see [terminalPastePayload]). */ + val bracketedPaste: Boolean = false, + val alternateScreen: Boolean = false, +) + +internal fun StringBuilder.appendCodePoint(code: Int) { + if (code < 0x10000) append(code.toChar()) + else { val v = code - 0x10000; append((0xD800 + (v shr 10)).toChar()); append((0xDC00 + (v and 0x3FF)).toChar()) } +} + +/** + * Xterm-compatible screen model: a subset of xterm ctlseqs and ECMA-48, written from the public + * specifications (sources in docs/zavislosti.md). The parser follows the DEC ANSI parser model + * (ground, escape, CSI, OSC, ignored strings). Bounds: [MAX_SEQUENCE] characters per escape sequence + * (a longer one is discarded without effect), scrollback [historyLimit] rows and [historyByteLimit] bytes, + * grid 10–240 × 2–100. Unknown sequences are dropped silently. Deliberately not implemented: + * OSC 52 clipboard, title/colour reports, mouse reporting, sixel and other images. + */ class TerminalBuffer(columns: Int = 80, rows: Int = 24, private val historyLimit: Int = 5000, historyByteLimit: Int = MAX_HISTORY_BYTES) { private val historyByteLimit = historyByteLimit.coerceIn(0, MAX_HISTORY_BYTES) var historyBytes: Int = 0; private set - companion object { const val MAX_HISTORY_BYTES = 8 * 1024 * 1024 } + companion object { + const val MAX_HISTORY_BYTES = 8 * 1024 * 1024 + const val MAX_SEQUENCE = 256 + const val MAX_TITLE = 128 + private const val MAX_PARAMS = 32 + private const val MAX_COMBINING = 16 + private const val BLANK = 0x20 + private const val TAIL = TerminalRow.WIDE_TAIL + // DEC Special Graphics for 0x5F..0x7E (VT100 line drawing set, ESC ( 0). + private val DEC_GRAPHICS = intArrayOf(0x00A0, 0x25C6, 0x2592, 0x2409, 0x240C, 0x240D, 0x240A, 0x00B0, 0x00B1, + 0x2424, 0x240B, 0x2518, 0x2510, 0x250C, 0x2514, 0x253C, 0x23BA, 0x23BB, 0x2500, 0x23BC, 0x23BD, 0x251C, + 0x2524, 0x2534, 0x252C, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00B7) + } var columns = columns.coerceIn(10, 240); private set var rows = rows.coerceIn(2, 100); private set - private class Line(size: Int) { - val chars = CharArray(size) { ' ' }; val fg = IntArray(size) { 7 }; val bg = IntArray(size); val bold = BooleanArray(size) - fun clear(from: Int, until: Int, foreground: Int, background: Int) { for (i in from until until) { chars[i] = ' '; fg[i] = foreground; bg[i] = background; bold[i] = false } } - fun snapshot(): TerminalRow = TerminalRow(chars.copyOf(), fg.copyOf(), bg.copyOf(), bold.copyOf()) + + /** Mutable row. Every write drops the cached immutable [TerminalRow], so unchanged rows keep their snapshot. */ + private class Line(size: Int, background: Int = 0) { + val cells = IntArray(size) { BLANK }; val fg = IntArray(size) { 7 }; val bg = IntArray(size) { background } + val attrs = ByteArray(size); var extras: Array? = null + private var cached: TerminalRow? = null + val size: Int get() = cells.size + fun row(): TerminalRow = cached ?: TerminalRow(cells.copyOf(), fg.copyOf(), bg.copyOf(), attrs.copyOf(), + extras?.takeIf { e -> e.any { it != null } }?.copyOf()).also { cached = it } + fun set(i: Int, code: Int, foreground: Int, background: Int, attr: Int) { + cells[i] = code; fg[i] = foreground; bg[i] = background; attrs[i] = attr.toByte() + extras?.set(i, null); cached = null + } + fun blank(i: Int) { cells[i] = BLANK; extras?.set(i, null); cached = null } + fun erase(from: Int, until: Int, background: Int) { + for (i in from.coerceAtLeast(0) until until.coerceAtMost(size)) { + cells[i] = BLANK; fg[i] = 7; bg[i] = background; attrs[i] = 0; extras?.set(i, null) + } + cached = null; repair(from - 1, from); repair(until - 1, until) + } + fun copy(to: Int, from: Int) { + cells[to] = cells[from]; fg[to] = fg[from]; bg[to] = bg[from]; attrs[to] = attrs[from] + extras?.let { it[to] = it[from] }; cached = null + } + fun combine(i: Int, text: String) { + val all = extras ?: arrayOfNulls(size).also { extras = it } + val old = all[i].orEmpty() + if (old.length + text.length <= MAX_COMBINING) { all[i] = old + text; cached = null } + } + /** Never leave half of a wide character: a lone head or tail in [from, until] becomes a blank. */ + fun repair(from: Int, until: Int) { + for (i in from.coerceAtLeast(0)..until.coerceAtMost(size - 1)) { + if (cells[i] == TAIL) { if (i == 0 || cells[i - 1] == TAIL || TerminalWidth.of(cells[i - 1]) != 2) blank(i) } + else if (cells[i] > 0x7E && TerminalWidth.of(cells[i]) == 2 && (i + 1 >= size || cells[i + 1] != TAIL)) blank(i) + } + } + fun resized(width: Int): Line = Line(width).also { line -> + for (col in 0 until minOf(width, size)) { + line.cells[col] = cells[col]; line.fg[col] = fg[col]; line.bg[col] = bg[col]; line.attrs[col] = attrs[col] + extras?.get(col)?.let { line.combine(col, it) } + } + line.repair(width - 1, width - 1) + } } + + private class Saved(val x: Int, val y: Int, val foreground: Int, val background: Int, val attrs: Int, val inverse: Boolean, + val origin: Boolean, val wrapPending: Boolean, val g0: Boolean, val g1: Boolean, val shifted: Boolean) + private var screen = MutableList(this.rows) { Line(this.columns) } private val history = ArrayDeque() + private var historyView: List? = null private var primary: MutableList? = null private var primaryCursor = 0 to 0 - private var x = 0; private var y = 0; private var saved = 0 to 0 - private var foreground = 7; private var background = 0; private var bold = false; private var inverse = false - private var state = 0; private val sequence = StringBuilder(); private var top = 0; private var bottom = this.rows - 1 - private var wrap = true; private var wrapPending = false; private var cursorVisible = true; private var applicationCursorKeys = false + private var x = 0; private var y = 0 + private var savedMain: Saved? = null; private var savedAlternate: Saved? = null + private var foreground = 7; private var background = 0; private var attrs = 0; private var inverse = false + private var top = 0; private var bottom = this.rows - 1 + private var wrap = true; private var wrapPending = false; private var cursorVisible = true + private var applicationCursorKeys = false; private var originMode = false; private var insertMode = false + private var bracketedPaste = false; private var title = "" + private var g0Graphics = false; private var g1Graphics = false; private var shifted = false + private var tabs = defaultTabs(this.columns) + private var lastPrinted = -1 + + // Parser state (DEC ANSI parser model). + private enum class State { GROUND, ESCAPE, ESCAPE_INTERMEDIATE, CSI, CSI_IGNORE, OSC, OSC_ESCAPE, STRING, STRING_ESCAPE } + private var state = State.GROUND + private var sequenceLength = 0 + private val params = IntArray(MAX_PARAMS); private val subParam = BooleanArray(MAX_PARAMS) + private var paramCount = 0; private var paramStarted = false; private var current = -1 + private var privateMarker = NONE; private var intermediate = NONE + private val osc = StringBuilder(); private var oscOverflow = false + private var pendingHigh: Char? = null fun resize(columns: Int, rows: Int) { val w = columns.coerceIn(10, 240); val h = rows.coerceIn(2, 100) if (w == this.columns && h == this.rows) return resizeScreen(w, h, primary == null) this.columns = w; this.rows = h + val old = tabs + tabs = BooleanArray(w) { col -> if (col < old.size) old[col] else col % 8 == 0 } } private fun resizeScreen(w: Int, h: Int, useHistory: Boolean) { val oldHeight = screen.size @@ -65,156 +204,446 @@ class TerminalBuffer(columns: Int = 80, rows: Int = 24, private val historyLimit if (h > oldHeight && useHistory && y == oldHeight - 1) { restored = minOf(h - oldHeight, history.size) repeat(restored) { val row = history.removeLast(); historyBytes -= row.retainedBytes; screen.add(0, fromSnapshot(row)) } + if (restored > 0) historyView = null y += restored } - screen = MutableList(h) { row -> Line(w).also { line -> - if (row < screen.size) for (col in 0 until minOf(w, screen[row].chars.size)) { - line.chars[col] = screen[row].chars[col]; line.fg[col] = screen[row].fg[col] - line.bg[col] = screen[row].bg[col]; line.bold[col] = screen[row].bold[col] - } - } } + val old = screen + screen = MutableList(h) { row -> old.getOrNull(row)?.let { if (it.size == w) it else it.resized(w) } ?: Line(w) } x = x.coerceIn(0, w - 1); y = y.coerceIn(0, h - 1) - saved = saved.first.coerceIn(0, w - 1) to (saved.second - removed + restored).coerceIn(0, h - 1) + if (useHistory) savedMain = savedMain?.let { moved(it, w, h, restored - removed) } + else savedAlternate = savedAlternate?.let { moved(it, w, h, -removed) } top = 0; bottom = h - 1; wrapPending = false } - private fun fromSnapshot(row: TerminalRow): Line = Line(row.text.length).also { line -> - var index = 0 - for (run in row.runs) for (char in run.text) { - line.chars[index] = char; line.fg[index] = run.foreground - line.bg[index] = run.background; line.bold[index] = run.bold; index++ - } + private fun moved(s: Saved, w: Int, h: Int, shift: Int) = Saved(s.x.coerceIn(0, w - 1), (s.y + shift).coerceIn(0, h - 1), + s.foreground, s.background, s.attrs, s.inverse, s.origin, false, s.g0, s.g1, s.shifted) + private fun fromSnapshot(row: TerminalRow): Line = Line(row.columns).also { line -> + row.cells.copyInto(line.cells); row.fg.copyInto(line.fg); row.bg.copyInto(line.bg); row.attrs.copyInto(line.attrs) + row.extras?.let { line.extras = it.copyOf() } } private fun rememberLine(line: Line) { if (historyLimit <= 0) return - val row = line.snapshot() - history.addLast(row); historyBytes += row.retainedBytes + val row = line.row() + history.addLast(row); historyBytes += row.retainedBytes; historyView = null while (history.size > historyLimit || historyBytes > historyByteLimit) historyBytes -= history.removeFirst().retainedBytes } - fun snapshot() = TerminalSnapshot(if (primary == null) history.toList() else emptyList(), screen.map { it.snapshot() }, y, x, cursorVisible, applicationCursorKeys) + + fun snapshot(): TerminalSnapshot { + val visibleHistory = if (primary == null) historyView ?: history.toList().also { historyView = it } else emptyList() + return TerminalSnapshot(visibleHistory, screen.map { it.row() }, y, x, cursorVisible, applicationCursorKeys, + title, bracketedPaste, primary != null) + } + + /** Feeds decoded UTF-16 output (pairs may be split between calls); returns replies (DSR, DA) for the PTY. */ fun feed(text: String): String { val replies = StringBuilder() - for (char in text) { - when (state) { - 0 -> when (char) { - '\u001b' -> state = 1 - '\r' -> { x = 0; wrapPending = false } - '\n', '\u000b', '\u000c' -> { linefeed(); wrapPending = false } - '\b' -> { x = (x - 1).coerceAtLeast(0); wrapPending = false } - '\t' -> { x = ((x / 8 + 1) * 8).coerceAtMost(columns - 1); wrapPending = false } - else -> if (char.code >= 32 && char.code !in 127..159) put(char) + var i = 0 + while (i < text.length) { + val char = text[i++] + val high = pendingHigh + val code = when { + high != null -> { + pendingHigh = null + if (char.isLowSurrogate()) 0x10000 + ((high.code - 0xD800) shl 10) + (char.code - 0xDC00) + else { i--; 0xFFFD } } - 1 -> { state = 0; when (char) { - '[' -> { state = 2; sequence.clear() } - ']', 'P', '^', '_' -> state = 3 - '7' -> saved = x to y - '8' -> { x = saved.first.coerceIn(0, columns - 1); y = saved.second.coerceIn(0, rows - 1) } - 'D' -> linefeed() - 'M' -> if (y == top) scrollDown(1) else y = (y - 1).coerceAtLeast(0) - 'E' -> { x = 0; linefeed() } - 'c' -> { screen = MutableList(rows) { Line(columns) }; x = 0; y = 0; foreground = 7; background = 0; bold = false; inverse = false; top = 0; bottom = rows - 1; applicationCursorKeys = false } - '(', ')' -> state = 5 // Character set designation: consume, use Unicode text. - } } - 2 -> if (char in '@'..'~') { csi(char, sequence.toString(), replies); state = 0; sequence.clear() } - else if (sequence.length < 128) sequence.append(char) else { state = 0; sequence.clear() } - 3 -> if (char == '\u0007') state = 0 else if (char == '\u001b') state = 4 - 4 -> { state = if (char == '\\') 0 else 3 } - 5 -> state = 0 + char.isHighSurrogate() -> { pendingHigh = char; continue } + char.isLowSurrogate() -> 0xFFFD + else -> char.code } + step(code, replies) } return replies.toString() } - private fun put(char: Char) { + + private fun step(code: Int, replies: StringBuilder) { + // CAN and SUB abort any sequence. + if (code == 0x18 || code == 0x1A) { state = State.GROUND; return } + when (state) { + State.GROUND -> if (code == 0x1B) enterEscape() else if (code < 0x20) control(code) else print(code) + State.ESCAPE -> when { + code == 0x1B -> enterEscape() + code < 0x20 -> control(code) + code in 0x20..0x2F -> { intermediate = code.toChar(); state = State.ESCAPE_INTERMEDIATE } + else -> { state = State.GROUND; escape(code) } + } + State.ESCAPE_INTERMEDIATE -> when { + code == 0x1B -> enterEscape() + code < 0x20 -> control(code) + code in 0x20..0x2F -> if (++sequenceLength > MAX_SEQUENCE) state = State.GROUND + else -> { state = State.GROUND; escapeIntermediate(intermediate, code) } + } + State.CSI -> csiStep(code, replies) + State.CSI_IGNORE -> when { + code == 0x1B -> enterEscape() + code < 0x20 -> control(code) + code in 0x40..0x7E -> state = State.GROUND + } + State.OSC -> when { + code == 0x07 -> { state = State.GROUND; oscDispatch() } + code == 0x1B -> state = State.OSC_ESCAPE + code < 0x20 -> Unit + ++sequenceLength > MAX_SEQUENCE -> { oscOverflow = true; osc.clear() } + !oscOverflow -> osc.appendCodePoint(code) + } + State.OSC_ESCAPE -> if (code == '\\'.code) { state = State.GROUND; oscDispatch() } + else { osc.clear(); enterEscape(); step(code, replies) } + State.STRING -> if (code == 0x07) state = State.GROUND else if (code == 0x1B) state = State.STRING_ESCAPE + State.STRING_ESCAPE -> state = if (code == '\\'.code) State.GROUND else State.STRING + } + } + + private fun enterEscape() { state = State.ESCAPE; sequenceLength = 1; intermediate = NONE } + + private fun addParam(sub: Boolean) { + if (paramCount < MAX_PARAMS) { params[paramCount] = 0; subParam[paramCount] = sub; current = paramCount; paramCount++ } + else current = -1 + } + + private fun csiStep(code: Int, replies: StringBuilder) { + if (code == 0x1B) { enterEscape(); return } + if (code < 0x20) { control(code); return } + if (++sequenceLength > MAX_SEQUENCE) { + state = if (code in 0x40..0x7E) State.GROUND else State.CSI_IGNORE + return + } + when (code) { + in 0x30..0x39 -> { + if (intermediate != NONE) { state = State.CSI_IGNORE; return } + if (!paramStarted) { addParam(false); paramStarted = true } + if (current >= 0) params[current] = (params[current] * 10 + (code - 0x30)).coerceAtMost(65535) + } + 0x3B, 0x3A -> { + if (intermediate != NONE) { state = State.CSI_IGNORE; return } + if (!paramStarted) { addParam(false); paramStarted = true } + addParam(code == 0x3A) + } + in 0x3C..0x3F -> if (sequenceLength == 3) privateMarker = code.toChar() else state = State.CSI_IGNORE + in 0x20..0x2F -> if (intermediate == NONE) intermediate = code.toChar() else state = State.CSI_IGNORE + in 0x40..0x7E -> { state = State.GROUND; csi(code.toChar(), replies) } + else -> state = State.CSI_IGNORE + } + } + + private fun control(code: Int) { + when (code) { + 0x08 -> { if (x > 0) x--; wrapPending = false } + 0x09 -> { x = nextTab(x, 1); wrapPending = false } + 0x0A, 0x0B, 0x0C -> { linefeed(); wrapPending = false } + 0x0D -> { x = 0; wrapPending = false } + 0x0E -> shifted = true + 0x0F -> shifted = false + // BEL: no sound or vibration; other C0 controls are ignored. + } + } + + private fun escape(final: Int) { + when (final.toChar()) { + '[' -> { state = State.CSI; sequenceLength = 2; paramCount = 0; paramStarted = false; current = -1; privateMarker = NONE; intermediate = NONE } + ']' -> { state = State.OSC; sequenceLength = 2; osc.clear(); oscOverflow = false } + 'P', 'X', '^', '_' -> state = State.STRING // DCS, SOS, PM, APC: consumed until ST, never executed. + '7' -> saveCursor() + '8' -> restoreCursor() + 'D' -> { linefeed(); wrapPending = false } + 'E' -> { x = 0; linefeed(); wrapPending = false } + 'H' -> tabs[x] = true + 'M' -> { reverseIndex(); wrapPending = false } + 'c' -> reset() + else -> Unit // DECKPAM/DECKPNM, SS2/SS3, ST and unknown finals. + } + } + + private fun escapeIntermediate(intermediate: Char, final: Int) { + when (intermediate) { + '(' -> g0Graphics = final == '0'.code + ')' -> g1Graphics = final == '0'.code + '#' -> if (final == '8'.code) { // DECALN screen alignment pattern. + top = 0; bottom = rows - 1; x = 0; y = 0; wrapPending = false + screen.forEach { line -> for (col in 0 until line.size) line.set(col, 'E'.code, 7, 0, 0) } + } + } + } + + private fun print(code: Int) { + val mapped = if ((if (shifted) g1Graphics else g0Graphics) && code in 0x5F..0x7E) DEC_GRAPHICS[code - 0x5F] else code + if (mapped in 0x7F..0x9F) return + val width = TerminalWidth.of(mapped) + if (width == 0) { combine(mapped); return } if (wrapPending && wrap) { x = 0; linefeed() } - val line = screen[y]; line.chars[x] = char; line.fg[x] = if (inverse) background else foreground - line.bg[x] = if (inverse) foreground else background; line.bold[x] = bold - wrapPending = x == columns - 1 - if (!wrapPending) x++ + wrapPending = false + if (width == 2 && x == columns - 1) { + if (wrap) { screen[y].erase(x, x + 1, background); x = 0; linefeed() } else x = columns - 2 + } + val line = screen[y] + if (insertMode) insertCells(line, x, width) + val fgColor = if (inverse) background else foreground + val bgColor = if (inverse) foreground else background + if (line.cells[x] == TAIL && x > 0) line.blank(x - 1) + val end = x + width + if (end < columns && line.cells[end] == TAIL) line.blank(end) + line.set(x, mapped, fgColor, bgColor, attrs) + if (width == 2) line.set(x + 1, TAIL, fgColor, bgColor, attrs) + lastPrinted = mapped + if (end >= columns) { x = columns - 1; wrapPending = true } else x = end + } + + private fun combine(code: Int) { + var column = if (wrapPending) x else x - 1 + if (column < 0) return + val line = screen[y] + if (line.cells[column] == TAIL && column > 0) column-- + line.combine(column, buildString { appendCodePoint(code) }) + } + + private fun insertCells(line: Line, at: Int, count: Int) { + val n = count.coerceIn(0, columns - at) + for (i in columns - 1 downTo at + n) line.copy(i, i - n) + line.erase(at, at + n, background) + line.repair(0, columns - 1) } - private fun linefeed() { if (y == bottom) scrollUp(1) else y = (y + 1).coerceAtMost(rows - 1) } - private fun scrollUp(count: Int) { repeat(count.coerceIn(0, rows)) { + + private fun linefeed() { if (y == bottom) scrollUp(1) else if (y < rows - 1) y++ } + private fun reverseIndex() { if (y == top) scrollDown(1) else if (y > 0) y-- } + private fun scrollUp(count: Int) { repeat(count.coerceIn(0, bottom - top + 1)) { val removed = screen.removeAt(top) - if (top == 0 && bottom == rows - 1 && primary == null && historyLimit > 0) { - rememberLine(removed) - } - screen.add(bottom, Line(columns)) + if (top == 0 && bottom == rows - 1 && primary == null) rememberLine(removed) + screen.add(bottom, Line(columns, background)) + } } + private fun scrollDown(count: Int) { repeat(count.coerceIn(0, bottom - top + 1)) { + screen.removeAt(bottom); screen.add(top, Line(columns, background)) } } - private fun scrollDown(count: Int) { repeat(count.coerceIn(0, rows)) { screen.removeAt(bottom); screen.add(top, Line(columns)) } } - private fun clear(row: Int, from: Int = 0, until: Int = columns) = screen[row].clear(from, until, foreground, background) - private fun csi(command: Char, raw: String, replies: StringBuilder) { - // Only the standard numeric grammar and the supported DEC private grammar are accepted. - // Prefixes >, <, = and intermediate bytes must not accidentally become SGR parameters. - if (raw.removePrefix("?").any { it !in '0'..'9' && it != ';' }) return - val private = raw.startsWith('?') - if (private && command != 'h' && command != 'l') return - val args = raw.removePrefix("?").split(';').map { it.toIntOrNull() ?: 0 } - fun arg(index: Int = 0, default: Int = 1) = (args.getOrNull(index) ?: default).let { if (it == 0) default else it }.coerceIn(0, 10000) - if (command != 'm') wrapPending = false - when (command) { - 'A' -> y = (y - arg()).coerceAtLeast(0) - 'B', 'e' -> y = (y + arg()).coerceAtMost(rows - 1) - 'C', 'a' -> x = (x + arg()).coerceAtMost(columns - 1) - 'D' -> x = (x - arg()).coerceAtLeast(0) - 'E' -> { y = (y + arg()).coerceAtMost(rows - 1); x = 0 } - 'F' -> { y = (y - arg()).coerceAtLeast(0); x = 0 } - 'G', '`' -> x = (arg() - 1).coerceIn(0, columns - 1) - 'd' -> y = (arg() - 1).coerceIn(0, rows - 1) - 'H', 'f' -> { y = (arg() - 1).coerceIn(0, rows - 1); x = (arg(1) - 1).coerceIn(0, columns - 1) } - 'J' -> when (args[0]) { - 0 -> { clear(y, x); for (row in y + 1 until rows) clear(row) } - 1 -> { for (row in 0 until y) clear(row); clear(y, 0, x + 1) } - 2 -> for (row in 0 until rows) clear(row) - 3 -> { history.clear(); historyBytes = 0 } - } - 'K' -> when (args[0]) { 0 -> clear(y, x); 1 -> clear(y, 0, x + 1); 2 -> clear(y) } - 'X' -> clear(y, x, (x + arg()).coerceAtMost(columns)) - 'P', '@' -> { - val line = screen[y]; val count = arg().coerceAtMost(columns - x) - val range = if (command == 'P') x until columns - count else (columns - 1 downTo x + count) - for (i in range) { val source = if (command == 'P') i + count else i - count - line.chars[i] = line.chars[source]; line.fg[i] = line.fg[source]; line.bg[i] = line.bg[source]; line.bold[i] = line.bold[source] } - if (command == 'P') clear(y, columns - count) else clear(y, x, x + count) - } - 'L', 'M' -> if (y in top..bottom) repeat(arg().coerceAtMost(bottom - y + 1)) { - if (command == 'L') { screen.removeAt(bottom); screen.add(y, Line(columns)) } - else { screen.removeAt(y); screen.add(bottom, Line(columns)) } - } - 'S' -> scrollUp(arg()) - 'T' -> scrollDown(arg()) - 'r' -> { val a = arg() - 1; val b = arg(1, rows) - 1; if (a in 0 until b && b < rows) { top = a; bottom = b; x = 0; y = 0 } } - 's' -> saved = x to y - 'u' -> { x = saved.first.coerceIn(0, columns - 1); y = saved.second.coerceIn(0, rows - 1) } - 'm' -> sgr(args) - 'n' -> if (!private) when (args[0]) { 5 -> replies.append("\u001b[0n"); 6 -> replies.append("\u001b[${y + 1};${x + 1}R") } - 'c' -> if (!private) replies.append("\u001b[?1;2c") - 'h', 'l' -> if (private) args.forEach { mode -> val on = command == 'h'; when (mode) { - 1 -> applicationCursorKeys = on - 7 -> wrap = on - 25 -> cursorVisible = on - 47, 1047, 1049 -> if (on && primary == null) { primary = screen; primaryCursor = x to y; screen = MutableList(rows) { Line(columns) }; x = 0; y = 0; top = 0; bottom = rows - 1 } - else if (!on && primary != null) { screen = primary!!; primary = null; x = primaryCursor.first; y = primaryCursor.second; resizeScreen(columns, rows, true) } - } } - } - } - private fun sgr(args: List) { + private fun erase(row: Int, from: Int = 0, until: Int = columns) = screen[row].erase(from, until, background) + private fun nextTab(from: Int, count: Int): Int { + var col = from; var left = count + while (left > 0 && col < columns - 1) { col++; if (tabs[col]) left-- } + return col + } + private fun previousTab(from: Int, count: Int): Int { + var col = from; var left = count + while (left > 0 && col > 0) { col--; if (tabs[col]) left-- } + return col + } + private fun defaultTabs(width: Int) = BooleanArray(width) { it % 8 == 0 } + + private fun saveCursor() { + val saved = Saved(x, y, foreground, background, attrs, inverse, originMode, wrapPending, g0Graphics, g1Graphics, shifted) + if (primary == null) savedMain = saved else savedAlternate = saved + } + private fun restoreCursor() { + val saved = if (primary == null) savedMain else savedAlternate + if (saved == null) { x = 0; y = 0; foreground = 7; background = 0; attrs = 0; inverse = false; originMode = false; wrapPending = false; return } + x = saved.x.coerceIn(0, columns - 1); y = saved.y.coerceIn(0, rows - 1) + foreground = saved.foreground; background = saved.background; attrs = saved.attrs; inverse = saved.inverse + originMode = saved.origin; wrapPending = saved.wrapPending && x == columns - 1 + g0Graphics = saved.g0; g1Graphics = saved.g1; shifted = saved.shifted + } + + private fun reset() { + primary = null + screen = MutableList(rows) { Line(columns) }; x = 0; y = 0 + foreground = 7; background = 0; attrs = 0; inverse = false + top = 0; bottom = rows - 1; wrap = true; wrapPending = false; cursorVisible = true + applicationCursorKeys = false; originMode = false; insertMode = false; bracketedPaste = false; title = "" + g0Graphics = false; g1Graphics = false; shifted = false; tabs = defaultTabs(columns) + savedMain = null; savedAlternate = null; lastPrinted = -1 + } + private fun softReset() { + cursorVisible = true; insertMode = false; originMode = false; applicationCursorKeys = false + top = 0; bottom = rows - 1; foreground = 7; background = 0; attrs = 0; inverse = false + g0Graphics = false; g1Graphics = false; shifted = false; savedMain = null; savedAlternate = null + } + + /** One alternate screen without scrollback; the primary keeps its content and cursor while it is hidden. */ + private fun alternate(on: Boolean) { + if (on && primary == null) { + primary = screen; primaryCursor = x to y; screen = MutableList(rows) { Line(columns) } + savedAlternate = null; top = 0; bottom = rows - 1; wrapPending = false + } else if (!on && primary != null) { + screen = primary!!; primary = null + x = primaryCursor.first; y = primaryCursor.second + if (screen.size != rows || screen.any { it.size != columns }) resizeScreen(columns, rows, true) + x = x.coerceIn(0, columns - 1); y = y.coerceIn(0, rows - 1) + top = 0; bottom = rows - 1; wrapPending = false + } + } + + private fun param(index: Int, default: Int = 1): Int { + val value = if (index < paramCount) params[index] else 0 + return if (value == 0) default else value + } + + private fun csi(final: Char, replies: StringBuilder) { + when (privateMarker) { + NONE -> Unit + '?' -> { privateCsi(final, replies); return } + '>' -> { if (final == 'c' && intermediate == NONE && param(0, 0) == 0) replies.append("\u001b[>1;10;0c"); return } + else -> return + } + when (intermediate) { + NONE -> Unit + '!' -> { if (final == 'p') softReset(); return } + else -> return // DECSCUSR, DECRQM, DECSCA and other intermediates: accepted and ignored. + } + if (final != 'm' && final != 'b') wrapPending = false + val minRow = if (originMode) top else 0; val maxRow = if (originMode) bottom else rows - 1 + when (final) { + '@' -> insertCells(screen[y], x, param(0)) + 'A' -> y = (y - param(0)).coerceAtLeast(if (y >= top) top else 0) + 'B', 'e' -> y = (y + param(0)).coerceAtMost(if (y <= bottom) bottom else rows - 1) + 'C', 'a' -> x = (x + param(0)).coerceAtMost(columns - 1) + 'D' -> x = (x - param(0)).coerceAtLeast(0) + 'E' -> { y = (y + param(0)).coerceAtMost(if (y <= bottom) bottom else rows - 1); x = 0 } + 'F' -> { y = (y - param(0)).coerceAtLeast(if (y >= top) top else 0); x = 0 } + 'G', '`' -> x = (param(0) - 1).coerceIn(0, columns - 1) + 'H', 'f' -> { y = (minRow + param(0) - 1).coerceIn(minRow, maxRow); x = (param(1) - 1).coerceIn(0, columns - 1) } + 'I' -> x = nextTab(x, param(0)) + 'Z' -> x = previousTab(x, param(0)) + 'd' -> y = (minRow + param(0) - 1).coerceIn(minRow, maxRow) + 'J' -> eraseDisplay(param(0, 0)) + 'K' -> eraseLine(param(0, 0)) + 'X' -> erase(y, x, (x + param(0)).coerceAtMost(columns)) + 'P' -> { + val line = screen[y]; val n = param(0).coerceAtMost(columns - x) + for (i in x until columns - n) line.copy(i, i + n) + line.erase(columns - n, columns, background); line.repair(0, columns - 1) + } + 'L', 'M' -> if (y in top..bottom) { + repeat(param(0).coerceAtMost(bottom - y + 1)) { + if (final == 'L') { screen.removeAt(bottom); screen.add(y, Line(columns, background)) } + else { screen.removeAt(y); screen.add(bottom, Line(columns, background)) } + } + x = 0 + } + 'S' -> if (paramCount <= 1) scrollUp(param(0)) + 'T' -> if (paramCount <= 1) scrollDown(param(0)) + 'b' -> if (lastPrinted >= 0) repeat(param(0).coerceAtMost(columns * rows)) { print(lastPrinted) } + 'g' -> when (param(0, 0)) { 0 -> tabs[x] = false; 3 -> tabs.fill(false) } + 'h', 'l' -> for (index in 0 until paramCount) if (params[index] == 4) insertMode = final == 'h' + 'r' -> { + val a = param(0) - 1; val b = param(1, rows) - 1 + if (a in 0 until b && b < rows) { top = a; bottom = b; x = 0; y = if (originMode) top else 0 } + } + 's' -> if (paramCount == 0) saveCursor() + 'u' -> if (paramCount == 0) restoreCursor() + 'm' -> sgr() + 'n' -> when (param(0, 0)) { + 5 -> replies.append("\u001b[0n") + 6 -> replies.append("\u001b[${y - minRow + 1};${x + 1}R") + } + 'c' -> if (param(0, 0) == 0) replies.append("\u001b[?1;2c") + // 't' window operations (including title reports) and other finals are ignored on purpose. + } + } + + private fun privateCsi(final: Char, replies: StringBuilder) { + if (intermediate != NONE) return + when (final) { + 'h', 'l' -> for (index in 0 until paramCount) setMode(params[index], final == 'h') + 'J' -> { wrapPending = false; eraseDisplay(param(0, 0)) } + 'K' -> { wrapPending = false; eraseLine(param(0, 0)) } + 'n' -> if (param(0, 0) == 6) replies.append("\u001b[?${y - (if (originMode) top else 0) + 1};${x + 1}R") + } + } + + private fun setMode(mode: Int, on: Boolean) { + when (mode) { + 1 -> applicationCursorKeys = on + 6 -> { originMode = on; x = 0; y = if (on) top else 0; wrapPending = false } + 7 -> { wrap = on; if (!on) wrapPending = false } + 25 -> cursorVisible = on + 47, 1047 -> alternate(on) + 1048 -> if (on) saveCursor() else restoreCursor() + 1049 -> if (on) { if (primary == null) { saveCursor(); alternate(true) } } + else if (primary != null) { alternate(false); restoreCursor() } + 2004 -> bracketedPaste = on + // Mouse (9, 1000–1006, 1015), focus (1004), blink (12), DECCOLM (3) and others are ignored on purpose. + } + } + + private fun eraseDisplay(mode: Int) = when (mode) { + 0 -> { erase(y, x); for (row in y + 1 until rows) erase(row) } + 1 -> { for (row in 0 until y) erase(row); erase(y, 0, x + 1) } + 2 -> for (row in 0 until rows) erase(row) + 3 -> { history.clear(); historyBytes = 0; historyView = null } + else -> Unit + } + private fun eraseLine(mode: Int) = when (mode) { 0 -> erase(y, x); 1 -> erase(y, 0, x + 1); 2 -> erase(y); else -> Unit } + + private fun sgr() { + if (paramCount == 0) { foreground = 7; background = 0; attrs = 0; inverse = false; return } var i = 0 - while (i < args.size) { val n = args[i]; when (n) { - 0 -> { foreground = 7; background = 0; bold = false; inverse = false } - 1 -> bold = true - 22 -> bold = false - 7 -> inverse = true - 27 -> inverse = false - in 30..37 -> foreground = n - 30 - in 40..47 -> background = n - 40 - in 90..97 -> foreground = n - 90 + 8 - in 100..107 -> background = n - 100 + 8 - 39 -> foreground = 7 - 49 -> background = 0 - 38, 48 -> if (args.getOrNull(i + 1) == 5 && args.getOrNull(i + 2) in 0..255) { - if (n == 38) foreground = args[i + 2] else background = args[i + 2]; i += 2 - } else if (args.getOrNull(i + 1) == 2 && i + 4 < args.size) { - val rgb = 0x1000000 or (args[i + 2].coerceIn(0, 255) shl 16) or (args[i + 3].coerceIn(0, 255) shl 8) or args[i + 4].coerceIn(0, 255) - if (n == 38) foreground = rgb else background = rgb; i += 4 - } - }; i++ } + while (i < paramCount) { + val n = params[i] + // Colon sub-parameters (ITU T.416 style, e.g. 38:2::r:g:b) belong to the parameter before them. + var subCount = 0 + while (i + 1 + subCount < paramCount && subParam[i + 1 + subCount]) subCount++ + when (n) { + 0 -> { foreground = 7; background = 0; attrs = 0; inverse = false } + 1 -> attrs = attrs or TerminalRow.BOLD + 2 -> attrs = attrs or TerminalRow.DIM + 3 -> attrs = attrs or TerminalRow.ITALIC + 4 -> attrs = if (subCount > 0 && params[i + 1] == 0) attrs and TerminalRow.UNDERLINE.inv() else attrs or TerminalRow.UNDERLINE + 7 -> inverse = true + 8 -> attrs = attrs or TerminalRow.HIDDEN + 9 -> attrs = attrs or TerminalRow.STRIKE + 21 -> attrs = attrs or TerminalRow.UNDERLINE + 22 -> attrs = attrs and (TerminalRow.BOLD or TerminalRow.DIM).inv() + 23 -> attrs = attrs and TerminalRow.ITALIC.inv() + 24 -> attrs = attrs and TerminalRow.UNDERLINE.inv() + 27 -> inverse = false + 28 -> attrs = attrs and TerminalRow.HIDDEN.inv() + 29 -> attrs = attrs and TerminalRow.STRIKE.inv() + in 30..37 -> foreground = n - 30 + 39 -> foreground = 7 + in 40..47 -> background = n - 40 + 49 -> background = 0 + in 90..97 -> foreground = n - 90 + 8 + in 100..107 -> background = n - 100 + 8 + 38, 48, 58 -> { + val color: Int? = if (subCount > 0) { + val kind = params[i + 1] + when { + kind == 5 && subCount >= 2 -> params[i + 2].takeIf { it in 0..255 } + kind == 2 && subCount >= 5 -> rgb(params[i + 3], params[i + 4], params[i + 5]) + kind == 2 && subCount == 4 -> rgb(params[i + 2], params[i + 3], params[i + 4]) + else -> null + } + } else { + val kind = if (i + 1 < paramCount) params[i + 1] else -1 + when { + kind == 5 && i + 2 < paramCount -> params[i + 2].takeIf { it in 0..255 }.also { i += 2 } + kind == 2 && i + 4 < paramCount -> rgb(params[i + 2], params[i + 3], params[i + 4]).also { i += 4 } + else -> { i = paramCount; null } // Malformed extended colour: the rest is dropped. + } + } + if (color != null) when (n) { 38 -> foreground = color; 48 -> background = color } // 58: underline colour unsupported. + } + } + i += 1 + subCount + } + } + private fun rgb(r: Int, g: Int, b: Int) = 0x1000000 or (r.coerceIn(0, 255) shl 16) or (g.coerceIn(0, 255) shl 8) or b.coerceIn(0, 255) + + private fun oscDispatch() { + if (oscOverflow) { osc.clear(); return } + val value = osc.toString(); osc.clear() + val separator = value.indexOf(';') + if (separator <= 0) return + when (value.substring(0, separator)) { + "0", "2" -> title = sanitizeTitle(value.substring(separator + 1)) + // 1 (icon name), 4/10/11 (colours), 7 (cwd), 8 (links), 52 (clipboard) and others are ignored. + } + } + private fun sanitizeTitle(value: String): String { + val result = StringBuilder() + for (char in value) { + if (result.length >= MAX_TITLE) break + val code = char.code + if (code < 0x20 || code in 0x7F..0x9F || code in 0x200E..0x200F || code in 0x202A..0x202E || code in 0x2066..0x2069) continue + result.append(char) + } + if (result.isNotEmpty() && result.last().isHighSurrogate()) result.deleteAt(result.length - 1) + return result.toString().trim() } } + +private const val NONE = '\u0000' diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalInput.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalInput.kt index 1441dc5..2ded7cd 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalInput.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalInput.kt @@ -47,3 +47,19 @@ fun terminalTextSequence(text: String, control: Boolean = false, alt: Boolean = } else text return (if (alt) "\u001b" else "") + transformed } + +/** + * Text sent as one paste. Control characters (including ESC and newlines) are already replaced by + * [safeTerminalPaste], so the payload cannot contain the end marker; with DECSET 2004 active it is wrapped + * in ESC[200~ … ESC[201~ and a shell inserts it literally instead of interpreting it as typed keys. + */ +fun terminalPastePayload(text: String, bracketed: Boolean): String { + val safe = safeTerminalPaste(text) + return if (bracketed && safe.isNotEmpty()) "\u001b[200~$safe\u001b[201~" else safe +} + +fun terminalFallbackPayload(text: String, control: Boolean, alt: Boolean, bracketed: Boolean): String { + if (text.isEmpty()) return "" + return if (control || alt) terminalTextSequence(safeTerminalPaste(text), control, alt) + else terminalPastePayload(text, bracketed) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalLog.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalLog.kt new file mode 100644 index 0000000..20f86a4 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalLog.kt @@ -0,0 +1,133 @@ +package cz.netkit.shared.ssh + +/** Session log limit: writing stops (with a footer) once this many UTF-8 bytes were written. */ +const val SSH_SESSION_LOG_LIMIT_BYTES = 50L * 1024 * 1024 + +/** + * Turns raw terminal output into plain text lines for the session log. Escape sequences (CSI, OSC, + * DCS/APC/PM, charset designations, C1 controls) never reach the file; a small line editor applies + * carriage return, backspace, cursor left/right and erase-in-line so shell line editing and progress + * bars produce the text the user saw on that line. Full-screen programs (cursor addressing) are not + * reproduced, their printable text is kept in order. Stateful: a sequence split across chunks is handled. + */ +class TerminalLogFilter(private val maxLine: Int = 4096) { + private val line = StringBuilder() + private var column = 0 + private var state = State.TEXT + private val params = StringBuilder() + private var pendingCarriageReturn = false + + private enum class State { TEXT, ESCAPE, CSI, CSI_SKIP, STRING, STRING_ESCAPE, CHARSET } + + /** Returns completed lines (each ending with `\n`); the current line stays buffered. */ + fun feed(text: String): String { + val out = StringBuilder() + for (char in text) { + when (state) { + State.TEXT -> text(char, out) + State.ESCAPE -> escape(char) + State.CSI -> if (char in '@'..'~') { csi(char, params.toString()); params.clear(); state = State.TEXT } + else if (params.length < 64) params.append(char) else { params.clear(); state = State.CSI_SKIP } + State.CSI_SKIP -> if (char in '@'..'~') state = State.TEXT // Overlong parameters: drop the whole sequence. + State.STRING -> when (char) { '\u0007', '\u009c' -> state = State.TEXT; '\u001b' -> state = State.STRING_ESCAPE } + State.STRING_ESCAPE -> state = if (char == '\\') State.TEXT else State.STRING + State.CHARSET -> state = State.TEXT + } + } + return out.toString() + } + + /** Pending partial line (without a trailing newline if it is empty). */ + fun flush(): String { + pendingCarriageReturn = false + if (line.isEmpty()) return "" + val text = line.toString().trimEnd() + "\n" + line.clear(); column = 0 + return text + } + + private fun text(char: Char, out: StringBuilder) { + if (pendingCarriageReturn && char != '\n') { + // A lone CR returns to column 0: the following text overwrites the line (progress bars, prompts). + column = 0 + } + pendingCarriageReturn = false + when { + char == '\u001b' -> state = State.ESCAPE + char == '\u009b' -> { params.clear(); state = State.CSI } + char == '\u009d' || char == '\u0090' || char == '\u009e' || char == '\u009f' || char == '\u0098' -> state = State.STRING + char == '\r' -> pendingCarriageReturn = true + char == '\n' -> newline(out) + char == '\b' -> column = (column - 1).coerceAtLeast(0) + char == '\t' -> put('\t', out) + char.code < 32 || char.code in 127..159 -> Unit + else -> put(char, out) + } + } + + private fun put(char: Char, out: StringBuilder) { + if (column >= maxLine) newline(out) + while (line.length < column) line.append(' ') + if (column < line.length) line[column] = char else line.append(char) + column++ + } + + private fun newline(out: StringBuilder) { + out.append(line.toString().trimEnd()).append('\n') + line.clear(); column = 0 + } + + private fun escape(char: Char) { + state = when (char) { + '[' -> { params.clear(); State.CSI } + ']', 'P', 'X', '^', '_' -> State.STRING + '(', ')', '*', '+', '-', '.', '/', '#', '%', ' ' -> State.CHARSET + else -> State.TEXT // Two-byte sequences (ESC 7, ESC M, ESC =, ...) are dropped. + } + } + + private fun csi(command: Char, raw: String) { + if (raw.any { it !in '0'..'9' && it != ';' }) return // Private/intermediate forms have no text meaning. + val first = raw.substringBefore(';').toIntOrNull() + val count = (first ?: 1).coerceIn(1, maxLine) + when (command) { + 'C' -> column = (column + count).coerceAtMost(maxLine) + 'D' -> column = (column - count).coerceAtLeast(0) + 'G' -> column = (count - 1).coerceIn(0, maxLine) + 'K' -> when (first ?: 0) { + 0 -> if (column < line.length) line.setLength(column) + 1 -> for (index in 0 until minOf(column + 1, line.length)) line[index] = ' ' + 2 -> line.clear() + } + 'P' -> if (column < line.length) line.deleteRange(column, minOf(line.length, column + count)) + '@' -> if (column < line.length) { + val spaces = minOf(count, maxLine - line.length).coerceAtLeast(0) + line.insertRange(column, CharArray(spaces) { ' ' }, 0, spaces) + } + } + } +} + +/** Byte budget of one log file. [take] returns the part that still fits; afterwards [exhausted] is true. */ +class SessionLogBudget(private val limitBytes: Long = SSH_SESSION_LOG_LIMIT_BYTES) { + var written: Long = 0; private set + var exhausted: Boolean = false; private set + + fun take(text: String): String { + if (exhausted || text.isEmpty()) return "" + val bytes = text.encodeToByteArray() + if (written + bytes.size <= limitBytes) { written += bytes.size; return text } + // Cut at a character boundary that keeps the UTF-8 size within the limit. + val remaining = limitBytes - written + var size = 0L + var end = 0 + while (end < text.length) { + val step = if (text[end].isHighSurrogate() && end + 1 < text.length) 2 else 1 + val charBytes = text.substring(end, end + step).encodeToByteArray().size + if (size + charBytes > remaining) break + size += charBytes; end += step + } + written += size; exhausted = true + return text.substring(0, end) + } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalPalette.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalPalette.kt new file mode 100644 index 0000000..8918f7d --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalPalette.kt @@ -0,0 +1,64 @@ +package cz.netkit.shared.ssh + +import kotlin.math.pow + +/** Resolved colours of one run as opaque ARGB integers. */ +data class TerminalColors(val foreground: Int, val background: Int) + +/** + * Xterm 256-colour palette for the always-dark terminal surface (docs/design.md §2: the terminal tokens + * are the same in the dark and light app themes). Indices 1–15 are tuned so that text on the default + * background keeps at least 4.5:1 (8 = "bright black" at least 3:1); 16–231 are the xterm 6×6×6 cube + * (levels 0, 95, 135, 175, 215, 255) and 232–255 the grey ramp 8 + 10·n. Default colours (SGR 39/49, + * index 7 as foreground and 0 as background, and their inverse) follow the theme tokens. + */ +object TerminalPalette { + private val BASIC = intArrayOf( + 0xFF000000.toInt(), 0xFFE5534B.toInt(), 0xFF57C764.toInt(), 0xFFD5B53B.toInt(), + 0xFF5B9CF0.toInt(), 0xFFC678DD.toInt(), 0xFF3FC1C9.toInt(), 0xFFD0D7DE.toInt(), + 0xFF7D8590.toInt(), 0xFFFF7B72.toInt(), 0xFF7EE787.toInt(), 0xFFF2CC60.toInt(), + 0xFF79C0FF.toInt(), 0xFFE39AF5.toInt(), 0xFF6FE3E3.toInt(), 0xFFFFFFFF.toInt(), + ) + private val CUBE = intArrayOf(0, 95, 135, 175, 215, 255) + + /** ARGB of a palette index (0–255) or a truecolor value (`0x1000000 or rgb`). */ + fun argb(color: Int): Int = when { + color >= 0x1000000 -> (0xFF000000.toInt()) or (color and 0xFFFFFF) + color < 16 -> BASIC[color.coerceAtLeast(0)] + color < 232 -> { val n = color - 16; opaque(CUBE[n / 36], CUBE[n / 6 % 6], CUBE[n % 6]) } + else -> { val level = 8 + (color.coerceAtMost(255) - 232) * 10; opaque(level, level, level) } + } + + /** + * Colours for a run on the terminal surface. [defaultForeground]/[defaultBackground] are the theme tokens. + * Dim blends the foreground halfway to the background; hidden draws the text in the background colour. + */ + fun resolve(run: TerminalRun, defaultForeground: Int, defaultBackground: Int): TerminalColors { + val background = when (run.background) { 0 -> defaultBackground; 7 -> defaultForeground; else -> argb(run.background) } + var foreground = when (run.foreground) { 7 -> defaultForeground; 0 -> defaultBackground; else -> argb(run.foreground) } + if (run.dim) foreground = blend(foreground, background) + if (run.hidden) foreground = background + return TerminalColors(foreground, background) + } + + /** WCAG 2.x contrast ratio of two opaque colours. */ + fun contrast(first: Int, second: Int): Double { + val a = luminance(first); val b = luminance(second) + return (maxOf(a, b) + 0.05) / (minOf(a, b) + 0.05) + } + + private fun luminance(color: Int): Double { + fun channel(shift: Int): Double { + val c = ((color shr shift) and 0xFF) / 255.0 + return if (c <= 0.04045) c / 12.92 else ((c + 0.055) / 1.055).pow(2.4) + } + return 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0) + } + + private fun blend(a: Int, b: Int): Int { + fun mix(shift: Int) = (((a shr shift) and 0xFF) + ((b shr shift) and 0xFF)) / 2 + return opaque(mix(16), mix(8), mix(0)) + } + + private fun opaque(r: Int, g: Int, b: Int): Int = (0xFF000000.toInt()) or (r shl 16) or (g shl 8) or b +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt new file mode 100644 index 0000000..7bde344 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt @@ -0,0 +1,124 @@ +package cz.netkit.shared.ssh + +/** + * Terminal cell width of one Unicode code point (0, 1 or 2), in the style of POSIX wcwidth. + * Generated from Unicode 18.0.0 EastAsianWidth.txt (W and F are wide) and DerivedGeneralCategory.txt + * (Mn, Me and Cf are zero width; Hangul medial/final jamo too; U+00AD stays width 1). + * Source, checksums and generator: docs/zavislosti.md (terminál, Unicode data). + */ +object TerminalWidth { + fun of(codePoint: Int): Int = when { + codePoint < 0x20 -> 0 + codePoint < 0x7F -> 1 + codePoint < 0xA0 -> 0 + codePoint < 0x300 -> 1 + inRanges(ZERO, codePoint) -> 0 + inRanges(WIDE, codePoint) -> 2 + else -> 1 + } + + private fun inRanges(table: IntArray, codePoint: Int): Boolean { + var low = 0; var high = table.size / 2 - 1 + while (low <= high) { + val middle = (low + high) ushr 1 + when { + codePoint < table[middle * 2] -> high = middle - 1 + codePoint > table[middle * 2 + 1] -> low = middle + 1 + else -> return true + } + } + return false + } + + // Pairs of inclusive [start, end] ranges, sorted and merged. + private val WIDE = intArrayOf( + 0x1100, 0x115F, 0x231A, 0x231B, 0x2329, 0x232A, 0x23E9, 0x23EC, 0x23F0, 0x23F0, 0x23F3, 0x23F3, + 0x25FD, 0x25FE, 0x2614, 0x2615, 0x2630, 0x2637, 0x2648, 0x2653, 0x267F, 0x267F, 0x268A, 0x268F, + 0x2693, 0x2693, 0x26A1, 0x26A1, 0x26AA, 0x26AB, 0x26BD, 0x26BE, 0x26C4, 0x26C5, 0x26CE, 0x26CE, + 0x26D4, 0x26D4, 0x26EA, 0x26EA, 0x26F2, 0x26F3, 0x26F5, 0x26F5, 0x26FA, 0x26FA, 0x26FD, 0x26FD, + 0x2705, 0x2705, 0x270A, 0x270B, 0x2728, 0x2728, 0x274C, 0x274C, 0x274E, 0x274E, 0x2753, 0x2755, + 0x2757, 0x2757, 0x2795, 0x2797, 0x27B0, 0x27B0, 0x27BF, 0x27BF, 0x2B1B, 0x2B1C, 0x2B50, 0x2B50, + 0x2B55, 0x2B55, 0x2E80, 0x2E99, 0x2E9B, 0x2EF3, 0x2F00, 0x2FD5, 0x2FF0, 0x303E, 0x3041, 0x3096, + 0x3099, 0x30FF, 0x3105, 0x312F, 0x3131, 0x318E, 0x3190, 0x31E5, 0x31EF, 0x321E, 0x3220, 0x3247, + 0x3250, 0xA48C, 0xA490, 0xA4C6, 0xA960, 0xA97C, 0xAC00, 0xD7A3, 0xF900, 0xFAFF, 0xFE10, 0xFE19, + 0xFE30, 0xFE52, 0xFE54, 0xFE66, 0xFE68, 0xFE6B, 0xFF01, 0xFF60, 0xFFE0, 0xFFE6, 0x16FE0, 0x16FE4, + 0x16FF0, 0x16FF6, 0x17000, 0x18CDA, 0x18CFF, 0x18D20, 0x18D80, 0x18DF2, 0x18E00, 0x19191, 0x191A0, 0x191D2, + 0x1AFF0, 0x1AFF3, 0x1AFF5, 0x1AFFB, 0x1AFFD, 0x1AFFE, 0x1B000, 0x1B128, 0x1B132, 0x1B132, 0x1B150, 0x1B152, + 0x1B155, 0x1B155, 0x1B164, 0x1B168, 0x1B170, 0x1B2FB, 0x1D300, 0x1D356, 0x1D360, 0x1D376, 0x1F004, 0x1F004, + 0x1F0CF, 0x1F0CF, 0x1F18E, 0x1F18E, 0x1F191, 0x1F19A, 0x1F1AE, 0x1F1AE, 0x1F200, 0x1F202, 0x1F210, 0x1F23B, + 0x1F240, 0x1F248, 0x1F250, 0x1F251, 0x1F260, 0x1F265, 0x1F300, 0x1F320, 0x1F32D, 0x1F335, 0x1F337, 0x1F37C, + 0x1F37E, 0x1F393, 0x1F3A0, 0x1F3CA, 0x1F3CF, 0x1F3D3, 0x1F3E0, 0x1F3F0, 0x1F3F4, 0x1F3F4, 0x1F3F8, 0x1F43E, + 0x1F440, 0x1F440, 0x1F442, 0x1F4FC, 0x1F4FF, 0x1F53D, 0x1F54B, 0x1F54E, 0x1F550, 0x1F567, 0x1F57A, 0x1F57A, + 0x1F595, 0x1F596, 0x1F5A4, 0x1F5A4, 0x1F5FB, 0x1F64F, 0x1F680, 0x1F6C5, 0x1F6CC, 0x1F6CC, 0x1F6D0, 0x1F6D2, + 0x1F6D5, 0x1F6D9, 0x1F6DC, 0x1F6DF, 0x1F6EB, 0x1F6EC, 0x1F6F4, 0x1F6FC, 0x1F7DA, 0x1F7DA, 0x1F7E0, 0x1F7EB, + 0x1F7F0, 0x1F7F0, 0x1F90C, 0x1F93A, 0x1F93C, 0x1F945, 0x1F947, 0x1F9FF, 0x1FA70, 0x1FA7C, 0x1FA80, 0x1FAC6, + 0x1FAC8, 0x1FAC8, 0x1FACC, 0x1FADD, 0x1FADF, 0x1FAEB, 0x1FAEF, 0x1FAFA, 0x20000, 0x2FFFD, 0x30000, 0x3FFFD, + ) + + private val ZERO = intArrayOf( + 0x300, 0x36F, 0x483, 0x489, 0x591, 0x5BD, 0x5BF, 0x5BF, 0x5C1, 0x5C2, 0x5C4, 0x5C5, + 0x5C7, 0x5C9, 0x600, 0x605, 0x610, 0x61A, 0x61C, 0x61C, 0x64B, 0x65F, 0x670, 0x670, + 0x6D6, 0x6DD, 0x6DF, 0x6E4, 0x6E7, 0x6E8, 0x6EA, 0x6ED, 0x70F, 0x70F, 0x711, 0x711, + 0x730, 0x74A, 0x7A6, 0x7B0, 0x7EB, 0x7F3, 0x7FD, 0x7FD, 0x816, 0x819, 0x81B, 0x823, + 0x825, 0x827, 0x829, 0x82D, 0x859, 0x85B, 0x890, 0x891, 0x897, 0x89F, 0x8CA, 0x902, + 0x93A, 0x93A, 0x93C, 0x93C, 0x941, 0x948, 0x94D, 0x94D, 0x951, 0x957, 0x962, 0x963, + 0x981, 0x981, 0x9BC, 0x9BC, 0x9C1, 0x9C4, 0x9CD, 0x9CD, 0x9E2, 0x9E3, 0x9FE, 0x9FE, + 0xA01, 0xA02, 0xA3C, 0xA3C, 0xA41, 0xA42, 0xA47, 0xA48, 0xA4B, 0xA4D, 0xA51, 0xA51, + 0xA70, 0xA71, 0xA75, 0xA75, 0xA81, 0xA82, 0xABC, 0xABC, 0xAC1, 0xAC5, 0xAC7, 0xAC8, + 0xACD, 0xACD, 0xAE2, 0xAE3, 0xAFA, 0xAFF, 0xB01, 0xB01, 0xB3C, 0xB3C, 0xB3F, 0xB3F, + 0xB41, 0xB44, 0xB4D, 0xB4D, 0xB53, 0xB56, 0xB62, 0xB63, 0xB82, 0xB82, 0xBC0, 0xBC0, + 0xBCD, 0xBCD, 0xC00, 0xC00, 0xC04, 0xC04, 0xC3C, 0xC3C, 0xC3E, 0xC40, 0xC46, 0xC48, + 0xC4A, 0xC4D, 0xC55, 0xC56, 0xC62, 0xC63, 0xC81, 0xC81, 0xCBC, 0xCBC, 0xCBF, 0xCBF, + 0xCC6, 0xCC6, 0xCCC, 0xCCD, 0xCE2, 0xCE3, 0xD00, 0xD01, 0xD3B, 0xD3C, 0xD41, 0xD44, + 0xD4D, 0xD4D, 0xD62, 0xD63, 0xD81, 0xD81, 0xDCA, 0xDCA, 0xDD2, 0xDD4, 0xDD6, 0xDD6, + 0xE31, 0xE31, 0xE34, 0xE3A, 0xE47, 0xE4E, 0xEB1, 0xEB1, 0xEB4, 0xEBC, 0xEC8, 0xECE, + 0xF18, 0xF19, 0xF35, 0xF35, 0xF37, 0xF37, 0xF39, 0xF39, 0xF71, 0xF7E, 0xF80, 0xF84, + 0xF86, 0xF87, 0xF8D, 0xF97, 0xF99, 0xFBC, 0xFC6, 0xFC6, 0x102D, 0x1030, 0x1032, 0x1037, + 0x1039, 0x103A, 0x103D, 0x103E, 0x1058, 0x1059, 0x105E, 0x1060, 0x1071, 0x1074, 0x1082, 0x1082, + 0x1085, 0x1086, 0x108D, 0x108D, 0x109D, 0x109D, 0x1160, 0x11FF, 0x135D, 0x135F, 0x1712, 0x1714, + 0x1732, 0x1733, 0x1752, 0x1753, 0x1772, 0x1773, 0x17B4, 0x17B5, 0x17B7, 0x17BD, 0x17C6, 0x17C6, + 0x17C9, 0x17D3, 0x17DD, 0x17DD, 0x180B, 0x180F, 0x1885, 0x1886, 0x18A9, 0x18A9, 0x1920, 0x1922, + 0x1927, 0x1928, 0x1932, 0x1932, 0x1939, 0x193B, 0x1A17, 0x1A18, 0x1A1B, 0x1A1B, 0x1A56, 0x1A56, + 0x1A58, 0x1A5E, 0x1A60, 0x1A60, 0x1A62, 0x1A62, 0x1A65, 0x1A6C, 0x1A73, 0x1A7C, 0x1A7F, 0x1A7F, + 0x1AB0, 0x1AF0, 0x1B00, 0x1B03, 0x1B34, 0x1B34, 0x1B36, 0x1B3A, 0x1B3C, 0x1B3C, 0x1B42, 0x1B42, + 0x1B6B, 0x1B73, 0x1B80, 0x1B81, 0x1BA2, 0x1BA5, 0x1BA8, 0x1BA9, 0x1BAB, 0x1BAD, 0x1BE6, 0x1BE6, + 0x1BE8, 0x1BE9, 0x1BED, 0x1BED, 0x1BEF, 0x1BF1, 0x1C2C, 0x1C33, 0x1C36, 0x1C37, 0x1CD0, 0x1CD2, + 0x1CD4, 0x1CE0, 0x1CE2, 0x1CE8, 0x1CED, 0x1CED, 0x1CF4, 0x1CF4, 0x1CF8, 0x1CF9, 0x1DC0, 0x1DFF, + 0x200B, 0x200F, 0x202A, 0x202E, 0x2060, 0x2064, 0x2066, 0x206F, 0x20D0, 0x20F0, 0x2CEF, 0x2CF1, + 0x2D7F, 0x2D7F, 0x2DE0, 0x2DFF, 0x302A, 0x302D, 0x3099, 0x309A, 0xA66F, 0xA672, 0xA674, 0xA67D, + 0xA69E, 0xA69F, 0xA6F0, 0xA6F1, 0xA802, 0xA802, 0xA806, 0xA806, 0xA80B, 0xA80B, 0xA825, 0xA826, + 0xA82C, 0xA82C, 0xA8C4, 0xA8C5, 0xA8E0, 0xA8F1, 0xA8FF, 0xA8FF, 0xA926, 0xA92D, 0xA947, 0xA951, + 0xA980, 0xA982, 0xA9B3, 0xA9B3, 0xA9B6, 0xA9B9, 0xA9BC, 0xA9BD, 0xA9E5, 0xA9E5, 0xAA29, 0xAA2E, + 0xAA31, 0xAA32, 0xAA35, 0xAA36, 0xAA43, 0xAA43, 0xAA4C, 0xAA4C, 0xAA7C, 0xAA7C, 0xAAB0, 0xAAB0, + 0xAAB2, 0xAAB4, 0xAAB7, 0xAAB8, 0xAABE, 0xAABF, 0xAAC1, 0xAAC1, 0xAAEC, 0xAAED, 0xAAF6, 0xAAF6, + 0xABE5, 0xABE5, 0xABE8, 0xABE8, 0xABED, 0xABED, 0xD7B0, 0xD7FF, 0xFB1E, 0xFB1E, 0xFE00, 0xFE0F, + 0xFE20, 0xFE2F, 0xFEFF, 0xFEFF, 0xFFF9, 0xFFFB, 0x101FD, 0x101FD, 0x102E0, 0x102E0, 0x10376, 0x1037A, + 0x10A01, 0x10A03, 0x10A05, 0x10A06, 0x10A0C, 0x10A0F, 0x10A38, 0x10A3A, 0x10A3F, 0x10A3F, 0x10AE5, 0x10AE6, + 0x10D24, 0x10D27, 0x10D69, 0x10D6D, 0x10EAB, 0x10EAC, 0x10ECB, 0x10ECF, 0x10EF0, 0x10EFF, 0x10F46, 0x10F50, + 0x10F82, 0x10F85, 0x11001, 0x11001, 0x11038, 0x11046, 0x11070, 0x11070, 0x11073, 0x11074, 0x1107F, 0x11081, + 0x110B3, 0x110B6, 0x110B9, 0x110BA, 0x110BD, 0x110BD, 0x110C2, 0x110C2, 0x110CD, 0x110CD, 0x11100, 0x11102, + 0x11127, 0x1112B, 0x1112D, 0x11134, 0x11173, 0x11173, 0x11180, 0x11181, 0x111B6, 0x111BE, 0x111C9, 0x111CC, + 0x111CF, 0x111CF, 0x1122F, 0x11231, 0x11234, 0x11234, 0x11236, 0x11237, 0x1123E, 0x1123E, 0x11241, 0x11241, + 0x112DF, 0x112DF, 0x112E3, 0x112EA, 0x11300, 0x11301, 0x1133B, 0x1133C, 0x11340, 0x11340, 0x11366, 0x1136C, + 0x11370, 0x11374, 0x113BB, 0x113C0, 0x113CE, 0x113CE, 0x113D0, 0x113D0, 0x113D2, 0x113D2, 0x113E1, 0x113E2, + 0x11438, 0x1143F, 0x11442, 0x11444, 0x11446, 0x11446, 0x1145E, 0x1145E, 0x114B3, 0x114B8, 0x114BA, 0x114BA, + 0x114BF, 0x114C0, 0x114C2, 0x114C3, 0x115B2, 0x115B5, 0x115BC, 0x115BD, 0x115BF, 0x115C0, 0x115DC, 0x115DD, + 0x11633, 0x1163A, 0x1163D, 0x1163D, 0x1163F, 0x11640, 0x116AB, 0x116AB, 0x116AD, 0x116AD, 0x116B0, 0x116B5, + 0x116B7, 0x116B7, 0x1171D, 0x1171D, 0x1171F, 0x1171F, 0x11722, 0x11725, 0x11727, 0x1172B, 0x1182F, 0x11837, + 0x11839, 0x1183A, 0x1193B, 0x1193C, 0x1193E, 0x1193E, 0x11943, 0x11943, 0x119D4, 0x119D7, 0x119DA, 0x119DB, + 0x119E0, 0x119E0, 0x11A01, 0x11A0A, 0x11A33, 0x11A38, 0x11A3B, 0x11A3E, 0x11A47, 0x11A47, 0x11A51, 0x11A56, + 0x11A59, 0x11A5B, 0x11A8A, 0x11A96, 0x11A98, 0x11A99, 0x11B60, 0x11B60, 0x11B62, 0x11B64, 0x11B66, 0x11B66, + 0x11C30, 0x11C36, 0x11C38, 0x11C3D, 0x11C3F, 0x11C3F, 0x11C92, 0x11CA7, 0x11CAA, 0x11CB0, 0x11CB2, 0x11CB3, + 0x11CB5, 0x11CB6, 0x11D31, 0x11D36, 0x11D3A, 0x11D3A, 0x11D3C, 0x11D3D, 0x11D3F, 0x11D45, 0x11D47, 0x11D47, + 0x11D90, 0x11D91, 0x11D95, 0x11D95, 0x11D97, 0x11D97, 0x11DF0, 0x11DF0, 0x11EF3, 0x11EF4, 0x11F00, 0x11F01, + 0x11F36, 0x11F3A, 0x11F40, 0x11F40, 0x11F42, 0x11F42, 0x11F5A, 0x11F5A, 0x13430, 0x13440, 0x13447, 0x13455, + 0x1611E, 0x16129, 0x1612D, 0x1612F, 0x16AF0, 0x16AF4, 0x16B30, 0x16B36, 0x16F4F, 0x16F4F, 0x16F8F, 0x16F92, + 0x16FE4, 0x16FE4, 0x1BC9D, 0x1BC9E, 0x1BCA0, 0x1BCA3, 0x1CF00, 0x1CF2D, 0x1CF30, 0x1CF46, 0x1D127, 0x1D128, + 0x1D167, 0x1D169, 0x1D173, 0x1D182, 0x1D185, 0x1D18B, 0x1D1AA, 0x1D1AD, 0x1D242, 0x1D244, 0x1D25B, 0x1D25C, + 0x1DA00, 0x1DA36, 0x1DA3B, 0x1DA6C, 0x1DA75, 0x1DA75, 0x1DA84, 0x1DA84, 0x1DA9B, 0x1DA9F, 0x1DAA1, 0x1DAAF, + 0x1E000, 0x1E006, 0x1E008, 0x1E018, 0x1E01B, 0x1E021, 0x1E023, 0x1E024, 0x1E026, 0x1E02A, 0x1E08F, 0x1E08F, + 0x1E130, 0x1E136, 0x1E2AE, 0x1E2AE, 0x1E2EC, 0x1E2EF, 0x1E4EC, 0x1E4EF, 0x1E5EE, 0x1E5EF, 0x1E6E3, 0x1E6E3, + 0x1E6E6, 0x1E6E6, 0x1E6EE, 0x1E6EF, 0x1E6F5, 0x1E6F5, 0x1E8D0, 0x1E8D6, 0x1E944, 0x1E94A, 0xE0001, 0xE0001, + 0xE0020, 0xE007F, 0xE0100, 0xE01EF, + ) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/EssGroups.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/EssGroups.kt new file mode 100644 index 0000000..ef6cb3c --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/EssGroups.kt @@ -0,0 +1,87 @@ +package cz.netkit.shared.wifi + +/* + * Zadání 38 §2.2: AP list grouped by SSID (ESS). One group = one exact SSID (case-sensitive, + * as broadcast); hidden SSIDs are never grouped, each stays a single row — two hidden networks + * are not evidence of one ESS. + */ + +sealed interface EssListEntry { + /** Stable lazy-list key. */ + val key: String + + /** + * APs broadcasting [ssid]. [accessPoints] keep the input order (the caller's sort); + * [bands] ascending by band; [channelsByBand] the primary channels of each band, ascending + * (a channel number alone is ambiguous across bands: 2.4 GHz 5 ≠ 6 GHz 5; unknown left out); + * [strongestRssiDbm] the best RSSI of the group. + */ + data class Group( + val ssid: String, + val accessPoints: List, + val bands: List, + val channelsByBand: Map>, + val strongestRssiDbm: Int, + ) : EssListEntry { + override val key: String get() = "ess:${ssid.length}:$ssid" + /** Number of radios (BSSIDs); anonymous observations without a BSSID count once each. */ + val apCount: Int get() = accessPoints.size + val hasCurrent: Boolean get() = accessPoints.any { it.isCurrent } + } + + /** A hidden-SSID AP, shown alone. */ + data class Single(val accessPoint: AccessPoint) : EssListEntry { + override val key: String get() = "single:" + accessPointKey(accessPoint) + } +} + +/** + * Groups [points] (already filtered and sorted, e.g. [sortedAccessPoints]) by SSID. Entries are + * ordered by [sort]: SIGNAL strongest group first, NAME by SSID (hidden last), CHANNEL by the + * lowest band and channel. Ties fall back to the position of the first AP in [points]. + */ +fun essListEntries(points: List, sort: WifiSort = WifiSort.SIGNAL): List { + val firstIndex = HashMap() + val entries = mutableListOf() + val grouped = LinkedHashMap>() + points.forEachIndexed { index, point -> + val ssid = point.ssid?.takeIf { it.isNotEmpty() } + if (ssid == null) entries += EssListEntry.Single(point).also { firstIndex[it.key] = index } + else grouped.getOrPut(ssid) { firstIndex["ess:${ssid.length}:$ssid"] = index; mutableListOf() } += point + } + grouped.forEach { (ssid, aps) -> + entries += EssListEntry.Group( + ssid = ssid, + accessPoints = aps, + bands = aps.map { it.band }.distinct().sortedBy { it.ordinal }, + channelsByBand = aps.map { it.band }.distinct().sortedBy { it.ordinal }.associateWith { band -> + aps.filter { it.band == band }.mapNotNull { it.channel }.distinct().sorted() + }, + strongestRssiDbm = aps.maxOf { it.rssiDbm }, + ) + } + val order = compareBy { firstIndex[it.key] ?: Int.MAX_VALUE } + return entries.sortedWith(when (sort) { + WifiSort.SIGNAL -> compareByDescending { it.strongestRssi() }.then(order) + WifiSort.NAME -> compareBy { it.ssidOrNull() == null } + .thenBy { it.ssidOrNull().orEmpty().lowercase() }.then(order) + WifiSort.CHANNEL -> compareBy { it.lowestBand() }.thenBy { it.lowestChannel() }.then(order) + }) +} + +private fun EssListEntry.strongestRssi(): Int = when (this) { + is EssListEntry.Group -> strongestRssiDbm + is EssListEntry.Single -> accessPoint.rssiDbm +} + +private fun EssListEntry.ssidOrNull(): String? = (this as? EssListEntry.Group)?.ssid + +private fun EssListEntry.lowestBand(): Int = when (this) { + is EssListEntry.Group -> bands.minOf { it.ordinal } + is EssListEntry.Single -> accessPoint.band.ordinal +} + +private fun EssListEntry.lowestChannel(): Int = when (this) { + is EssListEntry.Group -> channelsByBand.entries.minByOrNull { it.key.ordinal }?.value?.firstOrNull() + is EssListEntry.Single -> accessPoint.channel +} ?: Int.MAX_VALUE diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Mlo.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Mlo.kt new file mode 100644 index 0000000..5028852 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Mlo.kt @@ -0,0 +1,47 @@ +package cz.netkit.shared.wifi + +/** Only associated links from the current connection belong in the overview. */ +data class MloConnection(val links: List, val apMldAddress: String?) +enum class MloBand { GHZ_2_4, GHZ_5, GHZ_6, GHZ_60 } +enum class MloState { ACTIVE, IDLE, UNASSOCIATED, UNKNOWN } + +data class MloLinkInfo(val id: Int, val band: MloBand?, val channel: Int?, val rssiDbm: Int?, + val state: MloState, val advertisedWidth: MloWidth?) +enum class MloWidth(val mhz: Int) { W20(20), W40(40), W80(80), W160(160), W80_PLUS_80(160), W320(320) } + +/** Platform codes from ScanResult/MloLink. Frequency is derived from this link's band and channel. */ +data class AssociatedLink(val id: Int, val band: Int, val channel: Int, val frequencyMhz: Int, val rssi: Int, val state: Int) +data class MloScanWidth(val mld: String, val id: Int, val frequencyMhz: Int, val seenMs: Long, val widthCode: Int) + +fun mloConnection(links: List, mld: String?, locationAllowed: Boolean, + scans: List, nowMs: Long): MloConnection? { + val address = if (locationAllowed) usableBssid(mld) else null + val mapped = links.filter { it.id in 0..15 }.distinctBy { it.id }.sortedBy { it.id }.map { link -> + // Only a recent observation of this MLD, link and channel can describe its advertised width. + val scan = if (address != null && link.frequencyMhz > 0) scans.filter { + it.id == link.id && it.frequencyMhz == link.frequencyMhz && it.mld.equals(address, ignoreCase = true) && + it.seenMs > 0 && it.seenMs <= nowMs && nowMs - it.seenMs <= WIFI_DATASET_WARNING_MS + }.maxByOrNull { it.seenMs } else null + MloLinkInfo(link.id, when (link.band) { + 1 -> MloBand.GHZ_2_4 + 2 -> MloBand.GHZ_5 + 8 -> MloBand.GHZ_6 + 16 -> MloBand.GHZ_60 + else -> null + }, link.channel.takeIf { it > 0 }, validRssiDbm(link.rssi), when (link.state) { + 3 -> MloState.ACTIVE + 2 -> MloState.IDLE + 1 -> MloState.UNASSOCIATED + else -> MloState.UNKNOWN + }, when (scan?.widthCode) { + 0 -> MloWidth.W20 + 1 -> MloWidth.W40 + 2 -> MloWidth.W80 + 3 -> MloWidth.W160 + 4 -> MloWidth.W80_PLUS_80 + 5 -> MloWidth.W320 + else -> null + }) + } + return if (mapped.isEmpty()) null else MloConnection(mapped, address) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/RegionalRaster.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/RegionalRaster.kt new file mode 100644 index 0000000..a0d2c2c --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/RegionalRaster.kt @@ -0,0 +1,45 @@ +package cz.netkit.shared.wifi + +/* + * Zadání 38 §2.5: informative 2.4 GHz channel raster by country code (ISO 3166-1 alpha-2, as + * Android's TelephonyManager.getNetworkCountryIso() gives it). It is a note only: channel health, + * the heat strip and the recommendations keep their global raster (1, 6, 11) and are not changed. + * Without a country code, or for a country outside the table, nothing is shown. + */ + +enum class WifiRegion { EU, US, JP } + +/** + * Permitted 2.4 GHz channels of a region: [firstChannel]..[lastChannel]; [dsssOnlyChannel] is a + * channel allowed only for 802.11b (DSSS/CCK), i.e. Japan's channel 14. + */ +data class Regional24Raster( + val region: WifiRegion, + val countryCode: String, + val firstChannel: Int, + val lastChannel: Int, + val dsssOnlyChannel: Int? = null, +) { + /** Channel within the region's raster for OFDM (802.11g/n/ax), i.e. excluding a DSSS-only channel. */ + fun allowsOfdm(channel: Int): Boolean = channel in firstChannel..lastChannel && channel != dsssOnlyChannel +} + +/** EU member states (ISO 3166-1 alpha-2; Greece is "GR" in ISO, "EL" is the EU's own code). */ +val EU_COUNTRY_CODES: Set = setOf( + "AT", "BE", "BG", "HR", "CY", "CZ", "DK", "EE", "FI", "FR", "DE", "GR", "HU", "IE", "IT", "LV", "LT", "LU", + "MT", "NL", "PL", "PT", "RO", "SK", "SI", "ES", "SE", +) + +/** + * Maps a country code (any case, surrounding blanks ignored) to the informative 2.4 GHz raster: + * EU 1–13, US 1–11, JP 1–14 (14 802.11b only). Null for a blank, malformed or other country. + */ +fun regional24Raster(countryCode: String?): Regional24Raster? { + val code = countryCode?.trim()?.uppercase()?.takeIf { it.length == 2 && it.all { c -> c in 'A'..'Z' } } ?: return null + return when { + code in EU_COUNTRY_CODES -> Regional24Raster(WifiRegion.EU, code, 1, 13) + code == "US" -> Regional24Raster(WifiRegion.US, code, 1, 11) + code == "JP" -> Regional24Raster(WifiRegion.JP, code, 1, 14, dsssOnlyChannel = 14) + else -> null + } +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Spectrum.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Spectrum.kt index 225be62..48f1bde 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Spectrum.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Spectrum.kt @@ -18,7 +18,7 @@ import kotlin.math.round * } * val counts = wifiBandCounts(state.accessPoints) // chips All / 2.4 / 5 / 6 * when (val h = channelHealthReport(state, band, SystemClock.elapsedRealtime())) { - * is ChannelHealthReport.Ready -> h.channels // one entry per axis channel + * is ChannelHealthReport.Ready -> h.channels // one entry per raster channel * is ChannelHealthReport.Stale -> offerNewScan() // never show old health * is ChannelHealthReport.NoData -> showNoBandData() // no AP observed in band * } @@ -28,19 +28,33 @@ import kotlin.math.round * channel health follows the recommendation age policy (wifiDatasetAge.allowsRecommendation). */ -/** One channel tick on the axis. [labelled] marks the subset the UI should print. */ -data class SpectrumTick(val channel: Int, val frequencyMhz: Double, val labelled: Boolean) +/** + * One channel tick on the axis. [labelled] marks the subset the UI should print; [outOfBand] + * marks a channel centred outside the permitted band (2.4 GHz channel 14), printed muted. + */ +data class SpectrumTick(val channel: Int, val frequencyMhz: Double, val labelled: Boolean, val outOfBand: Boolean = false) -/** Frequency range inside the axis without any listed 20 MHz channel (e.g. 5 GHz UNII-2/2C gap). */ +/** + * Frequency range inside the axis without any listed 20 MHz channel (e.g. 5 GHz UNII-2/2C gap), + * or, in [SpectrumAxis.outOfBand], a range outside the permitted band. + */ data class SpectrumGap(val lowerMhz: Double, val upperMhz: Double) /** * Linear frequency axis for one band. The axis is **not** an evenly spaced channel index: * gaps between channel blocks occupy their real width so that bonded spans keep proportions. * + * This is the **display** axis of the chart. Channel health and recommendations use their own + * raster ([channelHealthChannels], [recommendationChannels]); e.g. 2.4 GHz channel 14 is always + * on this axis but scored only when an AP uses it. + * + * @property minMhz lower end of the displayed range (may include a margin, see [SPECTRUM_24_MIN_MHZ]). + * @property maxMhz upper end of the displayed range. * @property channels 20 MHz primary channels shown on the axis, ascending by frequency. * @property ticks one tick per channel; only [SpectrumTick.labelled] ones carry a printed label. * @property gaps regions between channel blocks; the UI may shade them. + * @property outOfBand displayed regions outside the permitted band (2.4 GHz above + * [WIFI_24_BAND_UPPER_EDGE_MHZ]); the UI shades them like [gaps]. */ data class SpectrumAxis( val band: WifiBand, @@ -49,6 +63,7 @@ data class SpectrumAxis( val channels: List, val ticks: List, val gaps: List, + val outOfBand: List = emptyList(), ) { val spanMhz: Double get() = maxMhz - minMhz @@ -72,7 +87,8 @@ data class SpectrumShape( /** * Drawable AP. [key] is [accessPointKey] (stable list/legend key), [peakDbm] is RSSI, - * [shapes] has one item, or two for 80+80 MHz. + * [shapes] has one item, or two for 80+80 MHz. [centerSource] tells how the first shape was + * placed ([occupiedLayout]); with [BondingCenterSource.UNKNOWN] it covers only the primary 20 MHz. */ data class SpectrumTrace( val key: String, @@ -80,7 +96,10 @@ data class SpectrumTrace( val primaryChannel: Int, val peakDbm: Int, val shapes: List, -) + val centerSource: BondingCenterSource = BondingCenterSource.PRIMARY, +) { + val centerUnknown: Boolean get() = centerSource == BondingCenterSource.UNKNOWN +} data class BandSpectrum(val axis: SpectrumAxis, val traces: List) @@ -88,56 +107,88 @@ data class BandSpectrum(val axis: SpectrumAxis, val traces: List) const val SPECTRUM_TRAPEZOID_SKIRT_FRACTION = 0.1 private const val CHANNEL_HALF_WIDTH_MHZ = 10.0 + +/** + * Display margin of the 2.4 GHz axis beyond the outer 20 MHz channel edges, so that the skirts + * of channel 1 and 14 traces do not lie on the chart edge (WiFiman-like, Daniel 2026-12-01). + */ +const val SPECTRUM_24_EDGE_MARGIN_MHZ = 5.0 +/** 2.4 GHz axis start: channel 1 lower edge (2402 MHz) minus the margin = 2397 MHz. */ +const val SPECTRUM_24_MIN_MHZ = 2412.0 - CHANNEL_HALF_WIDTH_MHZ - SPECTRUM_24_EDGE_MARGIN_MHZ +/** 2.4 GHz axis end: channel 14 upper edge (2494 MHz) plus the margin = 2499 MHz. */ +const val SPECTRUM_24_MAX_MHZ = 2484.0 + CHANNEL_HALF_WIDTH_MHZ + SPECTRUM_24_EDGE_MARGIN_MHZ +/** Upper edge of the 2.4 GHz ISM band (and of the EU allocation); above it the axis is shaded. */ +const val WIFI_24_BAND_UPPER_EDGE_MHZ = 2483.5 private val LABELLED_5GHZ = setOf(36, 52, 100, 116, 132, 149, 165) private val LABELLED_6GHZ = (1..233 step 32).toSet() // 1, 33, 65, 97, 129, 161, 193, 225 /** - * Axis for [band]: 2.4 GHz channels 1–13 (14 only when an AP on 2484 MHz is present), - * 5 GHz the global 20 MHz candidates 36–64, 100–144, 149–177 (see [recommendationChannels]), - * 6 GHz 1–233 step 4 (special channel 2 only when present). Range is the lower edge of the - * first channel to the upper edge of the last one. Returns null for [WifiBand.UNKNOWN]. - * The list of channels is a global raster, not a statement about regional permission. + * 20 MHz channels scored by channel health, ascending by frequency: 2.4 GHz 1–13 (14 only when + * an AP on 2484 MHz is present), 5 GHz the global 20 MHz candidates 36–64, 100–144, 149–177 + * (see [recommendationChannels]), 6 GHz 1–233 step 4 (special channel 2 only when present). + * Empty for [WifiBand.UNKNOWN]. A global raster, not a statement about regional permission. */ -fun spectrumAxis(band: WifiBand, points: List = emptyList()): SpectrumAxis? { +fun channelHealthChannels(band: WifiBand, points: List = emptyList()): List { val present = snapshotAccessPoints(points).filter { it.band == band }.mapNotNull { channelForFrequency(it.frequencyMhz) }.toSet() - val channels = when (band) { + return when (band) { WifiBand.GHZ_2_4 -> (1..13).toList() + listOfNotNull(14.takeIf { it in present }) WifiBand.GHZ_5 -> recommendationChannels(WifiBand.GHZ_5, 20) WifiBand.GHZ_6 -> listOfNotNull(2.takeIf { it in present }) + recommendationChannels(WifiBand.GHZ_6, 20) + WifiBand.UNKNOWN -> emptyList() + } +} + +/** + * Display axis for [band]. Returns null for [WifiBand.UNKNOWN]. + * + * - 2.4 GHz: ticks 1–14 always, all labelled; range [SPECTRUM_24_MIN_MHZ]..[SPECTRUM_24_MAX_MHZ] + * (outer channel edges ± [SPECTRUM_24_EDGE_MARGIN_MHZ]); above [WIFI_24_BAND_UPPER_EDGE_MHZ] is + * [SpectrumAxis.outOfBand] and channel 14 is an out-of-band tick. + * - 5 and 6 GHz: the [channelHealthChannels] raster, range from the lower edge of the first + * channel to the upper edge of the last one, no margin. + */ +fun spectrumAxis(band: WifiBand, points: List = emptyList()): SpectrumAxis? { + val channels = when (band) { + WifiBand.GHZ_2_4 -> (1..14).toList() + WifiBand.GHZ_5, WifiBand.GHZ_6 -> channelHealthChannels(band, points) WifiBand.UNKNOWN -> return null } val centers = channels.map { frequencyForChannel(it, band)!! } + val minMhz = if (band == WifiBand.GHZ_2_4) SPECTRUM_24_MIN_MHZ else centers.first() - CHANNEL_HALF_WIDTH_MHZ + val maxMhz = if (band == WifiBand.GHZ_2_4) SPECTRUM_24_MAX_MHZ else centers.last() + CHANNEL_HALF_WIDTH_MHZ + val outOfBand = if (band == WifiBand.GHZ_2_4) listOf(SpectrumGap(WIFI_24_BAND_UPPER_EDGE_MHZ, maxMhz)) else emptyList() val ticks = channels.zip(centers) { channel, center -> SpectrumTick(channel, center, when (band) { WifiBand.GHZ_5 -> channel in LABELLED_5GHZ WifiBand.GHZ_6 -> channel in LABELLED_6GHZ else -> true - }) + }, outOfBand = outOfBand.any { center > it.lowerMhz && center <= it.upperMhz }) } val gaps = centers.zipWithNext().mapNotNull { (previous, next) -> val lower = previous + CHANNEL_HALF_WIDTH_MHZ val upper = next - CHANNEL_HALF_WIDTH_MHZ if (upper > lower) SpectrumGap(lower, upper) else null } - return SpectrumAxis(band, centers.first() - CHANNEL_HALF_WIDTH_MHZ, centers.last() + CHANNEL_HALF_WIDTH_MHZ, - channels, ticks, gaps) + return SpectrumAxis(band, minMhz, maxMhz, channels, ticks, gaps, outOfBand) } /** * All plottable APs of [band] (valid frequency, see [snapshotAccessPoints]), strongest first, * ties broken by [accessPointKey]. Unlike [chartAccessPoints] there is no display cap here; * the UI may `take(WIFI_CHART_AP_LIMIT)` when it reuses the six-colour palette. - * Bonded widths use the AP's centre frequency fields; without them primary ±width/2. + * Bonded widths use the AP's centre frequency fields; without them the bonding raster, or only + * the primary 20 MHz when the raster is ambiguous ([occupiedLayout], [SpectrumTrace.centerSource]). */ fun spectrumTraces(points: List, band: WifiBand): List = snapshotAccessPoints(points) .filter { it.band == band } .sortedWith(compareByDescending { it.rssiDbm }.thenBy { accessPointKey(it) }) .map { ap -> + val layout = occupiedLayout(ap) SpectrumTrace(accessPointKey(ap), ap, channelForFrequency(ap.frequencyMhz)!!, ap.rssiDbm, - occupiedFrequencySegments(ap).map { segment -> + layout.segments.map { segment -> val skirt = (segment.upperMhz - segment.lowerMhz) * SPECTRUM_TRAPEZOID_SKIRT_FRACTION SpectrumShape(segment.lowerMhz, segment.upperMhz, segment.lowerMhz + skirt, segment.upperMhz - skirt) - }) + }, layout.centerSource) } /** Axis + traces of one band; null for [WifiBand.UNKNOWN]. Not gated by dataset age (like the chart). */ @@ -238,7 +289,7 @@ data class ChannelHealthEntry( sealed interface ChannelHealthReport { val band: WifiBand - /** Channels in axis order ([spectrumAxis]); [age] is FRESH or AGING (UI shows the AGING warning). */ + /** Channels in raster order ([channelHealthChannels]); [age] is FRESH or AGING (UI shows the AGING warning). */ data class Ready(override val band: WifiBand, val age: WifiDatasetAge, val channels: List) : ChannelHealthReport /** Dataset is UNKNOWN or EXPIRED by [wifiDatasetAge]; no health values are produced. */ @@ -259,24 +310,26 @@ fun scoreChannelHealth( isExcluded: (AccessPoint) -> Boolean = { it.isCurrent }, connectedChannel: Int? = null, ): List { - val axis = spectrumAxis(band, points) ?: return emptyList() + // The health raster, not the display axis: 2.4 GHz channel 14 only with an AP on it. + val channels = channelHealthChannels(band, points) val inBand = snapshotAccessPoints(points).filter { it.band == band } val neighbours = inBand.filterNot(isExcluded) - return axis.ticks.map { tick -> - val lower = tick.frequencyMhz - CHANNEL_HALF_WIDTH_MHZ - val upper = tick.frequencyMhz + CHANNEL_HALF_WIDTH_MHZ - val pressureMw = overlapScore(tick.channel, band, neighbours, 20) + return channels.map { channel -> + val centerMhz = frequencyForChannel(channel, band)!! + val lower = centerMhz - CHANNEL_HALF_WIDTH_MHZ + val upper = centerMhz + CHANNEL_HALF_WIDTH_MHZ + val pressureMw = overlapScore(channel, band, neighbours, 20) val pressureDbm = if (pressureMw > 0.0) round(10 * log10(pressureMw) * 100) / 100 else null val overlapping = neighbours.count { ap -> occupiedFrequencySegments(ap).any { minOf(upper, it.upperMhz) - maxOf(lower, it.lowerMhz) > 0.0 } } - val utilization = inBand.filter { channelForFrequency(it.frequencyMhz) == tick.channel } + val utilization = inBand.filter { channelForFrequency(it.frequencyMhz) == channel } .mapNotNull { it.channelUtilizationPercent?.coerceIn(0, 100) }.maxOrNull() val byPressure = pressureHealth(pressureDbm) val byUtilization = utilizationHealth(utilization) - ChannelHealthEntry(band, tick.channel, tick.frequencyMhz, combineChannelHealth(byPressure, byUtilization), + ChannelHealthEntry(band, channel, centerMhz, combineChannelHealth(byPressure, byUtilization), byPressure, byUtilization, pressureMw, pressureDbm, overlapping, utilization, - candidateMayRequireDfs(band, tick.channel, 20), connectedChannel == tick.channel) + candidateMayRequireDfs(band, channel, 20), connectedChannel == channel) } } diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/SpectrumPins.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/SpectrumPins.kt new file mode 100644 index 0000000..4351616 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/SpectrumPins.kt @@ -0,0 +1,86 @@ +package cz.netkit.shared.wifi + +/* + * Zadání 38 §2.1: APs pinned into the spectrum chart. + * + * A pin is a BSSID (never an SSID: one ESS has many radios). It survives a new scan because it + * is matched by BSSID, but it lives only in memory (the ViewModel), not across an app restart. + * The last observed SSID and band are kept so the legend can name a pinned AP that is missing + * from the newest scan. + */ + +/** Maximum number of pinned APs; with the connected AP that is 4 of [WIFI_CHART_AP_LIMIT] traces. */ +const val WIFI_PIN_LIMIT = 3 + +/** Pinned AP: normalized [bssid] ([normalizeBssid]) and its last observed [ssid] and [band]. */ +data class PinnedAccessPoint(val bssid: String, val ssid: String?, val band: WifiBand) + +enum class PinChange { PINNED, UNPINNED, LIMIT_REACHED, NO_BSSID } + +data class PinUpdate(val pins: List, val change: PinChange) + +/** + * Pins [point] or unpins it when already pinned. A fourth pin is refused ([PinChange.LIMIT_REACHED], + * pins unchanged) instead of silently dropping an older one; an anonymous observation without a + * BSSID cannot be pinned ([PinChange.NO_BSSID]). Order of [PinUpdate.pins] = order of pinning. + */ +fun togglePinnedAccessPoint(pins: List, point: AccessPoint): PinUpdate { + val bssid = normalizeBssid(point.bssid) ?: return PinUpdate(pins, PinChange.NO_BSSID) + if (pins.any { it.bssid == bssid }) return PinUpdate(pins.filterNot { it.bssid == bssid }, PinChange.UNPINNED) + if (pins.size >= WIFI_PIN_LIMIT) return PinUpdate(pins, PinChange.LIMIT_REACHED) + return PinUpdate(pins + PinnedAccessPoint(bssid, point.ssid, point.band), PinChange.PINNED) +} + +/** Removes the pin of [bssid] (any case); unknown BSSID → pins unchanged. */ +fun unpinAccessPoint(pins: List, bssid: String): List { + val normalized = normalizeBssid(bssid) ?: return pins + return pins.filterNot { it.bssid == normalized } +} + +fun isPinned(pins: List, point: AccessPoint): Boolean = + normalizeBssid(point.bssid)?.let { bssid -> pins.any { it.bssid == bssid } } == true + +/** After a new scan: pins seen again take the new SSID/band; pins missing from it stay unchanged. */ +fun refreshPinnedAccessPoints(pins: List, points: List): List { + if (pins.isEmpty()) return pins + val byBssid = points.mapNotNull { point -> normalizeBssid(point.bssid)?.let { it to point } }.toMap() + return pins.map { pin -> byBssid[pin.bssid]?.let { pin.copy(ssid = it.ssid, band = it.band) } ?: pin } +} + +/** + * What the spectrum card draws for one band. + * + * @property drawn traces in palette order: the connected AP, then the pinned ones (in pin order), + * then the strongest others, at most [WIFI_CHART_AP_LIMIT]. + * @property pinnedKeys [SpectrumTrace.key] of the drawn pinned traces (legend marks them). + * @property missingPins pins of this band (by their last observed band) whose BSSID is absent + * from the whole last scan; the legend says "not found in the last scan". + */ +data class SpectrumSelection( + val drawn: List, + val pinnedKeys: Set, + val missingPins: List, +) + +/** + * Picks the drawn traces of one band. [traces] are the band's traces strongest first + * ([spectrumTraces]); [allPoints] is the whole scan (all bands), used to tell a pin that moved to + * another band (present, simply not in this chart) from one that is gone. + */ +fun spectrumSelection( + traces: List, + pins: List = emptyList(), + band: WifiBand? = null, + allPoints: List = emptyList(), +): SpectrumSelection { + val connected = traces.firstOrNull { it.accessPoint.isCurrent } + val byBssid = traces.mapNotNull { trace -> normalizeBssid(trace.accessPoint.bssid)?.let { it to trace } }.toMap() + val pinned = pins.mapNotNull { byBssid[it.bssid] }.filterNot { it === connected } + val head = listOfNotNull(connected) + pinned + val drawn = (head + traces.filterNot { trace -> head.any { it === trace } }).take(WIFI_CHART_AP_LIMIT) + val present = allPoints.mapNotNull { normalizeBssid(it.bssid) }.toSet() + byBssid.keys + val missing = pins.filter { it.bssid !in present && (band == null || it.band == band) } + val pinnedKeys = drawn.filter { trace -> pins.any { it.bssid == normalizeBssid(trace.accessPoint.bssid) } } + .map { it.key }.toSet() + return SpectrumSelection(drawn, pinnedKeys, missing) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WalkLog.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WalkLog.kt new file mode 100644 index 0000000..cc3317d --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WalkLog.kt @@ -0,0 +1,317 @@ +package cz.netkit.shared.wifi + +import kotlinx.serialization.Serializable +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json + +/* + * Zadání 38 §2.4: "Záznam obchůzky" (walk / roaming log) of the Overview screen. + * + * While recording, the live telemetry's 1 Hz link reading becomes one [WalkSample] (RSSI, BSSID, + * channel, link rates and the latest gateway echo). Roaming (from [RoamingDetector]) and channel + * changes of the same AP become [WalkEvent]s, the user adds text marks of the place. Memory only, + * at most [WALK_MAX_SAMPLES] samples / [WALK_MAX_DURATION_MS]; the recording stops when the + * Overview stops sampling (app in background, other tab). Resolution is one second: the length + * of a hand-over cannot be determined from it. + */ + +const val WALK_MAX_SAMPLES = 7_200 +const val WALK_MAX_DURATION_MS = 2 * 60 * 60 * 1_000L +const val WALK_MARK_MAX_LENGTH = 40 +/** Two link readings closer than this are one sample (1 Hz with jitter). */ +const val WALK_MIN_SAMPLE_SPACING_MS = 500L + +enum class WalkStatus { IDLE, RECORDING, STOPPED } +enum class WalkStopReason { USER, SAMPLE_LIMIT, DURATION_LIMIT, PAUSED } +enum class WalkEventKind { ROAMING, CHANNEL_CHANGE, MARK } +enum class WalkMarkResult { ADDED, EMPTY, TOO_LONG, NOT_RECORDING } + +/** + * One 1 Hz reading; null = not available at that moment (no Wi-Fi, redacted, no echo yet). + * [gatewayMs] / [gatewayLost] summarize the gateway echoes that **completed** since the previous + * sample (by completion time): the newest reply time, and whether at least one echo was lost. + * An echo that times out after the sample of its second lands on the next sample. + */ +data class WalkSample( + val elapsedMs: Long, + val rssiDbm: Int?, + val bssid: String?, + val channel: Int?, + val rxLinkMbps: Int?, + val txLinkMbps: Int?, + val gatewayMs: Double?, + val gatewayLost: Boolean, +) + +/** [detail]: "from → to" BSSIDs for roaming, "6 → 11" for a channel change, the text of a mark. */ +data class WalkEvent(val elapsedMs: Long, val kind: WalkEventKind, val detail: String) + +data class WalkSummary( + val durationMs: Long, + val samples: Int, + val roamings: Int, + val channelChanges: Int, + val marks: Int, + val minRssiDbm: Int?, + val gatewaySent: Int, + val gatewayLost: Int, + val stopReason: WalkStopReason?, +) + +/** Immutable copy of a recording for the UI and the export. */ +data class WalkLog( + val status: WalkStatus, + val startedElapsedMs: Long?, + val startedEpochMs: Long?, + val stoppedElapsedMs: Long?, + val samples: List, + val events: List, + val summary: WalkSummary?, +) { + companion object { val EMPTY = WalkLog(WalkStatus.IDLE, null, null, null, emptyList(), emptyList(), null) } +} + +/** Not thread-safe: confine to one thread (the ViewModel's main dispatcher). */ +class WalkRecorder( + val maxSamples: Int = WALK_MAX_SAMPLES, + val maxDurationMs: Long = WALK_MAX_DURATION_MS, +) { + init { require(maxSamples > 0 && maxDurationMs > 0) } + + var status: WalkStatus = WalkStatus.IDLE + private set + var stopReason: WalkStopReason? = null + private set + private var startedElapsedMs: Long? = null + private var startedEpochMs: Long? = null + private var stoppedElapsedMs: Long? = null + private val samples = ArrayList() + private val events = ArrayList() + private var gatewaySent = 0 + private var gatewayLost = 0 + /** Completed echoes (completion time, reply ms or null = lost) not yet attached to a sample. */ + private val pendingGateway = ArrayList>() + private var lastBssid: String? = null + private var lastChannel: Int? = null + /** Bumped on every change; lets the UI layer skip rebuilding an unchanged [snapshot]. */ + var revision: Long = 0 + private set + + val sampleCount: Int get() = samples.size + + /** Starts a new recording, discarding any previous one. */ + fun start(elapsedMs: Long, epochMs: Long) { + clear() + status = WalkStatus.RECORDING + startedElapsedMs = elapsedMs + startedEpochMs = epochMs + revision++ + } + + /** + * Result of one gateway echo (only OK or lost, not "no Wi-Fi"), counted while recording. + * [completedElapsedMs] is when the result became known (a timeout ends ~1 s after the probe + * started); the result waits for the first sample at or after that time, however late. + */ + fun observeGateway(completedElapsedMs: Long, milliseconds: Double?, lost: Boolean) { + if (status != WalkStatus.RECORDING || !withinStart(completedElapsedMs)) return + gatewaySent++ + if (lost) gatewayLost++ + pendingGateway += completedElapsedMs to (if (lost) null else milliseconds) + revision++ + } + + /** Removes and summarizes the pending echoes completed at or before [elapsedMs]. */ + private fun takeGateway(elapsedMs: Long?): Pair { + val taken = pendingGateway.filter { elapsedMs == null || it.first <= elapsedMs } + if (taken.isEmpty()) return null to false + pendingGateway.removeAll(taken.toSet()) + val newestReply = taken.filter { it.second != null }.maxByOrNull { it.first }?.second + return newestReply to taken.any { it.second == null } + } + + /** + * One link reading. Returns `true` when it became a sample. Readings closer than + * [WALK_MIN_SAMPLE_SPACING_MS] to the previous sample are dropped; the duration and sample + * limits stop the recording ([WalkStopReason.DURATION_LIMIT], [WalkStopReason.SAMPLE_LIMIT]). + */ + fun sample(elapsedMs: Long, rssiDbm: Int?, bssid: String?, channel: Int?, rxLinkMbps: Int?, txLinkMbps: Int?, + roam: RoamingEvent? = null): Boolean { + if (status != WalkStatus.RECORDING) return false + val start = startedElapsedMs ?: return false + if (elapsedMs < start) return false + if (elapsedMs - start >= maxDurationMs) { stop(start + maxDurationMs, WalkStopReason.DURATION_LIMIT); return false } + samples.lastOrNull()?.let { if (elapsedMs - it.elapsedMs < WALK_MIN_SAMPLE_SPACING_MS) return false } + // Every completed echo lands on exactly one sample (the first one after its completion). + val (gatewayMs, gatewayLostHere) = takeGateway(elapsedMs) + val current = usableBssid(bssid) + samples += WalkSample(elapsedMs, rssiDbm, current, channel, rxLinkMbps, txLinkMbps, gatewayMs, gatewayLostHere) + if (roam != null) { + events += WalkEvent(elapsedMs, WalkEventKind.ROAMING, "${roam.fromBssid} → ${roam.toBssid}") + } else if (channel != null) { + val previous = lastChannel + val sameAp = current == null || lastBssid == null || current == lastBssid + if (previous != null && previous != channel && sameAp) + events += WalkEvent(elapsedMs, WalkEventKind.CHANNEL_CHANGE, "$previous → $channel") + } + if (channel != null) lastChannel = channel + if (current != null) lastBssid = current + revision++ + if (samples.size >= maxSamples) stop(elapsedMs, WalkStopReason.SAMPLE_LIMIT) + return true + } + + /** Adds a mark of the place (trimmed, control characters → space, 1..[WALK_MARK_MAX_LENGTH] characters). */ + fun mark(elapsedMs: Long, text: String): WalkMarkResult { + if (status != WalkStatus.RECORDING || !withinStart(elapsedMs)) return WalkMarkResult.NOT_RECORDING + val clean = sanitizeWalkMark(text) + if (clean.isEmpty()) return WalkMarkResult.EMPTY + if (clean.length > WALK_MARK_MAX_LENGTH) return WalkMarkResult.TOO_LONG + events += WalkEvent(elapsedMs, WalkEventKind.MARK, clean) + revision++ + return WalkMarkResult.ADDED + } + + /** Ends the recording; data stays until [start] or [clear]. No effect unless recording. */ + fun stop(elapsedMs: Long, reason: WalkStopReason) { + if (status != WalkStatus.RECORDING) return + status = WalkStatus.STOPPED + stopReason = reason + // Echoes completed after the last sample still belong to the recording: attach them to it, + // so a final loss counted in the summary is also visible in the samples. + samples.lastOrNull()?.let { last -> + val (gatewayMs, lost) = takeGateway(null) + samples[samples.lastIndex] = last.copy(gatewayMs = gatewayMs ?: last.gatewayMs, gatewayLost = last.gatewayLost || lost) + } + pendingGateway.clear() + stoppedElapsedMs = maxOf(elapsedMs, startedElapsedMs ?: elapsedMs) + revision++ + } + + fun clear() { + status = WalkStatus.IDLE + stopReason = null + startedElapsedMs = null + startedEpochMs = null + stoppedElapsedMs = null + samples.clear() + events.clear() + gatewaySent = 0 + gatewayLost = 0 + pendingGateway.clear() + lastBssid = null + lastChannel = null + revision++ + } + + /** Summary up to [nowElapsedMs] while recording, or up to the stop. Null when idle. */ + fun summary(nowElapsedMs: Long): WalkSummary? { + val start = startedElapsedMs ?: return null + val end = stoppedElapsedMs ?: nowElapsedMs + return WalkSummary( + durationMs = (end - start).coerceIn(0, maxDurationMs), + samples = samples.size, + roamings = events.count { it.kind == WalkEventKind.ROAMING }, + channelChanges = events.count { it.kind == WalkEventKind.CHANNEL_CHANGE }, + marks = events.count { it.kind == WalkEventKind.MARK }, + minRssiDbm = samples.mapNotNull { it.rssiDbm }.minOrNull(), + gatewaySent = gatewaySent, + gatewayLost = gatewayLost, + stopReason = stopReason, + ) + } + + fun snapshot(nowElapsedMs: Long): WalkLog = WalkLog(status, startedElapsedMs, startedEpochMs, stoppedElapsedMs, + samples.toList(), events.toList(), summary(nowElapsedMs)) + + private fun withinStart(elapsedMs: Long): Boolean = startedElapsedMs?.let { elapsedMs >= it } == true +} + +fun sanitizeWalkMark(text: String): String = + text.map { if (it.isISOControl() || it == '
' || it == '
') ' ' else it }.joinToString("").trim() + +// --- Export ---------------------------------------------------------------------------------- + +const val WALK_EXPORT_FORMAT = "netkit-wifi-walk" + +@Serializable +data class WalkExportSample( + val time: String, val offsetS: Double, val rssiDbm: Int?, val bssid: String?, val channel: Int?, + val rxLinkMbps: Int?, val txLinkMbps: Int?, val gatewayMs: Double?, val gatewayLost: Boolean, +) + +@Serializable +data class WalkExportEvent(val time: String, val offsetS: Double, val kind: String, val detail: String) + +@Serializable +data class WalkExportSummary( + val durationS: Double, val samples: Int, val roamings: Int, val channelChanges: Int, val marks: Int, + val minRssiDbm: Int?, val gatewaySent: Int, val gatewayLost: Int, val stopReason: String?, +) + +@Serializable +data class WalkExportDocument( + val format: String = WALK_EXPORT_FORMAT, + val version: Int = WIFI_EXPORT_VERSION, + val startedAt: String, + /** The resolution of every time below. */ + val sampleIntervalS: Int = 1, + val summary: WalkExportSummary, + val samples: List, + val events: List, +) + +private val walkJson = Json { prettyPrint = true; encodeDefaults = true } + +private const val WALK_CSV_HEADER = "type,time,offset_s,rssi_dbm,bssid,channel,rx_link_mbps,tx_link_mbps,gateway_ms,gateway_lost,detail" + +/** Export text of a finished recording; null while idle or still recording (the UI exports only after stop). */ +fun walkExportText(log: WalkLog, format: WifiExportFormat): String? = + if (log.status == WalkStatus.STOPPED) exportWalkLog(log, format) else null + +/** + * Serializes a recording. CSV is one table ordered by time: `sample` rows and `roaming`, + * `channel_change` and `mark` rows (text in `detail`); the summary is only in JSON. + * Null when the log was never started. + */ +fun exportWalkLog(log: WalkLog, format: WifiExportFormat): String? { + val start = log.startedElapsedMs ?: return null + val startEpoch = log.startedEpochMs ?: return null + val summary = log.summary ?: return null + fun time(elapsed: Long) = isoUtc(startEpoch + (elapsed - start)) + fun offset(elapsed: Long) = (elapsed - start) / 1000.0 + fun kind(kind: WalkEventKind) = when (kind) { + WalkEventKind.ROAMING -> "roaming" + WalkEventKind.CHANNEL_CHANGE -> "channel_change" + WalkEventKind.MARK -> "mark" + } + fun gateway(ms: Double?) = ms?.let { kotlin.math.round(it * 1000.0) / 1000.0 } + return when (format) { + WifiExportFormat.JSON -> walkJson.encodeToString(WalkExportDocument( + startedAt = isoUtc(startEpoch), + summary = WalkExportSummary(summary.durationMs / 1000.0, summary.samples, summary.roamings, summary.channelChanges, + summary.marks, summary.minRssiDbm, summary.gatewaySent, summary.gatewayLost, summary.stopReason?.name), + samples = log.samples.map { + WalkExportSample(time(it.elapsedMs), offset(it.elapsedMs), it.rssiDbm, it.bssid, it.channel, it.rxLinkMbps, + it.txLinkMbps, gateway(it.gatewayMs), it.gatewayLost) + }, + events = log.events.map { WalkExportEvent(time(it.elapsedMs), offset(it.elapsedMs), kind(it.kind), it.detail) }, + )) + "\n" + WifiExportFormat.CSV -> buildString { + append(WALK_CSV_HEADER).append('\n') + // Stable merge: a sample comes before the events of the same instant. + val rows = log.samples.map { + WalkCsvRow(it.elapsedMs, 0, listOf("sample", csvText(time(it.elapsedMs)), offset(it.elapsedMs).toString(), + csvNumber(it.rssiDbm), csvText(it.bssid), csvNumber(it.channel), csvNumber(it.rxLinkMbps), + csvNumber(it.txLinkMbps), csvNumber(gateway(it.gatewayMs)), it.gatewayLost.toString(), "")) + } + log.events.map { + WalkCsvRow(it.elapsedMs, 1, listOf(kind(it.kind), csvText(time(it.elapsedMs)), offset(it.elapsedMs).toString(), + "", "", "", "", "", "", "", csvText(it.detail))) + } + rows.sortedWith(compareBy { it.elapsedMs }.thenBy { it.order }) + .forEach { append(it.cells.joinToString(",")).append('\n') } + } + } +} + +private class WalkCsvRow(val elapsedMs: Long, val order: Int, val cells: List) diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiDomain.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiDomain.kt index 913bc76..ef06682 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiDomain.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiDomain.kt @@ -122,13 +122,88 @@ fun classifySecurity(capabilities: String): WifiSecurity { } } -/** Frequency occupancy is modelled as a symmetric channel-width interval. */ -fun occupiedFrequencySegments(ap: AccessPoint): List { - val centers = listOfNotNull(ap.centerFrequencyMhz ?: ap.frequencyMhz, ap.secondaryCenterFrequencyMhz) +/** Where the centre of the (first) occupied segment of an AP comes from. */ +enum class BondingCenterSource { + /** 20 MHz or unknown width: the primary channel itself. */ + PRIMARY, + /** Bonded width with a centre reported by the AP (`ScanResult.centerFreq0`). */ + REPORTED, + /** Bonded width without a reported centre, derived from the fixed bonding raster. */ + RASTER, + /** + * Bonded width without a reported centre and the raster is ambiguous (2.4 GHz primary 5–9, + * 6 GHz 320 MHz) or the primary lies outside it: only the primary 20 MHz is modelled. + */ + UNKNOWN, +} + +/** Occupied spectrum of one AP: segments (two for 80+80) and the source of the first centre. */ +data class OccupiedLayout(val segments: List, val centerSource: BondingCenterSource) { + /** Bonded width reported but its position is unknown; [segments] then cover only the primary 20 MHz. */ + val centerUnknown: Boolean get() = centerSource == BondingCenterSource.UNKNOWN +} + +/** + * Frequency occupancy, each segment a symmetric interval around its centre. + * + * Centre: the AP's `centerFrequencyMhz` always wins. Without it a bonded width (> 20 MHz) is + * placed by [bondingRasterCenterMhz]; when that is ambiguous the segment is only the primary + * 20 MHz and [OccupiedLayout.centerSource] is [BondingCenterSource.UNKNOWN] (never a guess on + * the wrong side of the primary channel). The 80+80 secondary centre is used as reported. + */ +fun occupiedLayout(ap: AccessPoint): OccupiedLayout { val segmentWidth = if (ap.is80Plus80) { (ap.widthMhz ?: 160).coerceAtLeast(40) / 2.0 } else (ap.widthMhz ?: 20).coerceAtLeast(20).toDouble() - return centers.map { center -> OccupiedFrequencySegment(center - segmentWidth / 2, center + segmentWidth / 2) } + val reported = ap.centerFrequencyMhz + val raster = if (reported == null && segmentWidth > 20.0) + bondingRasterCenterMhz(ap.frequencyMhz, ap.band, segmentWidth.toInt()) else null + val (center, width, source) = when { + reported != null -> Triple(reported.toDouble(), segmentWidth, + if (segmentWidth > 20.0) BondingCenterSource.REPORTED else BondingCenterSource.PRIMARY) + segmentWidth <= 20.0 -> Triple(ap.frequencyMhz.toDouble(), segmentWidth, BondingCenterSource.PRIMARY) + raster != null -> Triple(raster, segmentWidth, BondingCenterSource.RASTER) + else -> Triple(ap.frequencyMhz.toDouble(), 20.0, BondingCenterSource.UNKNOWN) + } + val segments = listOf(OccupiedFrequencySegment(center - width / 2, center + width / 2)) + + listOfNotNull(ap.secondaryCenterFrequencyMhz).map { OccupiedFrequencySegment(it - segmentWidth / 2, it + segmentWidth / 2) } + return OccupiedLayout(segments, source) +} + +fun occupiedFrequencySegments(ap: AccessPoint): List = occupiedLayout(ap).segments + +/** Shortcut for UI notes: bonded width reported without a centre that the raster can place. */ +fun bondingCenterUnknown(ap: AccessPoint): Boolean = occupiedLayout(ap).centerUnknown + +/** + * Centre frequency of a [widthMhz] bonded channel whose primary 20 MHz channel is at + * [primaryFrequencyMhz], when the global raster places it unambiguously; null otherwise. + * + * - 2.4 GHz 40 MHz: primary 1–4 → HT40+ (+10 MHz), 10–13 → HT40− (−10 MHz); 5–9 may be either, + * 14 cannot bond → null. Other widths → null. + * - 5 and 6 GHz: the fixed blocks of [recommendationChannels] (5 GHz 40: 36–40, 44–48, …; + * 80: 36–48, 52–64, 100–112, 116–128, 132–144, 149–161, 165–177; 160: 36–64, 100–128, 149–177; + * 6 GHz 40/80/160 blocks from channel 1). A primary outside every complete block, 6 GHz special + * channel 2 and 320 MHz (two overlapping rasters) → null. + */ +fun bondingRasterCenterMhz(primaryFrequencyMhz: Int, band: WifiBand, widthMhz: Int): Double? { + val primary = channelForFrequency(primaryFrequencyMhz) ?: return null + val primaryCenter = frequencyForChannel(primary, band)?.takeIf { it == primaryFrequencyMhz.toDouble() } ?: return null + return when (band) { + WifiBand.GHZ_2_4 -> if (widthMhz != 40) null else when (primary) { + in 1..4 -> primaryCenter + 10 + in 10..13 -> primaryCenter - 10 + else -> null + } + WifiBand.GHZ_5, WifiBand.GHZ_6 -> { + if (widthMhz !in listOf(40, 80, 160) || (band == WifiBand.GHZ_6 && primary == 2)) return null + val halfSpan = 2 * (widthMhz / 20 - 1) // channel numbers from the block centre to its outer primaries + recommendationChannels(band, widthMhz).firstOrNull { centre -> + primary in (centre - halfSpan)..(centre + halfSpan) && (primary - (centre - halfSpan)) % 4 == 0 + }?.let { frequencyForChannel(it, band) } + } + WifiBand.UNKNOWN -> null + } } fun overlapScore(candidateChannel: Int, band: WifiBand, networks: List, widthMhz: Int = 20): Double { @@ -206,7 +281,10 @@ fun signalSampleForDataset(state: WifiAnalyzerState, bssid: String?, nowElapsedM return SignalSample(timestamp, point.rssiDbm) } -/** Global candidate centers; device/country permission and DFS availability are not inferred. */ +/** + * Global candidate centers; device/country permission and DFS availability are not inferred. + * The bonded 5/6 GHz lists double as the fixed bonding raster of [bondingRasterCenterMhz]. + */ fun recommendationChannels(band: WifiBand, widthMhz: Int): List = when (band) { WifiBand.GHZ_2_4 -> if (widthMhz == 20) listOf(1, 6, 11) else emptyList() WifiBand.GHZ_5 -> when (widthMhz) { diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiScanExport.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiScanExport.kt new file mode 100644 index 0000000..3f06e77 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiScanExport.kt @@ -0,0 +1,172 @@ +package cz.netkit.shared.wifi + +import kotlinx.serialization.Serializable +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.Json + +/* + * Zadání 38 §2.3: export of one Wi-Fi scan as CSV or JSON. The file is written only to a + * document the user picks (SAF); it contains identifiers of networks around the user (SSID, + * BSSID), the UI warns before saving. Nothing is sent anywhere. + */ + +enum class WifiExportFormat(val extension: String, val mimeType: String) { + CSV("csv", "text/csv"), + JSON("json", "application/json"), +} + +/** Format id and version of the JSON documents (scan and walk log). */ +const val WIFI_SCAN_EXPORT_FORMAT = "netkit-wifi-scan" +const val WIFI_EXPORT_VERSION = 1 + +/** One exported AP. Units in the names; null = the value is unknown (empty CSV cell). */ +@Serializable +data class WifiScanExportRow( + /** ISO 8601 UTC time of the AP's own observation (scan timestamp), else of the scan. */ + val time: String, + val ssid: String?, + val bssid: String, + val vendor: String?, + /** "2.4", "5", "6" or null for an unknown band. */ + val band: String?, + val channel: Int?, + val widthMhz: Int?, + /** Centre frequency as reported by the AP (`centerFreq0`); null when not reported. */ + val centerMhz: Int?, + /** Second centre of an 80+80 MHz AP. */ + val center2Mhz: Int?, + val frequencyMhz: Int, + val rssiDbm: Int, + /** [WifiSecurity] name. */ + val security: String, + /** 802.11 amendment letters ("ax", "ac", …). */ + val standard: String?, + val bssLoadStations: Int?, + val bssLoadUtilizationPercent: Int?, + val connected: Boolean, +) + +@Serializable +data class WifiScanExportDocument( + val format: String = WIFI_SCAN_EXPORT_FORMAT, + val version: Int = WIFI_EXPORT_VERSION, + val exportedAt: String, + /** Receipt of the confirmed scan (ISO 8601 UTC); null when the dataset was never confirmed. */ + val scanReceivedAt: String?, + val accessPoints: List, +) + +/** + * Wall-clock time of an `elapsedRealtime` instant, given one simultaneous reading of both clocks + * ([nowEpochMs], [nowElapsedMs]). Null for an invalid or future elapsed time. + */ +fun elapsedToEpochMs(elapsedMs: Long?, nowEpochMs: Long, nowElapsedMs: Long): Long? = + elapsedMs?.takeIf { it in 0..nowElapsedMs }?.let { nowEpochMs - (nowElapsedMs - it) } + +fun wifiBandLabel(band: WifiBand): String? = when (band) { + WifiBand.GHZ_2_4 -> "2.4" + WifiBand.GHZ_5 -> "5" + WifiBand.GHZ_6 -> "6" + WifiBand.UNKNOWN -> null +} + +/** Rows of [points] in a stable order (band, channel, BSSID). */ +fun wifiScanExportRows(points: List, nowEpochMs: Long, nowElapsedMs: Long, + scanReceivedElapsedMs: Long?): List { + val scanTime = elapsedToEpochMs(scanReceivedElapsedMs, nowEpochMs, nowElapsedMs) ?: nowEpochMs + return points.sortedWith(compareBy { it.band.ordinal }.thenBy { it.channel ?: Int.MAX_VALUE } + .thenBy { accessPointKey(it) }).map { ap -> + WifiScanExportRow( + time = isoUtc(elapsedToEpochMs(ap.seenAtElapsedMs, nowEpochMs, nowElapsedMs) ?: scanTime), + ssid = ap.ssid, + bssid = normalizeBssid(ap.bssid).orEmpty(), + vendor = ap.vendor, + band = wifiBandLabel(ap.band), + channel = ap.channel, + widthMhz = ap.widthMhz, + centerMhz = ap.centerFrequencyMhz, + center2Mhz = ap.secondaryCenterFrequencyMhz, + frequencyMhz = ap.frequencyMhz, + rssiDbm = ap.rssiDbm, + security = ap.security.name, + standard = ap.standard, + bssLoadStations = ap.stationCount, + bssLoadUtilizationPercent = ap.channelUtilizationPercent, + connected = ap.isCurrent, + ) + } +} + +private val exportJson = Json { prettyPrint = true; encodeDefaults = true } + +private const val SCAN_CSV_HEADER = "time,ssid,bssid,vendor,band,channel,width_mhz,center_mhz,center2_mhz,frequency_mhz," + + "rssi_dbm,security,standard,bss_load_stations,bss_load_utilization_percent,connected" + +/** + * Serializes one scan. CSV: RFC 4180 (CRLF-free `\n` line ends, every text cell quoted, quotes + * doubled, commas and line breaks kept inside the quotes), spreadsheet formulas neutralized + * ([csvText]); numbers are plain. JSON: [WifiScanExportDocument]. + */ +fun exportWifiScan(points: List, format: WifiExportFormat, nowEpochMs: Long, nowElapsedMs: Long, + scanReceivedElapsedMs: Long?): String { + val rows = wifiScanExportRows(points, nowEpochMs, nowElapsedMs, scanReceivedElapsedMs) + return when (format) { + WifiExportFormat.JSON -> exportJson.encodeToString(WifiScanExportDocument( + exportedAt = isoUtc(nowEpochMs), + scanReceivedAt = elapsedToEpochMs(scanReceivedElapsedMs, nowEpochMs, nowElapsedMs)?.let(::isoUtc), + accessPoints = rows, + )) + "\n" + WifiExportFormat.CSV -> buildString { + append(SCAN_CSV_HEADER).append('\n') + rows.forEach { row -> + append(listOf(csvText(row.time), csvText(row.ssid), csvText(row.bssid), csvText(row.vendor), csvText(row.band), + csvNumber(row.channel), csvNumber(row.widthMhz), csvNumber(row.centerMhz), csvNumber(row.center2Mhz), + csvNumber(row.frequencyMhz), csvNumber(row.rssiDbm), csvText(row.security), csvText(row.standard), + csvNumber(row.bssLoadStations), csvNumber(row.bssLoadUtilizationPercent), row.connected.toString()) + .joinToString(",")) + append('\n') + } + } + } +} + +/** Export text of the dataset in [state] at the moment of the call; null when there is no AP to export. */ +fun scanExportText(state: WifiAnalyzerState, format: WifiExportFormat, nowEpochMs: Long, nowElapsedMs: Long): String? = + state.accessPoints.takeIf { it.isNotEmpty() } + ?.let { exportWifiScan(it, format, nowEpochMs, nowElapsedMs, state.lastUpdatedElapsedMs) } + +/** Characters that make a spreadsheet treat a cell as a formula (OWASP CSV injection). */ +private val FORMULA_START = setOf('=', '+', '-', '@', '\t', '\r') + +/** + * One quoted CSV text cell; null → empty unquoted cell. SSIDs and vendor names are untrusted: + * a leading formula character gets a `'` prefix so a spreadsheet shows it as text. + */ +internal fun csvText(value: String?): String { + if (value == null) return "" + val safe = if (value.firstOrNull() in FORMULA_START) "'$value" else value + return "\"" + safe.replace("\"", "\"\"") + "\"" +} + +internal fun csvNumber(value: Number?): String = value?.toString().orEmpty() + +/** `2026-12-01T09:05:03.042Z` for epoch milliseconds (proleptic Gregorian, UTC). */ +fun isoUtc(epochMs: Long): String { + val days = floorDiv(epochMs, 86_400_000L) + val msOfDay = epochMs - days * 86_400_000L + // Howard Hinnant, civil_from_days. + val z = days + 719_468 + val era = floorDiv(z, 146_097) + val doe = z - era * 146_097 + val yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365 + val doy = doe - (365 * yoe + yoe / 4 - yoe / 100) + val mp = (5 * doy + 2) / 153 + val day = doy - (153 * mp + 2) / 5 + 1 + val month = if (mp < 10) mp + 3 else mp - 9 + val year = yoe + era * 400 + if (month <= 2) 1 else 0 + fun pad(value: Long, width: Int) = value.toString().padStart(width, '0') + return "${pad(year, 4)}-${pad(month, 2)}-${pad(day, 2)}T${pad(msOfDay / 3_600_000, 2)}:" + + "${pad(msOfDay / 60_000 % 60, 2)}:${pad(msOfDay / 1_000 % 60, 2)}.${pad(msOfDay % 1_000, 3)}Z" +} + +private fun floorDiv(a: Long, b: Long): Long = a.floorDiv(b) diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolController.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolController.kt index a26df65..7534e4a 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolController.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolController.kt @@ -2,7 +2,6 @@ package cz.netkit.shared.wol import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.delay import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -12,6 +11,13 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withTimeoutOrNull +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeout + +/** Upper bound of one storage step (vault write + list save, or rollback) that runs NonCancellable. */ +const val STORAGE_STEP_TIMEOUT_MS = 10_000L class WolController( private val store: WolDeviceStore, @@ -24,6 +30,8 @@ class WolController( private val prober: WakeProber? = null, private val monotonicMillis: () -> Long = wakeMonotonicClock(), private val nameComparator: Comparator = naturalOrder(), + /** Encrypted SecureOn passwords (zadání 39); null = feature unavailable on this platform. */ + private val secureOn: WolSecureOnStore? = null, ) { private val mutableState = MutableStateFlow(WolUiState()) val state: StateFlow = mutableState.asStateFlow() @@ -45,7 +53,8 @@ class WolController( try { val devices = store.load() require(validateStoredDevices(devices)) - mutableState.update { it.copy(devices = devices, loading = false, loadFailed = false, loadFailure = null, recoveryConfirmationPending = false, archivePath = store.recoveryArchivePath ?: it.archivePath) } + val (secureOnIds, secureOnFailed) = loadSecureOnIds(devices) + mutableState.update { it.copy(devices = devices, secureOnIds = secureOnIds, secureOnFailed = secureOnFailed, loading = false, loadFailed = false, loadFailure = null, recoveryConfirmationPending = false, archivePath = store.recoveryArchivePath ?: it.archivePath) } } catch (e: CancellationException) { throw e } catch (error: Exception) { mutableState.update { it.copy(loading = false, loadFailed = true, loadFailure = (error as? StoreReadException)?.kind ?: StoreFailure.IO, archivePath = (error as? StoreReadException)?.archivePath ?: it.archivePath, message = WolMessage.LOAD_FAILED) } @@ -78,11 +87,24 @@ class WolController( } private fun original(draft: WolDeviceDraft) = state.value.devices.find { it.id == draft.id } private fun canEdit() = !state.value.loading && !state.value.loadFailed && !state.value.saving && !state.value.recovering && state.value.sendingDeviceId == null - fun add() { if (canEdit()) mutableState.update { it.copy(draft = WolDeviceDraft(), errors = emptySet()) } } + /** + * SecureOn binding of the edited device when its editor was opened, and whether its stored + * password matched that configuration then (revize 39/3). Only such a password may follow the + * owner's edit to a new MAC/target/port; anything else (e.g. left over from an import) is never re-bound. + */ + private var editOrigin: Pair? = null + + /** [prefill] comes from the LAN device detail (zadání 36 §2.7); it never targets an existing device. */ + fun add(prefill: WolDeviceDraft = WolDeviceDraft()) { + if (canEdit()) { editOrigin = null; mutableState.update { it.copy(draft = prefill.copy(id = null, secureOn = "", secureOnStored = false, + secureOnRemove = false, secureOnStale = false), errors = emptySet()) } } + } fun edit(id: String) { if (!canEdit()) return val device = state.value.devices.find { it.id == id } ?: return - mutableState.update { it.copy(draft = device.toDraft(), errors = emptySet()) } + editOrigin = id to secureOnBinding(device) + mutableState.update { it.copy(draft = device.toDraft().copy(secureOnStored = id in it.secureOnIds, + secureOnStale = id !in it.secureOnIds && (id in vaultIds || device.secureOnRequired)), errors = emptySet()) } } fun updateDraft(draft: WolDeviceDraft) { if (canEdit() && state.value.draft != null && draft.id == state.value.draft?.id) @@ -90,7 +112,6 @@ class WolController( } fun cancelEdit() { if (!state.value.saving) mutableState.update { it.copy(draft = null, errors = emptySet()) } } fun cancelDraft() = cancelEdit() - fun clearMessage() { mutableState.update { it.copy(message = null) } } fun save() { if (!canEdit()) return @@ -98,22 +119,35 @@ class WolController( val errors = validateDevice(draft, original(draft)).errors mutableState.update { it.copy(errors = errors) } if (errors.isNotEmpty()) return - mutate { + var savedId: String? = null + var previousVault: Map? = null + val origin = editOrigin?.takeIf { it.first == draft.id }?.second + mutate(beforeSave = { updated -> previousVault = writeDraftSecureOn(draft, origin, updated.first { it.id == savedId }, updated) }, + afterSave = { updated -> removeDraftSecureOn(draft, updated.first { it.id == savedId }, updated) }, + onSaveFailed = { previousVault?.let { restoreSecureOn(it) } }) { val old = draft.id?.let { id -> state.value.devices.find { it.id == id } } require(draft.id == null || old != null) val time = nowMillis() val id = old?.id ?: newId().also { value -> require(value.isNotBlank() && state.value.devices.none { it.id == value }) } + savedId = id val device = WolDevice(id, draft.name.trim(), parseMac(draft.mac)!!.toString(), draft.targetMode, draft.customTarget.trim().ifEmpty { null }, draft.port.toInt(), draft.probeHost.trim().ifEmpty { null }, draft.probePort.ifEmpty { null }?.toInt(), draft.note.trim().ifEmpty { null }, old?.createdAt ?: time, time, - draft.repeatCount.toInt(), draft.repeatIntervalMs.toInt(), draft.probeEnabled, draft.probeDelaySeconds.toInt()) + draft.repeatCount.toInt(), draft.repeatIntervalMs.toInt(), draft.probeEnabled, draft.probeDelaySeconds.toInt(), + // Persistent "password required" (revize 39/4): set by a typed password, kept until the owner removes it. + secureOnRequired = when { + draft.secureOnRemove -> false + draft.secureOn.isNotEmpty() -> true + else -> old?.secureOnRequired == true || draft.secureOnStored + }) if (old == null) state.value.devices + device else state.value.devices.map { if (it.id == id) device else it } } } fun delete(id: String) { if (!canEdit() || state.value.devices.none { it.id == id }) return - mutate { state.value.devices.filterNot { it.id == id } } + // Removed only after the device list is saved: a failed save keeps both (an orphan password is harmless). + mutate(afterSave = { updated -> pruneSecureOn(updated) }) { state.value.devices.filterNot { it.id == id } } } fun sortByName() { if (canEdit()) mutate { state.value.devices.sortedWith { first, second -> nameComparator.compare(first.name, second.name).takeIf { it != 0 } ?: first.id.compareTo(second.id) } } } @@ -132,13 +166,144 @@ class WolController( return true } fun cancelImport() { mutableState.update { it.copy(pendingImport = null, skippedCount = 0, secureOnDropped = 0) } } + /** The configuration restore stages exactly this merge and the same vault invalidations. */ + data class ImportPlan(val devices: List, val forgetSecureOn: Set) + companion object { + fun prepareImport(current: List, incoming: List) = + ImportPlan(mergeWolDevices(current, incoming), incoming.map { it.id }.toSet()) + } + fun confirmImport() { if (!canEdit()) return val incoming = state.value.pendingImport ?: return - mutate { mergeWolDevices(state.value.devices, incoming) } + // The list is saved first; the vault is changed only afterwards (an orphan is safer than a lost password). + // If that change fails, the old entry no longer matches the imported MAC/target and sending is blocked. + lateinit var plan: ImportPlan + mutate(afterSave = { updated -> dropSecureOn(plan.forgetSecureOn, updated) }) { + plan = prepareImport(state.value.devices, incoming) + plan.devices + } + } + + /** IDs with any entry in the vault, as last read or written (also entries bound to another configuration). */ + private var vaultIds: Set = emptySet() + + /** IDs whose stored password is bound to the device as it is now; (empty, true) when the store cannot be read. */ + private suspend fun loadSecureOnIds(devices: List): Pair, Boolean> { + val store = secureOn ?: return emptySet() to false + return try { store.load().let { vault -> vaultIds = vault.keys; matchingSecureOnIds(vault, devices) } to false } + catch (e: CancellationException) { throw e } + catch (_: Exception) { emptySet() to true } + } + + private fun matchingSecureOnIds(vault: Map, devices: List): Set = + devices.filter { secureOnPasswordFor(it, vault) != null }.map { it.id }.toSet() + + private fun publishSecureOn(vault: Map, devices: List) { + vaultIds = vault.keys + mutableState.update { it.copy(secureOnIds = matchingSecureOnIds(vault, devices), secureOnFailed = false) } + } + + /** + * Before the device list is saved (revize 39/2): a newly typed password, or a kept password + * re-bound to the owner's own edit of MAC/target/port, is written bound to the device being + * saved. Returns the previous vault for a rollback when the list save then fails (null when + * nothing was written). An unreadable store is replaced by a typed password only when no other + * device requires a password (revize 39/4): otherwise their passwords would be silently lost, so + * the save fails instead. A failed write stops the save, so the editor stays open and the old + * configuration keeps its old binding. + */ + private suspend fun writeDraftSecureOn(draft: WolDeviceDraft, originBinding: String?, device: WolDevice, updated: List): Map? { + val store = secureOn ?: return null + val typed = draft.secureOn.takeIf { it.isNotEmpty() }?.let { requireNotNull(parseSecureOn(it)) } + val binding = secureOnBinding(device) + val ids = updated.map { it.id }.toSet() + if (typed != null) { + val current = try { store.load() } catch (e: CancellationException) { throw e } catch (error: Exception) { + if (updated.any { it.id != device.id && it.secureOnRequired }) throw error + null + } + val next = current.orEmpty().filterKeys { it in ids && it != device.id } + (device.id to SecureOnEntry(typed, binding)) + store.save(next) + publishSecureOn(next, updated) + return current + } + if (draft.secureOnRemove || !draft.secureOnStored) return null + val current = store.load() + val entry = current[device.id] ?: return null + if (entry.binding == binding) return null + // Re-bind only the password that belonged to the configuration the owner opened (revize 39/3). + if (originBinding == null || entry.binding != originBinding) return null + val next = current + (device.id to SecureOnEntry(entry.password, binding)) + store.save(next) + publishSecureOn(next, updated) + return current + } + + /** Rollback after a failed list save; if it fails too, the mismatching binding blocks sending (fail-closed). */ + private suspend fun restoreSecureOn(previous: Map) { + val store = secureOn ?: return + try { store.save(previous); publishSecureOn(previous, state.value.devices) } + catch (e: CancellationException) { throw e } + catch (_: Exception) { /* Fail-closed: see secureOnFor. */ } } - private fun mutate(transform: () -> List) { + /** + * After a successful save without a new password: "remove" deletes the entry, and so does + * saving a device whose entry is bound to another configuration (the form showed no stored + * password, so the owner explicitly saved it without one). + */ + private suspend fun removeDraftSecureOn(draft: WolDeviceDraft, device: WolDevice, updated: List) { + val store = secureOn ?: return + if (draft.secureOn.isNotEmpty()) return + // A device that still requires a password keeps its (stale) entry: it stays blocked until re-entered or removed. + if (!draft.secureOnRemove && (draft.secureOnStored || device.secureOnRequired || device.id !in vaultIds)) return + val current = store.load() + val entry = current[device.id] ?: return + if (!draft.secureOnRemove && entry.binding == secureOnBinding(device)) return + val next = current - device.id + store.save(next) + publishSecureOn(next, updated) + } + + private suspend fun pruneSecureOn(updated: List) { + val store = secureOn ?: return + val ids = updated.map { it.id }.toSet() + val current = store.load() + val next = current.filterKeys { it in ids } + if (next.size != current.size) store.save(next) + publishSecureOn(next, updated) + } + + /** Import, after the list was saved: entries of the incoming IDs belong to the replaced cards. */ + private suspend fun dropSecureOn(ids: Set, updated: List) { + val store = secureOn ?: return + val current = store.load() + if (current.keys.none { it in ids }) return + val next = current - ids + store.save(next) + publishSecureOn(next, updated) + } + + /** + * Password for [device] at send time (revize 39/2, fail-closed): the entry must be bound to the + * device's current MAC/target/port. A protected device (an entry exists, it was protected when + * last read, or the store was unreadable) whose password cannot be obtained or does not match + * is never woken without it: [SendFailure.SECURE_ON_UNAVAILABLE] ("enter it again"). + */ + private suspend fun secureOnFor(device: WolDevice): ByteArray? = secureOnPasswordForSend(device, secureOn, + protectedOnFailure = device.secureOnRequired || device.id in vaultIds || device.id in state.value.secureOnIds || state.value.secureOnFailed, + expectProtected = device.secureOnRequired || device.id in state.value.secureOnIds) + + /** + * The vault write for the list ([beforeSave]), the list save and, on failure, [onSaveFailed] + * (rollback) run as one unit: NonCancellable, bounded by [STORAGE_STEP_TIMEOUT_MS] each (revize + * 39/3), so cancelling the scope cannot leave a vault change without its list or its rollback. + * After a saved list the SecureOn flags are recomputed from the vault and the new list, also + * when [afterSave] fails (revize 39/3). + */ + private fun mutate(beforeSave: suspend (List) -> Unit = {}, afterSave: suspend (List) -> Unit = {}, + onSaveFailed: suspend () -> Unit = {}, transform: () -> List) { // Reserve immediately, before launch dispatches, so rapid UI events cannot race. mutableState.update { it.copy(saving = true, message = null) } scope.launch { @@ -147,17 +312,42 @@ class WolController( val updated = transform() val previous = state.value.devices.associateBy { it.id } val unchanged = updated.filter { previous[it.id] == it }.map { it.id }.toSet() - store.save(updated) + withContext(NonCancellable) { + try { + withTimeout(STORAGE_STEP_TIMEOUT_MS) { beforeSave(updated); store.save(updated) } + } catch (error: Throwable) { + // The list was not written: undo a vault change made for it. + try { withTimeout(STORAGE_STEP_TIMEOUT_MS) { onSaveFailed() } } catch (_: Throwable) { /* Fail-closed via binding. */ } + throw if (error is TimeoutCancellationException) StorageTimeoutException(error) else error + } + } if (probeDevice?.id?.let { it !in unchanged } == true) cancelProbe(publishCancelled = false) mutableState.update { it.copy(devices = updated, draft = null, errors = emptySet(), pendingImport = null, skippedCount = 0, secureOnDropped = 0, outcomes = it.outcomes.filterKeys { id -> id in unchanged }, probes = it.probes.filterKeys { id -> id in unchanged }) } + try { afterSave(updated) } finally { withContext(NonCancellable) { refreshSecureOnFlags(updated, previous) } } } } catch (e: CancellationException) { throw e - } catch (_: Exception) { mutableState.update { it.copy(message = WolMessage.SAVE_FAILED) } - } + } catch (_: Exception) { mutableState.update { it.copy(message = WolMessage.SAVE_FAILED) } } }.invokeOnCompletion { mutableState.update { it.copy(saving = false) } } } + private class StorageTimeoutException(cause: Throwable) : Exception("STORAGE_TIMEOUT", cause) + + /** + * Flags after a saved list: from the vault when readable; otherwise an ID stays "matching" only + * if its device kept the binding it had, and the store counts as failed (sending fails closed). + */ + private suspend fun refreshSecureOnFlags(updated: List, previous: Map) { + val store = secureOn ?: return + try { withTimeout(STORAGE_STEP_TIMEOUT_MS) { publishSecureOn(store.load(), updated) } } + catch (_: Throwable) { + mutableState.update { state -> state.copy(secureOnFailed = true, secureOnIds = state.secureOnIds.filter { id -> + val before = previous[id]; val after = updated.firstOrNull { it.id == id } + before != null && after != null && secureOnBinding(before) == secureOnBinding(after) + }.toSet()) } + } + } + fun wake(id: String) { if (state.value.loading || state.value.loadFailed || state.value.saving || state.value.recovering || state.value.sendingDeviceId != null) return val device = state.value.devices.find { it.id == id } ?: return @@ -169,36 +359,17 @@ class WolController( var selectedNetwork: WifiNetworkInfo? = null var alreadyResponded = false val completed = withTimeoutOrNull(sendTimeoutMillis + (device.repeatCount - 1) * device.repeatIntervalMs.toLong() + (if (device.probeEnabled) WAKE_PRECHECK_TIMEOUT_MS else 0)) { - val network = networkInfo.currentWifi() - if (network == null) { - outcome(id, SendFailure.NO_WIFI) - return@withTimeoutOrNull - } - selectedNetwork = network - if (device.probeEnabled) { - alreadyResponded = wakeProbeAttempt(WAKE_PRECHECK_TIMEOUT_MS) { - prober?.probe(network.handle, requireNotNull(device.probeHost), device.probePort) - ?: WakeProbeStatus.UNAVAILABLE - } == WakeProbeStatus.RESPONDS - } - val host = when (device.targetMode) { - TargetMode.LIMITED_BROADCAST -> "255.255.255.255" - TargetMode.CUSTOM -> requireNotNull(device.customTarget) - TargetMode.AUTO_BROADCAST -> { - val ip = network.ipv4?.let(::parseIpv4) - val broadcast = if (ip != null) network.prefixLength?.let { directedBroadcast(ip, it) } else null - if (broadcast == null) { - outcome(id, SendFailure.NO_BROADCAST) - return@withTimeoutOrNull - } - broadcast.toString() + // The shared use-case sends; only the "already awake" pre-check stays here (zadání 36 §2.5). + val result = sendWolWake(device, networkInfo, sender, beforeSend = { network -> + selectedNetwork = network + if (device.probeEnabled) { + alreadyResponded = wakeProbeAttempt(WAKE_PRECHECK_TIMEOUT_MS) { + prober?.probe(network.handle, requireNotNull(device.probeHost), device.probePort) + ?: WakeProbeStatus.UNAVAILABLE + } == WakeProbeStatus.RESPONDS } - } - repeat(device.repeatCount) { attempt -> - if (attempt > 0) delay(device.repeatIntervalMs.toLong()) - sender.sendUdp(network.handle, host, device.port, magicPacket(requireNotNull(parseMac(device.mac)))) - } - outcome(id, null) + }, secureOn = { secureOnFor(device) }) + outcome(id, (result as? WolWakeResult.Failed)?.reason) } if (completed == null) outcome(id, SendFailure.TIMEOUT) if (state.value.outcomes[id]?.sent == true && device.probeEnabled) { @@ -223,6 +394,7 @@ class WolController( null -> WolMessage.SENT SendFailure.NO_WIFI -> WolMessage.NO_WIFI SendFailure.NO_BROADCAST -> WolMessage.NO_BROADCAST + SendFailure.SECURE_ON_UNAVAILABLE -> WolMessage.SECURE_ON_UNAVAILABLE SendFailure.CANCELLED -> null else -> WolMessage.SEND_FAILED }) } diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolDomain.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolDomain.kt index 46b6893..42cd6dd 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolDomain.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolDomain.kt @@ -72,6 +72,7 @@ fun validateDevice(draft: WolDeviceDraft, original: WolDevice? = null): DeviceVa if (!inRange(draft.repeatIntervalMs, 50..2000)) errors += DeviceField.REPEAT_INTERVAL if (!inRange(draft.probeDelaySeconds, 1..120)) errors += DeviceField.PROBE_DELAY if (draft.probeEnabled && draft.probeHost.isBlank()) errors += DeviceField.PROBE_HOST + if (draft.secureOn.isNotEmpty() && parseSecureOn(draft.secureOn) == null) errors += DeviceField.SECURE_ON return DeviceValidation(errors) } @@ -81,3 +82,23 @@ internal fun WolDevice.toDraft() = WolDeviceDraft(id, name, mac, targetMode, cus fun validateStoredDevices(devices: List): Boolean = devices.all { it.id.isNotBlank() && validateDevice(it.toDraft(), it).isValid } && devices.map { it.id }.distinct().size == devices.size + +/* + * SecureOn (zadání 39 §2.5): an optional 4- or 6-byte password appended to the magic packet + * (AMD Magic Packet / SecureOn). It is a secret: never part of WolDevice, so never in JSON/CSV + * export or import; the app keeps it in an encrypted store ([WolSecureOnStore]). + */ + +/** "xx:xx:xx:xx:xx:xx" (or `-`) = 6 bytes, dotted "a.b.c.d" = 4 bytes; null for anything else. */ +fun parseSecureOn(input: String): ByteArray? { + val text = input.trim() + if (Regex("[0-9a-fA-F]{2}([:-])[0-9a-fA-F]{2}(\\1[0-9a-fA-F]{2}){4}").matches(text)) + return text.split(':', '-').map { it.toInt(16).toByte() }.toByteArray() + return parseIpv4(text)?.let { ip -> ByteArray(4) { index -> (ip.value shr (24 - index * 8)).toByte() } } +} + +/** [magicPacket] (102 B) followed by the SecureOn [password] (4 or 6 B) when one is set: 106 or 108 B. */ +fun secureOnMagicPacket(mac: MacAddress, password: ByteArray?): ByteArray { + require(password == null || password.size == 4 || password.size == 6) + return if (password == null) magicPacket(mac) else magicPacket(mac) + password +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolModels.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolModels.kt index 4110e73..db7905a 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolModels.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolModels.kt @@ -22,6 +22,13 @@ data class WolDevice( val repeatIntervalMs: Int = 250, val probeEnabled: Boolean = false, val probeDelaySeconds: Int = 20, + /** + * The owner protected this device with a SecureOn password (zadání 39, revize 39/4). Not a secret: + * it only records that a password is required, independently of whether the encrypted store can + * produce it now. A wake of a device with the flag never goes out without its bound password. + * Cleared only by the owner's explicit "remove password". + */ + val secureOnRequired: Boolean = false, ) interface WifiNetworkHandle @@ -44,7 +51,8 @@ interface WolDeviceStore { enum class StoreFailure { IO, CORRUPT, UNSUPPORTED_SCHEMA } class StoreReadException(val kind: StoreFailure, val schema: Int? = null, cause: Throwable? = null, val archivePath: String? = null) : Exception(kind.name, cause) data class StoreRecovery(val archivePath: String?, val devices: List) -enum class SendFailure { DNS, TIMEOUT, NETWORK_LOST, IO, CANCELLED, NO_WIFI, NO_BROADCAST } +/** [SECURE_ON_UNAVAILABLE]: the device has a SecureOn password that cannot be used now; nothing was sent (revize 39/2). */ +enum class SendFailure { DNS, TIMEOUT, NETWORK_LOST, IO, CANCELLED, NO_WIFI, NO_BROADCAST, SECURE_ON_UNAVAILABLE } class PacketSendException(val reason: SendFailure, cause: Throwable? = null) : Exception(reason.name, cause) data class WolSendOutcome(val sent: Boolean, val reason: SendFailure?, val timestamp: Long) @@ -63,11 +71,23 @@ data class WolDeviceDraft( val repeatIntervalMs: String = "250", val probeEnabled: Boolean = false, val probeDelaySeconds: String = "20", -) + /** New SecureOn password as typed (zadání 39); empty = keep the stored one (or none). Never exported. */ + val secureOn: String = "", + /** The device already has a stored SecureOn password (the value itself is never loaded into the draft). */ + val secureOnStored: Boolean = false, + /** Remove the stored password on save. */ + val secureOnRemove: Boolean = false, + /** A stored password belongs to another MAC/target/port of this ID; sending is blocked until it is entered again. */ + val secureOnStale: Boolean = false, +) { + /** The typed password must not leak through logs or crash reports. */ + override fun toString(): String = "WolDeviceDraft(id=$id, name=$name, mac=$mac, targetMode=$targetMode, port=$port, " + + "secureOn=${if (secureOn.isEmpty()) "" else "***"}, secureOnStored=$secureOnStored, secureOnRemove=$secureOnRemove)" +} -enum class DeviceField { NAME, MAC, CUSTOM_TARGET, PORT, PROBE_HOST, PROBE_PORT, NOTE, REPEAT_COUNT, REPEAT_INTERVAL, PROBE_DELAY } +enum class DeviceField { NAME, MAC, CUSTOM_TARGET, PORT, PROBE_HOST, PROBE_PORT, NOTE, REPEAT_COUNT, REPEAT_INTERVAL, PROBE_DELAY, SECURE_ON } data class DeviceValidation(val errors: Set) { val isValid: Boolean get() = errors.isEmpty() } -enum class WolMessage { LOAD_FAILED, SAVE_FAILED, SEND_FAILED, NO_WIFI, NO_BROADCAST, SENT } +enum class WolMessage { LOAD_FAILED, SAVE_FAILED, SEND_FAILED, NO_WIFI, NO_BROADCAST, SENT, SECURE_ON_UNAVAILABLE } data class WolUiState( val devices: List = emptyList(), val loading: Boolean = true, @@ -87,5 +107,8 @@ data class WolUiState( val pendingImport: List? = null, val skippedCount: Int = 0, val secureOnDropped: Int = 0, - + /** Devices with a stored SecureOn password (IDs only; zadání 39). */ + val secureOnIds: Set = emptySet(), + /** The encrypted SecureOn store could not be read; devices may have a password that cannot be used now. */ + val secureOnFailed: Boolean = false, ) diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolSecureOn.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolSecureOn.kt new file mode 100644 index 0000000..8e614c1 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolSecureOn.kt @@ -0,0 +1,94 @@ +package cz.netkit.shared.wol + +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +/** + * One stored SecureOn password (zadání 39 §2.5) and the device it was set for. [binding] is + * [secureOnBinding] of that device when the owner typed the password (or edited it locally): + * MAC, target mode, custom target and port. A password is used only while the device still has + * the same binding, so a device replaced under the same ID (import) never gets another card's password. + */ +class SecureOnEntry(val password: ByteArray, val binding: String) { + init { require((password.size == 4 || password.size == 6) && binding.isNotEmpty() && binding.length <= 600) } + override fun equals(other: Any?): Boolean = other is SecureOnEntry && password.contentEquals(other.password) && binding == other.binding + override fun hashCode(): Int = password.contentHashCode() * 31 + binding.hashCode() + /** Never prints the password. */ + override fun toString(): String = "SecureOnEntry(binding=$binding, password=***)" +} + +/** Identity of a device for its SecureOn password: normalized MAC, target mode, custom target (lower case) and port. */ +fun secureOnBinding(device: WolDevice): String = + listOf(parseMac(device.mac)?.toString() ?: device.mac.uppercase(), device.targetMode.name, + device.customTarget.orEmpty().trim().lowercase(), device.port.toString()).joinToString("|") + +/** Password for [device] only when its entry is bound to the same MAC and target; otherwise null. */ +fun secureOnPasswordFor(device: WolDevice, vault: Map): ByteArray? = + vault[device.id]?.takeIf { it.binding == secureOnBinding(device) }?.password + +/** + * Encrypted SecureOn entries by device ID. Platform code encrypts the bytes of + * [encodeSecureOnVault] (Android Keystore AES-GCM); this layer never sees ciphertext. + * [load] returns an empty map when nothing was stored and throws when the stored data cannot be read. + */ +interface WolSecureOnStore { + suspend fun load(): Map + suspend fun save(entries: Map) +} + +@Serializable private data class SecureOnVaultEntry(val h: String, val b: String) +@Serializable private data class SecureOnVault(val v: Int, val p: Map) +private val vaultJson = Json { ignoreUnknownKeys = false } +const val SECURE_ON_VAULT_MAX_BYTES = 262_144 +/** Version 2 binds each password to its device (revize 39/1); v1 existed only in the unreleased branch. */ +private const val SECURE_ON_VAULT_VERSION = 2 + +fun encodeSecureOnVault(entries: Map): ByteArray { + require(entries.keys.all { it.isNotEmpty() && it.length <= 256 }) + val encoded = entries.mapValues { (_, entry) -> + SecureOnVaultEntry(entry.password.joinToString("") { (it.toInt() and 0xff).toString(16).padStart(2, '0') }, entry.binding) + } + return vaultJson.encodeToString(SecureOnVault.serializer(), SecureOnVault(SECURE_ON_VAULT_VERSION, encoded)).encodeToByteArray() + .also { require(it.size <= SECURE_ON_VAULT_MAX_BYTES) } +} + +/** Strict: any malformed entry rejects the whole vault (IllegalArgumentException), nothing is salvaged silently. */ +fun decodeSecureOnVault(bytes: ByteArray): Map { + require(bytes.size <= SECURE_ON_VAULT_MAX_BYTES) + val vault = try { vaultJson.decodeFromString(SecureOnVault.serializer(), bytes.decodeToString(throwOnInvalidSequence = true)) } + catch (error: Exception) { throw IllegalArgumentException("SECURE_ON_VAULT", error) } + require(vault.v == SECURE_ON_VAULT_VERSION) + return vault.p.mapValues { (id, entry) -> + val hex = entry.h + require(id.isNotEmpty() && id.length <= 256 && (hex.length == 8 || hex.length == 12) && hex.all { it in '0'..'9' || it in 'a'..'f' }) + SecureOnEntry(ByteArray(hex.length / 2) { hex.substring(it * 2, it * 2 + 2).toInt(16).toByte() }, entry.b) + } +} + +/** + * Fail-closed password lookup for sending (revize 39/2–3, used by the app and the widget): + * - an entry bound to the device's current MAC/target/port → its password; + * - an entry bound to another configuration → [SendFailure.SECURE_ON_UNAVAILABLE], nothing is sent; + * - no entry → plain packet, unless [expectProtected] (default: the device's persistent + * [WolDevice.secureOnRequired]) → blocked; + * - unreadable store → blocked when [protectedOnFailure] (default: the same flag), otherwise plain. + */ +suspend fun secureOnPasswordForSend(device: WolDevice, store: WolSecureOnStore?, protectedOnFailure: Boolean = device.secureOnRequired, + expectProtected: Boolean = device.secureOnRequired): ByteArray? { + if (store == null) { + if (device.secureOnRequired) throw PacketSendException(SendFailure.SECURE_ON_UNAVAILABLE) + return null + } + val vault = try { store.load() } + catch (e: kotlinx.coroutines.CancellationException) { throw e } + catch (error: Exception) { + if (protectedOnFailure) throw PacketSendException(SendFailure.SECURE_ON_UNAVAILABLE, error) + return null + } + if (vault[device.id] == null) { + if (expectProtected) throw PacketSendException(SendFailure.SECURE_ON_UNAVAILABLE) + return null + } + return secureOnPasswordFor(device, vault) ?: throw PacketSendException(SendFailure.SECURE_ON_UNAVAILABLE) +} + diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolTransfer.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolTransfer.kt index 2f7b774..6774181 100644 --- a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolTransfer.kt +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolTransfer.kt @@ -15,7 +15,7 @@ const val WOL_TRANSFER_LIMIT = 1_048_576 private val transferJson = Json { encodeDefaults = true } enum class WolImportFailure { SIZE, UTF8, FORMAT, SCHEMA, UNKNOWN_FIELD, DUPLICATE_ID, INVALID_DEVICE } class WolImportException(val reason: WolImportFailure) : IllegalArgumentException(reason.name) -private val importDeviceFields = setOf("id", "name", "mac", "targetMode", "customTarget", "port", "probeHost", +private val importDeviceFields = setOf("id", "name", "mac", "targetMode", "customTarget", "port", "probeHost", "secureOnRequired", "probePort", "note", "createdAt", "updatedAt", "repeatCount", "repeatIntervalMs", "probeEnabled", "probeDelaySeconds") /** Untrusted imports never inherit the persisted-store grandfathering exception. */ diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWake.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWake.kt new file mode 100644 index 0000000..4cec957 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWake.kt @@ -0,0 +1,115 @@ +package cz.netkit.shared.wol + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.delay + +/* + * WoL send use-case (zadání 36 §2.5): network selection, broadcast target, repetition and sending, + * without the wake probe and without UI state. WolController (app UI) and the home-screen widget + * both call it; the caller owns the timeout. + */ + +/** + * Final check and socket write of one packet, run as one step: the guard calls `write` (a short + * blocking UDP send) only while the caller still may send and returns whether it did. The widget runs + * it inside its state transaction, so a change of the widget's device waits for the write or wins + * before it (revize kolo 4). + */ +typealias PacketWriteGuard = suspend (write: () -> Unit) -> Boolean + +/** + * A [PacketSender] that resolves the target and prepares the socket (open, broadcast, bind) first and + * only then hands the write to [PacketWriteGuard]; a refused guard skips the packet and returns false. + * The widget uses it so a device change during DNS or socket setup never lets the old packet out + * (revize kolo 3–4). Platforms without it (iOS) keep the plain [PacketSender] path, checked before + * each packet only. + */ +interface GuardedPacketSender : PacketSender { + suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray, guard: PacketWriteGuard): Boolean +} + +sealed interface WolWakeResult { + /** All [packets] were handed to the OS for [host] on [network]. */ + data class Sent(val network: WifiNetworkInfo, val host: String, val packets: Int) : WolWakeResult + data class Failed(val reason: SendFailure) : WolWakeResult +} + +/** Destination of the magic packet on [network]; null when an automatic broadcast cannot be derived. */ +fun wolTargetHost(device: WolDevice, network: WifiNetworkInfo): String? = when (device.targetMode) { + TargetMode.LIMITED_BROADCAST -> "255.255.255.255" + TargetMode.CUSTOM -> requireNotNull(device.customTarget) + TargetMode.AUTO_BROADCAST -> { + val ip = network.ipv4?.let(::parseIpv4) + (if (ip != null) network.prefixLength?.let { directedBroadcast(ip, it) } else null)?.toString() + } +} + +/** + * Sends [repeatCount] magic packets for [device], [WolDevice.repeatIntervalMs] apart, over the current + * Wi-Fi. [beforeSend] runs once the Wi-Fi network is known and before the target is resolved (the UI + * uses it for its "already awake" pre-check); its exceptions count as an I/O failure. + * [shouldContinue] is asked before every packet; [writeGuard] (only with a [GuardedPacketSender]) decides + * the socket write itself after DNS and socket setup, default = [shouldContinue] then write. A refusal + * stops the series with [SendFailure.CANCELLED] + * (the widget uses it when its reservation is gone). Cancellation propagates; [PacketSendException] + * becomes its reason, any other error [SendFailure.IO]. + */ +suspend fun sendWolWake( + device: WolDevice, + networkInfo: NetworkInfoProvider, + sender: PacketSender, + repeatCount: Int = device.repeatCount, + beforeSend: suspend (WifiNetworkInfo) -> Unit = {}, + shouldContinue: suspend () -> Boolean = { true }, + writeGuard: PacketWriteGuard = { write -> if (shouldContinue()) { write(); true } else false }, + /** + * SecureOn password for [device] (zadání 39), asked once the Wi-Fi is known and before any packet: + * null = plain 102 B packet; a [PacketSendException] with [SendFailure.SECURE_ON_UNAVAILABLE] + * (fail-closed, see [secureOnPasswordForSend]) ends the wake before anything is sent. + */ + secureOn: suspend () -> ByteArray? = { null }, +): WolWakeResult { + require(repeatCount >= 1) + return try { + val network = networkInfo.currentWifi() ?: return WolWakeResult.Failed(SendFailure.NO_WIFI) + beforeSend(network) + val host = wolTargetHost(device, network) ?: return WolWakeResult.Failed(SendFailure.NO_BROADCAST) + val packet = secureOnMagicPacket(requireNotNull(parseMac(device.mac)), secureOn()) + repeat(repeatCount) { attempt -> + if (attempt > 0) delay(device.repeatIntervalMs.toLong()) + if (!shouldContinue()) return WolWakeResult.Failed(SendFailure.CANCELLED) + if (sender is GuardedPacketSender) { + if (!sender.sendUdp(network.handle, host, device.port, packet, writeGuard)) + return WolWakeResult.Failed(SendFailure.CANCELLED) + } else sender.sendUdp(network.handle, host, device.port, packet) + } + WolWakeResult.Sent(network, host, repeatCount) + } catch (e: CancellationException) { throw e + } catch (e: PacketSendException) { WolWakeResult.Failed(e.reason) + } catch (_: Exception) { WolWakeResult.Failed(SendFailure.IO) + } +} + +/** Longest span of repeated packets the widget allows, so the whole send fits its receiver budget. */ +const val WOL_WIDGET_REPEAT_SPAN_MS = 4_000L + +/** + * Deadline of one widget tap, measured from entering the action callback: reading the widget state, + * loading devices, publishing SENDING, sending and writing the result all fit in it. Android gives a + * broadcast receiver about 10 s. + */ +const val WOL_WIDGET_TIMEOUT_MS = 8_000L + +/** Part of [WOL_WIDGET_TIMEOUT_MS] kept for writing and drawing the result after the send. */ +const val WOL_WIDGET_WRITE_RESERVE_MS = 1_500L + +/** Time left for the send itself when [elapsedMillis] passed since the tap; 0 = do not start sending. */ +fun wolWidgetSendBudget(elapsedMillis: Long): Long = + (WOL_WIDGET_TIMEOUT_MS - WOL_WIDGET_WRITE_RESERVE_MS - elapsedMillis.coerceAtLeast(0)).coerceAtLeast(0) + +/** Time left for any step (including the final write) when [elapsedMillis] passed since the tap. */ +fun wolWidgetRemaining(elapsedMillis: Long): Long = (WOL_WIDGET_TIMEOUT_MS - elapsedMillis.coerceAtLeast(0)).coerceAtLeast(0) + +/** Repeat count used by the widget: the device setting, shortened to fit [WOL_WIDGET_REPEAT_SPAN_MS]. */ +fun wolWidgetRepeatCount(device: WolDevice): Int = + device.repeatCount.coerceAtMost(1 + (WOL_WIDGET_REPEAT_SPAN_MS / device.repeatIntervalMs.coerceAtLeast(1)).toInt()).coerceAtLeast(1) diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetModel.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetModel.kt new file mode 100644 index 0000000..fb932af --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetModel.kt @@ -0,0 +1,205 @@ +package cz.netkit.shared.wol + +/* + * State and content of the WoL home-screen widget (zadání 36 §2.6). Pure model: Android stores it in + * the widget's Glance preferences and renders [WolWidgetView]. The widget never holds the MAC; it keeps + * the device ID, the opaque device key ([wolDeviceKey]) and the name shown on the home screen. + * + * Concurrency (revize kolo 1 a 2): every state change runs as a transaction over the current + * preferences (DataStore `updateData`). The drawn "Wake" action carries the device key and the + * [WolWidgetState.revision] it was drawn with; a tap is accepted only while both still match and it + * then bumps the revision, so a second callback of the same drawing, a delayed callback of an older + * drawing or a callback drawn for device A after the user chose B is refused. The accepted tap holds + * a unique reservation token; the send stops as soon as the token is gone and only the holder writes + * the result, merged into the current state. + */ + +/** [SECURE_ON_UNAVAILABLE]: the device has a SecureOn password that cannot be used; nothing was sent (zadání 39). */ +enum class WolWidgetStatus { UNCONFIGURED, READY, SENDING, SENT, NO_WIFI, NO_BROADCAST, FAILED, DELETED, SECURE_ON_UNAVAILABLE } + +data class WolWidgetState( + val deviceId: String? = null, + /** [wolDeviceKey] of the chosen device; a different device that reuses the ID does not match. */ + val deviceKey: String? = null, + val name: String? = null, + val status: WolWidgetStatus = WolWidgetStatus.UNCONFIGURED, + /** Wall-clock time of [status] (send start or result), for "Odesláno HH:MM". */ + val atMillis: Long? = null, + /** Reservation of the running send; null when no send holds the widget. */ + val sendToken: String? = null, + /** Bumped by every new choice and every accepted tap; the drawn action carries it. */ + val revision: Long = 0, + /** + * [wolDeviceBindingKey] of the device configuration a running send uses (revize 39/4): a change of + * MAC, target mode, custom target or port while the device key stays the same cancels the reservation. + */ + val bindingKey: String? = null, +) + +/** What the drawn "Wake" action carries (Glance action parameters). */ +data class WolWidgetTap(val deviceKey: String, val revision: Long) + +/** A SENDING state older than this is a send interrupted by process death; the widget accepts taps again. */ +const val WOL_WIDGET_STALE_SENDING_MS = 15_000L + +/** Name length kept for the home screen; the card in the app shows the full name. */ +const val WOL_WIDGET_NAME_MAX = 40 + +/** + * Opaque identity of one saved device: 64-bit FNV-1a over ID, normalized MAC and creation time, + * as 16 hex digits. External navigation, pinned shortcuts and widgets carry it instead of the ID + * (an imported ID may look like a hostname or an IPv4 address). A device recreated with the same ID but + * another MAC or creation time (e.g. CSV re-import `webb-`) gets another key. Identity only, not a secret. + */ +fun wolDeviceKey(device: WolDevice): String { + val mac = parseMac(device.mac)?.toString() ?: device.mac.uppercase() + var hash = 0xcbf29ce484222325uL + for (byte in "${device.id}\n$mac\n${device.createdAt}".encodeToByteArray()) { + hash = (hash xor byte.toUByte().toULong()) * 0x100000001b3uL + } + return hash.toString(16).padStart(16, '0') +} + +/** + * Opaque fingerprint of a device's wake configuration: 64-bit FNV-1a over [secureOnBinding] (MAC, target + * mode, custom target, port), 16 hex digits. Stored by the widget instead of the target itself. + */ +fun wolDeviceBindingKey(device: WolDevice): String { + var hash = 0xcbf29ce484222325uL + for (byte in secureOnBinding(device).encodeToByteArray()) hash = (hash xor byte.toUByte().toULong()) * 0x100000001b3uL + return hash.toString(16).padStart(16, '0') +} + +/** + * Devices by key, without ambiguous keys: a (practically impossible) 64-bit collision must not open, + * pin or enable a shortcut for an arbitrary one of the colliding devices. + */ +fun uniqueWolDevicesByKey(devices: List, keyOf: (WolDevice) -> String = ::wolDeviceKey): Map = + devices.groupBy(keyOf).filterValues { it.size == 1 }.mapValues { it.value.single() } + +/** The saved device with [key]; null if none or if the key is ambiguous. */ +fun wolDeviceByKey(devices: List, key: String): WolDevice? = uniqueWolDevicesByKey(devices)[key] + +/** State right after the user picked [device] in the configuration activity (drops any running reservation). */ +fun configuredWolWidgetState(device: WolDevice, previous: WolWidgetState = WolWidgetState()) = + WolWidgetState(device.id, wolDeviceKey(device), device.name.take(WOL_WIDGET_NAME_MAX), WolWidgetStatus.READY, + revision = previous.revision + 1, bindingKey = wolDeviceBindingKey(device)) + +/** Status shown after a send; a caller timeout (null result) is a failure. */ +fun wolWidgetStatus(result: WolWakeResult?): WolWidgetStatus = when (result) { + is WolWakeResult.Sent -> WolWidgetStatus.SENT + is WolWakeResult.Failed -> when (result.reason) { + SendFailure.NO_WIFI -> WolWidgetStatus.NO_WIFI + SendFailure.NO_BROADCAST -> WolWidgetStatus.NO_BROADCAST + SendFailure.SECURE_ON_UNAVAILABLE -> WolWidgetStatus.SECURE_ON_UNAVAILABLE + else -> WolWidgetStatus.FAILED + } + null -> WolWidgetStatus.FAILED +} + +/** The saved device this widget is bound to, matched by ID **and** key; null if gone or replaced. */ +fun boundWolDevice(state: WolWidgetState, devices: List): WolDevice? { + val id = state.deviceId ?: return null + val key = state.deviceKey ?: return null + return devices.firstOrNull { it.id == id && wolDeviceKey(it) == key } +} + +/** + * After the device list changed: a rename follows the device; a deleted or replaced device (same ID, + * other key) turns the widget into "deleted, choose again" and drops a running reservation, so that send + * stops and cannot write its result. It never switches to another device by itself. [devices] must be a + * successfully read list. + */ +fun syncWolWidgetState(state: WolWidgetState, devices: List): WolWidgetState { + if (state.deviceId == null) return state + val device = boundWolDevice(state, devices) + ?: return if (state.status == WolWidgetStatus.DELETED && state.sendToken == null) state + else state.copy(status = WolWidgetStatus.DELETED, atMillis = null, sendToken = null) + val name = device.name.take(WOL_WIDGET_NAME_MAX) + val binding = wolDeviceBindingKey(device) + // Same device, new MAC/target/port (revize 39/4): a running series must not send another packet to + // the old target; drop the reservation and bump the revision so older drawings are refused too. + if (state.bindingKey != null && state.bindingKey != binding) { + val aborted = state.sendToken != null + return state.copy(name = name, bindingKey = binding, sendToken = null, revision = state.revision + 1, + status = if (aborted || state.status == WolWidgetStatus.DELETED) WolWidgetStatus.READY else state.status, + atMillis = if (aborted) null else state.atMillis) + } + // A widget configured before binding keys existed adopts the current one (no reservation to cancel then). + val known = if (state.bindingKey == null) state.copy(bindingKey = binding) else state + return when { + // The very same device came back (same ID, MAC and creation time, e.g. an undo by JSON import). + state.status == WolWidgetStatus.DELETED -> known.copy(name = name, status = WolWidgetStatus.READY, atMillis = null) + state.name != name -> known.copy(name = name) + else -> known + } +} + +private fun bound(state: WolWidgetState) = state.deviceId != null && state.deviceKey != null + +private fun runningSend(state: WolWidgetState, nowMillis: Long): Boolean = + state.status == WolWidgetStatus.SENDING && state.sendToken != null && + state.atMillis != null && nowMillis - state.atMillis in 0 until WOL_WIDGET_STALE_SENDING_MS + +/** The widget is bound to a device and no (non-stale) send holds it. Expiry uses wall-clock time. */ +fun canStartWolWidgetWake(state: WolWidgetState, nowMillis: Long): Boolean = + bound(state) && state.status != WolWidgetStatus.UNCONFIGURED && state.status != WolWidgetStatus.DELETED && + !runningSend(state, nowMillis) + +/** + * Transaction step of a tap: reserves the widget for [token] (status SENDING, revision + 1) only when the + * tap was drawn for the current device and revision and the widget may start; otherwise returns the + * state unchanged. The caller owns the send only if the stored token equals [token]. + */ +fun reserveWolWidgetWake(state: WolWidgetState, tap: WolWidgetTap, nowMillis: Long, token: String): WolWidgetState = + if (tap.deviceKey == state.deviceKey && tap.revision == state.revision && canStartWolWidgetWake(state, nowMillis)) + state.copy(status = WolWidgetStatus.SENDING, atMillis = nowMillis, sendToken = token, revision = state.revision + 1) + else state + +/** + * Transaction step after the send: writes [status] into the **current** state only while it still holds + * [token] for the same device; a newer choice, a deletion or a newer reservation keeps the current state. + * It bumps the revision again: Glance updates the extras of the button's PendingIntent when it redraws + * SENDING, so a second tap sent during the send carries that revision and must not start a new series + * once this one finished (emulator finding, revize kolo 2). + */ +fun completeWolWidgetWake(state: WolWidgetState, token: String, deviceId: String, deviceKey: String, + status: WolWidgetStatus, nowMillis: Long): WolWidgetState = + if (state.sendToken == token && state.deviceId == deviceId && state.deviceKey == deviceKey && state.status == WolWidgetStatus.SENDING) + state.copy(status = status, atMillis = nowMillis, sendToken = null, revision = state.revision + 1) + else state + +/** What the widget shows. [showTime] means "status + HH:MM of [WolWidgetState.atMillis]". */ +data class WolWidgetView( + val title: String?, + val status: WolWidgetStatus, + val showTime: Boolean, + /** Visual only: a tap always reaches the callback, which decides atomically (stale reservations recover). */ + val wakeEnabled: Boolean, + /** Tap on the title opens the WoL tab with this device; otherwise it opens the configuration. */ + val opensDevice: Boolean, + val error: Boolean, + /** Parameters of the drawn "Wake" action; null when no button is drawn. */ + val tap: WolWidgetTap?, +) + +fun wolWidgetView(state: WolWidgetState, nowMillis: Long): WolWidgetView { + val status = when { + state.deviceId == null -> WolWidgetStatus.UNCONFIGURED + // A state written before keys existed cannot prove its device: choose again. + state.deviceKey == null -> WolWidgetStatus.DELETED + state.status == WolWidgetStatus.SENDING && !runningSend(state, nowMillis) -> WolWidgetStatus.FAILED + else -> state.status + } + val opensDevice = bound(state) && status != WolWidgetStatus.UNCONFIGURED && status != WolWidgetStatus.DELETED + return WolWidgetView( + title = state.name.takeIf { state.deviceId != null }, + status = status, + showTime = status == WolWidgetStatus.SENT && state.atMillis != null, + wakeEnabled = canStartWolWidgetWake(state, nowMillis), + opensDevice = opensDevice, + error = status in setOf(WolWidgetStatus.NO_WIFI, WolWidgetStatus.NO_BROADCAST, WolWidgetStatus.FAILED, WolWidgetStatus.DELETED, + WolWidgetStatus.SECURE_ON_UNAVAILABLE), + tap = if (opensDevice) WolWidgetTap(requireNotNull(state.deviceKey), state.revision) else null, + ) +} diff --git a/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetRun.kt b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetRun.kt new file mode 100644 index 0000000..3bdc254 --- /dev/null +++ b/shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetRun.kt @@ -0,0 +1,136 @@ +package cz.netkit.shared.wol + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext +import kotlinx.coroutines.withTimeoutOrNull + +/* + * One "Wake" tap of the home-screen widget (zadání 36 §2.6, revize kolo 1 a 2). Platform-free so the + * whole sequence is tested with fake stores, senders and virtual time; Android supplies the Glance + * preferences store, the device store and the clocks. + */ + +/** Transactions over one widget's stored state (Glance preferences on Android). */ +interface WolWidgetStore { + /** Atomically replaces the current state with [change] of it and returns the stored result. */ + suspend fun transact(change: (WolWidgetState) -> WolWidgetState): WolWidgetState + suspend fun read(): WolWidgetState +} + +enum class WolWidgetRunOutcome { REFUSED, DEVICE_GONE, FINISHED, LOST_RESERVATION } + +/** + * Runs one tap within [WOL_WIDGET_TIMEOUT_MS] measured by [elapsedMillis] from the tap: + * 1. reserve (drawn key and revision must match, see [reserveWolWidgetWake]); a refused tap only redraws; + * 2. redraw SENDING, load devices, check the binding and that the reservation still holds; + * 3. send; the series stops before the next packet once the reservation is gone, and with a + * [GuardedPacketSender] the final check and the socket write of each packet run inside one store + * transaction (after DNS and socket setup), serialized with any change of the widget's binding; + * 4. write the result with the real remaining time (writing before redrawing); with no time left the + * reservation simply expires ([WOL_WIDGET_STALE_SENDING_MS]). + */ +suspend fun runWolWidgetWake( + tap: WolWidgetTap, + reservation: String, + store: WolWidgetStore, + loadDevices: suspend () -> List?, + networkInfo: NetworkInfoProvider, + sender: PacketSender, + nowMillis: () -> Long, + elapsedMillis: () -> Long, + redraw: suspend () -> Unit, + /** SecureOn password of the bound device (zadání 39), fail-closed via [secureOnPasswordForSend]. */ + secureOnPassword: suspend (WolDevice) -> ByteArray? = { null }, +): WolWidgetRunOutcome { + suspend fun inSendBudget(block: suspend () -> T): T? { + val budget = wolWidgetSendBudget(elapsedMillis()) + return if (budget <= 0) null else withTimeoutOrNull(budget) { block() } + } + var binding: String? = null + /** The reservation still holds and (once the device is known) still targets the same configuration. */ + fun owns(state: WolWidgetState) = state.sendToken == reservation && (binding == null || state.bindingKey == binding) + suspend fun holds() = owns(store.read()) + + val reserved = inSendBudget { store.transact { reserveWolWidgetWake(it, tap, nowMillis(), reservation) } } + if (reserved?.sendToken != reservation) { + // Stale drawing, second callback of a double tap or another device chosen: show the current state. + inSendBudget { redraw() } + return WolWidgetRunOutcome.REFUSED + } + val deviceId = requireNotNull(reserved.deviceId) + val deviceKey = requireNotNull(reserved.deviceKey) + var status = WolWidgetStatus.FAILED + var devices: List? = null + var outcome = WolWidgetRunOutcome.FINISHED + try { + inSendBudget { redraw() } + devices = inSendBudget { + try { loadDevices() } catch (e: CancellationException) { throw e } catch (_: Exception) { null } + } + val device = devices?.firstOrNull { it.id == deviceId && wolDeviceKey(it) == deviceKey } + when { + devices != null && device == null -> outcome = WolWidgetRunOutcome.DEVICE_GONE + device != null && inSendBudget { + // Adopt the configuration being sent (revize 39/4); a later change of it cancels this reservation. + binding = wolDeviceBindingKey(device) + store.transact { if (it.sendToken == reservation) it.copy(bindingKey = binding) else it } + holds() + } != true -> outcome = WolWidgetRunOutcome.LOST_RESERVATION + device != null -> { + val result = inSendBudget { + sendWolWake(device, networkInfo, sender, wolWidgetRepeatCount(device), shouldContinue = { holds() }, + secureOn = { secureOnPassword(device) }, + // Last check and socket write inside one widget transaction: a new choice or a + // deletion either wins before it (no write) or waits until the write is done. + writeGuard = { write -> + var wrote = false + store.transact { current -> current.also { if (owns(it)) { write(); wrote = true } } } + wrote + }) + } + if ((result as? WolWakeResult.Failed)?.reason == SendFailure.CANCELLED) outcome = WolWidgetRunOutcome.LOST_RESERVATION + status = wolWidgetStatus(result) + } + } + } finally { + withContext(NonCancellable) { + val writeTime = wolWidgetRemaining(elapsedMillis()) + if (writeTime > 0) { + val written = withTimeoutOrNull(writeTime) { + store.transact { current -> + val list = devices + // A readable list without the bound device: deleted or replaced, never "sent". + if (list != null && boundWolDevice(current, list) == null && current.sendToken == reservation) syncWolWidgetState(current, list) + else completeWolWidgetWake(current, reservation, deviceId, deviceKey, status, nowMillis()) + } + } + val redrawTime = wolWidgetRemaining(elapsedMillis()) + if (written != null && redrawTime > 0) withTimeoutOrNull(redrawTime) { redraw() } + } + } + } + return outcome +} + +/** + * Data URI of one drawn "Wake" button (revize kolo 3). Android identifies a PendingIntent by its intent + * data, so every widget, device key and revision gets its own PendingIntent: redrawing for device B can + * never update the extras of a PendingIntent still held by an older drawing for A. The URI carries the + * whole tap; there are no extras. + */ +fun wolWidgetWakeData(appWidgetId: Int, tap: WolWidgetTap): String { + require(appWidgetId >= 0 && tap.revision >= 0 && tap.deviceKey.length == 16 && tap.deviceKey.all { it in '0'..'9' || it in 'a'..'f' }) + return "$WOL_WIDGET_WAKE_SCHEME://wake/$appWidgetId/${tap.deviceKey}/${tap.revision}" +} + +const val WOL_WIDGET_WAKE_SCHEME = "netkit-wol-widget" + +private val wakeData = Regex("^$WOL_WIDGET_WAKE_SCHEME://wake/([0-9]{1,10})/([0-9a-f]{16})/([0-9]{1,19})$") + +/** Strict inverse of [wolWidgetWakeData]; null for anything else. */ +fun parseWolWidgetWakeData(data: String?): Pair? { + val match = wakeData.matchEntire(data ?: return null) ?: return null + val (id, key, revision) = match.destructured + return (id.toIntOrNull() ?: return null) to WolWidgetTap(key, revision.toLongOrNull() ?: return null) +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/backup/ConfigurationBackupTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/backup/ConfigurationBackupTest.kt new file mode 100644 index 0000000..5a1ffcb --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/backup/ConfigurationBackupTest.kt @@ -0,0 +1,173 @@ +package cz.netkit.shared.backup + +import cz.netkit.shared.lan.* +import cz.netkit.shared.settings.* +import cz.netkit.shared.ssh.* +import cz.netkit.shared.wol.* +import kotlin.test.* +import kotlinx.serialization.json.* + +class ConfigurationBackupTest { + private val tools = BackupTools("", "1", "16", true, "192.0.2.0/24", "22,443", MaskInterpretation.NETMASK) + private val servers = BackupServers("https://example.org/", "192.0.2.9", 5202) + private val settings = BackupSettings(ThemeMode.DARK, AppLanguage.EN, false) + private val endpoint = SshProfile("p1", "Switch", "192.0.2.1", username = "operator", group = "Rack", + secretRef = "local-vault-marker", keyRef = "local-identity-marker", + localForwards = listOf(SshLocalForward(4444, "192.0.2.8", 443)), dynamicForwardPort = 1080, dynamicForwardNoAuth = true) + private val host = TrustedHostKey(endpoint.endpoint, "ssh-ed25519", "YWJj", "SHA256:fixture") + private val ssh = SshData(profiles = listOf(endpoint, SshProfile("p2", "Jumped", "192.0.2.2", username = "operator", jumpProfileId = "p1")), + hostKeys = listOf(host), keys = listOf(SshKeyInfo("local-identity-marker", "fixture", "local-public-material")), + snippets = listOf(SshSnippet("s1", "Status", "show version", profileId = "p1")), + consoles = listOf(ConsoleProfile("c1", "Rack console", ConsoleKind.SERIAL, serial = SerialSettings.mikrotik, group = "Rack"), + ConsoleProfile("c2", "Console", ConsoleKind.TELNET, "192.0.2.4", skipTelnetWarning = true, group = "Test"))) + private val device = WolDevice("w1", "Lab", "02:00:00:00:00:01", TargetMode.LIMITED_BROADCAST, createdAt = 1, updatedAt = 2, + secureOnRequired = true) + private val favorite = FavoriteTarget("https://example.org/status", "Status") + private val file = configurationBackup(ssh, listOf(device), tools, listOf(favorite.copy(value = favorite.value + "?q=omit-query")), + servers, settings) + private val empty = ConfigurationState(SshData(), emptyList(), tools.copy(df = false), emptyList(), + BackupServers(null, "", 5201), BackupSettings(ThemeMode.SYSTEM, AppLanguage.SYSTEM, true)) + private fun plan(selected: Set = BackupSection.entries.toSet(), current: ConfigurationState = empty): RestorePlan { + var next = 0 + return planRestore(current, decodeBackup(encodeBackup(file)), selected) { "generated-${next++}" } + } + + @Test fun serializedTreeExcludesCredentialFieldsAndVaultReferencesInEverySection() { + val bytes = encodeBackup(file) + fun visit(element: JsonElement, path: List) { + when (element) { + is JsonArray -> element.forEach { visit(it, path) } + is JsonObject -> element.forEach { (name, value) -> + val lower = name.lowercase() + val allowedPublic = path == listOf("knownHosts") && name == "publicKey" + val allowedFlag = path == listOf("wol", "devices") && name == "secureOnRequired" + assertTrue(allowedPublic || allowedFlag || listOf("pass", "secret", "key", "community", "communities", "secureon", + "credential", "token").none { it in lower }, (path + name).joinToString(".")) + visit(value, path + name) + } + else -> Unit + } + } + visit(backupDocument(bytes, BACKUP_BYTES), emptyList()) + for (marker in listOf("local-vault-marker", "local-identity-marker", "local-public-material", "omit-query")) + assertFalse(marker in bytes.decodeToString()) + assertEquals(file, decodeBackup(bytes).file) + } + + @Test fun recognizableInlineCredentialsCannotBeWrittenEvenToEncryptedBackup() { + for (command in listOf("snmp-server community fixture", "token=fixture", "Authorization: Bearer fixture")) { + val withCommand = configurationBackup(ssh.copy(snippets = listOf(SshSnippet("s1", "Lab", command))), + emptyList(), tools, emptyList(), servers, settings) + assertFailsWith { encodeBackup(withCommand) } + } + } + + @Test fun allSectionsRoundTripThroughTheImportRules() { + val result = plan() + val out = result.state + assertEquals(BackupSection.entries.toSet(), result.changes.keys) + val profile = out.ssh.profiles.first() + assertEquals("Rack", profile.group) + assertNull(profile.keyRef); assertNull(profile.secretRef) + assertEquals(profile.id, out.ssh.profiles.last().jumpProfileId) + assertEquals(endpoint.localForwards, profile.localForwards) + assertEquals(1080, profile.dynamicForwardPort) + assertFalse(profile.dynamicForwardNoAuth) + assertEquals(ssh.consoles.map { it.copy(skipTelnetWarning = false) }, out.ssh.consoles) + assertEquals(ssh.snippets.single().text, out.ssh.snippets.single().text) + assertFalse(out.ssh.snippets.single().sendEnter) + assertEquals(profile.id, out.ssh.snippets.single().profileId) + assertEquals(ssh.hostKeys, out.ssh.hostKeys) + assertEquals(listOf(device), out.devices) + assertEquals(setOf(device.id), result.forgetSecureOn) + assertEquals(tools, out.tools); assertEquals(listOf(favorite), out.favorites) + assertEquals(servers, out.servers); assertEquals(settings, out.settings) + assertEquals(out, plan(current = out).state) + } + + @Test fun sectionSelectionNeverChangesUnselectedStoresOrPins() { + assertEquals(empty, plan(emptySet()).state) + assertEquals(empty.copy(favorites = listOf(favorite)), plan(setOf(BackupSection.FAVORITES)).state) + val existing = empty.copy(ssh = SshData(profiles = listOf(endpoint.copy(group = "Local")))) + val snippetsOnly = plan(setOf(BackupSection.SNIPPETS), existing).state.ssh + assertEquals(existing.ssh.profiles, snippetsOnly.profiles) + assertEquals(endpoint.id, snippetsOnly.snippets.single().profileId) + val orphan = plan(setOf(BackupSection.SNIPPETS)) + assertEquals(1, orphan.changes.getValue(BackupSection.SNIPPETS).skipped) + val conflict = host.copy(publicKey = "ZGVm") + for (data in listOf(SshData(hostKeys = listOf(conflict)), SshData(rejectedHostKeys = listOf(host)))) { + val result = plan(setOf(BackupSection.KNOWN_HOSTS), empty.copy(ssh = data)) + assertEquals(data, result.state.ssh) + assertEquals(1, result.changes.getValue(BackupSection.KNOWN_HOSTS).skipped) + } + } + + @Test fun restoringAFullProfileClearsOldGroupJumpAndMovedCredentialBindings() { + val old = empty.copy(ssh = ssh.copy(profiles = listOf(endpoint.copy(host = "192.0.2.99", group = "Obsolete", jumpProfileId = "p2"), + ssh.profiles.last().copy(jumpProfileId = null)))) + val direct = configurationBackup(ssh.copy(profiles = listOf(endpoint.copy(group = null), ssh.profiles.last().copy(jumpProfileId = null))), + emptyList(), tools, emptyList(), servers, settings) + val restored = planRestore(old, decodeBackup(encodeBackup(direct)), setOf(BackupSection.SSH)) { error("no new profiles") } + val row = restored.state.ssh.profiles.first() + assertNull(row.keyRef); assertNull(row.secretRef); assertNull(row.jumpProfileId); assertNull(row.group) + assertEquals(1, restored.changes.getValue(BackupSection.SSH).changed) + } + + @Test fun reversedJumpIsPlannedWithoutTheLocalLinkInsteadOfSkippingAsACycle() { + // Revize 51, kolo 1: locally A -> B; the backup has A direct and B -> A. + val local = SshData(profiles = listOf(SshProfile("a", "A", "192.0.2.10", username = "operator", jumpProfileId = "b"), + SshProfile("b", "B", "192.0.2.11", username = "operator"))) + val backup = configurationBackup(SshData(profiles = listOf(SshProfile("x", "A", "192.0.2.10", username = "operator"), + SshProfile("y", "B", "192.0.2.11", username = "operator", jumpProfileId = "x"))), emptyList(), tools, emptyList(), servers, settings) + val restored = planRestore(empty.copy(ssh = local), decodeBackup(encodeBackup(backup)), setOf(BackupSection.SSH)) { error("no new profile") } + val profiles = restored.state.ssh.profiles.associateBy { it.name } + assertNull(profiles.getValue("A").jumpProfileId) + assertEquals("a", profiles.getValue("B").jumpProfileId) + assertEquals(SectionChanges(changed = 2), restored.changes[BackupSection.SSH]) + // Snippets alone never rewrite the local profiles, including their jump links. + assertEquals(local.profiles, planRestore(empty.copy(ssh = local), decodeBackup(encodeBackup(backup)), + setOf(BackupSection.SNIPPETS)) { error("no new snippet") }.state.ssh.profiles) + } + + @Test fun previewListsKeyProfilesThatArriveWithoutALocalKey() { + // Revize 51, kolo 2: keys never travel in the backup. + val key = SshKeyInfo("k1", "Lab key", "ssh-ed25519 AAAA lab") + val keyed = SshProfile("x", "Keyed", "192.0.2.20", username = "operator", authentication = SshAuthentication.KEY, keyRef = "k1") + val moved = SshProfile("y", "Moved", "192.0.2.21", username = "operator", authentication = SshAuthentication.KEY, keyRef = "k1") + val backup = decodeBackup(encodeBackup(configurationBackup(SshData(profiles = listOf(keyed, moved, + SshProfile("z", "Password", "192.0.2.22", username = "operator")), keys = listOf(key)), + emptyList(), tools, emptyList(), servers, settings))) + var next = 0 + fun ids() = { "generated-${next++}" } + // Nothing local: both key profiles are new and keyless; password profiles are never listed. + assertEquals(setOf("Keyed", "Moved"), planRestore(empty, backup, setOf(BackupSection.SSH), ids()).keyless) + // Same endpoint keeps the local key; a moved endpoint drops it. + val local = empty.copy(ssh = SshData(profiles = listOf(keyed.copy(id = "a"), moved.copy(id = "b", host = "192.0.2.99")), keys = listOf(key))) + assertEquals(setOf("Moved"), planRestore(local, backup, setOf(BackupSection.SSH), ids()).keyless) + // Profiles not selected are not restored, so nothing is reported. + assertEquals(emptySet(), planRestore(empty, backup, setOf(BackupSection.WOL), ids()).keyless) + } + + @Test fun encryptedEnvelopeRejectsForeignVersionsAndUnboundedKdfBeforeDecryption() { + val bytes = encodeEnvelope("A".repeat(22) + "==", "A".repeat(16), "A".repeat(22) + "==") + assertTrue(encryptedBackup(bytes)) + assertEquals(BACKUP_ROUNDS, decodeEnvelope(bytes).iterations) + for ((from, to) in listOf(BACKUP_ENCRYPTED_FORMAT to "future", BACKUP_KDF to "other", + BACKUP_CIPHER to "other", BACKUP_ROUNDS.toString() to "2147483647")) + assertFails { decodeEnvelope(bytes.decodeToString().replace(from, to).encodeToByteArray()) } + } + + @Test fun rejectsTruncationSizeDepthForeignVersionAndInjectedSecrets() { + val text = encodeBackup(file).decodeToString() + val samples = listOf(text.dropLast(1), text.replace(BACKUP_FORMAT, "netkit-backup-v2"), + text.replace("\"username\":", "\"password\":\"fixture\",\"username\":"), + text.replace("\"secureOnRequired\":", "\"secureOn\":\"fixture\",\"secureOnRequired\":"), + text.replace("\"knownHosts\":", "\"community\":\"fixture\",\"knownHosts\":"), + "[".repeat(128) + "]".repeat(128)) + for (input in samples) assertFails { decodeBackup(input.encodeToByteArray()) } + assertFails { decodeBackup(ByteArray(BACKUP_BYTES + 1)) } + assertFails { decodeBackup(byteArrayOf(0xc0.toByte())) } + assertFails { encodeBackup(file.copy(forwards = listOf(ForwardSettings("unknown", emptyList(), null)))) } + assertFails { encodeBackup(file.copy(servers = servers.copy(iperfPort = 65536))) } + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/cellular/CellDetailTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/cellular/CellDetailTest.kt new file mode 100644 index 0000000..3fd39d9 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/cellular/CellDetailTest.kt @@ -0,0 +1,277 @@ +package cz.netkit.shared.cellular + +import kotlin.test.Test +import kotlinx.coroutines.test.runTest +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class CellDetailTest { + private val u = CELL_UNAVAILABLE + + private fun lteSignal(rsrp: Int = u, rsrq: Int = u, rssnr: Int = u) = CellStrengthReading.Lte(rsrp, rsrq, rssnr, u, 0) + + private fun nrSignal(ssRsrp: Int = u, ssRsrq: Int = u, ssSinr: Int = u, csiRsrp: Int = u) = + CellStrengthReading.Nr(ssRsrp, ssRsrq, ssSinr, csiRsrp, u, u, 0) + + private fun lte( + registered: Boolean = false, status: Int = CellConnection.NONE, earfcn: Int = u, pci: Int = u, ci: Int = u, + tac: Int = u, bandwidth: Int = u, bands: List = emptyList(), rsrp: Int = u, rsrq: Int = u, rssnr: Int = u, ta: Int = u, + ) = CellInfoReading.Lte(registered, status, earfcn, pci, ci, tac, bandwidth, bands, lteSignal(rsrp, rsrq, rssnr), ta) + + private fun nr( + registered: Boolean = false, status: Int = CellConnection.NONE, arfcn: Int = u, pci: Int = u, + nci: Long = CELL_UNAVAILABLE_LONG, tac: Int = u, bands: List = emptyList(), rsrp: Int = u, ta: Int = u, + ) = CellInfoReading.Nr(registered, status, arfcn, pci, nci, tac, bands, nrSignal(ssRsrp = rsrp), ta) + + // --- LTE EARFCN → band (TS 36.101 Table 5.7.3-1) -------------------------------------------- + + @Test fun lteBandEdges() { + assertEquals(1, lteBandForEarfcn(0)) + assertEquals(1, lteBandForEarfcn(599)) + assertEquals(2, lteBandForEarfcn(600)) + assertEquals(3, lteBandForEarfcn(1_200)) + assertEquals(3, lteBandForEarfcn(1_949)) + assertEquals(7, lteBandForEarfcn(2_750)) + assertEquals(7, lteBandForEarfcn(3_449)) + assertEquals(8, lteBandForEarfcn(3_450)) + assertEquals(8, lteBandForEarfcn(3_799)) + assertEquals(20, lteBandForEarfcn(6_150)) + assertEquals(20, lteBandForEarfcn(6_449)) + assertEquals(28, lteBandForEarfcn(9_210)) + assertEquals(28, lteBandForEarfcn(9_659)) + assertEquals(32, lteBandForEarfcn(10_359)) + assertEquals(33, lteBandForEarfcn(36_000)) + assertEquals(38, lteBandForEarfcn(37_750)) + assertEquals(66, lteBandForEarfcn(67_335)) + assertEquals(67, lteBandForEarfcn(67_336)) + assertEquals(88, lteBandForEarfcn(70_645)) + } + + @Test fun lteEarfcnOutsideAnyBand() { + assertNull(lteBandForEarfcn(-1)) + assertNull(lteBandForEarfcn(5_009)) // gap between B11 and B12 + assertNull(lteBandForEarfcn(5_380)) // gap between B14 and B17 + assertNull(lteBandForEarfcn(10_360)) // after B32 until B33 + assertNull(lteBandForEarfcn(35_999)) + assertNull(lteBandForEarfcn(60_255)) + assertNull(lteBandForEarfcn(65_535)) + assertNull(lteBandForEarfcn(70_646)) + assertNull(lteBandForEarfcn(262_143)) + assertNull(lteBandForEarfcn(CELL_UNAVAILABLE)) + } + + @Test fun lteDownlinkFrequency() { + assertEquals(2_110_000, lteDownlinkKhz(0)) + assertEquals(2_169_900, lteDownlinkKhz(599)) + assertEquals(1_815_000, lteDownlinkKhz(1_300)) // B3: 1805 + 0.1 × 100 + assertEquals(806_000, lteDownlinkKhz(6_300)) // B20 + assertEquals(2_660_000, lteDownlinkKhz(3_150)) // B7 + assertEquals(426_900, lteDownlinkKhz(70_645)) // B88 top: 422 + 0.1 × 49 + assertNull(lteDownlinkKhz(5_009)) + } + + // --- NR-ARFCN → band and frequency (TS 38.104) --------------------------------------------- + + @Test fun nrBandsPreferEuropeanUseInOverlaps() { + assertEquals(listOf(78, 77), nrBandsForArfcn(620_000)) + assertEquals(listOf(78, 77), nrBandsForArfcn(653_333)) + assertEquals(listOf(77), nrBandsForArfcn(653_334)) + assertEquals(listOf(77), nrBandsForArfcn(680_000)) + assertEquals(listOf(78, 77, 48), nrBandsForArfcn(640_000)) + assertEquals(listOf(1, 65, 66), nrBandsForArfcn(422_000)) + assertEquals(listOf(65, 66), nrBandsForArfcn(434_001)) + assertEquals(listOf(28, 14), nrBandsForArfcn(151_600)) + assertEquals(listOf(20, 28), nrBandsForArfcn(158_200)) + assertEquals(listOf(20), nrBandsForArfcn(164_200)) + assertEquals(listOf(79), nrBandsForArfcn(693_334)) + assertEquals(listOf(79), nrBandsForArfcn(733_333)) + assertEquals(listOf(258), nrBandsForArfcn(2_016_667)) + assertEquals(listOf(260), nrBandsForArfcn(2_279_165)) + } + + @Test fun nrArfcnOutsideAnyBand() { + assertEquals(emptyList(), nrBandsForArfcn(0)) + assertEquals(emptyList(), nrBandsForArfcn(123_399)) + assertEquals(emptyList(), nrBandsForArfcn(680_001)) + assertEquals(emptyList(), nrBandsForArfcn(733_334)) + assertEquals(emptyList(), nrBandsForArfcn(3_279_165)) + assertEquals(emptyList(), nrBandsForArfcn(CELL_UNAVAILABLE)) + } + + @Test fun nrFrequencyOnGlobalRaster() { + assertEquals(0, nrFrequencyKhz(0)) + assertEquals(2_999_995, nrFrequencyKhz(599_999)) + assertEquals(3_000_000, nrFrequencyKhz(600_000)) + assertEquals(3_549_990, nrFrequencyKhz(636_666)) + assertEquals(24_249_990, nrFrequencyKhz(2_016_666)) + assertEquals(24_250_080, nrFrequencyKhz(2_016_667)) + assertEquals(99_999_960, nrFrequencyKhz(3_279_165)) + assertEquals(2_110_000, nrFrequencyKhz(422_000)) + assertNull(nrFrequencyKhz(-1)) + assertNull(nrFrequencyKhz(3_279_166)) + } + + @Test fun reportedBandWinsOverDerived() { + assertEquals(CellBand(CellTech.NR, 77), cellBand(CellTech.NR, listOf(77), 630_000)) + assertEquals(CellBand(CellTech.NR, 78, derived = true, ambiguous = true), cellBand(CellTech.NR, emptyList(), 630_000)) + assertEquals(CellBand(CellTech.NR, 79, derived = true), cellBand(CellTech.NR, emptyList(), 700_000)) + assertEquals(CellBand(CellTech.LTE, 3, derived = true), cellBand(CellTech.LTE, listOf(0, 300), 1_300)) + assertEquals(CellBand(CellTech.LTE, 20), cellBand(CellTech.LTE, listOf(20), 6_300)) + assertNull(cellBand(CellTech.LTE, emptyList(), null)) + assertNull(cellBand(CellTech.NR, emptyList(), 0)) + } + + @Test fun enodebSplit() { + assertEquals(48_225L, lteEnodeb(48_225L * 256 + 78)) + assertEquals(78, lteLocalCellId(48_225L * 256 + 78)) + assertEquals(1_048_575L, lteEnodeb(268_435_455L)) + assertEquals(255, lteLocalCellId(268_435_455L)) + } + + // --- Validation ------------------------------------------------------------------------------ + + @Test fun lteServingValidatesEveryField() { + val detail = cellDetailOf(listOf(lte(registered = true, status = CellConnection.PRIMARY_SERVING, earfcn = 1_300, + pci = 503, ci = 268_435_455, tac = 65_535, bandwidth = 20_000, rsrp = -95, rsrq = -11, rssnr = 12, ta = 1_282))) + assertEquals( + ServingCell(CellTech.LTE, true, CellBand(CellTech.LTE, 3, derived = true), 1_300, 1_815_000, 503, 268_435_455L, + 65_535, 20_000, 1_282, -95, -11, 12), + detail.serving.single(), + ) + val bad = cellDetailOf(listOf(lte(registered = true, earfcn = 262_144, pci = 504, ci = 268_435_456, tac = 65_536, + bandwidth = 1_399, rsrp = -141, rsrq = 4, rssnr = 31, ta = 1_283))).serving.single() + assertEquals(ServingCell(CellTech.LTE, true, null, null, null, null, null, null, null, null, null, null, null), bad) + val unavailable = cellDetailOf(listOf(lte(registered = true))).serving.single() + assertEquals(ServingCell(CellTech.LTE, true, null, null, null, null, null, null, null, null, null, null, null), unavailable) + assertEquals(1_400, cellDetailOf(listOf(lte(registered = true, bandwidth = 1_400))).serving.single().bandwidthKhz) + assertEquals(0, cellDetailOf(listOf(lte(registered = true, ta = 0, pci = 0, tac = 0, ci = 0))).serving.single().timingAdvance) + } + + @Test fun nrServingValidatesEveryField() { + val ok = cellDetailOf(listOf(nr(registered = true, arfcn = 636_666, pci = 1_007, nci = 68_719_476_735L, + tac = 16_777_215, bands = listOf(78), rsrp = -90, ta = 3_846))).serving.single() + assertEquals(ServingCell(CellTech.NR, true, CellBand(CellTech.NR, 78), 636_666, 3_549_990, 1_007, 68_719_476_735L, + 16_777_215, null, 3_846, -90, null, null), ok) + val bad = cellDetailOf(listOf(nr(registered = true, arfcn = 3_279_166, pci = 1_008, nci = 68_719_476_736L, + tac = 16_777_216, rsrp = -157, ta = 3_847))).serving.single() + assertEquals(ServingCell(CellTech.NR, true, null, null, null, null, null, null, null, null, null, null, null), bad) + val unavailable = cellDetailOf(listOf(nr(registered = true))).serving.single() + assertNull(unavailable.cellId) + assertNull(unavailable.arfcn) + assertNull(cellDetailOf(listOf(nr(registered = true, nci = -1))).serving.single().cellId) + } + + @Test fun nrCsiRsrpFallsBackLikeTheGauge() { + val reading = CellInfoReading.Nr(true, CellConnection.PRIMARY_SERVING, 636_666, 1, 1L, 1, emptyList(), + nrSignal(csiRsrp = -101), u) + assertEquals(-101, cellDetailOf(listOf(reading)).serving.single().rsrpDbm) + } + + // --- Serving vs neighbours ------------------------------------------------------------------- + + @Test fun nsaAnchorFirstThenSecondaryNrLeg() { + val detail = cellDetailOf(listOf( + nr(status = CellConnection.SECONDARY_SERVING, arfcn = 636_666, pci = 12, rsrp = -88), + lte(registered = true, status = CellConnection.PRIMARY_SERVING, earfcn = 1_300, pci = 100, rsrp = -95), + lte(earfcn = 6_300, pci = 7, rsrp = -100), + )) + assertEquals(listOf(CellTech.LTE to true, CellTech.NR to false), detail.serving.map { it.tech to it.primary }) + assertEquals(listOf(NeighborCell(CellTech.LTE, 7, 6_300, CellBand(CellTech.LTE, 20, derived = true), -100)), detail.neighbors) + assertNull(detail.otherRat) + } + + @Test fun unknownConnectionStatusIsNeighbourUnlessRegistered() { + val detail = cellDetailOf(listOf( + lte(registered = true, status = CellConnection.UNKNOWN, earfcn = 1_300, pci = 1), + lte(status = CellConnection.UNKNOWN, earfcn = 1_300, pci = 2, rsrp = -110), + )) + assertEquals(1, detail.serving.single().pci) + assertEquals(2, detail.neighbors.single().pci) + } + + @Test fun neighboursSortedStrongestFirstDedupedAndCapped() { + val cells = (0 until 30).map { lte(earfcn = 1_300, pci = it, rsrp = -140 + it) } + + lte(earfcn = 1_300, pci = 29, rsrp = -120) + // duplicate of the strongest, weaker copy + nr(arfcn = 636_666, pci = 5) + // no RSRP: after every measured cell + lte(earfcn = u, pci = u, rsrp = -50) // nothing to identify: dropped + val neighbors = cellDetailOf(cells).neighbors + assertEquals(CELL_DETAIL_MAX_NEIGHBORS, neighbors.size) + assertEquals((29 downTo 14).toList(), neighbors.map { it.pci }) + assertEquals(-111, neighbors.first().rsrpDbm) + val all = sortNeighbors(cellDetailOf(cells).neighbors + NeighborCell(CellTech.NR, 5, 636_666, null, null), limit = 100) + assertEquals(NeighborCell(CellTech.NR, 5, 636_666, null, null), all.last()) + } + + @Test fun neighbourTieBreakIsStable() { + val sorted = sortNeighbors(listOf( + NeighborCell(CellTech.NR, 3, 636_666, null, -90), + NeighborCell(CellTech.LTE, 9, 6_300, null, -90), + NeighborCell(CellTech.LTE, 4, 1_300, null, -90), + NeighborCell(CellTech.LTE, 2, 1_300, null, null), + )) + assertEquals(listOf(4, 9, 3, 2), sorted.map { it.pci }) + assertEquals(emptyList(), sortNeighbors(sorted, limit = -1)) + } + + @Test fun otherRatOnlyWithoutLteOrNrServing() { + val gsm = CellInfoReading.Other(true, CellConnection.PRIMARY_SERVING, CellRat.GSM) + assertEquals(CellRat.GSM, cellDetailOf(listOf(gsm, lte(earfcn = 1_300, pci = 1, rsrp = -100))).otherRat) + assertNull(cellDetailOf(listOf(gsm, lte(registered = true, earfcn = 1_300))).otherRat) + assertNull(cellDetailOf(listOf(CellInfoReading.Other(false, CellConnection.NONE, CellRat.UMTS))).otherRat) + assertTrue(cellDetailOf(emptyList()).isEmpty) + } + + // --- Refresh throttle ------------------------------------------------------------------------ + + @Test fun scheduleRespectsFiveSeconds() { + assertEquals(emptyList() to CELL_DETAIL_INTERVAL_MS, cellDetailSchedule(emptySet(), emptyMap(), 1_000)) + assertEquals(listOf(1, 2) to 5_000L, cellDetailSchedule(setOf(2, 1), emptyMap(), 1_000)) + assertEquals(emptyList() to 1_000L, cellDetailSchedule(setOf(1), mapOf(1 to 10_000L), 14_000)) + assertEquals(listOf(1) to 5_000L, cellDetailSchedule(setOf(1), mapOf(1 to 10_000L), 15_000)) + // SIM 2 was asked 2 s ago: only SIM 1 is due, the loop wakes up again for SIM 2 in 3 s. + assertEquals(listOf(1) to 3_000L, cellDetailSchedule(setOf(1, 2), mapOf(1 to 0L, 2 to 18_000L), 20_000)) + // A clock that went backwards does not block the refresh forever. + assertEquals(listOf(1) to 5_000L, cellDetailSchedule(setOf(1), mapOf(1 to 50_000L), 20_000)) + } + + // Revize kolo 1: the time of each SIM is taken right before its own request. + @Test fun slowFirstReadDoesNotBackdateTheSecondSim() = runTest { + var now = 0L + val last = mutableMapOf() + val requested = mutableListOf>() + val wait = cellDetailRefreshPass({ setOf(1, 2) }, last, { now }) { id -> + requested += id to now + if (id == 1) now += 3_000 // SIM 1 answers after 3 s + } + assertEquals(listOf(1 to 0L, 2 to 3_000L), requested) + assertEquals(mapOf(1 to 0L, 2 to 3_000L), last) + assertEquals(2_000L, wait) // SIM 1 is due at 5 s + // Only SIM 2 reopened at 5 s: 2 s after its request, it must wait until 8 s. + now = 5_000 + assertEquals(emptyList() to 3_000L, cellDetailSchedule(setOf(2), last, now)) + val again = mutableListOf() + assertEquals(3_000L, cellDetailRefreshPass({ setOf(2) }, last, { now }) { again += it }) + assertEquals(emptyList(), again) + now = 8_000 + assertEquals(5_000L, cellDetailRefreshPass({ setOf(2) }, last, { now }) { again += it }) + assertEquals(listOf(2), again) + } + + @Test fun refreshPassSkipsHiddenSimsAndReportsDueOnes() = runTest { + var now = 0L + var shown = setOf(1, 2) + val last = mutableMapOf() + val requested = mutableListOf() + // SIM 2 is hidden while SIM 1 is being read: it is not requested. + cellDetailRefreshPass({ shown }, last, { now }) { id -> requested += id; shown = setOf(1); now += 1_000 } + assertEquals(listOf(1), requested) + assertEquals(CELL_DETAIL_INTERVAL_MS, cellDetailRefreshPass({ emptySet() }, last, { now }) { requested += it }) + // A newly shown SIM that was never requested is due at once (wait 0) when the pass skipped it. + shown = setOf(1, 3) + now = 2_000 + val wait = cellDetailRefreshPass({ shown }, last, { now }) { id -> requested += id; if (id == 3) shown = setOf(1, 3, 4) } + assertEquals(listOf(1, 3), requested) + assertEquals(0L, wait) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/ConsentResetGateTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/ConsentResetGateTest.kt new file mode 100644 index 0000000..933a979 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/ConsentResetGateTest.kt @@ -0,0 +1,65 @@ +package cz.netkit.shared.lan + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +/** + * Interleavings of a network load (onWifi → load → publish) with "forget all consents" (revize kolo 2). + * The load read ALLOWED from the store each time; only a load that did not overlap a reset keeps it. + */ +class ConsentResetGateTest { + private val allowed = DiscoveryConsent.ALLOWED + private val unknown = DiscoveryConsent.UNKNOWN + + @Test fun loadStartedBeforeResetAndPublishedDuringIt() { + val gate = ConsentResetGate() + val stamp = gate.loadStarted() + gate.begin() + assertEquals(unknown, gate.publishable(stamp, allowed)) + gate.end() + } + + @Test fun loadStartedBeforeResetAndPublishedAfterIt() { + // The reported race: load read ALLOWED, the reset ran while `current` was null, then the load published. + val gate = ConsentResetGate() + val stamp = gate.loadStarted() + gate.begin(); gate.end() + assertEquals(unknown, gate.publishable(stamp, allowed)) + } + + @Test fun loadStartedDuringResetIsDiscardedEvenAfterIt() { + // It may have read the store before the write was committed. + val gate = ConsentResetGate() + gate.begin() + val stamp = gate.loadStarted() + assertEquals(unknown, gate.publishable(stamp, allowed)) + gate.end() + assertEquals(unknown, gate.publishable(stamp, allowed)) + } + + @Test fun loadAfterResetPublishesWhatItRead() { + val gate = ConsentResetGate() + gate.begin(); gate.end() + val stamp = gate.loadStarted() + assertEquals(allowed, gate.publishable(stamp, allowed)) + assertEquals(DiscoveryConsent.DENIED, gate.publishable(stamp, DiscoveryConsent.DENIED)) + } + + @Test fun withoutResetNothingChanges() { + val gate = ConsentResetGate() + assertEquals(allowed, gate.publishable(gate.loadStarted(), allowed)) + } + + @Test fun overlappingResets() { + val gate = ConsentResetGate() + gate.begin() + gate.begin() + gate.end() + val during = gate.loadStarted() + assertEquals(unknown, gate.publishable(during, allowed), "one reset still running") + gate.end() + assertEquals(allowed, gate.publishable(gate.loadStarted(), allowed)) + assertFailsWith { gate.end() } + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRcodeTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRcodeTest.kt new file mode 100644 index 0000000..2368627 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRcodeTest.kt @@ -0,0 +1,13 @@ +package cz.netkit.shared.lan + +import kotlin.test.* + +class DnsRcodeTest { + @Test fun assignedAndUnknownCodes() { + assertEquals("NOERROR", dnsRcodeName(0)) + assertEquals("SERVFAIL", dnsRcodeName(2)) + assertEquals("NXDOMAIN", dnsRcodeName(3)) + assertEquals("REFUSED", dnsRcodeName(5)) + assertNull(dnsRcodeName(4094)) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRecordsTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRecordsTest.kt new file mode 100644 index 0000000..54a12c6 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRecordsTest.kt @@ -0,0 +1,54 @@ +package cz.netkit.shared.lan + +import kotlin.test.* + +class DnsRecordsTest { + private val owner = "example.test" + private fun answer(type: Int, bytes: DnsWire): ByteArray { + val data = bytes.build() + val message = DnsWire().header(qd = 1, an = 1, flags = 0x8780).name(owner).u16(type).u16(1) + message.pointer(12).rr(type, data.size, klass = 1, ttl = 0xffffffffL) + return message.build() + data + } + + @Test fun allTypesUnknownUnsignedTtlAndCompressedOwnersAndTargets() { + val records = listOf( + Triple(1, DnsWire().raw(192, 0, 2, 1), "192.0.2.1"), + Triple(28, DnsWire().u16(0x2001).u16(0xdb8).u32(0).u32(0).u32(1), "2001:db8::1"), + Triple(2, DnsWire().pointer(12), owner), Triple(5, DnsWire().pointer(12), owner), + Triple(12, DnsWire().pointer(12), owner), Triple(15, DnsWire().u16(10).pointer(12), "10 $owner"), + Triple(16, DnsWire().label("one").label("two"), "\"one\" \"two\""), + Triple(33, DnsWire().u16(1).u16(2).u16(443).pointer(12), "1 2 443 $owner"), + Triple(6, DnsWire().pointer(12).pointer(12).u32(0xffffffffL).u32(2).u32(3).u32(4).u32(5), + "$owner $owner 4294967295 2 3 4 5"), + Triple(257, DnsWire().u8(0).label("issue").raw(*owner.map(Char::code).toIntArray()), "0 issue $owner"), + Triple(65000, DnsWire().raw(0, 255), "00ff"), + ) + for ((type, data, expected) in records) { + val reply = assertNotNull(parseRecordReply(answer(type, data))) + assertEquals(RecordAnswer(owner, type, 4294967295, expected), reply.records.single()) + assertEquals(0x8780, reply.flags) + assertEquals(0, reply.rcode) + } + } + + @Test fun rejectsShortSectionsInvalidRdataAndCompressionCycle() { + val good = answer(5, DnsWire().pointer(12)) + for (len in 0 until good.size) assertNull(parseRecordReply(good.copyOf(len))) + assertNull(parseRecordReply(DnsWire().header(an = 1).pointer(12).rr(1, 4).u32(0).build())) + assertNull(parseRecordReply(answer(5, DnsWire().pointer(12).u8(0)))) + assertNull(parseRecordReply(answer(257, DnsWire().u8(0).u8(20).u8(0)))) + assertNull(parseRecordReply(answer(6, DnsWire().pointer(12)))) + assertEquals(3, parseRecordReply(DnsWire().header(flags = 0x8383).build())?.rcode) + } + + @Test fun namesForPtrAndServiceLookups() { + // Reverse of the documentation address 192.0.2.1 (RFC 5737), derived to keep the literal readable. + assertEquals("192.0.2.1".split('.').reversed().joinToString(".") + ".in-addr.arpa", + recordQueryName("192.0.2.1", RecordType.PTR)) + assertEquals("1" + ".0".repeat(23) + ".8.b.d.0.1.0.0.2.ip6.arpa", recordQueryName("2001:db8::1", RecordType.PTR)) + assertEquals("_x._tcp.example.test.", recordQueryName("_x._tcp.example.test.", RecordType.SRV)) + assertNull(recordQueryName("two names", RecordType.A)) + assertNull(recordQueryName("a".repeat(64), RecordType.A)) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/Icmpv6EchoTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/Icmpv6EchoTest.kt new file mode 100644 index 0000000..8aaf161 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/Icmpv6EchoTest.kt @@ -0,0 +1,31 @@ +package cz.netkit.shared.lan + +import kotlin.test.Test +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class Icmpv6EchoTest { + private fun request() = ByteArray(24) { (it * 5).toByte() }.apply { this[0] = ICMPV6_ECHO_REQUEST.toByte(); this[1] = 0 } + private fun reply(request: ByteArray) = request.copyOf().apply { this[0] = ICMPV6_ECHO_REPLY.toByte() } + + @Test fun replyMatchesDespiteKernelIdentifierAndChecksum() { + val request = request() + val response = reply(request).copyOf(64) + for (index in 2..5) response[index] = (response[index] + 3).toByte() + assertTrue(matchesIcmpv6EchoReply(request, response, request.size)) + } + @Test fun ipv4TypesWrongBytesAndLengthsDoNotMatch() { + val request = request() + assertFalse(matchesIcmpv6EchoReply(request, request, request.size)) // own request (type 128) + assertFalse(matchesIcmpv6EchoReply(request, reply(request).apply { this[0] = 0 }, request.size)) // IPv4 echo reply type + for (index in listOf(1) + (6 until request.size)) { + val response = reply(request); response[index] = (response[index] + 1).toByte() + assertFalse(matchesIcmpv6EchoReply(request, response, request.size), "index=$index") + } + for (length in listOf(-1, 0, 8, 23, 25)) assertFalse(matchesIcmpv6EchoReply(request, reply(request).copyOf(64), length), "length=$length") + assertFalse(matchesIcmpEchoReply(request, reply(request), request.size)) // IPv4 matcher never accepts ICMPv6 + val empty = ByteArray(8).apply { this[0] = ICMPV6_ECHO_REQUEST.toByte() } + assertFalse(matchesIcmpv6EchoReply(empty, reply(empty), 8)) + assertTrue(matchesIcmpv6EchoReply(empty, reply(empty), 8, allowEmptyPayload = true)) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/Ipv6Test.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/Ipv6Test.kt new file mode 100644 index 0000000..4445d8f --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/Ipv6Test.kt @@ -0,0 +1,83 @@ +package cz.netkit.shared.lan + +import kotlin.test.* + +class Ipv6Test { + @Test fun shortenedFormsZoneAndBracketsParse() { + assertEquals("::1", Ipv6Address.parse("::1")!!.canonical) + assertEquals("::", Ipv6Address.parse("::")!!.canonical) + assertEquals("2001:db8::1", Ipv6Address.parse("2001:0DB8:0000:0000:0000:0000:0000:0001")!!.canonical) + assertEquals("2001:db8:0:1::1", Ipv6Address.parse("2001:db8:0:1:0:0:0:1")!!.canonical) + // RFC 5952 4.2.2: a single zero group is not shortened; 4.2.3: the first of equal runs wins. + assertEquals("2001:db8:0:1:1:1:1:1", Ipv6Address.parse("2001:db8::1:1:1:1:1")!!.canonical) + assertEquals("2001:db8::1:0:0:1", Ipv6Address.parse("2001:db8:0:0:1:0:0:1")!!.canonical) + val zoned = Ipv6Address.parse("fe80::1%wlan0")!! + assertEquals("wlan0", zoned.zone) + assertEquals("fe80::1%wlan0", zoned.toString()) + assertEquals(Ipv6Scope.LINK_LOCAL, zoned.scope) + assertEquals("fe80::1", Ipv6Address.parse("[fe80::1]")!!.canonical) + assertEquals(Ipv6Address.parse("fe80::1%wlan0"), Ipv6Address.parse("[fe80:0::1%wlan0]")) + } + + @Test fun invalidLiteralsAndHostnamesAreRejected() { + listOf("", ":", ":::", "1::2::3", "12345::1", "g::1", "1:2:3:4:5:6:7:8:9", "1:2:3:4:5:6:7", "fe80::1%", "fe80::1%wl an0", + "fe80::1%" + "x".repeat(16), "[::1", "::1]", "localhost", "192.168.1.1", "::ffff:192.0.2", "192.0.2.4::", "::1/64") + .forEach { assertNull(Ipv6Address.parse(it), it) } + } + + @Test fun ipv4MappedBecomesIpv4() { + val mapped = Ipv6Address.parse("::ffff:192.168.1.10")!! + assertEquals(Ipv6Scope.IPV4_MAPPED, mapped.scope) + assertEquals("192.168.1.10", mapped.mappedIpv4) + assertEquals(LanNumericAddress.V4("192.168.1.10"), lanNumericAddress("::ffff:c0a8:010a")) + assertEquals(LanNumericAddress.V4("10.0.0.1"), lanNumericAddress(" 10.0.0.1 ")) + assertNull(lanNumericAddress("router.lan")) + assertEquals("::1", (lanNumericAddress("0:0:0:0:0:0:0:1") as LanNumericAddress.V6).text) + } + + @Test fun classification() { + mapOf("::" to Ipv6Scope.UNSPECIFIED, "::1" to Ipv6Scope.LOOPBACK, "fe80::abcd" to Ipv6Scope.LINK_LOCAL, + "febf::1" to Ipv6Scope.LINK_LOCAL, "fec0::1" to Ipv6Scope.GLOBAL, "fd12:3456::1" to Ipv6Scope.UNIQUE_LOCAL, + "fc00::1" to Ipv6Scope.UNIQUE_LOCAL, "ff02::1" to Ipv6Scope.MULTICAST, "2001:db8::5" to Ipv6Scope.DOCUMENTATION, + "2001:db9::5" to Ipv6Scope.GLOBAL) + .forEach { (text, scope) -> assertEquals(scope, Ipv6Address.parse(text)!!.scope, text) } + } + + @Test fun prefixesMaskAndContain() { + val prefix = Ipv6Prefix.parse("fd00:1:2:3:4::9/64")!! + assertEquals("fd00:1:2:3::/64", prefix.toString()) + assertTrue(prefix.contains(Ipv6Address.parse("fd00:1:2:3::99")!!)) + assertFalse(prefix.contains(Ipv6Address.parse("fd00:1:2:4::99")!!)) + val odd = Ipv6Prefix.parse("2001:db8:ff00::/39")!! + assertTrue(odd.contains(Ipv6Address.parse("2001:db8:ff00::1")!!)) + assertTrue(odd.contains(Ipv6Address.parse("2001:db8:ff01::1")!!)) + assertTrue(odd.contains(Ipv6Address.parse("2001:db8:fe00::1")!!)) + assertFalse(odd.contains(Ipv6Address.parse("2001:db8:fc00::1")!!)) + assertTrue(Ipv6Prefix.parse("::/0")!!.contains(Ipv6Address.parse("2001:db8::1")!!)) + listOf("fd00::/129", "fd00::", "fd00::/", "fd00::/-1", "fe80::1%wlan0/64", "fd00::/0x10").forEach { assertNull(Ipv6Prefix.parse(it), it) } + } + + @Test fun targetsAndConfirmation() { + assertTrue(validLanTarget("fe80::1%wlan0")) + assertTrue(validLanTarget("[2001:db8::1]")) + assertTrue(validLanTarget("router.lan")) + assertTrue(validLanTarget("192.168.1.1")) + assertFalse(validLanTarget("::")) + assertFalse(validLanTarget("ff02::1")) + assertFalse(validLanTarget("1::2::3")) + assertFalse(validLanTarget("192.168.1.256")) + + val own = listOf(Ipv6Prefix.parse("fd00:1::/64")!!, Ipv6Prefix.parse("2001:db8:1::/64")!!) + fun reasons(text: String, prefixes: List? = own, ports: Int = 0) = + ipv6TargetConfirmationReasons(Ipv6Address.parse(text)!!, prefixes, ports) + assertEquals(emptySet(), reasons("fe80::1%wlan0")) + assertEquals(emptySet(), reasons("fe80::1", prefixes = null)) + assertEquals(emptySet(), reasons("fd00:1::20")) + assertEquals(setOf(TargetConfirmationReason.NON_PRIVATE_ADDRESS), reasons("2001:db8:1::20")) + assertEquals(setOf(TargetConfirmationReason.OUTSIDE_WIFI), reasons("fd00:2::20")) + assertEquals(setOf(TargetConfirmationReason.OUTSIDE_WIFI, TargetConfirmationReason.NON_PRIVATE_ADDRESS), reasons("2001:db8:2::20")) + assertEquals(setOf(TargetConfirmationReason.OUTSIDE_WIFI), reasons("::1")) + assertEquals(setOf(TargetConfirmationReason.OUTSIDE_WIFI), reasons("fd00:1::20", prefixes = null)) + assertEquals(setOf(TargetConfirmationReason.LARGE_PORT_SET), reasons("fd00:1::20", ports = 255)) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDeviceExportTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDeviceExportTest.kt new file mode 100644 index 0000000..4158c71 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDeviceExportTest.kt @@ -0,0 +1,57 @@ +package cz.netkit.shared.lan + +import kotlinx.serialization.json.Json +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class LanDeviceExportTest { + private val devices = listOf( + LanDevice("192.168.1.20", names = listOf(LanDeviceName(LanNameSource.MDNS, "=HYPERLINK(\"x\")"), LanDeviceName(LanNameSource.PTR, "nas.lan")), + firstSeenElapsedMs = 0, lastSeenElapsedMs = 50_000, lastRttMs = 1.234, method = LanAliveMethod.ICMP, + openPorts = listOf(OpenPort(22, banner = "SSH-2.0-Open\u001b[31mSSH\nInjected: line")), netBiosMac = "AA-BB-CC-00-11-22", + upnp = LanUpnpInfo(friendlyName = "NAS\u202E", manufacturer = "Example", modelName = "DS", modelNumber = "220+")), + LanDevice("192.168.1.1", isGateway = true, firstSeenElapsedMs = 0, lastSeenElapsedMs = 59_000, method = LanAliveMethod.TCP), + LanDevice("192.168.1.50", isSelf = true, firstSeenElapsedMs = 0, lastSeenElapsedMs = 60_000, method = LanAliveMethod.SELF, stale = false), + ) + + @Test fun rowsAreSortedSanitizedAndRelative() { + val rows = lanDeviceExportRows(devices, nowElapsedMs = 60_000) + assertEquals(listOf("192.168.1.1", "192.168.1.20", "192.168.1.50"), rows.map { it.address }) + val nas = rows[1] + assertEquals("mdns", nas.nameSource) + assertEquals("nas.lan", nas.ptr) + assertEquals("AA:BB:CC:00:11:22", nas.mac) + assertEquals(1.2, nas.rttMs) + assertEquals(10, nas.lastSeenAgoS) + val banner = nas.openPorts.single().banner!! + assertFalse(banner.any { it == '\u001b' || it == '\n' }, "control characters are replaced") + assertFalse('\u202E' in nas.upnpName!!, "bidi override is replaced") + assertEquals("DS 220+", nas.upnpModel) + assertNull(rows[0].name, "an address-only device has no name") + } + + @Test fun csvGuardsFormulasAndQuotes() { + val csv = exportLanDevices(devices, LanExport.CSV, 60_000, "2026-12-02T10:00:00.000Z") + val lines = csv.trimEnd().lines() + assertEquals(4, lines.size) + assertTrue(lines[0].startsWith("address,name,nameSource")) + assertTrue("\"'=HYPERLINK(\"\"x\"\")\"" in lines[2], lines[2]) + assertTrue("\"22/SSH\"" in lines[2]) + } + + @Test fun jsonRoundTripsAndTextHasOneBlockPerDevice() { + val json = exportLanDevices(devices, LanExport.JSON, 60_000, "2026-12-02T10:00:00.000Z", network = "192.168.1.0/24") + val document = Json.decodeFromString(LanDevicesExportDocument.serializer(), json) + assertEquals(LAN_DEVICES_EXPORT_FORMAT, document.format) + assertEquals("192.168.1.0/24", document.network) + assertEquals(3, document.devices.size) + val text = exportLanDevices(devices, LanExport.TEXT, 60_000, "2026-12-02T10:00:00.000Z") + assertTrue(text.startsWith("NetKit devices · 2026-12-02T10:00:00.000Z\n")) + assertTrue("192.168.1.1 · gateway\n" in text) + assertTrue("192.168.1.50 · self\n" in text) + assertEquals(1, text.lines().count { it.startsWith(" banner 22:") }, "a banner stays on one line") + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanNetworkInfoTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanNetworkInfoTest.kt new file mode 100644 index 0000000..91b2f56 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanNetworkInfoTest.kt @@ -0,0 +1,56 @@ +package cz.netkit.shared.lan + +import kotlin.test.* + +class LanNetworkInfoTest { + private fun info( + dhcpSupported: Boolean = true, dhcp: String? = "192.168.1.1", mtu: Int = 1500, + ipv6: List = listOf("2001:db8:1:0:0:0:0:10/64", "fd00:1::10/64", "fe80::10%wlan0/64"), + domains: String? = "home.lan corp.example", + ) = LanNetworkInfo("wlan0", "192.168.1.30", 24, listOf("192.168.1.1", "fe80::1%wlan0"), listOf("192.168.1.1", "fd00:1::1"), + domains, dhcpSupported, dhcp, mtu, ipv6) + + @Test fun fullLinkFormatsEveryRowInOrder() { + val rows = lanNetworkInfoRows(info()) + assertEquals(LanNetworkInfoField.entries, rows.map { it.field }) + val byField = rows.associateBy { it.field } + assertEquals(listOf("wlan0"), byField.getValue(LanNetworkInfoField.INTERFACE).values) + assertEquals(listOf("192.168.1.30/24"), byField.getValue(LanNetworkInfoField.IPV4).values) + assertEquals(listOf("192.168.1.1", "fe80::1"), byField.getValue(LanNetworkInfoField.GATEWAY).values) + assertEquals(listOf("192.168.1.1", "fd00:1::1"), byField.getValue(LanNetworkInfoField.DNS).values) + assertEquals(listOf("home.lan", "corp.example"), byField.getValue(LanNetworkInfoField.DOMAINS).values) + assertEquals(listOf("192.168.1.1"), byField.getValue(LanNetworkInfoField.DHCP).values) + assertEquals(listOf("1500"), byField.getValue(LanNetworkInfoField.MTU).values) + assertEquals(listOf("2001:db8:1::10/64"), byField.getValue(LanNetworkInfoField.IPV6_GLOBAL).values) + assertEquals(listOf("fd00:1::10/64"), byField.getValue(LanNetworkInfoField.IPV6_ULA).values) + assertEquals(listOf("fe80::10/64"), byField.getValue(LanNetworkInfoField.IPV6_LINK_LOCAL).values) + } + + @Test fun missingFactsUseExplicitStates() { + val rows = lanNetworkInfoRows(info(dhcpSupported = false, dhcp = null, mtu = 0, ipv6 = emptyList(), domains = null)).associateBy { it.field } + assertEquals(LanNetworkInfoValue.UNAVAILABLE, rows.getValue(LanNetworkInfoField.DHCP).state) + assertEquals(LanNetworkInfoValue.UNKNOWN, rows.getValue(LanNetworkInfoField.MTU).state) + assertEquals(LanNetworkInfoValue.NONE, rows.getValue(LanNetworkInfoField.DOMAINS).state) + assertFalse(LanNetworkInfoField.IPV6_GLOBAL in rows) + assertFalse(LanNetworkInfoField.IPV6_LINK_LOCAL in rows) + // API 30+ without a lease server (static address): NONE, not UNAVAILABLE. + assertEquals(LanNetworkInfoValue.NONE, lanNetworkInfoRows(info(dhcp = null)).first { it.field == LanNetworkInfoField.DHCP }.state) + assertEquals(LanNetworkInfoValue.NONE, lanNetworkInfoRows(info(dhcp = "0.0.0.0")).first { it.field == LanNetworkInfoField.DHCP }.state) + assertEquals(LanNetworkInfoValue.UNKNOWN, lanNetworkInfoRows(LanNetworkInfo(null, null, null, emptyList(), emptyList(), null, true, null, -1, emptyList())) + .first { it.field == LanNetworkInfoField.INTERFACE }.state) + } + + @Test fun untrustedValuesAreFilteredAndBounded() { + val hostile = LanNetworkInfo("wlan0", "not-an-ip", 24, listOf("x", "192.168.1.1", "192.168.1.1"), + List(20) { "10.0.0.${it + 1}" }, "ok.lan bad\u0007name -bad.lan", true, "999.1.1.1", 9000, + listOf("fe80::1/64", "garbage/64", "fd00::1/129", "fd00::2")) + val rows = lanNetworkInfoRows(hostile).associateBy { it.field } + assertEquals(LanNetworkInfoValue.NONE, rows.getValue(LanNetworkInfoField.IPV4).state) + assertEquals(listOf("192.168.1.1"), rows.getValue(LanNetworkInfoField.GATEWAY).values) + assertEquals(LAN_NETWORK_INFO_MAX_VALUES, rows.getValue(LanNetworkInfoField.DNS).values.size) + assertEquals(listOf("ok.lan"), rows.getValue(LanNetworkInfoField.DOMAINS).values) + assertEquals(LanNetworkInfoValue.NONE, rows.getValue(LanNetworkInfoField.DHCP).state) + assertEquals(listOf("fe80::1/64"), rows.getValue(LanNetworkInfoField.IPV6_LINK_LOCAL).values) + assertFalse(LanNetworkInfoField.IPV6_ULA in rows) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanRevisionTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanRevisionTest.kt index aee8e9c..bca9745 100644 --- a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanRevisionTest.kt +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanRevisionTest.kt @@ -4,6 +4,16 @@ import kotlinx.serialization.json.* import kotlin.test.* class LanRevisionTest { + @Test fun dfSizeFailureHasReadableDetailInEveryExport() { + val rows = appendPingResult(emptyList(), "192.0.2.1", 1, 0, null, dfTooLarge = true) + assertTrue(rows.single().dfTooLarge) + val ordinaryLoss = appendPingResult(emptyList(), "192.0.2.1", 1, 0, null) + for (format in LanExport.entries) { + assertTrue("Packet too large with DF set" in exportLan(rows, format)) + assertFalse("Packet too large with DF set" in exportLan(ordinaryLoss, format)) + } + } + @Test fun confirmationBoundariesAndReasons() { val own=Ipv4Subnet.parse("10.0.0.0/16")!! val small=Ipv4Subnet.parse("10.0.0.0/24")!! diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanWolTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanWolTest.kt new file mode 100644 index 0000000..db618e4 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanWolTest.kt @@ -0,0 +1,81 @@ +package cz.netkit.shared.lan + +import cz.netkit.shared.wol.TargetMode +import cz.netkit.shared.wol.WolDevice +import cz.netkit.shared.wol.WolDeviceDraft +import cz.netkit.shared.wol.validateDevice +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** "Probudit" vs "Přidat do WoL" on the LAN device card (zadání 36 AC-005); documentation IPs, test MACs. */ +class LanWolTest { + private fun lan(address: String, vararg names: LanDeviceName, mac: String? = null, self: Boolean = false) = + LanDevice(address, names = names.toList(), firstSeenElapsedMs = 0, lastSeenElapsedMs = 0, method = LanAliveMethod.ICMP, + isSelf = self, netBiosMac = mac) + private fun wol(id: String, probeHost: String?) = + WolDevice(id, "PC $id", "02:00:5E:10:00:01", TargetMode.AUTO_BROADCAST, probeHost = probeHost, createdAt = 1, updatedAt = 1) + + private fun wake(vararg ids: String) = LanWolAction.Wake(ids.map { LanWolCandidate(it, "PC $it") }) + + @Test fun matchingProbeHostOffersWake() { + val saved = listOf(wol("a", "192.0.2.9"), wol("b", "192.0.2.10")) + assertEquals(wake("b"), lanWolAction(lan("192.0.2.10"), saved)) + // By name only when no device has the exact address: NetBIOS/mDNS/PTR, case and ".local" insensitive. + val named = lan("192.0.2.20", LanDeviceName(LanNameSource.NETBIOS, "PRACOVNA"), LanDeviceName(LanNameSource.MDNS, "nas")) + assertEquals(wake("n"), lanWolAction(named, listOf(wol("n", "pracovna")))) + assertEquals(wake("m"), lanWolAction(named, listOf(wol("m", "NAS.local")))) + assertEquals(wake("t"), lanWolAction(named, listOf(wol("t", " nas. ")))) + } + + @Test fun exactAddressOutranksAnUntrustedName() { + // Host B announces the name of profile A; profile B has B's exact IP → only B is offered. + val hostB = lan("192.0.2.11", LanDeviceName(LanNameSource.NETBIOS, "PC-A")) + assertEquals(wake("b"), lanWolAction(hostB, listOf(wol("a", "pc-a"), wol("b", "192.0.2.11")))) + // Only names match, but two saved devices: both offered, the user picks by the named button. + assertEquals(wake("a", "c"), lanWolAction(hostB, listOf(wol("a", "pc-a"), wol("c", "PC-A.local"), wol("x", "192.0.2.99")))) + // Two devices with the same exact address: both offered. + assertEquals(wake("p", "q"), lanWolAction(lan("192.0.2.12"), listOf(wol("p", "192.0.2.12"), wol("q", "192.0.2.12")))) + // A name equal to some other address does not count as that address. + assertEquals(wake("r"), lanWolAction(lan("192.0.2.13", LanDeviceName(LanNameSource.PTR, "192.0.2.14")), + listOf(wol("r", "192.0.2.13"), wol("s", "192.0.2.14")))) + } + + @Test fun exactMatchIsAParsedAddressNotANormalizedName() { + // A profile whose hostname only looks like the address after dropping ".local" is not an exact match. + val host = lan("192.0.2.11") + assertEquals(wake("ip"), lanWolAction(host, listOf(wol("fake", "192.0.2.11.local"), wol("ip", "192.0.2.11")))) + assertIs(lanWolAction(host, listOf(wol("fake", "192.0.2.11.local")))) + // Nor does it match a host that announces the address as its name. + val named = lan("192.0.2.12", LanDeviceName(LanNameSource.PTR, "192.0.2.11")) + assertIs(lanWolAction(named, listOf(wol("fake", "192.0.2.11.local"), wol("x", "192.0.2.11")))) + // Leading zeros or spaces in a saved IPv4 still compare as the same address. + assertEquals(wake("sp"), lanWolAction(host, listOf(wol("sp", " 192.0.2.11 ")))) + } + + @Test fun otherwiseAddPrefillsAddressNameAndNetBiosMac() { + val windows = lan("192.0.2.30", LanDeviceName(LanNameSource.NETBIOS, "HERNI-PC"), mac = "02:00:5e:10:ab:cd") + val add = assertIs(lanWolAction(windows, listOf(wol("x", "192.0.2.31"), wol("y", null)))) + assertEquals(WolDeviceDraft(name = "HERNI-PC", mac = "02:00:5E:10:AB:CD", probeHost = "192.0.2.30"), add.draft) + // The prefilled draft is a valid device once the user saves it. + assertTrue(validateDevice(add.draft).isValid) + // No name and no NetBIOS MAC: the IP as name, MAC left for the user (Android 10+ has no ARP access). + val bare = assertIs(lanWolAction(lan("192.0.2.40"), emptyList())) + assertEquals(WolDeviceDraft(name = "192.0.2.40", mac = "", probeHost = "192.0.2.40"), bare.draft) + } + + @Test fun thePhoneItselfHasNoWolAction() { + assertNull(lanWolAction(lan("192.0.2.2", self = true), listOf(wol("p", "192.0.2.2")))) + } + + @Test fun netBiosMacIsStoredOnlyWhenValid() { + val base = listOf(lan("192.0.2.50")) + assertEquals("02:00:5E:10:AB:CD", updateLanDeviceNames(base, "192.0.2.50", emptyList(), netBiosMac = "02-00-5E-10-AB-CD").single().netBiosMac) + assertNull(updateLanDeviceNames(base, "192.0.2.50", emptyList(), netBiosMac = "not a mac").single().netBiosMac) + // A later reply without MAC keeps the earlier one. + val kept = updateLanDeviceNames(updateLanDeviceNames(base, "192.0.2.50", emptyList(), netBiosMac = "02:00:5E:10:AB:CD"), "192.0.2.50", emptyList()) + assertEquals("02:00:5E:10:AB:CD", kept.single().netBiosMac) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/MacAddressTableTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/MacAddressTableTest.kt new file mode 100644 index 0000000..c5faca0 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/MacAddressTableTest.kt @@ -0,0 +1,116 @@ +package cz.netkit.shared.lan + +import cz.netkit.shared.wifi.OuiDatabase +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** Synthetic outputs; MACs from the RFC 7042 documentation block 00-00-5E-00-53-xx unless a flag is tested. */ +class MacAddressTableTest { + private val oui = OuiDatabase.parse("00005E\t24\tICANN, IANA Department\n0050C2\t24\tIEEE Registration Authority\n") + + @Test fun singleAddressInEveryAcceptedFormat() { + for (input in listOf("0000.5e00.5301", "0000-5E00-5301", "00:00:5e:00:53:01", "00-00-5E-00-53-01", " 00:00:5E:00:53:01\n")) { + val found = extractMacAddresses(input).macs.single() + assertEquals("00:00:5E:00:53:01", found.text, input) + assertEquals(0x00005E005301L, found.value) + } + } + + @Test fun ciscoMacAddressTable() { + val output = """ + | Mac Address Table + |------------------------------------------- + | + |Vlan Mac Address Type Ports + |---- ----------- -------- ----- + | All 0100.0ccc.cccc STATIC CPU + | 10 0000.5e00.5301 DYNAMIC Gi1/0/1 + | 10 0000.5e00.5302 DYNAMIC Gi1/0/2 + | 20 0000.5e00.5301 DYNAMIC Po1 + |Total Mac Addresses for this criterion: 4 + """.trimMargin() + val macs = extractMacAddresses(output).macs + assertEquals(listOf("01:00:0C:CC:CC:CC", "00:00:5E:00:53:01", "00:00:5E:00:53:02"), macs.map { it.text }) + assertEquals(listOf(1, 2, 1), macs.map { it.occurrences }) + assertTrue(macs[0].multicast) + } + + @Test fun huaweiDisplayMacAddress() { + val output = """ + |MAC address table of slot 0: + |------------------------------------------------------------------------------- + |MAC Address VLAN/ PEVLAN CEVLAN Port Type LSP/LSR-ID + | VSI/SI MAC-Tunnel + |------------------------------------------------------------------------------- + |0000-5e00-5303 10 - - GE0/0/1 dynamic 0/- + |0200-5e00-5304 10 - - GE0/0/2 dynamic 0/- + |------------------------------------------------------------------------------- + |Total matching items on slot 0 displayed = 2 + """.trimMargin() + val macs = extractMacAddresses(output).macs + assertEquals(listOf("00:00:5E:00:53:03", "02:00:5E:00:53:04"), macs.map { it.text }) + assertTrue(macs[1].locallyAdministered && !macs[1].multicast) + } + + @Test fun mikrotikBridgeHostPrint() { + val output = """ + |Flags: X - disabled, I - invalid, D - dynamic, L - local, E - external + | # MAC-ADDRESS VID ON-INTERFACE BRIDGE AGE + | 0 D 00:00:5E:00:53:05 ether2 bridge1 2s + | 1 DL 00:00:5E:00:53:06 bridge1 bridge1 + | 2 D 33:33:00:00:00:01 ether3 bridge1 1m + """.trimMargin() + val macs = extractMacAddresses(output).macs + assertEquals(listOf("00:00:5E:00:53:05", "00:00:5E:00:53:06", "33:33:00:00:00:01"), macs.map { it.text }) + assertTrue(macs[2].multicast && macs[2].locallyAdministered) + } + + @Test fun lookalikesAreNotMacs() { + val text = listOf( + "aa:bb:cc:dd:ee:ff:11", // seven groups + "2001:db8:0:1:2:3", // IPv6-like, groups not two digits + "fe80::200:5eff:fe00:5301", // IPv6 with an embedded MAC + "deadbeef0000.5e00.5301", // glued to hex + "0000.5e00.5301.0001", // a longer dotted run + "00:00:5e:00:53-01", // mixed separators + "00005e005301", // bare hex is not accepted + "0000.5e00.53g1", // not hex + "::00:00:5e:00:53:01", // compressed IPv6 ending in six two-digit groups + "fe80::00:00:5e:00:53:01", // the same after a prefix + "00:00:5e:00:53:01::", // compressed IPv6 starting with them + "00:00:5e:00:53:01::1", + "--00-00-5e-00-53-01", // dash runs on either side + "0000.5e00.5301..", + ).joinToString("\n") + assertEquals(emptyList(), extractMacAddresses(text).macs) + // Ordinary punctuation after an address is fine. + assertEquals(listOf("00:00:5E:00:53:07"), extractMacAddresses("MAC 00:00:5e:00:53:07, port 3.").macs.map { it.text }) + // A single separator followed by a space or the line end is punctuation, not more address. + assertEquals(listOf("00:00:5E:00:53:08", "00:00:5E:00:53:09"), + extractMacAddresses("(00:00:5e:00:53:08: up)\n0000.5e00.5309.").macs.map { it.text }) + } + + @Test fun inputLimits() { + val atLimit = "0000.5e00.5301\n".repeat(MAC_INPUT_MAX_LINES) + assertEquals(null, extractMacAddresses(atLimit).error) + assertEquals(MacInputError.TOO_MANY_LINES, extractMacAddresses(atLimit + "x").error) + assertEquals(MacInputError.TOO_LARGE, extractMacAddresses("a".repeat(MAC_INPUT_MAX_BYTES + 1)).error) + // Bytes, not chars: 32 769 two-byte chars are 64 KiB + 2 B. + assertEquals(MacInputError.TOO_LARGE, extractMacAddresses("é".repeat(MAC_INPUT_MAX_BYTES / 2 + 1)).error) + assertEquals(emptyList(), extractMacAddresses("a".repeat(MAC_INPUT_MAX_BYTES + 1)).macs) + } + + @Test fun vendorRowsAndExport() { + val macs = extractMacAddresses("0000.5e00.5301 0200.5e00.5302 0100.5e00.0001 0050.c200.0001 0000.5e00.5301 ac00.0000.0001").macs + val rows = macVendorRows(macs, oui) + assertEquals(listOf("ICANN, IANA Department", null, null, "IEEE Registration Authority", null), rows.map { it.vendor }) + val export = macExportRows(rows) + assertEquals("count=2", export[0].detail) + assertEquals("locally-administered", export[1].detail) + assertEquals("multicast", export[2].detail) + assertEquals("", export[4].detail) + val csv = exportLan(export, LanExport.CSV) + assertTrue("\"00:00:5E:00:53:01\",\"ICANN, IANA Department\",\"OUI\"" in csv, csv) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/ManagementPortsTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/ManagementPortsTest.kt new file mode 100644 index 0000000..17ce1e7 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/ManagementPortsTest.kt @@ -0,0 +1,14 @@ +package cz.netkit.shared.lan + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class ManagementPortsTest { + @Test fun presetIncludesLabeledManagementPortsInOrder() { + assertEquals(commonPorts.distinct().sorted(), commonPorts) + for (port in listOf(830, 8291, 8728, 8729, 10443)) { + assertTrue(port in commonPorts && portService(port).isNotBlank()) + } + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/NetBiosParserTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/NetBiosParserTest.kt index 66a1630..67f619d 100644 --- a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/NetBiosParserTest.kt +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/NetBiosParserTest.kt @@ -11,13 +11,13 @@ class NetBiosParserTest { private fun response( id: Int = 0x1234, flags: Int = 0x8400, qd: Int = 0, an: Int = 1, type: Int = 0x21, klass: Int = 1, entries: List, rawNames: List? = null, countOverride: Int? = null, rdLengthOverride: Int? = null, - pointerName: Boolean = false, + pointerName: Boolean = false, statistics: ByteArray = ByteArray(46), ): ByteArray { val rr = if (pointerName) byteArrayOf(0xC0.toByte(), 0x0C) else netBiosNodeStatusRequest(0).copyOfRange(12, 46) val names = entries.mapIndexed { index, entry -> (rawNames?.get(index) ?: nameBytes(entry.name)) + byteArrayOf(entry.suffix.toByte(), (entry.flags shr 8).toByte(), entry.flags.toByte()) }.fold(ByteArray(0)) { acc, bytes -> acc + bytes } - val rdata = byteArrayOf((countOverride ?: entries.size).toByte()) + names + ByteArray(46) + val rdata = byteArrayOf((countOverride ?: entries.size).toByte()) + names + statistics val rdLength = rdLengthOverride ?: rdata.size val header = byteArrayOf((id shr 8).toByte(), id.toByte(), (flags shr 8).toByte(), flags.toByte(), 0, qd.toByte(), 0, an.toByte(), 0, 0, 0, 0) @@ -121,4 +121,33 @@ class NetBiosParserTest { val long = parseNetBiosNodeStatus(response(entries = listOf(Entry("ABCDEFGHIJKLMNOPQ", 0x00, 0x0400))), 0x1234) assertEquals("ABCDEFGHIJKLMNO", long?.name) } + + private fun mac(vararg octets: Int) = ByteArray(6) { octets[it].toByte() } + ByteArray(40) + + @Test fun unitIdBecomesMacOnlyWhenUnicastAndNonZero() { + // Locally administered unicast test MAC (02:…); Windows puts the adapter MAC here. + val windows = assertNotNull(parseNetBiosNodeStatus(response(entries = typical, statistics = mac(0x02, 0x00, 0x5E, 0x10, 0xAB, 0xCD)), 0x1234)) + assertEquals("02:00:5E:10:AB:CD", windows.mac) + assertEquals("NAS-DOMA", windows.name) + // Samba usually reports zeros: no MAC suggestion. + assertNull(parseNetBiosNodeStatus(response(entries = typical), 0x1234)?.mac) + // Multicast / broadcast bit → null. + assertNull(parseNetBiosNodeStatus(response(entries = typical, statistics = mac(0x01, 0x00, 0x5E, 0x00, 0x00, 0x01)), 0x1234)?.mac) + assertNull(parseNetBiosNodeStatus(response(entries = typical, statistics = mac(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF)), 0x1234)?.mac) + } + + @Test fun truncatedStatisticsKeepNamesWithoutMac() { + // RDATA (and packet) end 3 bytes into UNIT_ID: names are complete, MAC is not trusted. + val short = assertNotNull(parseNetBiosNodeStatus(response(entries = typical, statistics = byteArrayOf(0x02, 0x00, 0x5E)), 0x1234)) + assertEquals("NAS-DOMA", short.name) + assertNull(short.mac) + // Exactly 6 bytes of statistics are enough for the UNIT_ID. + assertEquals("02:00:5E:10:AB:CD", parseNetBiosNodeStatus(response(entries = typical, + statistics = byteArrayOf(0x02, 0x00, 0x5E, 0x10, 0xAB.toByte(), 0xCD.toByte())), 0x1234)?.mac) + // A packet cut inside the declared RDATA is still rejected as a whole. + val full = response(entries = typical, statistics = mac(0x02, 0x00, 0x5E, 0x10, 0xAB, 0xCD)) + assertNull(parseNetBiosNodeStatus(full.copyOf(full.size - 10), 0x1234)) + assertEquals(listOf(null, null, "02:00:5E:10:AB:CD"), listOf(ByteArray(5), ByteArray(6), byteArrayOf(2, 0, 0x5E, 0x10, 0xAB.toByte(), 0xCD.toByte())) + .map { netBiosUnitIdMac(it) }) + } } diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/SubnetCalculatorTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/SubnetCalculatorTest.kt new file mode 100644 index 0000000..8af5ce2 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/SubnetCalculatorTest.kt @@ -0,0 +1,84 @@ +package cz.netkit.shared.lan + +import kotlin.test.* + +class SubnetCalculatorTest { + @Test fun prefixAndHostBoundaries() { + for ((input, first, last) in listOf( + Triple("0.0.0.0/0", "0.0.0.1", "255.255.255.254"), + Triple("10.2.3.4/8", "10.0.0.1", "10.255.255.254"), + Triple("192.0.2.12/24", "192.0.2.1", "192.0.2.254"), + Triple("192.0.2.5/30", "192.0.2.5", "192.0.2.6"), + Triple("255.255.255.255/31", "255.255.255.254", "255.255.255.255"), + Triple("255.255.255.255/32", "255.255.255.255", "255.255.255.255"), + )) { + val result = assertNotNull(calculateSubnet(input)) + assertEquals(first, result.firstHost) + assertEquals(last, result.lastHost) + assertEquals(ipv4Number(last)!! - ipv4Number(first)!! + 1, result.subnet.hostCount) + assertEquals(result.subnet.prefix >= 31, result.broadcast == null) + } + } + + @Test fun equivalentInputsAndInvalidMask() { + val cidr = assertNotNull(calculateSubnet("192.0.2.10/27")) + assertEquals(cidr, calculateSubnet("192.0.2.10 255.255.255.224")) + assertEquals(cidr, calculateSubnet("192.0.2.10 0.0.0.31")) + assertEquals(cidr, calculateSubnet("192.0.2.10/255.255.255.224")) + assertNull(calculateSubnet("192.0.2.10/255.0.255.0")) + assertEquals("192.0.2.0/27", cidr.subnet.toString()) + assertEquals("192.0.2.31", cidr.broadcast) + assertEquals("0.0.0.31", cidr.wildcard) + assertEquals("255.255.255.224", cidr.mask) + assertNull(calculateSubnet("192.0.2.10 255.0.255.0")) + } + + @Test fun splitIsBoundedEvenForEntireAddressSpace() { + assertEquals(listOf(0, 64, 128, 192).map { "192.0.2.$it/26" }, + calculateSubnet("192.0.2.10/24")!!.split(26)!!.rows.map { it.toString() }) + val split = calculateSubnet("0.0.0.0/0")!!.split(32)!! + assertEquals(256, split.rows.size) + assertEquals(4294967040L, split.remaining) + assertNull(calculateSubnet("192.0.2.8/30")!!.split(24)) + } + + @Test fun ambiguousDottedMasksExposeBothInterpretations() { + for ((suffix, prefix) in listOf("0.0.0.0" to 0, "255.255.255.255" to 32)) { + for (separator in listOf(" ", "/")) { + val input = "192.0.2.10$separator$suffix" + val mask = assertNotNull(calculateSubnet(input)) + assertEquals(prefix, mask.subnet.prefix) + assertEquals(MaskInterpretation.NETMASK, mask.ambiguousInterpretation) + val wildcard = assertNotNull(calculateSubnet(input, MaskInterpretation.WILDCARD)) + assertEquals(32 - prefix, wildcard.subnet.prefix) + assertEquals(MaskInterpretation.WILDCARD, wildcard.ambiguousInterpretation) + } + } + assertNull(calculateSubnet("192.0.2.10/32")!!.ambiguousInterpretation) + } + + @Test fun partialOverlapsClassifyTheWholeSubnetAsMixed() { + for (input in listOf("172.16.0.0/11", "100.64.0.0/9", "100.127.255.254/9", "0.0.0.0/0")) { + assertEquals(AddressRange.MIXED, calculateSubnet(input)?.range, input) + } + assertEquals(AddressRange.PRIVATE, calculateSubnet("172.16.0.0/12")?.range) + assertEquals(AddressRange.CGNAT, calculateSubnet("100.64.0.0/10")?.range) + } + + @Test fun addressClassUsesOriginalAddressEvenInASupernet() { + for ((octet, expected) in mapOf(127 to AddressClass.A, 128 to AddressClass.B, 191 to AddressClass.B, + 192 to AddressClass.C, 223 to AddressClass.C, 224 to AddressClass.D, 239 to AddressClass.D, + 240 to AddressClass.E, 255 to AddressClass.E)) { + assertEquals(expected, calculateSubnet("$octet.0.0.1/0")?.addressClass) + } + } + + @Test fun classifyHostSubnets() { + for ((address, range) in mapOf("172.31.0.1" to AddressRange.PRIVATE, "100.127.1.1" to AddressRange.CGNAT, + "0.0.0.0" to AddressRange.OTHER, "169.254.1.1" to AddressRange.LINK_LOCAL, + "127.2.3.4" to AddressRange.LOOPBACK, "239.255.255.255" to AddressRange.MULTICAST, + "203.0.113.255" to AddressRange.DOCUMENTATION)) { + assertEquals(range, calculateSubnet("$address/32")?.range) + } + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/TcpPingTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/TcpPingTest.kt new file mode 100644 index 0000000..38f67da --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/TcpPingTest.kt @@ -0,0 +1,42 @@ +package cz.netkit.shared.lan + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull + +class TcpPingTest { + @Test fun optionsValidatePortAndCount() { + assertEquals(TcpPingOptions(443, 10), tcpPingOptions("443", "10")) + assertEquals(TcpPingOptions(22, null), tcpPingOptions(" 22 ", "")) + assertEquals(TcpPingOptions(65535, TCP_PING_MAX_COUNT), tcpPingOptions("65535", "1000")) + listOf("0" to "1", "65536" to "1", "-1" to "1", "443" to "1", "" to "1", "443" to "0", "443" to "1001", "443" to "1e3", "443" to "-5") + .forEach { (port, count) -> assertNull(tcpPingOptions(port, count), "$port/$count") } + } + + @Test fun rowsAndStatisticsCountOnlyCompletedHandshakes() { + var rows = emptyList() + val outcomes = listOf(12.0 to ProbeStatus.OPEN, null to ProbeStatus.TIMEOUT, 14.0 to ProbeStatus.OPEN, + 3.0 to ProbeStatus.REFUSED, 10.0 to ProbeStatus.OPEN) + outcomes.forEachIndexed { index, (rtt, status) -> + rows = appendTcpPingResult(rows, "192.0.2.80", 443, index + 1L, index * TCP_PING_INTERVAL_MS, rtt, status) + } + assertEquals(listOf(12.0, null, 14.0, null, 10.0), rows.map { it.milliseconds }) + assertEquals(listOf("", "TIMEOUT", "", "REFUSED", ""), rows.map { it.detail }) + assertEquals(setOf("TCP"), rows.map { it.method }.toSet()) + assertEquals(setOf(443), rows.map { it.port }.toSet()) + val stats = pingStatistics(rows.map { it.milliseconds }) + assertEquals(5, stats.sent); assertEquals(3, stats.received); assertEquals(40.0, stats.lossPercent) + assertEquals(10.0, stats.minimum); assertEquals(12.0, stats.average); assertEquals(14.0, stats.maximum) + // Jitter only between consecutive replies: |12-14| is not adjacent (a loss in between), none are. + assertNull(stats.jitter) + assertFailsWith { appendTcpPingResult(rows, "192.0.2.80", 443, 5, 9000, 1.0, ProbeStatus.OPEN) } + } + + @Test fun keepsTheNewest600Rows() { + var rows = emptyList() + for (sequence in 1L..605L) rows = appendTcpPingResult(rows, "192.0.2.80", 22, sequence, sequence, 1.0, ProbeStatus.OPEN) + assertEquals(600, rows.size) + assertEquals(6L, rows.first().sequence) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/ToolTargetsTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/ToolTargetsTest.kt new file mode 100644 index 0000000..16d378d --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/ToolTargetsTest.kt @@ -0,0 +1,90 @@ +package cz.netkit.shared.lan + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertTrue +import kotlinx.serialization.json.Json + +class ToolTargetsTest { + private fun ToolTargets.starred(value: String, label: String = "") = assertIs(star(value, label)).targets + + @Test fun recentIsMostRecentFirstDeduplicatedAndLimitedToTen() { + var targets = ToolTargets() + (1..12).forEach { targets = targets.remember("192.0.2.$it") } + assertEquals((12 downTo 3).map { "192.0.2.$it" }, targets.recent) + targets = targets.remember(" 192.0.2.5 ") + assertEquals("192.0.2.5", targets.recent.first()) + assertEquals(TARGET_RECENT_LIMIT, targets.recent.size) + assertEquals(1, targets.recent.count { it == "192.0.2.5" }) + // Hostnames compare without case; the newest spelling wins. + targets = targets.remember("Router.Example.COM").remember("router.example.com") + assertEquals(listOf("router.example.com"), targets.recent.filter { it.equals("router.example.com", true) }) + } + + @Test fun invalidValuesAreNeverStored() { + val empty = ToolTargets() + listOf("", " ", "host name", "a\u0000b", "bad‮host", "x".repeat(TARGET_VALUE_LIMIT + 1), "host;rm", "ftp://example.com/") + .forEach { assertEquals(empty, empty.remember(it), it); assertIs(empty.star(it), it) } + } + + @Test fun urlHistoryDropsQueryAndFragmentButFavouriteKeepsWhatWasStarred() { + val url = "https://example.com/status?token=abc#top" + val targets = ToolTargets().remember(url) + assertEquals(listOf("https://example.com/status"), targets.recent) + assertEquals(url, targets.starred(url).favorites.single().value) + } + + @Test fun favouritesHaveLabelsLimitAndUnstar() { + var targets = ToolTargets() + (1..TARGET_FAVORITE_LIMIT).forEach { targets = targets.starred("198.51.100.$it", "AP $it") } + assertEquals(TARGET_FAVORITE_LIMIT, targets.favorites.size) + assertIs(targets.star("203.0.113.1")) + // Renaming an existing favourite is allowed at the limit. + targets = targets.starred("198.51.100.1", " Core\nswitch " + "x".repeat(60)) + val renamed = targets.favorites.first() + assertEquals("198.51.100.1", renamed.value) + assertEquals(TARGET_LABEL_LIMIT, renamed.label.length) + assertTrue(renamed.label.startsWith("Core switch")) + assertTrue(targets.isFavorite("198.51.100.1")) + targets = targets.unstar("198.51.100.1") + assertFalse(targets.isFavorite("198.51.100.1")) + assertEquals(TARGET_FAVORITE_LIMIT - 1, targets.favorites.size) + } + + @Test fun suggestionsAreSharedButFilteredByWhatTheToolAccepts() { + val targets = ToolTargets() + .remember("192.0.2.10").remember("example.com").remember("https://example.com/").remember("AS13335").remember("AS64511").remember("2001:db8::1") + .starred("gw.example.net", "Brána").starred("8.8.8.8") + fun values(field: TargetField) = targets.suggestions(field).map { it.value } + assertEquals(listOf("gw.example.net", "8.8.8.8", "2001:db8::1", "example.com", "192.0.2.10"), values(TargetField.HOST)) + assertEquals(listOf("gw.example.net", "8.8.8.8", "2001:db8::1", "example.com", "192.0.2.10"), values(TargetField.DNS_NAME)) + assertEquals(listOf("https://example.com/"), values(TargetField.URL)) + // RDAP takes public IPs and ASNs only (documentation ranges and private ASNs are refused); + // an ASN is never offered as a hostname. + assertEquals(listOf("8.8.8.8", "AS13335"), values(TargetField.RDAP)) + val first = targets.suggestions(TargetField.HOST).first() + assertEquals(TargetSuggestion("gw.example.net", "Brána", true), first) + // A favourite is not repeated among recent entries. + assertEquals(1, targets.remember("8.8.8.8").suggestions(TargetField.HOST).count { it.value == "8.8.8.8" }) + } + + @Test fun clearHistoryKeepsFavourites() { + val targets = ToolTargets().remember("192.0.2.1").starred("192.0.2.2").clearHistory() + assertEquals(emptyList(), targets.recent) + assertEquals(listOf("192.0.2.2"), targets.favorites.map { it.value }) + } + + @Test fun storedDataIsNormalizedWhenRead() { + val stored = """{"recent":[${(1..15).joinToString(",") { "\"192.0.2.$it\"" }},"192.0.2.1","bad host","https://example.com/a?x=1"], + |"favorites":[${(1..35).joinToString(",") { "{\"value\":\"198.51.100.$it\",\"label\":\"L\\u0007$it\"}" }},{"value":"198.51.100.1"}]}""".trimMargin() + val targets = Json.decodeFromString(stored).normalized() + assertEquals((1..10).map { "192.0.2.$it" }, targets.recent) + assertEquals(TARGET_FAVORITE_LIMIT, targets.favorites.size) + assertEquals("L 1", targets.favorites.first().label) + assertEquals(targets, targets.normalized()) + // Round trip through the serializer the DataStore uses. + assertEquals(targets, Json.decodeFromString(Json.encodeToString(ToolTargets.serializer(), targets))) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/lan/UdpServicesCodecTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/UdpServicesCodecTest.kt new file mode 100644 index 0000000..bf1443a --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/lan/UdpServicesCodecTest.kt @@ -0,0 +1,200 @@ +package cz.netkit.shared.lan + +import kotlin.test.* +import kotlinx.coroutines.test.runTest + +/** Synthetic packets only: SNMP BER, NTP and version.bind parsers over valid, short, long and nested input. */ +class UdpServicesCodecTest { + private val community = "s3cret-lab".encodeToByteArray() + + // --- Tiny BER writer for synthetic responses --------------------------------------------- + private fun tlv(tag: Int, content: ByteArray): ByteArray = when { + content.size < 0x80 -> byteArrayOf(tag.toByte(), content.size.toByte()) + content + content.size <= 0xff -> byteArrayOf(tag.toByte(), 0x81.toByte(), content.size.toByte()) + content + else -> byteArrayOf(tag.toByte(), 0x82.toByte(), (content.size shr 8).toByte(), content.size.toByte()) + content + } + private fun int(value: Int) = tlv(0x02, if (value in 0..127) byteArrayOf(value.toByte()) + else byteArrayOf((value ushr 24).toByte(), (value ushr 16).toByte(), (value ushr 8).toByte(), value.toByte())) + private fun oid(vararg arcs: Int): ByteArray { + val body = mutableListOf((arcs[0] * 40 + arcs[1]).toByte()) + arcs.drop(2).forEach { arc -> if (arc < 128) body += arc.toByte() else { body += (0x80 or (arc shr 7)).toByte(); body += (arc and 0x7f).toByte() } } + return tlv(0x06, body.toByteArray()) + } + private fun seq(vararg parts: ByteArray) = tlv(0x30, parts.fold(ByteArray(0)) { a, b -> a + b }) + private fun response(id: Int, vararg bindings: ByteArray, status: Int = 0, version: Int = 1, pduTag: Int = 0xA2, communityBytes: ByteArray = community) = + seq(int(version), tlv(0x04, communityBytes), tlv(pduTag, int(id) + int(status) + int(0) + seq(*bindings))) + private fun text(value: String) = tlv(0x04, value.encodeToByteArray()) + private val descr = intArrayOf(1, 3, 6, 1, 2, 1, 1, 1, 0) + private val name = intArrayOf(1, 3, 6, 1, 2, 1, 1, 5, 0) + + @Test fun snmpRequestIsCanonicalBer() { + val request = encodeSnmpGet(community, 0x1234, listOf(SNMP_SYS_DESCR, SNMP_SYS_NAME)) + val expected = seq(int(1), tlv(0x04, community), tlv(0xA0, tlv(0x02, byteArrayOf(0x12, 0x34)) + int(0) + int(0) + + seq(seq(oid(*descr), tlv(0x05, ByteArray(0))), seq(oid(*name), tlv(0x05, ByteArray(0)))))) + assertContentEquals(expected, request) + // Minimal two's complement: 128 needs a leading zero byte, 0x7f does not. + assertContentEquals(byteArrayOf(0x02, 0x02, 0x00, 0x80.toByte()), encodeSnmpGet(community, 128, listOf(SNMP_SYS_NAME)).copyOfRange(19, 23)) + } + + @Test fun snmpValidResponse() { + val packet = response(77, seq(oid(*descr), text("RouterOS RB5009 \u0007")), seq(oid(*name), text("gw-lab"))) + val parsed = assertNotNull(parseSnmpResponse(packet, packet.size, community, 77)) + assertEquals(0, parsed.errorStatus) + assertEquals(listOf(SnmpVarBind(SNMP_SYS_DESCR, "RouterOS RB5009"), SnmpVarBind(SNMP_SYS_NAME, "gw-lab")), parsed.varBinds) + // noSuchObject [80] is a value without text, not an error. + val missing = response(77, seq(oid(*name), tlv(0x80, ByteArray(0)))) + assertEquals(listOf(SnmpVarBind(SNMP_SYS_NAME, null)), parseSnmpResponse(missing, missing.size, community, 77)!!.varBinds) + // Long form length (0x81) is accepted. + val long = response(77, seq(oid(*descr), text("x".repeat(200)))) + assertEquals("x".repeat(200), parseSnmpResponse(long, long.size, community, 77)!!.varBinds.single().text) + } + + @Test fun snmpForeignOrWrongResponsesAreRejected() { + val binding = seq(oid(*name), text("gw")) + assertNull(parseSnmpResponse(response(78, binding), response(78, binding).size, community, 77), "request id") + assertNull(response(77, binding, communityBytes = "other".encodeToByteArray()).let { parseSnmpResponse(it, it.size, community, 77) }, "community") + assertNull(response(77, binding, version = 0).let { parseSnmpResponse(it, it.size, community, 77) }, "v1") + assertNull(response(77, binding, pduTag = 0xA0).let { parseSnmpResponse(it, it.size, community, 77) }, "GetRequest echo") + val good = response(77, binding) + assertNull(parseSnmpResponse(good + byteArrayOf(0), good.size + 1, community, 77), "trailing byte") + } + + @Test fun snmpTruncatedTooLongAndDeepInputFailClosed() { + val good = response(77, seq(oid(*descr), text("RouterOS"))) + for (length in 0 until good.size) assertNull(parseSnmpResponse(good, length, community, 77), "truncated $length") + assertNull(parseSnmpResponse(good, good.size + 1, community, 77), "length beyond array") + val huge = response(77, seq(oid(*descr), text("y".repeat(SNMP_MAX_DATAGRAM_BYTES)))) + assertTrue(huge.size > SNMP_MAX_DATAGRAM_BYTES) + assertNull(parseSnmpResponse(huge, huge.size, community, 77), "over the datagram limit") + // Indefinite length and a length field of 3 bytes. + assertNull(parseSnmpResponse(byteArrayOf(0x30, 0x80.toByte(), 0, 0), 4, community, 77)) + assertNull(parseSnmpResponse(byteArrayOf(0x30, 0x83.toByte(), 0, 0, 1, 0), 6, community, 77)) + // Deeply nested constructed value: rejected without recursion over the data. + var nested = text("deep") + repeat(500) { nested = seq(nested) } + val deep = response(77, seq(oid(*descr), nested)) + assertNull(parseSnmpResponse(deep, minOf(deep.size, deep.size), community, 77)) + var deepMessage = good + repeat(2000) { deepMessage = byteArrayOf(0x30, 0x82.toByte(), (deepMessage.size shr 8).toByte(), deepMessage.size.toByte()) + deepMessage.take(0xffff).toByteArray() } + assertNull(parseSnmpResponse(deepMessage, deepMessage.size, community, 77)) + // Element claiming more than its parent. + val lying = good.copyOf().also { it[it.size - 9] = 0x7f } + assertNull(parseSnmpResponse(lying, lying.size, community, 77)) + } + + // --- NTP --------------------------------------------------------------------------------- + private val nonce = byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8) + private fun ntpReply(stratum: Int, refId: ByteArray, mode: Int = 4, version: Int = 4, leap: Int = 0, origin: ByteArray = nonce, size: Int = 48) = + ByteArray(size).also { + it[0] = ((leap shl 6) or (version shl 3) or mode).toByte(); it[1] = stratum.toByte() + refId.copyInto(it, 12); origin.copyInto(it, 24) + } + + @Test fun ntpRequestAndValidReplies() { + val request = ntpRequest(nonce) + assertEquals(48, request.size); assertEquals(0x23, request[0].toInt()) + assertContentEquals(nonce, request.copyOfRange(40, 48)) + assertEquals(NtpReply(4, 2, false, NtpReferenceKind.UPSTREAM_ADDRESS, "192.0.2.1"), + parseNtpReply(ntpReply(2, byteArrayOf(192.toByte(), 0, 2, 1)), 48, nonce)) + assertEquals(NtpReply(4, 1, false, NtpReferenceKind.SOURCE, "GPS"), parseNtpReply(ntpReply(1, "GPS\u0000".encodeToByteArray()), 48, nonce)) + assertEquals(NtpReferenceKind.KISS_CODE to "RATE", parseNtpReply(ntpReply(0, "RATE".encodeToByteArray()), 48, nonce)!!.let { it.referenceKind to it.reference }) + val unsynced = parseNtpReply(ntpReply(16, ByteArray(4), leap = 3), 48, nonce)!! + assertTrue(unsynced.leapUnsynchronized); assertNull(unsynced.reference) + assertNull(parseNtpReply(ntpReply(1, byteArrayOf(1, 2, 3, 4)), 48, nonce)!!.reference, "non-printable code") + assertNotNull(parseNtpReply(ntpReply(2, ByteArray(4), size = 68), 68, nonce), "extension/MAC allowed") + } + + @Test fun ntpForeignShortAndLongRepliesAreRejected() { + assertNull(parseNtpReply(ntpReply(2, ByteArray(4), mode = 3), 48, nonce), "client echo") + assertNull(parseNtpReply(ntpReply(2, ByteArray(4), mode = 5), 48, nonce), "broadcast") + assertNull(parseNtpReply(ntpReply(2, ByteArray(4), version = 0), 48, nonce)) + assertNull(parseNtpReply(ntpReply(2, ByteArray(4), origin = ByteArray(8)), 48, nonce), "other origin") + assertNull(parseNtpReply(ntpReply(17, ByteArray(4)), 48, nonce), "reserved stratum") + assertNull(parseNtpReply(ntpReply(2, ByteArray(4)), 47, nonce), "truncated") + assertNull(parseNtpReply(ntpReply(2, ByteArray(4)), 49, nonce), "beyond array") + assertNull(parseNtpReply(ntpReply(2, ByteArray(4), size = NTP_MAX_DATAGRAM_BYTES + 1), NTP_MAX_DATAGRAM_BYTES + 1, nonce), "too long") + } + + // --- version.bind ------------------------------------------------------------------------ + private fun dnsReply(id: Int, rcode: Int = 0, txt: List = listOf("9.18.0-lab"), qname: List = listOf("version", "bind"), klass: Int = 3, qr: Boolean = true): ByteArray { + val question = qname.flatMap { listOf(it.length.toByte()) + it.encodeToByteArray().toList() }.toByteArray() + byteArrayOf(0, 0, 16, 0, klass.toByte()) + val answer = if (txt.isEmpty()) ByteArray(0) else { + val data = txt.flatMap { listOf(it.length.toByte()) + it.encodeToByteArray().toList() }.toByteArray() + byteArrayOf(0xC0.toByte(), 12, 0, 16, 0, klass.toByte(), 0, 0, 0, 0, 0, data.size.toByte()) + data + } + val flags = (if (qr) 0x8000 else 0) or rcode + return byteArrayOf((id shr 8).toByte(), id.toByte(), (flags shr 8).toByte(), flags.toByte(), 0, 1, 0, if (txt.isEmpty()) 0 else 1, 0, 0, 0, 0) + question + answer + } + + @Test fun versionBindQueryAndReplies() { + val query = versionBindQuery(0x0102) + val parsed = parseDnsMessage(query)!! + assertEquals(DNS_CLASS_CH, parsed.questions.single().dnsClass) + assertEquals(DNS_TYPE_TXT, parsed.questions.single().type) + assertEquals("version.bind", parsed.questions.single().name.text) + assertEquals(VersionBindReply(0, "9.18.0-lab"), dnsReply(0x0102).let { parseVersionBind(it, it.size, 0x0102) }) + assertEquals(VersionBindReply(0, "ab"), dnsReply(0x0102, txt = listOf("a", "b")).let { parseVersionBind(it, it.size, 0x0102) }) + assertEquals(VersionBindReply(5, null), dnsReply(0x0102, rcode = 5, txt = emptyList()).let { parseVersionBind(it, it.size, 0x0102) }) + assertNull(dnsReply(0x0103).let { parseVersionBind(it, it.size, 0x0102) }, "other id") + assertNull(dnsReply(0x0102, qr = false).let { parseVersionBind(it, it.size, 0x0102) }, "query, not response") + assertNull(dnsReply(0x0102, qname = listOf("version", "server")).let { parseVersionBind(it, it.size, 0x0102) }, "other question") + assertEquals(VersionBindReply(0, null), dnsReply(0x0102, klass = 1).let { parseVersionBind(it, it.size, 0x0102) }, "IN answer is ignored") + val good = dnsReply(0x0102) + for (length in 0 until good.size) assertNull(parseVersionBind(good, length, 0x0102), "truncated $length") + assertNull(parseVersionBind(ByteArray(DNS_MAX_DATAGRAM_BYTES + 1), DNS_MAX_DATAGRAM_BYTES + 1, 0), "too long") + // Compression loop in the question name: a forward/self pointer is refused by the codec. + val loop = good.copyOf().also { it[12] = 0xC0.toByte(); it[13] = 12 } + assertNull(parseVersionBind(loop, loop.size, 0x0102)) + } + + // --- Orchestration ------------------------------------------------------------------------- + @Test fun probesRetryOnceSkipWithoutCommunityAndReportClosedPorts() = runTest { + val sent = mutableMapOf() + val ports = UdpServicePorts(16161, 11123, 10053) + val exchange = UdpExchange { port, payload, timeout, accept -> + assertEquals(UDP_PROBE_TIMEOUT_MS, timeout) + val attempt = (sent[port] ?: 0) + 1 + sent[port] = attempt + when (port) { + // NTP answers the second attempt only; a garbage datagram is not accepted. + 11123 -> if (attempt == 1) { assertFalse(accept(ByteArray(48), 48)); UdpReply.Timeout } else { + val reply = ntpReply(3, byteArrayOf(10, 0, 0, 1), origin = payload.copyOfRange(40, 48)) + assertTrue(accept(reply, reply.size)); UdpReply.Data(reply) + } + 10053 -> UdpReply.Refused + else -> error("SNMP must not be sent without a community") + } + } + val result = probeUdpServices(exchange, community = ByteArray(0), dnsAllowed = true, randomBytes = { ByteArray(it) { 9 } }, ports = ports) + assertEquals(UdpProbeOutcome.SKIPPED, result.snmp.outcome) + assertEquals(UdpProbeOutcome.OK, result.ntp.outcome) + assertEquals("10.0.0.1", result.ntp.reply!!.reference) + assertEquals(UdpProbeOutcome.CLOSED, result.dns.outcome) + assertEquals(mapOf(11123 to 2, 10053 to 1), sent) + + val silent = probeUdpServices({ _, _, _, _ -> UdpReply.Timeout }, community, dnsAllowed = false, randomBytes = { ByteArray(it) }, ports = ports) + assertEquals(listOf(UdpProbeOutcome.NO_REPLY, UdpProbeOutcome.NO_REPLY, UdpProbeOutcome.SKIPPED), + listOf(silent.snmp.outcome, silent.ntp.outcome, silent.dns.outcome)) + } + + @Test fun snmpErrorStatusIsAnError() = runTest { + val exchange = UdpExchange { port, payload, _, _ -> + if (port != 161) return@UdpExchange UdpReply.Timeout + // Echo the request ID from the request: SEQUENCE{INT 1, OCTETS community, A0{INT id ...}}. + val idOffset = 2 + 3 + 2 + community.size + 2 + val idLength = payload[idOffset + 1].toInt() + val id = (0 until idLength).fold(0) { v, i -> (v shl 8) or (payload[idOffset + 2 + i].toInt() and 0xff) } + UdpReply.Data(response(id, seq(oid(*name), tlv(0x05, ByteArray(0))), status = 5)) + } + val result = probeUdpServices(exchange, community, dnsAllowed = false, randomBytes = { ByteArray(it) { 3 } }) + assertEquals(SnmpProbeResult(UdpProbeOutcome.ERROR, errorStatus = 5), result.snmp) + } + + @Test fun dnsProbeOnlyForKnownDnsHosts() { + val info = LanNetworkInfo("wlan0", "192.168.1.30", 24, emptyList(), listOf("192.168.1.1", "fd00::1"), null, true, null, 0, emptyList()) + assertTrue(lanDnsProbeAllowed("192.168.1.1", info, emptyList())) + assertFalse(lanDnsProbeAllowed("192.168.1.20", info, emptyList())) + assertTrue(lanDnsProbeAllowed("192.168.1.20", info, listOf(OpenPort(53)))) + assertFalse(lanDnsProbeAllowed("192.168.1.20", null, listOf(OpenPort(80)))) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/nav/AdaptiveNavigationTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/nav/AdaptiveNavigationTest.kt new file mode 100644 index 0000000..8c0d2f8 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/nav/AdaptiveNavigationTest.kt @@ -0,0 +1,21 @@ +package cz.netkit.shared.nav + +import kotlin.test.Test +import kotlin.test.assertEquals + +class AdaptiveNavigationTest { + @Test fun breakpointUsesWindowWidthInEitherOrientation() { + for (landscape in listOf(false, true)) { + assertEquals(NavigationPlacement.BOTTOM, navigationPlacement(599, landscape, false)) + assertEquals(NavigationPlacement.RAIL, navigationPlacement(600, landscape, false)) + assertEquals(NavigationPlacement.RAIL, navigationPlacement(1200, landscape, false)) + } + } + + @Test fun landscapeTerminalOverridesBothPlacements() { + for (width in listOf(480, 600, 960)) + assertEquals(NavigationPlacement.HIDDEN, navigationPlacement(width, true, true)) + assertEquals(NavigationPlacement.BOTTOM, navigationPlacement(412, false, true)) + assertEquals(NavigationPlacement.RAIL, navigationPlacement(800, false, true)) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/nav/AppTargetTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/nav/AppTargetTest.kt new file mode 100644 index 0000000..ab8e13d --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/nav/AppTargetTest.kt @@ -0,0 +1,89 @@ +package cz.netkit.shared.nav + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class AppTargetTest { + private val uuid = "0f8fad5b-d9cb-469f-a165-70867728950e" + private val key = "0123456789abcdef" + + @Test fun whitelistedTargetsParse() { + assertEquals(AppTarget.Signal, parseAppTarget("signal")) + assertEquals(AppTarget.Spectrum, parseAppTarget("spectrum")) + assertEquals(AppTarget.Ssh, parseAppTarget("ssh")) + assertEquals("ssh", AppTarget.Ssh.encode()) + assertEquals(AppTarget.LanTools(AppLanTool.PING), parseAppTarget("lan_tools/ping")) + AppLanTool.entries.forEach { assertEquals(AppTarget.LanTools(it), parseAppTarget("lan_tools/${it.key}")) } + assertEquals(AppTarget.SshProfile(uuid), parseAppTarget("ssh_profile/$uuid")) + assertEquals(AppTarget.WolDevice(key), parseAppTarget("wol_device/$key")) + } + + @Test fun unknownOrMalformedTargetsAreRejected() { + listOf(null, "", "SIGNAL", "signal/", " signal", "settings", "lan_tools", "lan_tools/", "lan_tools/discovery", + "lan_tools/PING", "lan_tools/ping/x", "ssh_profile", "ssh_profile/", "ssh_profile/a/b", "wol_device/..", + "wol_device/.", "ssh_profile/a b", "ssh_profile/a%2Fb", "ssh_profile/üser", "wol_device/aa:bb:cc:dd:ee:ff", + "ssh_profile/root@host", "wol_device/x;reboot", "/ssh_profile", "ssh/1", "SSH", "ssh/", " ssh", "file:///etc/passwd", + // WoL accepts only the opaque 16-hex device key, never an ID that looks like a host. + "wol_device/nas_1.home", "wol_device/192.168.1.10", "wol_device/0123456789ABCDEF", "wol_device/0123456789abcde", + "wol_device/0123456789abcdef0", "wol_device/$uuid", + ).forEach { assertNull(parseAppTarget(it), "accepted: $it") } + } + + @Test fun idLengthIsBounded() { + val max = "a".repeat(APP_TARGET_ID_MAX) + assertEquals(AppTarget.SshProfile(max), parseAppTarget("ssh_profile/$max")) + assertNull(parseAppTarget("ssh_profile/${max}a"), "ID over limit") + assertNull(parseAppTarget("ssh_profile/" + "a".repeat(10_000)), "huge input") + } + + @Test fun recordTargetNeedsExistingRecord() { + val ssh = AppTarget.SshProfile("p1") + val wol = AppTarget.WolDevice(key) + assertEquals(ssh, resolveAppTarget(ssh, listOf("p1"), emptyList())) + assertNull(resolveAppTarget(ssh, listOf("p2"), listOf("p1")), "missing profile → default tab") + assertNull(resolveAppTarget(ssh, null, null), "unreadable store → default tab") + assertEquals(wol, resolveAppTarget(wol, null, listOf(key))) + assertNull(resolveAppTarget(wol, listOf("d1"), emptyList()), "missing device → default tab") + assertEquals(AppTarget.Spectrum, resolveAppTarget(AppTarget.Spectrum, null, null)) + assertNull(resolveAppTarget(null, listOf("p1"), listOf("d1"))) + } + + @Test fun encodingRoundTripsAndCarriesOnlyTheTarget() { + val targets = listOf(AppTarget.Signal, AppTarget.Spectrum, AppTarget.Ssh, AppTarget.LanTools(AppLanTool.TRACE), + AppTarget.SshProfile(uuid), AppTarget.WolDevice(key)) + targets.forEach { target -> + assertEquals(target, parseAppTarget(target.encode())) + // A shortcut intent carries exactly one extra: the whitelisted target, nothing about the host. + assertEquals(mapOf(APP_TARGET_EXTRA to target.encode()), appTargetExtras(target)) + } + assertEquals("ssh_profile/$uuid", AppTarget.SshProfile(uuid).shortcutId()) + assertFailsWith { AppTarget.SshProfile("host name").encode() } + } + + @Test fun deletedRecordsDisableTheirShortcuts() { + val a = "aaaaaaaaaaaaaaaa"; val b = "bbbbbbbbbbbbbbbb"; val c = "cccccccccccccccc" + val pinned = listOf( + PinnedShortcut("wol_device/$a", true, "NAS"), + PinnedShortcut("wol_device/$b", true, "PC"), + PinnedShortcut("wol_device/$c", false, "Old"), + PinnedShortcut("ssh_profile/a", true, "Router"), + PinnedShortcut("signal", true, "Signál"), + ) + // b deleted (or replaced: its key is gone) → disabled; c is back → enabled; a renamed → new label. + val plan = planPinnedShortcutSync(AppRecordKind.WOL_DEVICE, pinned, mapOf(a to "NAS doma", c to "Old")) + assertEquals(listOf("wol_device/$b"), plan.disable) + assertEquals(listOf("wol_device/$c"), plan.enable) + assertEquals(mapOf("wol_device/$a" to "NAS doma"), plan.relabel) + val ssh = planPinnedShortcutSync(AppRecordKind.SSH_PROFILE, pinned, emptyMap()) + assertEquals(listOf("ssh_profile/a"), ssh.disable) + assertTrue(ssh.enable.isEmpty() && ssh.relabel.isEmpty()) + // Already in sync: nothing to do. + assertTrue(planPinnedShortcutSync(AppRecordKind.SSH_PROFILE, pinned, mapOf("a" to "Router")).isEmpty) + // A value that could never have had a shortcut is ignored instead of failing. + assertTrue(planPinnedShortcutSync(AppRecordKind.WOL_DEVICE, emptyList(), mapOf("bad id" to "x", "nas.home" to "y")).isEmpty) + assertNull(AppRecordKind.WOL_DEVICE.target("192.168.1.10")) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusTest.kt new file mode 100644 index 0000000..6ad3aa8 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusTest.kt @@ -0,0 +1,317 @@ +package cz.netkit.shared.netstatus + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.launch +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceTimeBy +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Zadání 37 AC-001 (snapshot: serialization, throttling, SSID and public IP rules) and the common part + * of AC-002 (refresh: radio only, SSID untouched, deadline). Synthetic SSIDs and documentation addresses only. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class NetStatusTest { + private val t0 = 1_800_000_000_000L + private val allowed = NetStatusPrivacy(locationGranted = true, publicIpLookupEnabled = true) + + /** In-memory store counting the writes that changed the data, like the file store. */ + private class Store(var data: NetStatusData = NetStatusData(), var updateGate: (suspend () -> Unit)? = null) : NetStatusStore { + private val mutex = Mutex() + val writes = mutableListOf>() + var clock: () -> Long = { 0 } + override suspend fun read() = mutex.withLock { data } + override suspend fun update(transform: (NetStatusData) -> NetStatusData): NetStatusData = mutex.withLock { + updateGate?.invoke() + transform(data).also { if (it != data) { writes += clock() to it; data = it } } + } + } + + private fun TestScope.recorder(store: Store, privacy: () -> NetStatusPrivacy = { allowed }, redraws: MutableList = mutableListOf()) = + NetStatusRecorder(this, store, { privacy() }, { currentTime }, { wallNow }, { redraws += it }).also { store.clock = { currentTime } } + + /** Wall clock of the recorder; tests move it backwards to simulate a clock change. */ + private var wallNow = t0 + 3_600_000 + + private fun radio(at: Long, rssi: Int = -60, frequency: Int = 5180) = + netStatusRadio(at, frequency, rssi, 866, 780, NetStatusRadioSource.FOREGROUND) + + // --- Serialization ----------------------------------------------------------------------------- + + @Test fun roundTripKeepsEveryPart() { + val data = NetStatusData( + settings = NetStatusSettings(showSsid = true, showPublicIp = true), + radio = radio(t0), width = NetStatusWidth(t0, 5180, 80), gateway = NetStatusGateway(t0, 2.5), + speed = NetStatusSpeed(t0 - 1000, 412.5, 98.1, 11.0), ssid = NetStatusLabel(t0, "TestNet-5G"), + publicIp = NetStatusLabel(t0, "203.0.113.7"), + ) + assertEquals(data, NetStatusCodec.decode(NetStatusCodec.encode(data))) + // Defaults: both options off. + assertEquals(NetStatusSettings(false, false), NetStatusCodec.decode("""{"schema":1}""").settings) + } + + @Test fun decodeIsStrict() { + for (text in listOf("", "[]", "{}", """{"schema":2}""", """{"schema":1,"radio":{"atMs":1,"wifi":true,"rssiDbm":40}}""", + """{"schema":1,"publicIp":{"atMs":1,"value":"192.168.1.1"}}""", """{"schema":1,"publicIp":{"atMs":1,"value":"example.com"}}""", + """{"schema":1,"ssid":{"atMs":1,"value":"${"x".repeat(33)}"}}""", """{"schema":1,"gateway":{"atMs":0,"latencyMs":1}}""", + """{"schema":1,"radio":{"atMs":1,"wifi":false,"rssiDbm":-50}}""", "{" + " ".repeat(NET_STATUS_MAX_BYTES) + "}")) { + assertFailsWith(text.take(60)) { NetStatusCodec.decode(text) } + } + } + + @Test fun encodeDropsInvalidParts() { + val text = NetStatusCodec.encode(NetStatusData(gateway = NetStatusGateway(t0, Double.NaN), ssid = NetStatusLabel(t0, "a\u0000b"), + publicIp = NetStatusLabel(t0, "10.0.0.1"), radio = radio(t0))) + val back = NetStatusCodec.decode(text) + assertNull(back.gateway); assertNull(back.ssid); assertNull(back.publicIp); assertNotNull(back.radio) + } + + // --- Throttling --------------------------------------------------------------------------------- + + @Test fun foregroundWritesAtMostOncePer30Seconds() = runTest { + val store = Store() + val recorder = recorder(store) + // Přehled at 1 Hz for 95 s. + for (second in 0 until 95) { + recorder.offer(NetStatusPatch(radio = radio(t0 + second * 1000L, rssi = -40 - second % 50))) + advanceTimeBy(1_000) + } + advanceUntilIdle() + val times = store.writes.map { it.first } + assertEquals(listOf(0L, 30_000L, 60_000L, 90_000L, 120_000L), times) + times.zipWithNext().forEach { (a, b) -> assertTrue(b - a >= NET_STATUS_WRITE_INTERVAL_MS) } + // The trailing write carries the newest offered values. + assertEquals(t0 + 94_000, store.data.radio?.atMs) + } + + @Test fun speedResultInsideTheWindowIsWrittenByTheTrailingWrite() = runTest { + val store = Store() + val recorder = recorder(store) + recorder.offer(NetStatusPatch(radio = radio(t0))) + runCurrent() + advanceTimeBy(5_000) + recorder.offer(NetStatusPatch(speed = NetStatusSpeed(t0 + 5_000, 300.0, 50.0, 12.0))) + advanceTimeBy(20_000); runCurrent() + assertEquals(1, store.writes.size, "no second write inside 30 s") + advanceTimeBy(10_000); runCurrent() + assertEquals(2, store.writes.size) + assertEquals(300.0, store.data.speed?.downloadMbps) + assertEquals(30_000L, store.writes[1].first) + } + + @Test fun olderPartNeverOverwritesNewerOne() = runTest { + val store = Store(NetStatusData(radio = netStatusRadio(t0 + 10_000, 2437, -50, null, null, NetStatusRadioSource.WIDGET_REFRESH))) + recorder(store).offer(NetStatusPatch(radio = radio(t0))) + advanceUntilIdle() + assertEquals(NetStatusRadioSource.WIDGET_REFRESH, store.data.radio?.source) + assertEquals(t0 + 10_000, store.data.radio?.atMs) + } + + @Test fun redrawOnlyAfterAChange() = runTest { + val store = Store() + val redraws = mutableListOf() + val recorder = recorder(store, redraws = redraws) + recorder.enforcePrivacy() + assertEquals(0, redraws.size) + recorder.offer(NetStatusPatch(radio = radio(t0))) + advanceUntilIdle() + assertEquals(1, redraws.size) + } + + // --- SSID --------------------------------------------------------------------------------------- + + private fun ssidPatch(at: Long, value: String? = "TestNet") = NetStatusPatch(radio = radio(at), ssid = NetStatusSsidReport(at, value)) + + @Test fun ssidIsNotStoredWithTheOptionOff() = runTest { + val store = Store() + recorder(store).offer(ssidPatch(t0)) + advanceUntilIdle() + assertNull(store.data.ssid) + assertNotNull(store.data.radio) + } + + @Test fun ssidIsStoredWithOptionAndLocationAndDeletedWhenTheOptionGoesOff() = runTest { + val store = Store(NetStatusData(settings = NetStatusSettings(showSsid = true))) + val recorder = recorder(store) + recorder.offer(ssidPatch(t0)) + advanceUntilIdle() + assertEquals("TestNet", store.data.ssid?.value) + recorder.update { it.copy(settings = it.settings.copy(showSsid = false)) } + assertNull(store.data.ssid) + assertNull(NetStatusCodec.decode(NetStatusCodec.encode(store.data)).ssid) + } + + @Test fun ssidIsDeletedWhenLocationIsMissing() = runTest { + var privacy = allowed + val store = Store(NetStatusData(settings = NetStatusSettings(showSsid = true))) + val recorder = recorder(store, privacy = { privacy }) + recorder.offer(ssidPatch(t0)) + advanceUntilIdle() + assertNotNull(store.data.ssid) + // Location revoked: the check at app start / widget update removes it. + privacy = privacy.copy(locationGranted = false) + recorder.enforcePrivacy() + assertNull(store.data.ssid) + // And a foreground reading without location never stores one. + recorder.offer(ssidPatch(t0 + 60_000)) + advanceUntilIdle() + assertNull(store.data.ssid) + } + + @Test fun readingWithoutSsidClearsTheStoredOne() = runTest { + val store = Store(NetStatusData(settings = NetStatusSettings(showSsid = true), ssid = NetStatusLabel(t0, "OldNet"))) + recorder(store).offer(ssidPatch(t0 + 1_000, value = null)) + advanceUntilIdle() + assertNull(store.data.ssid) + } + + // --- Public IP ---------------------------------------------------------------------------------- + + @Test fun publicIpIsNotStoredWhileLookupIsDisabled() = runTest { + val store = Store(NetStatusData(settings = NetStatusSettings(showPublicIp = true))) + val recorder = recorder(store, privacy = { allowed.copy(publicIpLookupEnabled = false) }) + recorder.offer(NetStatusPatch(publicIp = NetStatusLabel(t0, "198.51.100.20"))) + advanceUntilIdle() + assertNull(store.data.publicIp) + } + + @Test fun publicIpNeedsTheOptionAndIsDeletedWhenLookupGoesOff() = runTest { + var privacy = allowed + val store = Store() + val recorder = recorder(store, privacy = { privacy }) + recorder.offer(NetStatusPatch(publicIp = NetStatusLabel(t0, "198.51.100.20"))) + advanceUntilIdle() + assertNull(store.data.publicIp, "option off by default") + recorder.update { it.copy(settings = NetStatusSettings(showPublicIp = true)) } + recorder.offer(NetStatusPatch(publicIp = NetStatusLabel(t0 + 40_000, "2001:db8::20"))) + advanceUntilIdle() + assertEquals("2001:db8::20", store.data.publicIp?.value) + privacy = privacy.copy(publicIpLookupEnabled = false) + recorder.enforcePrivacy() + assertNull(store.data.publicIp) + } + + // --- Revize kolo 1 ------------------------------------------------------------------------------------ + + @Test fun deletionAfterRevocationIsNeverOverwrittenByAWriteThatCheckedEarlier() = runTest { + // The writer reads "lookup on" and stalls; meanwhile the lookup is switched off and the copy deleted. + var lookup = true + var first = true + val stall = CompletableDeferred() + val store = Store(NetStatusData(settings = NetStatusSettings(showPublicIp = true))) + val recorder = NetStatusRecorder(this, store, { + val read = allowed.copy(publicIpLookupEnabled = lookup) + if (first) { first = false; stall.await() } + read + }, { currentTime }, { wallNow }, { }) + recorder.offer(NetStatusPatch(publicIp = NetStatusLabel(t0, "198.51.100.20"))) + runCurrent() + lookup = false + val deletion = launch { recorder.update { it.copy(publicIp = null) } } + runCurrent() + assertTrue(deletion.isActive, "the deletion waits for the write that already checked privacy") + // Before the fix the stalled writer stored the address after the deletion with its stale "lookup on". + stall.complete(Unit) + advanceUntilIdle() + assertNull(store.data.publicIp) + assertNull(store.writes.lastOrNull()?.second?.publicIp) + } + + @Test fun laterOfferWinsEvenWithAnEarlierWallTime() = runTest { + // Clock moved backwards between two offers inside one throttle window: the later offer is written. + val store = Store() + val recorder = recorder(store) + recorder.offer(NetStatusPatch(radio = radio(t0))) + runCurrent() + recorder.offer(NetStatusPatch(radio = radio(t0 + 10_000, rssi = -70))) + advanceTimeBy(5_000) + recorder.offer(NetStatusPatch(radio = radio(t0 + 5_000, rssi = -45))) + advanceUntilIdle() + assertEquals(-45, store.data.radio?.rssiDbm) + } + + @Test fun futurePartsAfterAClockChangeAreReplaced() = runTest { + // Snapshot written before the clock went back by a day: every part lies in the future now. + val future = wallNow + 86_400_000 + val store = Store(NetStatusData(settings = NetStatusSettings(showSsid = true), radio = radio(future, rssi = -80), + gateway = NetStatusGateway(future, 9.0), ssid = NetStatusLabel(future, "OldNet"))) + val recorder = recorder(store) + assertEquals(NetStatusState.STALE, netStatusView(store.data, wallNow, NetStatusWidgetSize.MEDIUM, false).state) + recorder.offer(ssidPatch(wallNow, value = "TestNet").copy(radio = radio(wallNow, rssi = -55))) + advanceUntilIdle() + assertEquals(-55, store.data.radio?.rssiDbm) + assertEquals("TestNet", store.data.ssid?.value) + assertNull(store.data.gateway, "an untrusted future gateway value is dropped") + assertEquals(NetStatusState.FRESH, netStatusView(store.data, wallNow, NetStatusWidgetSize.MEDIUM, false).state) + // The refresh tap replaces a future radio part as well (it used to report UPDATED and keep it). + val again = Store(NetStatusData(radio = radio(future))) + assertEquals(NetStatusRefreshResult.UPDATED, refreshNetStatus({ NetStatusRadioReading(2412, -48, 72, 72) }, recorder(again), { wallNow })) + assertEquals(wallNow, again.data.radio?.atMs) + assertEquals(-48, again.data.radio?.rssiDbm) + // A part measured within the tolerance is still ordered normally. + assertTrue(NET_STATUS_FUTURE_TOLERANCE_MS > 0) + } + + // --- Refresh (AC-002, common part) ---------------------------------------------------------------- + + @Test fun refreshUpdatesRadioOnlyAndKeepsSsid() = runTest { + val ssid = NetStatusLabel(t0, "TestNet") + val store = Store(NetStatusData(settings = NetStatusSettings(showSsid = true), radio = radio(t0, rssi = -70, frequency = 2412), + ssid = ssid, gateway = NetStatusGateway(t0, 3.0))) + val recorder = recorder(store) + val started = currentTime + val result = refreshNetStatus({ NetStatusRadioReading(5500, -48, 1200, 960) }, recorder, { t0 + 600_000 }) + assertEquals(NetStatusRefreshResult.UPDATED, result) + assertTrue(currentTime - started < 10_000) + val radio = assertNotNull(store.data.radio) + assertEquals(-48, radio.rssiDbm); assertEquals(5500, radio.frequencyMhz); assertEquals(NetStatusRadioSource.WIDGET_REFRESH, radio.source) + val view = netStatusView(store.data, t0 + 600_000, NetStatusWidgetSize.MEDIUM, lockscreen = false) + assertEquals(100, view.channel) + // SSID is not touched by the refresh: same value and time, shown with its own (older) time. + assertEquals(ssid, store.data.ssid) + assertEquals(t0, view.ssid?.ownTimeMs) + assertEquals(3.0, store.data.gateway?.latencyMs) + } + + @Test fun refreshWithoutWifiStoresNoWifi() = runTest { + val store = Store(NetStatusData(radio = radio(t0))) + assertEquals(NetStatusRefreshResult.NO_WIFI, refreshNetStatus({ null }, recorder(store), { t0 + 1_000 })) + assertEquals(false, store.data.radio?.wifi) + } + + @Test fun hangingReaderEndsWithinTheDeadlineAndChangesNothing() = runTest { + val before = NetStatusData(radio = radio(t0)) + val store = Store(before) + val started = currentTime + assertEquals(NetStatusRefreshResult.TIMEOUT, refreshNetStatus({ awaitCancellation() }, recorder(store), { t0 + 1 })) + assertEquals(NET_STATUS_REFRESH_READ_MS, currentTime - started) + assertEquals(before, store.data) + } + + @Test fun hangingStoreEndsWithinTheDeadline() = runTest { + val store = Store(NetStatusData(), updateGate = { awaitCancellation() }) + val started = currentTime + assertEquals(NetStatusRefreshResult.TIMEOUT, refreshNetStatus({ NetStatusRadioReading(2412, -50, 72, 72) }, recorder(store), { t0 })) + assertEquals(NET_STATUS_REFRESH_BUDGET_MS, currentTime - started) + assertTrue(NET_STATUS_REFRESH_BUDGET_MS < 10_000) + } + + @Test fun failingReaderIsReported() = runTest { + val store = Store() + assertEquals(NetStatusRefreshResult.FAILED, refreshNetStatus({ error("binder") }, recorder(store), { t0 })) + assertTrue(store.writes.isEmpty()) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusViewTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusViewTest.kt new file mode 100644 index 0000000..ad79ac7 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusViewTest.kt @@ -0,0 +1,97 @@ +package cz.netkit.shared.netstatus + +import cz.netkit.shared.wifi.SignalQuality +import cz.netkit.shared.wifi.WifiBand +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +/** Zadání 37 AC-003 (model part): small/medium content and the fresh, stale, no-data and SSID states. */ +class NetStatusViewTest { + private val now = 1_800_000_000_000L + private val full = NetStatusData( + settings = NetStatusSettings(showSsid = true, showPublicIp = true), + radio = netStatusRadio(now - 12 * 60_000, 5180, -58, 866, 780, NetStatusRadioSource.FOREGROUND), + width = NetStatusWidth(now - 13 * 60_000, 5180, 80), + gateway = NetStatusGateway(now - 12 * 60_000, 2.4), + speed = NetStatusSpeed(now - 2 * 3_600_000, 412.0, 98.0, 11.0), + ssid = NetStatusLabel(now - 12 * 60_000, "TestNet-5G"), + publicIp = NetStatusLabel(now - 3 * 3_600_000, "203.0.113.7"), + ) + + @Test fun mediumFreshShowsEverything() { + val view = netStatusView(full, now, NetStatusWidgetSize.MEDIUM, lockscreen = false) + assertEquals(NetStatusState.FRESH, view.state) + assertEquals(-58, view.rssiDbm); assertEquals(36, view.channel); assertEquals(WifiBand.GHZ_5, view.band); assertEquals(80, view.widthMhz) + assertEquals(cz.netkit.shared.wifi.signalQuality(-58), view.quality) + assertEquals(SignalQuality.UNKNOWN, netStatusView(NetStatusData(radio = NetStatusRadio(now, wifi = false)), now, + NetStatusWidgetSize.MEDIUM, false).quality) + assertEquals(866, view.rxLinkMbps); assertEquals(780, view.txLinkMbps) + assertEquals(NetStatusStamped(2.4, null), view.gatewayMs, "same measurement as the signal: no own time") + assertEquals(412.0, view.speed?.downloadMbps) + assertEquals(NetStatusStamped("TestNet-5G", null), view.ssid) + assertEquals(NetStatusStamped("203.0.113.7", now - 3 * 3_600_000), view.publicIp, "older value shows its own time") + assertEquals(now - 12 * 60_000, view.radioAtMs) + } + + @Test fun smallShowsSignalChannelAndAgeOnly() { + val view = netStatusView(full, now, NetStatusWidgetSize.SMALL, lockscreen = false) + assertEquals(-58, view.rssiDbm); assertEquals(36, view.channel); assertEquals(now - 12 * 60_000, view.radioAtMs) + assertNull(view.widthMhz); assertNull(view.rxLinkMbps); assertNull(view.gatewayMs); assertNull(view.speed) + assertNull(view.ssid); assertNull(view.publicIp) + } + + @Test fun ssidOptionOffOrLockScreenHidesSsidAndPublicIp() { + val off = netStatusView(full.copy(settings = NetStatusSettings()), now, NetStatusWidgetSize.MEDIUM, lockscreen = false) + assertNull(off.ssid); assertNull(off.publicIp) + val locked = netStatusView(full, now, NetStatusWidgetSize.MEDIUM, lockscreen = true) + assertNull(locked.ssid); assertNull(locked.publicIp) + assertEquals(-58, locked.rssiDbm) + } + + @Test fun olderThan24HoursIsStale() { + val view = netStatusView(full, now + 25 * 3_600_000L, NetStatusWidgetSize.MEDIUM, lockscreen = false) + assertEquals(NetStatusState.STALE, view.state) + assertEquals(now - 12 * 60_000, view.lastAtMs) + assertNull(view.rssiDbm); assertNull(view.ssid) + // Exactly 24 h is still fresh; a time far in the future (clock moved back) is stale. + assertEquals(NetStatusState.FRESH, netStatusView(full, now - 12 * 60_000 + NET_STATUS_STALE_AFTER_MS, NetStatusWidgetSize.SMALL, false).state) + assertEquals(NetStatusState.STALE, netStatusView(full, now - 2 * 3_600_000 - NET_STATUS_FUTURE_TOLERANCE_MS - 1, NetStatusWidgetSize.SMALL, false).state) + } + + @Test fun noDataAndSpeedOnly() { + assertEquals(NetStatusState.NO_DATA, netStatusView(NetStatusData(), now, NetStatusWidgetSize.MEDIUM, false).state) + // SSID alone is not a measurement. + assertEquals(NetStatusState.NO_DATA, netStatusView(NetStatusData(ssid = full.ssid), now, NetStatusWidgetSize.MEDIUM, false).state) + val speedOnly = netStatusView(NetStatusData(speed = full.speed), now, NetStatusWidgetSize.MEDIUM, false) + assertEquals(NetStatusState.FRESH, speedOnly.state) + assertNull(speedOnly.wifi); assertNull(speedOnly.radioAtMs) + assertEquals(412.0, speedOnly.speed?.downloadMbps) + } + + @Test fun noWifiAndWidthOfAnotherChannel() { + val noWifi = full.copy(radio = NetStatusRadio(now, wifi = false)) + val view = netStatusView(noWifi, now, NetStatusWidgetSize.MEDIUM, false) + assertEquals(false, view.wifi); assertNull(view.rssiDbm); assertNull(view.channel); assertNull(view.widthMhz); assertNull(view.rxLinkMbps) + val moved = full.copy(radio = full.radio!!.copy(frequencyMhz = 5500)) + assertNull(netStatusView(moved, now, NetStatusWidgetSize.MEDIUM, false).widthMhz, "width belongs to channel 36 only") + } + + @Test fun refreshMarksTheSource() { + val refreshed = full.copy(radio = full.radio!!.copy(atMs = now, source = NetStatusRadioSource.WIDGET_REFRESH)) + val view = netStatusView(refreshed, now, NetStatusWidgetSize.MEDIUM, false) + assertEquals(true, view.fromRefresh) + assertEquals(now - 12 * 60_000, view.gatewayMs?.ownTimeMs) + assertEquals(now - 12 * 60_000, view.ssid?.ownTimeMs) + } +} + +class NetStatusRefreshDataTest { + @Test fun roundTripAndRejects() { + assertEquals(42, parseNetStatusRefreshData(netStatusRefreshData(42))) + assertEquals(Int.MAX_VALUE, parseNetStatusRefreshData(netStatusRefreshData(Int.MAX_VALUE))) + for (bad in listOf(null, "", "netkit-netstatus://refresh/", "netkit-netstatus://refresh/0", "netkit-netstatus://refresh/-1", + "netkit-netstatus://refresh/2147483648", "netkit-netstatus://refresh/12a", "netkit-netstatus://refresh/1/2", + "netkit-wol://wake/1", "netkit-netstatus://refresh/99999999999")) assertNull(parseNetStatusRefreshData(bad), bad) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/publicip/RdapTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/publicip/RdapTest.kt new file mode 100644 index 0000000..465122d --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/publicip/RdapTest.kt @@ -0,0 +1,36 @@ +package cz.netkit.shared.publicip + +import kotlin.test.* + +class RdapTest { + @Test fun arinNetworkAndNestedAbuseContact() { + val text = """{"name":"EXAMPLE","country":"CZ","cidr0_cidrs":[{"v4prefix":"192.0.2.0","length":24}], + "arin_originas0_originautnums":[64496],"entities":[{"roles":["registrant"], + "vcardArray":["vcard",[["fn",{},"text","Example Org"]]],"entities":[{"roles":["abuse"], + "vcardArray":["vcard",[["email",{},"text","abuse@example.test"]]]}]}]}""" + assertEquals(RdapInfo("192.0.2.0/24", "EXAMPLE", "CZ", "Example Org", "abuse@example.test", "AS64496"), parseRdap(text)) + } + + @Test fun ripeRangeAndAutnumWithoutInventingMissingFields() { + assertEquals("2001:db8::1/128, 2001:db8::2/127, 2001:db8::4/126", + parseRdap("""{"startAddress":"2001:db8::1","endAddress":"2001:db8::7"}""")?.network) + assertEquals("192.0.2.0/24", parseRdap("""{"startAddress":"192.0.2.0","endAddress":"192.0.2.255"}""")?.network) + assertEquals(RdapInfo(null, null, null, null, null, "AS64496–AS64498"), + parseRdap("""{"startAutnum":64496,"endAutnum":64498}""")) + assertEquals(RdapInfo(null, null, null, null, null, null), parseRdap("{}")) + } + + @Test fun malformedSizeBytesAndDepthCheckedBeforeDecoding() { + assertNull(parseRdap("{")) + assertNull(parseRdap("[]")) + assertNull(parseRdap("""{"x":""" + "[".repeat(16) + "]".repeat(16) + "}")) + assertNull(parseRdap("""{"x":"""" + "ě".repeat(RDAP_MAX_BYTES / 2) + """"}""")) + assertNotNull(parseRdap("{}" + " ".repeat(RDAP_MAX_BYTES - 2))) + } + + @Test fun outboundPolicyIsStricterThanPublicIpFixtures() { + for (input in listOf("192.0.2.10", "198.51.100.1", "203.0.113.1", "2001:db8::1", "example.test", + "AS64496", "AS4294967295", "AS-1", "ASas4")) assertNull(rdapPath(input), input) + assertEquals("autnum/123", rdapPath("As123")) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/report/DiagnosticReportTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/report/DiagnosticReportTest.kt new file mode 100644 index 0000000..7081a18 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/report/DiagnosticReportTest.kt @@ -0,0 +1,263 @@ +package cz.netkit.shared.report + +import cz.netkit.shared.net.NetKind +import cz.netkit.shared.speed.SpeedEngine +import cz.netkit.shared.speed.SpeedRecord +import cz.netkit.shared.wifi.WifiBand +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.descriptors.StructureKind +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class DiagnosticReportTest { + private val speed = SpeedRecord(timestampMs = 1_764_665_103_042, engine = SpeedEngine.LIBRESPEED, serverName = "Praha (example)", + downloadMbps = 512.345, uploadMbps = 98.76, idleLatencyMs = 7.25, idleJitterMs = 0.84, ssid = "HomeNet", networkKind = NetKind.WIFI) + private val iperf = SpeedRecord(timestampMs = 1_764_665_200_000, engine = SpeedEngine.IPERF3, serverName = "192.0.2.10:5201", + downloadMbps = 940.0, retransmits = 12, networkKind = NetKind.WIFI, partial = true) + + private fun input( + wifi: DiagnosticWifiInput? = DiagnosticWifiInput("HomeNet", "AA:BB:CC:00:11:22", -58, 866, 780, 5180, 36, WifiBand.GHZ_5, 80, "802.11ax"), + ) = DiagnosticReportInput( + generatedAtMs = 1_764_666_000_000, appVersion = "2.0.0", networkKind = NetKind.WIFI, metered = false, interfaceName = "wlan0", + ipv4 = "192.168.1.50", ipv6 = "2001:DB8:0:0::50%wlan0", gateway = "192.168.1.1", dnsServers = listOf("192.168.1.1", "not-an-ip", "2001:db8::53"), + privateDns = false, privateDnsHost = "ignored.example", dhcpServer = "192.168.1.1", mtu = 1500, wifi = wifi, + gatewayLatency = DiagnosticLatencyInput("192.168.1.1", listOf(1.0, 2.0, null, 3.0)), + internetLatency = DiagnosticLatencyInput("192.0.2.53", listOf(10.0, 12.0, 11.0, 13.0)), + publicIp = DiagnosticPublicIpInput("203.0.113.7", "2001:db8:1::7", 5610, "O2 Czech\u0007 Republic"), + lastSpeedTest = speed, lastIperf3 = iperf, + ) + + @Test fun defaultsOmitSsidBssidAndPublicIp() { + val report = buildDiagnosticReport(input()) + assertNull(report.wifi!!.ssid) + assertNull(report.wifi!!.bssid) + assertNull(report.publicIp) + val json = diagnosticReportJson(report) + val text = diagnosticReportText(report) + for (value in listOf("HomeNet", "aa:bb:cc", "AA:BB:CC", "203.0.113.7", "2001:db8:1::7", "5610", "O2 Czech")) { + assertFalse(value in json, "JSON leaks $value") + assertFalse(value in text, "text leaks $value") + } + } + + @Test fun optionsIncludeIdentifiersSanitized() { + val report = buildDiagnosticReport(input(), DiagnosticReportOptions(includeSsid = true, includeBssid = true, includePublicIp = true)) + assertEquals("HomeNet", report.wifi!!.ssid) + assertEquals("aa:bb:cc:00:11:22", report.wifi!!.bssid) + val publicIp = assertNotNull(report.publicIp) + assertEquals("203.0.113.7", publicIp.ipv4) + assertEquals(5610L, publicIp.asn) + assertEquals("O2 Czech Republic", publicIp.provider, "control characters become spaces like the LAN export") + val text = diagnosticReportText(report) + assertTrue("SSID: HomeNet" in text) + assertTrue("ASN: AS5610" in text) + } + + @Test fun networkValuesAreValidatedAndCanonical() { + val net = buildDiagnosticReport(input(), DiagnosticReportOptions(includePublicIp = true)).network + assertEquals("wifi", net.type) + assertEquals("2001:db8::50", net.ipv6) + assertEquals(listOf("192.168.1.1", "2001:db8::53"), net.dns, "a non-numeric resolver is dropped, never shown raw") + assertNull(net.privateDnsHost, "host only when Private DNS is active") + assertEquals(1500, net.mtu) + val odd = buildDiagnosticReport(input().copy(mtu = 0, dhcpServer = "0.0.0.0", privateDns = true)).network + assertNull(odd.mtu) + assertNull(odd.dhcpServer) + assertNull(odd.privateDnsHost) + } + + /** Revize kolo 1 (P1): publicly routable link addresses follow the public-IP consent. */ + @Test fun publicInterfaceAddressesNeedConsent() { + val public = input().copy(ipv4 = "198.51.100.7", ipv6 = "2001:db8:2::7", gateway = "198.51.100.1", dhcpServer = "198.51.100.1", + gatewayLatency = DiagnosticLatencyInput("198.51.100.1", listOf(1.0))) + val hidden = buildDiagnosticReport(public) + assertNull(hidden.network.ipv4) + assertNull(hidden.network.ipv6) + assertNull(hidden.network.gateway) + assertNull(hidden.network.dhcpServer) + assertNull(hidden.gatewayLatency!!.target) + assertEquals(1, hidden.gatewayLatency!!.received, "the measurement stays, only the address goes") + for (text in listOf(diagnosticReportText(hidden), diagnosticReportJson(hidden))) { + assertFalse("198.51.100" in text || "2001:db8:2" in text, text) + } + val shown = buildDiagnosticReport(public, DiagnosticReportOptions(includePublicIp = true)) + assertEquals("198.51.100.7", shown.network.ipv4) + assertEquals("2001:db8:2::7", shown.network.ipv6) + assertEquals("198.51.100.1", shown.gatewayLatency!!.target) + // Local scopes are not identifying and stay by default; resolvers are not the user's address. + val local = buildDiagnosticReport(input().copy(ipv4 = "100.64.1.2", ipv6 = "fd00::5", gateway = "10.0.0.1", + dnsServers = listOf("192.0.2.53"))) + assertEquals("100.64.1.2", local.network.ipv4) + assertEquals("fd00::5", local.network.ipv6) + assertEquals("10.0.0.1", local.network.gateway) + assertEquals(listOf("192.0.2.53"), local.network.dns) + } + + /** Revize kolo 1 (kontrola P2): without a public-IP lookup the consent still covers a known global address. */ + @Test fun consentSwitchAvailableWithoutLookup() { + val noLookup = input().copy(publicIp = null, lastIperf3 = null, ipv4 = "192.168.1.50", ipv6 = "2001:db8:2::7", gateway = "192.168.1.1", + dhcpServer = "192.168.1.1", gatewayLatency = DiagnosticLatencyInput("192.168.1.1", listOf(1.0))) + assertTrue(hasConsentableAddresses(noLookup)) + assertEquals("2001:db8:2::7", buildDiagnosticReport(noLookup, DiagnosticReportOptions(includePublicIp = true)).network.ipv6) + assertNull(buildDiagnosticReport(noLookup).network.ipv6) + val privateOnly = noLookup.copy(ipv6 = "fd00::7") + assertFalse(hasConsentableAddresses(privateOnly), "nothing to include: the switch stays disabled") + assertTrue(hasConsentableAddresses(privateOnly.copy(publicIp = DiagnosticPublicIpInput("203.0.113.7", null, null, null)))) + assertTrue(hasConsentableAddresses(privateOnly.copy(gateway = "198.51.100.1"))) + } + + @Test fun iperfEndpointOnlyAppearsWithConsentUnlessLocal() { + val base = input().copy(publicIp = null, ipv6 = null) + val options = DiagnosticReportOptions(includePublicIp = true) + for (endpoint in listOf("203.0.113.25:5217", "home.example.org:5217", "[2001:db8::25]:5217", + "[::ffff:203.0.113.25]:5217", "192.168.1.25:bad")) { + val record = iperf.copy(serverName = endpoint) + val snapshot = base.copy(lastIperf3 = record) + assertTrue(hasConsentableAddresses(snapshot), endpoint) + val hidden = buildDiagnosticReport(snapshot) + assertEquals("?", hidden.iperf3!!.server) + assertEquals(940.0, hidden.iperf3!!.downloadMbps) + for (output in listOf(diagnosticReportText(hidden), diagnosticReportJson(hidden))) { + assertFalse(endpoint.substringBeforeLast(':') in output || "5217" in output) + } + assertEquals(endpoint, buildDiagnosticReport(snapshot, options).iperf3!!.server) + assertTrue(endpoint in speedShareText(record)) + } + for (endpoint in listOf("10.0.0.25:5217", "[fd00::25]:5217", "[::ffff:192.168.1.25]:5217")) { + val snapshot = base.copy(lastIperf3 = iperf.copy(serverName = endpoint)) + assertFalse(hasConsentableAddresses(snapshot), endpoint) + assertEquals(endpoint, buildDiagnosticReport(snapshot).iperf3!!.server) + } + } + + @Test fun privateDnsStatusIsVisibleButItsHostnameRequiresConsent() { + val host = "account.dns.example.org" + val snapshot = input().copy(publicIp = null, ipv6 = null, lastIperf3 = null, privateDns = true, privateDnsHost = host) + val hidden = buildDiagnosticReport(snapshot) + assertTrue(hidden.network.privateDns) + assertTrue(hasConsentableAddresses(snapshot)) + assertFalse(host in diagnosticReportText(hidden) || host in diagnosticReportJson(hidden)) + val options = DiagnosticReportOptions(includePublicIp = true) + assertEquals(host, buildDiagnosticReport(snapshot, options).network.privateDnsHost) + val inactive = snapshot.copy(privateDns = false) + assertFalse(hasConsentableAddresses(inactive)) + assertNull(buildDiagnosticReport(inactive, options).network.privateDnsHost) + assertFalse(hasConsentableAddresses(snapshot.copy(privateDnsHost = " "))) + } + + @Test fun latencyIsLastMinuteStatistics() { + val report = buildDiagnosticReport(input()) + val gateway = assertNotNull(report.gatewayLatency) + assertEquals(4, gateway.sent) + assertEquals(3, gateway.received) + assertEquals(25.0, gateway.lossPercent) + assertEquals(1.0, gateway.minMs) + assertEquals(2.0, gateway.avgMs) + assertEquals(3.0, gateway.maxMs) + assertEquals(1.0, gateway.jitterMs, "jitter counts adjacent replies only") + assertEquals(DIAGNOSTIC_LATENCY_WINDOW_S, report.latencyWindowSeconds) + val text = diagnosticReportText(report) + assertTrue("Gateway: 192.168.1.1: 1/2/3 ms, loss 25 % (3/4)" in text, text) + val empty = buildDiagnosticReport(input().copy(gatewayLatency = DiagnosticLatencyInput("192.168.1.1", emptyList()), internetLatency = null)) + assertNull(empty.gatewayLatency) + assertTrue("Internet: no data" in diagnosticReportText(empty)) + } + + @Test fun speedAndIperfComeFromTheirEngines() { + val report = buildDiagnosticReport(input()) + assertEquals("librespeed", report.speedTest!!.engine) + assertEquals(512.3, report.speedTest!!.downloadMbps) + assertEquals("2025-12-02T08:45:03.042Z", report.speedTest!!.time) + assertEquals("iperf3", report.iperf3!!.engine) + assertEquals(12L, report.iperf3!!.retransmits) + // A record of the wrong engine in a slot is ignored rather than mislabelled. + val swapped = buildDiagnosticReport(input().copy(lastSpeedTest = iperf, lastIperf3 = speed)) + assertNull(swapped.speedTest) + assertNull(swapped.iperf3) + assertFalse("HomeNet" in diagnosticReportJson(report), "the speed record's SSID never enters the report") + } + + @Test fun cellularWithoutWifiSectionAndJsonRoundTrip() { + val report = buildDiagnosticReport(input(wifi = null).copy(networkKind = NetKind.CELLULAR, gatewayLatency = null, metered = true)) + assertNull(report.wifi) + val text = diagnosticReportText(report) + assertFalse("== Wi-Fi ==" in text) + assertFalse("Gateway: no data" in text, "no gateway row without Wi-Fi") + assertTrue("Network type: Mobile data" in text) + assertEquals(report, Json.decodeFromString(DiagnosticReport.serializer(), diagnosticReportJson(report))) + } + + /** + * D31 / zadání 53: cell identity (cell ID, TAC/LAC, PCI, EARFCN, operator codes) is location + * data and stays on the phone; SSH and SecureOn secrets never leave their stores. The report + * model has no field that could carry them: checked on the serial descriptor (every nested + * class) and on the keys of a fully populated JSON report. + */ + @Test fun reportModelHasNoCellOrSecretFields() { + val names = descriptorNames(DiagnosticReport.serializer().descriptor) + val keys = jsonKeys(Json.parseToJsonElement(diagnosticReportJson(buildDiagnosticReport(input(), + DiagnosticReportOptions(includeSsid = true, includeBssid = true, includePublicIp = true))))) + assertTrue(keys.isNotEmpty() && names.containsAll(keys)) + val exact = setOf("ci", "eci", "nci", "cid", "tac", "lac", "pci", "psc", "bsic", "mcc", "mnc", "enb", "gnb", "arfcn", "earfcn", + "nrarfcn", "uarfcn", "imsi", "imei", "iccid", "lat", "lon", "latitude", "longitude") + val parts = listOf("cell", "sim", "operator", "carrier", "rsrp", "rsrq", "sinr", "secureon", "password", "passphrase", "secret", + "privatekey", "key", "token", "credential", "snippet", "ssh", "location") + for (name in names) { + val lower = name.lowercase() + assertFalse(lower in exact, "report field '$name' could carry cell identity") + parts.forEach { part -> assertFalse(part in lower, "report field '$name' matches forbidden '$part'") } + } + } + + @Test fun speedShareTextOmitsSsidByDefault() { + val text = speedShareText(speed) + assertTrue(text.startsWith("NetKit speed test\nTime: 2025-12-02T08:45:03.042Z\nNetwork type: Wi-Fi\nServer: Praha (example)\n"), text) + assertTrue("Download: 512.3 Mb/s" in text) + assertTrue("Latency: 7.3 ms" in text || "Latency: 7.2 ms" in text) + assertTrue("Jitter: 0.8 ms" in text) + assertFalse("HomeNet" in text) + assertTrue("SSID: HomeNet" in speedShareText(speed, includeSsid = true)) + val iperfText = speedShareText(iperf) + assertTrue("Engine: iperf3" in iperfText && "Retransmits: 12" in iperfText && "incomplete result: yes" in iperfText, iperfText) + } + + @Test fun localizedLabelsAreUsed() { + val labels = ReportLabels { key -> if (key == ReportLabel.TITLE) "Diagnostický report" else ReportLabels.english.label(key) } + assertTrue(diagnosticReportText(buildDiagnosticReport(input()), labels).startsWith("Diagnostický report\n")) + } + + @Test fun numberFormatting() { + assertEquals("12.3", num(12.34)) + assertEquals("0", num(0.0)) + assertEquals("1500", num(1500.0)) + assertEquals("–", num(null)) + assertEquals("–", num(Double.NaN)) + assertEquals("-0.5", num(-0.5)) + } + + @OptIn(ExperimentalSerializationApi::class) + private fun descriptorNames(descriptor: SerialDescriptor, seen: MutableSet = mutableSetOf()): Set { + if (!seen.add(descriptor.serialName)) return emptySet() + return buildSet { + for (i in 0 until descriptor.elementsCount) { + if (descriptor.kind == StructureKind.CLASS) add(descriptor.getElementName(i)) + addAll(descriptorNames(descriptor.getElementDescriptor(i), seen)) + } + } + } + + private fun jsonKeys(element: JsonElement): Set = when (element) { + is JsonObject -> element.keys + element.values.flatMap { jsonKeys(it) } + is JsonArray -> element.flatMap { jsonKeys(it) }.toSet() + else -> emptySet() + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/settings/AppSettingsTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/settings/AppSettingsTest.kt new file mode 100644 index 0000000..7dfca41 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/settings/AppSettingsTest.kt @@ -0,0 +1,84 @@ +package cz.netkit.shared.settings + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +class AppSettingsTest { + @Test fun defaultsFollowSystemAndKeepScreenOn() { + val settings = AppSettings() + assertEquals(ThemeMode.SYSTEM, settings.theme) + assertTrue(settings.keepScreenOn) + } + + @Test fun themeModeResolvesAgainstSystem() { + for (system in listOf(false, true)) { + assertEquals(system, ThemeMode.SYSTEM.isDark(system)) + assertFalse(ThemeMode.LIGHT.isDark(system)) + assertTrue(ThemeMode.DARK.isDark(system)) + } + } + + @Test fun codecRoundTrip() { + for (theme in ThemeMode.entries) for (keep in listOf(false, true)) { + val settings = AppSettings(theme = theme, keepScreenOn = keep) + assertEquals(settings, AppSettingsCodec.decode(AppSettingsCodec.encode(settings))) + } + // Encoding always writes the current schema. + assertEquals(APP_SETTINGS_SCHEMA, AppSettingsCodec.decode(AppSettingsCodec.encode(AppSettings(schema = 99))).schema) + } + + @Test fun codecIgnoresUnknownKeysAndFillsDefaults() { + assertEquals(AppSettings(theme = ThemeMode.DARK), AppSettingsCodec.decode("""{"schema":1,"theme":"DARK","future":42}""")) + assertEquals(AppSettings(), AppSettingsCodec.decode("""{"schema":1}""")) + } + + @Test fun codecRejectsCorruptInput() { + val bad = listOf( + "", "{", "[]", "null", """{"theme":"DARK"}""", """{"schema":2,"theme":"DARK"}""", + """{"schema":1,"theme":"SEPIA"}""", """{"schema":1,"keepScreenOn":"yes"}""", + """{"schema":1,"x":""" + "[".repeat(40) + "]".repeat(40) + "}", + """{"schema":1,"pad":"""" + "a".repeat(APP_SETTINGS_MAX_BYTES) + "\"}", + ) + for (text in bad) assertFailsWith(text.take(40)) { AppSettingsCodec.decode(text) } + } + + @Test fun languageFromSystemTags() { + assertEquals(AppLanguage.SYSTEM, appLanguageFromTags("")) + assertEquals(AppLanguage.CS, appLanguageFromTags("cs")) + assertEquals(AppLanguage.CS, appLanguageFromTags("cs-CZ")) + assertEquals(AppLanguage.EN, appLanguageFromTags("en-US,cs-CZ")) + assertEquals(AppLanguage.EN, appLanguageFromTags(" EN_gb ")) + // A language the app does not ship falls back to the system choice (and the default resources). + assertEquals(AppLanguage.SYSTEM, appLanguageFromTags("de-DE,en")) + assertNull(AppLanguage.SYSTEM.tag) + assertEquals(listOf("cs", "en"), AppLanguage.entries.mapNotNull { it.tag }) + } + + @Test fun backFromOtherTabsGoesToStart() { + assertNull(tabBackTarget(0)) + for (tab in 1..4) assertEquals(0, tabBackTarget(tab)) + assertNull(tabBackTarget(2, start = 2)) + } + + @Test fun keepScreenOnNeedsSettingAndRun() { + assertTrue(keepScreenOnActive(setting = true, running = true)) + assertFalse(keepScreenOnActive(setting = true, running = false)) + assertFalse(keepScreenOnActive(setting = false, running = true)) + assertFalse(keepScreenOnActive(setting = false, running = false)) + } + + @Test fun overlappingHoldersKeepTheFlag() { + var holders = 0 + holders = screenOnHolders(holders, acquire = true) + holders = screenOnHolders(holders, acquire = true) + holders = screenOnHolders(holders, acquire = false) + assertEquals(1, holders) // one holder still runs: the flag stays on + holders = screenOnHolders(holders, acquire = false) + assertEquals(0, holders) + assertEquals(0, screenOnHolders(holders, acquire = false)) // an extra release never goes negative + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/speed/Iperf3ProtocolTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/speed/Iperf3ProtocolTest.kt new file mode 100644 index 0000000..dca023d --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/speed/Iperf3ProtocolTest.kt @@ -0,0 +1,110 @@ +package cz.netkit.shared.speed + +import kotlinx.serialization.json.* +import kotlin.test.* + +class Iperf3ProtocolTest { + @Test fun serverSequenceAndClientStates() { + val session = Iperf3Handshake() + listOf(9, 10, 1, 2).forEach { session.receive(it.toByte()) } + assertEquals(4.toByte(), session.send(Iperf3State.TEST_END)) + listOf(13, 14).forEach { session.receive(it.toByte()) } + assertEquals(16.toByte(), session.send(Iperf3State.IPERF_DONE)) + assertFails { session.receive(9) } + } + + @Test fun rejectsSkippedDuplicatedOrWrongDirectionStates() { + for (byte in listOf(10, 1, 4, 16, 99)) assertFails { Iperf3Handshake().receive(byte.toByte()) } + Iperf3Handshake().apply { receive(9); assertFails { receive(9) } } + assertFails { Iperf3Handshake().send(Iperf3State.TEST_END) } + for (state in listOf(Iperf3State.SERVER_TERMINATE, Iperf3State.SERVER_ERROR, Iperf3State.ACCESS_DENIED)) { + val session = Iperf3Handshake() + assertEquals(state, assertFailsWith { session.receive(state.wire.toByte()) }.state) + assertFails { session.receive(9) } + } + } + + @Test fun cookieParametersAndFrames() { + val cookie = Iperf3Protocol.cookie("a".repeat(36)) + assertEquals(37, cookie.size) + assertEquals(0.toByte(), cookie.last()) + assertFails { Iperf3Protocol.cookie("á".repeat(36)) } + val params = Iperf3Protocol.parameters(Iperf3Options(2, 3, true, 123456)) + assertEquals(123456L, params.getValue("bandwidth").jsonPrimitive.long) + assertTrue(params.getValue("reverse").jsonPrimitive.boolean) + assertFalse("reverse" in Iperf3Protocol.parameters(Iperf3Options())) + val message = buildJsonObject { put("label", "ž".repeat(200)) } + val wire = Iperf3Protocol.frame(message) + assertEquals(wire.size - 4, Iperf3Protocol.payloadLength(wire.copyOf(4))) + assertEquals(message, Iperf3Protocol.decode(wire.copyOfRange(4, wire.size))) + } + + @Test fun jsonLimitsAndMalformedInputs() { + assertEquals(65536, Iperf3Protocol.payloadLength(byteArrayOf(0, 1, 0, 0))) + listOf(byteArrayOf(0, 1, 0, 1), ByteArray(4), ByteArray(4) { -1 }, ByteArray(3)).forEach { + assertFails { Iperf3Protocol.payloadLength(it) } + } + assertFails { Iperf3Protocol.decode(ByteArray(65537)) } + assertFails { Iperf3Protocol.decode(("{\"x\":" + "[".repeat(16) + "0" + "]".repeat(16) + "}").encodeToByteArray()) } + assertFails { Iperf3Protocol.decode(byteArrayOf(-1)) } + assertFails { Iperf3Protocol.decode("[]".encodeToByteArray()) } + assertFails { Iperf3Options(streams = 9) } + assertFails { Iperf3Options(seconds = 2) } + } + + @Test fun resultIdsAndOptionalCounters() { + val result = Iperf3Protocol.results(Iperf3Options(streams = 2), longArrayOf(100, 200), 3000) + val streams = result.getValue("streams").jsonArray + assertEquals(listOf(1, 3), streams.map { it.jsonObject.getValue("id").jsonPrimitive.int }) + assertNull(Iperf3Protocol.retransmits(result, 2)) + fun counters(ids: List) = buildJsonObject { + putJsonArray("streams") { ids.forEach { addJsonObject { put("id", it); put("retransmits", 2) } } } + } + assertEquals(4L, Iperf3Protocol.retransmits(counters(listOf(3, 1)), 2)) + for (ids in listOf(listOf(1, 1), listOf(1, 2), listOf(1))) { + assertNull(Iperf3Protocol.retransmits(counters(ids), 2)) + } + } + + @Test fun uploadUsesReceiverBytesAndLastServerEndTime() { + val result = Iperf3Protocol.decode("""{"streams":[{"id":3,"bytes":750000,"end_time":3.125},{"id":1,"bytes":500000,"end_time":3.0},{"id":4,"bytes":0,"end_time":3.0}]}""".encodeToByteArray()) + val receiver = assertNotNull(Iperf3Protocol.receiver(result, Iperf3Options(streams = 3, seconds = 3))) + assertEquals(Iperf3Receiver(1_250_000, 3125.0, 2), receiver) + assertEquals(3.2, receiver.mbps) + } + + @Test fun unusableReceiverFieldsAndIntervalsReturnNull() { + val options = Iperf3Options(streams = 2, seconds = 10) + fun receiver(row: String) = Iperf3Protocol.receiver(Iperf3Protocol.decode( + """{"streams":[{"bytes":1,"end_time":10},$row]}""".encodeToByteArray()), options) + for (row in listOf( + """{"end_time":10}""", """{"bytes":1}""", """{"bytes":"1","end_time":10}""", + """{"bytes":-1,"end_time":10}""", """{"bytes":1.5,"end_time":10}""", + """{"bytes":9223372036854775807,"end_time":10}""", """{"bytes":1,"end_time":"10"}""", + """{"bytes":1,"end_time":1e999}""", """{"bytes":1,"end_time":4.999}""", + """{"bytes":1,"end_time":20.001}""", """{"bytes":{},"end_time":null}""", "null" + )) assertNull(receiver(row), row) + for (end in listOf(5, 20)) assertNotNull(receiver("""{"bytes":0,"end_time":$end}""")) + } + + @Test fun negotiatesRateSizedBlocksInBothDirections() { + for (reverse in listOf(false, true)) { + for ((rate, expected) in listOf(0L to 131072, 1L to 1024, 100_000L to 1250, + 2_000_000L to 25000, 1_000_000_000_000L to 131072)) { + val options = Iperf3Options(reverse = reverse, bitsPerSecond = rate) + assertEquals(expected, Iperf3Protocol.parameters(options).getValue("len").jsonPrimitive.int) + } + } + } + + @Test fun preferencesAndUploadOnlyHistory() { + val old = SpeedStoreCodec.decode("""{"schema":1,"records":[]}""") + assertEquals("", old.iperfHost) + assertEquals(5201, old.iperfPort) + val record = SpeedRecord(1, SpeedEngine.IPERF3, "test.invalid", uploadMbps = 1.5, retransmits = 4) + val data = old.copy(iperfHost = "test.invalid", iperfPort = 5202).withRecord(record) + val stored = SpeedStoreCodec.encode(data) + assertTrue("\"iperf3\"" in stored) + assertEquals(data, SpeedStoreCodec.decode(stored)) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedDataEstimateTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedDataEstimateTest.kt index bc7951d..a0a6d30 100644 --- a/shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedDataEstimateTest.kt +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedDataEstimateTest.kt @@ -8,32 +8,76 @@ class SpeedDataEstimateTest { SpeedRecord(ts, SpeedEngine.LIBRESPEED, "zelina", downloadMbps = down, uploadMbps = up, networkKind = kind) @Test fun withoutHistoryIsConservative() { - assertEquals(SpeedDataEstimate(SPEED_DATA_FALLBACK_MB, false), estimateSpeedTestData(SpeedEngine.LIBRESPEED, emptyList(), NetKind.CELLULAR)) + assertEquals(SpeedDataEstimate.Approximate(SPEED_DATA_FALLBACK_MB, false), estimateSpeedTestData(SpeedEngine.LIBRESPEED, emptyList(), NetKind.CELLULAR)) assertEquals(200, SPEED_DATA_FALLBACK_MB) } @Test fun usesNewestResultOfTheSameKind() { // 100 Mbit/s down and 20 up for 10 s each: 125 + 25 = 150 MB, × 1.2 = 180 MB. val history = listOf(record(NetKind.WIFI, 900.0, 900.0, 3), record(NetKind.CELLULAR, 100.0, 20.0, 2), record(NetKind.CELLULAR, 5.0, 1.0, 1)) - assertEquals(SpeedDataEstimate(180, true), estimateSpeedTestData(SpeedEngine.LIBRESPEED, history, NetKind.CELLULAR)) + assertEquals(SpeedDataEstimate.Approximate(180, true), estimateSpeedTestData(SpeedEngine.LIBRESPEED, history, NetKind.CELLULAR)) } @Test fun ndt7UsesTheLongerDownloadCap() { // 100 × 15 s + 20 × 10 s = 1700 Mbit = 212.5 MB, × 1.2 = 255 → 260 MB. val history = listOf(record(NetKind.CELLULAR, 100.0, 20.0)) - assertEquals(260, estimateSpeedTestData(SpeedEngine.NDT7, history, NetKind.CELLULAR).megabytes) + assertEquals(SpeedDataEstimate.Approximate(260, true), estimateSpeedTestData(SpeedEngine.NDT7, history, NetKind.CELLULAR)) + } + + @Test fun unlimitedIperfWarnsEvenWithUsableHistory() { + val history = listOf(record(NetKind.CELLULAR, 100.0, 20.0)) + for (reverse in listOf(false, true)) { + val options = Iperf3Options(streams = 8, reverse = reverse) + for (records in listOf(emptyList(), history)) { + assertEquals(SpeedDataEstimate.Unlimited, + estimateSpeedTestData(SpeedEngine.IPERF3, records, NetKind.CELLULAR, options)) + } + } + } + + @Test fun limitedIperfCountsEachStreamForOneDirection() { + val options = Iperf3Options(streams = 2, seconds = 10, bitsPerSecond = 2_000_000) + for (reverse in listOf(false, true)) { + assertEquals(SpeedDataEstimate.PayloadUpperBound(if (reverse) 7 else 5), + estimateSpeedTestData(SpeedEngine.IPERF3, emptyList(), NetKind.CELLULAR, options.copy(reverse = reverse))) + } + } + + @Test fun limitedIperfRoundsUpAndHandlesTheMaximumRate() { + fun bound(options: Iperf3Options) = estimateSpeedTestData(SpeedEngine.IPERF3, emptyList(), NetKind.WIFI, options) + val short = Iperf3Options(streams = 2, seconds = 3, reverse = true, bitsPerSecond = 10_000_000) + assertEquals(11_250_000L, short.payloadLimitBytes) + assertEquals(SpeedDataEstimate.PayloadUpperBound(12), bound(short)) + assertEquals(SpeedDataEstimate.PayloadUpperBound(1), bound(Iperf3Options(bitsPerSecond = 10_000))) + val maximum = Iperf3Options(streams = 8, seconds = 30, bitsPerSecond = 1_000_000_000_000) + assertEquals(SpeedDataEstimate.PayloadUpperBound(30_000_000), bound(maximum)) + assertEquals(SpeedDataEstimate.PayloadUpperBound(34_000_003), bound(maximum.copy(reverse = true))) + } + + @Test fun privateServerRatesNeverFeedTheMeteredEstimate() { + val internet = record(NetKind.CELLULAR, 100.0, 20.0) + val privateServer = internet.copy(engine = SpeedEngine.IPERF3, downloadMbps = 2.0, uploadMbps = null) + val privateUpload = privateServer.copy(downloadMbps = null, uploadMbps = 1.0) + for (engine in SpeedEngine.entries) { + for (reverse in listOf(false, true)) { + val options = Iperf3Options(reverse = reverse) + fun estimate(history: List) = estimateSpeedTestData(engine, history, NetKind.CELLULAR, options) + assertEquals(estimate(emptyList()), estimate(listOf(privateServer, privateUpload))) + assertEquals(estimate(listOf(internet)), estimate(listOf(privateServer, privateUpload, internet))) + } + } } @Test fun missingUploadCountsAsDownloadAndSmallValuesRoundUp() { // 40 × 10 + 40 × 10 = 800 Mbit = 100 MB, × 1.2 = 120 MB. - assertEquals(120, estimateSpeedTestData(SpeedEngine.LIBRESPEED, listOf(record(NetKind.CELLULAR, 40.0)), NetKind.CELLULAR).megabytes) - assertEquals(10, estimateSpeedTestData(SpeedEngine.LIBRESPEED, listOf(record(NetKind.CELLULAR, 0.5, 0.1)), NetKind.CELLULAR).megabytes) + assertEquals(SpeedDataEstimate.Approximate(120, true), estimateSpeedTestData(SpeedEngine.LIBRESPEED, listOf(record(NetKind.CELLULAR, 40.0)), NetKind.CELLULAR)) + assertEquals(SpeedDataEstimate.Approximate(10, true), estimateSpeedTestData(SpeedEngine.LIBRESPEED, listOf(record(NetKind.CELLULAR, 0.5, 0.1)), NetKind.CELLULAR)) } @Test fun oldRecordsCountAsWifiAndFailedOnesAreSkipped() { val history = listOf(record(NetKind.CELLULAR, null), record(null, 80.0, 80.0)) - assertEquals(SpeedDataEstimate(200, false), estimateSpeedTestData(SpeedEngine.LIBRESPEED, history, NetKind.CELLULAR)) + assertEquals(SpeedDataEstimate.Approximate(200, false), estimateSpeedTestData(SpeedEngine.LIBRESPEED, history, NetKind.CELLULAR)) // 80 × 10 × 2 = 1600 Mbit = 200 MB, × 1.2 = 240 MB. - assertEquals(SpeedDataEstimate(240, true), estimateSpeedTestData(SpeedEngine.LIBRESPEED, history, NetKind.WIFI)) + assertEquals(SpeedDataEstimate.Approximate(240, true), estimateSpeedTestData(SpeedEngine.LIBRESPEED, history, NetKind.WIFI)) } } diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedHistoryClearTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedHistoryClearTest.kt new file mode 100644 index 0000000..aadc72a --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedHistoryClearTest.kt @@ -0,0 +1,52 @@ +package cz.netkit.shared.speed + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class SpeedHistoryClearTest { + private fun record(engine: SpeedEngine, ts: Long) = SpeedRecord(ts, engine, "server-$ts") + private val data = SpeedStoreData( + ndt7ConsentMs = 1_000L, + records = listOf(record(SpeedEngine.IPERF3, 5), record(SpeedEngine.LIBRESPEED, 4), record(SpeedEngine.NDT7, 3), record(SpeedEngine.IPERF3, 2)), + iperfHost = "192.0.2.10", iperfPort = 5202, + ) + + @Test fun countsByKind() { + assertEquals(2, data.records.countOf(SpeedHistoryKind.SPEED_TEST)) + assertEquals(2, data.records.countOf(SpeedHistoryKind.IPERF3)) + } + + @Test fun clearingSpeedTestKeepsIperf3AndEverythingElse() { + val cleared = data.withoutHistory(SpeedHistoryKind.SPEED_TEST) + assertEquals(listOf(5L, 2L), cleared.records.map { it.timestampMs }) + assertEquals(data.copy(records = cleared.records), cleared) + } + + @Test fun clearingIperf3KeepsSpeedTestAndTarget() { + val cleared = data.withoutHistory(SpeedHistoryKind.IPERF3) + assertEquals(listOf(SpeedEngine.LIBRESPEED, SpeedEngine.NDT7), cleared.records.map { it.engine }) + assertEquals("192.0.2.10", cleared.iperfHost) + assertEquals(1_000L, cleared.ndt7ConsentMs) + } + + @Test fun forgettingTargetAndConsent() { + val noTarget = data.withoutIperfTarget() + assertEquals("", noTarget.iperfHost) + assertEquals(5201, noTarget.iperfPort) + assertEquals(data.records, noTarget.records) + val noConsent = data.withoutNdt7Consent() + assertNull(noConsent.ndt7ConsentMs) + assertEquals(data.copy(ndt7ConsentMs = null), noConsent) + // The cleared store still encodes and decodes. + assertEquals(noTarget.withoutNdt7Consent(), SpeedStoreCodec.decode(SpeedStoreCodec.encode(noTarget.withoutNdt7Consent()))) + } + + /** Settings shows the stored server, never the edited form (revize kolo 1). */ + @Test fun savedIperfTargetComesFromTheStore() { + assertEquals("192.0.2.10:5202", data.savedIperfTarget()) + assertEquals("[2001:db8::10]:5201", data.copy(iperfHost = "2001:db8::10", iperfPort = 5201).savedIperfTarget()) + assertNull(data.withoutIperfTarget().savedIperfTarget()) + assertNull(data.copy(iperfHost = " ").savedIperfTarget()) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SftpTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SftpTest.kt new file mode 100644 index 0000000..0b2c001 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SftpTest.kt @@ -0,0 +1,59 @@ +package cz.netkit.shared.ssh + +import kotlin.test.* + +class SftpTest { + @Test fun namesAreSinglePathElements() { + listOf("a", "file.txt", ".bashrc", "..x", "x..", "mezera v názvu", "a".repeat(SFTP_MAX_NAME)).forEach { + assertTrue(isValidSftpName(it), it) + } + listOf("", ".", "..", "a/b", "/", "../etc", "a\u0000b", "a\nb", "a\u007fb", "a".repeat(SFTP_MAX_NAME + 1)).forEach { + assertFalse(isValidSftpName(it), it) + } + } + + @Test fun childPathsNeverContainDotDot() { + assertEquals("/a", sftpChild("/", "a")) + assertEquals("/home/u/a", sftpChild("/home/u", "a")) + assertEquals("/home/u/a", sftpChild("/home/u/", "a")) + assertFailsWith { sftpChild("/home", "..") } + assertFailsWith { sftpChild("/home", "../etc") } + assertFailsWith { sftpChild("relative", "a") } + } + + @Test fun parentIsOnlyARealpathRequest() { + assertEquals("/home/u/..", sftpParentRequest("/home/u")) + assertEquals("/..", sftpParentRequest("/")) + assertFailsWith { sftpParentRequest("home") } + } + + @Test fun displayNameHidesControlAndBidi() { + assertEquals("a?b", displaySftpName("a\u001bb")) + assertEquals("invoice?fdp.exe", displaySftpName("invoice‮fdp.exe")) + assertEquals("x?y", displaySftpName("x⁦y")) + assertEquals("Žluťoučký kůň.txt", displaySftpName("Žluťoučký kůň.txt")) + assertEquals(SFTP_MAX_NAME, displaySftpName("a".repeat(400)).length) + } + + @Test fun directoriesFirstThenName() { + val sorted = sortSftpEntries(listOf( + SftpEntry("b.txt", SftpEntryKind.FILE, 1, 0), SftpEntry("Zeta", SftpEntryKind.DIRECTORY, 0, 0), + SftpEntry("a-link", SftpEntryKind.LINK, 0, 0), SftpEntry("alpha", SftpEntryKind.DIRECTORY, 0, 0), + SftpEntry("B.txt", SftpEntryKind.FILE, 1, 0))) + assertEquals(listOf("alpha", "Zeta", "a-link", "B.txt", "b.txt"), sorted.map { it.name }) + } + + @Test fun statusCodesAndLimits() { + assertEquals(SftpFailure.NOT_FOUND, sftpFailureForStatus(2)) + assertEquals(SftpFailure.PERMISSION, sftpFailureForStatus(3)) + assertEquals(SftpFailure.FAILURE, sftpFailureForStatus(4)) + assertEquals(SftpFailure.CONNECTION, sftpFailureForStatus(7)) + assertEquals(SftpFailure.UNSUPPORTED, sftpFailureForStatus(8)) + assertEquals(2_147_483_648L, SFTP_MAX_FILE_BYTES) + assertTrue(sftpSizeAllowed(SFTP_MAX_FILE_BYTES)) + assertFalse(sftpSizeAllowed(SFTP_MAX_FILE_BYTES + 1)) + assertTrue(sftpSizeAllowed(null)); assertTrue(sftpSizeAllowed(-1)) + assertNull(sftpProgress(10, null)); assertNull(sftpProgress(10, 0)) + assertEquals(0.5f, sftpProgress(5, 10)); assertEquals(1f, sftpProgress(20, 10)) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt index 1bc1065..b52c093 100644 --- a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt @@ -27,3 +27,35 @@ class SshBackgroundPolicyTest { assertFalse(policy.expired()) } } + +class SshKeepAliveTest { + @Test fun serviceOnlyWithLiveSessionAndNotifications() { + assertFalse(sshServiceWanted(0, true), "no session → no service") + assertFalse(sshServiceWanted(2, false), "notifications denied → 5-minute fallback, no service") + assertTrue(sshServiceWanted(1, true)) + } + @Test fun serviceKeepsSessionsPastTheDeadline() { + assertTrue(sshBackgroundCloses(expired = true, serviceForeground = false)) + assertFalse(sshBackgroundCloses(expired = true, serviceForeground = true)) + assertFalse(sshBackgroundCloses(expired = false, serviceForeground = false)) + } + /** iOS calls `SshBackgroundPolicy(nowMillis)` with a function value (not a trailing lambda): keep that form. */ + @Test fun positionalClockKeepsTheFiveMinuteDefault() { + var now = 0L + val clock: () -> Long = { now } + val policy = SshBackgroundPolicy(clock) + policy.background() + assertEquals(SshBackgroundPolicy.BACKGROUND_GRACE_MILLIS, policy.remainingMillis()) + now = SshBackgroundPolicy.BACKGROUND_GRACE_MILLIS + assertTrue(policy.expired()) + } + @Test fun shortenedGraceForInstrumentation() { + var now = 0L + val policy = SshBackgroundPolicy(graceMillis = 3000) { now } + policy.background() + assertEquals(3000L, policy.remainingMillis()) + now = 3000 + assertTrue(policy.expired()) + assertFailsWith { SshBackgroundPolicy(graceMillis = 0) { 0L } } + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshDirectoryTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshDirectoryTest.kt new file mode 100644 index 0000000..e384144 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshDirectoryTest.kt @@ -0,0 +1,102 @@ +package cz.netkit.shared.ssh + +import kotlinx.serialization.json.Json +import kotlin.test.* + +class SshDirectoryTest { + private val ssh = SshProfile("one", "B", "192.0.2.1", username = "Operator", group = "Lab") + private val telnet = ConsoleProfile("one", "C", ConsoleKind.TELNET, "192.0.2.2", group = "Lab") + private val serial = ConsoleProfile("two", "A", ConsoleKind.SERIAL, group = "Lab") + private val source = SshData(profiles = listOf(ssh), consoles = listOf(telnet, serial)) + + @Test fun allTransportsSearchByAvailableFieldsAndGroup() { + for ((term, expected) in listOf("OpEr" to listOf(ssh), " 192.0.2.2 " to listOf(telnet), + "A" to listOf(telnet, serial, ssh), "laB" to listOf(telnet, serial, ssh), "missing" to emptyList())) { + assertEquals(expected, source.profileGroups(term, ProfileSort.MANUAL).values.flatten()) + } + val ungrouped = serial.copy(group = null) + assertEquals(listOf(ungrouped), source.copy(consoles = listOf(ungrouped)) + .profileGroups("", ProfileSort.MANUAL)[null]) + } + + @Test fun mixedManualOrderAndRecencySurviveSerializationAndNeverCollide() { + val swapped = source.swapProfiles(telnet.listKey, ssh.listKey) + val used = swapped.profileUsed(ssh.listKey).profileUsed(telnet.listKey).profileUsed(ssh.listKey) + val roundtrip = Json.decodeFromString(Json.encodeToString(used)) + fun names(sort: ProfileSort) = roundtrip.profileGroups("", sort)["Lab"]!!.map { it.name } + assertEquals(listOf("B", "A", "C"), names(ProfileSort.MANUAL)) + assertEquals(listOf("A", "B", "C"), names(ProfileSort.ALPHABETICAL)) + assertEquals(listOf("B", "C", "A"), names(ProfileSort.RECENT)) + assertEquals(listOf(ssh.listKey, telnet.listKey), roundtrip.recentProfiles) + assertSame(used, used.profileUsed("ssh:deleted")) + } + + @Test fun optionalGroupRoundTripsAndOldImportsPreserveLocalGroups() { + fun wire(profile: SshProfile) = encodeSshProfileExport(SshData(profiles = listOf(profile)), "test") + val incoming = decodeSshProfileImport(wire(ssh)) + val added = applySshImportPlan(SshData(), planSshProfileImport(SshData(), incoming, null) { "new" }) + assertEquals("Lab", added.profiles.single().group) + val older = wire(ssh.copy(group = null)) + assertFalse("group" in older.decodeToString()) + assertEquals(source, applySshImportPlan(source, planSshProfileImport(source, decodeSshProfileImport(older), null) { error("new") })) + for (invalid in listOf(" ", "a\nb", "x".repeat(61))) { + assertFalse(ssh.copy(group = invalid).valid()) + assertFalse(telnet.copy(group = invalid).valid()) + } + } + + @Test fun deadlineIsExclusiveAndZeroNeverReusesAnAuthentication() { + assertTrue(SshUnlock().canReuse(0)) + assertEquals(5, SshUnlock().minutes) + for (minutes in 0..15) { + val locked = SshUnlock(enabled = true, minutes = minutes) + assertFalse(locked.canView(100)) + val grant = locked.copy(authenticatedAt = 100L) + assertTrue(grant.canView(100)) + assertFalse(grant.canReuse(99)) + if (minutes > 0) assertTrue(grant.canReuse(99 + minutes * 60_000L)) + assertFalse(grant.canReuse(100 + minutes * 60_000L)) + } + assertFailsWith { SshUnlock(true, 16) } + } + + @Test fun enablingAfterAuthenticationKeepsTheGrantAndStartsTheTimer() { + // setEnabled authenticates while the stored settings are still "off": no timer yet. + val off = SshUnlock(enabled = false, minutes = 5, authenticatedAt = 1_000L) + assertNull(off.expiresIn(1_000)) + val on = off.reconfigure(enabled = true, minutes = 5, now = 1_200) + assertEquals(1_000L, on.authenticatedAt) + assertTrue(on.canView(1_200) && on.canReuse(1_200)) + assertEquals(5 * 60_000L - 200, on.expiresIn(1_200)) + // Not authenticated: enabling locks, nothing to time. + val locked = SshUnlock().reconfigure(enabled = true, minutes = 5, now = 1_200) + assertFalse(locked.canView(1_200)) + assertNull(locked.expiresIn(1_200)) + } + + @Test fun shorterLimitIsJudgedFromTheOriginalAuthentication() { + val grant = SshUnlock(enabled = true, minutes = 5, authenticatedAt = 0L) + val soon = grant.reconfigure(enabled = true, minutes = 1, now = 30_000) + assertEquals(0L, soon.authenticatedAt) + assertTrue(soon.canView(30_000)) + assertEquals(30_000L, soon.expiresIn(30_000)) + assertFalse(soon.canView(60_000)) + val late = grant.reconfigure(enabled = true, minutes = 1, now = 120_000) + assertNull(late.authenticatedAt) + assertFalse(late.canView(120_000)) + assertNull(late.expiresIn(120_000)) + } + + @Test fun zeroKeepsTheCurrentViewButNotTheNextAction() { + val grant = SshUnlock(enabled = true, minutes = 5, authenticatedAt = 0L) + val zero = grant.reconfigure(enabled = true, minutes = 0, now = 30_000) + assertEquals(0L, zero.authenticatedAt) + assertTrue(zero.canView(30_000)) + assertFalse(zero.canReuse(30_000)) + assertNull(zero.expiresIn(30_000)) + // Disabling keeps everything reusable and needs no timer. + val disabled = grant.reconfigure(enabled = false, minutes = 5, now = 30_000) + assertTrue(disabled.canReuse(30_000)) + assertNull(disabled.expiresIn(30_000)) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshExportProductivityTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshExportProductivityTest.kt new file mode 100644 index 0000000..dc458b7 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshExportProductivityTest.kt @@ -0,0 +1,177 @@ +package cz.netkit.shared.ssh + +import kotlinx.serialization.json.* +import kotlin.test.* + +/** Zadání 41: optional proxyJump and snippets in the v2 exchange file, compatible with v1/v2/legacy files. */ +class SshExportProductivityTest { + private val bastion = SshProfile("b", "Bastion", "192.0.2.1", username = "ops") + private val inner = SshProfile("i", "Inner", "10.0.0.5", username = "admin", jumpProfileId = "b", + localForwards = listOf(SshLocalForward(8080, "127.0.0.1", 80)), dynamicForwardPort = 1080) + private val source = SshData(profiles = listOf(bastion, inner), snippets = listOf( + SshSnippet("s1", "Verze", "show version"), SshSnippet("s2", "Logy", "tail -n 50 /var/log/messages", sendEnter = false, profileId = "i"))) + + private fun ids(): () -> String { var next = 0; return { "new-${next++}" } } + private fun restore(bytes: ByteArray, current: SshData = SshData()): SshData = + applySshImportPlan(current, planSshProfileImport(current, decodeSshProfileImport(bytes), null, ids())) + + @Test fun roundtripCarriesJumpAliasAndSnippetsButNotForwards() { + val bytes = encodeSshProfileExport(source, "netkit-android") + val root = Json.parseToJsonElement(bytes.decodeToString()).jsonObject + assertEquals(setOf("format", "schema", "source", "profiles", "skipped", "snippets"), root.keys) + val rows = root.getValue("profiles").jsonArray.map { it.jsonObject } + assertFalse("proxyJump" in rows[0]) + assertEquals("Bastion", rows[1].getValue("proxyJump").jsonPrimitive.content) + assertTrue(rows.none { "localForwards" in it || "dynamicForwardPort" in it }) + val restored = restore(bytes) + val (b, i) = restored.profiles + assertEquals(b.id, i.jumpProfileId) + assertEquals(emptyList(), i.localForwards) + assertEquals(listOf("Verze" to null, "Logy" to i.id), restored.snippets.map { it.name to it.profileId }) + assertEquals(listOf(false, false), restored.snippets.map { it.sendEnter }) // Enter only after the user enables it. + assertTrue(restored.valid()) + } + + @Test fun fileWithoutNewFieldsIsUnchangedForOlderImporters() { + val plain = SshData(profiles = listOf(bastion)) + val root = Json.parseToJsonElement(encodeSshProfileExport(plain, "netkit-android").decodeToString()).jsonObject + assertEquals(setOf("format", "schema", "source", "profiles", "skipped"), root.keys) + assertEquals(setOf("alias", "host", "port", "username", "authentication", "startupCommand", "keepaliveSeconds"), + root.getValue("profiles").jsonArray.single().jsonObject.keys) + } + + @Test fun olderFilesStillImport() { + val v1 = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"A","host":"192.0.2.9","port":22,"username":"u"}],"skipped":[{"alias":"J","reason":"PROXY_JUMP"}]}""" + val v2 = """{"format":"netkit-ssh-profiles","schema":2,"source":"netkit-android","profiles":[{"alias":"A","host":"192.0.2.9","port":22,"username":"u","authentication":"PASSWORD","startupCommand":"","keepaliveSeconds":30}],"skipped":[]}""" + for (text in listOf(v1, v2, LEGACY_SSH_EXPORT)) { + val decoded = decodeSshProfileImport(text.encodeToByteArray()) + assertEquals(emptyList(), decoded.snippets) + assertTrue(decoded.profiles.all { it.proxyJump == null }) + assertTrue(restore(text.encodeToByteArray()).valid()) + } + } + + @Test fun v1FromPcScriptMayCarryProxyJumpButNotSnippets() { + val v1 = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"jump","host":"192.0.2.1","port":22,"username":"u"},{"alias":"db","host":"10.0.0.9","port":22,"username":"u","proxyJump":"jump"}],"skipped":[]}""" + val data = restore(v1.encodeToByteArray()) + assertEquals(data.profiles[0].id, data.profiles[1].jumpProfileId) + val withSnippets = v1.replace("\"skipped\":[]", "\"skipped\":[],\"snippets\":[]") + assertEquals(SshProfileImportFailure.UNKNOWN_FIELD, + assertFailsWith { decodeSshProfileImport(withSnippets.encodeToByteArray()) }.reason) + } + + @Test fun unresolvedJumpAliasMovesRowToSkippedAndKeepsOthers() { + val text = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"ok","host":"192.0.2.1","port":22,"username":"u"},{"alias":"db","host":"10.0.0.9","port":22,"username":"u","proxyJump":"nowhere"}],"skipped":[]}""" + val plan = planSshProfileImport(SshData(), decodeSshProfileImport(text.encodeToByteArray()), null, ids()) + assertEquals(listOf("ok"), plan.newProfiles.map { it.after.name }) + assertEquals(listOf("new-0", "new-1"), plan.generatedIds) // The skipped row also drew an id. + assertEquals(listOf(SshImportSkipped("db", SshImportSkipReason.PROXY_JUMP)), plan.skipped) + } + + @Test fun jumpResolvesToExistingLocalProfileByAlias() { + val current = SshData(profiles = listOf(bastion)) + val text = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"db","host":"10.0.0.9","port":22,"username":"u","proxyJump":"Bastion"}],"skipped":[]}""" + assertEquals("b", restore(text.encodeToByteArray(), current).profiles.last().jumpProfileId) + } + + @Test fun cyclesAndOverlongChainsAreSkippedTransitively() { + val cycle = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"x","host":"192.0.2.1","port":22,"username":"u","proxyJump":"y"},{"alias":"y","host":"192.0.2.2","port":22,"username":"u","proxyJump":"x"},{"alias":"z","host":"192.0.2.3","port":22,"username":"u","proxyJump":"x"}],"skipped":[]}""" + val plan = planSshProfileImport(SshData(), decodeSshProfileImport(cycle.encodeToByteArray()), null, ids()) + assertEquals(emptyList(), plan.newProfiles) + assertEquals(setOf("x", "y", "z"), plan.skipped.map { it.alias }.toSet()) + val rows = (0..4).joinToString(",") { i -> + """{"alias":"h$i","host":"192.0.2.${i + 1}","port":22,"username":"u"""" + (if (i > 0) ""","proxyJump":"h${i - 1}"""" else "") + "}" + } + val long = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[$rows],"skipped":[]}""" + val chained = planSshProfileImport(SshData(), decodeSshProfileImport(long.encodeToByteArray()), null, ids()) + assertEquals(listOf("h0", "h1", "h2", "h3"), chained.newProfiles.map { it.after.name }) + assertEquals(listOf(SshImportSkipped("h4", SshImportSkipReason.PROXY_JUMP)), chained.skipped) + } + + /** Review of 41 (P2): iOS cannot connect through a jump host, so such rows must not import as direct profiles. */ + @Test fun platformWithoutProxyJumpSkipsJumpRowsInsteadOfConnectingDirectly() { + val text = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"jump","host":"192.0.2.1","port":22,"username":"u"},{"alias":"db","host":"10.0.0.9","port":22,"username":"u","proxyJump":"jump"}],"skipped":[]}""" + val plan = planSshProfileImport(SshData(), decodeSshProfileImport(text.encodeToByteArray()), null, supportsProxyJump = false, generateId = ids()) + assertEquals(listOf("jump"), plan.newProfiles.map { it.after.name }) + assertTrue(plan.newProfiles.all { it.after.jumpProfileId == null }) + assertEquals(listOf(SshImportSkipped("db", SshImportSkipReason.PROXY_JUMP)), plan.skipped) + // An update of a local profile that already has a jump host is skipped too (it would stay unusable or go direct). + val current = SshData(profiles = listOf(bastion, inner)) + val update = """{"format":"netkit-ssh-profiles","schema":2,"profiles":[{"alias":"Inner","host":"10.0.0.6","port":22,"username":"admin","authentication":"PASSWORD","startupCommand":"","keepaliveSeconds":30}],"skipped":[]}""" + val skipped = planSshProfileImport(current, decodeSshProfileImport(update.encodeToByteArray()), null, supportsProxyJump = false, generateId = ids()) + assertEquals(emptyList(), skipped.updatedProfiles + skipped.unchangedProfiles) + assertEquals(listOf(SshImportSkipped("Inner", SshImportSkipReason.PROXY_JUMP)), skipped.skipped) + // Android keeps the jump link. + assertEquals("b", planSshProfileImport(current, decodeSshProfileImport(update.encodeToByteArray()), null, ids()).updatedProfiles.single().after.jumpProfileId) + } + + @Test fun rowWithoutProxyJumpKeepsLocalLink() { + val current = SshData(profiles = listOf(bastion, inner)) + val text = """{"format":"netkit-ssh-profiles","schema":2,"profiles":[{"alias":"Inner","host":"10.0.0.6","port":22,"username":"admin","authentication":"PASSWORD","startupCommand":"","keepaliveSeconds":30}],"skipped":[]}""" + val updated = restore(text.encodeToByteArray(), current).profiles.single { it.id == "i" } + assertEquals("b", updated.jumpProfileId) + assertEquals(inner.localForwards, updated.localForwards) // Local-only forwards survive an update. + assertEquals(1080, updated.dynamicForwardPort) + } + + @Test fun snippetsMergeByNameAndScope() { + val current = SshData(profiles = listOf(bastion), snippets = listOf(SshSnippet("old", "Verze", "show ver"))) + val bytes = encodeSshProfileExport(source, "netkit-android") + val plan = planSshProfileImport(current, decodeSshProfileImport(bytes), null, ids()) + assertEquals(1, plan.updatedSnippets) + assertEquals(1, plan.newSnippets) + assertEquals(listOf(SshSnippet("old", "Verze", "show ver") to SshSnippet("old", "Verze", "show version", sendEnter = false)), + plan.snippetChanges.filter { it.before != null }.map { it.before to it.after }) + assertEquals(listOf("new-0", "new-1"), plan.generatedIds) // Inner profile, then its snippet. + val result = applySshImportPlan(current, plan) + assertEquals(listOf("old", "new-1"), result.snippets.map { it.id }) + assertEquals("show version", result.snippets[0].text) + assertFalse(result.snippets[0].sendEnter) + // Same text from the file keeps the local Enter choice and is not a change. + val enabled = result.copy(snippets = result.snippets.map { it.copy(sendEnter = true) }) + assertEquals(emptyList(), planSshProfileImport(enabled, decodeSshProfileImport(bytes), null, ids()).snippetChanges) + assertEquals(0, planSshProfileImport(result, decodeSshProfileImport(bytes), null, ids()).let { it.newSnippets + it.updatedSnippets }) + } + + @Test fun invalidSnippetRowsRejectWholeFile() { + fun doc(snippets: String) = """{"format":"netkit-ssh-profiles","schema":2,"profiles":[{"alias":"A","host":"192.0.2.9","port":22,"username":"u","authentication":"PASSWORD","startupCommand":"","keepaliveSeconds":30}],"skipped":[],"snippets":$snippets}""" + fun reason(snippets: String) = assertFailsWith { decodeSshProfileImport(doc(snippets).encodeToByteArray()) }.reason + assertEquals(SshProfileImportFailure.INVALID_PROFILE, reason("""[{"name":"n","text":"a\nb","sendEnter":true}]""")) + assertEquals(SshProfileImportFailure.INVALID_PROFILE, reason("""[{"name":"n","text":"x","sendEnter":true,"profile":"Missing"}]""")) + assertEquals(SshProfileImportFailure.UNKNOWN_FIELD, reason("""[{"name":"n","text":"x","sendEnter":true,"id":"s"}]""")) + assertEquals(SshProfileImportFailure.FORMAT, reason("""[{"name":"n","text":"x","sendEnter":"yes"}]""")) + assertEquals(SshProfileImportFailure.DUPLICATE_ALIAS, reason("""[{"name":"n","text":"x","sendEnter":true},{"name":"n","text":"y","sendEnter":true}]""")) + val many = (0..SSH_MAX_SNIPPETS).joinToString(",") { """{"name":"n$it","text":"x","sendEnter":true}""" } + assertEquals(SshProfileImportFailure.LIMIT, reason("[$many]")) + assertEquals(1, decodeSshProfileImport(doc("""[{"name":"n","text":"x","sendEnter":true,"profile":"A"}]""").encodeToByteArray()).snippets.size) + } + + @Test fun selfJumpOrInvalidAliasIsInvalidProfile() { + val self = """{"format":"netkit-ssh-profiles","schema":1,"profiles":[{"alias":"x","host":"192.0.2.1","port":22,"username":"u","proxyJump":"x"}],"skipped":[]}""" + assertEquals(SshProfileImportFailure.INVALID_PROFILE, + assertFailsWith { decodeSshProfileImport(self.encodeToByteArray()) }.reason) + } + + @Test fun stalePlanDetectsSnippetEdits() { + val current = SshData(profiles = listOf(bastion)) + val plan = planSshProfileImport(current, decodeSshProfileImport(encodeSshProfileExport(source, "netkit-android")), null, ids()) + val edited = current.copy(snippets = listOf(SshSnippet("x", "n", "x"))) + assertEquals(SshProfileImportFailure.STALE_PLAN, assertFailsWith { applySshImportPlan(edited, plan) }.reason) + } +} + +class SshLegacyStoreFieldsTest { + private val base = """{"schema":1,"profiles":[{"id":"x","name":"A","host":"192.0.2.1","port":22,"username":"u","authentication":"PASSWORD","secretRef":null,"keyRef":null,"startupCommand":"","keepaliveSeconds":30ROW}],"hostKeys":[],"keys":[],"rejectedHostKeys":[]ROOT}""" + private fun decode(row: String, root: String = "") = decodeSshProfileImport(base.replace("ROW", row).replace("ROOT", root).encodeToByteArray()) + + @Test fun defaultValuedNewStoreFieldsAreTolerated() { + assertEquals(1, decode(""","jumpProfileId":null,"localForwards":[],"dynamicForwardPort":null,"dynamicForwardNoAuth":false""", ""","snippets":[]""").profiles.size) + } + + @Test fun nonDefaultNewStoreFieldsRejectLegacyFile() { + for (row in listOf(""","jumpProfileId":"y"""", ""","dynamicForwardPort":1080""", ""","dynamicForwardNoAuth":true""", ""","localForwards":[{"localPort":8080,"host":"h","port":80}]""")) + assertEquals(SshProfileImportFailure.FORMAT, assertFailsWith { decode(row) }.reason, row) + assertEquals(SshProfileImportFailure.FORMAT, assertFailsWith { + decode("", ""","snippets":[{"id":"s","name":"n","text":"x"}]""") }.reason) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProductivityTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProductivityTest.kt new file mode 100644 index 0000000..7d92fe3 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProductivityTest.kt @@ -0,0 +1,270 @@ +package cz.netkit.shared.ssh + +import kotlinx.serialization.json.* +import kotlin.test.* + +class SshSnippetTest { + private val profile = SshProfile("p1", "Router", "192.0.2.1", username = "admin") + + @Test fun validationRejectsControlCharactersAndLimits() { + assertTrue(SshSnippet("s1", "Verze", "show version").valid()) + for (text in listOf("", "a\nb", "a\rb", "a\u001b[2J", "a\u0003", "x".repeat(4097), "a\u009bb")) + assertFalse(SshSnippet("s1", "n", text).valid(), text) + assertFalse(SshSnippet("s1", "", "x").valid()) + assertFalse(SshSnippet("s1", "n".repeat(61), "x").valid()) + assertFalse(SshSnippet("bad id", "n", "x").valid()) + assertTrue(SshSnippet("s1", "n", "x".repeat(4096)).valid()) + } + + @Test fun payloadAddsEnterOnlyWhenRequested() { + assertEquals("uptime\r", SshSnippet("s", "n", "uptime").payload()) + assertEquals("uptime", SshSnippet("s", "n", "uptime", sendEnter = false).payload()) + } + + @Test fun scopeShowsGlobalThenProfileSnippets() { + val data = SshData(profiles = listOf(profile, profile.copy(id = "p2", name = "Other")), snippets = listOf( + SshSnippet("a", "own", "x", profileId = "p1"), SshSnippet("b", "global", "y"), SshSnippet("c", "foreign", "z", profileId = "p2"))) + assertEquals(listOf("b", "a"), data.snippetsFor("p1").map { it.id }) + assertEquals(listOf("b"), data.snippetsFor(null).map { it.id }) + } + + @Test fun secretHeuristicWarnsButCommonCommandsDoNot() { + for (text in listOf("snmp-server community public RO", "set password admin", "echo $(cat secret.txt)", "API_KEY=1", "heslo 123", "wpa-psk x")) + assertTrue(snippetLooksSecret(text), text) + for (text in listOf("show version", "pwd", "ip a", "uptime", "/system resource print")) + assertFalse(snippetLooksSecret(text), text) + } + + @Test fun upsertAndProfileRemovalKeepDataValid() { + val base = SshData(profiles = listOf(profile, profile.copy(id = "p2", name = "Jump-user", jumpProfileId = "p1"))) + val withGlobal = assertNotNull(upsertSnippet(base, SshSnippet("s1", "n", "x"))) + val withOwn = assertNotNull(upsertSnippet(withGlobal, SshSnippet("s2", "own", "y", profileId = "p1"))) + assertNull(upsertSnippet(withOwn, SshSnippet("s3", "dangling", "z", profileId = "missing"))) + assertNull(upsertSnippet(withOwn, SshSnippet("s3", "bad", "a\nb"))) + // Same name in the same scope would break the export; another scope or renaming itself is fine. + assertTrue(snippetNameTaken(withOwn, SshSnippet("s9", "n", "other"))) + assertNull(upsertSnippet(withOwn, SshSnippet("s9", "n", "other"))) + assertNotNull(upsertSnippet(withOwn, SshSnippet("s9", "n", "other", profileId = "p1"))) + assertNotNull(upsertSnippet(withOwn, SshSnippet("s1", "n", "changed text"))) + val replaced = assertNotNull(upsertSnippet(withOwn, SshSnippet("s1", "renamed", "x"))) + assertEquals(listOf("renamed", "own"), replaced.snippets.map { it.name }) + var full = base + repeat(SSH_MAX_SNIPPETS) { full = assertNotNull(upsertSnippet(full, SshSnippet("s$it", "n$it", "x"))) } + assertNull(upsertSnippet(full, SshSnippet("over", "n", "x"))) + val removed = removeSshProfile(replaced, "p1") + assertTrue(removed.valid()) + assertEquals(listOf("s1"), removed.snippets.map { it.id }) + assertNull(removed.profiles.single().jumpProfileId) + } + + @Test fun serializedStoreWithoutNewFieldsStillDecodes() { + val old = """{"schema":1,"profiles":[{"id":"p1","name":"Router","host":"192.0.2.1","username":"admin"}]}""" + val data = Json.decodeFromString(old) + assertTrue(data.valid()) + assertEquals(emptyList(), data.snippets) + assertEquals(null, data.profiles.single().jumpProfileId) + assertEquals(emptyList(), data.profiles.single().localForwards) + } +} + +class SshForwardingTest { + private fun p(id: String, jump: String? = null) = SshProfile(id, "name-$id", "192.0.2.10", username = "u", jumpProfileId = jump) + + @Test fun forwardsValidateLoopbackPortsTargetsAndUniqueness() { + assertTrue(validSshForwards(listOf(SshLocalForward(8080, "10.0.0.1", 80)), 1080)) + assertFalse(validSshForwards(listOf(SshLocalForward(80, "10.0.0.1", 80)), null)) + assertFalse(validSshForwards(listOf(SshLocalForward(8080, "10.0.0.1", 0)), null)) + assertFalse(validSshForwards(listOf(SshLocalForward(8080, "bad host", 80)), null)) + assertFalse(validSshForwards(listOf(SshLocalForward(8080, "a@b", 80)), null)) + assertFalse(validSshForwards(listOf(SshLocalForward(8080, "a", 80), SshLocalForward(8080, "b", 80)), null)) + assertFalse(validSshForwards(listOf(SshLocalForward(1080, "a", 80)), 1080)) + assertFalse(validSshForwards(emptyList(), 1023)) + assertFalse(validSshForwards((0..SSH_MAX_LOCAL_FORWARDS).map { SshLocalForward(9000 + it, "a", 80) }, null)) + assertEquals("[2001:db8::1]:443", SshLocalForward(8443, "2001:db8::1", 443).target) + assertEquals("127.0.0.1:8080", SshForwardStatus(SshForwardKind.LOCAL, 8080, "a:80", SshForwardState.ACTIVE).localAddress) + assertFalse(SshProfile("p", "n", "h", username = "u", localForwards = listOf(SshLocalForward(80, "a", 1))).valid()) + assertFalse(p("self", jump = "self").valid()) + } + + @Test fun chainResolvesInConnectionOrder() { + val a = p("a"); val b = p("b", "a"); val c = p("c", "b") + assertEquals(SshJumpResolution.Chain(emptyList()), resolveSshJumpChain(listOf(a), a)) + assertEquals(SshJumpResolution.Chain(listOf(a, b)), resolveSshJumpChain(listOf(a, b, c), c)) + } + + @Test fun chainOfThreeAllowedFourRejected() { + val list = listOf(p("a"), p("b", "a"), p("c", "b"), p("d", "c"), p("e", "d")) + assertEquals(3, (resolveSshJumpChain(list, list[3]) as SshJumpResolution.Chain).hops.size) + assertEquals(SshJumpResolution.TooLong, resolveSshJumpChain(list, list[4])) + } + + @Test fun cyclesAndMissingFailClosed() { + val a = p("a", "c"); val b = p("b", "a"); val c = p("c", "b") + assertEquals(SshJumpResolution.Cycle, resolveSshJumpChain(listOf(a, b, c), c)) + assertEquals(SshJumpResolution.Cycle, resolveSshJumpChain(listOf(p("x", "y"), p("y", "x")), p("z", "x"))) + assertEquals(SshJumpResolution.Missing("gone"), resolveSshJumpChain(listOf(p("a", "gone")), p("t", "a"))) + } + + @Test fun candidatesExcludeSelfAndCycles() { + val a = p("a"); val b = p("b", "a"); val c = p("c", "b") + val data = SshData(profiles = listOf(a, b, c)) + assertEquals(emptyList(), data.jumpCandidates(a).map { it.id }) // b and c already route through a. + assertEquals(listOf("a", "b"), data.jumpCandidates(c).map { it.id }) + assertEquals(listOf("a", "b", "c"), data.jumpCandidates(p("new")).map { it.id }) + } +} + +class Socks5Test { + private fun bytes(vararg values: Int) = ByteArray(values.size) { values[it].toByte() } + + @Test fun greetingRequiresVersionAndNoAuthMethod() { + assertEquals(Socks5Parse.Done(Unit, 3), Socks5.parseGreeting(bytes(5, 1, 0))) + assertEquals(Socks5Parse.Done(Unit, 4), Socks5.parseGreeting(bytes(5, 2, 2, 0, 9), 5)) + assertEquals(Socks5Parse.NeedMore, Socks5.parseGreeting(bytes())) + assertEquals(Socks5Parse.NeedMore, Socks5.parseGreeting(bytes(5))) + assertEquals(Socks5Parse.NeedMore, Socks5.parseGreeting(bytes(5, 3, 0))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.PROTOCOL), Socks5.parseGreeting(bytes(4, 1, 0))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.PROTOCOL), Socks5.parseGreeting(bytes(5, 0))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.NO_ACCEPTABLE_METHOD), Socks5.parseGreeting(bytes(5, 1, 2))) + } + + @Test fun connectIpv4Ipv6AndDomain() { + assertEquals(Socks5Parse.Done(Socks5Request("192.0.2.7", 443, 1), 10), + Socks5.parseRequest(bytes(5, 1, 0, 1, 192, 0, 2, 7, 1, 187))) + val v6 = bytes(5, 1, 0, 4, 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 22) + assertEquals(Socks5Parse.Done(Socks5Request("2001:db8:0:0:0:0:0:1", 22, 4), 22), Socks5.parseRequest(v6)) + val name = "router.example.test".encodeToByteArray() + val domain = bytes(5, 1, 0, 3, name.size) + name + bytes(0x1f, 0x90) + assertEquals(Socks5Parse.Done(Socks5Request("router.example.test", 8080, 3), domain.size), Socks5.parseRequest(domain + bytes(1, 2, 3))) + } + + @Test fun truncatedRequestsNeedMoreAtEveryLength() { + val name = "example.test".encodeToByteArray() + val full = bytes(5, 1, 0, 3, name.size) + name + bytes(0, 80) + for (length in 0 until full.size) assertEquals(Socks5Parse.NeedMore, Socks5.parseRequest(full, length), "length $length") + val v4 = bytes(5, 1, 0, 1, 127, 0, 0, 1, 0, 7) + for (length in 0 until v4.size) assertEquals(Socks5Parse.NeedMore, Socks5.parseRequest(v4.copyOf(length)), "v4 $length") + } + + @Test fun unsupportedCommandsAndAddressTypesAreTyped() { + assertEquals(Socks5Parse.Invalid(Socks5Reply.COMMAND_NOT_SUPPORTED), Socks5.parseRequest(bytes(5, 2, 0, 1, 127, 0, 0, 1, 0, 7))) // BIND + assertEquals(Socks5Parse.Invalid(Socks5Reply.COMMAND_NOT_SUPPORTED), Socks5.parseRequest(bytes(5, 3, 0, 1, 127, 0, 0, 1, 0, 7))) // UDP + assertEquals(Socks5Parse.Invalid(Socks5Reply.ADDRESS_TYPE_NOT_SUPPORTED), Socks5.parseRequest(bytes(5, 1, 0, 2, 0, 0))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.PROTOCOL), Socks5.parseRequest(bytes(4, 1, 0, 1))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.GENERAL_FAILURE), Socks5.parseRequest(bytes(5, 1, 1, 1, 127, 0, 0, 1, 0, 7))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.GENERAL_FAILURE), Socks5.parseRequest(bytes(5, 1, 0, 1, 127, 0, 0, 1, 0, 0))) + } + + @Test fun domainLengthAndCharactersAreBounded() { + fun request(name: ByteArray) = bytes(5, 1, 0, 3, name.size) + name + bytes(0, 80) + val longest = ("a".repeat(63) + ".").repeat(3) + "a".repeat(61) + assertEquals(253, longest.length) + assertIs>(Socks5.parseRequest(request(longest.encodeToByteArray()))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.GENERAL_FAILURE), Socks5.parseRequest(request(("b" + longest).encodeToByteArray()))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.GENERAL_FAILURE), Socks5.parseRequest(request("a".repeat(255).encodeToByteArray()))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.GENERAL_FAILURE), Socks5.parseRequest(bytes(5, 1, 0, 3, 0, 0, 80))) + for (bad in listOf("a b", "a@b", "a%25", "-x", ".x", "a\u0000", "ř.test")) + assertEquals(Socks5Parse.Invalid(Socks5Reply.GENERAL_FAILURE), Socks5.parseRequest(request(bad.encodeToByteArray())), bad) + } + + @Test fun usernamePasswordMethodAndSubnegotiation() { + assertEquals(Socks5Parse.Done(Unit, 3), Socks5.parseGreeting(bytes(5, 1, 2), method = Socks5.METHOD_USERNAME_PASSWORD)) + assertEquals(Socks5Parse.Invalid(Socks5Reply.NO_ACCEPTABLE_METHOD), Socks5.parseGreeting(bytes(5, 1, 0), method = Socks5.METHOD_USERNAME_PASSWORD)) + val login = bytes(1, 2) + "nk".encodeToByteArray() + bytes(3) + "abc".encodeToByteArray() + val done = assertIs>(Socks5.parseUserPass(login + bytes(5, 1))) + assertEquals(login.size, done.consumed) + assertEquals("nk", done.value.username.decodeToString()); assertEquals("abc", done.value.password.decodeToString()) + for (length in 0 until login.size) assertEquals(Socks5Parse.NeedMore, Socks5.parseUserPass(login, length), "length $length") + assertEquals(Socks5Parse.Invalid(Socks5Reply.PROTOCOL), Socks5.parseUserPass(bytes(5, 1, 0))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.PROTOCOL), Socks5.parseUserPass(bytes(1, 0, 1, 0))) + assertEquals(Socks5Parse.Invalid(Socks5Reply.PROTOCOL), Socks5.parseUserPass(bytes(1, 1, 65, 0))) + assertTrue(Socks5.constantTimeEquals("abc".encodeToByteArray(), "abc".encodeToByteArray())) + assertFalse(Socks5.constantTimeEquals("abc".encodeToByteArray(), "abd".encodeToByteArray())) + assertFalse(Socks5.constantTimeEquals("abc".encodeToByteArray(), "abcd".encodeToByteArray())) + assertFalse(Socks5.constantTimeEquals(ByteArray(0), "a".encodeToByteArray())) + } + + @Test fun generatedCredentialsAreLongRandomAndRedacted() { + var next = 0 + val credentials = SshSocksCredentials.generate { bound -> (next++ * 7) % bound } + assertEquals("netkit", credentials.username) + assertEquals(20, credentials.password.length) + assertTrue(credentials.password.all { it.isLetterOrDigit() && it.code < 128 }) + assertFalse(credentials.password in credentials.toString()) + } + + @Test fun repliesHaveFixedShape() { + assertContentEquals(bytes(5, 0, 0, 1, 0, 0, 0, 0, 0, 0), Socks5.reply(Socks5Reply.SUCCEEDED)) + assertContentEquals(bytes(5, 7, 0, 1, 0, 0, 0, 0, 0, 0), Socks5.reply(Socks5Reply.COMMAND_NOT_SUPPORTED)) + assertContentEquals(bytes(5, 0xFF), Socks5.NO_ACCEPTABLE_METHOD_REPLY) + } + + @Test fun arbitraryBytesNeverThrow() { + var seed = 12345 + repeat(5000) { + seed = seed * 1103515245 + 12345 + val size = (seed ushr 16) % 300 + val data = ByteArray(size) { index -> ((seed ushr (index % 24)) + index * 31).toByte() } + if (data.isNotEmpty()) data[0] = 5 + Socks5.parseGreeting(data); Socks5.parseRequest(data) + } + } +} + +class TerminalLogTest { + private fun filter(vararg chunks: String): String { + val f = TerminalLogFilter() + return chunks.joinToString("") { f.feed(it) } + f.flush() + } + + @Test fun removesColorsOscAndCharsetSequences() { + assertEquals("NETKIT_FIXTURE_READY\nfixture>\n", filter("\u001b[1;32mNETKIT_FIXTURE_READY\u001b[0m\r\nfixture> ")) + assertEquals("title gone\n", filter("\u001b]0;user@host: ~\u0007title gone\n")) + assertEquals("st form\n", filter("\u001b]8;;http://x\u001b\\st form\n")) + assertEquals("box\n", filter("\u001b(0\u001b(Bbox\n")) + assertEquals("dcs\n", filter("\u001bPq#0;2;0;0;0\u001b\\dcs\n")) + assertEquals("c1\n", filter("\u009b31mc1\u009b0m\n")) + assertEquals("private\n", filter("\u001b[?2004hprivate\u001b[?25l\n")) + } + + @Test fun sequencesSplitAcrossChunks() { + assertEquals("ab\n", filter("a\u001b", "[3", "1m", "b\u001b]0;t", "itle\u0007\n")) + assertEquals("ok\n", filter("o", "k\r", "\n")) + } + + @Test fun lineEditingAppliesCarriageReturnBackspaceAndErase() { + assertEquals("ac\n", filter("ab\b \bc\r\n")) + assertEquals("100%\n", filter(" 10%\r 50%\r100%\n")) + assertEquals("prompt$ ls\n", filter("prompt$ lx\u001b[D\u001b[Ks\r\n")) + assertEquals("abc\n", filter("abcdef\u001b[3D\u001b[K\n")) + assertEquals("new\n", filter("old text\r\u001b[2Knew\n")) + assertEquals("a\tb\n", filter("a\tb\u0007\n")) + } + + @Test fun bareCarriageReturnBeforeNewlineIsOneLineBreak() { + assertEquals("one\ntwo\n", filter("one\r\ntwo\r\n")) + assertEquals("", filter("")) + } + + @Test fun overlongLinesAreSplitAndUnterminatedSequencesDropped() { + val f = TerminalLogFilter(maxLine = 10) + assertEquals("0123456789\n", f.feed("0123456789abc")) + assertEquals("abc\n", f.flush()) + assertEquals("x\n", filter("\u001b[" + "1".repeat(100) + "mx\n")) + } + + @Test fun budgetCutsAtUtf8BoundaryAndStops() { + val budget = SessionLogBudget(10) + assertEquals("abcd", budget.take("abcd")) + assertEquals("ěšč", budget.take("ěščř")) // 2 bytes each: 4 + 6 = 10 + assertTrue(budget.exhausted) + assertEquals("", budget.take("x")) + assertEquals(10, budget.written) + val emoji = SessionLogBudget(4) + assertEquals("a", emoji.take("a😀b")) // 4-byte pair is never split. + assertEquals(SSH_SESSION_LOG_LIMIT_BYTES, 50L * 1024 * 1024) + val exact = SessionLogBudget(3) + assertEquals("abc", exact.take("abc")) + assertFalse(exact.exhausted) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt index c753dbe..80e5160 100644 --- a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt @@ -101,7 +101,7 @@ class SshProfileImportTest { assertEquals(1, planned.updatedProfiles.size) assertTrue(planned.newProfiles.isEmpty()) val result = applySshImportPlan(current, planned) - assertEquals(existing.copy(host = "192.168.0.10", port = 22, username = "root", secretRef = null), result.profiles.first()) + assertEquals(existing.copy(host = "192.168.0.10", port = 22, username = "root", secretRef = null, group = "Homelab"), result.profiles.first()) assertEquals(caseDifferent, result.profiles.last()) val unchanged = plan(result) assertEquals(1, unchanged.unchangedProfiles.size) @@ -118,7 +118,7 @@ class SshProfileImportTest { val current = SshData(profiles = listOf(existing)) val planned = plan(current, incoming) val entry = planned.updatedProfiles.single() - assertEquals(changed.copy(secretRef = null), entry.after) + assertEquals(changed.copy(secretRef = null, group = "Homelab"), entry.after) assertEquals("secret-ref", entry.detachedSecretRef) assertEquals(listOf("secret-ref"), planned.detachedSecretRefs) assertEquals(entry.after, applySshImportPlan(current, planned).profiles.single()) @@ -126,7 +126,7 @@ class SshProfileImportTest { } @Test fun unchangedTargetKeepsPasswordAndOtherRowsDetachNothing() { - val existing = SshProfile("saved", "proxmox", "192.168.0.10", username = "root", secretRef = "secret-ref") + val existing = SshProfile("saved", "proxmox", "192.168.0.10", username = "root", secretRef = "secret-ref", group = "Homelab") val unchanged = plan(SshData(profiles = listOf(existing))) assertEquals(existing, unchanged.unchangedProfiles.single().after) assertNull(unchanged.unchangedProfiles.single().detachedSecretRef) @@ -185,8 +185,10 @@ class SshProfileImportTest { assertEquals(1, result.schema) val json = Json { encodeDefaults = true } val root = json.parseToJsonElement(json.encodeToString(SshData.serializer(), result)).jsonObject - assertEquals(setOf("schema", "profiles", "hostKeys", "keys", "rejectedHostKeys"), root.keys) - assertEquals(setOf("id", "name", "host", "port", "username", "authentication", "secretRef", "keyRef", "startupCommand", "keepaliveSeconds"), + // Zadání 41 adds local store fields (snippets, jump link, forwards); group is persistent, source and skipped are preview-only. + assertEquals(setOf("schema", "profiles", "hostKeys", "keys", "rejectedHostKeys", "snippets"), root.keys) + assertEquals(setOf("id", "name", "host", "port", "username", "authentication", "secretRef", "keyRef", "startupCommand", "keepaliveSeconds", + "jumpProfileId", "localForwards", "dynamicForwardPort", "dynamicForwardNoAuth", "group"), root.getValue("profiles").jsonArray.single().jsonObject.keys) assertEquals(result, json.decodeFromString(SshData.serializer(), root.toString())) } diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TelnetConsoleTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TelnetConsoleTest.kt new file mode 100644 index 0000000..bc0ff43 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TelnetConsoleTest.kt @@ -0,0 +1,79 @@ +package cz.netkit.shared.ssh + +import kotlin.test.* +import kotlinx.serialization.json.Json + +class TelnetConsoleTest { + private fun bytes(vararg values: Int) = ByteArray(values.size) { values[it].toByte() } + private fun TelnetCodec.reply(vararg data: Int) = receive(bytes(*data)).reply + + @Test fun optionsAreDirectionalAndRepeatedOffersDoNotLoop() { + val c = TelnetCodec() + assertContentEquals(bytes(255,253,1, 255,253,3, 255,251,3), c.reply(255,251,1, 255,251,3, 255,253,3)) + assertContentEquals(bytes(), c.reply(255,251,1, 255,253,3)) + assertContentEquals(bytes(255,254,1, 255,252,3), c.reply(255,252,1, 255,254,3)) + assertContentEquals(bytes(255,252,1, 255,254,31, 255,252,99, 255,254,99), c.reply(255,253,1, 255,251,31, 255,253,99, 255,251,99)) + assertContentEquals(bytes(), c.reply(255,252,99, 255,254,99)) + } + + @Test fun nawsIsNegotiatedUpdatedEscapedAndDisabled() { + val c = TelnetCodec() + assertContentEquals(bytes(), c.resize(255, 511)) + assertContentEquals(bytes(255,251,31, 255,250,31,0,255,255,1,255,255,255,240), c.reply(255,253,31)) + assertContentEquals(bytes(), c.reply(255,253,31)) + assertContentEquals(bytes(255,250,31,0,80,0,24,255,240), c.resize(80,24)) + assertContentEquals(bytes(), c.resize(80,24)) + assertContentEquals(bytes(255,252,31), c.reply(255,254,31)) + assertContentEquals(bytes(), c.resize(100,30)) + } + + @Test fun fragmentedTerminalTypeAndUntrustedSubnegotiation() { + val c = TelnetCodec() + val send = bytes(255,250,24,1,255,240) + assertContentEquals(bytes(), c.receive(send).reply) + assertContentEquals(bytes(255,251,24), c.reply(255,253,24)) + val response = send.flatMap { c.receive(byteArrayOf(it)).reply.asList() }.toByteArray() + assertContentEquals(bytes(255,250,24,0) + "xterm-256color".encodeToByteArray() + bytes(255,240), response) + val malformed = bytes(255,250,24) + ByteArray(100000) { 1 } + bytes(255,255,255,240,65) + val result = c.receive(malformed) + assertContentEquals(bytes(65), result.data) + assertContentEquals(bytes(), result.reply) + c.reply(255,254,24) + assertContentEquals(bytes(), c.receive(send).reply) + } + + @Test fun nvtAndIacAcrossEverySplit() { + val wire = bytes(65,13,255,241,0,66,255,255,13,10,67) + for (split in 0..wire.size) { + val c = TelnetCodec() + assertContentEquals(bytes(65,13,66,255,13,10,67), c.receive(wire.copyOfRange(0,split)).data + + c.receive(wire.copyOfRange(split,wire.size)).data) + } + assertContentEquals(bytes(255,255,13,0,65,13,10,13,10), TelnetCodec.encode(bytes(255,13,65,10,13,10))) + } + + @Test fun oldProfilesAndConsoleMetadataRoundTripWithoutChangingSshExport() { + val old = Json.decodeFromString("""{"schema":1,"profiles":[{"id":"s","name":"SSH","host":"example.test","username":"lab"}]}""") + assertTrue(old.valid()) + assertTrue(old.consoles.isEmpty()) + val profile = ConsoleProfile("t","Console",ConsoleKind.TELNET,"example.test", skipTelnetWarning = true) + val mixed = old.copy(consoles = listOf(profile, ConsoleProfile("u","USB",ConsoleKind.SERIAL))) + assertTrue(mixed.valid()) + assertEquals(mixed, Json.decodeFromString(Json.encodeToString(mixed))) + assertContentEquals(encodeSshProfileExport(old, source = "test"), encodeSshProfileExport(mixed, source = "test")) + } + + @Test fun serialDefaultsBoundsAndTelnetProfile() { + assertEquals(SerialSettings(9600,8,SerialParity.NONE,SerialStopBits.ONE,false), SerialSettings.enterprise) + assertEquals(SerialSettings.enterprise.copy(baud = 115200), SerialSettings.mikrotik) + for (baud in listOf(1200, 9600, 115200, 921600)) assertTrue(SerialSettings(baud = baud).valid()) + for (baud in listOf(1199, 921601)) assertFalse(SerialSettings(baud = baud).valid()) + for (bits in listOf(4,9)) assertFalse(SerialSettings(dataBits = bits).valid()) + val p = ConsoleProfile("id","Lab",ConsoleKind.TELNET,"example.test") + assertTrue(p.valid()) + assertEquals(23,p.port) + assertFalse(p.copy(host = "user@example.test").valid()) + assertFalse(p.copy(kind = ConsoleKind.SERIAL).valid()) + assertTrue(p.copy(kind = ConsoleKind.SERIAL,host = "").valid()) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalInputTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalInputTest.kt index d94e710..78191fd 100644 --- a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalInputTest.kt +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalInputTest.kt @@ -26,6 +26,17 @@ class TerminalInputTest { assertEquals("\u001bx", terminalTextSequence("x", alt = true)) assertEquals("\u0000", terminalTextSequence(" ", control = true)) } + @Test fun fallbackFieldEncodesModifiedKeysEvenInBracketedPasteMode() { + for (bracketed in listOf(false, true)) { + assertEquals("\u0003", terminalFallbackPayload("c", control = true, alt = false, bracketed = bracketed)) + assertEquals("\u001bx", terminalFallbackPayload("x", control = false, alt = true, bracketed = bracketed)) + assertEquals("\u001b\u0003", terminalFallbackPayload("c", control = true, alt = true, bracketed = bracketed)) + assertEquals("", terminalFallbackPayload("", control = false, alt = true, bracketed = bracketed)) + } + assertEquals("a b", terminalFallbackPayload("a\nb", control = false, alt = false, bracketed = false)) + assertEquals("\u001b[200~a b\u001b[201~", terminalFallbackPayload("a\nb", control = false, alt = false, bracketed = true)) + } + @Test fun compactHistoryBudgetIncludesWorstCaseAlternatingStyles() { val buffer = TerminalBuffer(240, 2) val line = (0 until 240).joinToString("") { "\u001b[${30 + it % 8}mX" } diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalXtermTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalXtermTest.kt new file mode 100644 index 0000000..3803ad5 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalXtermTest.kt @@ -0,0 +1,304 @@ +package cz.netkit.shared.ssh + +import kotlin.random.Random +import kotlin.test.* +import kotlin.time.TimeSource + +/** Zadání 43: sequences from xterm ctlseqs / ECMA-48, wide characters, bounds and fuzz. */ +class TerminalXtermTest { + private fun TerminalBuffer.row(index: Int) = snapshot().screen[index] + private fun TerminalRow.cell(column: Int) = runs.let { runs -> + var start = 0 + runs.first { run -> (column < start + run.columns).also { if (!it) start += run.columns } } + } + + @Test fun sgrPaletteTruecolorAndAttributes() { + val t = TerminalBuffer(40, 4) + t.feed("\u001b[38;5;196;48;5;21mA\u001b[38;2;1;2;3mB\u001b[38:2::4:5:6mC\u001b[48:5:200mD\u001b[0m") + t.feed("\u001b[1;2;3;4;9mE\u001b[22;23;24;29mF\u001b[7mG\u001b[27;8mH\u001b[28;4:0mI\u001b[97;101mJ\u001b[39;49mK") + val row = t.row(0) + assertEquals(196, row.cell(0).foreground); assertEquals(21, row.cell(0).background) + assertEquals(0x1000000 or 0x010203, row.cell(1).foreground) + assertEquals(0x1000000 or 0x040506, row.cell(2).foreground) + assertEquals(200, row.cell(3).background) + row.cell(4).let { assertTrue(it.bold && it.dim && it.italic && it.underline && it.strikethrough) } + row.cell(5).let { assertFalse(it.bold || it.dim || it.italic || it.underline || it.strikethrough) } + row.cell(6).let { assertEquals(0, it.foreground); assertEquals(7, it.background) } // inverse of defaults + assertTrue(row.cell(7).hidden); assertEquals(7, row.cell(7).foreground) + assertFalse(row.cell(8).hidden); assertFalse(row.cell(8).underline) + row.cell(9).let { assertEquals(15, it.foreground); assertEquals(9, it.background) } + row.cell(10).let { assertEquals(7, it.foreground); assertEquals(0, it.background) } + // Malformed extended colours are dropped without touching the previous state. + t.feed("\r\n\u001b[31m\u001b[38;5mX\u001b[38;5;999mY\u001b[38;2;1mZ") + assertEquals(1, t.row(1).cell(0).foreground) + assertEquals(1, t.row(1).cell(2).foreground) + } + + @Test fun alternateScreenSwitchAndRestoreKeepsPrimaryCursorAndAttributes() { + val t = TerminalBuffer(20, 5) + t.feed("one\r\ntwo\u001b[32m") + val primary = t.snapshot() + t.feed("\u001b[?1049h") + assertTrue(t.snapshot().alternateScreen) + assertTrue(t.snapshot().screen.all { it.text.isBlank() }) + t.feed("\u001b[0;35m\u001b[3;3HALT\u001b[?1049l") + val back = t.snapshot() + assertFalse(back.alternateScreen) + assertEquals(primary.screen, back.screen) + assertEquals(1, back.cursorRow); assertEquals(3, back.cursorColumn) + t.feed("X") + assertEquals(2, t.row(1).cell(3).foreground) // DECSC/DECRC restored SGR 32 with the cursor. + // 47 and 1047 switch buffers as well; the primary content comes back unchanged. + val before = t.snapshot().screen + t.feed("\u001b[?47hA\u001b[?47l"); assertEquals(before, t.snapshot().screen) + t.feed("\u001b[?1047hB\u001b[?1047l"); assertEquals(before, t.snapshot().screen) + // Alternate output never reaches the scrollback. + t.feed("\u001b[?1049h" + (1..20).joinToString("\r\n") { "alt$it" } + "\u001b[?1049l") + assertTrue(t.snapshot().history.none { it.text.startsWith("alt") }) + } + + @Test fun scrollRegionIndexReverseIndexAndOriginMode() { + val t = TerminalBuffer(10, 6) + t.feed((0..5).joinToString("\r\n") { "r$it" }) + t.feed("\u001b[2;4r") // rows 2..4 (1-based) + assertEquals(0, t.snapshot().cursorRow) + t.feed("\u001b[4;1H\nX") + assertEquals(listOf("r0", "r2", "r3", "X", "r4", "r5"), t.snapshot().screen.map { it.text.trim() }) + assertTrue(t.snapshot().history.isEmpty()) + t.feed("\u001b[2;1H\u001bM") + assertEquals(listOf("r0", "", "r2", "r3", "r4", "r5"), t.snapshot().screen.map { it.text.trim() }) + t.feed("\u001b[?6h\u001b[1;1HO\u001b[99;1HP") + assertEquals("O", t.row(1).text.trim()); assertEquals("P", t.row(3).text.trim().take(1)) + assertEquals("\u001b[3;2R", t.feed("\u001b[6n")) + t.feed("\u001b[?6l\u001b[r\u001b[6;1H\n") + assertEquals(1, t.snapshot().history.size) + } + + @Test fun insertDeleteLinesAndCharacters() { + val t = TerminalBuffer(10, 5) + t.feed("a\r\nb\r\nc\r\nd\r\ne") + t.feed("\u001b[2;1H\u001b[2L") + assertEquals(listOf("a", "", "", "b", "c"), t.snapshot().screen.map { it.text.trim() }) + t.feed("\u001b[2M") + assertEquals(listOf("a", "b", "c", "", ""), t.snapshot().screen.map { it.text.trim() }) + t.feed("\u001b[1;1H\u001b[2K0123456789\u001b[1;3H\u001b[2@") + assertEquals("01 234567", t.row(0).text) + t.feed("\u001b[3P"); assertEquals("0134567 ", t.row(0).text) + t.feed("\u001b[1;2H\u001b[3X"); assertEquals("0 567 ", t.row(0).text) + t.feed("\u001b[4h\u001b[1;1HZ\u001b[4l"); assertEquals("Z0 567 ", t.row(0).text) + t.feed("\u001b[1;1H\u001b[1K"); assertEquals(" 0 567 ", t.row(0).text) + } + + @Test fun wideCharactersOccupyTwoCellsAndWrapAsAUnit() { + val t = TerminalBuffer(10, 3) + t.feed("中文ab") + val row = t.row(0) + assertEquals("中文ab ", row.text) + assertEquals(10, row.columns) + assertEquals(6, t.snapshot().cursorColumn) + assertEquals(1, row.offsetOf(2)); assertEquals(0, row.offsetOf(1)); assertEquals(3, row.offsetOf(5)) + // A wide character never splits at the right margin. + t.feed("\r\n123456789字x") + assertEquals("123456789 ", t.row(1).text) + assertEquals("字x", t.row(2).text.trimEnd()) + // Overwriting half of a wide character blanks the other half. + t.feed("\u001b[1;2HZ") + assertEquals(" Z文ab", t.row(0).text.trimEnd()) + // Emoji (surrogate pair split between feeds) and a combining mark. + t.feed("\u001b[3;1H\u001b[2K\uD83D"); t.feed("\uDE00é!") + assertEquals("😀é!", t.row(2).text.trimEnd()) + assertEquals(4, t.snapshot().cursorColumn) + assertEquals(2, t.row(2).offsetOf(2)) + // Erase, insert and delete keep wide pairs intact or blank both halves. + t.feed("\u001b[1;1H\u001b[2K中文中文中\u001b[1;2H\u001b[P") + assertEquals(" 文中文中 ", t.row(0).text) + t.feed("\u001b[1;4H\u001b[X") + assertEquals(" 文 文中 ", t.row(0).text) + } + + @Test fun resizeWithWideCharacterAtTheEdgeAndWindowSize() { + val t = TerminalBuffer(12, 3) + t.feed("0123456789中") + t.resize(11, 3) + assertEquals("0123456789 ", t.row(0).text) + t.resize(30, 10) + assertEquals(30, t.row(0).columns); assertEquals(10, t.snapshot().screen.size) + assertEquals("\u001b[1;11R", t.feed("\u001b[6n")) + } + + @Test fun decSpecialGraphicsAndShiftOut() { + val t = TerminalBuffer(20, 2) + t.feed("\u001b(0lqk\u001b(Bq\u001b)0\u000ex\u000fx") + assertEquals("┌─┐q│x", t.row(0).text.trimEnd()) + } + + @Test fun titleIsDisplayOnlySanitizedAndBounded() { + val t = TerminalBuffer(20, 2) + t.feed("\u001b]0;host: ~/src\u0007") + assertEquals("host: ~/src", t.snapshot().title) + t.feed("\u001b]2;a‮b\u0001c\u001b\\") + assertEquals("abc", t.snapshot().title) + t.feed("\u001b]2;" + "x".repeat(200) + "\u0007") + assertEquals(TerminalBuffer.MAX_TITLE, t.snapshot().title.length) + t.feed("\u001b]2;" + "y".repeat(400) + "\u0007ok") + assertEquals("x".repeat(128), t.snapshot().title) // Over the sequence limit: discarded. + assertEquals("ok", t.row(0).text.trim()) + // Clipboard, colour queries, title reports and links: no effect and no reply. + assertEquals("", t.feed("\u001b]52;c;c2VjcmV0\u0007\u001b]11;?\u0007\u001b[21t\u001b]8;;https://example.invalid\u0007")) + assertEquals("ok", t.row(0).text.trim()) + } + + @Test fun bracketedPasteModeAndPayload() { + val t = TerminalBuffer() + assertFalse(t.snapshot().bracketedPaste) + t.feed("\u001b[?2004h"); assertTrue(t.snapshot().bracketedPaste) + assertEquals("\u001b[200~ls -l rm\u001b[201~", terminalPastePayload("ls -l\nrm", true)) + assertEquals("a [201~b", terminalPastePayload("a\n\u001b[201~b", false)) + assertEquals("\u001b[200~a [201~b\u001b[201~", terminalPastePayload("a\n\u001b[201~b", true)) + assertEquals("", terminalPastePayload("", true)) + t.feed("\u001b[?2004l"); assertFalse(t.snapshot().bracketedPaste) + } + + @Test fun csiLengthLimitIncludesTheFinalByte() { + val t = TerminalBuffer() + val prefix = "\u001b[" + "0".repeat(TerminalBuffer.MAX_SEQUENCE - 3) + t.feed("\u001b[31m" + prefix + "mA") // Exactly at the limit: SGR 0 resets red. + assertEquals(7, t.row(0).cell(0).foreground) + + t.feed("\u001b[31m" + prefix + "0") + t.feed("mOK") // One byte over: discard SGR 0 and resume printing immediately. + assertEquals("AOK", t.row(0).text.trimEnd()) + assertEquals(1, t.row(0).cell(1).foreground) + } + + @Test fun overlongAndUnknownSequencesAreDroppedWithoutEffect() { + val t = TerminalBuffer(20, 3) + t.feed("\u001b[" + "1;".repeat(200) + "31mA") + assertEquals(7, t.row(0).cell(0).foreground); assertEquals("A", t.row(0).text.trim()) + t.feed("\u001b[?9999h\u001b[>5;5m\u001b[5 q\u001b[!pB\u001bPqdata\u001b\\C\u001b_apc\u0007D\u001b%GE\u001b[1;2\u0018F") + assertEquals("ABCDEF", t.row(0).text.trim()) + assertEquals("\u001b[>1;10;0c", t.feed("\u001b[>c")) + assertEquals("\u001b[?1;2c", t.feed("\u001b[c")) + } + + @Test fun tabsRepeatAndSavedCursorDefaults() { + val t = TerminalBuffer(30, 3) + t.feed("a\tb\u001b[3g\u001b[1;5H\u001bH\r\tc\u001b[2;1H-\u001b[5b") + assertEquals("a c b", t.row(0).text.substring(0, 9)) + assertEquals("------", t.row(1).text.trim()) + t.feed("\u001b[2;1H\u001b[Z\u001b[I"); assertEquals(4, t.snapshot().cursorColumn) + } + + @Test fun unchangedRowsKeepTheirSnapshotInstance() { + val t = TerminalBuffer(20, 5) + t.feed("one\r\ntwo\r\nthree") + val first = t.snapshot() + t.feed("!") + val second = t.snapshot() + assertSame(first.screen[0], second.screen[0]); assertSame(first.screen[1], second.screen[1]) + assertNotSame(first.screen[2], second.screen[2]) + assertSame(first.history, second.history) + } + + @Test fun fuzzRandomInputNeverBreaksInvariants() { + val random = Random(43) + val alphabet = "\u001b[]();:?>!\" 0123456789mHJKLMPX@hlrsu\u0007\u0018\\\r\n\t\b中😀́abc" + val t = TerminalBuffer(30, 8, historyLimit = 50) + repeat(4000) { round -> + val chunk = buildString { + repeat(random.nextInt(1, 300)) { + when (random.nextInt(4)) { + 0 -> append(random.nextInt(0, 0x110000).let { if (it in 0xD800..0xDFFF) 'x'.code else it }.let { code -> + buildString { appendCodePoint(code) } }) + 1 -> append(random.nextInt(0, 0x10000).toChar()) // includes lone surrogates + else -> append(alphabet[random.nextInt(alphabet.length)]) + } + } + } + t.feed(chunk) + if (round % 97 == 0) t.resize(random.nextInt(5, 60), random.nextInt(1, 30)) + val s = t.snapshot() + assertEquals(t.rows, s.screen.size) + assertTrue(s.screen.all { it.columns == t.columns }) + assertTrue(s.cursorRow in 0 until t.rows && s.cursorColumn in 0 until t.columns) + assertTrue(s.history.size <= 50) + assertTrue(s.title.length <= TerminalBuffer.MAX_TITLE) + s.screen.forEach { row -> assertEquals(row.columns, row.runs.sumOf { it.columns }) } + } + // Random bytes interpreted as Latin-1 (what a broken decoder could deliver). + repeat(200) { t.feed(random.nextBytes(512).map { (it.toInt() and 0xFF).toChar() }.joinToString("")) } + assertEquals(t.rows, t.snapshot().screen.size) + } + + @Test fun fixtureColorDemoMatchesExpectedCells() { + // Same bytes as tools/testsrv/m1_fixture.py "netkit-xterm-colors" (printf of 256 background swatches). + val demo = xtermColorDemo() + var fnv = 0x811C9DC5.toInt() + for (byte in demo.encodeToByteArray()) fnv = (fnv xor (byte.toInt() and 0xFF)) * 0x01000193 + assertEquals(0x9A12C5C8.toInt() to 3459, fnv to demo.encodeToByteArray().size) // Same pin as test_m1_fixture.py. + val t = TerminalBuffer(40, 24) + t.feed(demo) + val screen = t.snapshot().screen + val header = screen.indexOfFirst { it.text.startsWith("256 colors") } + assertTrue(header >= 0) + for (line in 0 until 16) for (column in 0 until 16) { + assertEquals(line * 16 + column, screen[header + 1 + line].cell(column * 2).background) + } + val styles = screen[header + 17] + assertEquals(0x1000000 or 0xFF6400, styles.cell(0).foreground) + assertTrue(screen.any { it.text.startsWith("NETKIT_XTERM_COLORS_OK") }) + } + + @Test fun throughputOfTypicalAndRandomOutput() { + val typical = buildString { + var n = 0 + while (length < 1_000_000) { + append("\u001b[01;34mdirectory-$n\u001b[0m \u001b[01;32mscript.sh\u001b[0m plain-file-$n.txt ") + append("\u001b[38;5;${n % 256}mcolour\u001b[0m \u001b[38;2;10;20;${n % 256}mtrue\u001b[0m 中文\r\n") + if (n % 25 == 0) append("\u001b[H\u001b[2J\u001b[?25l\u001b[5;10H\u001b[K\u001b[?25h") + n++ + } + } + val random = Random(7) + val noisy = buildString { while (length < 1_000_000) append(random.nextInt(0x20, 0x7F).toChar()); } + val t = TerminalBuffer(120, 40) + val mark = TimeSource.Monotonic.markNow() + repeat(5) { t.feed(typical); t.feed(noisy) } + val elapsed = mark.elapsedNow().inWholeMilliseconds + val megabytes = 10.0 + println("TERMINAL_THROUGHPUT chars=10000000 ms=$elapsed mbPerSecond=${(megabytes * 1000 / elapsed.coerceAtLeast(1) * 10).toLong() / 10.0}") + assertTrue(elapsed < 20_000, "10 MB took $elapsed ms") + } + + @Test fun paletteMatchesXtermAndKeepsContrastOnTheTerminalBackground() { + val background = 0xFF05090C.toInt() + assertEquals(0xFF000000.toInt(), TerminalPalette.argb(16)) + assertEquals(0xFF5F87AF.toInt(), TerminalPalette.argb(67)) + assertEquals(0xFFFFFFFF.toInt(), TerminalPalette.argb(231)) + assertEquals(0xFF080808.toInt(), TerminalPalette.argb(232)) + assertEquals(0xFFEEEEEE.toInt(), TerminalPalette.argb(255)) + assertEquals(0xFF123456.toInt(), TerminalPalette.argb(0x1123456)) + for (index in 1..15) { + val minimum = if (index == 8) 3.0 else 4.5 + assertTrue(TerminalPalette.contrast(TerminalPalette.argb(index), background) >= minimum, "index $index") + } + val text = 0xFFB8F5E9.toInt() + assertEquals(TerminalColors(text, background), TerminalPalette.resolve(TerminalRun("a"), text, background)) + assertEquals(TerminalColors(background, text), TerminalPalette.resolve(TerminalRun("a", 0, 7), text, background)) + val dim = TerminalPalette.resolve(TerminalRun("a", dim = true), text, background).foreground + assertTrue(TerminalPalette.contrast(dim, background) < TerminalPalette.contrast(text, background)) + assertEquals(background, TerminalPalette.resolve(TerminalRun("a", hidden = true), text, background).foreground) + } +} + +/** Mirrors tools/testsrv/m1_fixture.py XTERM_COLORS (kept byte-identical; see TerminalXtermTest). */ +internal fun xtermColorDemo(): String = buildString { + append("\r\n256 colors\r\n") + for (line in 0 until 16) { + for (column in 0 until 16) append("\u001b[48;5;${line * 16 + column}m ") + append("\u001b[0m\r\n") + } + append("\u001b[38;2;255;100;0mTRUE\u001b[0m \u001b[1mBOLD\u001b[0m \u001b[2mDIM\u001b[0m \u001b[3mITAL\u001b[0m ") + append("\u001b[4mUNDER\u001b[0m \u001b[7mINV\u001b[0m 中文\r\n") + append("NETKIT_XTERM_COLORS_OK\r\nfixture> ") +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/BondingCenterTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/BondingCenterTest.kt new file mode 100644 index 0000000..a1b105a --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/BondingCenterTest.kt @@ -0,0 +1,125 @@ +package cz.netkit.shared.wifi + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** Zadání 34 bod 4: centre of a bonded AP without `centerFreq0`. Synthetic, locally administered BSSIDs. */ +class BondingCenterTest { + private fun ap(frequency: Int, width: Int?, center: Int? = null, rssi: Int = -50, id: Int = 1): AccessPoint = + AccessPoint("fixture", "02:00:00:00:01:${id.toString(16).padStart(2, '0')}", rssi, frequency, + centerFrequencyMhz = center, channel = channelForFrequency(frequency), band = bandForFrequency(frequency), + widthMhz = width, security = WifiSecurity.WPA2, standard = "ax", ageMs = 0, locallyAdministered = true) + + private data class Case(val name: String, val frequency: Int, val width: Int?, val center: Int?, + val lower: Double, val upper: Double, val source: BondingCenterSource) + + private val cases = listOf( + // 2.4 GHz 40 MHz: 1–4 HT40+, 10–13 HT40−, 5–9 ambiguous, 14 cannot bond. + Case("2.4 ch1 40", 2412, 40, null, 2402.0, 2442.0, BondingCenterSource.RASTER), + Case("2.4 ch4 40", 2427, 40, null, 2417.0, 2457.0, BondingCenterSource.RASTER), + Case("2.4 ch5 40", 2432, 40, null, 2422.0, 2442.0, BondingCenterSource.UNKNOWN), + Case("2.4 ch9 40", 2452, 40, null, 2442.0, 2462.0, BondingCenterSource.UNKNOWN), + Case("2.4 ch10 40", 2457, 40, null, 2427.0, 2467.0, BondingCenterSource.RASTER), + Case("2.4 ch13 40", 2472, 40, null, 2442.0, 2482.0, BondingCenterSource.RASTER), + Case("2.4 ch14 40", 2484, 40, null, 2474.0, 2494.0, BondingCenterSource.UNKNOWN), + Case("2.4 ch1 80 (invalid)", 2412, 80, null, 2402.0, 2422.0, BondingCenterSource.UNKNOWN), + // 5 GHz fixed blocks. + Case("5 ch36 40", 5180, 40, null, 5170.0, 5210.0, BondingCenterSource.RASTER), + Case("5 ch40 40", 5200, 40, null, 5170.0, 5210.0, BondingCenterSource.RASTER), + Case("5 ch44 40", 5220, 40, null, 5210.0, 5250.0, BondingCenterSource.RASTER), + Case("5 ch40 80", 5200, 80, null, 5170.0, 5250.0, BondingCenterSource.RASTER), + Case("5 ch64 80", 5320, 80, null, 5250.0, 5330.0, BondingCenterSource.RASTER), + Case("5 ch144 80", 5720, 80, null, 5650.0, 5730.0, BondingCenterSource.RASTER), + Case("5 ch165 80", 5825, 80, null, 5815.0, 5895.0, BondingCenterSource.RASTER), + Case("5 ch40 160", 5200, 160, null, 5170.0, 5330.0, BondingCenterSource.RASTER), + Case("5 ch165 160", 5825, 160, null, 5735.0, 5895.0, BondingCenterSource.RASTER), + Case("5 ch144 160 (outside block)", 5720, 160, null, 5710.0, 5730.0, BondingCenterSource.UNKNOWN), + Case("5 ch32 40 (outside block)", 5160, 40, null, 5150.0, 5170.0, BondingCenterSource.UNKNOWN), + Case("5 ch36 320", 5180, 320, null, 5170.0, 5190.0, BondingCenterSource.UNKNOWN), + // 6 GHz blocks from channel 1; 320 MHz has two overlapping rasters. + Case("6 ch1 80", 5955, 80, null, 5945.0, 6025.0, BondingCenterSource.RASTER), + Case("6 ch13 80", 6015, 80, null, 5945.0, 6025.0, BondingCenterSource.RASTER), + Case("6 ch17 80", 6035, 80, null, 6025.0, 6105.0, BondingCenterSource.RASTER), + Case("6 ch225 80 (incomplete block)", 7075, 80, null, 7065.0, 7085.0, BondingCenterSource.UNKNOWN), + Case("6 ch33 160", 6115, 160, null, 6105.0, 6265.0, BondingCenterSource.RASTER), + Case("6 ch233 40 (incomplete block)", 7115, 40, null, 7105.0, 7125.0, BondingCenterSource.UNKNOWN), + Case("6 ch2 40 (special)", 5935, 40, null, 5925.0, 5945.0, BondingCenterSource.UNKNOWN), + Case("6 ch1 320", 5955, 320, null, 5945.0, 5965.0, BondingCenterSource.UNKNOWN), + Case("6 ch33 320", 6115, 320, null, 6105.0, 6125.0, BondingCenterSource.UNKNOWN), + // Reported centre always wins, even where the raster would disagree or is ambiguous. + Case("2.4 ch5 40 reported HT40+", 2432, 40, 2442, 2422.0, 2462.0, BondingCenterSource.REPORTED), + Case("2.4 ch13 40 reported", 2472, 40, 2462, 2442.0, 2482.0, BondingCenterSource.REPORTED), + Case("5 ch36 80 reported", 5180, 80, 5210, 5170.0, 5250.0, BondingCenterSource.REPORTED), + Case("6 ch1 320 reported", 5955, 320, 6105, 5945.0, 6265.0, BondingCenterSource.REPORTED), + // 20 MHz and unknown width: primary channel, never a note. + Case("2.4 ch6 20", 2437, 20, null, 2427.0, 2447.0, BondingCenterSource.PRIMARY), + Case("5 ch36 width unknown", 5180, null, null, 5170.0, 5190.0, BondingCenterSource.PRIMARY), + ) + + @Test fun fallbackTable() { + for (case in cases) { + val layout = occupiedLayout(ap(case.frequency, case.width, case.center)) + assertEquals(listOf(OccupiedFrequencySegment(case.lower, case.upper)), layout.segments, case.name) + assertEquals(case.source, layout.centerSource, case.name) + assertEquals(case.source == BondingCenterSource.UNKNOWN, layout.centerUnknown, case.name) + assertEquals(layout.segments, occupiedFrequencySegments(ap(case.frequency, case.width, case.center)), case.name) + assertEquals(layout.centerUnknown, bondingCenterUnknown(ap(case.frequency, case.width, case.center)), case.name) + } + } + + @Test fun rasterCentreIsNullWhenAmbiguous() { + assertEquals(2422.0, bondingRasterCenterMhz(2412, WifiBand.GHZ_2_4, 40)) + assertNull(bondingRasterCenterMhz(2437, WifiBand.GHZ_2_4, 40)) + assertNull(bondingRasterCenterMhz(2412, WifiBand.GHZ_2_4, 20)) + assertEquals(5250.0, bondingRasterCenterMhz(5180, WifiBand.GHZ_5, 160)) + assertNull(bondingRasterCenterMhz(5180, WifiBand.GHZ_5, 320)) + assertNull(bondingRasterCenterMhz(5180, WifiBand.GHZ_6, 80)) // band does not match the frequency + assertNull(bondingRasterCenterMhz(2477, WifiBand.GHZ_2_4, 40)) // not a channel + assertNull(bondingRasterCenterMhz(2412, WifiBand.UNKNOWN, 40)) + } + + @Test fun eightyPlusEightyWithoutCentreUsesThe80RasterForThePrimarySegment() { + val plus = ap(5180, 160).copy(secondaryCenterFrequencyMhz = 5530, is80Plus80 = true) + val layout = occupiedLayout(plus) + assertEquals(listOf(OccupiedFrequencySegment(5170.0, 5250.0), OccupiedFrequencySegment(5490.0, 5570.0)), layout.segments) + assertEquals(BondingCenterSource.RASTER, layout.centerSource) + } + + @Test fun spectrumTraceCarriesTheSourceAndDrawsOnlyThePrimaryWhenUnknown() { + val traces = spectrumTraces(listOf(ap(2472, 40, id = 1, rssi = -40), ap(2437, 40, id = 2, rssi = -60), + ap(2412, 20, id = 3, rssi = -70)), WifiBand.GHZ_2_4) + assertEquals(listOf(BondingCenterSource.RASTER, BondingCenterSource.UNKNOWN, BondingCenterSource.PRIMARY), + traces.map { it.centerSource }) + assertEquals(listOf(false, true, false), traces.map { it.centerUnknown }) + assertEquals(2442.0 to 2482.0, traces[0].shapes.single().let { it.lowerMhz to it.upperMhz }) + assertEquals(2427.0 to 2447.0, traces[1].shapes.single().let { it.lowerMhz to it.upperMhz }) + // Channel 13 at 40 MHz without centre no longer runs past the 2.4 GHz axis. + val axis = spectrumAxis(WifiBand.GHZ_2_4)!! + assertTrue(traces[0].shapes.single().upperMhz < axis.maxMhz) + } + + @Test fun overlapScoreAndHealthFollowTheFallback() { + // Channel 13 HT40− without centre occupies 2442–2482: channel 9 (2442–2462) fully covered. + // Before: primary ±20 MHz = 2452–2492, i.e. only half of channel 9. + val ch13 = listOf(ap(2472, 40, rssi = -50)) + assertEquals(1e-5, overlapScore(9, WifiBand.GHZ_2_4, ch13), 1e-15) + // Channel 14 (2474–2494) overlaps 8 MHz of it (before: 18 MHz). + assertEquals(0.4e-5, overlapScore(14, WifiBand.GHZ_2_4, ch13), 1e-15) + // Channel 1 HT40+ without centre: 2402–2442 covers channel 5 (2422–2442) fully, nothing below 2402. + val ch1 = listOf(ap(2412, 40, rssi = -50)) + assertEquals(1e-5, overlapScore(5, WifiBand.GHZ_2_4, ch1), 1e-15) + // Ambiguous channel 6: only its primary 20 MHz counts (channel 3 overlaps 5 of 20 MHz). + val ch6 = listOf(ap(2437, 40, rssi = -50)) + assertEquals(0.25e-5, overlapScore(3, WifiBand.GHZ_2_4, ch6), 1e-15) + assertEquals(0.0, overlapScore(10, WifiBand.GHZ_2_4, ch6), 1e-15) + + // 5 GHz 80 MHz on primary 36 without centre: block 36–48, so channel 48 is overlapped. + val health = scoreChannelHealth(listOf(ap(5180, 80, rssi = -50)), WifiBand.GHZ_5) + assertEquals(1, health.single { it.channel == 48 }.overlappingAccessPoints) + assertEquals(0, health.single { it.channel == 52 }.overlappingAccessPoints) + assertFalse(health.any { it.channel == 32 }) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/MloTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/MloTest.kt new file mode 100644 index 0000000..a386332 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/MloTest.kt @@ -0,0 +1,58 @@ +package cz.netkit.shared.wifi + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class MloTest { + private val address = "02:00:00:00:52:ab" + private val link = AssociatedLink(1, 2, 36, 5180, -55, 3) + private val scan = MloScanWidth(address.uppercase(), 1, 5180, 1000, 4) + private fun read(links: List = listOf(link), mld: String? = address.uppercase(), + allowed: Boolean = true, scans: List = listOf(scan), now: Long = 1100) = + mloConnection(links, mld, allowed, scans, now) + + @Test fun emptyOrInvalidLinksHideTheCard() { + assertNull(read(emptyList())) + assertNull(read(listOf(link.copy(id = -1), link.copy(id = 16)))) + } + + @Test fun stableOrderAndDistinctLinksWithTheirOwnMetrics() { + val other = link.copy(id = 0, band = 8, channel = 5, frequencyMhz = 5975, state = 2, rssi = -67) + assertEquals(MloConnection(listOf( + MloLinkInfo(0, MloBand.GHZ_6, 5, -67, MloState.IDLE, null), + MloLinkInfo(1, MloBand.GHZ_5, 36, -55, MloState.ACTIVE, MloWidth.W80_PLUS_80)), address), + read(listOf(link, other, link))) + } + + @Test fun permissionAndRedactionSuppressAddressAndScanMatch() { + for (result in listOf(read(allowed = false), read(mld = "02:00:00:00:00:00"), read(mld = null))) { + assertNull(result!!.apMldAddress) + assertNull(result.links.single().advertisedWidth) + assertEquals(-55, result.links.single().rssiDbm) + } + } + + @Test fun unknownFieldsRemainUnknown() { + val invalid = link.copy(band = 99, state = 0, channel = 0, rssi = -127, frequencyMhz = -1) + assertEquals(MloLinkInfo(1, null, null, null, MloState.UNKNOWN, null), read(listOf(invalid))!!.links.single()) + assertEquals(MloBand.GHZ_2_4, read(listOf(link.copy(band = 1)))!!.links.single().band) + val unassociated = read(listOf(link.copy(band = 16, state = 1)))!!.links.single() + assertEquals(MloBand.GHZ_60, unassociated.band) + assertEquals(MloState.UNASSOCIATED, unassociated.state) + } + + @Test fun widthRequiresSameMldLinkFrequencyAndRecentTimestamp() { + for (wrong in listOf(scan.copy(mld = "02:00:00:00:52:cd"), scan.copy(id = 2), + scan.copy(frequencyMhz = 5200), scan.copy(seenMs = 0), scan.copy(seenMs = 1101), scan.copy(widthCode = 99))) + assertNull(read(scans = listOf(wrong))!!.links.single().advertisedWidth) + assertNull(read(now = 1001 + WIFI_DATASET_WARNING_MS)!!.links.single().advertisedWidth) + assertEquals(MloWidth.W80_PLUS_80, read(now = 1000 + WIFI_DATASET_WARNING_MS)!!.links.single().advertisedWidth) + } + + @Test fun newestMatchingScanWinsAndAllDocumentedWidthsMap() { + val expected = listOf(MloWidth.W20, MloWidth.W40, MloWidth.W80, MloWidth.W160, MloWidth.W80_PLUS_80, MloWidth.W320) + for ((code, width) in expected.withIndex()) + assertEquals(width, read(scans = listOf(scan.copy(widthCode = code, seenMs = 1050), scan))!!.links.single().advertisedWidth) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/SpectrumTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/SpectrumTest.kt index 66b009a..ca63f45 100644 --- a/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/SpectrumTest.kt +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/SpectrumTest.kt @@ -22,19 +22,57 @@ class SpectrumTest { // --- axis ------------------------------------------------------------------------------- - @Test fun axis24CoversChannels1To13AndAdds14OnlyWhenPresent() { + @Test fun axis24AlwaysShowsChannels1To14WithMarginAndOutOfBandAbove2483_5() { val axis = spectrumAxis(WifiBand.GHZ_2_4)!! - assertEquals((1..13).toList(), axis.channels) - assertEquals(2402.0, axis.minMhz) - assertEquals(2482.0, axis.maxMhz) + assertEquals((1..14).toList(), axis.channels) + // Channel 1 lower edge 2402 − 5 MHz, channel 14 upper edge 2494 + 5 MHz (zadání 34, rozhodnutí 1). + assertEquals(2397.0, axis.minMhz) + assertEquals(2499.0, axis.maxMhz) + assertEquals(SPECTRUM_24_MIN_MHZ, axis.minMhz) + assertEquals(SPECTRUM_24_MAX_MHZ, axis.maxMhz) assertTrue(axis.ticks.all { it.labelled }) assertEquals(2437.0, axis.ticks.single { it.channel == 6 }.frequencyMhz) - assertTrue(axis.gaps.isEmpty()) + assertEquals(2484.0, axis.ticks.single { it.channel == 14 }.frequencyMhz) + assertTrue(axis.gaps.isEmpty()) // 13 (2462–2482) and 14 (2474–2494) touch/overlap + assertEquals(listOf(SpectrumGap(2483.5, 2499.0)), axis.outOfBand) + assertEquals(listOf(14), axis.ticks.filter { it.outOfBand }.map { it.channel }) + // Both skirts of channel 1 and 13 lie strictly inside the axis (no clamping to the edge). + assertTrue(axis.fraction(2402.0) > 0.0) + assertTrue(axis.fraction(2482.0) < 1.0) + assertTrue(axis.fraction(2494.0) < 1.0) + // An AP on 2484 MHz does not change the display axis. + assertEquals(axis, spectrumAxis(WifiBand.GHZ_2_4, listOf(ap(2484)))!!) + } + + @Test fun axisMarginAndOutOfBandOnlyOn24() { + assertTrue(spectrumAxis(WifiBand.GHZ_5)!!.outOfBand.isEmpty()) + assertTrue(spectrumAxis(WifiBand.GHZ_6)!!.outOfBand.isEmpty()) + assertTrue(spectrumAxis(WifiBand.GHZ_5)!!.ticks.none { it.outOfBand }) + assertTrue(spectrumAxis(WifiBand.GHZ_6, listOf(ap(5935)))!!.ticks.none { it.outOfBand }) + } + + @Test fun healthRaster24StaysChannels1To13And14OnlyWithAnApOn2484() { + assertEquals((1..13).toList(), channelHealthChannels(WifiBand.GHZ_2_4)) + assertEquals((1..13).toList(), channelHealthChannels(WifiBand.GHZ_2_4, listOf(ap(2412), ap(2472, id = 2)))) + assertEquals((1..14).toList(), channelHealthChannels(WifiBand.GHZ_2_4, listOf(ap(2484)))) + // A 5 GHz AP does not count as a channel 14 user; invalid 2477 MHz is not a channel. + assertEquals((1..13).toList(), channelHealthChannels(WifiBand.GHZ_2_4, listOf(ap(5180), ap(2477)))) + assertTrue(channelHealthChannels(WifiBand.UNKNOWN).isEmpty()) + assertEquals(spectrumAxis(WifiBand.GHZ_5)!!.channels, channelHealthChannels(WifiBand.GHZ_5)) + assertEquals(spectrumAxis(WifiBand.GHZ_6, listOf(ap(5935)))!!.channels, channelHealthChannels(WifiBand.GHZ_6, listOf(ap(5935)))) - val withJapan = spectrumAxis(WifiBand.GHZ_2_4, listOf(ap(2484)))!! - assertEquals(14, withJapan.channels.last()) - assertEquals(2494.0, withJapan.maxMhz) - assertTrue(withJapan.gaps.isEmpty()) // 13 (2462–2482) and 14 (2474–2494) touch/overlap + assertEquals((1..13).toList(), scoreChannelHealth(listOf(ap(2412, -60)), WifiBand.GHZ_2_4).map { it.channel }) + assertEquals((1..14).toList(), scoreChannelHealth(listOf(ap(2412, -60), ap(2484, -70, id = 2)), WifiBand.GHZ_2_4).map { it.channel }) + assertEquals(2484.0, scoreChannelHealth(listOf(ap(2484, -70)), WifiBand.GHZ_2_4).of(14).centerFrequencyMhz) + val report = channelHealthReport(state(ap(2412, -60)), WifiBand.GHZ_2_4, 2_000) + assertIs(report) + assertEquals((1..13).toList(), report.channels.map { it.channel }) + val withJapan = channelHealthReport(state(ap(2412, -60), ap(2484, -70, id = 2)), WifiBand.GHZ_2_4, 2_000) + assertIs(withJapan) + assertEquals((1..14).toList(), withJapan.channels.map { it.channel }) + // Recommendations keep the 1/6/11 candidates regardless of the display axis. + assertEquals(listOf(1, 6, 11), recommendationChannels(WifiBand.GHZ_2_4, 20)) + assertEquals(11, recommendChannels(listOf(ap(2412, -40), ap(2437, -40, id = 2))).single().channel) } @Test fun axis5KeepsRealGapsLinear() { @@ -83,9 +121,10 @@ class SpectrumTest { assertEquals(5178.0 to 5242.0, w80.plateauLowerMhz to w80.plateauUpperMhz) val w160 = shape(ap(5180, width = 160, center = 5250)) assertEquals(5170.0 to 5330.0, w160.lowerMhz to w160.upperMhz) - // Without centre fields the primary channel ± width/2 is used. + // Without centre fields the bonding raster places the span: primary 36 at 40 MHz is block 36–40 + // (zadání 34 bod 4; dříve primární ±20 MHz = 5160–5200, tj. na špatné straně kanálu 36). val noCenter = shape(ap(5180, width = 40)) - assertEquals(5160.0 to 5200.0, noCenter.lowerMhz to noCenter.upperMhz) + assertEquals(5170.0 to 5210.0, noCenter.lowerMhz to noCenter.upperMhz) val plus = ap(5180, width = 160, center = 5210).copy(secondaryCenterFrequencyMhz = 5530, is80Plus80 = true) val trace = spectrumTraces(listOf(plus), WifiBand.GHZ_5).single() diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WalkLogTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WalkLogTest.kt new file mode 100644 index 0000000..6521686 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WalkLogTest.kt @@ -0,0 +1,164 @@ +package cz.netkit.shared.wifi + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.double +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** Zadání 38 AC-004: walk recorder in virtual time (elapsed milliseconds are plain numbers). */ +class WalkLogTest { + private val a = "02:00:00:00:38:0a" + private val b = "02:00:00:00:38:0b" + + @Test fun recordsSamplesEventsMarksAndSummary() { + val recorder = WalkRecorder() + val roaming = RoamingDetector() + recorder.start(elapsedMs = 100_000, epochMs = 1_796_083_200_000) + var lost = 0 + for (second in 0 until 20) { + val t = 100_000L + second * 1_000 + val bssid = if (second < 10) a else b + val channel = if (second < 5) 1 else if (second < 10) 6 else 11 // channel change on AP a at 5 s + val isLost = second == 3 || second == 4 + if (isLost) lost++ + recorder.observeGateway(t, if (isLost) null else 2.5 + second, isLost) + val roam = roaming.observe(t, bssid, 2407 + channel * 5) + assertTrue(recorder.sample(t, -50 - second, bssid, channel, 433, 390, roam)) + // A second reading within the same second is not a new sample. + assertFalse(recorder.sample(t + 200, -99, bssid, channel, 1, 1)) + } + assertEquals(WalkMarkResult.ADDED, recorder.mark(112_500, " Kuchyň,\n2. patro ")) + assertEquals(WalkMarkResult.EMPTY, recorder.mark(112_600, " \t ")) + assertEquals(WalkMarkResult.TOO_LONG, recorder.mark(112_700, "x".repeat(WALK_MARK_MAX_LENGTH + 1))) + assertEquals(WalkMarkResult.ADDED, recorder.mark(112_800, "x".repeat(WALK_MARK_MAX_LENGTH))) + recorder.stop(120_000, WalkStopReason.USER) + assertEquals(WalkStatus.STOPPED, recorder.status) + assertFalse(recorder.sample(121_000, -50, a, 1, 1, 1)) + assertEquals(WalkMarkResult.NOT_RECORDING, recorder.mark(121_000, "late")) + + val log = recorder.snapshot(500_000) + val summary = log.summary!! + assertEquals(20_000, summary.durationMs) + assertEquals(20, summary.samples) + assertEquals(1, summary.roamings) + assertEquals(1, summary.channelChanges) // 1 → 6 on a; the 6 → 11 jump comes with the roam to b + assertEquals(2, summary.marks) + assertEquals(-69, summary.minRssiDbm) + assertEquals(20, summary.gatewaySent) + assertEquals(2, summary.gatewayLost) + assertEquals(WalkStopReason.USER, summary.stopReason) + assertEquals("Kuchyň, 2. patro", log.events.single { it.elapsedMs == 112_500L }.detail) + assertEquals("$a → $b", log.events.single { it.kind == WalkEventKind.ROAMING }.detail) + // Gateway echo attached to its sample: lost at 3 s, value at 2 s. + assertTrue(log.samples[3].gatewayLost) + assertNull(log.samples[3].gatewayMs) + assertEquals(4.5, log.samples[2].gatewayMs) + } + + /** Codex revize kolo 1 (P2): a timeout completes after the sample of its second and must still show up. */ + @Test fun asyncTimeoutLandsOnTheNextSampleAndLateResultsAreNotDropped() { + val recorder = WalkRecorder() + recorder.start(0, 0) + // Probe started at 1 ms; the sample at 1000 ms runs before the timeout is known. + assertTrue(recorder.sample(1_000, -60, a, 6, null, null)) + recorder.observeGateway(1_001, null, lost = true) // timeout completes after the sample + recorder.observeGateway(1_950, 4.0, lost = false) // next probe answers + assertTrue(recorder.sample(2_000, -60, a, 6, null, null)) + // The loop stalled: a loss completed 1.4 s before the next sample is still attached. + recorder.observeGateway(2_600, null, lost = true) + assertTrue(recorder.sample(4_000, -60, a, 6, null, null)) + // A result completed after a sample's time waits for the following one (virtual time). + recorder.observeGateway(4_600, 7.0, lost = false) + assertTrue(recorder.sample(4_500, -60, a, 6, null, null)) + assertNull(recorder.snapshot(4_500).samples.last().gatewayMs) + recorder.observeGateway(5_200, null, lost = true) // after the last sample + recorder.stop(5_300, WalkStopReason.USER) + val samples = recorder.snapshot(5_300).samples + assertEquals(listOf(false, true, true, true), samples.map { it.gatewayLost }) + assertEquals(listOf(null, 4.0, null, 7.0), samples.map { it.gatewayMs }) + val summary = recorder.summary(5_300)!! + assertEquals(5, summary.gatewaySent) + assertEquals(3, summary.gatewayLost) + // Every counted loss is visible in at least one sample of the CSV. + val csv = exportWalkLog(recorder.snapshot(5_300), WifiExportFormat.CSV)!! + assertEquals(3, csv.lines().count { it.startsWith("sample,") && it.endsWith(",true,") }) + } + + @Test fun sampleLimitStopsTheRecording() { + val recorder = WalkRecorder(maxSamples = 5) + recorder.start(0, 0) + for (second in 0 until 10) recorder.sample(second * 1_000L, -60, a, 6, null, null) + assertEquals(WalkStatus.STOPPED, recorder.status) + assertEquals(WalkStopReason.SAMPLE_LIMIT, recorder.stopReason) + assertEquals(5, recorder.sampleCount) + assertEquals(4_000, recorder.summary(99_000)!!.durationMs) + } + + @Test fun defaultLimitsAreTwoHoursAnd7200Samples() { + val recorder = WalkRecorder() + recorder.start(0, 0) + var t = 0L + while (recorder.status == WalkStatus.RECORDING) { recorder.sample(t, -60, a, 6, null, null); t += 1_000 } + assertEquals(WALK_MAX_SAMPLES, recorder.sampleCount) + assertEquals(WalkStopReason.SAMPLE_LIMIT, recorder.stopReason) + // With gaps the duration limit comes first: 2 h after the start, no more samples. + val sparse = WalkRecorder() + sparse.start(0, 0) + assertTrue(sparse.sample(WALK_MAX_DURATION_MS - 1, -60, a, 6, null, null)) + assertFalse(sparse.sample(WALK_MAX_DURATION_MS, -60, a, 6, null, null)) + assertEquals(WalkStopReason.DURATION_LIMIT, sparse.stopReason) + assertEquals(WALK_MAX_DURATION_MS, sparse.summary(10 * WALK_MAX_DURATION_MS)!!.durationMs) + } + + @Test fun pauseStopsAndRestartClears() { + val recorder = WalkRecorder() + assertNull(recorder.summary(0)) + recorder.start(1_000, 0) + recorder.sample(1_000, -60, a, 6, null, null) + recorder.stop(1_500, WalkStopReason.PAUSED) + assertEquals(WalkStopReason.PAUSED, recorder.summary(9_000)!!.stopReason) + recorder.start(10_000, 0) + assertEquals(0, recorder.sampleCount) + assertEquals(WalkStatus.RECORDING, recorder.status) + // Running summary counts up to "now". + assertEquals(5_000, recorder.summary(15_000)!!.durationMs) + recorder.clear() + assertEquals(WalkLog.EMPTY, recorder.snapshot(0)) + assertNull(exportWalkLog(recorder.snapshot(0), WifiExportFormat.CSV)) + } + + @Test fun exportsCsvAndJson() { + val recorder = WalkRecorder() + recorder.start(5_000, 1_796_083_200_000) + recorder.observeGateway(5_050, 3.14159, lost = false) + recorder.sample(5_100, -55, a, 36, 866, 780) + recorder.mark(5_100, "Chodba, \"sever\"") + recorder.sample(6_100, null, null, null, null, null) + recorder.stop(7_000, WalkStopReason.USER) + val log = recorder.snapshot(7_000) + val csv = exportWalkLog(log, WifiExportFormat.CSV)!! + assertEquals(listOf( + "type,time,offset_s,rssi_dbm,bssid,channel,rx_link_mbps,tx_link_mbps,gateway_ms,gateway_lost,detail", + "sample,\"2026-12-01T00:00:00.100Z\",0.1,-55,\"$a\",36,866,780,3.142,false,", + "mark,\"2026-12-01T00:00:00.100Z\",0.1,,,,,,,,\"Chodba, \"\"sever\"\"\"", + "sample,\"2026-12-01T00:00:01.100Z\",1.1,,,,,,,false,", + "", + ), csv.split('\n')) + val json = Json.parseToJsonElement(exportWalkLog(log, WifiExportFormat.JSON)!!).jsonObject + assertEquals(WALK_EXPORT_FORMAT, json.getValue("format").jsonPrimitive.content) + assertEquals("2026-12-01T00:00:00.000Z", json.getValue("startedAt").jsonPrimitive.content) + val summary = json.getValue("summary").jsonObject + assertEquals(2.0, summary.getValue("durationS").jsonPrimitive.double) + assertEquals(2, summary.getValue("samples").jsonPrimitive.int) + assertEquals("USER", summary.getValue("stopReason").jsonPrimitive.content) + assertEquals(2, json.getValue("samples").jsonArray.size) + assertEquals("Chodba, \"sever\"", json.getValue("events").jsonArray.single().jsonObject.getValue("detail").jsonPrimitive.content) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiExtensionsTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiExtensionsTest.kt new file mode 100644 index 0000000..e990654 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiExtensionsTest.kt @@ -0,0 +1,229 @@ +package cz.netkit.shared.wifi + +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.int +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** Zadání 38: pins (AC-001), ESS groups (AC-002), scan export (AC-003), regional raster (AC-005). */ +class WifiExtensionsTest { + private fun ap(id: Int, frequency: Int, rssi: Int, ssid: String? = "net$id", current: Boolean = false, + bssid: String = "02:00:00:00:38:${id.toString(16).padStart(2, '0')}", width: Int? = 20) = AccessPoint( + ssid, bssid, rssi, frequency, centerFrequencyMhz = null, channel = channelForFrequency(frequency), + band = bandForFrequency(frequency), widthMhz = width, security = WifiSecurity.WPA2, standard = "ax", ageMs = 0, + locallyAdministered = true, isCurrent = current) + + private fun keys(traces: List) = traces.map { it.accessPoint.bssid.takeLast(2) } + + // --- AC-001 pins -------------------------------------------------------------------------- + + @Test fun drawnOrderIsConnectedThenPinnedThenStrongestUpToSix() { + val points = (1..10).map { ap(it, 2412 + (it % 13) * 5, -40 - it * 3) } + + ap(0x20, 2437, -85, current = true) + val traces = spectrumTraces(points, WifiBand.GHZ_2_4) + var pins = emptyList() + // Pin the three weakest non-connected APs (9, 10, 8), in that order. + for (id in listOf(9, 10, 8)) { + val update = togglePinnedAccessPoint(pins, points.single { it.bssid.endsWith(id.toString(16).padStart(2, '0')) }) + assertEquals(PinChange.PINNED, update.change) + pins = update.pins + } + val selection = spectrumSelection(traces, pins, WifiBand.GHZ_2_4, points) + assertEquals(WIFI_CHART_AP_LIMIT, selection.drawn.size) + assertEquals(listOf("20", "09", "0a", "08", "01", "02"), keys(selection.drawn)) + assertEquals(3, selection.pinnedKeys.size) + assertTrue(selection.missingPins.isEmpty()) + // Without pins: the connected AP first, then the strongest. + assertEquals(listOf("20", "01", "02", "03", "04", "05"), keys(spectrumSelection(traces).drawn)) + } + + @Test fun fourthPinIsRefusedAndTogglingUnpins() { + val points = (1..4).map { ap(it, 2437, -50) } + var pins = emptyList() + points.take(3).forEach { pins = togglePinnedAccessPoint(pins, it).pins } + assertEquals(3, pins.size) + val refused = togglePinnedAccessPoint(pins, points[3]) + assertEquals(PinChange.LIMIT_REACHED, refused.change) + assertEquals(pins, refused.pins) + val unpinned = togglePinnedAccessPoint(pins, points[1]) + assertEquals(PinChange.UNPINNED, unpinned.change) + assertEquals(listOf("02:00:00:00:38:01", "02:00:00:00:38:03"), unpinned.pins.map { it.bssid }) + assertEquals(PinChange.NO_BSSID, togglePinnedAccessPoint(pins, ap(9, 2437, -50, bssid = "")).change) + assertTrue(isPinned(pins, points[0].copy(bssid = "02:00:00:00:38:01".uppercase()))) + } + + @Test fun pinSurvivesNewScanByBssidAndMissingPinIsReportedInItsBand() { + val first = listOf(ap(1, 2412, -50), ap(2, 2437, -60, ssid = "Old name"), ap(3, 5180, -55)) + var pins = togglePinnedAccessPoint(emptyList(), first[1]).pins + pins = togglePinnedAccessPoint(pins, first[2]).pins + // New scan: AP 2 reappears with another SSID and RSSI, AP 3 (5 GHz) is gone. + val second = listOf(ap(1, 2412, -50), ap(2, 2437, -70, ssid = "New name"), ap(4, 2462, -40)) + pins = refreshPinnedAccessPoints(pins, second) + assertEquals("New name", pins.first().ssid) + val selection24 = spectrumSelection(spectrumTraces(second, WifiBand.GHZ_2_4), pins, WifiBand.GHZ_2_4, second) + assertEquals(listOf("02", "04", "01"), keys(selection24.drawn)) + assertTrue(selection24.missingPins.isEmpty()) // the missing pin was last seen on 5 GHz + val selection5 = spectrumSelection(spectrumTraces(second, WifiBand.GHZ_5), pins, WifiBand.GHZ_5, second) + assertTrue(selection5.drawn.isEmpty()) + assertEquals(listOf("02:00:00:00:38:03"), selection5.missingPins.map { it.bssid }) + // A pin present in the scan but on another band is not "missing". + val moved = listOf(ap(3, 2422, -60)) + assertTrue(spectrumSelection(spectrumTraces(moved, WifiBand.GHZ_5), pins, WifiBand.GHZ_5, moved).missingPins.isEmpty()) + } + + /** Codex revize kolo 1: a pin missing from the scan can be removed by BSSID and frees the limit. */ + @Test fun missingPinCanBeUnpinnedByBssid() { + val points = (1..4).map { ap(it, 2437, -50) } + var pins = emptyList() + points.take(3).forEach { pins = togglePinnedAccessPoint(pins, it).pins } + val scan = listOf(points[1], points[2], points[3]) // AP 1 is gone + val missing = spectrumSelection(spectrumTraces(scan, WifiBand.GHZ_2_4), pins, WifiBand.GHZ_2_4, scan).missingPins + assertEquals(listOf("02:00:00:00:38:01"), missing.map { it.bssid }) + assertEquals(PinChange.LIMIT_REACHED, togglePinnedAccessPoint(pins, points[3]).change) + pins = unpinAccessPoint(pins, missing.single().bssid.uppercase()) + assertEquals(2, pins.size) + assertEquals(PinChange.PINNED, togglePinnedAccessPoint(pins, points[3]).change) + assertEquals(pins, unpinAccessPoint(pins, "02:00:00:00:38:99")) + assertEquals(pins, unpinAccessPoint(pins, " ")) + } + + @Test fun connectedPinnedApIsDrawnOnce() { + val points = listOf(ap(1, 2412, -70, current = true), ap(2, 2437, -50)) + val pins = togglePinnedAccessPoint(emptyList(), points[0]).pins + val selection = spectrumSelection(spectrumTraces(points, WifiBand.GHZ_2_4), pins, WifiBand.GHZ_2_4, points) + assertEquals(listOf("01", "02"), keys(selection.drawn)) + assertEquals(1, selection.pinnedKeys.size) + } + + // --- AC-002 ESS groups -------------------------------------------------------------------- + + @Test fun groupsAggregateBssidsBandsChannelsAndStrongestRssi() { + val points = listOf( + ap(1, 2412, -70, ssid = "Home"), ap(2, 5180, -52, ssid = "Home"), ap(3, 5500, -61, ssid = "Home", current = true), + ap(4, 2437, -45, ssid = "Office"), + ap(5, 2462, -40, ssid = null), ap(6, 2462, -80, ssid = null), + ap(7, 5955, -66, ssid = "Home"), + ) + val entries = essListEntries(sortedAccessPoints(points, null, WifiSort.SIGNAL), WifiSort.SIGNAL) + // Hidden SSIDs stay single rows; order by the strongest RSSI of each entry. + assertEquals(listOf("single", "ess", "ess", "single"), entries.map { it.key.substringBefore(':') }) + val home = entries.filterIsInstance().single { it.ssid == "Home" } + assertEquals(4, home.apCount) + assertEquals(listOf(WifiBand.GHZ_2_4, WifiBand.GHZ_5, WifiBand.GHZ_6), home.bands) + assertEquals(mapOf(WifiBand.GHZ_2_4 to listOf(1), WifiBand.GHZ_5 to listOf(36, 100), WifiBand.GHZ_6 to listOf(1)), + home.channelsByBand) + assertEquals(-52, home.strongestRssiDbm) + assertTrue(home.hasCurrent) + assertEquals(listOf(-52, -61, -66, -70), home.accessPoints.map { it.rssiDbm }) + assertEquals(2, entries.filterIsInstance().size) + assertTrue(entries.filterIsInstance().none { it.ssid.isEmpty() }) + } + + @Test fun groupsSortByNameAndChannel() { + val points = listOf(ap(1, 5180, -50, ssid = "beta"), ap(2, 2462, -60, ssid = "Alpha"), ap(3, 2412, -70, ssid = null), + ap(4, 2437, -55, ssid = "beta")) + assertEquals(listOf("Alpha", "beta", null), + essListEntries(points, WifiSort.NAME).map { (it as? EssListEntry.Group)?.ssid }) + // CHANNEL: lowest band first, then its lowest channel: hidden on 1, beta on 6, Alpha on 11. + assertEquals(listOf(null, "beta", "Alpha"), + essListEntries(points, WifiSort.CHANNEL).map { (it as? EssListEntry.Group)?.ssid }) + // Same SSID differing in case are different networks. + assertEquals(2, essListEntries(listOf(ap(1, 2412, -50, ssid = "a"), ap(2, 2412, -50, ssid = "A"))).size) + } + + // --- AC-003 export ------------------------------------------------------------------------ + + private val tricky = "Kavárna, \"U Lípy\"\nPatro 2" + + @Test fun csvEscapesCommasQuotesAndNewlinesInSsid() { + val points = listOf( + ap(1, 2437, -48, ssid = tricky).copy(vendor = "Acme, Inc.", stationCount = 3, channelUtilizationPercent = 40, + centerFrequencyMhz = 2447, widthMhz = 40, seenAtElapsedMs = 9_000), + ap(2, 5180, -70, ssid = "=HYPERLINK(\"x\")"), + ap(3, 2412, -60, ssid = null), + ) + val csv = exportWifiScan(points, WifiExportFormat.CSV, nowEpochMs = 1_764_579_903_042, nowElapsedMs = 10_000, + scanReceivedElapsedMs = 9_500) + val lines = csv.split('\n') + assertEquals("time,ssid,bssid,vendor,band,channel,width_mhz,center_mhz,center2_mhz,frequency_mhz," + + "rssi_dbm,security,standard,bss_load_stations,bss_load_utilization_percent,connected", lines[0]) + // Order: band, channel → hidden (ch 1), tricky (ch 6), 5 GHz. + assertEquals("\"2025-12-01T09:05:02.542Z\",,\"02:00:00:00:38:03\",,\"2.4\",1,20,,,2412,-60,\"WPA2\",\"ax\",,,false", lines[1]) + // RFC 4180: the quoted SSID keeps its comma and line break, quotes are doubled; RSSI stays a number. + assertTrue(csv.contains("\"2025-12-01T09:05:02.042Z\",\"Kavárna, \"\"U Lípy\"\"\nPatro 2\",\"02:00:00:00:38:01\"," + + "\"Acme, Inc.\",\"2.4\",6,40,2447,,2437,-48,\"WPA2\",\"ax\",3,40,false\n")) + // Formula neutralised. + assertTrue(csv.contains(",\"'=HYPERLINK(\"\"x\"\")\",")) + assertEquals(parseCsv(csv).map { it.size }.distinct(), listOf(16)) + assertEquals(tricky, parseCsv(csv)[1][1]) + } + + @Test fun jsonRoundTripsTrickySsidAndCarriesAllColumns() { + val points = listOf(ap(1, 2437, -48, ssid = tricky, current = true).copy(stationCount = 3, channelUtilizationPercent = 40)) + val text = exportWifiScan(points, WifiExportFormat.JSON, nowEpochMs = 0, nowElapsedMs = 0, scanReceivedElapsedMs = null) + val root = Json.parseToJsonElement(text).jsonObject + assertEquals(WIFI_SCAN_EXPORT_FORMAT, root.getValue("format").jsonPrimitive.content) + assertEquals("1970-01-01T00:00:00.000Z", root.getValue("exportedAt").jsonPrimitive.content) + val row = root.getValue("accessPoints").jsonArray.single().jsonObject + assertEquals(tricky, row.getValue("ssid").jsonPrimitive.content) + assertEquals(-48, row.getValue("rssiDbm").jsonPrimitive.int) + assertEquals(setOf("time", "ssid", "bssid", "vendor", "band", "channel", "widthMhz", "centerMhz", "center2Mhz", + "frequencyMhz", "rssiDbm", "security", "standard", "bssLoadStations", "bssLoadUtilizationPercent", "connected"), row.keys) + assertEquals(3, row.getValue("bssLoadStations").jsonPrimitive.int) + assertEquals("true", row.getValue("connected").jsonPrimitive.content) + } + + @Test fun isoUtcFormatsKnownInstants() { + assertEquals("1970-01-01T00:00:00.000Z", isoUtc(0)) + assertEquals("2000-02-29T23:59:59.999Z", isoUtc(951_868_799_999)) + assertEquals("2026-12-01T00:00:00.000Z", isoUtc(1_796_083_200_000)) + assertEquals("1969-12-31T23:59:59.999Z", isoUtc(-1)) + assertNull(elapsedToEpochMs(11, 1_000, 10)) + assertEquals(995, elapsedToEpochMs(5, 1_000, 10)) + } + + // --- AC-005 regional raster --------------------------------------------------------------- + + @Test fun regionalRasterMapsCountryCodes() { + assertEquals(Regional24Raster(WifiRegion.EU, "CZ", 1, 13), regional24Raster("cz")) + assertEquals(WifiRegion.EU, regional24Raster(" de ")?.region) + assertEquals(Regional24Raster(WifiRegion.US, "US", 1, 11), regional24Raster("us")) + val jp = regional24Raster("JP")!! + assertEquals(14, jp.lastChannel) + assertEquals(14, jp.dsssOnlyChannel) + assertFalse(jp.allowsOfdm(14)) + assertTrue(jp.allowsOfdm(13)) + assertFalse(regional24Raster("US")!!.allowsOfdm(12)) + assertEquals(27, EU_COUNTRY_CODES.size) + // Without a code (or an unknown one) nothing is shown. + for (code in listOf(null, "", " ", "XX", "CH", "GB", "cze", "c1")) assertNull(regional24Raster(code), "$code") + } + + /** Minimal RFC 4180 reader for the assertions (quoted cells may contain , " and \n). */ + private fun parseCsv(text: String): List> { + val rows = mutableListOf>() + var row = mutableListOf() + val cell = StringBuilder() + var quoted = false + var index = 0 + while (index < text.length) { + val c = text[index] + when { + quoted && c == '"' && text.getOrNull(index + 1) == '"' -> { cell.append('"'); index++ } + c == '"' -> quoted = !quoted + !quoted && c == ',' -> { row += cell.toString(); cell.clear() } + !quoted && c == '\n' -> { row += cell.toString(); cell.clear(); rows += row; row = mutableListOf() } + else -> cell.append(c) + } + index++ + } + return rows.drop(1) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolSecureOnTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolSecureOnTest.kt new file mode 100644 index 0000000..6977f48 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolSecureOnTest.kt @@ -0,0 +1,383 @@ +package cz.netkit.shared.wol + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest +import kotlin.test.* + +@OptIn(ExperimentalCoroutinesApi::class) +class WolSecureOnTest { + private val mac = parseMac("AA:BB:CC:DD:EE:FF")!! + private val password = byteArrayOf(0x11, 0x22, 0x33, 0x44, 0x55, 0x66) + + @Test fun passwordFormsAndPacketLength() { + assertContentEquals(password, parseSecureOn("11:22:33:44:55:66")) + assertContentEquals(password, parseSecureOn(" 11-22-33-44-55-66 ")) + assertContentEquals(byteArrayOf(192.toByte(), 0, 2, 7), parseSecureOn("192.0.2.7")) + listOf("", "11:22:33:44:55", "11:22:33:44:55:66:77", "11:22-33:44:55:66", "1122.3344.5566", "112233445566", "gg:22:33:44:55:66", "192.0.2", "256.0.0.1") + .forEach { assertNull(parseSecureOn(it), it) } + val packet = secureOnMagicPacket(mac, password) + assertEquals(108, packet.size) + assertContentEquals(magicPacket(mac), packet.copyOfRange(0, 102)) + assertContentEquals(password, packet.copyOfRange(102, 108)) + assertEquals(106, secureOnMagicPacket(mac, parseSecureOn("192.0.2.7")).size) + assertContentEquals(magicPacket(mac), secureOnMagicPacket(mac, null)) + assertFailsWith { secureOnMagicPacket(mac, ByteArray(5)) } + } + + @Test fun draftValidationAndMaskedToString() { + val draft = WolDeviceDraft(name = "PC", mac = "AA:BB:CC:DD:EE:FF", secureOn = "11:22:33:44:55:66") + assertTrue(validateDevice(draft).isValid) + assertEquals(setOf(DeviceField.SECURE_ON), validateDevice(draft.copy(secureOn = "11:22")).errors) + assertFalse("11:22:33:44:55:66" in draft.toString()) + assertTrue("***" in draft.toString()) + } + + @Test fun vaultRoundTripIsStrictAndBound() { + val vault = encodeSecureOnVault(mapOf("one" to SecureOnEntry(password, "AA|CUSTOM|x|9"), "two" to SecureOnEntry(byteArrayOf(1, 2, 3, 4), "BB|AUTO_BROADCAST||9"))) + val decoded = decodeSecureOnVault(vault) + assertContentEquals(password, decoded.getValue("one").password) + assertEquals("AA|CUSTOM|x|9", decoded.getValue("one").binding) + assertContentEquals(byteArrayOf(1, 2, 3, 4), decoded.getValue("two").password) + assertFalse("112233445566" in SecureOnEntry(password, "b").toString()) + listOf("""{"v":1,"p":{}}""", """{"v":2,"p":{"a":{"h":"11223","b":"x"}}}""", """{"v":2,"p":{"a":{"h":"1122334455GG","b":"x"}}}""", + """{"v":2,"p":{"a":{"h":"11223344","b":""}}}""", """{"v":2,"p":{"a":"11223344"}}""", """{"v":2,"p":{}, "x":1}""", "nope") + .forEach { assertFailsWith(it) { decodeSecureOnVault(it.encodeToByteArray()) } } + } + + @Test fun passwordIsReturnedOnlyForTheBoundMacAndTarget() { + val device = WolDevice("pc", "PC", "aa-bb-cc-dd-ee-ff", TargetMode.CUSTOM, "NAS.lan", 9, createdAt = 1, updatedAt = 1) + val vault = mapOf("pc" to SecureOnEntry(password, secureOnBinding(device))) + assertContentEquals(password, secureOnPasswordFor(device, vault)) + assertContentEquals(password, secureOnPasswordFor(device.copy(name = "Renamed", mac = "AA:BB:CC:DD:EE:FF", customTarget = "nas.lan"), vault)) + assertNull(secureOnPasswordFor(device.copy(mac = "AA:BB:CC:DD:EE:01"), vault)) + assertNull(secureOnPasswordFor(device.copy(customTarget = "192.168.1.9"), vault)) + assertNull(secureOnPasswordFor(device.copy(targetMode = TargetMode.LIMITED_BROADCAST), vault)) + assertNull(secureOnPasswordFor(device.copy(port = 7), vault)) + assertNull(secureOnPasswordFor(device.copy(id = "other"), vault)) + } + + @Test fun exportNeverCarriesThePasswordAndImportRejectsIt() { + // WolDevice has no password field, so neither format can contain one. + val device = WolDevice("one", "PC", "AA:BB:CC:DD:EE:FF", TargetMode.CUSTOM, "192.168.1.255", 9, createdAt = 1, updatedAt = 1) + val json = encodeWolExport(listOf(device)).decodeToString() + val csv = encodeWolCsvExport(listOf(device), { null }, "Default").decodeToString() + for (text in listOf(json, csv)) { + assertFalse("\"secureOn\":" in text, text) + assertFalse("11:22:33:44:55:66" in text.uppercase().lowercase(), text) + assertFalse("112233445566" in text, text) + } + // The Webb CSV column exists but is always empty. + assertTrue(csv.lines()[2].endsWith("\"-1\",\"\""), csv) + val field = "secure" + "On" + val extended = json.replace("\"probeDelaySeconds\":20", "\"probeDelaySeconds\":20,\"$field\":\"11-22-33-44-55-66\"") + assertNotEquals(json, extended) + assertEquals(WolImportFailure.UNKNOWN_FIELD, assertFailsWith { decodeWolImport(extended.encodeToByteArray()) }.reason) + } + + private class Store(var data: List = emptyList()) : WolDeviceStore { + override suspend fun load(): List = data + override suspend fun save(devices: List) { data = devices } + } + private class Store2(var data: List = emptyList()) : WolDeviceStore { + var failSave = false + override suspend fun load(): List = data + override suspend fun save(devices: List) { check(!failSave); data = devices } + } + private class Vault(var data: Map = emptyMap()) : WolSecureOnStore { + var failLoad = false + var failSave = false + var writes = 0 + override suspend fun load(): Map { check(!failLoad); return data } + override suspend fun save(entries: Map) { check(!failSave); writes++; data = entries; failLoad = false } + } + private fun bound(device: WolDevice, bytes: ByteArray = password) = SecureOnEntry(bytes, secureOnBinding(device)) + private class Sender : PacketSender { + val packets = mutableListOf() + override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray) { packets += payload } + } + private val wifi = object : NetworkInfoProvider { + override suspend fun currentWifi() = WifiNetworkInfo(object : WifiNetworkHandle {}, "192.168.1.30", 24) + } + + @Test fun controllerStoresUsesKeepsAndRemovesThePassword() = runTest { + val store = Store(); val vault = Vault(); val sender = Sender() + val c = WolController(store, wifi, sender, this, { 1 }, { "pc" }, secureOn = vault) + advanceUntilIdle() + c.add(); c.updateDraft(WolDeviceDraft(name = "PC", mac = "AA:BB:CC:DD:EE:FF", repeatCount = "1", secureOn = "11:22:33:44:55:66")); c.save() + advanceUntilIdle() + assertEquals(setOf("pc"), c.state.value.secureOnIds) + assertContentEquals(password, vault.data.getValue("pc").password) + assertEquals(secureOnBinding(store.data.single()), vault.data.getValue("pc").binding) + assertTrue(store.data.single().secureOnRequired, "the persistent flag, not the password, is in the device list") + c.wake("pc"); advanceUntilIdle() + assertEquals(108, sender.packets.single().size) + assertContentEquals(password, sender.packets.single().copyOfRange(102, 108)) + + // Editing without typing keeps it; the draft never holds the stored value. + c.edit("pc") + val draft = assertNotNull(c.state.value.draft) + assertTrue(draft.secureOnStored); assertEquals("", draft.secureOn) + c.updateDraft(draft.copy(name = "PC2")); c.save(); advanceUntilIdle() + assertContentEquals(password, vault.data.getValue("pc").password) + // The owner's own edit of MAC/target re-binds the kept password. + c.edit("pc"); c.updateDraft(assertNotNull(c.state.value.draft).copy(mac = "AA:BB:CC:DD:EE:01")); c.save(); advanceUntilIdle() + assertEquals(secureOnBinding(store.data.single()), vault.data.getValue("pc").binding) + assertEquals(setOf("pc"), c.state.value.secureOnIds) + c.wake("pc"); advanceUntilIdle() + assertEquals(108, sender.packets.last().size) + // Remove. + c.edit("pc"); c.updateDraft(assertNotNull(c.state.value.draft).copy(secureOnRemove = true)); c.save(); advanceUntilIdle() + assertTrue(vault.data.isEmpty()); assertEquals(emptySet(), c.state.value.secureOnIds) + c.wake("pc"); advanceUntilIdle() + assertEquals(102, sender.packets.last().size) + } + + @Test fun deletePrunesAndUnreadableStoreBlocksOnlyPossiblyProtectedDevices() = runTest { + val devices = listOf(WolDevice("a", "A", "AA:BB:CC:DD:EE:01", TargetMode.AUTO_BROADCAST, createdAt = 1, updatedAt = 1, repeatCount = 1), + WolDevice("b", "B", "AA:BB:CC:DD:EE:02", TargetMode.AUTO_BROADCAST, createdAt = 1, updatedAt = 1, repeatCount = 1)) + val vault = Vault(mapOf("a" to bound(devices[0]), "ghost" to SecureOnEntry(password, "x"))) + val sender = Sender() + val c = WolController(Store(devices), wifi, sender, this, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + assertEquals(setOf("a"), c.state.value.secureOnIds) + c.delete("a"); advanceUntilIdle() + assertTrue(vault.data.isEmpty(), "deleted and orphan entries are pruned") + + // A store that was readable at start but fails at send time: a device without a password still wakes. + vault.failLoad = true + c.wake("b"); advanceUntilIdle() + assertEquals(102, sender.packets.single().size) + + // Unreadable at start: every send fails closed rather than going out without a configured password. + val broken = Vault(mapOf("b" to bound(devices[1]))).also { it.failLoad = true } + val sender2 = Sender() + val c2 = WolController(Store(devices), wifi, sender2, this, { 1 }, { "new" }, secureOn = broken) + advanceUntilIdle() + assertTrue(c2.state.value.secureOnFailed) + c2.wake("b"); advanceUntilIdle() + assertTrue(sender2.packets.isEmpty()) + assertEquals(SendFailure.SECURE_ON_UNAVAILABLE, c2.state.value.outcomes.getValue("b").reason) + assertEquals(WolMessage.SECURE_ON_UNAVAILABLE, c2.state.value.message) + // Typing a new password replaces the unreadable store. + c2.edit("b"); c2.updateDraft(assertNotNull(c2.state.value.draft).copy(secureOn = "192.0.2.9")); c2.save(); advanceUntilIdle() + assertFalse(c2.state.value.secureOnFailed) + c2.wake("b"); advanceUntilIdle() + assertEquals(106, sender2.packets.single().size) + } + + @Test fun failedDeleteKeepsThePassword() = runTest { + val device = WolDevice("a", "A", "AA:BB:CC:DD:EE:01", TargetMode.AUTO_BROADCAST, createdAt = 1, updatedAt = 1, repeatCount = 1) + val store = Store2(listOf(device)).also { it.failSave = true } + val vault = Vault(mapOf("a" to bound(device))) + val c = WolController(store, wifi, Sender(), this, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + c.delete("a"); advanceUntilIdle() + assertEquals(WolMessage.SAVE_FAILED, c.state.value.message) + assertEquals(listOf(device), c.state.value.devices) + assertTrue("a" in vault.data, "the password is removed only after the device list was saved") + assertEquals(0, vault.writes) + } + + @Test fun importReplacingADeviceDropsItsPasswordAndForeignBindingNeverSends() = runTest { + val local = WolDevice("pc", "PC", "AA:BB:CC:DD:EE:01", TargetMode.CUSTOM, "192.168.1.10", 9, createdAt = 1, updatedAt = 1, repeatCount = 1) + val vault = Vault(mapOf("pc" to bound(local))) + val sender = Sender() + val c = WolController(Store2(listOf(local)), wifi, sender, this, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + assertEquals(setOf("pc"), c.state.value.secureOnIds) + val foreign = local.copy(name = "Other", mac = "AA:BB:CC:DD:EE:99", customTarget = "192.168.1.99", updatedAt = 2) + assertTrue(c.previewImport(listOf(foreign))) + c.confirmImport(); advanceUntilIdle() + assertFalse("pc" in vault.data, "import drops the entry of a replaced ID") + assertEquals(emptySet(), c.state.value.secureOnIds) + c.wake("pc"); advanceUntilIdle() + assertEquals(102, sender.packets.single().size) + + // Fail-closed (revize 39/2): an entry bound to another card blocks the wake, neither its password nor none is sent. + val stale = Vault(mapOf("pc" to bound(local))) + val sender2 = Sender() + val c2 = WolController(Store2(listOf(foreign)), wifi, sender2, this, { 1 }, { "new" }, secureOn = stale) + advanceUntilIdle() + assertEquals(emptySet(), c2.state.value.secureOnIds) + c2.wake("pc"); advanceUntilIdle() + assertTrue(sender2.packets.isEmpty()) + assertEquals(SendFailure.SECURE_ON_UNAVAILABLE, c2.state.value.outcomes.getValue("pc").reason) + // The editor says so; saving without a password deletes the stale entry, then the wake goes out plain. + c2.edit("pc") + val draft = assertNotNull(c2.state.value.draft) + assertTrue(draft.secureOnStale); assertFalse(draft.secureOnStored) + c2.save(); advanceUntilIdle() + assertFalse("pc" in stale.data) + c2.wake("pc"); advanceUntilIdle() + assertEquals(102, sender2.packets.single().size) + } + + private val local = WolDevice("pc", "PC", "AA:BB:CC:DD:EE:01", TargetMode.CUSTOM, "192.168.1.10", 9, createdAt = 1, updatedAt = 1, repeatCount = 1) + private val foreign = local.copy(name = "Other", mac = "AA:BB:CC:DD:EE:99", customTarget = "192.168.1.99", updatedAt = 2) + + @Test fun importWhoseListSaveFailsKeepsThePassword() = runTest { + val store = Store2(listOf(local)); val vault = Vault(mapOf("pc" to bound(local))); val sender = Sender() + val c = WolController(store, wifi, sender, this, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + store.failSave = true + assertTrue(c.previewImport(listOf(foreign))) + c.confirmImport(); advanceUntilIdle() + assertEquals(WolMessage.SAVE_FAILED, c.state.value.message) + assertEquals(listOf(local), c.state.value.devices) + assertEquals(bound(local), vault.data["pc"], "the vault is changed only after the list is saved") + c.wake("pc"); advanceUntilIdle() + assertEquals(108, sender.packets.single().size) + } + + @Test fun importWhoseVaultUpdateFailsBlocksTheReplacedDevice() = runTest { + val vault = Vault(mapOf("pc" to bound(local))); val sender = Sender() + val c = WolController(Store2(listOf(local)), wifi, sender, this, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + vault.failSave = true + assertTrue(c.previewImport(listOf(foreign))) + c.confirmImport(); advanceUntilIdle() + assertEquals(listOf(foreign), c.state.value.devices) + assertTrue("pc" in vault.data) + c.wake("pc"); advanceUntilIdle() + assertTrue(sender.packets.isEmpty(), "never the old card's password, never a packet without the expected one") + assertEquals(SendFailure.SECURE_ON_UNAVAILABLE, c.state.value.outcomes.getValue("pc").reason) + } + + @Test fun rebindWriteFailureKeepsTheEditorAndTheOldConfiguration() = runTest { + val store = Store2(listOf(local)); val vault = Vault(mapOf("pc" to bound(local))); val sender = Sender() + val c = WolController(store, wifi, sender, this, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + c.edit("pc"); c.updateDraft(assertNotNull(c.state.value.draft).copy(mac = "AA:BB:CC:DD:EE:02")) + vault.failSave = true + c.save(); advanceUntilIdle() + assertEquals(WolMessage.SAVE_FAILED, c.state.value.message) + assertNotNull(c.state.value.draft, "the editor stays open") + assertEquals(listOf(local), store.data) + c.cancelEdit() + c.wake("pc"); advanceUntilIdle() + assertEquals(108, sender.packets.single().size) + } + + @Test fun failedListSaveAfterRebindRollsBackOrFailsClosed() = runTest { + val store = Store2(listOf(local)); val vault = Vault(mapOf("pc" to bound(local))); val sender = Sender() + val c = WolController(store, wifi, sender, this, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + c.edit("pc"); c.updateDraft(assertNotNull(c.state.value.draft).copy(mac = "AA:BB:CC:DD:EE:02")) + store.failSave = true + c.save(); advanceUntilIdle() + assertEquals(bound(local), vault.data["pc"], "rolled back to the old binding") + c.cancelEdit(); c.wake("pc"); advanceUntilIdle() + assertEquals(108, sender.packets.single().size) + + // The rollback itself fails: the entry stays bound to the unsaved MAC, so the old device is blocked, not sent plain. + val vault2 = object : WolSecureOnStore { + var data = mapOf("pc" to bound(local)); var saves = 0 + override suspend fun load() = data + override suspend fun save(entries: Map) { check(++saves == 1); data = entries } + } + val sender2 = Sender() + val c2 = WolController(Store2(listOf(local)).also { it.failSave = true }, wifi, sender2, this, { 1 }, { "new" }, secureOn = vault2) + advanceUntilIdle() + c2.edit("pc"); c2.updateDraft(assertNotNull(c2.state.value.draft).copy(mac = "AA:BB:CC:DD:EE:02")); c2.save(); advanceUntilIdle() + assertEquals(SecureOnEntry(password, secureOnBinding(local.copy(mac = "AA:BB:CC:DD:EE:02"))), vault2.data["pc"]) + c2.cancelEdit(); c2.wake("pc"); advanceUntilIdle() + assertTrue(sender2.packets.isEmpty()) + assertEquals(SendFailure.SECURE_ON_UNAVAILABLE, c2.state.value.outcomes.getValue("pc").reason) + } + + @Test fun importVaultFailureThenEditWithoutPasswordNeverRebinds() = runTest { + val vault = Vault(mapOf("pc" to bound(local))); val sender = Sender() + val c = WolController(Store2(listOf(local)), wifi, sender, this, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + vault.failSave = true + assertTrue(c.previewImport(listOf(foreign))) + c.confirmImport(); advanceUntilIdle() + assertEquals(listOf(foreign), c.state.value.devices) + // Flags are recomputed from the vault and the new list although dropping the entry failed. + assertEquals(emptySet(), c.state.value.secureOnIds) + c.edit("pc") + val draft = assertNotNull(c.state.value.draft) + assertFalse(draft.secureOnStored); assertTrue(draft.secureOnStale) + // Even a draft that claims a stored password cannot re-bind the old card's password to the imported one. + c.updateDraft(draft.copy(secureOnStored = true, name = "Imported")) + c.save(); advanceUntilIdle() + assertEquals(bound(local), vault.data["pc"], "the old password stays bound to the old card") + c.cancelEdit() + c.wake("pc"); advanceUntilIdle() + assertTrue(sender.packets.isEmpty()) + assertEquals(SendFailure.SECURE_ON_UNAVAILABLE, c.state.value.outcomes.getValue("pc").reason) + } + + private class GatedStore(var data: List) : WolDeviceStore { + val gate = kotlinx.coroutines.CompletableDeferred() + var fail = false + var gated = false + override suspend fun load(): List = data + override suspend fun save(devices: List) { if (gated) gate.await(); check(!fail); data = devices } + } + + @Test fun cancellingTheScopeDuringTheListSaveStillRollsBackOrCompletes() = runTest { + for (listSaveFails in listOf(true, false)) { + val job = kotlinx.coroutines.Job() + val scope = kotlinx.coroutines.CoroutineScope(coroutineContext + job) + val store = GatedStore(listOf(local)); val vault = Vault(mapOf("pc" to bound(local))) + val c = WolController(store, wifi, Sender(), scope, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + store.gated = true; store.fail = listSaveFails + c.edit("pc"); c.updateDraft(assertNotNull(c.state.value.draft).copy(mac = "AA:BB:CC:DD:EE:02")); c.save() + runCurrent() + val moved = local.copy(mac = "AA:BB:CC:DD:EE:02") + assertEquals(secureOnBinding(moved), vault.data.getValue("pc").binding, "re-bound before the list save") + job.cancel() + store.gate.complete(Unit) + advanceUntilIdle() + if (listSaveFails) { + assertEquals(listOf(local), store.data) + assertEquals(bound(local), vault.data["pc"], "rollback ran despite the cancelled scope") + } else { + assertEquals(moved.mac, store.data.single().mac) + assertEquals(secureOnBinding(store.data.single()), vault.data.getValue("pc").binding, "list and vault stay consistent") + } + } + } + + @Test fun unreadableStoreIsNotOverwrittenWhileOtherDevicesRequireAPassword() = runTest { + val other = WolDevice("b", "B", "AA:BB:CC:DD:EE:02", TargetMode.AUTO_BROADCAST, createdAt = 1, updatedAt = 1, repeatCount = 1, secureOnRequired = true) + val vault = Vault(mapOf("b" to bound(other))).also { it.failLoad = true } + val store = Store2(listOf(local, other)) + val c = WolController(store, wifi, Sender(), this, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + c.edit("pc"); c.updateDraft(assertNotNull(c.state.value.draft).copy(secureOn = "11:22:33:44:55:66")); c.save(); advanceUntilIdle() + assertEquals(WolMessage.SAVE_FAILED, c.state.value.message) + assertEquals(0, vault.writes, "the other device's password is not silently dropped") + assertFalse(store.data.first { it.id == "pc" }.secureOnRequired) + // Without another protected device the unreadable store may be replaced by the typed password. + val vault2 = Vault(mapOf("x" to SecureOnEntry(password, "x"))).also { it.failLoad = true } + val store2 = Store2(listOf(local, other.copy(secureOnRequired = false))) + val c2 = WolController(store2, wifi, Sender(), this, { 1 }, { "new" }, secureOn = vault2) + advanceUntilIdle() + c2.edit("pc"); c2.updateDraft(assertNotNull(c2.state.value.draft).copy(secureOn = "11:22:33:44:55:66")); c2.save(); advanceUntilIdle() + assertEquals(setOf("pc"), vault2.data.keys) + assertTrue(store2.data.first { it.id == "pc" }.secureOnRequired) + } + + @Test fun persistentFlagBlocksWhenTheEntryVanishesUntilRemovedOnPurpose() = runTest { + val protectedPc = local.copy(secureOnRequired = true) + val vault = Vault(emptyMap()); val sender = Sender(); val store = Store2(listOf(protectedPc)) + val c = WolController(store, wifi, sender, this, { 1 }, { "new" }, secureOn = vault) + advanceUntilIdle() + c.wake("pc"); advanceUntilIdle() + assertTrue(sender.packets.isEmpty()) + assertEquals(SendFailure.SECURE_ON_UNAVAILABLE, c.state.value.outcomes.getValue("pc").reason) + // The editor flags it; saving without a password keeps the protection, removing it on purpose clears it. + c.edit("pc"); assertTrue(assertNotNull(c.state.value.draft).secureOnStale) + c.save(); advanceUntilIdle() + assertTrue(store.data.single().secureOnRequired) + c.edit("pc"); c.updateDraft(assertNotNull(c.state.value.draft).copy(secureOnRemove = true)); c.save(); advanceUntilIdle() + assertFalse(store.data.single().secureOnRequired) + c.wake("pc"); advanceUntilIdle() + assertEquals(102, sender.packets.single().size) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWakeTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWakeTest.kt new file mode 100644 index 0000000..3d30843 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWakeTest.kt @@ -0,0 +1,117 @@ +package cz.netkit.shared.wol + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeoutOrNull +import kotlin.test.Test +import kotlin.test.assertContentEquals +import kotlin.test.assertEquals +import kotlin.test.assertIs +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** WoL use-case (zadání 36 §2.5) over a fake PacketSender; MACs are locally administered test values. */ +@OptIn(ExperimentalCoroutinesApi::class) +class WolWakeTest { + private val handle = object : WifiNetworkHandle {} + private val wifi = WifiNetworkInfo(handle, "192.168.50.23", 24) + private fun device(mode: TargetMode = TargetMode.AUTO_BROADCAST, custom: String? = null, repeat: Int = 3, interval: Int = 250) = + WolDevice("pc", "PC", "02:00:5E:10:00:01", mode, custom, 9, createdAt = 1, updatedAt = 1, repeatCount = repeat, repeatIntervalMs = interval) + private fun provider(info: WifiNetworkInfo?) = object : NetworkInfoProvider { override suspend fun currentWifi() = info } + + private class Sender(private val now: () -> Long) : PacketSender { + val sends = mutableListOf>() + val times = mutableListOf() + var failWith: Exception? = null + override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray) { + failWith?.let { throw it } + sends += Triple(host, port, payload); times += now() + } + } + + @Test fun repeatsWithTheConfiguredIntervalAndPacket() = runTest { + val sender = Sender { currentTime } + val result = sendWolWake(device(repeat = 4, interval = 300), provider(wifi), sender) + val sent = assertIs(result) + assertEquals(4, sent.packets) + assertEquals(listOf(0L, 300L, 600L, 900L), sender.times) + val packet = magicPacket(parseMac("02:00:5E:10:00:01")!!) + sender.sends.forEach { (host, port, bytes) -> assertEquals("192.168.50.255", host); assertEquals(9, port); assertContentEquals(packet, bytes) } + } + + @Test fun broadcastTargetFollowsTheMode() = runTest { + suspend fun hostFor(device: WolDevice, info: WifiNetworkInfo = wifi): String? { + val sender = Sender { currentTime } + sendWolWake(device, provider(info), sender, repeatCount = 1) + return sender.sends.singleOrNull()?.first + } + assertEquals("192.168.50.255", hostFor(device(TargetMode.AUTO_BROADCAST))) + assertEquals("10.20.0.255", hostFor(device(TargetMode.AUTO_BROADCAST), WifiNetworkInfo(handle, "10.20.0.7", 24))) + assertEquals("255.255.255.255", hostFor(device(TargetMode.LIMITED_BROADCAST))) + assertEquals("192.0.2.9", hostFor(device(TargetMode.CUSTOM, "192.0.2.9"))) + assertEquals("pc.home.arpa", hostFor(device(TargetMode.CUSTOM, "pc.home.arpa"))) + // /31, /32 or no IPv4 → no directed broadcast, nothing sent. + val noBroadcast = Sender { currentTime } + assertEquals(WolWakeResult.Failed(SendFailure.NO_BROADCAST), + sendWolWake(device(), provider(WifiNetworkInfo(handle, "192.168.50.23", 32)), noBroadcast)) + assertEquals(WolWakeResult.Failed(SendFailure.NO_BROADCAST), + sendWolWake(device(), provider(WifiNetworkInfo(handle, null, null)), noBroadcast)) + assertTrue(noBroadcast.sends.isEmpty()) + } + + @Test fun noWifiSendsNothing() = runTest { + val sender = Sender { currentTime } + var hook = false + assertEquals(WolWakeResult.Failed(SendFailure.NO_WIFI), sendWolWake(device(), provider(null), sender, beforeSend = { hook = true })) + assertTrue(sender.sends.isEmpty()) + assertTrue(!hook, "the pre-send hook runs only with a Wi-Fi network") + } + + @Test fun sendErrorsMapToReasons() = runTest { + val dns = Sender { currentTime }.apply { failWith = PacketSendException(SendFailure.DNS) } + assertEquals(WolWakeResult.Failed(SendFailure.DNS), sendWolWake(device(TargetMode.CUSTOM, "pc.home.arpa"), provider(wifi), dns)) + val io = Sender { currentTime }.apply { failWith = IllegalStateException("socket") } + assertEquals(WolWakeResult.Failed(SendFailure.IO), sendWolWake(device(), provider(wifi), io)) + val hookFailure = sendWolWake(device(), provider(wifi), Sender { currentTime }, beforeSend = { error("probe") }) + assertEquals(WolWakeResult.Failed(SendFailure.IO), hookFailure) + } + + @Test fun callerTimeoutCancelsRemainingRepeats() = runTest { + val sender = Sender { currentTime } + val result = withTimeoutOrNull(450) { sendWolWake(device(repeat = 10, interval = 200), provider(wifi), sender) } + assertNull(result, "timeout propagates as cancellation, not as a failure result") + assertEquals(3, sender.sends.size) + } + + @Test fun seriesStopsWhenTheCallerSaysSo() = runTest { + val sender = Sender { currentTime } + var allowed = 2 + val result = sendWolWake(device(repeat = 5), provider(wifi), sender, shouldContinue = { allowed-- > 0 }) + assertEquals(WolWakeResult.Failed(SendFailure.CANCELLED), result) + assertEquals(2, sender.sends.size) + } + + @Test fun widgetRepeatCountFitsTheReceiverBudget() { + assertEquals(3, wolWidgetRepeatCount(device(repeat = 3, interval = 250))) + assertEquals(10, wolWidgetRepeatCount(device(repeat = 10, interval = 250))) + assertEquals(3, wolWidgetRepeatCount(device(repeat = 10, interval = 2000)), "1 + 4000/2000") + assertEquals(1, wolWidgetRepeatCount(device(repeat = 1, interval = 2000))) + // Worst case of the widget: repeats + DNS stay under its own timeout. + val worst = device(repeat = 10, interval = 2000) + assertTrue((wolWidgetRepeatCount(worst) - 1) * worst.repeatIntervalMs <= WOL_WIDGET_REPEAT_SPAN_MS) + assertTrue(WOL_WIDGET_TIMEOUT_MS < 10_000) + } + + @Test fun widgetDeadlineCountsFromTheTap() { + assertEquals(WOL_WIDGET_TIMEOUT_MS - WOL_WIDGET_WRITE_RESERVE_MS, wolWidgetSendBudget(0)) + // Slow store read: less time for the send, the write reserve stays. + assertEquals(WOL_WIDGET_TIMEOUT_MS - WOL_WIDGET_WRITE_RESERVE_MS - 3_000, wolWidgetSendBudget(3_000)) + assertEquals(0, wolWidgetSendBudget(WOL_WIDGET_TIMEOUT_MS - WOL_WIDGET_WRITE_RESERVE_MS)) + assertEquals(0, wolWidgetSendBudget(60_000)) + assertEquals(WOL_WIDGET_WRITE_RESERVE_MS, wolWidgetRemaining(WOL_WIDGET_TIMEOUT_MS - WOL_WIDGET_WRITE_RESERVE_MS)) + assertEquals(0, wolWidgetRemaining(9_000)) + // The longest allowed repeat span plus a DNS lookup fits the send budget. + assertTrue(WOL_WIDGET_REPEAT_SPAN_MS < wolWidgetSendBudget(0)) + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetModelTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetModelTest.kt new file mode 100644 index 0000000..7be4e2d --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetModelTest.kt @@ -0,0 +1,180 @@ +package cz.netkit.shared.wol + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +/** Content of the WoL widget (zadání 36 AC-004) and its transactions (revize kolo 1 a 2). */ +class WolWidgetModelTest { + private val handle = object : WifiNetworkHandle {} + private val pc = WolDevice("pc", "Pracovní PC", "02:00:5E:10:00:01", TargetMode.AUTO_BROADCAST, createdAt = 1, updatedAt = 1) + private val key = wolDeviceKey(pc) + + /** The tap the widget draws for [state]. */ + private fun tapOf(state: WolWidgetState, now: Long = 0) = requireNotNull(wolWidgetView(state, now).tap) + + @Test fun selectedDeviceIsReadyToWake() { + val state = configuredWolWidgetState(pc) + assertEquals(WolWidgetState("pc", key, "Pracovní PC", WolWidgetStatus.READY, revision = 1, bindingKey = wolDeviceBindingKey(pc)), state) + val view = wolWidgetView(state, 1_000) + assertEquals("Pracovní PC", view.title) + assertEquals(WolWidgetTap(key, 1), view.tap) + assertTrue(view.wakeEnabled); assertTrue(view.opensDevice); assertFalse(view.error); assertFalse(view.showTime) + // The widget state never holds the MAC or the target (only opaque keys). + assertFalse(state.toString().contains(pc.mac)) + pc.customTarget?.let { assertFalse(state.toString().contains(it)) } + assertFalse(state.toString().contains("5E:10")) + } + + @Test fun deviceKeyIsOpaqueAndChangesWithIdentity() { + assertEquals(16, key.length) + assertTrue(key.all { it in '0'..'9' || it in 'a'..'f' }) + assertEquals(key, wolDeviceKey(pc.copy(name = "Renamed", note = "x", port = 7)), "rename keeps the key") + assertEquals(key, wolDeviceKey(pc.copy(mac = "02-00-5e-10-00-01")), "MAC notation does not matter") + assertNotEquals(key, wolDeviceKey(pc.copy(mac = "02:00:5E:10:00:02")), "other MAC") + assertNotEquals(key, wolDeviceKey(pc.copy(createdAt = 2)), "recreated device") + assertNotEquals(key, wolDeviceKey(pc.copy(id = "pc2"))) + assertEquals(pc, wolDeviceByKey(listOf(pc.copy(id = "x", createdAt = 9), pc), key)) + // An imported ID that looks like a host never shows up in the key. + assertFalse(wolDeviceKey(pc.copy(id = "192.168.1.10")).contains("192.168")) + } + + @Test fun ambiguousKeysAreRefused() { + val other = pc.copy(id = "nas") + // Forced collision through the key function: neither device is chosen. + assertEquals(emptyMap(), uniqueWolDevicesByKey(listOf(pc, other)) { "same" }) + assertEquals(setOf(key, wolDeviceKey(other)), uniqueWolDevicesByKey(listOf(pc, other)).keys) + assertNull(wolDeviceByKey(listOf(pc, pc), key), "duplicate entry → ambiguous") + } + + @Test fun sentShowsTimeAndAllowsAnotherWake() { + val ready = configuredWolWidgetState(pc) + val sending = reserveWolWidgetWake(ready, tapOf(ready), 5_000, "t1") + assertEquals(2, sending.revision) + val sent = completeWolWidgetWake(sending, "t1", "pc", key, + wolWidgetStatus(WolWakeResult.Sent(WifiNetworkInfo(handle, "192.168.1.2", 24), "192.168.1.255", 3)), 5_500) + assertEquals(WolWidgetStatus.SENT, sent.status); assertNull(sent.sendToken) + val view = wolWidgetView(sent, 6_000) + assertTrue(view.showTime); assertTrue(view.wakeEnabled); assertFalse(view.error) + // The redrawn button carries the new revision and is accepted right away (no cooldown needed). + assertEquals("t2", reserveWolWidgetWake(sent, tapOf(sent), 5_600, "t2").sendToken) + } + + @Test fun noWifiAndFailuresAreErrors() { + assertEquals(WolWidgetStatus.NO_WIFI, wolWidgetStatus(WolWakeResult.Failed(SendFailure.NO_WIFI))) + assertEquals(WolWidgetStatus.NO_BROADCAST, wolWidgetStatus(WolWakeResult.Failed(SendFailure.NO_BROADCAST))) + assertEquals(WolWidgetStatus.FAILED, wolWidgetStatus(WolWakeResult.Failed(SendFailure.DNS))) + assertEquals(WolWidgetStatus.FAILED, wolWidgetStatus(null), "caller timeout") + val view = wolWidgetView(configuredWolWidgetState(pc).copy(status = WolWidgetStatus.NO_WIFI, atMillis = 5), 10) + assertTrue(view.error); assertTrue(view.wakeEnabled); assertFalse(view.showTime); assertEquals("Pracovní PC", view.title) + } + + @Test fun deletedDeviceDisablesWakeAndNeverSwitchesDevice() { + val other = pc.copy(id = "nas", name = "NAS") + val ready = configuredWolWidgetState(pc) + val deleted = syncWolWidgetState(ready, listOf(other)) + assertEquals(WolWidgetStatus.DELETED, deleted.status) + assertEquals("pc", deleted.deviceId) + val view = wolWidgetView(deleted, 0) + assertFalse(view.wakeEnabled); assertFalse(view.opensDevice); assertTrue(view.error); assertNull(view.tap) + assertSame(deleted, reserveWolWidgetWake(deleted, tapOf(ready), 0, "t")) + // The very same device restored (same ID, MAC, creation time) → ready again. + assertEquals(WolWidgetStatus.READY, syncWolWidgetState(deleted, listOf(pc)).status) + } + + @Test fun reusedIdOfAnotherDeviceDoesNotRebind() { + // CSV import after deletion: same `webb-…` ID, another MAC and creation time. + val deleted = syncWolWidgetState(configuredWolWidgetState(pc), emptyList()) + val impostor = pc.copy(mac = "02:00:5E:99:99:99", createdAt = 500) + assertEquals(WolWidgetStatus.DELETED, syncWolWidgetState(deleted, listOf(impostor)).status) + assertNull(boundWolDevice(deleted, listOf(impostor))) + // Even without the intermediate deletion the replaced device is rejected. + assertEquals(WolWidgetStatus.DELETED, syncWolWidgetState(configuredWolWidgetState(pc), listOf(impostor)).status) + } + + @Test fun renameFollowsTheDevice() { + val renamed = syncWolWidgetState(configuredWolWidgetState(pc).copy(status = WolWidgetStatus.SENT, atMillis = 7), listOf(pc.copy(name = "PC v pracovně"))) + assertEquals("PC v pracovně", renamed.name) + assertEquals(WolWidgetStatus.SENT, renamed.status) + val long = syncWolWidgetState(configuredWolWidgetState(pc), listOf(pc.copy(name = "x".repeat(100)))) + assertEquals(WOL_WIDGET_NAME_MAX, long.name?.length) + } + + @Test fun unconfiguredOrLegacyWidgetCannotWake() { + val view = wolWidgetView(WolWidgetState(), 0) + assertNull(view.title); assertFalse(view.wakeEnabled); assertFalse(view.opensDevice); assertNull(view.tap) + assertEquals(WolWidgetState(), syncWolWidgetState(WolWidgetState(), listOf(pc))) + // State written before device keys existed: choose again. + val legacy = WolWidgetState("pc", null, "Pracovní PC", WolWidgetStatus.READY) + assertEquals(WolWidgetStatus.DELETED, wolWidgetView(legacy, 0).status) + assertFalse(canStartWolWidgetWake(legacy, 0)) + assertEquals(WolWidgetStatus.DELETED, syncWolWidgetState(legacy, listOf(pc)).status) + } + + @Test fun twoCallbacksOfOneDrawingReserveOnlyOnce() { + val ready = configuredWolWidgetState(pc) + val tap = tapOf(ready) + val first = reserveWolWidgetWake(ready, tap, 1_000, "a") + assertEquals("a", first.sendToken); assertEquals(WolWidgetStatus.SENDING, first.status) + // Running send: refused. + assertSame(first, reserveWolWidgetWake(first, tap, 1_050, "b")) + // Android delivered the second callback only after the first send finished: still refused, + // because it was drawn with the old revision. + val sent = completeWolWidgetWake(first, "a", "pc", key, WolWidgetStatus.SENT, 1_500) + assertSame(sent, reserveWolWidgetWake(sent, tap, 1_515, "b")) + // The button redrawn while SENDING (PendingIntent extras updated) is refused after the result too. + assertSame(sent, reserveWolWidgetWake(sent, tapOf(first, 1_100), 1_515, "c")) + assertEquals("d", reserveWolWidgetWake(sent, tapOf(sent, 1_600), 1_600, "d").sendToken) + assertFalse(wolWidgetView(first, 2_000).wakeEnabled) + } + + @Test fun tapDrawnForAnotherDeviceIsRefused() { + val ready = configuredWolWidgetState(pc) + val tapForPc = tapOf(ready) + // The user chose NAS before the PC button's callback was processed. + val nas = configuredWolWidgetState(pc.copy(id = "nas", name = "NAS", mac = "02:00:5E:10:00:09"), ready) + assertEquals(2, nas.revision) + assertSame(nas, reserveWolWidgetWake(nas, tapForPc, 1_000, "a")) + // Same revision but another key (e.g. forged parameters) is refused as well. + assertSame(nas, reserveWolWidgetWake(nas, WolWidgetTap(key, nas.revision), 1_000, "a")) + assertEquals("a", reserveWolWidgetWake(nas, tapOf(nas), 1_000, "a").sendToken) + } + + @Test fun resultMergesIntoCurrentStateOnlyForItsToken() { + val ready = configuredWolWidgetState(pc) + val sending = reserveWolWidgetWake(ready, tapOf(ready), 1_000, "a") + // Renamed during the send: the result keeps the new name. + val renamed = syncWolWidgetState(sending, listOf(pc.copy(name = "Nové"))) + val done = completeWolWidgetWake(renamed, "a", "pc", key, WolWidgetStatus.SENT, 1_500) + assertEquals("Nové", done.name); assertEquals(WolWidgetStatus.SENT, done.status) + // Reconfigured A → B during the send: the old send must not bind the widget back to A. + val reconfigured = configuredWolWidgetState(pc.copy(id = "nas", name = "NAS", mac = "02:00:5E:10:00:09"), sending) + assertNull(reconfigured.sendToken) + assertSame(reconfigured, completeWolWidgetWake(reconfigured, "a", "pc", key, WolWidgetStatus.SENT, 1_500)) + // Deleted during the send: the reservation is dropped, the result is ignored. + val deleted = syncWolWidgetState(sending, emptyList()) + assertNull(deleted.sendToken) + assertSame(deleted, completeWolWidgetWake(deleted, "a", "pc", key, WolWidgetStatus.SENT, 1_500)) + // A foreign token never completes. + assertSame(sending, completeWolWidgetWake(sending, "x", "pc", key, WolWidgetStatus.SENT, 1_500)) + } + + @Test fun staleReservationRecoversAndOldSendCannotWrite() { + val ready = configuredWolWidgetState(pc) + val sending = reserveWolWidgetWake(ready, tapOf(ready), 1_000, "a") + assertFalse(canStartWolWidgetWake(sending, 2_000)) + // Process died during the send: after the stale limit the redrawn button may reserve again. + val later = 1_000 + WOL_WIDGET_STALE_SENDING_MS + assertTrue(canStartWolWidgetWake(sending, later)) + assertEquals(WolWidgetStatus.FAILED, wolWidgetView(sending, later).status) + assertTrue(wolWidgetView(sending, later).wakeEnabled) + val again = reserveWolWidgetWake(sending, tapOf(sending, later), later, "b") + assertEquals("b", again.sendToken) + assertSame(again, completeWolWidgetWake(again, "a", "pc", key, WolWidgetStatus.SENT, later + 1)) + assertTrue(canStartWolWidgetWake(sending, 0), "clock moved back") + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetRunTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetRunTest.kt new file mode 100644 index 0000000..3306622 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetRunTest.kt @@ -0,0 +1,239 @@ +package cz.netkit.shared.wol + +import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * One widget tap end to end over fakes and virtual time (revize kolo 2): drawn identity, reservation + * loss during the series, double callbacks and the shared 8 s deadline. Test MACs are locally administered. + */ +@OptIn(ExperimentalCoroutinesApi::class) +class WolWidgetRunTest { + private val handle = object : WifiNetworkHandle {} + private val pcA = WolDevice("a", "PC A", "02:00:5E:10:00:0A", TargetMode.CUSTOM, "192.0.2.10", 9, createdAt = 1, updatedAt = 1) + private val pcB = WolDevice("b", "PC B", "02:00:5E:10:00:0B", TargetMode.CUSTOM, "192.0.2.11", 9, createdAt = 2, updatedAt = 2) + + private class Store(var state: WolWidgetState, var transactDelay: Long = 0) : WolWidgetStore { + private val mutex = Mutex() + var writes = 0 + override suspend fun transact(change: (WolWidgetState) -> WolWidgetState): WolWidgetState = mutex.withLock { + delay(transactDelay) + change(state).also { if (it != state) writes++; state = it } + } + override suspend fun read() = mutex.withLock { state } + } + + /** + * Guarded sender like the Android transport: [onPacket] stands for the DNS lookup of the packet with + * that index, [onBind] for the socket setup; then the guard performs the "socket write" that records + * the packet. + */ + private class Sender(val onPacket: suspend (Int) -> Unit = {}, val onBind: suspend (Int) -> Unit = {}) : GuardedPacketSender { + val packets = mutableListOf>() + val events = mutableListOf() + private var attempts = 0 + override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray) { + sendUdp(network, host, port, payload) { write -> write(); true } + } + override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray, + guard: PacketWriteGuard): Boolean { + val index = attempts++ + onPacket(index) + onBind(index) + return guard { + events += "write" + packets += host to payload.copyOfRange(6, 12).joinToString(":") { (it.toInt() and 255).toString(16).padStart(2, '0') } + } + } + } + + private val wifi = object : NetworkInfoProvider { override suspend fun currentWifi() = WifiNetworkInfo(handle, "192.0.2.2", 24) } + + private suspend fun TestScope.tap(store: Store, tap: WolWidgetTap, sender: Sender, reservation: String = "t", + load: suspend () -> List? = { listOf(pcA, pcB) }, redraws: MutableList = mutableListOf()): WolWidgetRunOutcome { + val start = currentTime + return runWolWidgetWake(tap, reservation, store, load, wifi, sender, { 1_000_000 + currentTime }, { currentTime - start }, + redraw = { redraws += currentTime - start }) + } + + private fun drawn(state: WolWidgetState) = requireNotNull(wolWidgetView(state, 1_000_000).tap) + + @Test fun normalTapSendsTheSeriesAndWritesSent() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val sender = Sender() + assertEquals(WolWidgetRunOutcome.FINISHED, tap(store, drawn(store.state), sender)) + assertEquals(List(3) { "192.0.2.10" to "02:00:5e:10:00:0a" }, sender.packets) + assertEquals(WolWidgetStatus.SENT, store.state.status) + assertNull(store.state.sendToken) + } + + @Test fun choiceChangedBeforeReservationSendsNothing() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val drawnForA = drawn(store.state) + store.state = configuredWolWidgetState(pcB, store.state) // user picked B before the callback ran + val sender = Sender() + val redraws = mutableListOf() + assertEquals(WolWidgetRunOutcome.REFUSED, tap(store, drawnForA, sender, redraws = redraws)) + assertTrue(sender.packets.isEmpty(), "no packet for A, none for B") + assertEquals(1, redraws.size, "a refused tap redraws the current state") + assertEquals("b", store.state.deviceId); assertEquals(WolWidgetStatus.READY, store.state.status) + } + + @Test fun choiceChangedDuringTheSeriesStopsIt() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val sender = Sender { index -> if (index == 1) store.transact { configuredWolWidgetState(pcB, it) } } + assertEquals(WolWidgetRunOutcome.LOST_RESERVATION, tap(store, drawn(store.state), sender)) + // The first packet went out before the change; the change happened during the second packet's + // DNS lookup, so its write is skipped: exactly one packet, nothing for B. + assertEquals(listOf("192.0.2.10" to "02:00:5e:10:00:0a"), sender.packets) + assertEquals("b", store.state.deviceId); assertEquals(WolWidgetStatus.READY, store.state.status, "B is not overwritten") + } + + @Test fun choiceChangedDuringTheFirstDnsLookupWritesNothing() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + // Slow DNS of the very first packet; meanwhile the user picks B. + val sender = Sender { index -> if (index == 0) { delay(800); store.transact { configuredWolWidgetState(pcB, it) } } } + assertEquals(WolWidgetRunOutcome.LOST_RESERVATION, tap(store, drawn(store.state), sender)) + assertTrue(sender.packets.isEmpty(), "packets: ${sender.packets}") + assertEquals("b", store.state.deviceId); assertEquals(WolWidgetStatus.READY, store.state.status) + } + + @Test fun choiceChangedDuringSocketBindWritesNothing() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val sender = Sender(onBind = { index -> if (index == 0) store.transact { configuredWolWidgetState(pcB, it) } }) + assertEquals(WolWidgetRunOutcome.LOST_RESERVATION, tap(store, drawn(store.state), sender)) + assertTrue(sender.packets.isEmpty(), "packets: ${sender.packets}") + assertEquals("b", store.state.deviceId) + } + + @Test fun bindingChangeWaitsForTheGuardedWrite() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + lateinit var sender: Sender + sender = Sender(onBind = { index -> + // A new choice is requested while the first write is about to happen; it must run either + // completely before the write (then no write) or after it, never in between. + if (index == 0) launch { store.transact { configuredWolWidgetState(pcB, it) }; sender.events += "rebind" } + }) + tap(store, drawn(store.state), sender) + val rebind = sender.events.indexOf("rebind") + assertTrue(rebind >= 0, "events: ${sender.events}") + assertTrue(sender.events.take(rebind).all { it == "write" } && sender.events.drop(rebind + 1).none { it == "write" }, + "no write after the new choice: ${sender.events}") + assertTrue(sender.packets.size <= 1) + } + + @Test fun choiceChangedAfterReservationBeforeSendingSendsNothing() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val sender = Sender() + val outcome = tap(store, drawn(store.state), sender, load = { + store.transact { configuredWolWidgetState(pcB, it) } + listOf(pcA, pcB) + }) + assertEquals(WolWidgetRunOutcome.LOST_RESERVATION, outcome) + assertTrue(sender.packets.isEmpty()) + assertEquals("b", store.state.deviceId); assertEquals(WolWidgetStatus.READY, store.state.status) + } + + @Test fun secondCallbackOfTheSameDrawingSendsNothing() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val drawnOnce = drawn(store.state) + val sender = Sender() + assertEquals(WolWidgetRunOutcome.FINISHED, tap(store, drawnOnce, sender, reservation = "first")) + assertEquals(WolWidgetRunOutcome.REFUSED, tap(store, drawnOnce, sender, reservation = "second")) + assertEquals(3, sender.packets.size) + // The redrawn button works again. + assertEquals(WolWidgetRunOutcome.FINISHED, tap(store, drawn(store.state), sender, reservation = "third")) + assertEquals(6, sender.packets.size) + } + + @Test fun tapDrawnDuringTheSendIsRefusedAfterIt() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val sender = Sender() + var drawnWhileSending: WolWidgetTap? = null + // The SENDING redraw updates the button's action; a tap sent then is delivered after the series. + val start = currentTime + runWolWidgetWake(drawn(store.state), "first", store, { listOf(pcA, pcB) }, wifi, sender, { 1_000_000 + currentTime }, + { currentTime - start }, redraw = { if (drawnWhileSending == null) drawnWhileSending = drawn(store.read()) }) + assertEquals(WolWidgetRunOutcome.REFUSED, tap(store, requireNotNull(drawnWhileSending), sender, reservation = "second")) + assertEquals(3, sender.packets.size) + } + + @Test fun deletedDeviceIsReportedWithoutSending() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val sender = Sender() + assertEquals(WolWidgetRunOutcome.DEVICE_GONE, tap(store, drawn(store.state), sender, load = { listOf(pcB) })) + assertTrue(sender.packets.isEmpty()) + assertEquals(WolWidgetStatus.DELETED, store.state.status) + } + + @Test fun slowStepsShareOneDeadlineAndTheResultIsStillWritten() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val sender = Sender() + val start = currentTime + // Loading devices eats almost the whole send budget: no time left to send. + tap(store, drawn(store.state), sender, load = { delay(WOL_WIDGET_TIMEOUT_MS - WOL_WIDGET_WRITE_RESERVE_MS - 10); listOf(pcA) }) + assertTrue(currentTime - start <= WOL_WIDGET_TIMEOUT_MS, "took ${currentTime - start} ms") + assertTrue(sender.packets.size < 3) + assertEquals(WolWidgetStatus.FAILED, store.state.status, "result written within the reserve") + assertNull(store.state.sendToken) + } + + @Test fun hangingStoreNeverExceedsTheDeadline() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val sender = Sender() + val start = currentTime + val redraws = mutableListOf() + // After the reservation every transaction hangs: the final write gets only the real remaining time. + tap(store, drawn(store.state), sender, load = { store.transactDelay = 60_000; listOf(pcA) }, redraws = redraws) + assertTrue(currentTime - start <= WOL_WIDGET_TIMEOUT_MS, "took ${currentTime - start} ms") + // Each write needs the store transaction that confirms the reservation: a hanging store sends nothing. + assertEquals(0, sender.packets.size) + // The write did not finish, so there was no final redraw; the reservation expires on its own. + assertTrue(redraws.all { it <= WOL_WIDGET_TIMEOUT_MS }) + assertEquals(WolWidgetStatus.SENDING, store.state.status) + } + + @Test fun sendTimeoutLeavesTheReserveForTheResult() = runTest { + val store = Store(configuredWolWidgetState(pcA)) + val sender = Sender() + val start = currentTime + val redraws = mutableListOf() + // The send itself runs into the send budget (DNS never answers), leaving exactly the reserve. + val slow = object : PacketSender { + override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray) = delay(60_000) + } + runWolWidgetWake(drawn(store.state), "t", store, { listOf(pcA) }, wifi, slow, { 1_000_000 + currentTime }, + { currentTime - start }, redraw = { redraws += currentTime - start }) + assertTrue(currentTime - start <= WOL_WIDGET_TIMEOUT_MS) + assertEquals(WolWidgetStatus.FAILED, store.state.status, "timeout of the send is a failure") + assertTrue(sender.packets.isEmpty()) + } + + @Test fun eachDrawingHasItsOwnIntentData() { + val a = WolWidgetTap(wolDeviceKey(pcA), 3) + val b = WolWidgetTap(wolDeviceKey(pcB), 4) + val dataA = wolWidgetWakeData(7, a) + // Another device, revision or widget → another URI → another PendingIntent (no shared extras). + assertTrue(setOf(dataA, wolWidgetWakeData(7, b), wolWidgetWakeData(7, a.copy(revision = 4)), wolWidgetWakeData(8, a)).size == 4) + assertEquals(7 to a, parseWolWidgetWakeData(dataA)) + listOf(null, "", "$dataA/x", dataA.uppercase(), "netkit-wol-widget://wake/7/${a.deviceKey}", "netkit-wol-widget://wake/-1/${a.deviceKey}/3", + "netkit-wol-widget://wake/7/192.168.1.10/3", "http://wake/7/${a.deviceKey}/3", "netkit-wol-widget://wake/9999999999/${a.deviceKey}/3", + "netkit-wol-widget://wake/2147483648/${a.deviceKey}/3", "netkit-wol-widget://wake/7/${a.deviceKey}/9223372036854775808", + "netkit-wol-widget://wake/12345678901/${a.deviceKey}/3") + .forEach { assertNull(parseWolWidgetWakeData(it), "accepted: $it") } + // Edge values the generator produces round-trip (widget ID 1 000 000 000 and more, any Long revision). + for (tap in listOf(7 to a, 1_000_000_000 to a, Int.MAX_VALUE to a.copy(revision = Long.MAX_VALUE), 0 to a.copy(revision = 0))) { + assertEquals(tap, parseWolWidgetWakeData(wolWidgetWakeData(tap.first, tap.second))) + } + } +} diff --git a/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetSecureOnTest.kt b/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetSecureOnTest.kt new file mode 100644 index 0000000..27e72f3 --- /dev/null +++ b/shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetSecureOnTest.kt @@ -0,0 +1,118 @@ +package cz.netkit.shared.wol + +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.currentTime +import kotlinx.coroutines.test.runTest +import kotlin.test.* + +/** SecureOn in the widget path and in the shared `sendWolWake` (zadání 39 po sloučení 36): bound password or nothing. */ +class WolWidgetSecureOnTest { + private val handle = object : WifiNetworkHandle {} + private val pc = WolDevice("a", "PC A", "02:00:5E:10:00:0A", TargetMode.CUSTOM, "192.0.2.10", 9, createdAt = 1, updatedAt = 1, repeatCount = 2) + private val password = byteArrayOf(0x11, 0x22, 0x33, 0x44, 0x55, 0x66) + private val wifi = object : NetworkInfoProvider { override suspend fun currentWifi() = WifiNetworkInfo(handle, "192.0.2.2", 24) } + + private class Store(var state: WolWidgetState) : WolWidgetStore { + override suspend fun transact(change: (WolWidgetState) -> WolWidgetState) = change(state).also { state = it } + override suspend fun read() = state + } + private class Sender : PacketSender { + val packets = mutableListOf() + override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray) { packets += payload } + } + private class Vault(var data: Map, var fail: Boolean = false) : WolSecureOnStore { + override suspend fun load(): Map { check(!fail); return data } + override suspend fun save(entries: Map) { data = entries } + } + + private suspend fun TestScope.widgetTap(vault: WolSecureOnStore?, device: WolDevice = pc): Pair { + val store = Store(configuredWolWidgetState(device)) + val sender = Sender() + val start = currentTime + runWolWidgetWake(requireNotNull(wolWidgetView(store.state, 1_000_000).tap), "t", store, { listOf(device) }, wifi, sender, + { 1_000_000 + currentTime }, { currentTime - start }, redraw = {}, + secureOnPassword = { secureOnPasswordForSend(it, vault) }) + return store to sender + } + + @Test fun widgetSendsTheBoundPasswordIn108Bytes() = runTest { + val (store, sender) = widgetTap(Vault(mapOf("a" to SecureOnEntry(password, secureOnBinding(pc))))) + assertEquals(WolWidgetStatus.SENT, store.state.status) + assertEquals(listOf(108, 108), sender.packets.map { it.size }) + assertContentEquals(password, sender.packets.first().copyOfRange(102, 108)) + } + + @Test fun widgetWithoutAPasswordStillSendsPlain() = runTest { + val (store, sender) = widgetTap(Vault(emptyMap())) + assertEquals(WolWidgetStatus.SENT, store.state.status) + assertEquals(listOf(102, 102), sender.packets.map { it.size }) + assertEquals(listOf(102, 102), widgetTap(null).second.packets.map { it.size }) + } + + @Test fun widgetWithAnUnusablePasswordSendsNothing() = runTest { + val protectedPc = pc.copy(secureOnRequired = true) + val vaults = listOf( + // Bound to another MAC/target (e.g. left over from an import). + Vault(mapOf("a" to SecureOnEntry(password, secureOnBinding(pc.copy(customTarget = "192.0.2.99"))))), + // Unreadable store. + Vault(mapOf("a" to SecureOnEntry(password, secureOnBinding(protectedPc))), fail = true), + // Revize 39/4: a readable store from which the protected device's entry vanished. + Vault(emptyMap()), + ) + for (vault in vaults) { + val (store, sender) = widgetTap(vault, protectedPc) + assertTrue(sender.packets.isEmpty(), "no packet without the bound password") + assertEquals(WolWidgetStatus.SECURE_ON_UNAVAILABLE, store.state.status) + assertTrue(wolWidgetView(store.state, 1_000_000).error, "shown as an error") + assertNull(store.state.sendToken) + } + // No store at all (platform without SecureOn) blocks a protected device too. + assertTrue(widgetTap(null, protectedPc).second.packets.isEmpty()) + // An unreadable store does not block a device that never required a password. + assertEquals(listOf(102, 102), widgetTap(Vault(emptyMap(), fail = true)).second.packets.map { it.size }) + } + + /** Guarded sender: [beforeWrite] runs after the 108 B packet was built and the socket prepared, before the guarded write. */ + private class GuardedSender(val beforeWrite: suspend (Int) -> Unit) : GuardedPacketSender { + val packets = mutableListOf() + private var index = 0 + override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray) { + sendUdp(network, host, port, payload) { write -> write(); true } + } + override suspend fun sendUdp(network: WifiNetworkHandle, host: String, port: Int, payload: ByteArray, guard: PacketWriteGuard): Boolean { + beforeWrite(index++) + return guard { packets += payload } + } + } + + @Test fun targetChangedDuringTheSeriesStopsTheNextWrite() = runTest { + val protectedPc = pc.copy(secureOnRequired = true, repeatCount = 3) + val vault = Vault(mapOf("a" to SecureOnEntry(password, secureOnBinding(protectedPc)))) + for (changeBefore in listOf(0, 1)) { + val store = Store(configuredWolWidgetState(protectedPc)) + val moved = protectedPc.copy(customTarget = "192.0.2.77") + // The app saves a new target and syncs the widget while the packet is being prepared. + val sender = GuardedSender { index -> if (index == changeBefore) store.transact { syncWolWidgetState(it, listOf(moved)) } } + val start = currentTime + val outcome = runWolWidgetWake(requireNotNull(wolWidgetView(store.state, 1_000_000).tap), "t", store, { listOf(protectedPc) }, wifi, + sender, { 1_000_000 + currentTime }, { currentTime - start }, redraw = {}, secureOnPassword = { secureOnPasswordForSend(it, vault) }) + assertEquals(WolWidgetRunOutcome.LOST_RESERVATION, outcome) + assertEquals(changeBefore, sender.packets.size, "the guard refused the write after the change") + assertTrue(sender.packets.all { it.size == 108 }) + assertNull(store.state.sendToken) + assertEquals(wolDeviceBindingKey(moved), store.state.bindingKey) + assertEquals(WolWidgetStatus.READY, store.state.status) + } + } + + @Test fun sharedSendUseCaseFailsClosedBeforeAnyPacket() = runTest { + val sender = Sender() + val result = sendWolWake(pc, wifi, sender, secureOn = { throw PacketSendException(SendFailure.SECURE_ON_UNAVAILABLE) }) + assertEquals(WolWakeResult.Failed(SendFailure.SECURE_ON_UNAVAILABLE), result) + assertTrue(sender.packets.isEmpty()) + assertEquals(WolWidgetStatus.SECURE_ON_UNAVAILABLE, wolWidgetStatus(result)) + // An expected password that vanished blocks too; the app passes expectProtected for its known IDs. + assertFailsWith { secureOnPasswordForSend(pc, Vault(emptyMap()), expectProtected = true) } + assertNull(secureOnPasswordForSend(pc, Vault(emptyMap(), fail = true), protectedOnFailure = false)) + } +} diff --git a/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt index 1c85d5a..a7d1fab 100644 --- a/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt +++ b/shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt @@ -127,7 +127,8 @@ class IosSshDomain { } fun planImport(current: SshData, imported: SshProfileImport, keyRef: String?, generateId: () -> String): IosSshPlanResult = try { - IosSshPlanResult(planSshProfileImport(current, imported, keyRef, generateId), null) + // The iOS transport connects only to the target: ProxyJump rows are skipped, never connected directly. + IosSshPlanResult(planSshProfileImport(current, imported, keyRef, supportsProxyJump = false, generateId = generateId), null) } catch (error: SshProfileImportException) { IosSshPlanResult(null, importFailure(error.reason)) } /** Stable categories only: never expose parser messages or document values to Swift UI. */ diff --git a/tools/m1_provision.py b/tools/m1_provision.py index cee1d74..a59a6c2 100644 --- a/tools/m1_provision.py +++ b/tools/m1_provision.py @@ -39,6 +39,17 @@ def fixture_evidence(phase: str, log: str) -> tuple[bool, list[str]]: 'ssh-reconnect': ['AUTH_OK:PASSWORD', 'SSH_SESSION_CLOSED', 'SSH_INPUT_BYTES:', 'SSH_COMMAND_OK'], 'ssh-legacy': ['SSH_SESSION_CLOSED'], 'ssh-rotated': ['SSH_SESSION_CLOSED'], + 'ssh-forward': ['SSH_DIRECT_TCPIP:18084', 'SSH_DIRECT_TCPIP:22223', 'SSH_DIRECT_TCPIP_DENIED', 'TCP_ECHO_BYTES:', + 'SSH_COMMAND_OK', 'SSH_SESSION_CLOSED'], + 'ssh-snippet-log': ['AUTH_OK:PASSWORD', 'SSH_COMMAND_OK', 'SSH_SESSION_CLOSED'], + 'ssh-background': ['AUTH_OK:PASSWORD', 'SSH_COMMAND_OK', 'SSH_SESSION_CLOSED'], + 'ssh-background-denied': ['AUTH_OK:PASSWORD', 'SSH_SESSION_CLOSED'], + 'ssh-sftp': ['AUTH_OK:PASSWORD', 'SFTP_SESSION_STARTED', 'SFTP_LIST', 'SFTP_ESCAPE_DENIED', 'SFTP_DOWNLOAD', + 'SFTP_UPLOAD_BYTES:200000', 'SFTP_HARDLINK', 'SFTP_HARDLINK_EXISTS', 'SFTP_REMOVE', 'SFTP_MKDIR', + 'SFTP_RMDIR', 'SFTP_HANG_READ', 'SSH_SESSION_CLOSED'], + 'ssh-forwards-panel': ['AUTH_OK:PASSWORD', 'SSH_SESSION_CLOSED'], + 'ssh-xterm': ['AUTH_OK:PASSWORD', 'SSH_RESIZE', 'SSH_XTERM_SENT:netkit-xterm-colors', 'SSH_XTERM_SENT:netkit-xterm-alt', + 'SSH_XTERM_SENT:netkit-xterm-main', 'SSH_SESSION_CLOSED'], }.get(phase, []) missing = [marker for marker in required if marker not in log] if phase in ('ssh-legacy', 'ssh-rotated') and 'AUTH_OK:' in log: @@ -46,6 +57,15 @@ def fixture_evidence(phase: str, log: str) -> tuple[bool, list[str]]: return not missing, missing +def notification_permission_commands(phase: str) -> list[list[str]]: + """Zadání 42: POST_NOTIFICATIONS is granted only for ssh-background; every other phase starts denied + and never asked (flags cleared), so the once-only runtime question is reproducible.""" + permission = 'android.permission.POST_NOTIFICATIONS' + action = 'grant' if phase == 'ssh-background' else 'revoke' + return [['shell', 'pm', 'clear-permission-flags', 'cz.netkit.app', permission, 'user-set', 'user-fixed'], + ['shell', 'pm', action, 'cz.netkit.app', permission]] + + class Provisioner: def __init__(self, adb: str, serial: str, state: Path): self.adb = runner_module.validate_adb_path(adb) @@ -143,6 +163,8 @@ def run_all(self, phases: list[str], repeats: int, git_sha: str, expected: str, for permission in ('ACCESS_COARSE_LOCATION', 'ACCESS_FINE_LOCATION'): action = 'revoke' if phase == 'wifi-denied' else 'grant' self.command(['shell', 'pm', action, 'cz.netkit.app', 'android.permission.' + permission]) + for command in notification_permission_commands(phase): + self.command(command) run = runner_module.Runner(adb=self.adb, serial=self.serial, phase=phase, run_id=uuid.uuid4().hex, output_dir=str(self.state / f'{phase}-{attempt}-{uuid.uuid4().hex[:8]}'), git_sha=git_sha, expect_apk_sha256=expected, expect_test_apk_sha256=expected_test) diff --git a/tools/netkit_ssh_export.py b/tools/netkit_ssh_export.py index 6dc5af6..8dd87ec 100644 --- a/tools/netkit_ssh_export.py +++ b/tools/netkit_ssh_export.py @@ -37,6 +37,7 @@ MAX_USERNAME = 128 MAX_INCLUDE_DEPTH = 16 # READCONF_MAX_DEPTH v OpenSSH MAX_PUBKEY_BYTES = 16 * 1024 +MAX_JUMP_HOPS = 3 # SSH_MAX_JUMP_HOPS v aplikaci SSH_G_TIMEOUT = 5.0 COPY_ID_TIMEOUT = 120.0 @@ -90,7 +91,7 @@ def valid_alias(value: str) -> bool: def valid_group(value: str) -> bool: - return 1 <= utf16_len(value) <= MAX_GROUP and value.strip() != "" and not _has_control(value) + return 1 <= utf16_len(value) <= MAX_GROUP and valid_alias(value) def valid_host(value: str) -> bool: @@ -389,12 +390,15 @@ class Profile: host: str port: int username: str + proxy_jump: str | None = None def to_json(self) -> dict[str, object]: item: dict[str, object] = {"alias": self.alias} if self.group is not None: item["group"] = self.group item.update({"host": self.host, "port": self.port, "username": self.username}) + if self.proxy_jump is not None: + item["proxyJump"] = self.proxy_jump return item @@ -419,9 +423,15 @@ def _not_none(value: str | None) -> str | None: return None if value is None or value.lower() == "none" or value == "" else value +def plain_jump_alias(value: str) -> bool: + """ProxyJump, který aplikace umí: jediný alias bez user@, :port a řetězu (a,b).""" + return valid_alias(value) and not any(ch in value for ch in ",@:") and not _has_space(value) + + def build_profile(alias: str, group: str | None, resolved: Resolved, default_user: str | None, - warnings: list[str]) -> Profile | Skipped: - if _not_none(resolved.proxyjump) is not None: + warnings: list[str], map_jump: bool = False) -> Profile | Skipped: + jump = _not_none(resolved.proxyjump) + if jump is not None and (not map_jump or not plain_jump_alias(jump) or jump == alias): return Skipped(alias, REASON_PROXY_JUMP) if _not_none(resolved.proxycommand) is not None: return Skipped(alias, REASON_PROXY_COMMAND) @@ -445,11 +455,37 @@ def build_profile(alias: str, group: str | None, resolved: Resolved, default_use if not valid_username(username): warnings.append(f"{alias}: neplatné uživatelské jméno (1–{MAX_USERNAME} znaků bez mezer).") return Skipped(alias, REASON_UNSUPPORTED) - return Profile(alias, group, host, port, username) + return Profile(alias, group, host, port, username, jump) + + +def resolve_jumps(result: Collection) -> None: + """Profil s ProxyJump zůstane, jen když jump je exportovaný profil a řetěz je bez cyklu a nejvýše 3 skoky.""" + while True: + by_alias = {p.alias: p for p in result.profiles} + broken: list[Profile] = [] + for profile in result.profiles: + seen = {profile.alias} + hops = 0 + current = profile.proxy_jump + while current is not None: + hop = by_alias.get(current) + if hop is None or current in seen or hops == MAX_JUMP_HOPS: + broken.append(profile) + break + seen.add(current) + hops += 1 + current = hop.proxy_jump + if not broken: + return + for profile in broken: + result.profiles.remove(profile) + result.skipped.append(Skipped(profile.alias, REASON_PROXY_JUMP)) + result.warnings.append(f"{profile.alias}: ProxyJump {profile.proxy_jump} není exportovaný profil, " + f"tvoří cyklus nebo řetěz delší než {MAX_JUMP_HOPS} skoky; přeskočeno.") def collect(parsed: ParsedConfig, resolver: Resolver, default_user: str | None, - only: set[str] | None, fallback: bool) -> Collection: + only: set[str] | None, fallback: bool, map_jump: bool = False) -> Collection: result = Collection(warnings=list(parsed.warnings)) seen: set[str] = set() for entry in parsed.hosts: @@ -473,11 +509,13 @@ def collect(parsed: ParsedConfig, resolver: Resolver, default_user: str | None, if isinstance(resolved, str): result.skipped.append(Skipped(alias, resolved)) continue - item = build_profile(alias, entry.group, resolved, default_user, result.warnings) + item = build_profile(alias, entry.group, resolved, default_user, result.warnings, map_jump) if isinstance(item, Profile): result.profiles.append(item) else: result.skipped.append(item) + if map_jump: + resolve_jumps(result) if only is not None: result.unknown_only = sorted(only - seen) return result @@ -674,7 +712,7 @@ def build_parser() -> argparse.ArgumentParser: return parser -def _discover(args: argparse.Namespace, env: Environment) -> tuple[Path, Collection]: +def _discover(args: argparse.Namespace, env: Environment, map_jump: bool = False) -> tuple[Path, Collection]: explicit: Path | None = args.config config = explicit if explicit is not None else env.ssh_dir / "config" parsed = parse_config(config, env.home, env.ssh_dir) @@ -685,7 +723,7 @@ def _discover(args: argparse.Namespace, env: Environment) -> tuple[Path, Collect resolver = fallback_resolver(parsed, warnings) else: resolver = ssh_g_resolver(env.ssh_runner, explicit, warnings) - collection = collect(parsed, resolver, args.default_user, args.only, env.ssh_runner is None) + collection = collect(parsed, resolver, args.default_user, args.only, env.ssh_runner is None, map_jump) collection.warnings.extend(warnings) return config, collection @@ -698,7 +736,8 @@ def _print_warnings(collection: Collection, env: Environment) -> None: def run_export(args: argparse.Namespace, env: Environment) -> int: - config, collection = _discover(args, env) + # Export mapuje ProxyJump na odkaz na profil (aplikace od zadání 41); install-pubkey ho dál přeskakuje. + config, collection = _discover(args, env, map_jump=True) source = default_source(args.source if args.source is not None else env.hostname) document = build_document(collection, source) data = encode_document(document) diff --git a/tools/public_export.manifest b/tools/public_export.manifest index 0422fa3..c7470f8 100644 --- a/tools/public_export.manifest +++ b/tools/public_export.manifest @@ -13,20 +13,38 @@ file LICENSE LICENSE file NOTICE NOTICE file SECURITY.md SECURITY.md file androidApp/build.gradle.kts androidApp/build.gradle.kts +file androidApp/lint.xml androidApp/lint.xml file androidApp/proguard-rules.pro androidApp/proguard-rules.pro file androidApp/src/androidTest/AndroidManifest.xml androidApp/src/androidTest/AndroidManifest.xml +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/AccessibilityEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/AccessibilityEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/BackupEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/BackupEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/CellDetailEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/CellDetailEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/LanRozsireniEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/LanRozsireniEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/LandscapeMloEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/LandscapeMloEvidence.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitInstrumentation.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitInstrumentation.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitTestApplication.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitTestApplication.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetStatusWidgetEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetStatusWidgetEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/ShareResultsEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/ShareResultsEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshBackgroundSftpEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshBackgroundSftpEvidence.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshKeyEditorEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshKeyEditorEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshLockEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshLockEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProductivityEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProductivityEvidence.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesR1Evidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesR1Evidence.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshXtermEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshXtermEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/SystemSettingsEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/SystemSettingsEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/ToolTargetsEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/ToolTargetsEvidence.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/UpdateDialogEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/UpdateDialogEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiExtensionsEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiExtensionsEvidence.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiFreshnessEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiFreshnessEvidence.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiScanLimitEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiScanLimitEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiSpectrumEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiSpectrumEvidence.kt file androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiVendorEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiVendorEvidence.kt +file androidApp/src/androidTest/kotlin/cz/netkit/app/test/WolWidgetIntentEvidence.kt androidApp/src/androidTest/kotlin/cz/netkit/app/test/WolWidgetIntentEvidence.kt file androidApp/src/dev/res/drawable/ic_launcher_background.xml androidApp/src/dev/res/drawable/ic_launcher_background.xml file androidApp/src/dev/res/values/strings.xml androidApp/src/dev/res/values/strings.xml +file androidApp/src/dev/res/xml/shortcuts.xml androidApp/src/dev/res/xml/shortcuts.xml file androidApp/src/main/AndroidManifest.xml androidApp/src/main/AndroidManifest.xml file androidApp/src/main/assets/licenses/Apache-2.0.txt androidApp/src/main/assets/licenses/Apache-2.0.txt file androidApp/src/main/assets/licenses/MPL-2.0.txt androidApp/src/main/assets/licenses/MPL-2.0.txt @@ -39,49 +57,121 @@ file androidApp/src/main/assets/licenses/jetbrains-mono-OFL.txt androidApp/src/m file androidApp/src/main/assets/licenses/jsch-LICENSE.txt androidApp/src/main/assets/licenses/jsch-LICENSE.txt file androidApp/src/main/assets/licenses/jzlib-LICENSE.txt androidApp/src/main/assets/licenses/jzlib-LICENSE.txt file androidApp/src/main/assets/licenses/manrope-OFL.txt androidApp/src/main/assets/licenses/manrope-OFL.txt +file androidApp/src/main/assets/licenses/protobuf-LICENSE.txt androidApp/src/main/assets/licenses/protobuf-LICENSE.txt +file androidApp/src/main/assets/licenses/unicode-LICENSE.txt androidApp/src/main/assets/licenses/unicode-LICENSE.txt +file androidApp/src/main/assets/licenses/usb-serial-for-android-LICENSE.txt androidApp/src/main/assets/licenses/usb-serial-for-android-LICENSE.txt file androidApp/src/main/assets/oui/ieee-oui.tsv androidApp/src/main/assets/oui/ieee-oui.tsv +file androidApp/src/main/java/com/hoho/android/usbserial/driver/CdcAcmSerialDriver.java androidApp/src/main/java/com/hoho/android/usbserial/driver/CdcAcmSerialDriver.java +file androidApp/src/main/java/com/hoho/android/usbserial/driver/Ch34xSerialDriver.java androidApp/src/main/java/com/hoho/android/usbserial/driver/Ch34xSerialDriver.java +file androidApp/src/main/java/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java androidApp/src/main/java/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java +file androidApp/src/main/java/com/hoho/android/usbserial/driver/Cp21xxSerialDriver.java androidApp/src/main/java/com/hoho/android/usbserial/driver/Cp21xxSerialDriver.java +file androidApp/src/main/java/com/hoho/android/usbserial/driver/FtdiSerialDriver.java androidApp/src/main/java/com/hoho/android/usbserial/driver/FtdiSerialDriver.java +file androidApp/src/main/java/com/hoho/android/usbserial/driver/ProlificSerialDriver.java androidApp/src/main/java/com/hoho/android/usbserial/driver/ProlificSerialDriver.java +file androidApp/src/main/java/com/hoho/android/usbserial/driver/SerialTimeoutException.java androidApp/src/main/java/com/hoho/android/usbserial/driver/SerialTimeoutException.java +file androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbId.java androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbId.java +file androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java +file androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialPort.java androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialPort.java +file androidApp/src/main/java/com/hoho/android/usbserial/util/HexDump.java androidApp/src/main/java/com/hoho/android/usbserial/util/HexDump.java +file androidApp/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java androidApp/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java +file androidApp/src/main/java/com/hoho/android/usbserial/util/UsbUtils.java androidApp/src/main/java/com/hoho/android/usbserial/util/UsbUtils.java file androidApp/src/main/kotlin/cz/netkit/app/MainActivity.kt androidApp/src/main/kotlin/cz/netkit/app/MainActivity.kt +file androidApp/src/main/kotlin/cz/netkit/app/backup/BackupCrypto.kt androidApp/src/main/kotlin/cz/netkit/app/backup/BackupCrypto.kt +file androidApp/src/main/kotlin/cz/netkit/app/backup/BackupRepository.kt androidApp/src/main/kotlin/cz/netkit/app/backup/BackupRepository.kt +file androidApp/src/main/kotlin/cz/netkit/app/backup/BackupScreen.kt androidApp/src/main/kotlin/cz/netkit/app/backup/BackupScreen.kt +file androidApp/src/main/kotlin/cz/netkit/app/backup/BackupViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/backup/BackupViewModel.kt +file androidApp/src/main/kotlin/cz/netkit/app/backup/RestoreFiles.kt androidApp/src/main/kotlin/cz/netkit/app/backup/RestoreFiles.kt +file androidApp/src/main/kotlin/cz/netkit/app/cellular/CellDetailViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/cellular/CellDetailViewModel.kt +file androidApp/src/main/kotlin/cz/netkit/app/cellular/CellInfoReader.kt androidApp/src/main/kotlin/cz/netkit/app/cellular/CellInfoReader.kt file androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesExport.kt androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesExport.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesScreen.kt androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesScreen.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticLookup.kt androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticLookup.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticPanel.kt androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticPanel.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/DnsLookup.kt androidApp/src/main/kotlin/cz/netkit/app/lan/DnsLookup.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/LanDeviceNetwork.kt androidApp/src/main/kotlin/cz/netkit/app/lan/LanDeviceNetwork.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/LanIpv6Tools.kt androidApp/src/main/kotlin/cz/netkit/app/lan/LanIpv6Tools.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/LanScreen.kt androidApp/src/main/kotlin/cz/netkit/app/lan/LanScreen.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/LanToolPreferences.kt androidApp/src/main/kotlin/cz/netkit/app/lan/LanToolPreferences.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/MacVendorPanel.kt androidApp/src/main/kotlin/cz/netkit/app/lan/MacVendorPanel.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/MdnsProbe.kt androidApp/src/main/kotlin/cz/netkit/app/lan/MdnsProbe.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/NetBios.kt androidApp/src/main/kotlin/cz/netkit/app/lan/NetBios.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/NetworkInfoCard.kt androidApp/src/main/kotlin/cz/netkit/app/lan/NetworkInfoCard.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/PingOptions.kt androidApp/src/main/kotlin/cz/netkit/app/lan/PingOptions.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/ServicesPanel.kt androidApp/src/main/kotlin/cz/netkit/app/lan/ServicesPanel.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/SubnetPanel.kt androidApp/src/main/kotlin/cz/netkit/app/lan/SubnetPanel.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/TargetHistory.kt androidApp/src/main/kotlin/cz/netkit/app/lan/TargetHistory.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/TcpProbe.kt androidApp/src/main/kotlin/cz/netkit/app/lan/TcpProbe.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/TracePath.kt androidApp/src/main/kotlin/cz/netkit/app/lan/TracePath.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/UdpServiceProbe.kt androidApp/src/main/kotlin/cz/netkit/app/lan/UdpServiceProbe.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/UpnpProbe.kt androidApp/src/main/kotlin/cz/netkit/app/lan/UpnpProbe.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/WebDiagnostic.kt androidApp/src/main/kotlin/cz/netkit/app/lan/WebDiagnostic.kt file androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp.kt androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp.kt +file androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp6.kt androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp6.kt +file androidApp/src/main/kotlin/cz/netkit/app/nav/AppShortcuts.kt androidApp/src/main/kotlin/cz/netkit/app/nav/AppShortcuts.kt file androidApp/src/main/kotlin/cz/netkit/app/net/ActiveNetworkMonitor.kt androidApp/src/main/kotlin/cz/netkit/app/net/ActiveNetworkMonitor.kt file androidApp/src/main/kotlin/cz/netkit/app/net/NetKindText.kt androidApp/src/main/kotlin/cz/netkit/app/net/NetKindText.kt +file androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusService.kt androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusService.kt +file androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidget.kt androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidget.kt +file androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidgetConfigActivity.kt androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidgetConfigActivity.kt +file androidApp/src/main/kotlin/cz/netkit/app/overview/CellDetailSection.kt androidApp/src/main/kotlin/cz/netkit/app/overview/CellDetailSection.kt +file androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportDialog.kt androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportDialog.kt +file androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportViewModel.kt file androidApp/src/main/kotlin/cz/netkit/app/overview/OverviewCards.kt androidApp/src/main/kotlin/cz/netkit/app/overview/OverviewCards.kt file androidApp/src/main/kotlin/cz/netkit/app/overview/PathCard.kt androidApp/src/main/kotlin/cz/netkit/app/overview/PathCard.kt file androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt +file androidApp/src/main/kotlin/cz/netkit/app/settings/AppLanguageSystem.kt androidApp/src/main/kotlin/cz/netkit/app/settings/AppLanguageSystem.kt +file androidApp/src/main/kotlin/cz/netkit/app/settings/OwnedOperation.kt androidApp/src/main/kotlin/cz/netkit/app/settings/OwnedOperation.kt +file androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsHost.kt androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsHost.kt +file androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsScreen.kt androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsScreen.kt +file androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsStore.kt androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsStore.kt +file androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsViewModel.kt +file androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Client.kt androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Client.kt +file androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Form.kt androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Form.kt file androidApp/src/main/kotlin/cz/netkit/app/speed/LibreSpeedClient.kt androidApp/src/main/kotlin/cz/netkit/app/speed/LibreSpeedClient.kt file androidApp/src/main/kotlin/cz/netkit/app/speed/Ndt7Client.kt androidApp/src/main/kotlin/cz/netkit/app/speed/Ndt7Client.kt file androidApp/src/main/kotlin/cz/netkit/app/speed/SignalHost.kt androidApp/src/main/kotlin/cz/netkit/app/speed/SignalHost.kt file androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedDial.kt androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedDial.kt file androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedHttp.kt androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedHttp.kt +file androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedShare.kt androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedShare.kt file androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedStore.kt androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedStore.kt file androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestScreen.kt androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestScreen.kt file androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt file androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedWifi.kt androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedWifi.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleConnection.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleConnection.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleProfileUi.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleProfileUi.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/DirectTerminalInput.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/DirectTerminalInput.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/PrivateTerminalEditText.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/PrivateTerminalEditText.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpClient.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpClient.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpController.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpController.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpRun.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpRun.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpScreen.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpScreen.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshAccess.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshAccess.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshAttemptGate.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshAttemptGate.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshConnectionOutcome.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshConnectionOutcome.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshDns.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshDns.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshFailureClassifier.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshFailureClassifier.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshForwarders.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshForwarders.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshKeys.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshKeys.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshLockUi.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshLockUi.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProductivityUi.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProductivityUi.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionLog.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionLog.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionService.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionService.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt file androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt +file androidApp/src/main/kotlin/cz/netkit/app/ssh/UsbConsole.kt androidApp/src/main/kotlin/cz/netkit/app/ssh/UsbConsole.kt +file androidApp/src/main/kotlin/cz/netkit/app/tile/SignalTileService.kt androidApp/src/main/kotlin/cz/netkit/app/tile/SignalTileService.kt file androidApp/src/main/kotlin/cz/netkit/app/ui/Components.kt androidApp/src/main/kotlin/cz/netkit/app/ui/Components.kt +file androidApp/src/main/kotlin/cz/netkit/app/ui/KeepScreenOn.kt androidApp/src/main/kotlin/cz/netkit/app/ui/KeepScreenOn.kt file androidApp/src/main/kotlin/cz/netkit/app/ui/NetKitIcons.kt androidApp/src/main/kotlin/cz/netkit/app/ui/NetKitIcons.kt +file androidApp/src/main/kotlin/cz/netkit/app/ui/RunSummary.kt androidApp/src/main/kotlin/cz/netkit/app/ui/RunSummary.kt +file androidApp/src/main/kotlin/cz/netkit/app/ui/ShareActions.kt androidApp/src/main/kotlin/cz/netkit/app/ui/ShareActions.kt file androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt file androidApp/src/main/kotlin/cz/netkit/app/ui/about/OssLicenses.kt androidApp/src/main/kotlin/cz/netkit/app/ui/about/OssLicenses.kt file androidApp/src/main/kotlin/cz/netkit/app/ui/chart/FullscreenChart.kt androidApp/src/main/kotlin/cz/netkit/app/ui/chart/FullscreenChart.kt @@ -93,17 +183,21 @@ file androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt androidApp/sr file androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt file androidApp/src/main/kotlin/cz/netkit/app/update/UpdateDialog.kt androidApp/src/main/kotlin/cz/netkit/app/update/UpdateDialog.kt file androidApp/src/main/kotlin/cz/netkit/app/update/UpdateViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/update/UpdateViewModel.kt +file androidApp/src/main/kotlin/cz/netkit/app/wifi/ExportSession.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/ExportSession.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/ForegroundScanObserver.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/ForegroundScanObserver.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/OuiAssets.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/OuiAssets.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/SpectrumChart.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/SpectrumChart.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiChartPalette.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiChartPalette.kt +file androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiExportFiles.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiExportFiles.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanBudget.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanBudget.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanEvents.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanEvents.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanLimitHelp.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanLimitHelp.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScreen.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScreen.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/live/LiveRadioSource.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/live/LiveRadioSource.kt +file androidApp/src/main/kotlin/cz/netkit/app/wifi/live/MloReader.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/live/MloReader.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/live/SignalScreen.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/live/SignalScreen.kt +file androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WalkCard.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WalkCard.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLinkMonitor.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLinkMonitor.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveState.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveState.kt file androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveStrings.kt androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveStrings.kt @@ -115,32 +209,67 @@ file androidApp/src/main/kotlin/cz/netkit/app/wol/DeviceStore.kt androidApp/src/ file androidApp/src/main/kotlin/cz/netkit/app/wol/UdpTransport.kt androidApp/src/main/kotlin/cz/netkit/app/wol/UdpTransport.kt file androidApp/src/main/kotlin/cz/netkit/app/wol/WolNameOrder.kt androidApp/src/main/kotlin/cz/netkit/app/wol/WolNameOrder.kt file androidApp/src/main/kotlin/cz/netkit/app/wol/WolScreen.kt androidApp/src/main/kotlin/cz/netkit/app/wol/WolScreen.kt +file androidApp/src/main/kotlin/cz/netkit/app/wol/WolSecureOnStorage.kt androidApp/src/main/kotlin/cz/netkit/app/wol/WolSecureOnStorage.kt file androidApp/src/main/kotlin/cz/netkit/app/wol/WolViewModel.kt androidApp/src/main/kotlin/cz/netkit/app/wol/WolViewModel.kt +file androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidget.kt androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidget.kt +file androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidgetConfigActivity.kt androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidgetConfigActivity.kt file androidApp/src/main/res/drawable/ic_launcher_background.xml androidApp/src/main/res/drawable/ic_launcher_background.xml file androidApp/src/main/res/drawable/ic_launcher_foreground.xml androidApp/src/main/res/drawable/ic_launcher_foreground.xml file androidApp/src/main/res/drawable/ic_launcher_monochrome.xml androidApp/src/main/res/drawable/ic_launcher_monochrome.xml +file androidApp/src/main/res/drawable/ic_notification_ssh.xml androidApp/src/main/res/drawable/ic_notification_ssh.xml +file androidApp/src/main/res/drawable/ic_shortcut_background.xml androidApp/src/main/res/drawable/ic_shortcut_background.xml +file androidApp/src/main/res/drawable/ic_shortcut_ping.xml androidApp/src/main/res/drawable/ic_shortcut_ping.xml +file androidApp/src/main/res/drawable/ic_shortcut_ping_foreground.xml androidApp/src/main/res/drawable/ic_shortcut_ping_foreground.xml +file androidApp/src/main/res/drawable/ic_shortcut_signal.xml androidApp/src/main/res/drawable/ic_shortcut_signal.xml +file androidApp/src/main/res/drawable/ic_shortcut_signal_foreground.xml androidApp/src/main/res/drawable/ic_shortcut_signal_foreground.xml +file androidApp/src/main/res/drawable/ic_shortcut_spectrum.xml androidApp/src/main/res/drawable/ic_shortcut_spectrum.xml +file androidApp/src/main/res/drawable/ic_shortcut_spectrum_foreground.xml androidApp/src/main/res/drawable/ic_shortcut_spectrum_foreground.xml +file androidApp/src/main/res/drawable/ic_shortcut_ssh.xml androidApp/src/main/res/drawable/ic_shortcut_ssh.xml +file androidApp/src/main/res/drawable/ic_shortcut_ssh_foreground.xml androidApp/src/main/res/drawable/ic_shortcut_ssh_foreground.xml +file androidApp/src/main/res/drawable/ic_shortcut_subnet.xml androidApp/src/main/res/drawable/ic_shortcut_subnet.xml +file androidApp/src/main/res/drawable/ic_shortcut_subnet_foreground.xml androidApp/src/main/res/drawable/ic_shortcut_subnet_foreground.xml +file androidApp/src/main/res/drawable/ic_shortcut_wol.xml androidApp/src/main/res/drawable/ic_shortcut_wol.xml +file androidApp/src/main/res/drawable/ic_shortcut_wol_foreground.xml androidApp/src/main/res/drawable/ic_shortcut_wol_foreground.xml +file androidApp/src/main/res/drawable/ic_tile_signal.xml androidApp/src/main/res/drawable/ic_tile_signal.xml +file androidApp/src/main/res/drawable/ic_widget_refresh.xml androidApp/src/main/res/drawable/ic_widget_refresh.xml file androidApp/src/main/res/font/jetbrains_mono.ttf androidApp/src/main/res/font/jetbrains_mono.ttf file androidApp/src/main/res/font/manrope.ttf androidApp/src/main/res/font/manrope.ttf +file androidApp/src/main/res/layout/netstatus_age.xml androidApp/src/main/res/layout/netstatus_age.xml file androidApp/src/main/res/mipmap-anydpi/ic_launcher.xml androidApp/src/main/res/mipmap-anydpi/ic_launcher.xml file androidApp/src/main/res/mipmap-anydpi/ic_launcher_round.xml androidApp/src/main/res/mipmap-anydpi/ic_launcher_round.xml +file androidApp/src/main/res/resources.properties androidApp/src/main/res/resources.properties +file androidApp/src/main/res/values-en/accessibility.xml androidApp/src/main/res/values-en/accessibility.xml +file androidApp/src/main/res/values-en/backup.xml androidApp/src/main/res/values-en/backup.xml file androidApp/src/main/res/values-en/cellular.xml androidApp/src/main/res/values-en/cellular.xml file androidApp/src/main/res/values-en/chart.xml androidApp/src/main/res/values-en/chart.xml file androidApp/src/main/res/values-en/lan_devices_ui.xml androidApp/src/main/res/values-en/lan_devices_ui.xml file androidApp/src/main/res/values-en/lan_devid.xml androidApp/src/main/res/values-en/lan_devid.xml file androidApp/src/main/res/values-en/lan_revision.xml androidApp/src/main/res/values-en/lan_revision.xml +file androidApp/src/main/res/values-en/lan_rozsireni.xml androidApp/src/main/res/values-en/lan_rozsireni.xml +file androidApp/src/main/res/values-en/lan_wol.xml androidApp/src/main/res/values-en/lan_wol.xml file androidApp/src/main/res/values-en/nav_m2.xml androidApp/src/main/res/values-en/nav_m2.xml file androidApp/src/main/res/values-en/net.xml androidApp/src/main/res/values-en/net.xml +file androidApp/src/main/res/values-en/netstatus_widget.xml androidApp/src/main/res/values-en/netstatus_widget.xml file androidApp/src/main/res/values-en/overview.xml androidApp/src/main/res/values-en/overview.xml +file androidApp/src/main/res/values-en/settings.xml androidApp/src/main/res/values-en/settings.xml +file androidApp/src/main/res/values-en/sharing.xml androidApp/src/main/res/values-en/sharing.xml +file androidApp/src/main/res/values-en/shortcuts.xml androidApp/src/main/res/values-en/shortcuts.xml file androidApp/src/main/res/values-en/speedtest.xml androidApp/src/main/res/values-en/speedtest.xml +file androidApp/src/main/res/values-en/ssh_background_sftp.xml androidApp/src/main/res/values-en/ssh_background_sftp.xml file androidApp/src/main/res/values-en/ssh_closure.xml androidApp/src/main/res/values-en/ssh_closure.xml +file androidApp/src/main/res/values-en/ssh_console.xml androidApp/src/main/res/values-en/ssh_console.xml file androidApp/src/main/res/values-en/ssh_design.xml androidApp/src/main/res/values-en/ssh_design.xml file androidApp/src/main/res/values-en/ssh_import.xml androidApp/src/main/res/values-en/ssh_import.xml +file androidApp/src/main/res/values-en/ssh_productivity.xml androidApp/src/main/res/values-en/ssh_productivity.xml file androidApp/src/main/res/values-en/ssh_revision.xml androidApp/src/main/res/values-en/ssh_revision.xml +file androidApp/src/main/res/values-en/ssh_terminal.xml androidApp/src/main/res/values-en/ssh_terminal.xml file androidApp/src/main/res/values-en/strings.xml androidApp/src/main/res/values-en/strings.xml file androidApp/src/main/res/values-en/strings_lan.xml androidApp/src/main/res/values-en/strings_lan.xml file androidApp/src/main/res/values-en/strings_ssh.xml androidApp/src/main/res/values-en/strings_ssh.xml file androidApp/src/main/res/values-en/strings_wifi.xml androidApp/src/main/res/values-en/strings_wifi.xml +file androidApp/src/main/res/values-en/tools_targets.xml androidApp/src/main/res/values-en/tools_targets.xml file androidApp/src/main/res/values-en/update.xml androidApp/src/main/res/values-en/update.xml +file androidApp/src/main/res/values-en/wifi_ext.xml androidApp/src/main/res/values-en/wifi_ext.xml file androidApp/src/main/res/values-en/wifi_revision.xml androidApp/src/main/res/values-en/wifi_revision.xml file androidApp/src/main/res/values-en/wifi_signal.xml androidApp/src/main/res/values-en/wifi_signal.xml file androidApp/src/main/res/values-en/wifi_spectrum.xml androidApp/src/main/res/values-en/wifi_spectrum.xml @@ -148,27 +277,45 @@ file androidApp/src/main/res/values-en/wol_closure.xml androidApp/src/main/res/v file androidApp/src/main/res/values-en/wol_design.xml androidApp/src/main/res/values-en/wol_design.xml file androidApp/src/main/res/values-en/wol_import_csv.xml androidApp/src/main/res/values-en/wol_import_csv.xml file androidApp/src/main/res/values-en/wol_revision.xml androidApp/src/main/res/values-en/wol_revision.xml +file androidApp/src/main/res/values-en/wol_secureon.xml androidApp/src/main/res/values-en/wol_secureon.xml +file androidApp/src/main/res/values-en/wol_widget.xml androidApp/src/main/res/values-en/wol_widget.xml +file androidApp/src/main/res/values-night/netstatus_widget_colors.xml androidApp/src/main/res/values-night/netstatus_widget_colors.xml file androidApp/src/main/res/values-night/styles.xml androidApp/src/main/res/values-night/styles.xml +file androidApp/src/main/res/values/accessibility.xml androidApp/src/main/res/values/accessibility.xml +file androidApp/src/main/res/values/backup.xml androidApp/src/main/res/values/backup.xml file androidApp/src/main/res/values/cellular.xml androidApp/src/main/res/values/cellular.xml file androidApp/src/main/res/values/chart.xml androidApp/src/main/res/values/chart.xml file androidApp/src/main/res/values/ids.xml androidApp/src/main/res/values/ids.xml file androidApp/src/main/res/values/lan_devices_ui.xml androidApp/src/main/res/values/lan_devices_ui.xml file androidApp/src/main/res/values/lan_devid.xml androidApp/src/main/res/values/lan_devid.xml file androidApp/src/main/res/values/lan_revision.xml androidApp/src/main/res/values/lan_revision.xml +file androidApp/src/main/res/values/lan_rozsireni.xml androidApp/src/main/res/values/lan_rozsireni.xml +file androidApp/src/main/res/values/lan_wol.xml androidApp/src/main/res/values/lan_wol.xml file androidApp/src/main/res/values/nav_m2.xml androidApp/src/main/res/values/nav_m2.xml file androidApp/src/main/res/values/net.xml androidApp/src/main/res/values/net.xml +file androidApp/src/main/res/values/netstatus_widget.xml androidApp/src/main/res/values/netstatus_widget.xml +file androidApp/src/main/res/values/netstatus_widget_colors.xml androidApp/src/main/res/values/netstatus_widget_colors.xml file androidApp/src/main/res/values/overview.xml androidApp/src/main/res/values/overview.xml +file androidApp/src/main/res/values/settings.xml androidApp/src/main/res/values/settings.xml +file androidApp/src/main/res/values/sharing.xml androidApp/src/main/res/values/sharing.xml +file androidApp/src/main/res/values/shortcuts.xml androidApp/src/main/res/values/shortcuts.xml file androidApp/src/main/res/values/speedtest.xml androidApp/src/main/res/values/speedtest.xml +file androidApp/src/main/res/values/ssh_background_sftp.xml androidApp/src/main/res/values/ssh_background_sftp.xml file androidApp/src/main/res/values/ssh_closure.xml androidApp/src/main/res/values/ssh_closure.xml +file androidApp/src/main/res/values/ssh_console.xml androidApp/src/main/res/values/ssh_console.xml file androidApp/src/main/res/values/ssh_design.xml androidApp/src/main/res/values/ssh_design.xml file androidApp/src/main/res/values/ssh_import.xml androidApp/src/main/res/values/ssh_import.xml +file androidApp/src/main/res/values/ssh_productivity.xml androidApp/src/main/res/values/ssh_productivity.xml file androidApp/src/main/res/values/ssh_revision.xml androidApp/src/main/res/values/ssh_revision.xml +file androidApp/src/main/res/values/ssh_terminal.xml androidApp/src/main/res/values/ssh_terminal.xml file androidApp/src/main/res/values/strings.xml androidApp/src/main/res/values/strings.xml file androidApp/src/main/res/values/strings_lan.xml androidApp/src/main/res/values/strings_lan.xml file androidApp/src/main/res/values/strings_ssh.xml androidApp/src/main/res/values/strings_ssh.xml file androidApp/src/main/res/values/strings_wifi.xml androidApp/src/main/res/values/strings_wifi.xml file androidApp/src/main/res/values/styles.xml androidApp/src/main/res/values/styles.xml +file androidApp/src/main/res/values/tools_targets.xml androidApp/src/main/res/values/tools_targets.xml file androidApp/src/main/res/values/update.xml androidApp/src/main/res/values/update.xml +file androidApp/src/main/res/values/wifi_ext.xml androidApp/src/main/res/values/wifi_ext.xml file androidApp/src/main/res/values/wifi_revision.xml androidApp/src/main/res/values/wifi_revision.xml file androidApp/src/main/res/values/wifi_signal.xml androidApp/src/main/res/values/wifi_signal.xml file androidApp/src/main/res/values/wifi_spectrum.xml androidApp/src/main/res/values/wifi_spectrum.xml @@ -176,36 +323,71 @@ file androidApp/src/main/res/values/wol_closure.xml androidApp/src/main/res/valu file androidApp/src/main/res/values/wol_design.xml androidApp/src/main/res/values/wol_design.xml file androidApp/src/main/res/values/wol_import_csv.xml androidApp/src/main/res/values/wol_import_csv.xml file androidApp/src/main/res/values/wol_revision.xml androidApp/src/main/res/values/wol_revision.xml +file androidApp/src/main/res/values/wol_secureon.xml androidApp/src/main/res/values/wol_secureon.xml +file androidApp/src/main/res/values/wol_widget.xml androidApp/src/main/res/values/wol_widget.xml file androidApp/src/main/res/xml/backup_rules.xml androidApp/src/main/res/xml/backup_rules.xml file androidApp/src/main/res/xml/data_extraction_rules.xml androidApp/src/main/res/xml/data_extraction_rules.xml +file androidApp/src/main/res/xml/netstatus_widget_info.xml androidApp/src/main/res/xml/netstatus_widget_info.xml file androidApp/src/main/res/xml/network_security_config.xml androidApp/src/main/res/xml/network_security_config.xml +file androidApp/src/main/res/xml/shortcuts.xml androidApp/src/main/res/xml/shortcuts.xml +file androidApp/src/main/res/xml/wol_widget_info.xml androidApp/src/main/res/xml/wol_widget_info.xml +file androidApp/src/test/kotlin/cz/netkit/app/backup/BackupCryptoTest.kt androidApp/src/test/kotlin/cz/netkit/app/backup/BackupCryptoTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/backup/BackupRepositoryTest.kt androidApp/src/test/kotlin/cz/netkit/app/backup/BackupRepositoryTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/backup/RestoreFilesTest.kt androidApp/src/test/kotlin/cz/netkit/app/backup/RestoreFilesTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/lan/DiagnosticLookupTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/DiagnosticLookupTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/lan/DnsLookupTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/DnsLookupTest.kt file androidApp/src/test/kotlin/cz/netkit/app/lan/DnsPtrTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/DnsPtrTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/lan/LanIpv6ToolsTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/LanIpv6ToolsTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/lan/LanNetworkInfoRefreshTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/LanNetworkInfoRefreshTest.kt file androidApp/src/test/kotlin/cz/netkit/app/lan/LanSettingsTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/LanSettingsTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/lan/LanToolPreferencesTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/LanToolPreferencesTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/lan/PingOptionsTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/PingOptionsTest.kt file androidApp/src/test/kotlin/cz/netkit/app/lan/TcpProbeTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/TcpProbeTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/lan/TracePathTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/TracePathTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/lan/UdpServicesFixtureTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/UdpServicesFixtureTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/lan/WebDiagnosticTest.kt androidApp/src/test/kotlin/cz/netkit/app/lan/WebDiagnosticTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/nav/ManifestExportsTest.kt androidApp/src/test/kotlin/cz/netkit/app/nav/ManifestExportsTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/nav/ShortcutResourcesTest.kt androidApp/src/test/kotlin/cz/netkit/app/nav/ShortcutResourcesTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/netstatus/NetStatusWidgetTest.kt androidApp/src/test/kotlin/cz/netkit/app/netstatus/NetStatusWidgetTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/overview/DiagnosticReportInputTest.kt androidApp/src/test/kotlin/cz/netkit/app/overview/DiagnosticReportInputTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/settings/CzechLocaleResourcesTest.kt androidApp/src/test/kotlin/cz/netkit/app/settings/CzechLocaleResourcesTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/settings/OwnedOperationTest.kt androidApp/src/test/kotlin/cz/netkit/app/settings/OwnedOperationTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/settings/SettingsStoreTest.kt androidApp/src/test/kotlin/cz/netkit/app/settings/SettingsStoreTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/speed/Iperf3ClientTest.kt androidApp/src/test/kotlin/cz/netkit/app/speed/Iperf3ClientTest.kt file androidApp/src/test/kotlin/cz/netkit/app/speed/LibreSpeedClientTest.kt androidApp/src/test/kotlin/cz/netkit/app/speed/LibreSpeedClientTest.kt file androidApp/src/test/kotlin/cz/netkit/app/speed/LoopbackServers.kt androidApp/src/test/kotlin/cz/netkit/app/speed/LoopbackServers.kt file androidApp/src/test/kotlin/cz/netkit/app/speed/Ndt7ClientTest.kt androidApp/src/test/kotlin/cz/netkit/app/speed/Ndt7ClientTest.kt file androidApp/src/test/kotlin/cz/netkit/app/speed/SpeedDialTest.kt androidApp/src/test/kotlin/cz/netkit/app/speed/SpeedDialTest.kt file androidApp/src/test/kotlin/cz/netkit/app/speed/SpeedStoreTest.kt androidApp/src/test/kotlin/cz/netkit/app/speed/SpeedStoreTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/ssh/ProfileEditorTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/ProfileEditorTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/ssh/SessionNotificationTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SessionNotificationTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/ssh/SftpRunTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SftpRunTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshAttemptGateTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshAttemptGateTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshConnectionOutcomeTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshConnectionOutcomeTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshCryptoTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshCryptoTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshLegacyExportFixtureTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshLegacyExportFixtureTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProductivityJvmTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProductivityJvmTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileExportTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileExportTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/SshRevisionTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/SshRevisionTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/ssh/TelnetConsoleWireTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/TelnetConsoleWireTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ssh/TerminalInputPrivacyTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/TerminalInputPrivacyTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/ssh/UsbConsoleWireTest.kt androidApp/src/test/kotlin/cz/netkit/app/ssh/UsbConsoleWireTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/ui/AccessibilityTest.kt androidApp/src/test/kotlin/cz/netkit/app/ui/AccessibilityTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ui/DesignSystemTest.kt androidApp/src/test/kotlin/cz/netkit/app/ui/DesignSystemTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ui/about/OssComponentsTest.kt androidApp/src/test/kotlin/cz/netkit/app/ui/about/OssComponentsTest.kt file androidApp/src/test/kotlin/cz/netkit/app/ui/chart/FullscreenChartTest.kt androidApp/src/test/kotlin/cz/netkit/app/ui/chart/FullscreenChartTest.kt file androidApp/src/test/kotlin/cz/netkit/app/update/OkHttpUpdateHttpTest.kt androidApp/src/test/kotlin/cz/netkit/app/update/OkHttpUpdateHttpTest.kt file androidApp/src/test/kotlin/cz/netkit/app/update/StartupUpdateTest.kt androidApp/src/test/kotlin/cz/netkit/app/update/StartupUpdateTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/wifi/ExportSessionTest.kt androidApp/src/test/kotlin/cz/netkit/app/wifi/ExportSessionTest.kt file androidApp/src/test/kotlin/cz/netkit/app/wifi/ForegroundScanObserverTest.kt androidApp/src/test/kotlin/cz/netkit/app/wifi/ForegroundScanObserverTest.kt file androidApp/src/test/kotlin/cz/netkit/app/wifi/OuiAssetTest.kt androidApp/src/test/kotlin/cz/netkit/app/wifi/OuiAssetTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/wifi/SpectrumAxisLabelsTest.kt androidApp/src/test/kotlin/cz/netkit/app/wifi/SpectrumAxisLabelsTest.kt file androidApp/src/test/kotlin/cz/netkit/app/wifi/WifiChartPaletteTest.kt androidApp/src/test/kotlin/cz/netkit/app/wifi/WifiChartPaletteTest.kt file androidApp/src/test/kotlin/cz/netkit/app/wifi/WifiDeveloperSettingsTest.kt androidApp/src/test/kotlin/cz/netkit/app/wifi/WifiDeveloperSettingsTest.kt file androidApp/src/test/kotlin/cz/netkit/app/wifi/WifiScanWindowTest.kt androidApp/src/test/kotlin/cz/netkit/app/wifi/WifiScanWindowTest.kt file androidApp/src/test/kotlin/cz/netkit/app/wifi/live/LiveRadioSourceTest.kt androidApp/src/test/kotlin/cz/netkit/app/wifi/live/LiveRadioSourceTest.kt +file androidApp/src/test/kotlin/cz/netkit/app/wifi/live/WalkCardTest.kt androidApp/src/test/kotlin/cz/netkit/app/wifi/live/WalkCardTest.kt file androidApp/src/test/kotlin/cz/netkit/app/wol/BoundedStreamIoTest.kt androidApp/src/test/kotlin/cz/netkit/app/wol/BoundedStreamIoTest.kt file androidApp/src/test/kotlin/cz/netkit/app/wol/DeviceSerializerTest.kt androidApp/src/test/kotlin/cz/netkit/app/wol/DeviceSerializerTest.kt file androidApp/src/test/kotlin/cz/netkit/app/wol/UdpTransportTest.kt androidApp/src/test/kotlin/cz/netkit/app/wol/UdpTransportTest.kt @@ -218,6 +400,7 @@ file docs/design/prototyp-m3.html docs/design/prototyp-m3.html file docs/distribuce.md docs/distribuce.md file docs/funkce/lan-scanner.md docs/funkce/lan-scanner.md file docs/funkce/mobilni-sit.md docs/funkce/mobilni-sit.md +file docs/funkce/nastaveni.md docs/funkce/nastaveni.md file docs/funkce/speedtest.md docs/funkce/speedtest.md file docs/funkce/ssh.md docs/funkce/ssh.md file docs/funkce/wifi-analyzer.md docs/funkce/wifi-analyzer.md @@ -227,7 +410,10 @@ file docs/licenses/bouncycastle-LICENSE.html docs/licenses/bouncycastle-LICENSE. file docs/licenses/jsch-META-INF_LICENSE.JZlib.txt docs/licenses/jsch-META-INF_LICENSE.JZlib.txt file docs/licenses/jsch-META-INF_LICENSE.jBCrypt.txt docs/licenses/jsch-META-INF_LICENSE.jBCrypt.txt file docs/licenses/jsch-META-INF_LICENSE.txt docs/licenses/jsch-META-INF_LICENSE.txt +file docs/licenses/protobuf-LICENSE.txt docs/licenses/protobuf-LICENSE.txt file docs/licenses/slf4j-api-META-INF_LICENSE.txt docs/licenses/slf4j-api-META-INF_LICENSE.txt +file docs/licenses/unicode-LICENSE.txt docs/licenses/unicode-LICENSE.txt +file docs/licenses/usb-serial-for-android-LICENSE.txt docs/licenses/usb-serial-for-android-LICENSE.txt file docs/plan.md docs/plan.md file docs/project-license-inventory.tsv docs/project-license-inventory.tsv file docs/public-export.md docs/public-export.md @@ -293,107 +479,192 @@ file iosApp/NetKitUITests/NetKitUITests.swift iosApp/NetKitUITests/NetKitUITests file settings.gradle.kts settings.gradle.kts file shared/build.gradle.kts shared/build.gradle.kts file shared/src/commonMain/kotlin/cz/netkit/shared/NetKit.kt shared/src/commonMain/kotlin/cz/netkit/shared/NetKit.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/backup/ConfigurationBackup.kt shared/src/commonMain/kotlin/cz/netkit/shared/backup/ConfigurationBackup.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/backup/RestorePlan.kt shared/src/commonMain/kotlin/cz/netkit/shared/backup/RestorePlan.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/cellular/CellDetail.kt shared/src/commonMain/kotlin/cz/netkit/shared/cellular/CellDetail.kt file shared/src/commonMain/kotlin/cz/netkit/shared/cellular/Cellular.kt shared/src/commonMain/kotlin/cz/netkit/shared/cellular/Cellular.kt file shared/src/commonMain/kotlin/cz/netkit/shared/chart/ChartViewport.kt shared/src/commonMain/kotlin/cz/netkit/shared/chart/ChartViewport.kt file shared/src/commonMain/kotlin/cz/netkit/shared/json/JsonLimits.kt shared/src/commonMain/kotlin/cz/netkit/shared/json/JsonLimits.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/BoundedProbes.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/BoundedProbes.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/ConsentResetGate.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/ConsentResetGate.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsMessage.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsMessage.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsQuery.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsQuery.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRcode.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRcode.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRecords.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRecords.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/IcmpEcho.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/IcmpEcho.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/Ipv6.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/Ipv6.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDeviceExport.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDeviceExport.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDevices.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDevices.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDomain.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDomain.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanExportLimits.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanExportLimits.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanNetworkInfo.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanNetworkInfo.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanWol.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanWol.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/MacAddressTable.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/MacAddressTable.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/MdnsIdentity.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/MdnsIdentity.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/NetBiosParser.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/NetBiosParser.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/NtpPacket.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/NtpPacket.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/PinnedProbe.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/PinnedProbe.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/ProbeResult.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/ProbeResult.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/SnmpBer.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/SnmpBer.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/SubnetCalculator.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/SubnetCalculator.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/TcpPing.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/TcpPing.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/ToolTargets.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/ToolTargets.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/UdpServices.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/UdpServices.kt file shared/src/commonMain/kotlin/cz/netkit/shared/lan/UpnpIdentity.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/UpnpIdentity.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/lan/VersionBind.kt shared/src/commonMain/kotlin/cz/netkit/shared/lan/VersionBind.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/nav/AdaptiveNavigation.kt shared/src/commonMain/kotlin/cz/netkit/shared/nav/AdaptiveNavigation.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/nav/AppTarget.kt shared/src/commonMain/kotlin/cz/netkit/shared/nav/AppTarget.kt file shared/src/commonMain/kotlin/cz/netkit/shared/net/LocalTarget.kt shared/src/commonMain/kotlin/cz/netkit/shared/net/LocalTarget.kt file shared/src/commonMain/kotlin/cz/netkit/shared/net/NetKind.kt shared/src/commonMain/kotlin/cz/netkit/shared/net/NetKind.kt file shared/src/commonMain/kotlin/cz/netkit/shared/net/ToolRoute.kt shared/src/commonMain/kotlin/cz/netkit/shared/net/ToolRoute.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatus.kt shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatus.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRecorder.kt shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRecorder.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRefresh.kt shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRefresh.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusView.kt shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusView.kt file shared/src/commonMain/kotlin/cz/netkit/shared/overview/Overview.kt shared/src/commonMain/kotlin/cz/netkit/shared/overview/Overview.kt file shared/src/commonMain/kotlin/cz/netkit/shared/publicip/PublicIp.kt shared/src/commonMain/kotlin/cz/netkit/shared/publicip/PublicIp.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/publicip/Rdap.kt shared/src/commonMain/kotlin/cz/netkit/shared/publicip/Rdap.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/report/DiagnosticReport.kt shared/src/commonMain/kotlin/cz/netkit/shared/report/DiagnosticReport.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/report/ReportText.kt shared/src/commonMain/kotlin/cz/netkit/shared/report/ReportText.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/settings/AppSettings.kt shared/src/commonMain/kotlin/cz/netkit/shared/settings/AppSettings.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/speed/Iperf3Protocol.kt shared/src/commonMain/kotlin/cz/netkit/shared/speed/Iperf3Protocol.kt file shared/src/commonMain/kotlin/cz/netkit/shared/speed/LibreSpeed.kt shared/src/commonMain/kotlin/cz/netkit/shared/speed/LibreSpeed.kt file shared/src/commonMain/kotlin/cz/netkit/shared/speed/Ndt7.kt shared/src/commonMain/kotlin/cz/netkit/shared/speed/Ndt7.kt file shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedDataEstimate.kt shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedDataEstimate.kt file shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt file shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedMeasure.kt shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedMeasure.kt file shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedScale.kt shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedScale.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ConsoleProfile.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ConsoleProfile.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ProfileDirectory.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ProfileDirectory.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/PromptReplyGate.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/PromptReplyGate.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Sftp.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Sftp.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Socks5.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Socks5.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshForwarding.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshForwarding.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshPromptPolicy.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshPromptPolicy.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshSnippets.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshSnippets.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshUnlock.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshUnlock.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TelnetCodec.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TelnetCodec.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalComposition.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalComposition.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalInput.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalInput.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalLog.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalLog.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalPalette.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalPalette.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalSessionBuffers.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalSessionBuffers.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt file shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWritePump.kt shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWritePump.kt file shared/src/commonMain/kotlin/cz/netkit/shared/update/ProjectLinks.kt shared/src/commonMain/kotlin/cz/netkit/shared/update/ProjectLinks.kt file shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateFetch.kt shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateFetch.kt file shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateInfo.kt shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateInfo.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/BssLoad.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/BssLoad.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/EssGroups.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/EssGroups.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/LiveTelemetry.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/LiveTelemetry.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Mlo.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Mlo.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/OuiDatabase.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/OuiDatabase.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/RegionalRaster.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/RegionalRaster.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Spectrum.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Spectrum.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/SpectrumPins.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/SpectrumPins.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WalkLog.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WalkLog.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiDomain.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiDomain.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiScanExport.kt shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiScanExport.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WakeProbePolicy.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WakeProbePolicy.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolController.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolController.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolCsvExport.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolCsvExport.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolCsvImport.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolCsvImport.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolDomain.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolDomain.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolModels.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolModels.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolSecureOn.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolSecureOn.kt file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolTransfer.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolTransfer.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWake.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWake.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetModel.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetModel.kt +file shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetRun.kt shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetRun.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/backup/ConfigurationBackupTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/backup/ConfigurationBackupTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/cellular/CellDetailTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/cellular/CellDetailTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/cellular/CellularTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/cellular/CellularTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/chart/ChartViewportTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/chart/ChartViewportTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/json/JsonInputLimitsTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/json/JsonInputLimitsTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/json/JsonLimitsTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/json/JsonLimitsTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/BoundedProbesTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/BoundedProbesTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/ConsentResetGateTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/ConsentResetGateTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/DiscoveryFallbackTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/DiscoveryFallbackTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsMessageTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsMessageTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsQueryTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsQueryTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRcodeTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRcodeTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRecordsTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRecordsTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/IcmpEchoTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/IcmpEchoTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/Icmpv6EchoTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/Icmpv6EchoTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/Ipv6Test.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/Ipv6Test.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDeviceExportTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDeviceExportTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDeviceIdentityTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDeviceIdentityTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDevicesTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDevicesTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDomainTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDomainTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanExportLimitsTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanExportLimitsTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanNetworkInfoTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanNetworkInfoTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanRevisionTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanRevisionTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanWolTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanWolTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/MacAddressTableTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/MacAddressTableTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/ManagementPortsTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/ManagementPortsTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/MdnsIdentityTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/MdnsIdentityTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/NetBiosParserTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/NetBiosParserTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/PinnedProbeTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/PinnedProbeTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/ProbeResultTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/ProbeResultTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/SubnetCalculatorTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/SubnetCalculatorTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/TcpPingTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/TcpPingTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/ToolTargetsTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/ToolTargetsTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/lan/UdpServicesCodecTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/UdpServicesCodecTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/lan/UpnpIdentityTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/lan/UpnpIdentityTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/nav/AdaptiveNavigationTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/nav/AdaptiveNavigationTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/nav/AppTargetTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/nav/AppTargetTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/net/LocalTargetTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/net/LocalTargetTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/net/ToolRouteTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/net/ToolRouteTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusViewTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusViewTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/overview/OverviewTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/overview/OverviewTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/publicip/PublicIpTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/publicip/PublicIpTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/publicip/RdapTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/publicip/RdapTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/report/DiagnosticReportTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/report/DiagnosticReportTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/settings/AppSettingsTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/settings/AppSettingsTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/speed/Iperf3ProtocolTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/speed/Iperf3ProtocolTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedDataEstimateTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedDataEstimateTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedHistoryClearTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedHistoryClearTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedMeasureTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedMeasureTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedProtocolTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedProtocolTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedScaleTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedScaleTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/PromptReplyGateTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/PromptReplyGateTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SftpTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SftpTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshDirectoryTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshDirectoryTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshExportProductivityTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshExportProductivityTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshLegacyFixture.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshLegacyFixture.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProductivityTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProductivityTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileExchangeTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileExchangeTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPromptPolicyTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPromptPolicyTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TelnetConsoleTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TelnetConsoleTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalBufferTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalBufferTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalCompositionTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalCompositionTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalInputTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalInputTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalSessionBuffersTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalSessionBuffersTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalWritePumpTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalWritePumpTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalXtermTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalXtermTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/update/ProjectLinksTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/update/ProjectLinksTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/update/UpdateFetchTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/update/UpdateFetchTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/update/UpdateInfoTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/update/UpdateInfoTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/BondingCenterTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/BondingCenterTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/LiveChartTimelineTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/LiveChartTimelineTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/LiveTelemetryTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/LiveTelemetryTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/MloTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/MloTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/OuiDatabaseTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/OuiDatabaseTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/SpectrumTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/SpectrumTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WalkLogTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WalkLogTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiDatasetPolicyTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiDatasetPolicyTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiDomainTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiDomainTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiExtensionsTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiExtensionsTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiRevisionTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiRevisionTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiUiPolicyTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiUiPolicyTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WakeProbePolicyTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WakeProbePolicyTest.kt @@ -404,6 +675,11 @@ file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolDomainTest.kt shared/s file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolImportLimitsTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolImportLimitsTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolInteractionRevisionTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolInteractionRevisionTest.kt file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolRevisionTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolRevisionTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolSecureOnTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolSecureOnTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWakeTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWakeTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetModelTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetModelTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetRunTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetRunTest.kt +file shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetSecureOnTest.kt shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetSecureOnTest.kt file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosAboutDomain.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosAboutDomain.kt file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosNetworkDomain.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosNetworkDomain.kt file shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSecretStoreAdapter.kt shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSecretStoreAdapter.kt @@ -442,10 +718,19 @@ file tools/test_release_latest_json.py tools/test_release_latest_json.py file tools/test_run_m1_checks.py tools/test_run_m1_checks.py file tools/test_run_wol_e2e.py tools/test_run_wol_e2e.py file tools/test_update_oui.py tools/test_update_oui.py +file tools/test_update_terminal_width.py tools/test_update_terminal_width.py file tools/testsrv/__init__.py tools/testsrv/__init__.py +file tools/testsrv/iperf3_fixture.py tools/testsrv/iperf3_fixture.py file tools/testsrv/m1_fixture.py tools/testsrv/m1_fixture.py +file tools/testsrv/telnet_fixture.py tools/testsrv/telnet_fixture.py +file tools/testsrv/test_iperf3_fixture.py tools/testsrv/test_iperf3_fixture.py file tools/testsrv/test_m1_fixture.py tools/testsrv/test_m1_fixture.py +file tools/testsrv/test_udp_services.py tools/testsrv/test_udp_services.py +file tools/testsrv/test_wol_listener.py tools/testsrv/test_wol_listener.py +file tools/testsrv/udp_services.py tools/testsrv/udp_services.py +file tools/testsrv/web_diagnostic.py tools/testsrv/web_diagnostic.py file tools/testsrv/wol_listener.py tools/testsrv/wol_listener.py file tools/update_oui.py tools/update_oui.py +file tools/update_terminal_width.py tools/update_terminal_width.py file tools/verify_release_assets.sh tools/verify_release_assets.sh file web/netkit/README.md web/netkit/README.md diff --git a/tools/public_export.reviewed.tsv b/tools/public_export.reviewed.tsv index bdcd969..9c6894b 100644 --- a/tools/public_export.reviewed.tsv +++ b/tools/public_export.reviewed.tsv @@ -1,241 +1,427 @@ -# Reviewed 2026-10-28 (F2), refreshed 2026-10-31 (F3–F7, independent subagent review): path, SHA256 of entire file, classification.; refreshed 2026-11-01 (1.0.1: SSH profiles v2 and iOS, two independent subagent reviews); 2026-11-01 iOS zadání 30 (independent subagent review + Claude review of R1 diff); 2026-11-01 docs P3 6046126 (manual diff review: phone model removed, iOS CI status); 2026-11-02 1.1.0 (independent review of the export diff, internal references removed); 2026-11-02 1.1.0 manifest fix (12 files of the update dialog / scan limit change, manual review) +# Reviewed 2026-10-28 (F2), refreshed 2026-10-31 (F3–F7, independent subagent review): path, SHA256 of entire file, classification.; refreshed 2026-11-01 (1.0.1: SSH profiles v2 and iOS, two independent subagent reviews); 2026-11-01 iOS zadání 30 (independent subagent review + Claude review of R1 diff); 2026-11-01 docs P3 6046126 (manual diff review: phone model removed, iOS CI status); 2026-11-02 1.1.0 (independent review of the export diff, internal references removed); 2026-11-02 1.1.0 manifest fix (12 files of the update dialog / scan limit change, manual review); 2026-12-02 2.0.0 (150 otisků obnoveno, 285 nových: ruční revize nálezů grep a interních identifikátorů proti exportu 1.1.0 ee5f223, syntetická data, interní odkazy a model telefonu odstraněny) # Changes require manual review, including context. Do not auto-refresh. .gitattributes ae58971fd773ee1c787aabb95003ac562a6e70406754341dc00e8bc0469cb661 code .github/workflows/ci.yml bea84d1b09d4a29d21332db81764fedd98f23dc9641b36c8eff8bb98dd29c01f code .github/workflows/ios.yml e9ce3273927a55d598654467d4bb4fe0b17cc7a65430a263449529f113c96d28 code .github/workflows/publish.yml 8c90ff245bee1ce515b2d41b2e55e48d5b6fab78efa9a3a5f13fe874fe0a3978 code -.github/workflows/release.yml 0aa2b4920cc39cb7041060a3dfcb9d3c7e8ab559087c81af57dab0bf1d598995 code +.github/workflows/release.yml d7484d62083d25efbfcb196f9ae900dcc5edc7a679b7131aa348489a84f545e4 code .gitignore 415584539eaeda8c23d5848ca8099dcb063f933532ba818643e6f31f9f7da4a8 code -CHANGELOG.md f5fdb496872e451dd74b2fe1ce8038210301a7e860366a06325db7a8a6622a86 documentation -CLAUDE.md ccf16e55ed4f4d65a7c1e85fea270246deee8aaae518078320f50d5473340014 documentation +CHANGELOG.md d99079e07fc4d577789cbf320a200db54e95e3041ca05dfd7aa1d3652758e816 documentation +CLAUDE.md ea92500e8a7b8de9def7bfa236d1933b651d212428268dee12789970dfbcec3b documentation LICENSE cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 upstream-license -NOTICE c1adb6b5852efea3d77e9dd529f7765c48595093e8d3d571203c3b62aaa148de documentation -README.cs.md 7a5434d07b140428856f950e19fcac78ff594d8190eae34dcb1a1b60340ca338 documentation -README.md 0c871bae56f61f25d15b7b6a268cc93fe46c68be9015dfef74fd7b73478b64ce documentation +NOTICE 0cbd12ae837f14ea51e5ca30b1f4b58d7da4c200a03f121d5768c52e7cd0719e documentation +README.cs.md c8f54cd3ad818b1232bd869ae70769a88463deb26fb85c9ccc874b7d7f86e6af documentation +README.md f83b07d2b6b44f409fbf56c3688f5a4925a52c4e7d9d7e98ff1c041128c1c2aa documentation SECURITY.md fbc26445e76ab9911f4455b19a27b1f1dd20519fcee28904d6417038671d06a2 documentation -androidApp/build.gradle.kts 5cace2bbf6d7374dd35586f6de12d452777c8fcd6670d1fee47f8b71be677063 code +androidApp/build.gradle.kts 55340698acb42bc24f04874333e74dc69ec580f6187fedd31b1ac148a713af67 code +androidApp/lint.xml 0c0c6772a53c5f6694444cd1833d548ab29bd37d7960cf47ecbc4975cd1ef337 code androidApp/proguard-rules.pro aded657fad6038d476d8fe0de5c1496356c20da7c9dd18bad9edac81c9cdaf40 code androidApp/src/androidTest/AndroidManifest.xml 787cbff61e052dfab11a246ab278dbfde7a22ce1ba387373f2e1206b80e18b97 code -androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt 7efe832eb81c4354cdc101739cba2825c42d168d7214cf18c97243a1c6e642ca synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/AccessibilityEvidence.kt ff2163e1aacc193c84dd17de7901e8c3c9218cc641fc7ea407645796af154778 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/BackupEvidence.kt ba14ecc266b94acada64ec321b73257bb1dfa2ebb9a397d724efb177c1f91002 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/CellDetailEvidence.kt 42eb4d12f8744019bef1810e39c88881a5d1ab17bef7e3d817d830e9603e05d4 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/LanRozsireniEvidence.kt 1fde16302b896d391da2d0f91a80d72daaaff05c5c9a4002dd85d9cbc61f2656 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/LandscapeMloEvidence.kt ce4214a628cb08d524a4aabd2cc1641ae9b98bb085670e6b0eac0a78ad45c6ca synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/M1Instrumentation.kt 8b207194457594903e4c0d4ce36e24c6bc1839bbe69f6162d63664a803429666 synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitInstrumentation.kt 6a33294d7ff1173bd03e589c1e5a50af3b113e877635c161a0a475ab3558b435 synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetKitTestApplication.kt a703c6e56b1540851d0af2b9c8b4b5f24c70db0be5a88eb77e6c0084c7da94eb synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/NetStatusWidgetEvidence.kt 8d0d0ce6e6ebb8c2cd62e718605fd972d37de56d77f1500832ea70e7aff9a41c synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/ShareResultsEvidence.kt 2fd29139136b6d99cc97d653ea4299b5e572a09caef2ea80030f1b9a80ec9f8e synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshBackgroundSftpEvidence.kt 2460974a41a68c7351ffa2dee44e2ccf57fd4004174a14272adc213e675e50fe synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshKeyEditorEvidence.kt 25a8ca2a8c1b95bdd6e0590f438e2d4a03185fbd8fc0f1b87a2b9d48c8015120 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshLockEvidence.kt fe16fd13d13c6e4e2f1215d41c3ae148de95d02aace506a86e2c50d7f3b0ffc4 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProductivityEvidence.kt 3e73fd13125cdec59f8a9faa8b753c62485237f390781db8cab818776c46a97a synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesR1Evidence.kt 264d57a610a5ef15c654a2828e4af23b98e8e1dbf9442333918bc124c1f9f376 synthetic -androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt e9b2e36909212c1b891327d58cc0fd32fd12aac22f7cc7c36e8783a062f2cc2d synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshProfilesV2Evidence.kt 6d5286bd6dd7cc94483d6392b7e122421d054dedb9401e32059a4b6a44a46d8b synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/SshXtermEvidence.kt 3ab64e6c2463761987f128b553c9cb87839a5c6c9537ad4ae54596e5a32c39c5 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/SystemSettingsEvidence.kt 596391c3a3e1194f329182b855f3bc5bed12275a90602a9f6265205c22ddafa0 synthetic +androidApp/src/androidTest/kotlin/cz/netkit/app/test/ToolTargetsEvidence.kt 347ad35902f40416cf3fd67ed1d3b74d612e59333b983b9a3ff82a5655175596 synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/UpdateDialogEvidence.kt 80f5b17b1b22cdeb6c90418b104d6397237ec8ffac03fb12edd67156191fc1c3 code +androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiExtensionsEvidence.kt ca3653140d9296f66ace01b1d47ae617ae5a87bbcb48666dddc04a6123b3e9af synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiFreshnessEvidence.kt 64fccb274984a4a2663afa7fe390bfdd7fcf4f6fa111f5e0eb328fd8c76b7372 synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiScanLimitEvidence.kt 735783521879baed066aff6cbda92becfa4061f0bcad7f91fb0f458dbf51c053 code +androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiSpectrumEvidence.kt a57a1c3f8f1fbd6e0b9a5e8eba82f91769d25f2d503c26393f31c6ba59be9d26 synthetic androidApp/src/androidTest/kotlin/cz/netkit/app/test/WifiVendorEvidence.kt af09bcd5d3321f0bd4b4019bc2e63b4cfee9ae947ddca085af9a82a90b3577bc code +androidApp/src/androidTest/kotlin/cz/netkit/app/test/WolWidgetIntentEvidence.kt 9f3045c8c04b2cf6d88d27b0b3eb79c06cbf789557e04a8b69b97f62ce6062b7 synthetic androidApp/src/dev/res/drawable/ic_launcher_background.xml 625231d3902f22287e65d8e2f5423e18a6239e6e120e556042d66bff56c3249f code androidApp/src/dev/res/values/strings.xml 108a1b751c7b8705111ce5c13135c3e4e4a82681212d47a766835a58b90ff995 code -androidApp/src/main/AndroidManifest.xml 7301ca2f335df63ca0b5ce0763b792840e13d500fe116d1a32d909e427f49743 code +androidApp/src/dev/res/xml/shortcuts.xml c392e0dcc4937e24f54609b7693db32b830b137d476e1f229fd4423b94bf69cc code +androidApp/src/main/AndroidManifest.xml 460565ac4e7215e4035cc5ffee410707a5a3c8e6ce989eeb697344b27f0d8f2e code androidApp/src/main/assets/licenses/Apache-2.0.txt cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 upstream-license androidApp/src/main/assets/licenses/MPL-2.0.txt 3f3d9e0024b1921b067d6f7f88deb4a60cbe7a78e76c64e3f1d7fc3b779b9d04 upstream-license -androidApp/src/main/assets/licenses/NOTICE.txt c1adb6b5852efea3d77e9dd529f7765c48595093e8d3d571203c3b62aaa148de documentation +androidApp/src/main/assets/licenses/NOTICE.txt 0cbd12ae837f14ea51e5ca30b1f4b58d7da4c200a03f121d5768c52e7cd0719e documentation androidApp/src/main/assets/licenses/bouncycastle-LICENSE.txt 782703fcd39c06fcfba0e23d1cdc65c3f219d58b5a5ffa632a5b37008cfec956 upstream-license -androidApp/src/main/assets/licenses/components.json 36a1c1bdf0606106e56ebec7cb96975deb23de0428090b828f33c093ced2c54a documentation +androidApp/src/main/assets/licenses/components.json 042e2c8631e4fb0d18d80ba736e37b6ee187ac1f1b2bf575d24ab5221ac70208 documentation androidApp/src/main/assets/licenses/ieee-oui-NOTICE.txt 39e5caddd2683ecbc90b0ba0f7769ebaad0747a31734b2ee36db68eb5ef4689b upstream-license androidApp/src/main/assets/licenses/jbcrypt-LICENSE.txt a85927641ed1c8b95a5cef79b127b2392d80e0aa9d8e2d6f3b7b7401c5396af9 upstream-license androidApp/src/main/assets/licenses/jetbrains-mono-OFL.txt b2fe5e8987594e9ffd1d2ca52a2f5d73eb8335243893c5d6254b5ad69269591d upstream-license androidApp/src/main/assets/licenses/jsch-LICENSE.txt 9c3537ab0b485b391b887b95fdff761de3dd3273a6931e8a1942dde4d2093cc5 upstream-license androidApp/src/main/assets/licenses/jzlib-LICENSE.txt 9aa93e9bc58ae423a9e6476f608ee8f46063f5679e3bac0bc55f2f4b10d243ee upstream-license androidApp/src/main/assets/licenses/manrope-OFL.txt 58172e0c0fac2cda8a37b348164bb55e44b0e69051e557e92b1d3f6910141f7b upstream-license +androidApp/src/main/assets/licenses/protobuf-LICENSE.txt 6e5e117324afd944dcf67f36cf329843bc1a92229a8cd9bb573d7a83130fea7d upstream-license +androidApp/src/main/assets/licenses/unicode-LICENSE.txt 1b57920e5dc491971020bb9fb619e052545b7358b66e365074870b5e5527480e upstream-license +androidApp/src/main/assets/licenses/usb-serial-for-android-LICENSE.txt 6f467d3d79c5d31734881fb83e082e84512bde05d3f7893e0e8373fd0d2b5d2c upstream-license androidApp/src/main/assets/oui/ieee-oui.tsv 04c3ef42420bad9a212083bd4702b497b27771ba1dd8c05e9eceac809f1a3ccb public-service -androidApp/src/main/kotlin/cz/netkit/app/MainActivity.kt f96b489dde95ca33c4a74bc053b58686a77264a87113a58fe4fb7ac1587d0291 code +androidApp/src/main/java/com/hoho/android/usbserial/driver/CdcAcmSerialDriver.java 1afc2ec2d9bad17b4a6925e0c84f95fa20a9c4671b836fe9f914949fce583648 code +androidApp/src/main/java/com/hoho/android/usbserial/driver/Ch34xSerialDriver.java 6cf0d0ab38de0506b6b71abb2e0333671cfbcffa1b9d5f7824a9aefcadc5e8c6 code +androidApp/src/main/java/com/hoho/android/usbserial/driver/CommonUsbSerialPort.java fc6d5491eb21adff034ee04be16b7d0b27d180c487755dce35d07518198a9637 code +androidApp/src/main/java/com/hoho/android/usbserial/driver/Cp21xxSerialDriver.java a092b92e118f4a8110ae7db0563d9b09df32a9c37d1a0ac5f0bc676b3ecf99fe code +androidApp/src/main/java/com/hoho/android/usbserial/driver/FtdiSerialDriver.java b23d21f835f01d27121715154489f59bce061bc4ba0f91ff5a64e17f69bcd438 code +androidApp/src/main/java/com/hoho/android/usbserial/driver/ProlificSerialDriver.java e7991bb6e284ae0d904517520d97b42ac7c982ebd9bf2edc6743a6169f4f23dd code +androidApp/src/main/java/com/hoho/android/usbserial/driver/SerialTimeoutException.java 0934207aae9dc4aee7f20d91b44c9387fc364995a746cb33f9e2f52f57dd3f9c code +androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbId.java 9aedcd07cae0bb1ea521a653e19731e2763913eee7661bb6ab0b445f2ab22360 code +androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialDriver.java ee606636a29cd4c682b4325eec27dffbba66f07eda93b8c3fd9716520dbac8f1 code +androidApp/src/main/java/com/hoho/android/usbserial/driver/UsbSerialPort.java 9729208dadbbec93b45a35132fcb1baea40257f4a7ed88d50c915475c4f4534a code +androidApp/src/main/java/com/hoho/android/usbserial/util/HexDump.java 06e0c6e28c2b6d850ff451a54660f64bf83aeae93b688c80f1cf6fba41b81c2e code +androidApp/src/main/java/com/hoho/android/usbserial/util/MonotonicClock.java 73e29449754cff976e0ab1c3ec4f890f11f6630cee1e3e164df5e3092cea2e12 code +androidApp/src/main/java/com/hoho/android/usbserial/util/UsbUtils.java b366665e94d7e4f5da6c0492e31fd63c67dcfb77ab25698dfe1bea4105d3e26f code +androidApp/src/main/kotlin/cz/netkit/app/MainActivity.kt 3767bcd1e16fa3596a5ee4dae7721b9311336b94a045d12eafe34d8bcd367a54 code +androidApp/src/main/kotlin/cz/netkit/app/backup/BackupCrypto.kt 8ec3510c5f406283f580c9ad724b7910a66a9cb7a0419b4e4423a3ece7c73348 code +androidApp/src/main/kotlin/cz/netkit/app/backup/BackupRepository.kt ea84b40c25243a45f1a07faf96b4d7c9eed90b0de6ab48b3f4d2bec44c824f7d code +androidApp/src/main/kotlin/cz/netkit/app/backup/BackupScreen.kt cfae23772131face9bed40e5fe8280d38e1dc5dc0852d4ff20bfb7015053fea9 code +androidApp/src/main/kotlin/cz/netkit/app/backup/BackupViewModel.kt b0d3df26658b394ceffc335db0549ef9b960b90cfcd660d57dc90fac717fb4b2 code +androidApp/src/main/kotlin/cz/netkit/app/backup/RestoreFiles.kt 3d05330608c68d5ba99453c02ba276463c2aaddc2b86aaca4390d30a52796e06 code +androidApp/src/main/kotlin/cz/netkit/app/cellular/CellDetailViewModel.kt 928b031e231658023959727d13e767f92d00db3eb1a414aa87de2bb0144da58e code +androidApp/src/main/kotlin/cz/netkit/app/cellular/CellInfoReader.kt 799c7c1d96d58c228fa2cdc56ba811dbb216de2168453dc12ff9de0b0891560e code androidApp/src/main/kotlin/cz/netkit/app/cellular/CellularMonitor.kt 7cfdf7985b8ab9e6ce9634ce52d8378da97d423014a2ad80c83593bb371049ce code -androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesScreen.kt 41f29530890ebd56aae237cc338163e97cf07e6de23ce2eccf5bce0faedfd565 code -androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt 95d0835e5c6b53b3beaa6bff8ec8d4773635d20dda2c479f654944e72f64591e code -androidApp/src/main/kotlin/cz/netkit/app/lan/LanDeviceNetwork.kt e4daec4112205028400b9b39907d5c0bf2fc7493f8da3757806d0a29405b2c76 code -androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt 730b7e9aefc75b38766e35d2859d622be998ea815f53fcb9757ff53ab1fa358b code -androidApp/src/main/kotlin/cz/netkit/app/lan/LanScreen.kt 514a346ba7eb8d680aaa8cb86de768bb161d192e7f936d38e55b3e72632af5ba code -androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt b8b27e6ea20d75fd3b149b206e94f18ee3c2751e8f086851a7c0d39cc1e3bd75 code +androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesExport.kt 1ef18879c42825588da37dadf4b6195875dbeb55fd043bad1cbb9b11bb613cf6 code +androidApp/src/main/kotlin/cz/netkit/app/lan/DevicesScreen.kt 8c26e3e6c956084fcec966d4cc55b2cccd1840b7548424ec6fee7747a048dc9c code +androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticLookup.kt 3bd0416c52bc6e6f1a4100fe243b91a4867e702694ed17a59a7eff7a4362e114 code +androidApp/src/main/kotlin/cz/netkit/app/lan/DiagnosticPanel.kt 4c00c4810ce2d145b7eacc504ef1c44e4a219cfb656250d2f46f186ee9bd878e code +androidApp/src/main/kotlin/cz/netkit/app/lan/DnsLookup.kt 2b3a428a3f616af65adfab09efdda383d6076449cdf3dc622d36cd5a49d6c3c0 code +androidApp/src/main/kotlin/cz/netkit/app/lan/LanBackend.kt aaf7c55e20197dc71341dda8f26ee5ec0f31cca9ee2e5399fe88949b88aea56b code +androidApp/src/main/kotlin/cz/netkit/app/lan/LanDeviceNetwork.kt e169c6dfe9a33a8e01907608b6f7cf7100e003e82f080211d7f42b55fbb061f6 code +androidApp/src/main/kotlin/cz/netkit/app/lan/LanDevicesViewModel.kt 836786ab6563e454342d8c14bd8da9b840909163266f95ece10a6fa8c5898555 code +androidApp/src/main/kotlin/cz/netkit/app/lan/LanIpv6Tools.kt 393cb02bb43a035c8ca2be1f6c0ae06f159e54d9404e199f40200e941c325322 code +androidApp/src/main/kotlin/cz/netkit/app/lan/LanScreen.kt ab33c8535178c0349827c443590d8fe188f1c2552413aa0636d109fb9885bc69 code +androidApp/src/main/kotlin/cz/netkit/app/lan/LanToolPreferences.kt 9ce4bf69a8de9520c1eb1050610ffe89a34b1f82c3b437ef244d6490f5bf666f code +androidApp/src/main/kotlin/cz/netkit/app/lan/LanViewModel.kt 424dad36383aed52b072f390ca49eb71c139136d8f6f83849098554a182426b6 code +androidApp/src/main/kotlin/cz/netkit/app/lan/MacVendorPanel.kt 22e177732383413087864ce3c6dd27b33a5c6df0ec6cb3b8f7e8e8ee86d746d8 code androidApp/src/main/kotlin/cz/netkit/app/lan/MdnsProbe.kt cd4217057b52252971788a0ec6c0fb930c00421e2182026aa50982c382185f9d code androidApp/src/main/kotlin/cz/netkit/app/lan/NetBios.kt 301d54545c9135d18b1244cd3e1bec7c4496b82ac1fff7c571ec4ac35c5f767b code +androidApp/src/main/kotlin/cz/netkit/app/lan/NetworkInfoCard.kt 8cbf70db7c073917715e4f8bbb30543f374f20129efada32e02d4f936be1a0b2 code +androidApp/src/main/kotlin/cz/netkit/app/lan/PingOptions.kt 94f201a948d313ada7cacc7661bdcf9ba5664575fdb997f4e445212fa27e2736 code +androidApp/src/main/kotlin/cz/netkit/app/lan/ServicesPanel.kt d5eb44c2ef6d8d291e8ff27db691479ef6206c7e1900d1651dd5518d83ee4550 code +androidApp/src/main/kotlin/cz/netkit/app/lan/SubnetPanel.kt 940098322c859014fecf002401c1bc1ccb0d7417e5e2244f6a6451e6a4016313 code +androidApp/src/main/kotlin/cz/netkit/app/lan/TargetHistory.kt f29952aa254b696d7b7e44cc5bc0c1b545dc6ce9156db96e448cfa45eed1e0ba code androidApp/src/main/kotlin/cz/netkit/app/lan/TcpProbe.kt 6f0b9bb3aa0630118f746859c677a7b9cee18ddf41ccf48b97a90cde76fe3a79 code +androidApp/src/main/kotlin/cz/netkit/app/lan/TracePath.kt dbebc872a184fef738a0b4e02cad87891f0f975a312519078fa4ede0065ae4ad code +androidApp/src/main/kotlin/cz/netkit/app/lan/UdpServiceProbe.kt 1f80f91f673d08a4ab3bf6b0e61aca336124ec3834a9d5a2594329cb5b239097 code androidApp/src/main/kotlin/cz/netkit/app/lan/UpnpProbe.kt a57301608240cce2c8eecba0459e21e24c1926612f61471ed69ced921046485c code -androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp.kt 902a075ff283110437da03e6079b2deaaa9602d8b24985c63e53840c813859f9 code -androidApp/src/main/kotlin/cz/netkit/app/net/ActiveNetworkMonitor.kt 0cce0cec5ec2e21ab0a4ee97d9bf17b3df9bf8ca728ac89e31995db338232d40 code +androidApp/src/main/kotlin/cz/netkit/app/lan/WebDiagnostic.kt b950181e91277a8a0d53ebb1090a855fa88412ec37c1cea4963dfa48f25c8e5d code +androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp.kt b8cb1ec2b6183f1053c2d005a9330e63fbed699b1a53ee2bc037572bcda20157 code +androidApp/src/main/kotlin/cz/netkit/app/lan/WifiIcmp6.kt 428b489264d575fc784e0ff41666d1877e65ad30cbabfa4fc9eb1f5e7d202f9a code +androidApp/src/main/kotlin/cz/netkit/app/nav/AppShortcuts.kt 3ae83014ba437dbb0d38338b4dbcef38c733beed78c0294cfe4f21a421ee84d5 code +androidApp/src/main/kotlin/cz/netkit/app/net/ActiveNetworkMonitor.kt 35d7fbbda8476b935d6f13717bbf1aa817f577a5e9acdfc44e2d80d1f96b3679 code androidApp/src/main/kotlin/cz/netkit/app/net/NetKindText.kt 9788adaf7fe405555e6cfe989ea11a3d94b16d43714b006f1747c47d24b98d13 code -androidApp/src/main/kotlin/cz/netkit/app/overview/OverviewCards.kt 7afb34f548121f2f58669bbb2de655b199988d772ab8eeac92f2bbb5b71c1b28 code -androidApp/src/main/kotlin/cz/netkit/app/overview/PathCard.kt 5faaa4c9ebd3724c7fc1ff7bc712cb6732dcc53b8fcbb76a423988145dbc9628 code -androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt 1e007277aa4090550a233b024e4f339a8bbd785c49b7f4c45ea1d16051827dbd code +androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusService.kt f15a5bcb723e9db94ef6e32dbf87b8a86acb4db1452b69c8c0956791f66cf477 code +androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidget.kt d564bdf8bc637bcf0de20df929650d36be69819a51f1308dbb6fccd75a0dc44c code +androidApp/src/main/kotlin/cz/netkit/app/netstatus/NetStatusWidgetConfigActivity.kt c3a149d6cd421378dac3be25aad6b23745e95d8c8e53b68beb8e0000b9f913b3 code +androidApp/src/main/kotlin/cz/netkit/app/overview/CellDetailSection.kt ed9c84b6453764c5c243d68895309a32c09302ff192ca6e2eb59c1be6636d5d5 code +androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportDialog.kt 547efa4b8b857c62b2b97c47fd9cc46db7c91e14f145a0ab473104e744380bd8 code +androidApp/src/main/kotlin/cz/netkit/app/overview/DiagnosticReportViewModel.kt d44809c0310d630abb7874346ac71a520a8a9c36f129d74d1737c283016043e9 code +androidApp/src/main/kotlin/cz/netkit/app/overview/OverviewCards.kt 0bc67b63fcce08c048665adf50b0d499bcf75ffa5ea957b5ecc892ae36b07726 code +androidApp/src/main/kotlin/cz/netkit/app/overview/PathCard.kt d534c7636a7101a6bfc639bc0884bca6703b6d8dc7f2dbdd7b37647be14c5454 code +androidApp/src/main/kotlin/cz/netkit/app/publicip/PublicIpRepository.kt 7abff2734117d6bf7792a09792ee89ab9edb696c0b3d6b5c494ec19f356f773d code +androidApp/src/main/kotlin/cz/netkit/app/settings/AppLanguageSystem.kt 5d3fabc3ea5ad916acc333c354709aab8635f7fbf5d43670fbacc6b52ebe12b0 code +androidApp/src/main/kotlin/cz/netkit/app/settings/OwnedOperation.kt ca013b1891f2f4cc1f663ca2f6f8362b5961836cfd0fba9efcd4d90533733a5f code +androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsHost.kt 20d1252f5bc184145cf1038512ab65270fd103b8794597cd64e31a6fa1710c88 code +androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsScreen.kt 77d5dc6b330fd275269bede918449a3f81b7fdfd22512ee8484e13bfdc53c0ae code +androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsStore.kt 70b8abd84d94a9eb5e1adaefa76f1ca3cdea79e977ee503055108c1ba34fb36d code +androidApp/src/main/kotlin/cz/netkit/app/settings/SettingsViewModel.kt af0c772e20937e0b05831569f85064464127f6e522d08a53de45a23302e1a46e code +androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Client.kt 064db97b51a507f321255994c1c12bd69430991cb65443747fcf70d15219c19e code +androidApp/src/main/kotlin/cz/netkit/app/speed/Iperf3Form.kt 465ec81f44c89a43a1a9b47e465d9772b3a695f626dfbb43f51ba9c19eb74a0e code androidApp/src/main/kotlin/cz/netkit/app/speed/LibreSpeedClient.kt cc6ee6a08c311c09b07345cbd50eed07ff11e483403fb9623ba5fdb3ff62d08c code androidApp/src/main/kotlin/cz/netkit/app/speed/Ndt7Client.kt 43a7111d92c62bceb443db0f1114c01c1ac6cd88cf3998ac94f4659b7fd94696 code -androidApp/src/main/kotlin/cz/netkit/app/speed/SignalHost.kt b21988dec54e5d4909a70bdea0d701a79a8506f6749bf52710a9bd0cbd00c6f6 code -androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedDial.kt 00e4007a1225e411086570a0ceb460be2982175fb5b56116ba679df291a18687 code -androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedHttp.kt 1892113c53bfac841c3fb94255358f919267093fa19a32631439393dea18bab6 code +androidApp/src/main/kotlin/cz/netkit/app/speed/SignalHost.kt 829d0548baa56b47aaf66064ff59e01eefbbf6310df07a9e3376763ffa9c97da code +androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedDial.kt 7cbb693ab8835c1effdab6ade766700ee2e874b3a0aecb4aa3551fbc8093a2e6 code +androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedHttp.kt fccd397488a0d02e33025927fd229f5fb1bebfd560001562fd645ae12f2b86a6 code +androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedShare.kt 51dd4a1a2140a77e950fb959f5a8200351793a0823fbe902884bc67c95d1039a code androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedStore.kt cb892b83de8a7ef82766d99e1851eaea0e3b536cf2d9ed441ab8906b7b96c920 code -androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestScreen.kt dcb8abc8db9abd820a1ed37159f0bbe8403eb3a7b052733b6ff3ce5c6c168319 code -androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt c498a15bea7291b927d20742c455d123cc2fefcc0344e06f4205fc7b5ec81fa9 code +androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestScreen.kt 33657f65810bcde4dde5c25889e2574403d34a333df95cc6b86c09596cb89c67 code +androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedTestViewModel.kt b71303a092feb8aaa2d1568926d14dae241c26f9c5c88ee87f8fc9e3a2f1b7b8 code androidApp/src/main/kotlin/cz/netkit/app/speed/SpeedWifi.kt 3e636617547c92a50a50d1ba4145168ceac909b56e3af5ba06580d70b81257f0 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleConnection.kt d7a732efeaf43f7a5cf2d3bcc8a9a8fe350ca13802b8a3dcf97b67a6acb54b25 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/ConsoleProfileUi.kt 141dc62b1de5ab356f8d5955d431f5ddffbb31bf65640b0e82eefb41543c3b1f code androidApp/src/main/kotlin/cz/netkit/app/ssh/DirectTerminalInput.kt 638ff6eb85a944a67007b84ad4b863c079289b91a1360eb9b8708bb5f6f82141 code -androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt 01b0e0cf88206c1c2c717e5146bd9b5370b6e893d2bd5496fb024bbb8326c9c0 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/JschConnection.kt af0ce27f78f512e6b88880862bf4f9a1fb0b545de722e52b68361be5e6866d4b code androidApp/src/main/kotlin/cz/netkit/app/ssh/PrivateTerminalEditText.kt 56ced6fcb79497200986f924b8a1677fadf263881164e931a265307077ad3185 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpClient.kt 1b5333440398d223058a63d0b3eb72931982046f4357701a58467b25d9d69bf0 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpController.kt 9e8f9b6a00888ac3e14d02afa9e708998f5d8d359a93cf7dca5a242c118b4ad5 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpRun.kt ed7d2df6933d58417c6e9f751b226a093561ccf860dd42f172adba6df183a0f0 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SftpScreen.kt d0b6e928ef367508214f3621474011880297bdfea0fc8616b1f7d1af49ef73ac code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshAccess.kt a4756f597966c0ed3af50c96198d431e38a468311e341c768965bb95df0301c6 code androidApp/src/main/kotlin/cz/netkit/app/ssh/SshAttemptGate.kt c254b8bd506401c2889261d36f042d95559f953f9c0c54d998e32175c050b2bd code androidApp/src/main/kotlin/cz/netkit/app/ssh/SshConnectionOutcome.kt b4ac003e783c4e54383c1185cf0f566da398b89de774c143a25a8fd57fd0afb4 code androidApp/src/main/kotlin/cz/netkit/app/ssh/SshDns.kt 2f740a884282940bdbf6b46c704a66c99348520c4bea6b50174cc7c55e8f760b code androidApp/src/main/kotlin/cz/netkit/app/ssh/SshFailureClassifier.kt cc2cacaef4999894bd07547b07471fae7a25bcefa2864fe2fcdede0f59549289 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshForwarders.kt c74f5fc5a952177f0b45b8099e4be725808d5ad0e3967d9efb57fb0b43fe062b code androidApp/src/main/kotlin/cz/netkit/app/ssh/SshKeys.kt 4708e7b0b29e970ceab3eec0b99993cd4275ce539f687bbc98b66b39bfc038ee code -androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt c289e379d5b962a9eec5e0bfc49bf6b4b2a32269fa6b59879e72329faa3607bc code -androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt e304b3e63498644fd89791abcf42dcf427888c9a94c4a37e78b032bfe431acba code -androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt 9b85c922421917cb72d441d37902ccd33f2187f1d4d727fb884a1f588480faee code -androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt 3113ee6eb54b2049718cbb79368fd157b3c6205bb486e5ebf9e3e217891a4931 code -androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt 4dbb89b04e6105ef68177159572d93dc98d48dff14b2b2ce0cd7e6be5fdd6ef9 code -androidApp/src/main/kotlin/cz/netkit/app/ui/Components.kt ae5d061ff3d90a248642c677cd5d9f2ad32810127f00ed58e0970325bdad50cb code -androidApp/src/main/kotlin/cz/netkit/app/ui/NetKitIcons.kt e4aeb04474ab6b8ff42773c2eb9b177fece3c45e2d3ed06f1e6ac506b9a46857 code -androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt fdc465b382ff6b6b4f3772008bea23ec5dc11c856404d268a4f5d35aecb655a0 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshLockUi.kt e27323923a4a655c319d5e2a626f0df8951e308ce60eab86693b5b51d5ebf2a8 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProductivityUi.kt 6de07a6056edbe40779a89d694e78dd61724e004dff47b73e60f3291c9cae3ee code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportController.kt 5946e65a1271ad18183f3ac38461fe6e669e06c7320c459aa7c92c347a14b127 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshProfileImportUi.kt 96dc7dba058fa5754e432001eac4e5811ab1e334781d64c74aedcfc911e14cf9 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshScreen.kt c686408fe79eb6a81997f26c32101173854042362481b27e86b78c853149e5f1 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionLog.kt e17b5382035074ec69457ee5a141fa71d04c9303720b90fe3d10b860b79a1e6d code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshSessionService.kt 3e5a45d53ccbef4626be66fb20dd600884adc51e9d5ed3ab2c46a656a095d4bf code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshStorage.kt 6b4e24b4c615031e9bb53ff9b51c5999db63d24848f67b214b9374d0c728b7f7 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/SshViewModel.kt 519f36be6e9302b54deb3aec19c7a2969f2e20a2fd2e2e134d31364dc4f5e0b9 code +androidApp/src/main/kotlin/cz/netkit/app/ssh/UsbConsole.kt 7cb8c566fc8f0298b774d6432b84bff38252678afa4f24a4f9aaf85c25af0be5 code +androidApp/src/main/kotlin/cz/netkit/app/tile/SignalTileService.kt 06cbd5d0c2033dfdb29d1e2d5e53589a1ac0bc0923031753085aeffea224de9b code +androidApp/src/main/kotlin/cz/netkit/app/ui/Components.kt b632f7fd2f357c0cca25c74d9b7cc5b084299677ee1bd7df915d191adda21ac9 code +androidApp/src/main/kotlin/cz/netkit/app/ui/KeepScreenOn.kt 56692a3fb8a0b9416c877aae360bdeac27b8579f871516a33c66fb7bd4b7abac code +androidApp/src/main/kotlin/cz/netkit/app/ui/NetKitIcons.kt 58bdf7b5c6756ff8ac7d586c52370c1cbe9f2514f02041aa83acffc2b1c7bd16 code +androidApp/src/main/kotlin/cz/netkit/app/ui/RunSummary.kt f145718fd352928c35ac8fb36ba22b7100521ba4f6ba20c8d9e11c0e194759d9 code +androidApp/src/main/kotlin/cz/netkit/app/ui/ShareActions.kt 97febbaf4f501ad069e18ca8ef6ac38fc34352f802e1213a4dc67f83b901091f code +androidApp/src/main/kotlin/cz/netkit/app/ui/about/AboutScreen.kt 005810f89b3e124f00663655f46fb4d40c102aab2dae27fa9e22baead2dc3dec code androidApp/src/main/kotlin/cz/netkit/app/ui/about/OssLicenses.kt 3659275d66fe1311fd82bafb4fb37be5d0056609a7dbb727ecea5bdd5cbb02ea code -androidApp/src/main/kotlin/cz/netkit/app/ui/chart/FullscreenChart.kt 0dc50ed01294e7b942bba2159d69a919d9cde96b7ebc6d6470b1375a4d9b8326 code -androidApp/src/main/kotlin/cz/netkit/app/ui/chart/TimeSeriesChart.kt 3c7aff1ce2c7785e3d87aa5631b1ba033c89535d8556576de6d8c79b2f6986dd code +androidApp/src/main/kotlin/cz/netkit/app/ui/chart/FullscreenChart.kt 61a0f5a4bd81778884c6434fb7be82de7271b6eb5b09aa0fa0a0e418c64ee144 code +androidApp/src/main/kotlin/cz/netkit/app/ui/chart/TimeSeriesChart.kt 0e81b524666f99d7dc6eb29c0b0b2e8ce32c9b678c9b00a682b42145d7c8265a code androidApp/src/main/kotlin/cz/netkit/app/ui/motion/Motion.kt 9d4fc200415ea03a0a486e2405a6ee93550835ea3079cfb586d8a6d52629475e code -androidApp/src/main/kotlin/cz/netkit/app/ui/theme/Theme.kt 7d389067b5e70b91334669524904a72dfd572b490267f51a4cd7862211780595 code +androidApp/src/main/kotlin/cz/netkit/app/ui/theme/Theme.kt 8eacaa101fd55079d37d7cc625fc782f92b17fa6787ca81cc85993bb4e9fbe67 code androidApp/src/main/kotlin/cz/netkit/app/update/StartupUpdateSession.kt a9b91564d03366a2b9e80af4b3f3d7adb450e39cdba3db125a2495c19bd9dd16 code -androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt f3478a034d16c4d22ed6d3f854d2f0547b8862a0cea7b7a32d1047d5d6e62d47 code -androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt 092d56c6a84cc2afe0ef86412cb144b30ac4b6d4dc103c46bad1c3663e6b53e2 code +androidApp/src/main/kotlin/cz/netkit/app/update/UpdateCard.kt d616fbd6dd04ff2e46158d3adaf6a0bc043e51b4325980a3c235dfda2b4d2ec9 code +androidApp/src/main/kotlin/cz/netkit/app/update/UpdateChecker.kt 97fbbc86ee9e0c451d723b96c9d49100298de7a88f57865820b301e49d1b5eec code androidApp/src/main/kotlin/cz/netkit/app/update/UpdateDialog.kt f1362d1e615ed8d8b4b6606543927f616d6f909136dc09c2f95323f64f375206 code androidApp/src/main/kotlin/cz/netkit/app/update/UpdateViewModel.kt e09327a22a898f40178466679b702cfae2bccd2689627b5d07c2ad31df36509c code +androidApp/src/main/kotlin/cz/netkit/app/wifi/ExportSession.kt 58de499f12744d63b89e18d741cca0962cd619ef9ff6822022ae999d1586105a code androidApp/src/main/kotlin/cz/netkit/app/wifi/ForegroundScanObserver.kt 5f248c2720c1813b8ac2fd9bf4d2a49d671d5533d5ebe0189c16be47ccd6be0f code androidApp/src/main/kotlin/cz/netkit/app/wifi/OuiAssets.kt 206ddbebd60edeb62bfb6137179531bb63ddeec225b786a9ae0223b3f6bdf79a code -androidApp/src/main/kotlin/cz/netkit/app/wifi/SpectrumChart.kt e8b4bb619d04caa1f9e3c7e600e6e4873ebb8c255989c1cb47971a82cd3d74c4 code +androidApp/src/main/kotlin/cz/netkit/app/wifi/SpectrumChart.kt 6d2236eff7b69e5b30094188432777077a3f70e11dd6dba8898c8445c9960e4a code androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiChartPalette.kt 290039abd7f9a60a0ae09ee08234daf9b115252db9f4356959831430c35007cb code -androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanBudget.kt 37660b10b0a2eec240116dcc95f027f24a05638966115472327aaacdf4b0b5c4 code +androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiExportFiles.kt 96349a754f712980b2b5767d5120813803b45dae58298c546ac5fab3f2d88023 code +androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanBudget.kt 1fcd95f757bb972785fc719e758389c070cb3caefd12a717ac99ad30281d0267 code androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanEvents.kt 71bfb17d312841d3cc4ca96749fbeedc1deea5df63952a3f25eddaebe32fb437 code -androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanLimitHelp.kt a95f6d6f818d46164d7971fdf341320b58e795208ef45671e19839831334a036 code -androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScreen.kt 7607c2b66bdc963fba3d33f696d0a2016eab119edcc8e0c29d2f5efe16c6b414 code -androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt 515562b654c80bf660d525819f80c8fd4860bf87d823a7a98895e6e268657b12 code +androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScanLimitHelp.kt b44301b3aa528dab73e93fa87c4f94b041832049391ed847c7fb18dda0245ddb code +androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiScreen.kt b3bac6fc3638237d816d5089bb367b2dc6b8c97a639a70a1fda1b8e30bc92a3c code +androidApp/src/main/kotlin/cz/netkit/app/wifi/WifiViewModel.kt 181e152bc4fde5cc955931d71c2f22de833ba894da3cd5f486a38abc5ba12b7c code androidApp/src/main/kotlin/cz/netkit/app/wifi/live/LiveRadioSource.kt 45d73a0d5ac23e93dae757f2c6f6309e76fe84a5f9ec090d39d923789cf9390e code -androidApp/src/main/kotlin/cz/netkit/app/wifi/live/SignalScreen.kt 1d47aa4133625039913f039d9b2058861c481df1ae89c5d47f02c8072b0d4aba code +androidApp/src/main/kotlin/cz/netkit/app/wifi/live/MloReader.kt c95c7f9a44343a36ba727c0d6e3b74dd7b2d2e5fff748f8eba1ea4581f9f18f0 code +androidApp/src/main/kotlin/cz/netkit/app/wifi/live/SignalScreen.kt 2f8518ab48ee121eecd99df03588181e1a1f629e1f8bed1e264b6b0d24433ff8 code +androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WalkCard.kt 1ed3c8e2078cc4cb77ede5c0b34e59a34dcefad2c94becd05d4094a1cb4a29df code androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLinkMonitor.kt 2987c5534ca8cb878a9f27d6d5c1d4c926636de25677dccccf274312ae7b4927 code -androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveState.kt d8ef2922dde3e2eecc6e16fb82a30503aa99028e364e028922c28ab6b7778ee1 code +androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveState.kt 14fb58b0f7f4a615b60a0c0b733d348408803d1e76f9777e8ff1ef7df879705a code androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveStrings.kt d726ab12dc87898ae22e46dc6d1d42a832cc3986deda767b06a8df5bf829bcbc code -androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt 752b7a8b55130b95b77e23c3c856698c6e2b035212c332692afa2e2025d0b5cc code -androidApp/src/main/kotlin/cz/netkit/app/wol/AndroidNetwork.kt bfa0b62313cdf4cf7ed42c06e6b040aea90ee99259cf4dc92997fdd47e577192 code +androidApp/src/main/kotlin/cz/netkit/app/wifi/live/WifiLiveViewModel.kt d219c7d389aabcaf2eb4d621d75940b5fcd0fd5bae8037d342a7ef97e6ea541f code +androidApp/src/main/kotlin/cz/netkit/app/wol/AndroidNetwork.kt 30fb154d140adf9b1087d4c810ac432abc0133d199e79ea237a41b55e3b8843a code androidApp/src/main/kotlin/cz/netkit/app/wol/AndroidWakeProber.kt 69fbff76bdfafbb37675555db407fdfb00c1e05548158931949eb8cce3fbfc35 code androidApp/src/main/kotlin/cz/netkit/app/wol/BoundedStreamIo.kt 5828a7882698fd69d8dbcb5ed2471de99646405c043751004b650171d3fb3040 code -androidApp/src/main/kotlin/cz/netkit/app/wol/DeviceStore.kt 488c12ed72de846aa461f5849d8365754560774ad604d1d86e4ffe89c4d89358 code -androidApp/src/main/kotlin/cz/netkit/app/wol/UdpTransport.kt 33a920967e0a8c7d326043f0c51263555d77f1ad906a85456f4807159d39bc74 code +androidApp/src/main/kotlin/cz/netkit/app/wol/DeviceStore.kt 9433c889f320aae4daf348d2d11a3a03dae8171a524cfe4b30c6e20fe76b7fb9 code +androidApp/src/main/kotlin/cz/netkit/app/wol/UdpTransport.kt 80d3037458e2169cab723c832117dd8579211737104376b39b4260685eb1aab7 code androidApp/src/main/kotlin/cz/netkit/app/wol/WolNameOrder.kt 5f3b33e9bd5ae9c0d465b336fa8a08efefe01bf9df6ed4e4e32dcfacb1929df7 code -androidApp/src/main/kotlin/cz/netkit/app/wol/WolScreen.kt 7ee5f4d6f43407fbf658dfc6151bd0df2d1b9bfc15c439dcfcd242f002d7238d code -androidApp/src/main/kotlin/cz/netkit/app/wol/WolViewModel.kt 349c8ca41b771000959d51a58f34fa1dabd5ae3b7b9538b4e7f28773ee356a5f code +androidApp/src/main/kotlin/cz/netkit/app/wol/WolScreen.kt 55ae85e1baf37f3309132d0a47f19e160dc02a7a047bd36234a0b754825d1f4e code +androidApp/src/main/kotlin/cz/netkit/app/wol/WolSecureOnStorage.kt 9c143751909251ea48e31d8bc395ab1aa804e8333184164286dc2ec128b64ff7 code +androidApp/src/main/kotlin/cz/netkit/app/wol/WolViewModel.kt 946e3b54be6e4fc8e8f901746d22736a6d583c11eb029009897a9482664ebd6a code +androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidget.kt d39c4e4142052a63b0e567998ee3454bd97c0cf76f18231e43ecd0c991ae133e code +androidApp/src/main/kotlin/cz/netkit/app/wol/widget/WolWidgetConfigActivity.kt eb0328bbb26fa48eaf64251b399ecaa5445fba1ad6ed80efc08bcf5d4f4feabf code androidApp/src/main/res/drawable/ic_launcher_background.xml 2ae3e1d388ed6d88fadd55c0fd4c7ebced62e5c91a870756a3b7fa5a8b7bedeb code androidApp/src/main/res/drawable/ic_launcher_foreground.xml b0791a9171e3d795fbb398bb85feb6ec1464c10748914a7e90db3629d9f2ce54 code androidApp/src/main/res/drawable/ic_launcher_monochrome.xml 3677514da9ebeba6330e6a77c98608788339478098714f2e23517634fb8044b9 code +androidApp/src/main/res/drawable/ic_notification_ssh.xml fff147875f812f5f1a0bdba397663904a667a9d4997f3a72073b5977d7217c4d code +androidApp/src/main/res/drawable/ic_shortcut_background.xml f519ddc930def6588d2fb10fb50308d517e0d8153f32633c91c38725590bef52 code +androidApp/src/main/res/drawable/ic_shortcut_ping.xml 4cbc6e435335c0f7ee2b7deb173b9ab7d398825784519edcf32c3a5ba2f97e38 code +androidApp/src/main/res/drawable/ic_shortcut_ping_foreground.xml f962913fea170e0979f17a37dfa7b84e490c4b7d365e5d175e9d48da48d90300 code +androidApp/src/main/res/drawable/ic_shortcut_signal.xml 1153a89e8eb277039c1239ec84c0ccade5f5fc681a591c3b0555b505c7bf32b4 code +androidApp/src/main/res/drawable/ic_shortcut_signal_foreground.xml 0b5b8999ceb9119b1e45e6757c70590f6b6b66c9a7050ec391e2a6c1a958b842 code +androidApp/src/main/res/drawable/ic_shortcut_spectrum.xml 526bf61dff5262630078349708e0eaa11ad2ff3b6b94970e74ad537ec9778eab code +androidApp/src/main/res/drawable/ic_shortcut_spectrum_foreground.xml 05a3b5e079cd86d8a6f23014c6dee49d732fd4fdb87632b71f97093e3227fbfe code +androidApp/src/main/res/drawable/ic_shortcut_ssh.xml c76400d6dacbb3c28076a9a97b24d7780206b7667fd4b29b0fcab097d207d579 code +androidApp/src/main/res/drawable/ic_shortcut_ssh_foreground.xml da01fef57c92d911746dc0be4b257f4fe3dc73657da349071234033643eb972c code +androidApp/src/main/res/drawable/ic_shortcut_subnet.xml 944b8963de5069d356e76b74b3d277fe88897429745238a9083c25a98e507265 code +androidApp/src/main/res/drawable/ic_shortcut_subnet_foreground.xml 0660fce792039fc70e8e429b60216995d284f1b6f7546fd04d77bc21e91533d9 code +androidApp/src/main/res/drawable/ic_shortcut_wol.xml f16ffd7ffaee191211579a7d9c2fa0a25cbb3cd4b6632311ffd134c8f567f54c code +androidApp/src/main/res/drawable/ic_shortcut_wol_foreground.xml b58a43ad025db8c525734069fa481b913ab73d1022cbb27471aa6bcc2546d0e5 code +androidApp/src/main/res/drawable/ic_tile_signal.xml a8d2960cb14b4f128c19bfa5f0786b49f3020b491fb7141f9a9d6307b858f6ad code +androidApp/src/main/res/drawable/ic_widget_refresh.xml 11603e0e17410dcde99a41ee8a873de6244ae4269bb94ac1f1fbba9c4a02a159 code androidApp/src/main/res/font/jetbrains_mono.ttf 48715a42ec242c21e9f02692891e147d022299a52e48d5e413e1a942193ffeda binary androidApp/src/main/res/font/manrope.ttf 3ae11c49db0455a3cc33e37d380f20fdb8c7f8b41dc07625c177e3d87a9d6ae6 binary +androidApp/src/main/res/layout/netstatus_age.xml d4f5b3ef58d777ea7f59e8179bdef779b67e1001f32d63a871ebb85fd3ce83e3 code androidApp/src/main/res/mipmap-anydpi/ic_launcher.xml ada31da9e23f4520f3753e71ca23799a107431473daa3774b6cecac26847260c code androidApp/src/main/res/mipmap-anydpi/ic_launcher_round.xml ada31da9e23f4520f3753e71ca23799a107431473daa3774b6cecac26847260c code -androidApp/src/main/res/values-en/cellular.xml 775afe58c7bdf75313a01f2e5a9505cc6bea80c5e2c84c4b57506cf974b9644b code +androidApp/src/main/res/resources.properties e2072a954cea4329202abdaaf2dd0d4ca3d4c51bbe23d14bc80a15665ae1334f code +androidApp/src/main/res/values-en/accessibility.xml 6c8d6a7b732650429e9e9d651f7bfb7d97b092f9c4fb461ddcc52f2d778f57fc code +androidApp/src/main/res/values-en/backup.xml 2d1fd473e0000b75bb2fa74e145b0d8abd9a08e7078b0498fb82219d66348283 code +androidApp/src/main/res/values-en/cellular.xml 3e27fb3a44b231e4574bea2503350683839a0873e70b4816abc2559d0b478490 code androidApp/src/main/res/values-en/chart.xml 043b40fedc9b4ea70ab089dcfb6af1a981ceb1ff2c2427d664aab1215d9fbf56 code androidApp/src/main/res/values-en/lan_devices_ui.xml 6f356f2df529bdce566036efcab09e9e44e22db5f0465d72fe9f6677f213aba3 code androidApp/src/main/res/values-en/lan_devid.xml 74d9c855df56c71403cc4d06fce9f9951a793f24fcf695c5e819d0d87e4a883e code androidApp/src/main/res/values-en/lan_revision.xml b9111048bcdca5969f03ecd8a826e0832722a63a7246d9977d21ed5fb2fbfb61 code +androidApp/src/main/res/values-en/lan_rozsireni.xml 610ee65bea209446539024422a7286f0fb53121c83b20aee8b392cf397ba0253 code +androidApp/src/main/res/values-en/lan_wol.xml 91d40bb738327b2edbc28cf9fc44b97f41b0ecc0822907ca9151e98a603ad327 code androidApp/src/main/res/values-en/nav_m2.xml bb81c70c62cb525b5775c4d020c5569a11fec3621b9ac3d76c30a33937cb82eb code androidApp/src/main/res/values-en/net.xml c588dc9197b23ee9c7f960878a8a3705f7e3b4b362d9c8d21204ac39b4ca8749 code +androidApp/src/main/res/values-en/netstatus_widget.xml 611a57322ef4d97cb4b7ae921aa35481907afffe6fc306d82b755ab3f72c43ee code androidApp/src/main/res/values-en/overview.xml 4ea9c29beaef958ff433f6f95a7dc4082a18694d8d4d0b780db1eec684a178b2 code -androidApp/src/main/res/values-en/speedtest.xml 7814880fc8464e34764bc871ba0cb1b71ae99bbb06f0b131278884c1f2318e1c code +androidApp/src/main/res/values-en/settings.xml 1b8864c15a7d858e601c7422e7478c743c307998c57e0485c4ea235fbdf609e6 code +androidApp/src/main/res/values-en/sharing.xml 73274ed772604bc18c4e98bd1afa1905b0483dc313f1f5ae24195b7edb6ae520 code +androidApp/src/main/res/values-en/shortcuts.xml 0d4dac5fb1532d616340099e061cac681f5157976e65fe495c86c0dfee4a70f3 code +androidApp/src/main/res/values-en/speedtest.xml 0e383a7abe134198ce281bb27f8c45ec7b9bf124bd644cd53a955ff1d611c48b code +androidApp/src/main/res/values-en/ssh_background_sftp.xml 051b77160aec5b6f9a0e1e0d6da895d3569b4ad5206e4ed96ecc61d68c561159 code androidApp/src/main/res/values-en/ssh_closure.xml 46589351e503111477035baca6bc19beb9c8bd910b0ce743dc68871e8a9170bd code -androidApp/src/main/res/values-en/ssh_design.xml ff098c275a1c9b001119c3b16ffd36773fb06aa0715920201a6f48af525799ba code -androidApp/src/main/res/values-en/ssh_import.xml c3bec543dc25ad8bb5a92b5ccc7f8c4de1a92dfa8693f6cb00bea4398cad14ad code +androidApp/src/main/res/values-en/ssh_console.xml 7de7333f67e6bca48b68ca626cf9f35b3b054c93fa1fd34c74b612957f7009b5 code +androidApp/src/main/res/values-en/ssh_design.xml 109b7c30dc77e48a4e0a1a99b75c7959f4852113e9973ce1bb29c075c8b9b7c1 code +androidApp/src/main/res/values-en/ssh_import.xml bc4e6c5448af88f2d52c9425cc974eae10adb77c7348a1cb0eeb484b1197e16e code +androidApp/src/main/res/values-en/ssh_productivity.xml d2f81e6ddb43fd5355a3e82dfb05e02665ab5a9d694637403f97e242d3b9d70e code androidApp/src/main/res/values-en/ssh_revision.xml d35234edae2c0af87cfca9c00ba9fe086bb722e44c602a018cd714bb98f3457c code -androidApp/src/main/res/values-en/strings.xml 5dc7556992bb1e231c8fd5c096c227a301661a03b03b613731fa441ef946f4b5 code -androidApp/src/main/res/values-en/strings_lan.xml a1e698e3bf65f3001bd6171bab7765bf0f65aff2aa04623d04408c577ed2df38 code -androidApp/src/main/res/values-en/strings_ssh.xml abb91cd3e33e613c43add7eaf1732604ece7579c253410a1dd98746f59878606 code -androidApp/src/main/res/values-en/strings_wifi.xml 2d0ea239bda43b99d6eb43f573fd4bb0465afbb830ff2f90a1ed23873182433c code +androidApp/src/main/res/values-en/ssh_terminal.xml 2be76cc2508a4ed3e8dbe8cf97e2aa697854cf193669b5628af25980542d4525 code +androidApp/src/main/res/values-en/strings.xml 4cf17fb4a4eaf742a241b97627aab448108bde210ae2534dbabd1dc2edfddc5a code +androidApp/src/main/res/values-en/strings_lan.xml abe67cb512b5701b2d9ee73d3ee059dac450d048fa9b8cce28f33bbdc130818e code +androidApp/src/main/res/values-en/strings_ssh.xml d20467976a19215837b2b64dfe963a0c3782971f8c61186f00988c1915c2661f code +androidApp/src/main/res/values-en/strings_wifi.xml 39b48c64a0d556393533fef35a7595dd5397f3b6a1d54ffab9f41037f3d14133 code +androidApp/src/main/res/values-en/tools_targets.xml 34f145efedde279b6a827212d2df06e5463244060c09599de6e4d33d918d741d code androidApp/src/main/res/values-en/update.xml a83e8242fb450bd259023877f90337cb4e0b423cf6d6dc264b8366c6bfdea3ed code +androidApp/src/main/res/values-en/wifi_ext.xml b00a3125635cec8d1845643fc244b3344d414587ef19464f76c3b9424e643b9b code androidApp/src/main/res/values-en/wifi_revision.xml 051d370fdbb726ff221dc76f907735a8c7a691756d454b2ff2fd7a98665fc97b code -androidApp/src/main/res/values-en/wifi_signal.xml 8cbcc723bcabce6312290b4e119097364dc3b90a9296dff112e5e5bbe82a1d62 code -androidApp/src/main/res/values-en/wifi_spectrum.xml 478a2b98ba61332ccf15d97b864fb82381ede2391fe2b11755bea26efbf40d68 code +androidApp/src/main/res/values-en/wifi_signal.xml 4b232149b3c9df2dc5a5799f4f83525a596debf610bdbff7a6071b50a65dc883 code +androidApp/src/main/res/values-en/wifi_spectrum.xml 3473987bf37f2b1fac0a2a8e363420ce109687f451cd5d5edf428e1be7bc72a8 code androidApp/src/main/res/values-en/wol_closure.xml af2e4b3118aff7cbe771ea7d72b8146f5fe388e1d75ec4aa10f295e6b4b53dd5 code androidApp/src/main/res/values-en/wol_design.xml e459d91392b192b5d582d14c145a287883eb1cdaaf8343258f2c72e4e400872a code androidApp/src/main/res/values-en/wol_import_csv.xml d9cfc766b8313be192f6bea54a4349edca96496dc820b6ba00786e0629d312fe code androidApp/src/main/res/values-en/wol_revision.xml 4294450d605f82586847f59de0d1fc3559771a67a2afb3abb1d2df4b3e956c63 code +androidApp/src/main/res/values-en/wol_secureon.xml 53b5404c4ea13ec2942f2bda82e408d19858aa8bad5a07c446c7b6705a313ca1 code +androidApp/src/main/res/values-en/wol_widget.xml 7b65f8645512043a8d6aa1d6119d863735ab06bfc02282fa51c5e568c13e6f36 code +androidApp/src/main/res/values-night/netstatus_widget_colors.xml 5483df923be27b452ffd10caed7d64271577fda56eac7fd8027baf0dee063787 code androidApp/src/main/res/values-night/styles.xml 4eb365659c10d6a7cc55cfe60d8f518b7626a138a64ec01c5620aad36301e67b code -androidApp/src/main/res/values/cellular.xml 6cd0415df1cc6b219eb455bf033a1c521d61a9c6001d6d9070ee6accb1e7b95d code +androidApp/src/main/res/values/accessibility.xml 7498701c4f21f5fa74b05fdf0ac1dfeae49652deb0a93f186f996f80772dc2ac code +androidApp/src/main/res/values/backup.xml 0d1d07b0fe94099910c8d6cd38aeee9bc15b35fa30f0105b6614ad959ec2008d code +androidApp/src/main/res/values/cellular.xml c638c24a892727ddfe5110701c01897e9babe21f441949d91726549c534f3522 code androidApp/src/main/res/values/chart.xml c478120cfd7b8e965d5518bd274d5d578c2f64300d4f874a73318550a16de110 code -androidApp/src/main/res/values/ids.xml 3fb9ba459432a58d4994ca7b4f77375aba97d649c686da0400c19b2b0e7d5069 code +androidApp/src/main/res/values/ids.xml 6bc4e722c8c30941e9a090e78000120dae15580af98b747ec4f0ac2f63bcbfaa code androidApp/src/main/res/values/lan_devices_ui.xml 0d3e03ee24e019ee024757dc443d07973a3b065931206ac4bce4cdeb1aa16c2c code androidApp/src/main/res/values/lan_devid.xml 11d2645d3e38e9df8f748e8c13d47a733bc68e866374fc573cc5d1753285a600 code androidApp/src/main/res/values/lan_revision.xml 49e66ae698760f00beb466aaef7c7e536a4a5025e701c2b3a0bd9e7c1a5e5829 code +androidApp/src/main/res/values/lan_rozsireni.xml 8a7a2ec229582279ec33580409ff81f1198bbc89024b28c378db5f20837feb78 code +androidApp/src/main/res/values/lan_wol.xml 19d0e200c000e0855c273960e932965c31eed00282f6af39682bfa86292f0ec6 code androidApp/src/main/res/values/nav_m2.xml c511d8ca123e2a284843c452cca7d5cde7375fe2dc94f9c0be029f4fe6f76930 code androidApp/src/main/res/values/net.xml 4b8755bc602231170660c60b14d52550a1a1957a09518e580090350925d7b7f2 code +androidApp/src/main/res/values/netstatus_widget.xml 0799700a4d3613fd215374a642c1e7d5422290e80ad733c76405925fdffd4ee2 code +androidApp/src/main/res/values/netstatus_widget_colors.xml 6adb81616826d01a194b150c83d1b9410699667143a0dd6ae0c431165f4e461b code androidApp/src/main/res/values/overview.xml 05265575c592ad0012237a1286dd90a170ae1cd27cb9e526081880b750835a82 code -androidApp/src/main/res/values/speedtest.xml 366bc645c1adb6a89f40c51f50fd17a57668e00a66bdaab88fb49187a7ac94e0 code +androidApp/src/main/res/values/settings.xml ee59e477d59a2222f9cbc372ddc0c437a276f1c4ec8c50a88ab97a253e92bd46 code +androidApp/src/main/res/values/sharing.xml eef10b3db2db88e845966e4e2f7c58dcce39e655b9cbefbeb264100027e106fe code +androidApp/src/main/res/values/shortcuts.xml 83545b74d2c731597e143cb19832b822d89d0ca3dbd5b6ef1f10617771f369bd code +androidApp/src/main/res/values/speedtest.xml 9bbc1618ddb6ec2414dc4f20eb6308b801cf630f7d213ee192a34f08d4f9be1c code +androidApp/src/main/res/values/ssh_background_sftp.xml e819458bfd57a2d772c0832d071db5d6fa1d71c2c09b4a912a687aae5248c410 code androidApp/src/main/res/values/ssh_closure.xml 8576c9776d5841b5a69a89116492a72604f94167eb3cbefc255b394a3a55568e code -androidApp/src/main/res/values/ssh_design.xml 8d191f319dab350b724ea53b6c65c9f71df465cc98f7dcd3d23a2dfb2842f971 code -androidApp/src/main/res/values/ssh_import.xml 7545ab6621a7330a495f5ca922bafd31646d59978adec29151056eaf4b62459e code +androidApp/src/main/res/values/ssh_console.xml 53ab6ba532cba63e73b6f74404e7cbbb851b3bef8d5442577cab20c8d606aad8 code +androidApp/src/main/res/values/ssh_design.xml 36fd7e8a164bebda28057529dd2c627f84acee31eefcda5eb5be3738c5b71aeb code +androidApp/src/main/res/values/ssh_import.xml 5ec7ffa6695b461b08ad1f655a3513bdb5d16636696cf2637f9bb0171819a17a code +androidApp/src/main/res/values/ssh_productivity.xml 449b70f1de1177b8ce1b288038ce1ddd7737bdd0ecea98e738c70f3f4dc404c3 code androidApp/src/main/res/values/ssh_revision.xml bd4010b02ae6638e40e4d708d09252a77a5907e48086e34abb43e68c36fcdba6 code -androidApp/src/main/res/values/strings.xml e9ede585555690ff9075ddc62c6dee8e3a86aed6180a1416464ff5aeb3334559 code -androidApp/src/main/res/values/strings_lan.xml 3b9a60c77ff521544df36b7e5e9928e07fdec129551508f88184760b950db9d6 code -androidApp/src/main/res/values/strings_ssh.xml b7af71f5bbdde4f9a47258fb5a86db9b238efe488cd42375b51164754d3b4744 code -androidApp/src/main/res/values/strings_wifi.xml 105ab746f531e5aae4960c4850e2124e7dad984b0be803d53a892a13050ae345 code +androidApp/src/main/res/values/ssh_terminal.xml 8ce271c10df4d392995dd1aa93ee4ae867df1fcf8322dc3f3636af8ab7dd3c96 code +androidApp/src/main/res/values/strings.xml 6cd221e6ec04f5376fb0e84c4d1e66547a69b48ff3140ddb29bfa853d7987862 code +androidApp/src/main/res/values/strings_lan.xml 61406f62853709fa5eb909bb37c3142873dd4f162c1eeaa09ad8ea08619835a6 code +androidApp/src/main/res/values/strings_ssh.xml 3a7028c7c7629ad45885fddbc38a1791403fd3e6d4a45b0f202ee584bbcdb1eb code +androidApp/src/main/res/values/strings_wifi.xml 72d07e822aa8814874d13206fbeeb655ec2f7e4b59f622f76bf9595ba4cefc69 code androidApp/src/main/res/values/styles.xml cd4b308efe4098adebe102a7be8635a4bec442bf9d2776fc53e44fe28efce88b code +androidApp/src/main/res/values/tools_targets.xml 13200fa18511b30d7922ed2bf25134dc52bd1a2feadc19611f2a6745c8d2e66e code androidApp/src/main/res/values/update.xml 9c784f1ef95a16d7deef29bb6b1d204d1d3f3a58388af6e289298e383f6ab1da code +androidApp/src/main/res/values/wifi_ext.xml 6800de6b622733bf1c8217a0712f5afc8b197068016409a54185aa87e56f9e1f code androidApp/src/main/res/values/wifi_revision.xml 9f4c341afef2d1bd780be13fe2ad1b5bab5c74fe6de1c2591dfc5d1014a2e2fa code -androidApp/src/main/res/values/wifi_signal.xml 355b316b1aeb81f04031bfad59473d537c958d679aa18148e7d4409eeb85140b code -androidApp/src/main/res/values/wifi_spectrum.xml fdd4690ee0b2459d445930d8110f95d86debbd2672a1651883b5994bb42c414c code +androidApp/src/main/res/values/wifi_signal.xml b766b516921ef34f2e67b5df8e79ba8e1442495e45ffc13979e8939ca461f9a4 code +androidApp/src/main/res/values/wifi_spectrum.xml 65c5280f8b067a65a84016bfd9e5a151523a6a2f647ae509bc4f182a8437b6e4 code androidApp/src/main/res/values/wol_closure.xml 3bf2969bd33fe4bddfb97abc51d7341cd92aa7d5eda17fc5fc4012c2205de925 code androidApp/src/main/res/values/wol_design.xml ea6710a863941e7e086bae4ce0eb1bcceebe7ef594d90690268f5fb1e9e95937 code androidApp/src/main/res/values/wol_import_csv.xml 1f2a0f53db5a21dae7512c886e2ede7a6b2b7fe6f9be359c7646ae37b6ee611d code androidApp/src/main/res/values/wol_revision.xml d33274f78f65c3add118efafc685fb4527b8231b19e780c911ede3cbb738b770 code +androidApp/src/main/res/values/wol_secureon.xml 567ee2438a4eb085b35f26ee825cc5080235254e95787b039e3fa0f472379697 code +androidApp/src/main/res/values/wol_widget.xml 434434aab46e9a8d66e0b8dc04fdbd0aa2dfab0294dfccb1d2548bf0680bdc02 code androidApp/src/main/res/xml/backup_rules.xml 865cae97840e81b9950d70457a05c5c1125a68364b0a83f44cd3daa030bc7e96 code androidApp/src/main/res/xml/data_extraction_rules.xml cb029b35db0e976c087100424e16e14a6256b46962398887520e51508c3b5842 code +androidApp/src/main/res/xml/netstatus_widget_info.xml 08e7622edfe23e367999c82ad40e8a7844aa60b60d6ee2fdd0b2a22e1d2297c5 code androidApp/src/main/res/xml/network_security_config.xml dea35ebed76536c24c13f74036f02dc874f944147cb3a49c2ad0550f71e3e0c7 code +androidApp/src/main/res/xml/shortcuts.xml 9154c926c7f9eb1b3240e4e0bd005bd93ccb5c6d1099c5f021bce23f20c8732b code +androidApp/src/main/res/xml/wol_widget_info.xml 6b2ec46012c7776774a54833883a5a888e8801a1feb10811fee2f7cb6ec1ee75 code +androidApp/src/test/kotlin/cz/netkit/app/backup/BackupCryptoTest.kt 0c4f8a2a516ab1cb71cb8a6c13298022617564956d27bddf1e2922cf8bc55a38 synthetic +androidApp/src/test/kotlin/cz/netkit/app/backup/BackupRepositoryTest.kt 5dc94274a962c7460fa74924324af5fc515f1d227914e407feb89ee17c7e0a66 synthetic +androidApp/src/test/kotlin/cz/netkit/app/backup/RestoreFilesTest.kt a41b64f559c5bcb2cfcd0f6b2f101ef2d85bd5b4429f0851a41d2c3eca5d93d4 synthetic +androidApp/src/test/kotlin/cz/netkit/app/lan/DiagnosticLookupTest.kt 3ceb2866ec3009cdde51eac92c7273a9e9ac04d1c4e6eb94c154be9186277882 synthetic +androidApp/src/test/kotlin/cz/netkit/app/lan/DnsLookupTest.kt 21455eb321d1fb9043b672b532eb38760bcea977b3e88da324946e9abfc1e58c synthetic androidApp/src/test/kotlin/cz/netkit/app/lan/DnsPtrTest.kt 115857c7fedc9a068f0c5535b414e711fb6952f12cf31ad4877a920be3844cbf synthetic +androidApp/src/test/kotlin/cz/netkit/app/lan/LanIpv6ToolsTest.kt 97fe8e35abb9a765dee7840002429d18078767eb68dc1300f8e169d8f926d8d7 synthetic +androidApp/src/test/kotlin/cz/netkit/app/lan/LanNetworkInfoRefreshTest.kt abd5622345eea613badfee1c4f32a43de73af3180d4bbd102dc97536f4960760 synthetic androidApp/src/test/kotlin/cz/netkit/app/lan/LanSettingsTest.kt 4264006f52f2224199328047c9d3748cd475b707d6a572fcf4ae111faa685a64 synthetic +androidApp/src/test/kotlin/cz/netkit/app/lan/LanToolPreferencesTest.kt 6a9103cac59207445232b9f1d35b58755d058a89f25ba25590e48a319fb3c45e synthetic +androidApp/src/test/kotlin/cz/netkit/app/lan/PingOptionsTest.kt 5a1e849adbeb11d9d73c0a598059378413d7d16670035ec68d7d5aabf6a04065 synthetic androidApp/src/test/kotlin/cz/netkit/app/lan/TcpProbeTest.kt 2e0d134cb5ad81c8ed7da9842813569e3c0dbb5b69f1522c104d10e10e75a882 synthetic +androidApp/src/test/kotlin/cz/netkit/app/lan/TracePathTest.kt c3f19b5b1db45d1df43beda73e3065ecc38c5a32738ea1bba1470f0b70425ece synthetic +androidApp/src/test/kotlin/cz/netkit/app/lan/UdpServicesFixtureTest.kt 693546d8e7324dd34e0cd7ed72e83f6dce10afc82d1b7e36bfd4b15d55058699 synthetic +androidApp/src/test/kotlin/cz/netkit/app/lan/WebDiagnosticTest.kt 61a250a476ed4f1fd4e6b42a3c5d9b11655ab494e542895d178fb5827c607b84 synthetic +androidApp/src/test/kotlin/cz/netkit/app/nav/ManifestExportsTest.kt c3da9394c172508b076b50675d26debd130ca3e3abd7ab7ab236eb0615163278 synthetic +androidApp/src/test/kotlin/cz/netkit/app/nav/ShortcutResourcesTest.kt bea240a4a895f739268a66ceb81442c47f456f8864146499ea0d44a03bd382b8 synthetic +androidApp/src/test/kotlin/cz/netkit/app/netstatus/NetStatusWidgetTest.kt 3212b0b69213d2a22d29b4cd760342fa9e07d60c83bfe195f0b17d9ad732b18e synthetic +androidApp/src/test/kotlin/cz/netkit/app/overview/DiagnosticReportInputTest.kt 76f5e67a8d59262802cc52a3746ed820bf3dcbedd4621c612e2100735f3b276d synthetic +androidApp/src/test/kotlin/cz/netkit/app/settings/CzechLocaleResourcesTest.kt a97c7d5d3525179fa6c8ebcac7cbf1c65e81a0022e7ed99c58db722e5641e2a8 synthetic +androidApp/src/test/kotlin/cz/netkit/app/settings/OwnedOperationTest.kt 3c8840720d43bcde964411add62f62601c3ca1cd8a0952035429129789b8ded0 synthetic +androidApp/src/test/kotlin/cz/netkit/app/settings/SettingsStoreTest.kt 66d3dd25c48de2bab6a52366850fd93d87a181450d5fcc29d4557e6046eccd3b synthetic +androidApp/src/test/kotlin/cz/netkit/app/speed/Iperf3ClientTest.kt cdb4b04744ae6cdb06571a8e633343c5ea29b1eaecc16fefcc74f5ccc19e91f1 synthetic androidApp/src/test/kotlin/cz/netkit/app/speed/LibreSpeedClientTest.kt cf2802c447d63e1d34a2fd3992d01e8f58308492ae5524ca7eb9b30ad9c4f0a3 synthetic androidApp/src/test/kotlin/cz/netkit/app/speed/LoopbackServers.kt 3b617c060fd1c422fb5a9cd5ffaf250f2c79dc3ef09145f000bf6e35d4fd4ee0 synthetic androidApp/src/test/kotlin/cz/netkit/app/speed/Ndt7ClientTest.kt 34abc1d1103f76eb19189218bfc820ba1bec5286ec38f3a05d8fe86fad58985c synthetic androidApp/src/test/kotlin/cz/netkit/app/speed/SpeedDialTest.kt 1b28d37642326824e57478df3f972afe171055c9a5fb148a9e9b7a823935da4c synthetic androidApp/src/test/kotlin/cz/netkit/app/speed/SpeedStoreTest.kt 311fb5f625c61528e23c2ee3972d5d05cdce6472d14700e3afc4340925339720 synthetic +androidApp/src/test/kotlin/cz/netkit/app/ssh/ProfileEditorTest.kt ad73600d4e7372dec42fb05ec52e6cd50adf637d1bda0b075554014cfafeb453 synthetic +androidApp/src/test/kotlin/cz/netkit/app/ssh/SessionNotificationTest.kt dcba888723d094717e38f6f39423d60fd2cec5c83a557c14aa3e1933b3970b74 synthetic +androidApp/src/test/kotlin/cz/netkit/app/ssh/SftpRunTest.kt a32e13dd84ec453305379052723771dd0415e1a587f7c3ffef0769304c767719 synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/SshAttemptGateTest.kt f3b51d9cbfce0187a33e624bc941848be36e028969c88260ae050bd639a9eefa synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/SshConnectionOutcomeTest.kt ae04876b01fcd431e54c09d93e9644ba7361ed52461b0916ebf23699a2063dc2 synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/SshCryptoTest.kt e1a8ad51003f24b71579e5f08bf4bbd209b4e81de6bf26b797a84e3bf85be705 synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/SshLegacyExportFixtureTest.kt dad2836d6d67db7b527767e2e62d1e352a47da5a17e50d4d258c03bdeb8eab8f synthetic +androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProductivityJvmTest.kt a00bfd4590bbf491caa082ae9381c810a8605ed48b7ee26f5120606880436c46 synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileExportTest.kt 352cd8d3a6f52157b4607a4ba24aa02c9d51bb64bfca5a334877e9fbb077bc75 synthetic -androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt b8563aa238a3bb238f09d5615b3934ee5f2baec5bb74b4c17662d9b337eb1947 synthetic +androidApp/src/test/kotlin/cz/netkit/app/ssh/SshProfileImportControllerTest.kt 5ca568b5d854e182777e91f4e2c020de022a80c04d6e9f9949530a36c111e979 synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/SshRevisionTest.kt 4c5366206da2014f418b2b63fc599068167b0d88bb13ecacbff26e6dcdd80f1c synthetic +androidApp/src/test/kotlin/cz/netkit/app/ssh/TelnetConsoleWireTest.kt 9826c16c6590f4b1ae949cc1ac7d06fa33cc62e0550bbc3ea9443cb528649da2 synthetic androidApp/src/test/kotlin/cz/netkit/app/ssh/TerminalInputPrivacyTest.kt 514828ed0da09233e384e3a23bf6f956c63dafcc47fce33ac8af20a7c3368806 synthetic +androidApp/src/test/kotlin/cz/netkit/app/ssh/UsbConsoleWireTest.kt 39a7d3bfc2862144dcd7b4b14ed1d53ef0159ad6de0df094f9669fd5b5fbad05 synthetic +androidApp/src/test/kotlin/cz/netkit/app/ui/AccessibilityTest.kt ee1a052f41da3b2db8367c3c133e56e95a50c30e675e629e03f1313c07792140 synthetic androidApp/src/test/kotlin/cz/netkit/app/ui/DesignSystemTest.kt 42305f6d6a44eee4b1bb8a2976ddc11d5bbd8c20e9285f4a2276c3e70e916fcb synthetic -androidApp/src/test/kotlin/cz/netkit/app/ui/about/OssComponentsTest.kt abf72b015a2e76f19046da718d9455e3d7d358792cdcf32e8a0773843aaf40a0 synthetic +androidApp/src/test/kotlin/cz/netkit/app/ui/about/OssComponentsTest.kt 3898d9a7dd69e4b2065e004cf3320aa93b57cbae1d6c15b243b0c82fb46811d5 synthetic androidApp/src/test/kotlin/cz/netkit/app/ui/chart/FullscreenChartTest.kt 9c56963cb5f509906c632a051dd548018d62ffde1c767a80585ec5cf959e1699 synthetic androidApp/src/test/kotlin/cz/netkit/app/update/OkHttpUpdateHttpTest.kt 47f5008ad78cacae4966bfbc2cf3bd3adf3174f4c03181965ce660e1d3f8f399 synthetic androidApp/src/test/kotlin/cz/netkit/app/update/StartupUpdateTest.kt 7cd5ac76c2b8687f921d1a85e589627a96036b1f5733c550209fa3a8758f8637 code +androidApp/src/test/kotlin/cz/netkit/app/wifi/ExportSessionTest.kt c221698aeefb837c8a37481049c1676c65acd961861865ae36ec47f72f160b24 synthetic androidApp/src/test/kotlin/cz/netkit/app/wifi/ForegroundScanObserverTest.kt 21e9011d1ab97db473caa7d2d93778a228dd6a8d4249c4d669f7ba7c2ea01e8c code androidApp/src/test/kotlin/cz/netkit/app/wifi/OuiAssetTest.kt 1232c52c7074d78d58243a587d3b9575bd808e7cce9e88af845d155f68962bc2 code +androidApp/src/test/kotlin/cz/netkit/app/wifi/SpectrumAxisLabelsTest.kt 5df90a3f550865a35af727036e2263ba8051432380fe6642a6a47f3d32382c84 synthetic androidApp/src/test/kotlin/cz/netkit/app/wifi/WifiChartPaletteTest.kt a137738f3f66c555a37fd1e6bd5efa3841a71414ab2a3befa55b9a53993e4e14 synthetic androidApp/src/test/kotlin/cz/netkit/app/wifi/WifiDeveloperSettingsTest.kt 76b0c59377d5708b01d2f2d935fef1b48099c51d8a8f7d08066087580765fe40 code androidApp/src/test/kotlin/cz/netkit/app/wifi/WifiScanWindowTest.kt ada8a88c4e61edd756526e668393da7e121b4d2e8beb7795085fe92ef263829b code -androidApp/src/test/kotlin/cz/netkit/app/wifi/live/LiveRadioSourceTest.kt 7d8babd715ca5cce7e6ce87b83cba8df741e9ce8a85e63d92dca5a68849e5d26 synthetic +androidApp/src/test/kotlin/cz/netkit/app/wifi/live/LiveRadioSourceTest.kt 956e726301beff7d96a353caf3ac7b2617ac66ed14b88d8821e7ab32b4c39427 synthetic +androidApp/src/test/kotlin/cz/netkit/app/wifi/live/WalkCardTest.kt 6689c875613c5dde13a2acee11f06264186ea8ef01478ac006b7da29f25ac12c synthetic androidApp/src/test/kotlin/cz/netkit/app/wol/BoundedStreamIoTest.kt 671d6042fc41dee9a0a59c456610010420342b4e0002ad3ca707852a8029d9bf synthetic androidApp/src/test/kotlin/cz/netkit/app/wol/DeviceSerializerTest.kt bba5b5768ac4ca78671beb6b8cb0b91785c7b12a2ff847a5dcbd2858bf2111db synthetic -androidApp/src/test/kotlin/cz/netkit/app/wol/UdpTransportTest.kt 46c781a24c05ddc689009955463a53c0fc8b6b517ef7ae791030c7c45545da88 synthetic +androidApp/src/test/kotlin/cz/netkit/app/wol/UdpTransportTest.kt 32e678aba2c11567f3f0c0e3137e8217257482e6ef779c8b747a3a1d74fe2d24 synthetic androidApp/src/test/kotlin/cz/netkit/app/wol/WolNameOrderTest.kt 5d0cbfa6178c7a01bda35c1a561c79dd024e44233cfa4b812c8af2d5cd2db744 synthetic build.gradle.kts 0e2fd81ef9cf014e2988cd1e4dd2c67b00a2e4beacf16cb7ed7b34f6fcc7fef5 code -docs/architektura.md 601f8ec3ad274e3f6c095e824ac30375c29850a6783cab492ccd8c93e975988e documentation -docs/bezpecnost.md a8cb3b015f54b2cbdda54c6e663bf17800cece7c0a00675439ff9f835ec69f62 documentation -docs/design.md 965b87cbb0e0c5cbf5a7e61a0f5454b380552d33b7a9f869b29f3abf23ab37d1 documentation +docs/architektura.md 4f6153877f22433043f85c4073966c1e96ecf72780bb8956cde0bff753df2288 documentation +docs/bezpecnost.md 95fb81efb9ca35526259984dc03847ad8d9b23d36676f52c0bc5789ce016010c documentation +docs/design.md 958a4fec68896f79b9d9c95dbce70dc49d7075f04e7a73911569fa698dc041f1 documentation docs/design/prototyp-m3.html 139c648b33badd5b42c81de0df30f67199f1fcfed4ce83b132e4469f87fb7f68 documentation docs/distribuce.md e4c40f389dcb7e9147a3fe3db7dce992d78f5492a63865ff6bd9f6723d5d57d7 documentation -docs/funkce/lan-scanner.md d73d8e116566765e0176af3a94a7c9b26cc5aa9fc906784a832f243b4265e5fe documentation -docs/funkce/mobilni-sit.md 9df9884c1d05a8b89faef5316d7d94269283557047ed640678ab67175e40a809 documentation -docs/funkce/speedtest.md 3dc20538d6a023a38a4d347c52bff9ec3131ce8e93b2038068818796c468d280 documentation -docs/funkce/ssh.md 83a595ad096a2d23d8d7d455790f904a4236a724fd09c547040d05adaefee783 documentation -docs/funkce/wifi-analyzer.md 1701454b195b55325fc04389ffca088f1434f8e0d1f1e45241fe703b94cef518 documentation -docs/funkce/wol.md 6c2d407cd573a7f6922869fea9800ce06db44aa4bd1d19e5c1f146a0f084a0b0 documentation +docs/funkce/lan-scanner.md 12cb81758455ef65e726ae732b9264acb6da081bfe9a68e45ab255241426e073 documentation +docs/funkce/mobilni-sit.md f2f35e36514ee3688b129d26fd159bf8d9d66504d9bc07700c37cc49abfdda8f documentation +docs/funkce/nastaveni.md e33147a38eb5e140326b540a7d1235f9b0c330dba75a2608bd286c41fdc4146d documentation +docs/funkce/speedtest.md 84c40defbbb744a9577510b00aee3d1a8ab35079724751fc0d0e533688eae9e9 documentation +docs/funkce/ssh.md 3f57643fe689ad2f8dec8e09720da1bf799159c97ce51f9a213e8f1226ce266c documentation +docs/funkce/wifi-analyzer.md 82ad9cc7c76d0cc83a5c88019b34c09344ec806f5cea3af109c26b2266859b1e documentation +docs/funkce/wol.md 73fd31e74d6fa0f6b673054bb9af10b5ea2ee89acfadbaa459070b17d9793ffc documentation docs/ios.md 7afe6f6500769a948b935987d259936de05ea54aa8b8b8a80515697afc7fe9a2 documentation docs/licenses/bouncycastle-LICENSE.html 6b0a6f8310ad417bdd06d9daaa228cee385d828301e96fda411f7732479651e4 upstream-license docs/licenses/jsch-META-INF_LICENSE.JZlib.txt 9aa93e9bc58ae423a9e6476f608ee8f46063f5679e3bac0bc55f2f4b10d243ee upstream-license docs/licenses/jsch-META-INF_LICENSE.jBCrypt.txt a85927641ed1c8b95a5cef79b127b2392d80e0aa9d8e2d6f3b7b7401c5396af9 upstream-license docs/licenses/jsch-META-INF_LICENSE.txt 9c3537ab0b485b391b887b95fdff761de3dd3273a6931e8a1942dde4d2093cc5 upstream-license +docs/licenses/protobuf-LICENSE.txt 6e5e117324afd944dcf67f36cf329843bc1a92229a8cd9bb573d7a83130fea7d upstream-license docs/licenses/slf4j-api-META-INF_LICENSE.txt 4e7f90c86ab51278228bce153122f1d8df30149d13ce9ef524c8444a84c32dcc upstream-license -docs/plan.md b3fbf65a3a1b7913a39b11f8ca92dd9ad8cc832efaa02d5938878bfe4e3142d3 documentation -docs/project-license-inventory.tsv 617dc4873a169f681bf2fe315504ff79339fdf9634fe7d8b2439e6716a1188e7 documentation +docs/licenses/unicode-LICENSE.txt e7a93b009565cfce55919a381437ac4db883e9da2126fa28b91d12732bc53d96 upstream-license +docs/licenses/usb-serial-for-android-LICENSE.txt 6f467d3d79c5d31734881fb83e082e84512bde05d3f7893e0e8373fd0d2b5d2c upstream-license +docs/plan.md 3446eed9fc2cbeeded490c9feae697bddb21c92782e816f6e8d1b24068d7c913 documentation +docs/project-license-inventory.tsv 6970441d6c0fb237818b2d8dcbda75bb3260da084744c4ad47a08dc7baf2c652 documentation docs/public-export.md 6b18cef46625c3194dcdb687f3932b3191512e149dc6f0500859d0f711b08529 documentation -docs/public-license-verification.tsv e0f9a1569831680508edff3956d7d3546015a262c88bca6c5b0dcbe1939fe69d documentation +docs/public-license-verification.tsv dbaf058beaca7f515a77f417244a9805e3affbd88d55f669e6c87465e831c0b4 documentation docs/public/README.md fa885ca64f70b1b2a5fb1e94060b36937c6ea5c526effff59f1f5b9f85a28c30 documentation -docs/public/data-safety-podklad.md 130894912b7a5cf63781459985ee9de4b1111421f7d0f7bd47f47fe8e7a298f8 documentation -docs/public/data-toky.md 7edaf2bc14c3f29a8164f44c6872f920f497c9ac2b7887eec4c3904608b0e180 documentation +docs/public/data-safety-podklad.md f423deb9380a05e83d74315e476765a233aa45c53369d7d20ba5dede58ff63ef documentation +docs/public/data-toky.md 8bba6885dc38ef7ddd273687625f701de3444457a2a0e92b9cef01c6c3f31cea documentation docs/public/grafika/README.md 18b47fdda2d7e980c00f0460da2c59bc877e354cc3047ca7b3afe63d99281840 documentation docs/public/grafika/feature-graphic.png feb4bc9d26db7bd26f13dcbafb600f6e897b9351b1dd74664ce63520cf1026dd binary docs/public/grafika/feature-graphic.svg 953db52d59a71aeca1b3161762ff99381fcd9632c7a533b2ad6f446583c33df9 documentation @@ -243,16 +429,16 @@ docs/public/grafika/ikona-512.png 56767e5c10cdf3ee55790924af00704ce4507e69b440ce docs/public/grafika/ikona-512.svg 820c197afd4c1e9ca6de7cfcc5994cb100e43d6696a5b9f85cc839d928d00582 documentation docs/public/listing-cs.md 01f62df4f324ff75c2fbb76e1e6b39f5a36187ea7ff7527a57deb908116a12e0 documentation docs/public/listing-en.md 57d3f98afecdfb86ace75c3977e15bef833bf5c11473bc5b6e7af72fc42c3f0f documentation -docs/public/privacy-cs.md 9c1b01b0b753242343367b74685132e4dc060cedaa958995868fc32e1a2b7b77 documentation -docs/public/privacy-en.md 00278b52c6b0c4b3b4e749c7c8b2548663f6b3fcc8396dccfe62e3ff9b6befa3 documentation -docs/publikace-play.md 16fbba5b0ba587b156b79d9505c76ba5ee504d9f5565163937dddda9368b0cdf documentation +docs/public/privacy-cs.md ffd6cdbf77444e8d1ba62635c331f3a81e0cf66389a1432b57b6c02f0055a5d2 documentation +docs/public/privacy-en.md d7612fbc72c2d340042ba119b1b0b5db5b43e29752d53c341980bbc3532e00e4 documentation +docs/publikace-play.md 07a74bbdfe7092ace02115750021604afe38e0a97c961f95a014fc859714e873 documentation docs/revize.md cbfc8342f5dd1902e7e48f78d1d8e2d4f5b8d59d3561b113ffb842d0152fc07d documentation -docs/testovani.md 1e37b8befb52569780addb5d006e913e9624be32e65be9551b2e9926cb701e14 documentation +docs/testovani.md 2d0d2f1a5c35f0dc16c4eb9ecc729cb20d4cc3cd48b422e1fcdc1e2d48d72172 documentation docs/toolchain.md e2cb54e1d27f0458f0ec95d827a2639ac34f205fdc7321acae7e2451ba508a6f documentation -docs/zavislosti.md 98fda151a6396e0a8005923a03b0d0b8c2683a55d45366619d3ba19b9da4a7e7 documentation +docs/zavislosti.md 757a305197902d31bf5d8e604ac57f61ccc13e082097100691ff3ceb8a174a4a documentation gradle.properties 3b0360faee84b00fee599a4c9f51bff401e62eeef157369a68c3be16f04df764 code -gradle/libs.versions.toml 494d6fcf3ece113c7b68141b9c6f5c6a837ff15f6dfac4ab51c3ee18c1858919 code -gradle/verification-metadata.xml 086407449512aa3998a3cbc87dffbfc9288e8cdc9656c89305cdc18f1556586f code +gradle/libs.versions.toml 57b1910fabb4e7a0de263edcc72651ac1bd94b8afa1e1e17ecab4feb467104bb code +gradle/verification-metadata.xml 15c9df31a00e76a3cf8e41985fc32aeb2213af1a8e118e1e81ccff58119b1bf5 code gradle/wrapper/gradle-wrapper.jar 2db75c40782f5e8ba1fc278a5574bab070adccb2d21ca5a6e5ed840888448046 binary gradle/wrapper/gradle-wrapper.properties fe90ff0d9944879f591a8c37b6dbaf5046d1051ccbb6b26b22081692c321f432 code gradlew a3648413b47ef77af21d5ebc36c687c7d103aaef3e17f33de7d4f080a6f300a3 code @@ -264,9 +450,9 @@ iosApp/NetKit/IcmpPing.swift cdb1173d693fc85470970c66283b9d56cbe77c1ae928ad6799a iosApp/NetKit/Info.plist e107de3c536e8c5e00b1e300413d12e15ab0a898bbb54697f19e0b73fc5dd275 code iosApp/NetKit/KeychainSecrets.swift 4d0ebc9c6153180df98cb293a0f315daa63adcd751e9aee29bb427faae9080f6 code iosApp/NetKit/LanView.swift e01d1f308c155066dd065612477135eaa08db28d91339bb19dd10ea03a2248c0 code -iosApp/NetKit/Localizable.xcstrings 5c150e8c0a0cfd7c1bf0149994409d482dc8b75c75d8a57baf3baf463938e84d code +iosApp/NetKit/Localizable.xcstrings 420bc47053115590f6eb26f100e5853c27a335b92be526c5b1183d668bccc331 code iosApp/NetKit/NetKitApp.swift e0691df04bb2d2fab73d1c8844dd68b0e33bea5c908ee6acd29d0cdfd3004796 code -iosApp/NetKit/OpenSourceLicenses.txt 997dff8804ae121858c90f5b2323ccf2574b52bcac58ce4d0c5219a6427db1d7 upstream-license +iosApp/NetKit/OpenSourceLicenses.txt 4ed1d8bb00ff0beee5334e06230ee40f393e38afbc99c316d1675e6f4f5555c1 upstream-license iosApp/NetKit/PortScan.swift fd1d185560d26ba41a62fd6375bbce637c05c9d3ae78de7642ae3007e2821c91 code iosApp/NetKit/PrivacyInfo.xcprivacy fe3d88cc003bb85f70c517010312e70ed1549c6e2505b00e8add05595c0d1adc code iosApp/NetKit/SpeedView.swift eaf451e1a2d21f6e83fc4e22ab9a6b5c85bbe006d47d7bf1c46ffaa77ff95696 code @@ -275,8 +461,8 @@ iosApp/NetKit/SshKeyboard.swift 7bd4098b93134616c1e2931dd7f27414647c91d167a7653f iosApp/NetKit/SshMetadataStore.swift 62327fd2acd116d31ac957fe222b57be2b541f92493f45ac5e39feb3030880dc code iosApp/NetKit/SshTerminalRows.swift 2031388ce728601a119c4a8020681ccdd1836d0aae4e0b58aceeb90ddd2c7262 code iosApp/NetKit/SshTransport.swift 9755b456a8097a631866f3041340beea5ef2e6997fa9a7e0e98999f7e184f702 code -iosApp/NetKit/SshView.swift 3b61550a4593a6fd6977d1049fe10356b7ee04fee51848430ecc8f131be7c277 code -iosApp/NetKit/SshViewModel.swift 7832a392f118f9c70c96040e55ddc5209c14a031854a28cb061805ee50ec8f17 code +iosApp/NetKit/SshView.swift 644f522709de223ae5f2d96047143fd57d950f6a38ba357de32d95b13b741c13 code +iosApp/NetKit/SshViewModel.swift f536b1dde7545e9873ffcf3910957bf0bd795a4db720e24aeb3e9538ac410d0f code iosApp/NetKit/WifiView.swift 5ddeaff07586bd54880a4cc5b37f0b07d0f755ccdf1f99b7b7602c4a80318cd2 code iosApp/NetKit/WolPersistence.swift 2adcb02b69b918d5d04b472bdaaff4d3c38bc66de43f345411f0ac2fadaf77f1 code iosApp/NetKit/WolPlatform.swift 809eca7110d6002a1273ae780af48d83ec0d8499e669c043ee0a5d0ffd56bfa9 code @@ -284,118 +470,203 @@ iosApp/NetKit/WolView.swift 531ec2bbb48496bd58ebd7e5d06e4488917c1a1c516c95e8c6ee iosApp/NetKit/cs.lproj/InfoPlist.strings b2f610ef5ac9a70d0e02ef20f01479254d64d972c5ac298681333ca05d1daddc code iosApp/NetKit/en.lproj/InfoPlist.strings b281a360feac92533c46ce454ad894a1e07ebc6fad96cd742a19a2a808858128 code iosApp/NetKitTests/KeychainSecretsTests.swift e39948d97c6c1490a9311411a1ca053c3d95c225a255a3091b3d81d65000435d synthetic -iosApp/NetKitTests/LanTests.swift 7c2c8e49a25d158807c81ba236d44cd04bd6eeaf459399790e8ca16f6279076f synthetic +iosApp/NetKitTests/LanTests.swift 0b61a41b1f7819e3e829d9e271a92ca5b0c745a70eaf2af4f97af6391699a0ad synthetic iosApp/NetKitTests/LocalSshServer.swift fdccb9da53ae0e6adcca5493ff3738e60bfc3e5c04a92531e23d4a0bc30c461a synthetic -iosApp/NetKitTests/NetKitTests.swift 9f10730d049ab01855b6d1f02b975a5019673d4afa73df582acf4f7f5a77f5d4 synthetic +iosApp/NetKitTests/NetKitTests.swift effe4d9429b7cb153da0408affc15d753923a3f239b904042f37d2d6c0a9b59b synthetic iosApp/NetKitTests/SpeedTests.swift e8049864cea86e65d91ea60e05677947d5e90a3a801fb03250f36d1b7d5b63a8 synthetic iosApp/NetKitTests/SshIntegrationTests.swift eafad8dbe3db4673a0f58958986fbb5393b4dbe0e208f7bcb1436f59addfc2df synthetic -iosApp/NetKitTests/SshMetadataStoreTests.swift d86649b07ad1615045e63dc0e74ad571fb561d37bca074111f5364f03a370e9b synthetic +iosApp/NetKitTests/SshMetadataStoreTests.swift 995434b834acbb7607ba9fb6b480e2c259fa66a18745cd6a78a37b42e2991007 synthetic iosApp/NetKitTests/SshTerminalTests.swift ff678ebca66ddaa746a49dd53b1873ad0b80e2aa513bdacbf01552905f195e75 synthetic iosApp/NetKitUITests/NetKitUITests.swift ad833026b034e1674b773ef168be250f28d5dd53497ddb6d9f15491e1ed447b5 synthetic settings.gradle.kts cfc6539e9e50b14277775f45a5fe0f942d6490665ebdd651a2902b24d618190c code shared/build.gradle.kts 0b971204b006ff95eeb65e432a3d0a913e917c7272b679013c7c327e30c57355 code shared/src/commonMain/kotlin/cz/netkit/shared/NetKit.kt 2ff7b63264316c333a069006f71ce23b9749e2ade6ff2ef7221cdbc86c66758f code +shared/src/commonMain/kotlin/cz/netkit/shared/backup/ConfigurationBackup.kt b4e198d83d076bc22cfa302659c81ff64e66b61016c96486d8023df3ff33e512 code +shared/src/commonMain/kotlin/cz/netkit/shared/backup/RestorePlan.kt a8045d2558fea6dd717d8e47a0b8009c287f07ddcda2b60e06388218ec4c47b2 code +shared/src/commonMain/kotlin/cz/netkit/shared/cellular/CellDetail.kt 9520a8c747843ce4354e8cc648546e79bb05a16d561a0c6d4bb855baa97d1a51 code shared/src/commonMain/kotlin/cz/netkit/shared/cellular/Cellular.kt e919aee45840d0d97cbaa9676ae2660b85b5c6d5ced4034845c1a223a35cd44c code shared/src/commonMain/kotlin/cz/netkit/shared/chart/ChartViewport.kt 3d10556a45a287f3dcc47986d1b8706e5eea27240cf6b65e7eb11c4a9241ad8d code shared/src/commonMain/kotlin/cz/netkit/shared/json/JsonLimits.kt fc354857be8ae24a4ce95bfc5654eb63495fc8b109cc6472c5f46804fa41c05e code shared/src/commonMain/kotlin/cz/netkit/shared/lan/BoundedProbes.kt c96b512392ed45c4cb28a28856131463c538aa31123adc8778c62e9b5f07eb5b code -shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsMessage.kt c4e1bd373fb6b71e9122e4da4b4ebae0d574b0e1ed55b5483d123e8ee5b302b2 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/ConsentResetGate.kt 188e2fc1db0b89143652e9c7fff74fe7e2a082c8a4ec0727efdd15f8f2377000 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsMessage.kt 607dd5a30eb36f1714d85e0cd25fa41a9ea10616ad025c9572f7d210a908ebcf code shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsQuery.kt f2b28ab6fc098f8219c0c709251b4efca1d72609fa14b6f06aa9dda763e8a6e5 code -shared/src/commonMain/kotlin/cz/netkit/shared/lan/IcmpEcho.kt dfccd97333467d31f928f5554657d1df7f057d6adeaead531bba27aec8f1e398 code -shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDevices.kt 1dcc8a6b21dec83c9db0070b75b4a8917a6d87c01930daac7a0a2a5567070cec code -shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDomain.kt 0a97b9db3f4b876d7d8ba27e943f6121e857f145c575589b23fc491d96fe3e91 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRcode.kt d19ee34e4e196ffeec0e506bffd26b222a6bd64178483020dc8d797a2af2b839 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/DnsRecords.kt a7793c7747022bbe4b9337fdf739cc0e53440dae5b798481e204d57381979836 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/IcmpEcho.kt 41e6f100087da8b7d9de37c95482700c14fc8cc66971b8febbf53de1ca52a06b code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/Ipv6.kt 8406ea9963e804fec98e4fdf3fb319b22d7e78e639749e58e2ce9975e8c15b55 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDeviceExport.kt 0fad4ee23339db0aa100f1c9f9a7a3c521f83dc45b0b13f86f5335d939f17b20 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDevices.kt d76595f3642cca85cf443b869b40aea503f41aa2f7435c00d8618a418d76330c code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanDomain.kt b64ecd572e86c93871ed9c76194ca34405f0121fe23748f189f3bf9f28f4d4fd code shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanExportLimits.kt d540f2964d6b54b9e63a8822041ebb79202ee07668d1744512bb1d42be08d14e code -shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt c61a56aed653decaa99307c0a3efe8091b512e21775c395118d347cf1df57bcb code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanNetworkInfo.kt 62b0a0f652d4e14017f841626413f369f5f076151fdec866ef9518943f05d8ce code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanPolicy.kt a4b3b6aea85965736d168bc370be0beea5c69a10786e57b7bf0208b7006e22b0 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/LanWol.kt 2fd8b586cbc310e66f25d64b7214111d8cd98e5a315e38efa189803339bc68ec code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/MacAddressTable.kt 525521f00cd66d00cdcd9dfba263273249c274bbfe2eb1a91ef8282ce2fceb7b code shared/src/commonMain/kotlin/cz/netkit/shared/lan/MdnsIdentity.kt 5a7c67608ccdf6269be5c84cddf323ca7a876503b057d0a49b86806fb78295e2 code -shared/src/commonMain/kotlin/cz/netkit/shared/lan/NetBiosParser.kt 5be4b02c983039159c13b01a35f479b8853bc4077d129ab0849d2e12822e4367 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/NetBiosParser.kt ac7a8ce84503f8ece75b355a9e6c5825174e660bb0bc3ba4be3c9da8d787aa3a code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/NtpPacket.kt 2509cf4fde7f81a9f1db3a7be14faf6ca2fb4d139201d683ff71bf501a641dcd code shared/src/commonMain/kotlin/cz/netkit/shared/lan/PinnedProbe.kt 4d9411d687ca4d166a09d992754630703ab1b90bccca89eb6dee6fdad8a33ca0 code shared/src/commonMain/kotlin/cz/netkit/shared/lan/ProbeResult.kt 74b2194138e7d8d15430815ac169265ac428324c285f98faf7f0d69c42ab5646 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/SnmpBer.kt a67b98670cdd78c6441a25a3be0636fa73d93dc60262e82d0146cf416aaa4998 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/SubnetCalculator.kt c8af05be7ec83bca1a8cdf9e692378d843aa1190d49a7dda2911f120a03f4416 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/TcpPing.kt 5172049e351e286c242b4eb271d4522234163b34523492485813c6dfe44d85d8 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/ToolTargets.kt 771a944029ff272949b82e430b7b022395be9636307862d481ad7539caeb3b79 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/UdpServices.kt 7f3ca6faca9fc083bf961980f65b7a2821a025328c1af8be5db3caf3cc55a20b code shared/src/commonMain/kotlin/cz/netkit/shared/lan/UpnpIdentity.kt 640867e46056531f763d19bb658ce22fa11d3a9511c6f1116ecdc2f7e0556132 code +shared/src/commonMain/kotlin/cz/netkit/shared/lan/VersionBind.kt 01a1647e8d9d4a037c295ca207c06c8404a9c255cbe43b824b7c5d831ee7a278 code +shared/src/commonMain/kotlin/cz/netkit/shared/nav/AdaptiveNavigation.kt 5b1674764b7ebe1aaecb0e13f8f564a624b8e75b4a48af7df53acc5472d7741e code +shared/src/commonMain/kotlin/cz/netkit/shared/nav/AppTarget.kt 5ca250e39ae3293ccb1d0d2ba9d07888d7d8944e8f12b889b9ba1b39fb3117cf code shared/src/commonMain/kotlin/cz/netkit/shared/net/LocalTarget.kt 9e7896c3ab332d26b1085590270e72cd0f5f017ea591b2a0b9574a8bd1bf28a1 code shared/src/commonMain/kotlin/cz/netkit/shared/net/NetKind.kt 90d8b4071b7727498944fb3d7eae23fd6997f4d8967bea05e6bde46919bbca85 code shared/src/commonMain/kotlin/cz/netkit/shared/net/ToolRoute.kt 849aee8df597a7a8b546aedc94a050b44fe989cf1b8b549812ec760f32ef57f4 code +shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatus.kt 05e9dae8287d10e40e9e1b5fd7d7954d4b3704d1263a120784559eea20f0d848 code +shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRecorder.kt 6335d1984e4be18fb96adb6cfd22f4d7ea464c3530def67f793d30bd12b2bb2e code +shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusRefresh.kt 920858b07e77a8bc6981edcc2e4e6ddfb54d14e4e2b54ea4c66f2a061274c565 code +shared/src/commonMain/kotlin/cz/netkit/shared/netstatus/NetStatusView.kt 690163b2590b1eae06858156b23ca70ca9586542631591a7f05950df389e434a code shared/src/commonMain/kotlin/cz/netkit/shared/overview/Overview.kt 59c2fb681c5d6fa63f0f4a06ce9286bb0c04f4fbfe31441553d29a2286831565 code -shared/src/commonMain/kotlin/cz/netkit/shared/publicip/PublicIp.kt b3c5395f7fb4e1cce49715d2c5b855bba3a636fcd65c3ecbe77ee1fd125938e5 code +shared/src/commonMain/kotlin/cz/netkit/shared/publicip/PublicIp.kt 72fd7e2b056adba731fb6fcb73fe21768817ba8f5df837292e710eed9056d1f3 code +shared/src/commonMain/kotlin/cz/netkit/shared/publicip/Rdap.kt 1b56e2534624c188065b0653efe5c09185ac49bacf968641cae4e71f745fc43b code +shared/src/commonMain/kotlin/cz/netkit/shared/report/DiagnosticReport.kt 834d821c6261f6982c8673226a2c83815a3c37c907a2c48059543c22ee6ab6d1 code +shared/src/commonMain/kotlin/cz/netkit/shared/report/ReportText.kt 37e909729436abd8b5ff2d5dcd64532c3a5d96f59e03a4b22e107d2c98e7cfe7 code +shared/src/commonMain/kotlin/cz/netkit/shared/settings/AppSettings.kt a0499d29429cac111fe7a3eb5d21e57bb9366f26a1f71daebc7db4d3f488b129 code +shared/src/commonMain/kotlin/cz/netkit/shared/speed/Iperf3Protocol.kt 9370b876e6dc271462ddb69e10876544b64f2f2bc9af459ca67a8a4be1af486e code shared/src/commonMain/kotlin/cz/netkit/shared/speed/LibreSpeed.kt cfe204ed2c0f7e4a7c4cc158a94110a1c852349ae77385469b2aa14894bd2524 public-service shared/src/commonMain/kotlin/cz/netkit/shared/speed/Ndt7.kt 05804e1fe87134ed83d4d6fa660e1f3a3a18f8355a4713285001ad60dc1626eb public-service -shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedDataEstimate.kt a21af20941cbb3bd30ff4984dc073bcf9167318f0de81bf578eaad8fdeade501 code -shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt e63f1394e33e1c247a258f7ec00a945b8f7f6749d335c556fcebd1eb888ece43 code +shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedDataEstimate.kt cde2ea87cdd4788e864fb29fad356064b46dc2f05b4d95b7880253326492f617 code +shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedHistory.kt 1a023e4c7e76d2298b70d0cc4e2c631d19d951d4ec571ffc57fee3ac03795e0b code shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedMeasure.kt 8ccccdf0d1574dc4a24198c6244448d71fe52adda51273f17b429819aa46a9eb code shared/src/commonMain/kotlin/cz/netkit/shared/speed/SpeedScale.kt a979719b322f65c27fe84018822a05d8511a3a1c2252e91f457ecb61dc4a126f code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ConsoleProfile.kt 4b5220f698db0f79a1b8f3efe356ee8bcb959441331dd5e8db1bc9221ed4e91c code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/ProfileDirectory.kt 25c5e0ec879fe7a801dc86ca8eed293062787358bfe26fc5280471e940f0d0db code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/PromptReplyGate.kt 2cb4562e34737dacd18921e22992d65f5c05e277a66f4fe2872db24abc18aed4 code -shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt 3f1077e82016e8b20feeb42ad6268b27f71d26bf0a6e1c7bb053c40143c06e4c code -shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt 56ece94b3cf579bb938dc8c93851fccedc34763b22cb839e9979bd669618b4db code -shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt dc9af5a64707c6dd293d474b9bc05caf41d6a5f5799a7c3e0083b5dd328fea06 code -shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt 722b618207641e4ca183a577b6accb0d88cda31d48259b17ccd6c4b120435036 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Sftp.kt 21ecf90ba3b150e256c8909527c6b0cef429af186f5dda52141856fb73cb33e6 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/Socks5.kt 04cde722d07ff41d4a0aa8f8df6120cfc4fe1923de62532f5ed045cb859305d5 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicy.kt dc38fd9a391266d78831c728c96ab78f69a3de470340dbb11c0ac86a4266e2fc code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshForwarding.kt 1c628e7054c565117a80f704ef6245100c3b86aa343302e8729ab6c8559a42d6 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshModels.kt 2c2dcc5bcd8d00ea714a2e2d9c502c07a5b86b6c6b7107dc221e09df6d4a0581 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileExchange.kt 3ecd16b0435d9ca75417c63c4517e84e82d3ac21cb4c153c97897f5da6a670db code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshProfileImport.kt 6aaf3759eb84a575f8cfb14c80b79ed1af9f4ceb8cd86c83f57ca2b6fd1362e0 code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshPromptPolicy.kt df67c645fe0443a4fe824e971678438105efbb947f329e61a24f3e46693fee1b code -shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt 4a9b527efa3aa637fbd16d5c0f8a06543fb38661bcbda52f8dd4c47fa20ce1ba code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshSnippets.kt 154166476fc1e5905aae877a9e8a3c7dfa9de50182b8fddb4a1682608ce0af9e code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/SshUnlock.kt c20dc7deb5117beb18bc63ef78716d77dd25106a36622dfb473486edb8645652 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TelnetCodec.kt 556238fbfba8190e4b8687f60a7c9a95f81474073942eb9f1065314b2863d885 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalBuffer.kt d013b5d2d9b3746d2c837cf046ad66866b0741c94109b4c255123672edb31973 code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalComposition.kt 4a339f543e52e2c9a22df1080cbcb19c4db85b71eac42c96ff220d43ca8c4bf4 code -shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalInput.kt f6b8fa1029897b347c401d22bf19b7b895cf06a6a8f795a3c0192abe4b139418 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalInput.kt e7c82c2a3ddc676f67cee78ced37dd9a3331502f252cd55c1d012e0c08498b96 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalLog.kt b25003beb640a6386d71f5e4404b02aa93489ed74ccb00d9fddb29824868a717 code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalPalette.kt 69993ea5f29aae9cd1a4310131d9bed3791087658717aeb3f74e3a04816426b4 code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalSessionBuffers.kt 3150baea5e92369386f8dc9bd7989d2990817dbe4c86a100f0243d251f51f0ae code +shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt ff3f0f1a9e1655388047356d15b87acd99f3e5fee3e3695b11ab1c25c62bcebd code shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWritePump.kt 60a86e222f696a297460e9d007c41ef5643f45bc0f3087eae96c5ec5a2f575ef code shared/src/commonMain/kotlin/cz/netkit/shared/update/ProjectLinks.kt 12a820c8ea007be1d4d3d744b522fc787d66bd25945bf2acef5375aeb30dbe30 code shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateFetch.kt 4cf17717441451a3f377119c2ff98b9a400a8420795247324ec70cda70999c12 code shared/src/commonMain/kotlin/cz/netkit/shared/update/UpdateInfo.kt 029551c8a2ca23c584419aef45f8feae838519c30d138c8f064bddc04f6bba89 code shared/src/commonMain/kotlin/cz/netkit/shared/wifi/BssLoad.kt e522fb7e793b226bea7aa3f2d3ef2b934b22ef0de2e54e19bc3fdeefec1bf453 code +shared/src/commonMain/kotlin/cz/netkit/shared/wifi/EssGroups.kt b2d3fda6ec942df4fafde13d94df83542e90c1c442f9245459a925718a730741 code shared/src/commonMain/kotlin/cz/netkit/shared/wifi/LiveTelemetry.kt 5907d5b64655853a039753217955e39de0ff7342c02b0aec3f51a52704069e01 code +shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Mlo.kt f1513f3e57742b487dd850f9b3e660651f61de9fa73ba3a6e7c2915730224fcc code shared/src/commonMain/kotlin/cz/netkit/shared/wifi/OuiDatabase.kt 2b9ada03ce54a40489f91caf2c9ab199539353c86577e5366f0dc677e704b133 code -shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Spectrum.kt b21003a743ec0c18b58dec0497ecd381aab698933aab6e814a8a3da635d7d876 code -shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiDomain.kt b962b01e32412099fa117c0d8deeebd56adeab692512f1dc450ab4cf77d5859d code +shared/src/commonMain/kotlin/cz/netkit/shared/wifi/RegionalRaster.kt 0bae0e832aba4a42efd47046b20780b2120c3bada80ccf6c946ef370977c01b6 code +shared/src/commonMain/kotlin/cz/netkit/shared/wifi/Spectrum.kt b22301379881cf1ae061df784e6b8fc72f41b6559afd2db3dff455483d1e5279 code +shared/src/commonMain/kotlin/cz/netkit/shared/wifi/SpectrumPins.kt 04b61c8f576451d466ed60ee98e4dde6c17a3132e49cc3141d46cbff9992fdcf code +shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WalkLog.kt 6fded8c67c04c1074acd56fceae3cd1ba45746f27e48533dea4583fd5edd04f0 code +shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiDomain.kt d2a8114ec3b9df677c5714257818cbc52372ca5ba7343bfee213c5c322967f16 code +shared/src/commonMain/kotlin/cz/netkit/shared/wifi/WifiScanExport.kt 75fdcd11e79e8a99e7c675c1e9cd251e00dde8a9fe8b195ad4c749be2b092e45 code shared/src/commonMain/kotlin/cz/netkit/shared/wol/WakeProbePolicy.kt 3cd65a72a77b20dfd2b2551e7b3ae1349c714b3f9443063e689d3c767eefb44d code -shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolController.kt 08cee7e948b0ebb9bf7d6e971b5c76856146268dad7f3586732f3bea662421ad code +shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolController.kt 1ce28029df0c9d43a477a2721caf32c70e95ecb557aa5617f6fe0a43eddf0cbd code shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolCsvExport.kt 4e57b265b6c29028cb24e08c4cc70239cff6deecdcb36788da2b31db74f8d190 code shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolCsvImport.kt 55cde4b649c8684adc8d6091564e6e959fa2ba5b7f201e0c617adf28f34a2213 code -shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolDomain.kt 05c439777ce4b40b6187dc172790b23542783991d9f1ce17bf406ee893483977 code -shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolModels.kt 15e22b0a2daeb6058c4e17fb64275f30d3b4eaaed3b9ab7a3e2563c822775d6a code -shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolTransfer.kt 84c335524d6500508f0db2bbc2037fffac0b365d8ec3c3e586752bf8177658a4 code +shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolDomain.kt 56883c92b9265acdab4c5106dd877fb15590152670ec85bf576ee69cd7150953 code +shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolModels.kt e18ea65eb3267838d5fd817800067d643e48f9b70940feab9fc2f51fa24ae177 code +shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolSecureOn.kt edd7c5790a09d572b19ff5aaba8ad6d7f7b5a539ae703a9ef21e6383d5a9fa43 code +shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolTransfer.kt 000ae2d9020f05ee834b6b8b058b420b842b269e12da70b69829f52f87d19e1c code +shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWake.kt 1b6af7b459d47151bdeeee00ca94b9e3eee84a545bb179dc1eb63f9da3436bcf code +shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetModel.kt d2799d2b1bb4b929cdae85801b83b2c6991245e74424d13cd9aaa0686b2067fd code +shared/src/commonMain/kotlin/cz/netkit/shared/wol/WolWidgetRun.kt 99cd77da1da1627cb3ead74fa01a9f8f8c287cbdab7da7b6607cfd50225158cf code +shared/src/commonTest/kotlin/cz/netkit/shared/backup/ConfigurationBackupTest.kt 1ff682f60306543ca0c43e386adf3346abf77e52ba96072b8a5358116de5ae5f synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/cellular/CellDetailTest.kt bbb697d767a6c21155b9cc91b2b76c05744e2f1ea5757590cda43fb0adf768cd synthetic shared/src/commonTest/kotlin/cz/netkit/shared/cellular/CellularTest.kt 34a99a3c821cc3a0421785f507ae2a4502d03efd0a7224a86c68179587b3b656 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/chart/ChartViewportTest.kt 940a53490988497922753f980818cd189f10a0628b852536c9076cae13d84e13 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/json/JsonInputLimitsTest.kt c1f54026ee05ebe126bd831d2536fc7971c723ac53a12d4baceaa488228295f0 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/json/JsonLimitsTest.kt 57fb05b580bf5851144c2c68a628cf1c36977d163c42cbbb981c7b1a6a6314a3 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/BoundedProbesTest.kt bea642f510dae611d74322eb2dd31fef0041034e62c5fff76ff5eaeecfc40d19 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/ConsentResetGateTest.kt 0532f95f0b1003a0a63c7703d12692f6c15d6b80c6c5f4668a5a6713db6bbacd synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/DiscoveryFallbackTest.kt e2903af9f2f078269b5b372ea60a36a7492669bf6148f92341df2d31ca671118 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsMessageTest.kt 40481d276dec695c35e4da516c48d3038c23549d8f85263542044b5f791c1369 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsQueryTest.kt c058352f04c3653968ef1bd2c5fb14ad05ab1bd808620763b179aa23ab036b15 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRcodeTest.kt 270d87c4ec9a2cf4cf6f1e36873a43537cf68754d413ce52fc94058ea6044013 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/DnsRecordsTest.kt 831a95c1ee31f15e7f400f5e8a423824f8f784824c4c7f35bbaa518b5f2bbda9 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/IcmpEchoTest.kt b3d44c3489ab5f204bd9461fa8bc1e0d74fe6019af83037255cde1caa06a1076 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/Icmpv6EchoTest.kt fcd1fd28b964bb59973cfcf4a600d1da51f82dc03fd2a3ab11563bb17be598f8 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/Ipv6Test.kt 73088e47bec3aa62c20f8106c9309b1810c033b5d461ff9faf2ddd597511f0bf synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDeviceExportTest.kt be0cd8c048c75137dcf6db06488ebf161bec914095d3791721476b60d012efcc synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDeviceIdentityTest.kt 82854cb4142957e4c1174d7ff3c1cb0695e505cba58a12ee35d2c7e24e72e6e2 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDevicesTest.kt b2a61c0ccf50f5dba266b314904c9b71751363038a23e787fd5f67e949bf2a77 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanDomainTest.kt 2a324a88b380ad4f18b7a4503efcb791e68df35f890d697affb2cc588d11bb4d synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanExportLimitsTest.kt 1b91a4b28b6d379c6cd020571f4df305bd6b3c4c2015bec139989470a78e3d55 synthetic -shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanRevisionTest.kt d84d713564f8d51d280c16d712d2638de4ffdd7d543658a72b77fb4f252f9666 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanNetworkInfoTest.kt 79c601130b319b7097e391d0521f3c66ef593a5cd7abff0d2bfc3dafef25e074 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanRevisionTest.kt ec9e6e709eee45f00f75166f5a2e8b770a0de50dd7a2352e39ebdb760154b70b synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/LanWolTest.kt 5cdfbbfe53f543dccb6baa776b9fa2d1b41110d0f3a332581525e504cdbadf9b synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/MacAddressTableTest.kt e89a40d05f1b33b48d58412c89bf7b7122ee095c2b705b5e88d67dfa546482e6 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/ManagementPortsTest.kt ddd35baad8bd4a71a6dcec1b3711773457faaa06f83317dea80dbd3f0ff5b77f synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/MdnsIdentityTest.kt 3039ad0a47b3fd0df0dcfa283be504b3bab0e4e279efae6f25fe0b1ff8d2eaeb synthetic -shared/src/commonTest/kotlin/cz/netkit/shared/lan/NetBiosParserTest.kt b6985ed1bef728a7f14d3cbf418a778d49f00e0a1163ecde3c97b361f9e6646a synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/NetBiosParserTest.kt 5625383ccfcece30f84c40c74e2d063885decf1cb29437dc72604b1254b52782 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/PinnedProbeTest.kt d3f6723f2227fc478761c644ecd607c5a213bfab010efb66dd3db76824afdcc4 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/ProbeResultTest.kt 57f5b2738454485b70f8083becaea16347be31e87f056fbdd2d28ed32b3b6047 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/SubnetCalculatorTest.kt 317a84d9624d07fbb8830b767c0a727bba1535e1e8159d109b57e6ce2f279c35 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/TcpPingTest.kt 05adc27cce6600d60d01209e68333b83407f8619af069a635f7150e14d8001aa synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/ToolTargetsTest.kt 180b16ca98f2ccbac9089df161413f58fdc9a2f9953ee75805fd2b405222ee30 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/lan/UdpServicesCodecTest.kt 53e51e744be6533f1ad9bdd3787c28dfb2f705c3ac3c6bcb91254ad79ee2a1c8 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/lan/UpnpIdentityTest.kt 2b9b147f2d69cc14261dbc6a445e382e01a4b326654a4fa40d3687101bc9adce synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/nav/AdaptiveNavigationTest.kt f7a00c8c9b6c312e1b4fcb0c16e7de346372bed9752fcfdeefb1090b78050ad1 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/nav/AppTargetTest.kt 457c496825f2fdfb13094b81664e5cf7113c2ac6aa9e8e900abf81a1432a94e8 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/net/LocalTargetTest.kt da5c0b5039109732bf312eeb8abba3804430a17502ddd3c89284b53a5dd02f7f synthetic shared/src/commonTest/kotlin/cz/netkit/shared/net/ToolRouteTest.kt 595657ef77d012d5776e061f7cb7d92ea51d6ad9a1d4195e0da85650b69c194b synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusTest.kt 5d5e4c6f255e1bbd981e27885ec79c744dbc8114551b4c7fc2a005ba5cccff0d synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/netstatus/NetStatusViewTest.kt d2850a970dfc29ff83fe2afd027a681e3c3abfa53248fa8b0d09cc6a8e5a37a5 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/overview/OverviewTest.kt 3c68f9e6ab159aff5887c29e04d1b1a8ddb24174fd06faeb6097fd54fb9b1e7e synthetic shared/src/commonTest/kotlin/cz/netkit/shared/publicip/PublicIpTest.kt a9c5d103c292b47791e992710c4d1f18d44b88a5a6af55a64b3675b3259bdf06 synthetic -shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedDataEstimateTest.kt bd1cc15975f3a5ec8f306b55892126e187a62e32e558f1a6e23a462e1cf8b6fa synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/publicip/RdapTest.kt e38b167b80419e21ea6be813f4ad5326da230ec02ef779bbbba2a3d0e569216f synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/report/DiagnosticReportTest.kt 4a746ec475c3301eb6a9de42f26eb4ea7a28e40e899965fc41fa09add98bd0be synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/settings/AppSettingsTest.kt d09479ca02a2727ea2fb5f582fe400ebb37d1fa9cd3a47b02e03ab383154ebb4 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/speed/Iperf3ProtocolTest.kt 04f114d8191b0b9632d5bd77db103556ddd691502ce9f44e206d90576ba378f0 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedDataEstimateTest.kt a4029ca8fa0ffe49ec24fa17221845772ec204ff6bf0f1c28b83ed0334d0f4e4 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedHistoryClearTest.kt 00bcce583831280a997f76a322b33ca399b10023fd9a076b8a5d5349a6587734 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedMeasureTest.kt 3f83d9caf63e2e0bbf028fe973d1c86bc23d64c4efe31dc321413862b721f0ac synthetic shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedProtocolTest.kt 6caefd8769c48b206162a0b5a945e286acd7f3376c5506a03c3cfdcaa9e96ccd synthetic shared/src/commonTest/kotlin/cz/netkit/shared/speed/SpeedScaleTest.kt 1cb9081ceeebf56bd3b811a89b26ffb7b2a5a60f64cb8ab6d891d512f4db90cc synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/PromptReplyGateTest.kt 8f3c1230f694551744135df776c165f2a0591cd535f3d3b233e04535a9383c3b synthetic -shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt 025b1e4d50600d53da9ddd3611145737e33093d5ae406961572908587d7050de synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SftpTest.kt 7dffb8de01afe80671f716d2292d28318757a7edfa5534308bf07ab6b192d4f9 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshBackgroundPolicyTest.kt 42260d8c05243a905dd2341e63f968d9be07533fd04def4ba3e47698ac930d5f synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshDirectoryTest.kt 17aa172bb7703e2a5245eec9e3afa897eec400cedd12bdc06fc9262c1a1cca28 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshExportProductivityTest.kt 4fa68238e5621e538ad8bef6657bbb7cec92d80f65b9e55cd2c646e3b3a2e8b2 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshLegacyFixture.kt 55d45dfd0d9e7cad60f8057079fea1744c014f2729aa9679f280b3c5d77fc052 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPolicyTest.kt 0425d82c1ef252cb141348691ec1a75fe66fb2da15566f7a7058ab65f7f5bcd0 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProductivityTest.kt 402b1efa8135214fd596c219edf16b0b9999c7324169a67fc9ccd95af933394e synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileExchangeTest.kt e30cbe3d0e3646ff4d9c667a611f713882dab131763f3decefa934f5520fdbba synthetic -shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt 72bdb590d923baf362c03ec2b0b0f7bfa685a288d3fbbaf0890b008577f9ce75 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshProfileImportTest.kt 1fc3570322f468dd70dcd8b0ae91976b97f0b81966cd5339aa616547ceae5b8e synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/SshPromptPolicyTest.kt 8345a4988474ac901a1773ec6f5da3540aea33a971d2caf2593efeb3b3368347 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TelnetConsoleTest.kt c56e4b728008d5a40b1465b8e6b646cb41cba4de9b1c12c669e49caf95266116 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalBufferTest.kt 6248b4c2d185617f67b34168cc21d42406d8a91c8aa523bd94e58afd90e4b10c synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalCompositionTest.kt c829e4d2b6e29868b639e61a4bd303ed44f1ae9b1c3e71960f3f9ea23d99d13e synthetic -shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalInputTest.kt 1b2b9fc8fcc1bb5f71a795151d42b00d820239fd8e1b3a4cab5a07199aaf5a3a synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalInputTest.kt dad010b795a03b55ca206324215ace8aade1d0fa30c3f11163afcb78a3a766e9 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalSessionBuffersTest.kt 14e3455ce083a49ca38d0d8ea688f8c138a567d55f25dd179ccdefa04fcf3ef1 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalWritePumpTest.kt 7e81dafea64a33a2085ab642804ea25f2cfd7954d3b47432b8bd334de51db52d synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/ssh/TerminalXtermTest.kt ace71d02a282a81a14e74c343ec11f37b78ba0bd52c4489bf616cdb4046c46f0 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/update/ProjectLinksTest.kt 88171bd46016b523da43903079da19992127d112eec03318fcdda50127185d76 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/update/UpdateFetchTest.kt d59d2cf411c6e83f25a69a10e103493db7006978c5e22a11ac36b73e8848b4ce synthetic shared/src/commonTest/kotlin/cz/netkit/shared/update/UpdateInfoTest.kt cb228f029b1be648fb9029f479c05db96ee0e3460833dfd69b736d5ec1cf7f33 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/wifi/BondingCenterTest.kt e33814c7ab867efc98efb0e1e9dd87b18ad406539f131787d33607b31e88bbad synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wifi/LiveChartTimelineTest.kt 7d3393757e79c7e01dc8a2dcfdacf7fdbbb4acc4daec2490894bc02a02728723 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wifi/LiveTelemetryTest.kt 919415ae983caf87db354d7da8aab76521a83aa76c9ef32239624cd2b8246f67 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/wifi/MloTest.kt f68282d203820612865b34dd7cce536408c7316d4b3ff1f7c2df012e13eb2700 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wifi/OuiDatabaseTest.kt 9b7cacdc941ea794154fa343c28e55a02b9037038a915cbdb4ab6bb90f2e76b1 code -shared/src/commonTest/kotlin/cz/netkit/shared/wifi/SpectrumTest.kt b01701587f8533348a1b13fb1a5446c877014cfb7406dbe929340cb203833c7e synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/wifi/SpectrumTest.kt 83eb8275aa421927ae4e745ed80a0ef4bcd3ea2cdd37a3ab8e56d91b1f4a1163 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WalkLogTest.kt ec7e8ea179a9fa1d30d55e482a44703b3fcd7c98e30d85b2f39402951c20ca4d synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiDatasetPolicyTest.kt 2e36855c46f95b08e2295d378beb01ae15b5c6af0c07191fca909f51430c60a2 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiDomainTest.kt ea61b2d529118501c06d6e93d6a85f1922cab4863c97089c04a04bccbda3a31c synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiExtensionsTest.kt dee76cb1602d686c6a7921a5985beadfb7c7cd31118ea698552d64d0c74af9ac synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiRevisionTest.kt 13c688df5e7f1d9de2e36578274205fe90e0a745a4d308772dff5cfbff403ab8 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wifi/WifiUiPolicyTest.kt ea243311294f5ea96e3558ee1a5f437c88a719f9aa5ee4035818cf17a81090c9 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wol/WakeProbePolicyTest.kt 99c02d0696b7b6030fe756b66f655df41fe3ac8b8df8cdd38a1a2c1ae9c862d0 synthetic @@ -406,11 +677,16 @@ shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolDomainTest.kt aac8696c71220 shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolImportLimitsTest.kt b081118130fb4ae3b13dabd2c2c27a9b7014863d52b35117d35466e50c04dde3 synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolInteractionRevisionTest.kt a0738f1f9be31eef54e28fb0d7dca5422d6888fa1745d9c9bc98062a7fe8082c synthetic shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolRevisionTest.kt 5815bdb1b68548050ef78acae6b968eecb9ec1a905622397c5b9f6e7d9326079 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolSecureOnTest.kt 143fc0c941e395646ddc56880b575a69fbd04c9e843d784c43f2d8f036cf8d27 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWakeTest.kt 3ffc9608a1acbdfc4ff1b96b025c74afe9f2b612e2daf567ecd77074bbaba962 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetModelTest.kt 24a53ea68bf7846a9aade3a7e45e75f7e216388d7f67ba8de116075db94701df synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetRunTest.kt afa0fd991b130964053584fa60d43bce94689adef0f26fb3c92e67fee4fc8db8 synthetic +shared/src/commonTest/kotlin/cz/netkit/shared/wol/WolWidgetSecureOnTest.kt 504f0276223205b31002b156cb71c51585547eeaad6efdd6125729a4e8ee41dc synthetic shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosAboutDomain.kt d2e95a175c907ff23f448f55f8cd79964d6e815c5c714b1db556aca3d65aa11c public-service shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosNetworkDomain.kt 568650d0a2b67d7caf226cd307fcc1c07ca9af5b3e590c9063bc40cbc049afd6 code shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSecretStoreAdapter.kt 8c0e7795b089ecd3e6662440ae19081717932cda910e05f7aff0e38b58e5e91b code shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSpeedDomain.kt 2e17fc1d808434dbefb1b8ce6868e0d600294e4973cb54afa6c5f5317fad1fcd code -shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt abdafd36c1abb7473fec46e284e8cfdb43e37458effa17798300637390511db2 code +shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosSshDomain.kt 65d24b4ce0d370835f935043555f71bd5c3f08d3672b6288fd46b1dccdda3a04 code shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosTerminal.kt 14086e1dada83f13a6bf96bfaf8dd130fdad286e89890986b6833db6120569fe code shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolBridge.kt 16580456f96b515c328d21ced102df133957cdc5ebef2b78eaf0e5f1fb496871 code shared/src/iosMain/kotlin/cz/netkit/shared/ios/IosWolCodec.kt 758c6bb92e3a37ebd3755e5ab347408b284af32587bcb56da78cb2318233706a code @@ -420,29 +696,38 @@ shared/src/iosTest/kotlin/cz/netkit/shared/IosDomainSmokeTest.kt 6ab507180a14097 shared/src/iosTest/kotlin/cz/netkit/shared/IosSshBridgeTest.kt 22ed8d00a3739867775ef9345ae6772251888a4fe72d953683c21782f263ec39 synthetic tools/check_contrast.py 3f22880af40b94f990a6b74d6fe24eab68902b202edeeacb8eadf4593ee09118 code tools/check_release_version.sh 71bdd2e01f862fd123e01f14fbaa380dd5c8e45acf7f4c6627fb87c4b7bae052 code -tools/m1_provision.py c116d8c87ad1dcc9995bf7260268b1f368fd58fbc60879216a13e96f8b10e9a0 code +tools/m1_provision.py 32311dd7cf08653085fe344a3e1bbc14344d405f18d3aa106c95b221af614ef3 code tools/make_public_export.sh da89e4e62b4fa20240c2dc436898862e89549b7a8ab41a36ac5f194512ca5fa5 code -tools/netkit_ssh_export.py 6173d6cb09b379d991aa7c96b62a24c5ecbb51ecda6d6681946dcc1c4414c613 code -tools/public_export.manifest 8c38891210702e0cbbcf39b2b2c7586c9c35b1935999f4328727ee71ea296b9a code +tools/netkit_ssh_export.py 1c8c2918318cbbc0304c68f59a5d625a8567a6aae0526dac1f36b76850208e6f code +tools/public_export.manifest d86735b94d114478b94055b05b48f232efae7289ab1da89ab5d5a5b07e2c971d code tools/public_export.py e2bb5273ea3b14653ac644558fad2773f154c95a318d4153b3333058c78dfa61 code tools/release_latest_json.py a09e0a0436669e6a03f8e618f52591c6e739692a0aafc4e374a7570a9992ae28 code -tools/run_m1_checks.py cff6be0b27d3f0423e2d679e587817722dfbb91a9b760e8d34587b01d3db7331 code +tools/run_m1_checks.py 5ce016196fea0d91913dbb97aa7735fe8024a1de7c8fda4502f813b77e432111 code tools/run_wol_e2e.py 376daa244f5f91a3122981f28e1e31a3cbe085a63638f9b11e435444b608783c code tools/sign_release.sh ea97d642d3e81506bd1436cac206d90dc0377dd92fd2fa8fb6e315602029af2f code -tools/test_check_contrast.py ea946e5e927c7f8181ea7ad504463b64826ded5f3d54118042d600018cd3761a synthetic -tools/test_m1_fixture_server.py 792230469667597e6a1cf8bd6bf259b5de3bdd0aa6fd6c5704bb72c5aa8d4137 synthetic +tools/test_check_contrast.py 38649a44ba8e48820e783c8464776a846acd67b5f4a00d9d6aaa810e132a8873 synthetic +tools/test_m1_fixture_server.py 058cb8c4f6bb72ea1ca07898d43f4f16db103c4b53502fcc2be287677b3df749 synthetic tools/test_m1_identity.py a4cea900381def37423a33fe52b6e179cffc71b7bd99b114a3d96caac7bb689a synthetic -tools/test_m1_provision.py 9025035732eb080cc8a3f27a58f8d1d0ddad94c7c12ffd960cdaf177971ab2e8 synthetic -tools/test_netkit_ssh_export.py 13ad972955f27e7a0fcedd97868578726a3c4e78a262e7816c07f6d1850150b4 synthetic +tools/test_m1_provision.py 187a00eb673eaabdc527d01d2f695477b533eef7f3af7e9bd6f752a8c84e2101 synthetic +tools/test_netkit_ssh_export.py 791fb9b65f75ffc92ee11d9e6168aae2686e7a47cf551c1b947d0d9789129079 synthetic tools/test_public_export.py 8af286595e14832ba22dc2e344177a865840ae696350784787023793242bc641 synthetic tools/test_release_latest_json.py 1e463469417e59ca36a74a6c00e0752c49a46c83e6cc0e8670375dc5e6b69a96 synthetic -tools/test_run_m1_checks.py 785141a352c89ab6ba8f578b2e05983d2772e7aa4df9c22e6c0328573f232394 synthetic +tools/test_run_m1_checks.py 341af000eda6631401d723bfd9643a8ce2c9e2f3de0855bad9bffa254afb8f8c synthetic tools/test_run_wol_e2e.py 14a7c389761af64b482dfee592779a67fcaa3acf0301cb1f9d3bf3a078638c63 synthetic tools/test_update_oui.py b93e4ca96df28d511b426b58360c5f4750aaf9264ff9225cffb9b75070a65485 code +tools/test_update_terminal_width.py 63d1617c20b4ebab172efe0cebcdb93103679a8fa36faf530c37950847553c7e synthetic tools/testsrv/__init__.py 6af26ea6d644d46ee68bd60871001fd9593d442da5fb49d7edb4071a5f6dbd59 code -tools/testsrv/m1_fixture.py ac34fb43bb068e8e4d68e837cf8fc7441d696e465e45f764371cd77d9c05fca4 code -tools/testsrv/test_m1_fixture.py 17502aa748762f8325f10c538f9af2a8e20e467066415b4d9b8eb5c95712e47b synthetic -tools/testsrv/wol_listener.py 1fb954425dd31a0633d285dcd5f88ee018467f0f15e99af690aea49cc5f21b49 code +tools/testsrv/iperf3_fixture.py 0b1e9ea2d42baecff95da92f08041ab61e25c1f98a3afcc77b2c9ae833e96e9e synthetic +tools/testsrv/m1_fixture.py 787ed8685b1b39c9352d83a2f59c9799662642c04d320e5022631a45cf0f78a8 code +tools/testsrv/telnet_fixture.py 9c8213446b4c4f8160ccad54b77edbc2ee28f8e64b02f61017610b4e44354046 synthetic +tools/testsrv/test_iperf3_fixture.py 93c16f591b75d0bf3db03fe08b96d886227589fe1deaa3022dc9e9ceb1fc5b8f synthetic +tools/testsrv/test_m1_fixture.py 8388afda2f0fbd734278ed605bf36573a45ea2685b67c82256c951b440f2a386 synthetic +tools/testsrv/test_udp_services.py 7e1651fe8c1ff429735a6c8edcbdef8c0e750cbd10657778f3e52eefac0f7b35 synthetic +tools/testsrv/test_wol_listener.py c20d6e92a5bdf5fffd607a97a19eca76aca95d737532970c612f87d8e80fe781 synthetic +tools/testsrv/udp_services.py e8255109c8891a672a42387544d429fc5ec446182c3d4ae9f335436fde319226 synthetic +tools/testsrv/web_diagnostic.py 1baf9a5b6736359c999facb0f89d5971845711d80701cc2d2a09570bb3a0fe05 synthetic +tools/testsrv/wol_listener.py a9f38ec2722b9c9575d69d5b7213f73f7596d85afe6fcaf293de603e4c4e86ff code tools/update_oui.py 0912c381e89c1728bf518027cc84b745ccb073fd24b484592cd6bc901529050b code +tools/update_terminal_width.py 01cd365609efdebb79d0c92ad20e2524b4ae676e7c2be5971cd1ba5529370ae0 code tools/verify_release_assets.sh c3099f8fbbfc32c192b0fe05149c1358c6e675d02829c0bfbcca5a4f5d3aa998 code web/netkit/README.md fc882c2dd03d94699662603921fabfa6b3031042e15586bfb4b4fd740dd91e89 documentation diff --git a/tools/run_m1_checks.py b/tools/run_m1_checks.py index e402b7f..30724fa 100755 --- a/tools/run_m1_checks.py +++ b/tools/run_m1_checks.py @@ -40,6 +40,19 @@ "LAN_CONFIRM:ACTUAL_RESULT_PUBLISHED:PASS", "PHASE:lan-confirm:PASS", ), + "lan-tools": ( + "PHASE:lan-tools:START", + "LAN:SUBNET:PASS", + "LAN:SUBNET:MASK_0:PASS", + "LAN:SUBNET:WILDCARD_32:PASS", + "LAN:DF_SUPPORTED:", + "PHASE:lan-tools:PASS", + ), + "lan-trace-pause": ( + "PHASE:lan-trace-pause:START", + "LAN:TRACE:RESUME_CANCEL:PASS", + "PHASE:lan-trace-pause:PASS", + ), "ssh-rotated": ( "PHASE:ssh-rotated:START", "SSH:SERVER_ROTATION_REJECTED:PASS", @@ -116,6 +129,241 @@ PHASE_MARKERS["wifi-freshness"] = ("PHASE:wifi-freshness:START", *("WIFI:FRESHNESS:" + name + ":UI_VERIFIED" for name in ("fresh", "aging", "within-five-minutes", "expired", "cache")), "WIFI:CHART:SYNTHETIC_SIX_STYLES:UI_VERIFIED", "WIFI:VENDOR:list:UI_VERIFIED", "WIFI:VENDOR:detail:UI_VERIFIED", "PHASE:wifi-freshness:PASS") +PHASE_MARKERS["wol-widget-intent"] = ("PHASE:wol-widget-intent:START", "WOL_WIDGET:PLACED_WIDGET:PASS", "WOL_WIDGET:STALE_INTENT_REFUSED:PASS", "WOL_WIDGET:CURRENT_INTENT_SENT:PASS", "PHASE:wol-widget-intent:PASS") + +NETSTATUS_RENDER_CASES = ("fresh-small", "fresh-medium-ssid", "fresh-medium-no-ssid", "lockscreen-medium", "stale-small", + "stale-medium", "nodata-small", "nodata-medium") +PHASE_MARKERS["netstatus-widget"] = ("PHASE:netstatus-widget:START", "NETSTATUS:LOCATION_CONTROL_NOTED:PASS", + "NETSTATUS:REFRESH_UNDER_10S:PASS", "NETSTATUS:REFRESH_NO_LOCATION_OP:PASS", + "NETSTATUS:REFRESH_NO_TRAFFIC:PASS", "NETSTATUS:TRAFFIC_CONTROL_COUNTED:PASS", + "NETSTATUS:REFRESH_RADIO_UPDATED_SSID_KEPT:PASS", + *(f"NETSTATUS:RENDER:{name}:PASS" for name in NETSTATUS_RENDER_CASES), + "PHASE:netstatus-widget:PASS") + +PHASE_MARKERS["wifi-spectrum"] = ("PHASE:wifi-spectrum:START", "WIFI:SPECTRUM:AXIS24:UI_VERIFIED", "WIFI:SPECTRUM:CENTER_UNKNOWN:UI_VERIFIED", "WIFI:SPECTRUM:LEGEND_LONG_SSID_FONT_1_3:UI_VERIFIED", "PHASE:wifi-spectrum:PASS") + +# Zadání 39. Prefix markers (ending in ':') accept the measured value or a documented NOT_POSSIBLE. +PHASE_MARKERS["lan-list"] = ("PHASE:lan-list:START", "LAN_LIST:FIRST_FRAME_MS:legacy=", "LAN_LIST:LAZY_VISIBLE_ITEMS:", + "LAN_LIST:SCROLL_END_ROW_254:PASS", "LAN_LIST:ANCHOR_KEPT_ON_INSERT:PASS", + "LAN_LIST:254_ROWS_TESTTAGS:PASS", "PHASE:lan-list:PASS") +PHASE_MARKERS["lan-v39"] = ("PHASE:lan-v39:START", "LAN_INFO:SDK:", "LAN_INFO:CARD:PASS", "LAN_IPV6:PING_LOOPBACK_VM:PASS", + "LAN_IPV6:TRACE_REFUSED:PASS", "LAN_IPV6:PING_OWN_LINK_LOCAL:", "LAN_IPV6:TCP_LOOPBACK_OPEN:PASS", + "LAN_IPV6:AAAA_LOCALHOST:", "PHASE:lan-v39:PASS") +PHASE_MARKERS["lan-udp"] = ("PHASE:lan-udp:START", "LAN_UDP:SNMP:PASS", "LAN_UDP:NTP:PASS", "LAN_UDP:DNS_VERSION:PASS", + "LAN_UDP:WRONG_COMMUNITY_SILENT:PASS", "PHASE:lan-udp:PASS") +PHASE_MARKERS["wol-secureon"] = ("PHASE:wol-secureon:START", "WOL_SECUREON:STORED_NOT_EXPORTED:PASS", + "WOL_SECUREON:SENT_TO_HOST_LISTENER:PASS", "PHASE:wol-secureon:PASS") +ACCESSIBILITY_LANGUAGES = ("cs", "en") +ACCESSIBILITY_SCREENSHOTS = tuple( + f"accessibility-{language}-{scene}.png" for language in ACCESSIBILITY_LANGUAGES + for scene in ("ping", "lan", "speed", "iperf", "charts", "spectrum") +) +PHASE_MARKERS["accessibility"] = ( + "PHASE:accessibility:START", + *(f"ACCESSIBILITY:{language}:{check}:PASS" for language in ACCESSIBILITY_LANGUAGES + for check in ("HEADING_STATUS_TARGET", "OFFSCREEN", "LAN_RESULTS", "speed", "iperf", "CHARTS", "SPECTRUM")), + "PHASE:accessibility:PASS", +) +PHASE_SCREENSHOTS: dict[str, tuple[str, ...]] = { + "accessibility": ACCESSIBILITY_SCREENSHOTS, + "lan-list": ("lan-list-top.png", "lan-list-middle.png"), + "lan-v39": ("lan-network-info.png",), +} + +PHASE_MARKERS["ssh-forward"] = ( + "PHASE:ssh-forward:START", + "SSH_FWD:FORWARDS_STATUS:PASS", + "SSH_FWD:LISTEN_LOOPBACK_ONLY:PASS", + "SSH_FWD:LOCAL_ECHO:PASS", + "SSH_FWD:HALF_CLOSE_REPLY:PASS", + "SSH_FWD:SOCKS_AUTH_REQUIRED:PASS", + "SSH_FWD:PORT_IN_USE_REPORTED:PASS", + "SSH_FWD:SOCKS_CONNECT_ECHO:PASS", + "SSH_FWD:SOCKS_DOMAIN_ECHO:PASS", + "SSH_FWD:SOCKS_BIND_REJECTED:PASS", + "SSH_FWD:SOCKS_DENIED_TARGET:PASS", + "SSH_FWD:CLOSE_RELEASES_PORTS:PASS", + "SSH_JUMP:PER_HOP_TOFU:PASS", + "SSH_JUMP:TARGET_SHELL:PASS", + "SSH_JUMP:TARGET_CHANGED_KEY_REJECTED:PASS", + "SSH_JUMP:CYCLE_REJECTED:PASS", + "PHASE:ssh-forward:PASS", +) + +PHASE_MARKERS["ssh-snippet-log"] = ( + "PHASE:ssh-snippet-log:START", + "SSH_SNIPPET:BAR_VISIBLE:PASS", + "SSH_LOG:WARNING_SHOWN:PASS", + "SSH_LOG:SAF_DESTINATION:PASS", + "SSH_SNIPPET:SENT_FROM_BAR:PASS", + "SSH_LOG:SAF_FILE_PLAIN_TEXT:PASS", + "PHASE:ssh-snippet-log:PASS", +) + +# Zadání 42: SSH session foreground service (AC-001), SFTP against the fixture (AC-003) and the +# review-of-41 tunnel panel with the keyboard open. +PHASE_MARKERS["ssh-background"] = ( + "PHASE:ssh-background:START", + "SSH_BG:GRACE_MS:3000", + "SSH_BG:PERMISSION_STATE:granted", + "SSH_BG:SERVICE_FOREGROUND:PASS", + "SSH_BG:NOTIFICATION_PRIVATE:PASS", + "SSH_BG:SESSION_SURVIVES_BACKGROUND:PASS", + "SSH_BG:DISCONNECT_ALL_STOPS_SERVICE:PASS", + "PHASE:ssh-background:PASS", +) +PHASE_MARKERS["ssh-background-denied"] = ( + "PHASE:ssh-background-denied:START", + "SSH_BG:GRACE_MS:3000", + "SSH_BG:PERMISSION_STATE:denied", + "SSH_BG:PERMISSION_ASKED_AT_CONNECT:PASS", + "SSH_BG:LIMIT_BANNER:PASS", + "SSH_BG:NO_SERVICE_WITHOUT_NOTIFICATIONS:PASS", + "SSH_BG:FALLBACK_LIMIT_CLOSES:PASS", + "PHASE:ssh-background-denied:PASS", +) +PHASE_MARKERS["ssh-sftp"] = ( + "PHASE:ssh-sftp:START", + "SFTP:HOME_REALPATH:PASS", + "SFTP:LIST:PASS", + "SFTP:DOTDOT_NORMALIZED_BY_SERVER:PASS", + "SFTP:SYMLINKS_RESOLVED_IN_SANDBOX:PASS", + "SFTP:DOWNLOAD_SHA256:PASS", + "SFTP:DOWNLOAD_CANCEL:PASS", + "SFTP:UPLOAD_ROUNDTRIP:PASS", + "SFTP:UPLOAD_EXISTING_TARGET_UNTOUCHED:PASS", + "SFTP:UPLOAD_CANCEL_REMOVES_TEMP:PASS", + "SFTP:PUBLISH_NEVER_OVERWRITES:PASS", + "SFTP:RENAME_NO_OVERWRITE:PASS", + "SFTP:MKDIR_AND_NAMES:PASS", + "SFTP:DELETE_EXACT_ENTRY:PASS", + "SFTP:CHANNELS_RELEASED:PASS", + "SFTP:CANCEL_HANGING_PEER:PASS", + "SFTP:IO_TIMEOUT_HANGING_PEER:PASS", + "SFTP:CLOSE_DURING_OPEN_RELEASES:PASS", + "SFTP_UI:BROWSER_LISTED:PASS", + "SFTP_UI:NAVIGATE_LINK_AND_UP:PASS", + "SFTP_UI:SAF_DOWNLOAD:PASS", + "SFTP_UI:DELETE_CONFIRMED:PASS", + "PHASE:ssh-sftp:PASS", +) +PHASE_MARKERS["ssh-forwards-panel"] = ( + "PHASE:ssh-forwards-panel:START", + "SSH_FWD_UI:TERMINAL_VISIBLE_WITH_IME:PASS", + "SSH_FWD_UI:DETAILS_BOUNDED_SCROLLED:PASS", + "PHASE:ssh-forwards-panel:PASS", +) +# Separate from main's PHASE_SCREENSHOTS (zadání 39; names with .png): a merged second definition overrode it. +SSH42_SCREENSHOTS: dict[str, tuple[str, ...]] = { + "ssh-background": ("ssh-bg-notification",), + "ssh-background-denied": ("ssh-bg-permission", "ssh-bg-limited"), + "ssh-sftp": ("sftp-browser", "sftp-delete-confirm"), + "ssh-forwards-panel": ("ssh-forwards-ime", "ssh-forwards-expanded"), +} +# Zadání 43: xterm output over the real SSH session (256 colours, alternate screen, title, restore). +PHASE_MARKERS["ssh-xterm"] = ( + "PHASE:ssh-xterm:START", + "SSH_XTERM:COLORS_256:PASS", + "SSH_XTERM:ALT_SCREEN:PASS", + "SSH_XTERM:TITLE_SHOWN:PASS", + "SSH_XTERM:ALT_RESTORED:PASS", + "PHASE:ssh-xterm:PASS", +) + +# Zadání 38: pins, ESS groups, scan export through SAF (file read back), walk card, regional note. +PHASE_MARKERS["wifi-extensions"] = ("PHASE:wifi-extensions:START", "WIFI:PIN:ORDER:UI_VERIFIED", "WIFI:PIN:MISSING:UI_VERIFIED", + "WIFI:PIN:DETAIL:UI_VERIFIED", "WIFI:PIN:MISSING_UNPIN:UI_VERIFIED", "WIFI:REGION:NOTE:UI_VERIFIED", "WIFI:ESS_GROUPS:UI_VERIFIED", + "WIFI:EXPORT:CSV:SAF_FILE_VERIFIED", "WIFI:EXPORT:JSON:SAF_FILE_VERIFIED", + "WIFI:WALK:MARK:UI_VERIFIED", "WIFI:WALK:SUMMARY:UI_VERIFIED", "PHASE:wifi-extensions:PASS") + +# Zadání 46: predictive back, Settings (theme, consents, histories, updates, language) and KeepScreenOn. +PHASE_MARKERS["system-settings"] = ( + "PHASE:system-settings:START", + "SYSTEM:BACK:TAB_TO_OVERVIEW:PASS", "SYSTEM:BACK:WOL_EDITOR:PASS", "SYSTEM:BACK:SSH_EDITOR:PASS", + "SYSTEM:BACK:ABOUT_LICENSES:PASS", "SYSTEM:BACK:SETTINGS:PASS", "SYSTEM:BACK:OVERVIEW_LEAVES_APP:PASS", + "SYSTEM:SETTINGS:OPENED:UI_VERIFIED", "SYSTEM:THEME:DARK:PIXEL_AND_STORE_VERIFIED", "SYSTEM:THEME:LIGHT:PIXEL_VERIFIED", + "SYSTEM:THEME:SYSTEM:RESTORED", "SYSTEM:KEEP_SCREEN:SWITCH:STORE_VERIFIED", "SYSTEM:ONLINE:TOGGLE:PREFS_VERIFIED", + "SYSTEM:RESET:LAN_CONSENT:PREFS_VERIFIED", "SYSTEM:RESET:NDT7_CONSENT:STORE_VERIFIED", + "SYSTEM:CANCELLED_CALLER:LAN_CONSENT:STATE_AND_PREFS_VERIFIED", + "SYSTEM:IPERF_TARGET:STORED_NOT_FORM:UI_VERIFIED", "SYSTEM:CANCELLED_CALLER:IPERF_TARGET:STATE_AND_STORE_VERIFIED", + "SYSTEM:DELETE:TARGET_HISTORY:FAVORITES_PRESERVED", "SYSTEM:LANGUAGE:SSH_CHANNEL:VERIFIED", + "SYSTEM:DELETE:SPEED_HISTORY:STORE_VERIFIED", "SYSTEM:DELETE:IPERF_HISTORY:STORE_VERIFIED", + "SYSTEM:FORGET:IPERF_TARGET:STORE_VERIFIED", "SYSTEM:UPDATES:IN_SETTINGS:UI_VERIFIED", + "SYSTEM:ABOUT:SETTINGS_LINK:UI_VERIFIED", "SYSTEM:LANGUAGE:UI_SWITCH:PASS", + "SYSTEM:KEEP_SCREEN:IDLE:OFF", "SYSTEM:KEEP_SCREEN:RUNNING:ON", "SYSTEM:KEEP_SCREEN:SETTING_OFF:OFF", + "SYSTEM:KEEP_SCREEN:SETTING_ON:ON", "SYSTEM:KEEP_SCREEN:OVERLAP:ON", "SYSTEM:KEEP_SCREEN:RELEASED:OFF", + "SYSTEM:KEEP_SCREEN:WINDOW_FLAG:VERIFIED", + "PHASE:system-settings:PASS", +) +SYSTEM_SETTINGS_SCREENSHOTS = ("settings-menu", "settings-top", "settings-dark", "settings-privacy", "settings-confirm-lan", + "settings-data", "settings-confirm-delete", "settings-data-cleared", "settings-updates", + "about-settings-link") +# Phases that take the app language (cs/en) as an instrumentation argument. +LANGUAGE_PHASES = ("lan-tools", "system-settings", "landscape-mlo") +PHASE_MARKERS["landscape-mlo"] = ("PHASE:landscape-mlo:START", "LAYOUT:landscape:TABS:PASS", "LAYOUT:tablet:TABS:PASS", + "LAYOUT:TERMINAL:PASS", "MLO:SYNTHETIC:PASS", "PHASE:landscape-mlo:PASS") +LANDSCAPE_SHOTS = ("portrait", *(f"{layout}-{tab}" for layout in ("landscape", "tablet") + for tab in ("signal", "wifi", "lan", "ssh", "wol")), "landscape-terminal", "mlo-synthetic") + + +def landscape_shots(language: str) -> tuple[str, ...]: + return tuple(f"{name}-{language}.png" for name in LANDSCAPE_SHOTS) + + +# Zadání 53: cell detail on the emulator's synthetic LTE cell; the runner revokes the permissions first +# (revoking inside the instrumentation would kill its own process). +PHASE_MARKERS["cell-detail"] = ("PHASE:cell-detail:START", "CELL:DETAIL:NO_REQUEST_WITHOUT_PERMISSION:PASS", + "CELL:DETAIL:PERMISSION:UI_VERIFIED", "CELL:DETAIL:LTE:band=", + "CELL:DETAIL:LTE:cs:UI_VERIFIED", "CELL:DETAIL:LTE:en:UI_VERIFIED", + "CELL:DETAIL:FORGET_ON_COLLAPSE:PASS", "PHASE:cell-detail:PASS") +CELL_DETAIL_SCREENSHOTS = ("cell-detail-permission-cs", "cell-detail-cs", "cell-detail-en") +CELL_DETAIL_REVOKED = ("android.permission.READ_PHONE_STATE", "android.permission.ACCESS_FINE_LOCATION", + "android.permission.ACCESS_COARSE_LOCATION") + +# Zadání 47: long-press copy, diagnostic report (share + SAF text/JSON), device export, speed share; CS and EN. +PHASE_MARKERS["share-results"] = ("PHASE:share-results:START", "SHARE:COPY:IPV4:PASS", "SHARE:COPY:BSSID_SENSITIVE:PASS", + "SHARE:COPY:cs:UI_VERIFIED", "SHARE:REPORT:DEFAULTS_OFF:PASS", "SHARE:REPORT:SHARE_INTENT:bytes=", + "SHARE:REPORT:SAF_TEXT:PASS", "SHARE:REPORT:SAF_JSON:PASS", "SHARE:REPORT:SSID_OPT_IN:PASS", + "SHARE:REPORT:cs:UI_VERIFIED", "SHARE:DEVICES:CSV:SAF_FILE_VERIFIED:rows=", "SHARE:DEVICES:cs:UI_VERIFIED", + "SHARE:SPEED:SHARE_INTENT:PASS", "SHARE:SPEED:cs:UI_VERIFIED", "SHARE:COPY:en:UI_VERIFIED", + "SHARE:REPORT:en:UI_VERIFIED", "SHARE:DEVICES:en:UI_VERIFIED", "SHARE:SPEED:en:UI_VERIFIED", + "PHASE:share-results:PASS") +PHASE_SCREENSHOTS["share-results"] = tuple(f"share-{kind}-{language}.png" for language in ("cs", "en") + for kind in ("copy", "report", "devices", "speed")) +# Zadání 48: shared target history/favourites, TCP ping to a loopback listener, MAC → vendor; CS and EN in one run. +TOOLS_TARGETS_LANGUAGES = ("cs", "en") +PHASE_MARKERS["tools-targets"] = ( + "PHASE:tools-targets:START", + *(marker for language in TOOLS_TARGETS_LANGUAGES for marker in ( + f"TARGETS:MENU_FILTERED:{language}:UI_VERIFIED", f"TARGETS:CHOOSE:{language}:PASS", + f"TARGETS:WEB_URL_ONLY:{language}:PASS", f"TARGETS:STAR_LABEL:{language}:PASS", + f"TARGETS:CLEAR_KEEPS_FAVORITES:{language}:PASS", f"TCP_PING:LOOPBACK:{language}:sent=4;received=4;rtt=", + f"TARGETS:REMEMBERED_ON_START:{language}:PASS", f"TCP_PING:{language}:UI_VERIFIED", f"MAC_VENDOR:{language}:UI_VERIFIED", + f"MAC_VENDOR:EXPORT_ERROR_VISIBLE:{language}:PASS")), + "TCP_PING:REFUSED_IS_LOSS:PASS", "MAC_VENDOR:TABLE:PASS", "TCP_PING:ONE_CONNECTION_AT_A_TIME:PASS:max=", + "PHASE:tools-targets:PASS", +) +PHASE_SCREENSHOTS["tools-targets"] = tuple(f"{name}-{language}.png" for language in TOOLS_TARGETS_LANGUAGES + for name in ("tools-targets-menu", "tools-targets-star", "tools-tcp-ping", "tools-mac")) +PHASE_MARKERS["config-backup"] = ( + "PHASE:config-backup:START", + *(f"BACKUP:{step}:{lang}:PASS" for lang in ("cs", "en") + for step in ("ENCRYPTED", "CORRUPT", "AUTH_ERROR", "KEYLESS_NOTE", "SELECT_CONFIRM_CANCEL")), + "BACKUP:ROTATED_PICKER:cs:PASS", + "PHASE:config-backup:PASS", +) +PHASE_SCREENSHOTS["config-backup"] = tuple( + f"backup-{scene}-{lang}.png" for lang in ("cs", "en") + for scene in ("export", "warning", "corrupt", "password-error", "preview", "confirm") +) + ("backup-rotated-picker-cs.png",) +PHASE_MARKERS["ssh-lock"] = ( + "PHASE:ssh-lock:START", + *(f"SSH_LOCK:{check}:{lang}:PASS" for lang in ("cs", "en") for check in ("SHORTCUT", "SYSTEM_CANCEL", "DENIED", "DIRECTORY", "SORT")), + "PHASE:ssh-lock:PASS", +) +PHASE_SCREENSHOTS["ssh-lock"] = tuple(f"ssh-{scene}-{lang}.png" for lang in ("cs", "en") for scene in ("locked", "groups", "sort")) + + UI_SCREENSHOTS = ("wifi", "lan", "ssh", "wol") WIFI_PASS_MARKERS = ("WIFI:VIRTUAL_AP_RESULTS:PASS", "PHASE:wifi:PASS") WIFI_SKIP_MARKERS = ("WIFI:SCAN:SKIP:THROTTLED_CONFIRMED", "PHASE:wifi:SKIP") @@ -153,20 +401,32 @@ def validate_run_id(value: str) -> str: return value -def build_command(adb: str, serial: str, phase: str, run_id: str) -> list[str]: +def build_command(adb: str, serial: str, phase: str, run_id: str, language: str = "cs") -> list[str]: adb_path = validate_adb_path(adb) target = validate_serial(serial) if phase not in PHASE_MARKERS: raise ValueError(f"unsupported phase: {phase}") run = validate_run_id(run_id) command = [adb_path, "-s", target, "shell", "am", "instrument", "-w", "-r", - "-e", "phase", phase, "-e", "runId", run, TEST_COMPONENT] + "-e", "phase", phase, "-e", "runId", run] + if phase in LANGUAGE_PHASES: + if language not in ("cs", "en"): + raise ValueError(f"{phase} language must be cs or en") + command.extend(["-e", "language", language]) + command.append(TEST_COMPONENT) if command[1:3] != ["-s", target]: raise ValueError("internal error: adb command is missing its explicit emulator target") return command -def required_markers(phase: str, run_id: str) -> tuple[str, ...]: +def prepare_commands(phase: str) -> list[list[str]]: + """ADB arguments (without `adb -s `) run before the instrumentation of [phase].""" + if phase == "cell-detail": + return [["shell", "pm", "revoke", "cz.netkit.app", permission] for permission in CELL_DETAIL_REVOKED] + return [] + + +def required_markers(phase: str, run_id: str, language: str = "cs") -> tuple[str, ...]: if phase not in PHASE_MARKERS: raise ValueError(f"unsupported phase: {phase}") markers = PHASE_MARKERS[phase] @@ -177,8 +437,41 @@ def required_markers(phase: str, run_id: str) -> tuple[str, ...]: f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/ui-{name}.png" for name in UI_SCREENSHOTS ) return markers + screenshots + if phase == "landscape-mlo": + return markers + (f"LAYOUT:LANGUAGE:{language}",) + tuple( + f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/{name}" for name in landscape_shots(language)) if phase == "ssh-ui": return markers + (f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/ssh-ui-terminal.png",) + if phase == "netstatus-widget": + return markers + tuple( + f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/netstatus-{name}.png" for name in NETSTATUS_RENDER_CASES + ) + if phase == "ssh-xterm": + return markers + tuple(f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/{name}.png" + for name in ("ssh-xterm-colors", "ssh-xterm-alt", "ssh-xterm-main")) + if phase in PHASE_SCREENSHOTS: + return markers + tuple(f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/{name}" for name in PHASE_SCREENSHOTS[phase]) + if phase == "cell-detail": + return markers + tuple( + f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/{name}.png" for name in CELL_DETAIL_SCREENSHOTS + ) + if phase == "ssh-snippet-log": + return markers + tuple(f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/{name}.png" + for name in ("ssh-log-warning", "ssh-snippet-bar", "ssh-snippet-sent")) + if phase == "system-settings": + other = "en" if language == "cs" else "cs" + return markers + (f"SYSTEM:LANGUAGE:{language}",) + tuple( + f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/{name}.png" + for name in (*SYSTEM_SETTINGS_SCREENSHOTS, f"settings-language-{other}") + ) + if phase in SSH42_SCREENSHOTS: + return markers + tuple(f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/{name}.png" + for name in SSH42_SCREENSHOTS[phase]) + if phase == "lan-tools": + return markers + (f"LAN:LANGUAGE:{language}",) + tuple( + f"SCREENSHOT:files/m1-data/{run_id}/m1-evidence/{name}.png" + for name in ("lan-subnet", "lan-subnet-wildcard", "lan-ping-advanced") + ) return markers @@ -190,7 +483,7 @@ def _instrumentation_fields(output: str) -> tuple[dict[str, list[str]], list[int return fields, codes -def parse_output(output: str, *, phase: str, run_id: str, exit_code: int) -> PhaseResult: +def parse_output(output: str, *, phase: str, run_id: str, exit_code: int, language: str = "cs") -> PhaseResult: if phase not in PHASE_MARKERS: raise ValueError(f"unsupported phase: {phase}") fields, codes = _instrumentation_fields(output) @@ -204,7 +497,7 @@ def unique_field(name: str) -> str | None: result_phase = unique_field("netkit.phase") result_run_id = unique_field("netkit.runId") instrumentation_code = codes[0] if len(codes) == 1 else None - required = required_markers(phase, run_id) + required = required_markers(phase, run_id, language) if phase == "wifi" and result == "SKIP": required = PHASE_MARKERS[phase] + WIFI_SKIP_MARKERS missing = tuple(marker for marker in required if marker not in output) @@ -221,6 +514,8 @@ def unique_field(name: str) -> str | None: reasons.append(f"expected one instrumentation code RESULT_OK (-1), got {codes!r}") if missing: reasons.append("missing required phase markers: " + "; ".join(missing)) + if phase == "lan-tools" and not re.search(r"LAN:DF_SUPPORTED:(?:true|false)\s*$", output, re.MULTILINE): + reasons.append("expected boolean LAN:DF_SUPPORTED marker") if phase == "wifi": has_pass_branch = all(marker in output for marker in WIFI_PASS_MARKERS) has_skip_branch = all(marker in output for marker in WIFI_SKIP_MARKERS) @@ -251,7 +546,7 @@ def _text(value: str | bytes | None) -> str: class Runner: def __init__(self, *, adb: str, serial: str, phase: str, run_id: str, output_dir: str, git_sha: str = "unknown", expect_apk_sha256: str | None = None, - expect_test_apk_sha256: str | None = None) -> None: + expect_test_apk_sha256: str | None = None, language: str = "cs") -> None: self.adb = validate_adb_path(adb) self.serial = validate_serial(serial) if phase not in PHASE_MARKERS: @@ -266,9 +561,10 @@ def __init__(self, *, adb: str, serial: str, phase: str, run_id: str, output_dir self.aborted = False self.git_sha = git_sha self.expect_apk_sha256 = expect_apk_sha256 - self.timeout = 395 if phase in ("ssh-lifecycle", "wol-e2e", "wol-ime-matrix") else MAX_TIMEOUT_SECONDS + self.timeout = 395 if phase in ("ssh-lifecycle", "wol-e2e", "wol-ime-matrix", "share-results") else 215 if phase == "ssh-sftp" else MAX_TIMEOUT_SECONDS self.command_count = 0 self.phase = phase + self.language = language self.run_id = validate_run_id(run_id) self.output_dir = Path(output_dir).resolve() self.output_dir.mkdir(parents=True, exist_ok=False, mode=0o700) @@ -312,6 +608,14 @@ def collect_build_identity(self) -> dict[str, Any]: "lastUpdateTime": updated.group(1).strip()} return {"git_sha": self.git_sha, "serial": self.serial, "packages": packages} + def collect_landscape_screenshots(self) -> None: + for name in landscape_shots(self.language): + data = self._adb(["exec-out", "run-as", "cz.netkit.app", "cat", + f"files/m1-data/{self.run_id}/m1-evidence/{name}"]) + if not data.startswith(b"\x89PNG\r\n\x1a\n"): + raise ValueError(f"Missing PNG evidence: {name}") + (self.output_dir / name).write_bytes(data) + def _write_summary(self, summary: dict[str, Any]) -> None: self.summary_path.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") self.summary_path.chmod(0o600) @@ -366,7 +670,8 @@ def _observe_app_process(self) -> list[dict[str, Any]]: return observations def run(self) -> PhaseResult: - command = build_command(self.adb, self.serial, self.phase, self.run_id) + command = build_command(self.adb, self.serial, self.phase, self.run_id, self.language) + markers = required_markers(self.phase, self.run_id, self.language) if self.phase in ("wol-e2e", "wol-ime-matrix"): command = [sys.executable, "-I", str(Path(__file__).with_name("run_wol_e2e.py")), "--adb", self.adb, "--serial", self.serial, "--run-id", self.run_id, @@ -378,7 +683,7 @@ def run(self) -> PhaseResult: process: subprocess.Popen[str] | None = None identity: dict[str, Any] = {"git_sha": self.git_sha, "serial": self.serial} result = PhaseResult(False, False, self.phase, self.run_id, None, None, None, - required_markers(self.phase, self.run_id), "run interrupted before completion") + markers, "run interrupted before completion") self._write_summary({**asdict(result), "build": identity}) try: identity = self.collect_build_identity() @@ -389,6 +694,8 @@ def run(self) -> PhaseResult: if (self.expect_test_apk_sha256 is not None and identity["packages"]["cz.netkit.app.test"]["sha256"] != self.expect_test_apk_sha256): raise ValueError("Installed test APK SHA-256 does not match expected build") + for arguments in prepare_commands(self.phase): + self._adb(arguments) self.command_count += 1 self._log_command({"event": "start", "argv": command, "timeout_seconds": self.timeout}) process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, @@ -413,25 +720,38 @@ def run(self) -> PhaseResult: -1 if passed else None, "PASS" if passed else "FAIL", () if passed else ("WOL:E2E:PASS",), "WoL UI, listener and external restart passed" if passed else "WoL nested runner failed; see wol evidence") else: - result = parse_output(output, phase=self.phase, run_id=self.run_id, exit_code=completed.returncode) + result = parse_output(output, phase=self.phase, run_id=self.run_id, + exit_code=completed.returncode, language=self.language) + if result.passed and self.phase in ("accessibility", "ssh-lock", "config-backup"): + for name in PHASE_SCREENSHOTS[self.phase]: + path = f"files/m1-data/{self.run_id}/m1-evidence/{name}" + try: + png = self._adb(["exec-out", "run-as", "cz.netkit.app", "cat", path]) + except subprocess.TimeoutExpired as error: + raise ValueError(f"Timed out collecting screenshot: {name}") from error + if not png.startswith(b"\x89PNG\r\n\x1a\n") or not png.endswith(b"IEND\xaeB`\x82"): + raise ValueError(f"Incomplete screenshot: {name}") + (self.output_dir / name).write_bytes(png) + if self.phase == "landscape-mlo" and result.passed: + self.collect_landscape_screenshots() except subprocess.TimeoutExpired as error: self.aborted = True output = _text(error.stdout) + _text(error.stderr) result = PhaseResult(False, False, self.phase, self.run_id, None, None, None, - required_markers(self.phase, self.run_id), "ADB timed out; instrumentation may still be running") + markers, "ADB timed out; instrumentation may still be running") if process is not None: output = self._stop_client(process, output) identity["process_after_abort"] = self._observe_app_process() except (OSError, ValueError) as error: result = PhaseResult(False, False, self.phase, self.run_id, None, None, None, - required_markers(self.phase, self.run_id), str(error)) + markers, str(error)) except KeyboardInterrupt: self.aborted = True if process is not None: output = self._stop_client(process, output) identity["process_after_abort"] = self._observe_app_process() result = PhaseResult(False, False, self.phase, self.run_id, None, None, None, - required_markers(self.phase, self.run_id), "interrupted") + markers, "interrupted") finally: self.instrumentation_log.write_text(output, encoding="utf-8") self.instrumentation_log.chmod(0o600) @@ -447,6 +767,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser.add_argument("--adb", required=True, help="absolute SDK path ending in platform-tools/adb") parser.add_argument("--serial", required=True, help="explicit emulator serial only") parser.add_argument("--phase", required=True, choices=tuple(PHASE_MARKERS)) + parser.add_argument("--language", choices=("cs", "en"), default="cs", help="app language for lan-tools, system-settings and landscape-mlo (default: cs)") parser.add_argument("--run-id", required=True, help="32 lowercase hex characters") parser.add_argument("--output-dir", required=True, help="new output directory for this run") parser.add_argument("--git-sha", required=True, help="full source commit SHA") diff --git a/tools/test_check_contrast.py b/tools/test_check_contrast.py index 1b75c3e..ae55914 100644 --- a/tools/test_check_contrast.py +++ b/tools/test_check_contrast.py @@ -8,7 +8,7 @@ SAMPLE = """ val DarkNetKitColors = NetKitColors( - background = Color(0xFF000000), surface = Color(0xFF000000), surface2 = Color(0xFF000000), + background = Color(0xFF000000), surface = Color(0xFF000000), surface2 = Color(0xFF000000), surface3 = Color(0xFF000000), text = Color(0xFFFFFFFF), muted = Color(0xFFFFFFFF), dim = Color(0xFFFFFFFF), accent = Color(0xFFFFFFFF), accentInk = Color(0xFF000000), accentSoft = Color(0x1AFFFFFF), info = Color(0xFFFFFFFF), infoSoft = Color(0x1AFFFFFF), @@ -21,7 +21,7 @@ ) val LightNetKitColors = NetKitColors( - background = Color(0xFFFFFFFF), surface = Color(0xFFFFFFFF), surface2 = Color(0xFFFFFFFF), + background = Color(0xFFFFFFFF), surface = Color(0xFFFFFFFF), surface2 = Color(0xFFFFFFFF), surface3 = Color(0xFFFFFFFF), text = Color(0xFF000000), muted = Color(0xFF000000), dim = Color(0xFF000000), accent = Color(0xFF000000), accentInk = Color(0xFFFFFFFF), accentSoft = Color(0x1A000000), info = Color(0xFF000000), infoSoft = Color(0x1A000000), @@ -81,6 +81,17 @@ def test_extreme_palette_passes_everything(self): self.assertTrue(checks) self.assertTrue(all(c.passed for c in checks), [c for c in checks if not c.passed]) + def test_same_grey_passes_for_dim_graphics_but_fails_for_muted_text(self): + palette = SAMPLE.replace("dim = Color(0xFF000000)", "dim = Color(0xFF888888)").replace( + "muted = Color(0xFF000000)", "muted = Color(0xFF888888)") + light = [check for check in cc.run_checks(palette) if check.theme == "light"] + dim = [check for check in light if check.foreground == "dim"] + muted = [check for check in light if check.foreground == "muted"] + self.assertEqual({check.background for check in dim}, {"surface", "background"}) + self.assertTrue(all(3 < check.ratio < 4.5 and check.passed for check in dim)) + self.assertEqual({check.background for check in muted}, {"surface", "surface2", "background"}) + self.assertTrue(all(not check.passed for check in muted)) + def test_low_contrast_token_fails_and_main_exits_non_zero(self): bad = SAMPLE.replace("muted = Color(0xFF000000)", "muted = Color(0xFFBBBBBB)") failed = [c for c in cc.run_checks(bad) if not c.passed] diff --git a/tools/test_m1_fixture_server.py b/tools/test_m1_fixture_server.py index b916e47..a11502d 100644 --- a/tools/test_m1_fixture_server.py +++ b/tools/test_m1_fixture_server.py @@ -157,3 +157,80 @@ def output(): if process is not None and process.poll() is None: process.terminate(); process.wait(timeout=5) shutil.rmtree(directory) + + def test_direct_tcpip_echo_policy_and_proxy_jump_to_second_server(self): + """Zadání 41: -L/-D target (echo), denied destinations and a nested SSH session through a jump.""" + info = fixture.create_fixture(None, False) + directory = Path(info['fixtureDir']) + process = None + clients = [] + try: + config = json.loads(Path(info['configPath']).read_text()) + self.assertEqual(config['server']['tcpEchoPort'], fixture.TCP_ECHO_PORT) + self.assertNotEqual(config['server']['jumpTargetHostKeyFingerprint'], config['server']['hostKeyFingerprint']) + with tempfile.TemporaryFile() as log: + process = subprocess.Popen([sys.executable, '-I', str(Path(fixture.__file__)), + 'serve', '--fixture-dir', str(directory), '--host-key', 'primary', '--duration', '30'], + stdout=log, stderr=log) + def output(): + log.seek(0); return log.read().decode(errors='replace') + deadline = time.monotonic() + 8 + while '"event": "started"' not in output() and time.monotonic() < deadline: + self.assertIsNone(process.poll(), 'fixture exited before listening') + time.sleep(.05) + with socket.create_connection(('127.0.0.1', fixture.TCP_ECHO_PORT), timeout=2) as echo: + echo.sendall(b'ping'); self.assertEqual(echo.recv(16), b'ping') + user, password = config['server']['username'], config['client']['password'] + jump = fixture.paramiko.Transport(socket.create_connection(('127.0.0.1', fixture.SSH_PORT), timeout=2)) + clients.append(jump) + jump.start_client(timeout=5); jump.auth_password(user, password) + tunnel = jump.open_channel('direct-tcpip', ('127.0.0.1', fixture.TCP_ECHO_PORT), ('127.0.0.1', 0), timeout=5) + tunnel.settimeout(3); tunnel.sendall(b'through-ssh') + received = b'' + while len(received) < 11: + received += tunnel.recv(64) + self.assertEqual(received, b'through-ssh') + tunnel.close() + half = jump.open_channel('direct-tcpip', ('127.0.0.1', fixture.TCP_ECHO_PORT), ('127.0.0.1', 0), timeout=5) + half.settimeout(3); half.sendall(b'half-close'); half.shutdown_write() + received = b'' + while True: + chunk = half.recv(64) + if not chunk: + break + received += chunk + self.assertEqual(received, b'half-close', 'reply after client EOF must still arrive, then EOF') + half.close() + for denied in (('127.0.0.1', 22), ('192.0.2.1', fixture.TCP_ECHO_PORT), ('127.0.0.1', fixture.TCP_BANNER_PORT)): + with self.assertRaises(fixture.paramiko.ChannelException): + jump.open_channel('direct-tcpip', denied, ('127.0.0.1', 0), timeout=5) + hop = jump.open_channel('direct-tcpip', ('127.0.0.1', fixture.SSH_JUMP_TARGET_PORT), ('127.0.0.1', 0), timeout=5) + target = fixture.paramiko.Transport(hop) + clients.append(target) + target.start_client(timeout=5) + self.assertEqual(target.get_remote_server_key().get_base64(), config['server']['jumpTargetHostKeyPublicKey']) + target.auth_password(user, password) + shell = target.open_session(timeout=5); shell.get_pty(); shell.invoke_shell(); shell.settimeout(3) + data = b'' + deadline = time.monotonic() + 3 + while b'NETKIT_FIXTURE_READY' not in data and time.monotonic() < deadline: + data += shell.recv(4096) + self.assertIn(b'NETKIT_FIXTURE_READY', data) + shell.sendall(b'netkit-check\r') + deadline = time.monotonic() + 3 + while b'NETKIT_TEST_OK' not in data and time.monotonic() < deadline: + data += shell.recv(4096) + self.assertIn(b'NETKIT_TEST_OK', data) + shell.close(); target.close(); jump.close(); clients.clear() + process.terminate(); process.wait(timeout=5) + text = output() + for marker in (f'SSH_DIRECT_TCPIP:{fixture.TCP_ECHO_PORT}', f'SSH_DIRECT_TCPIP:{fixture.SSH_JUMP_TARGET_PORT}', + 'SSH_DIRECT_TCPIP_DENIED', 'TCP_ECHO_BYTES:', 'SSH_COMMAND_OK'): + self.assertIn(marker, text) + self.assertNotIn(password, text) + finally: + for client in clients: + client.close() + if process is not None and process.poll() is None: + process.terminate(); process.wait(timeout=5) + shutil.rmtree(directory) diff --git a/tools/test_m1_provision.py b/tools/test_m1_provision.py index 94c38f3..1b6ec46 100644 --- a/tools/test_m1_provision.py +++ b/tools/test_m1_provision.py @@ -5,7 +5,7 @@ from pathlib import Path from types import SimpleNamespace from unittest.mock import patch, Mock -from m1_provision import Provisioner, fixture_evidence +from m1_provision import Provisioner, fixture_evidence, notification_permission_commands class ProvisionTests(unittest.TestCase): @@ -14,8 +14,29 @@ def test_cross_check_requires_independent_server_auth_and_banner(self): self.assertTrue(fixture_evidence('ssh', 'AUTH_OK:PASSWORD AUTH_OK:KEY AUTH_OK:INTERACTIVE SSH_RESIZE SSH_SESSION_CLOSED SSH_INPUT_BYTES:1 SSH_COMMAND_OK AUTH_FAILED')[0]) self.assertFalse(fixture_evidence('ssh-legacy', 'AUTH_OK:PASSWORD SSH_SESSION_CLOSED')[0]) self.assertFalse(fixture_evidence('lan', 'TCP_BANNER_SENT SILENT_ACCEPTED')[0]) + forward = 'SSH_DIRECT_TCPIP:18084 SSH_DIRECT_TCPIP:22223 SSH_DIRECT_TCPIP_DENIED TCP_ECHO_BYTES:16 SSH_COMMAND_OK SSH_SESSION_CLOSED' + self.assertTrue(fixture_evidence('ssh-forward', forward)[0]) + self.assertFalse(fixture_evidence('ssh-forward', forward.replace('SSH_DIRECT_TCPIP:22223', ''))[0]) + self.assertTrue(fixture_evidence('ssh-snippet-log', 'AUTH_OK:PASSWORD SSH_COMMAND_OK SSH_SESSION_CLOSED')[0]) + xterm = ('AUTH_OK:PASSWORD SSH_RESIZE SSH_XTERM_SENT:netkit-xterm-colors SSH_XTERM_SENT:netkit-xterm-alt ' + 'SSH_XTERM_SENT:netkit-xterm-main SSH_SESSION_CLOSED') + self.assertTrue(fixture_evidence('ssh-xterm', xterm)[0]) + self.assertFalse(fixture_evidence('ssh-xterm', xterm.replace('SSH_XTERM_SENT:netkit-xterm-main', ''))[0]) self.assertTrue(fixture_evidence('lan', 'TCP_BANNER_SENT SILENT_ACCEPTED SILENT_EOF')[0]) + def test_notification_permission_only_for_background_phase_and_flags_reset(self): + granted = notification_permission_commands('ssh-background') + self.assertEqual(granted[-1], ['shell', 'pm', 'grant', 'cz.netkit.app', 'android.permission.POST_NOTIFICATIONS']) + for phase in ('ssh-background-denied', 'ssh-sftp', 'ssh-ui', 'wifi'): + commands = notification_permission_commands(phase) + self.assertEqual(commands[-1][2], 'revoke', phase) + self.assertEqual(commands[0][2:4], ['clear-permission-flags', 'cz.netkit.app']) + self.assertIn('user-fixed', commands[0]) + sftp = 'AUTH_OK:PASSWORD SFTP_SESSION_STARTED SFTP_LIST SFTP_ESCAPE_DENIED SFTP_DOWNLOAD SFTP_UPLOAD_BYTES:200000 SFTP_HARDLINK SFTP_HARDLINK_EXISTS SFTP_REMOVE SFTP_MKDIR SFTP_RMDIR SFTP_HANG_READ SSH_SESSION_CLOSED' + self.assertTrue(fixture_evidence('ssh-sftp', sftp)[0]) + self.assertFalse(fixture_evidence('ssh-sftp', sftp.replace('SFTP_ESCAPE_DENIED', ''))[0]) + self.assertTrue(fixture_evidence('ssh-background', 'AUTH_OK:PASSWORD SSH_COMMAND_OK SSH_SESSION_CLOSED')[0]) + def test_guard_refuses_shared_avd_before_any_mutation(self): with tempfile.TemporaryDirectory() as directory: tool = Provisioner('/sdk/platform-tools/adb', 'emulator-5554', Path(directory)) diff --git a/tools/test_netkit_ssh_export.py b/tools/test_netkit_ssh_export.py index 851de8d..2974e44 100644 --- a/tools/test_netkit_ssh_export.py +++ b/tools/test_netkit_ssh_export.py @@ -127,6 +127,13 @@ def test_wildcards_are_skipped_once_and_host_star_is_silent(self) -> None: self.assertEqual(list(profiles(document)), ["foo"]) self.assertEqual(skipped(document), [("*.lan", "WILDCARD"), ("!bar", "WILDCARD"), ("r?", "WILDCARD")]) + def test_group_uses_android_utf16_limit_and_rejects_controls(self) -> None: + self.assertTrue(tool.valid_group("Lab 🖧")) + self.assertTrue(tool.valid_group("A" * 60)) + for value in (" ", "A" * 61, "🖧" * 31, "Lab\x85Core"): + with self.subTest(value=value): + self.assertFalse(tool.valid_group(value)) + def test_group_comment_beats_include_stem(self) -> None: with tempfile.TemporaryDirectory() as directory: box = Sandbox(directory) @@ -164,7 +171,38 @@ def test_proxy_jump_and_proxy_command_are_skipped(self) -> None: code, document = box.export(fake) self.assertEqual(code, 0) self.assertEqual(sorted(profiles(document)), ["nojump", "plain"]) - self.assertEqual(skipped(document), [("jump", "PROXY_JUMP"), ("cmd", "PROXY_COMMAND")]) + # ProxyJump to an alias that is not exported stays skipped (after the chain check). + self.assertEqual(skipped(document), [("cmd", "PROXY_COMMAND"), ("jump", "PROXY_JUMP")]) + + def test_proxy_jump_to_exported_alias_becomes_profile_link(self) -> None: + with tempfile.TemporaryDirectory() as directory: + box = Sandbox(directory) + box.write("config", "Host bastion inner deep multi userjump selfjump c1 c2 h1 h2 h3 h4\n") + fake = FakeSsh({ + "bastion": "user u\nhostname 192.0.2.1\nport 22\n", + "inner": "user u\nhostname 10.0.0.5\nport 22\nproxyjump bastion\n", + "deep": "user u\nhostname 10.0.0.6\nport 22\nproxyjump inner\n", + "multi": "user u\nhostname 10.0.0.7\nport 22\nproxyjump bastion,inner\n", + "userjump": "user u\nhostname 10.0.0.8\nport 22\nproxyjump admin@bastion:2222\n", + "selfjump": "user u\nhostname 10.0.0.9\nport 22\nproxyjump selfjump\n", + "c1": "user u\nhostname 10.0.1.1\nport 22\nproxyjump c2\n", + "c2": "user u\nhostname 10.0.1.2\nport 22\nproxyjump c1\n", + "h1": "user u\nhostname 10.0.2.1\nport 22\nproxyjump bastion\n", + "h2": "user u\nhostname 10.0.2.2\nport 22\nproxyjump h1\n", + "h3": "user u\nhostname 10.0.2.3\nport 22\nproxyjump h2\n", + "h4": "user u\nhostname 10.0.2.4\nport 22\nproxyjump h3\n", + }) + code, document = box.export(fake) + self.assertEqual(code, 0) + found = profiles(document) + self.assertNotIn("proxyJump", found["bastion"]) + self.assertEqual(found["inner"]["proxyJump"], "bastion") + self.assertEqual(found["deep"]["proxyJump"], "inner") + self.assertEqual(found["h3"]["proxyJump"], "h2") + self.assertEqual(sorted(found), ["bastion", "deep", "h1", "h2", "h3", "inner"]) + self.assertEqual(sorted(skipped(document)), [("c1", "PROXY_JUMP"), ("c2", "PROXY_JUMP"), ("h4", "PROXY_JUMP"), + ("multi", "PROXY_JUMP"), ("selfjump", "PROXY_JUMP"), ("userjump", "PROXY_JUMP")]) + self.assertIn("cyklus", box.stderr.getvalue()) def test_missing_user_with_and_without_default_user(self) -> None: with tempfile.TemporaryDirectory() as directory: @@ -266,7 +304,8 @@ def test_fallback_first_match_wins_with_host_star_defaults_and_match(self) -> No found = profiles(document) self.assertEqual(found["pve"], {"alias": "pve", "host": "10.0.0.10", "port": 2200, "username": "root"}) self.assertEqual(found["alias-only"]["host"], "alias-only") - self.assertEqual(skipped(document), [("m1", "MATCH"), ("jump", "PROXY_JUMP")]) + self.assertEqual(found["jump"]["proxyJump"], "pve") + self.assertEqual(skipped(document), [("m1", "MATCH")]) self.assertIn("ssh není dostupný", box.stderr.getvalue()) def test_fallback_without_user_needs_default_user(self) -> None: diff --git a/tools/test_run_m1_checks.py b/tools/test_run_m1_checks.py index aea662e..d774735 100644 --- a/tools/test_run_m1_checks.py +++ b/tools/test_run_m1_checks.py @@ -12,7 +12,9 @@ PHASE_MARKERS, Runner, build_command, + parse_args, parse_output, + prepare_commands, required_markers, validate_adb_path, validate_run_id, @@ -26,6 +28,8 @@ def passing_output(phase: str) -> str: markers = "\n".join(required_markers(phase, RUN_ID)) + if phase == "lan-tools": + markers = markers.replace("LAN:DF_SUPPORTED:", "LAN:DF_SUPPORTED:true") return ( markers + "\nINSTRUMENTATION_RESULT: netkit.result=PASS" @@ -73,6 +77,161 @@ def test_command_has_explicit_target_and_only_instrumentation_action(self) -> No class OutputParserTests(unittest.TestCase): + def test_config_backup_requires_each_ui_check_and_screenshot_in_both_languages(self) -> None: + phase = "config-backup" + output = passing_output(phase) + def passed(log: str) -> bool: + return parse_output(log, phase=phase, run_id=RUN_ID, exit_code=0).passed + self.assertTrue(passed(output)) + for lang in ("cs", "en"): + for evidence in [*(f"backup-{scene}-{lang}.png" for scene in + ("export", "warning", "corrupt", "password-error", "preview", "confirm")), + *(f"BACKUP:{step}:{lang}:PASS" for step in + ("ENCRYPTED", "CORRUPT", "AUTH_ERROR", "KEYLESS_NOTE", "SELECT_CONFIRM_CANCEL"))]: + with self.subTest(evidence=evidence): + self.assertFalse(passed(output.replace(evidence, "missing"))) + for evidence in ("backup-rotated-picker-cs.png", "BACKUP:ROTATED_PICKER:cs:PASS"): + with self.subTest(evidence=evidence): + self.assertFalse(passed(output.replace(evidence, "missing"))) + + def test_ssh_lock_requires_both_languages_and_all_guard_markers(self) -> None: + phase = "ssh-lock" + log = passing_output(phase) + def passed(output: str) -> bool: + return parse_output(output, phase=phase, run_id=RUN_ID, exit_code=0).passed + self.assertTrue(passed(log)) + for lang in ("cs", "en"): + for evidence in (f"ssh-locked-{lang}.png", f"ssh-groups-{lang}.png", f"ssh-sort-{lang}.png", + *(f"SSH_LOCK:{check}:{lang}:PASS" for check in ("SHORTCUT", "SYSTEM_CANCEL", "DENIED", "DIRECTORY", "SORT"))): + with self.subTest(evidence=evidence): + self.assertFalse(passed(log.replace(evidence, "missing"))) + + def test_landscape_mlo_requires_every_view_and_language(self) -> None: + for language in ("cs", "en"): + command = build_command(ADB, "emulator-5556", "landscape-mlo", RUN_ID, language) + self.assertIn(["-e", "language", language], [command[i:i + 3] for i in range(len(command))]) + output = passing_output("landscape-mlo").replace("-cs.png", f"-{language}.png").replace( + "LANGUAGE:cs", f"LANGUAGE:{language}") + def passes(log: str) -> bool: + return parse_output(log, phase="landscape-mlo", run_id=RUN_ID, exit_code=0, language=language).passed + self.assertTrue(passes(output)) + markers = required_markers("landscape-mlo", RUN_ID, language) + self.assertEqual(sum(m.startswith("SCREENSHOT:") for m in markers), 13) + for marker in markers: + self.assertFalse(passes(output.replace(marker, "")), marker) + + def test_landscape_collects_only_run_scoped_pngs(self) -> None: + with tempfile.TemporaryDirectory() as temp: + runner = Runner(adb=ADB, serial="emulator-5556", phase="landscape-mlo", run_id=RUN_ID, + output_dir=str(Path(temp) / "artifacts"), language="en") + with patch.object(runner, "_adb", return_value=b"\x89PNG\r\n\x1a\n") as adb: + runner.collect_landscape_screenshots() + for call in adb.call_args_list: + name = Path(call.args[0][-1]).name + self.assertEqual(call.args[0], ["exec-out", "run-as", "cz.netkit.app", "cat", + f"files/m1-data/{RUN_ID}/m1-evidence/{name}"]) + self.assertTrue((runner.output_dir / name).is_file()) + with patch.object(runner, "_adb", return_value=b""): + with self.assertRaisesRegex(ValueError, "Missing PNG"): + runner.collect_landscape_screenshots() + + def test_lan_tool_phases_require_instrumentation_evidence(self) -> None: + evidence = f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/" + for phase, markers in ( + ("lan-tools", ("LAN:LANGUAGE:cs", "LAN:SUBNET:PASS", "LAN:SUBNET:MASK_0:PASS", + "LAN:SUBNET:WILDCARD_32:PASS", evidence + "lan-subnet-wildcard.png", evidence + "lan-subnet.png", + evidence + "lan-ping-advanced.png", "LAN:DF_SUPPORTED:false")), + ("lan-trace-pause", ("LAN:TRACE:RESUME_CANCEL:PASS",)), + ): + with self.subTest(phase=phase): + args = parse_args(["--adb", ADB, "--serial", "emulator-5556", "--phase", phase, + "--run-id", RUN_ID, "--output-dir", "unused", "--git-sha", "a" * 40]) + self.assertEqual(args.phase, phase) + output = passing_output(phase).replace("LAN:DF_SUPPORTED:true", "LAN:DF_SUPPORTED:false") + self.assertTrue(parse_output(output, phase=phase, run_id=RUN_ID, exit_code=0).passed) + for marker in (f"PHASE:{phase}:START", *markers, f"PHASE:{phase}:PASS"): + with self.subTest(marker=marker): + partial = output.replace(marker, "") + self.assertFalse(parse_output(partial, phase=phase, run_id=RUN_ID, exit_code=0).passed) + invalid = passing_output("lan-tools").replace("LAN:DF_SUPPORTED:true", "LAN:DF_SUPPORTED:") + self.assertFalse(parse_output(invalid, phase="lan-tools", run_id=RUN_ID, exit_code=0).passed) + + def test_ssh_background_sftp_phases_require_every_marker_and_screenshot(self) -> None: + evidence = f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/" + for phase, markers in ( + ("ssh-background", ("SSH_BG:SERVICE_FOREGROUND:PASS", "SSH_BG:NOTIFICATION_PRIVATE:PASS", + "SSH_BG:SESSION_SURVIVES_BACKGROUND:PASS", "SSH_BG:DISCONNECT_ALL_STOPS_SERVICE:PASS", + "SSH_BG:PERMISSION_STATE:granted", evidence + "ssh-bg-notification.png")), + ("ssh-background-denied", ("SSH_BG:PERMISSION_ASKED_AT_CONNECT:PASS", "SSH_BG:NO_SERVICE_WITHOUT_NOTIFICATIONS:PASS", + "SSH_BG:FALLBACK_LIMIT_CLOSES:PASS", evidence + "ssh-bg-limited.png")), + ("ssh-sftp", ("SFTP:DOTDOT_NORMALIZED_BY_SERVER:PASS", "SFTP:UPLOAD_EXISTING_TARGET_UNTOUCHED:PASS", + "SFTP:UPLOAD_CANCEL_REMOVES_TEMP:PASS", "SFTP:PUBLISH_NEVER_OVERWRITES:PASS", + "SFTP_UI:SAF_DOWNLOAD:PASS", "SFTP:CANCEL_HANGING_PEER:PASS", "SFTP:IO_TIMEOUT_HANGING_PEER:PASS", + "SFTP:CLOSE_DURING_OPEN_RELEASES:PASS", "SFTP:CHANNELS_RELEASED:PASS", evidence + "sftp-browser.png")), + ("ssh-forwards-panel", ("SSH_FWD_UI:TERMINAL_VISIBLE_WITH_IME:PASS", evidence + "ssh-forwards-ime.png")), + ): + output = passing_output(phase) + self.assertTrue(parse_output(output, phase=phase, run_id=RUN_ID, exit_code=0).passed) + for marker in (f"PHASE:{phase}:START", *markers, f"PHASE:{phase}:PASS"): + with self.subTest(phase=phase, marker=marker): + self.assertFalse(parse_output(output.replace(marker, ""), phase=phase, run_id=RUN_ID, exit_code=0).passed) + # The granted phase must never pass on the denied phase's evidence. + denied = passing_output("ssh-background").replace("SSH_BG:PERMISSION_STATE:granted", "SSH_BG:PERMISSION_STATE:denied") + self.assertFalse(parse_output(denied, phase="ssh-background", run_id=RUN_ID, exit_code=0).passed) + + def test_lan_rozsireni_phases_require_markers_and_screenshots(self) -> None: + evidence = f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/" + for phase, markers in ( + ("lan-list", ("LAN_LIST:FIRST_FRAME_MS:legacy=", "LAN_LIST:SCROLL_END_ROW_254:PASS", "LAN_LIST:ANCHOR_KEPT_ON_INSERT:PASS", + evidence + "lan-list-top.png", evidence + "lan-list-middle.png")), + ("lan-v39", ("LAN_INFO:CARD:PASS", "LAN_IPV6:PING_LOOPBACK_VM:PASS", "LAN_IPV6:TCP_LOOPBACK_OPEN:PASS", + "LAN_IPV6:AAAA_LOCALHOST:", evidence + "lan-network-info.png")), + ("lan-udp", ("LAN_UDP:SNMP:PASS", "LAN_UDP:NTP:PASS", "LAN_UDP:DNS_VERSION:PASS", "LAN_UDP:WRONG_COMMUNITY_SILENT:PASS")), + ("wol-secureon", ("WOL_SECUREON:STORED_NOT_EXPORTED:PASS", "WOL_SECUREON:SENT_TO_HOST_LISTENER:PASS")), + ): + with self.subTest(phase=phase): + command = build_command(ADB, "emulator-5556", phase, RUN_ID) + self.assertEqual(command[1:3], ["-s", "emulator-5556"]) + output = passing_output(phase) + self.assertTrue(parse_output(output, phase=phase, run_id=RUN_ID, exit_code=0).passed) + for marker in (f"PHASE:{phase}:START", *markers, f"PHASE:{phase}:PASS"): + with self.subTest(marker=marker): + self.assertFalse(parse_output(output.replace(marker, ""), phase=phase, run_id=RUN_ID, exit_code=0).passed) + + def test_ssh_productivity_phases_require_every_marker_and_screenshot(self) -> None: + evidence = f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/" + for phase, markers in ( + ("ssh-forward", ("SSH_FWD:LISTEN_LOOPBACK_ONLY:PASS", "SSH_FWD:LOCAL_ECHO:PASS", "SSH_FWD:SOCKS_CONNECT_ECHO:PASS", + "SSH_FWD:SOCKS_BIND_REJECTED:PASS", "SSH_JUMP:PER_HOP_TOFU:PASS", "SSH_JUMP:TARGET_SHELL:PASS", + "SSH_JUMP:CYCLE_REJECTED:PASS")), + ("ssh-snippet-log", ("SSH_SNIPPET:SENT_FROM_BAR:PASS", "SSH_LOG:SAF_FILE_PLAIN_TEXT:PASS", + evidence + "ssh-snippet-bar.png", evidence + "ssh-log-warning.png")), + ("ssh-xterm", ("SSH_XTERM:COLORS_256:PASS", "SSH_XTERM:ALT_SCREEN:PASS", "SSH_XTERM:TITLE_SHOWN:PASS", + "SSH_XTERM:ALT_RESTORED:PASS", evidence + "ssh-xterm-colors.png", evidence + "ssh-xterm-alt.png", + evidence + "ssh-xterm-main.png")), + ): + output = passing_output(phase) + self.assertTrue(parse_output(output, phase=phase, run_id=RUN_ID, exit_code=0).passed) + for marker in (f"PHASE:{phase}:START", *markers, f"PHASE:{phase}:PASS"): + with self.subTest(phase=phase, marker=marker): + self.assertFalse(parse_output(output.replace(marker, ""), phase=phase, run_id=RUN_ID, exit_code=0).passed) + + def test_accessibility_requires_semantics_and_screenshots_in_both_languages(self) -> None: + output = passing_output("accessibility") + command = build_command(ADB, "emulator-5556", "accessibility", RUN_ID) + self.assertEqual(command[1:3], ["-s", "emulator-5556"]) + self.assertTrue(parse_output(output, phase="accessibility", run_id=RUN_ID, exit_code=0).passed) + for language in ("cs", "en"): + markers = [f"ACCESSIBILITY:{language}:{name}:PASS" for name in + ("HEADING_STATUS_TARGET", "OFFSCREEN", "LAN_RESULTS", "speed", "iperf", "CHARTS", "SPECTRUM")] + markers += [f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/accessibility-{language}-{scene}.png" + for scene in ("ping", "lan", "speed", "iperf", "charts", "spectrum")] + for marker in markers: + with self.subTest(marker=marker): + partial = parse_output(output.replace(marker, ""), phase="accessibility", run_id=RUN_ID, exit_code=0) + self.assertIn(marker, partial.missing_markers) + self.assertFalse(partial.passed) + def test_requires_result_phase_run_id_code_and_every_phase_marker(self) -> None: for phase in PHASE_MARKERS: with self.subTest(phase=phase): @@ -138,6 +297,86 @@ def setUp(self) -> None: patcher.start() self.addCleanup(patcher.stop) + def test_lan_tools_forwards_language_and_requires_matching_evidence(self) -> None: + for language in ("cs", "en"): + with self.subTest(language=language), tempfile.TemporaryDirectory() as temporary: + options = ["--language", "en"] if language == "en" else [] + args = parse_args(["--adb", ADB, "--serial", "emulator-5556", "--phase", "lan-tools", + "--run-id", RUN_ID, "--output-dir", str(Path(temporary) / "run"), + "--git-sha", "a" * 40, *options]) + output = passing_output("lan-tools").replace("LAN:LANGUAGE:cs", f"LAN:LANGUAGE:{language}") + client = Mock(returncode=0) + client.communicate.return_value = (output, "") + with patch("run_m1_checks.subprocess.Popen", return_value=client) as launch: + result = Runner(**vars(args)).run() + self.assertTrue(result.passed, result.reason) + self.assertEqual(launch.call_args.args[0][-4:-1], ["-e", "language", language]) + other = "cs" if language == "en" else "en" + mismatch = parse_output(output, phase="lan-tools", run_id=RUN_ID, exit_code=0, language=other) + self.assertFalse(mismatch.passed) + self.assertEqual(mismatch.missing_markers, (f"LAN:LANGUAGE:{other}",)) + + def test_system_settings_forwards_language_and_requires_language_evidence(self) -> None: + evidence = f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/" + for language, other in (("cs", "en"), ("en", "cs")): + with self.subTest(language=language), tempfile.TemporaryDirectory() as temporary: + command = build_command(ADB, "emulator-5556", "system-settings", RUN_ID, language) + self.assertEqual(command[1:3], ["-s", "emulator-5556"]) + self.assertEqual(command[-4:-1], ["-e", "language", language]) + markers = required_markers("system-settings", RUN_ID, language) + for marker in (f"SYSTEM:LANGUAGE:{language}", evidence + f"settings-language-{other}.png", + evidence + "settings-dark.png", "SYSTEM:BACK:OVERVIEW_LEAVES_APP:PASS", + "SYSTEM:KEEP_SCREEN:OVERLAP:ON", "SYSTEM:KEEP_SCREEN:WINDOW_FLAG:VERIFIED", + "SYSTEM:CANCELLED_CALLER:LAN_CONSENT:STATE_AND_PREFS_VERIFIED", + "SYSTEM:DELETE:TARGET_HISTORY:FAVORITES_PRESERVED", "SYSTEM:LANGUAGE:SSH_CHANNEL:VERIFIED", + "SYSTEM:IPERF_TARGET:STORED_NOT_FORM:UI_VERIFIED", + "SYSTEM:CANCELLED_CALLER:IPERF_TARGET:STATE_AND_STORE_VERIFIED"): + self.assertIn(marker, markers) + output = ( + "\n".join(markers) + + "\nINSTRUMENTATION_RESULT: netkit.result=PASS" + + "\nINSTRUMENTATION_RESULT: netkit.phase=system-settings" + + f"\nINSTRUMENTATION_RESULT: netkit.runId={RUN_ID}" + + "\nINSTRUMENTATION_CODE: -1\n" + ) + args = parse_args(["--adb", ADB, "--serial", "emulator-5556", "--phase", "system-settings", + "--language", language, "--run-id", RUN_ID, + "--output-dir", str(Path(temporary) / "run"), "--git-sha", "a" * 40]) + client = Mock(returncode=0) + client.communicate.return_value = (output, "") + with patch("run_m1_checks.subprocess.Popen", return_value=client) as launch: + result = Runner(**vars(args)).run() + self.assertTrue(result.passed, result.reason) + self.assertEqual(launch.call_args.args[0][-4:-1], ["-e", "language", language]) + mismatch = parse_output(output, phase="system-settings", run_id=RUN_ID, exit_code=0, language=other) + self.assertFalse(mismatch.passed) + for marker in ("SYSTEM:KEEP_SCREEN:RELEASED:OFF", "SYSTEM:LANGUAGE:UI_SWITCH:PASS", "PHASE:system-settings:PASS"): + partial = output.replace(marker, "") + self.assertFalse(parse_output(partial, phase="system-settings", run_id=RUN_ID, exit_code=0, + language=language).passed) + with self.assertRaises(ValueError): + build_command(ADB, "emulator-5556", "system-settings", RUN_ID, "de") + def test_accessibility_collects_png_files_and_rejects_truncation(self) -> None: + png = b"\x89PNG\r\n\x1a\n" + bytes.fromhex("0000000049454e44ae426082") + for payload, complete in ((png, True), (png[:-4], False)): + with self.subTest(complete=complete), tempfile.TemporaryDirectory() as temporary: + dest = Path(temporary) / "run" + runner = Runner(adb=ADB, serial="emulator-5556", phase="accessibility", run_id=RUN_ID, output_dir=str(dest)) + client = Mock(returncode=0) + client.communicate.return_value = (passing_output("accessibility"), "") + with patch("run_m1_checks.subprocess.Popen", return_value=client), patch.object(runner, "_adb", return_value=payload) as fetch: + result = runner.run() + self.assertEqual(result.passed, complete, result.reason) + if complete: + files = list(dest.glob("*.png")) + self.assertEqual(len(files), 12) + for path in files: + fetch.assert_any_call(["exec-out", "run-as", "cz.netkit.app", "cat", + f"files/m1-data/{RUN_ID}/m1-evidence/{path.name}"]) + self.assertEqual(path.read_bytes(), payload) + else: + self.assertIn("Incomplete screenshot", result.reason) + def test_runner_issues_one_scoped_command_and_writes_evidence(self) -> None: with tempfile.TemporaryDirectory() as temporary: output_dir = Path(temporary) / "run" @@ -272,6 +511,154 @@ def test_output_directory_must_be_new(self) -> None: output_dir=temporary) +class WifiExtensionsPhaseTests(unittest.TestCase): + """Zadání 38: the wifi-extensions phase needs every UI marker and both SAF file read-backs.""" + + def test_wifi_extensions_requires_saf_and_ui_markers(self) -> None: + args = parse_args(["--adb", ADB, "--serial", "emulator-5556", "--phase", "wifi-extensions", + "--run-id", RUN_ID, "--output-dir", "unused", "--git-sha", "a" * 40]) + self.assertEqual(args.phase, "wifi-extensions") + command = build_command(ADB, "emulator-5556", "wifi-extensions", RUN_ID) + self.assertEqual(command[1:3], ["-s", "emulator-5556"]) + self.assertNotIn("language", command) + output = passing_output("wifi-extensions") + self.assertTrue(parse_output(output, phase="wifi-extensions", run_id=RUN_ID, exit_code=0).passed) + for marker in ("WIFI:EXPORT:CSV:SAF_FILE_VERIFIED", "WIFI:EXPORT:JSON:SAF_FILE_VERIFIED", "WIFI:PIN:ORDER:UI_VERIFIED", + "WIFI:ESS_GROUPS:UI_VERIFIED", "WIFI:WALK:SUMMARY:UI_VERIFIED", "WIFI:PIN:MISSING_UNPIN:UI_VERIFIED", + "PHASE:wifi-extensions:PASS"): + with self.subTest(marker=marker): + self.assertIn(marker, PHASE_MARKERS["wifi-extensions"]) + partial = output.replace(marker + "\n", "\n") + result = parse_output(partial, phase="wifi-extensions", run_id=RUN_ID, exit_code=0) + self.assertFalse(result.passed) + self.assertIn(marker, result.missing_markers) + + +class ToolsTargetsPhaseTests(unittest.TestCase): + """Zadání 48: tools-targets needs every CS/EN marker and all eight screenshots.""" + + def test_markers_and_screenshots_are_required(self) -> None: + command = build_command(ADB, "emulator-5556", "tools-targets", RUN_ID) + self.assertEqual(command[1:3], ["-s", "emulator-5556"]) + self.assertNotIn("language", command) + output = passing_output("tools-targets") + self.assertTrue(parse_output(output, phase="tools-targets", run_id=RUN_ID, exit_code=0).passed) + required = required_markers("tools-targets", RUN_ID) + for language in ("cs", "en"): + for name in ("tools-targets-menu", "tools-targets-star", "tools-tcp-ping", "tools-mac"): + self.assertIn(f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/{name}-{language}.png", required) + for marker in ("TARGETS:MENU_FILTERED:en:UI_VERIFIED", "TARGETS:CLEAR_KEEPS_FAVORITES:cs:PASS", + "TCP_PING:LOOPBACK:cs:sent=4;received=4;rtt=", "TCP_PING:REFUSED_IS_LOSS:PASS", + "TCP_PING:ONE_CONNECTION_AT_A_TIME:PASS:max=", "MAC_VENDOR:TABLE:PASS", "MAC_VENDOR:en:UI_VERIFIED", "MAC_VENDOR:EXPORT_ERROR_VISIBLE:cs:PASS", + f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/tools-mac-en.png", "PHASE:tools-targets:PASS"): + with self.subTest(marker=marker): + partial = "\n".join(line for line in output.splitlines() if not line.startswith(marker)) + result = parse_output(partial, phase="tools-targets", run_id=RUN_ID, exit_code=0) + self.assertFalse(result.passed) + self.assertIn(marker, result.missing_markers) + + def test_three_lost_samples_do_not_pass_as_four_replies(self) -> None: + output = passing_output("tools-targets").replace("TCP_PING:LOOPBACK:en:sent=4;received=4;rtt=", + "TCP_PING:LOOPBACK:en:sent=4;received=1;rtt=") + result = parse_output(output, phase="tools-targets", run_id=RUN_ID, exit_code=0) + self.assertFalse(result.passed) + + +class NetStatusWidgetPhaseTests(unittest.TestCase): + """Zadání 37: the netstatus-widget phase needs both positive controls, every refresh check and all drawings.""" + + def test_netstatus_widget_requires_controls_refresh_and_renders(self) -> None: + args = parse_args(["--adb", ADB, "--serial", "emulator-5556", "--phase", "netstatus-widget", + "--run-id", RUN_ID, "--output-dir", "unused", "--git-sha", "a" * 40]) + self.assertEqual(args.phase, "netstatus-widget") + command = build_command(ADB, "emulator-5556", "netstatus-widget", RUN_ID) + self.assertEqual(command[1:3], ["-s", "emulator-5556"]) + output = passing_output("netstatus-widget") + self.assertTrue(parse_output(output, phase="netstatus-widget", run_id=RUN_ID, exit_code=0).passed) + for marker in ("NETSTATUS:LOCATION_CONTROL_NOTED:PASS", "NETSTATUS:REFRESH_NO_LOCATION_OP:PASS", + "NETSTATUS:TRAFFIC_CONTROL_COUNTED:PASS", "NETSTATUS:REFRESH_NO_TRAFFIC:PASS", + "NETSTATUS:REFRESH_UNDER_10S:PASS", "NETSTATUS:REFRESH_RADIO_UPDATED_SSID_KEPT:PASS", + "NETSTATUS:RENDER:lockscreen-medium:PASS", "NETSTATUS:RENDER:stale-small:PASS", + f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/netstatus-fresh-medium-ssid.png", + "PHASE:netstatus-widget:PASS"): + with self.subTest(marker=marker): + partial = output.replace(marker + "\n", "\n") + result = parse_output(partial, phase="netstatus-widget", run_id=RUN_ID, exit_code=0) + self.assertFalse(result.passed) + self.assertIn(marker, result.missing_markers) + + +class CellDetailPhaseTests(unittest.TestCase): + """Zadání 53: cell-detail revokes the permissions first and needs every marker and screenshot.""" + + def setUp(self) -> None: + identity = {"serial": "emulator-5556", "git_sha": "a" * 40, + "packages": {"cz.netkit.app": {"sha256": "b" * 64}}} + patcher = patch.object(Runner, "collect_build_identity", return_value=identity) + patcher.start() + self.addCleanup(patcher.stop) + + def test_markers_and_screenshots_are_required(self) -> None: + output = passing_output("cell-detail").replace("CELL:DETAIL:LTE:band=", "CELL:DETAIL:LTE:band=3:earfcn=1300:pci=1:neighbors=0") + self.assertTrue(parse_output(output, phase="cell-detail", run_id=RUN_ID, exit_code=0).passed) + required = required_markers("cell-detail", RUN_ID) + for name in ("cell-detail-permission-cs", "cell-detail-cs", "cell-detail-en"): + self.assertIn(f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/{name}.png", required) + for marker in ("CELL:DETAIL:NO_REQUEST_WITHOUT_PERMISSION:PASS", "CELL:DETAIL:PERMISSION:UI_VERIFIED", + "CELL:DETAIL:LTE:band=", "CELL:DETAIL:LTE:cs:UI_VERIFIED", "CELL:DETAIL:LTE:en:UI_VERIFIED", + "CELL:DETAIL:FORGET_ON_COLLAPSE:PASS", f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/cell-detail-en.png"): + with self.subTest(marker=marker): + partial = "\n".join(line for line in output.splitlines() if not line.startswith(marker)) + result = parse_output(partial, phase="cell-detail", run_id=RUN_ID, exit_code=0) + self.assertFalse(result.passed) + self.assertIn(marker, result.missing_markers) + + def test_only_cell_detail_prepares_revokes(self) -> None: + self.assertEqual(prepare_commands("cell-detail"), [ + ["shell", "pm", "revoke", "cz.netkit.app", "android.permission.READ_PHONE_STATE"], + ["shell", "pm", "revoke", "cz.netkit.app", "android.permission.ACCESS_FINE_LOCATION"], + ["shell", "pm", "revoke", "cz.netkit.app", "android.permission.ACCESS_COARSE_LOCATION"], + ]) + for phase in PHASE_MARKERS: + if phase != "cell-detail": + with self.subTest(phase=phase): + self.assertEqual(prepare_commands(phase), []) + + def test_runner_revokes_on_the_explicit_emulator_before_instrumentation(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + runner = Runner(adb=ADB, serial="emulator-5556", phase="cell-detail", run_id=RUN_ID, + output_dir=str(Path(temporary) / "run")) + output = passing_output("cell-detail").replace("CELL:DETAIL:LTE:band=", "CELL:DETAIL:LTE:band=3") + client = Mock(returncode=0) + client.communicate.return_value = (output, "") + order: list[str] = [] + revoke = subprocess.CompletedProcess([], 0, b"", b"") + def run(command, **_kwargs): + order.append("revoke:" + command[-1]) + return revoke + def popen(command, **_kwargs): + order.append("instrument") + return client + with patch("run_m1_checks.subprocess.run", side_effect=run) as execute, \ + patch("run_m1_checks.subprocess.Popen", side_effect=popen): + result = runner.run() + self.assertTrue(result.passed, result.reason) + self.assertEqual(order, ["revoke:android.permission.READ_PHONE_STATE", "revoke:android.permission.ACCESS_FINE_LOCATION", + "revoke:android.permission.ACCESS_COARSE_LOCATION", "instrument"]) + for call in execute.call_args_list: + self.assertEqual(call.args[0][:3], [ADB, "-s", "emulator-5556"]) + + def test_failed_revoke_stops_before_instrumentation(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + runner = Runner(adb=ADB, serial="emulator-5556", phase="cell-detail", run_id=RUN_ID, + output_dir=str(Path(temporary) / "run")) + with patch("run_m1_checks.subprocess.run", return_value=subprocess.CompletedProcess([], 1, b"", b"")), \ + patch("run_m1_checks.subprocess.Popen") as launch: + result = runner.run() + self.assertFalse(result.passed) + launch.assert_not_called() + + class ProvisionRepeatTests(unittest.TestCase): def test_each_lifecycle_repeat_owns_a_new_bounded_fixture_and_log(self) -> None: with tempfile.TemporaryDirectory() as temporary: @@ -313,5 +700,26 @@ def make_runner(**kwargs): self.assertEqual(len({summary["fixture_cross_check"]["log"] for summary in summaries}), 3) +class ShareResultsPhaseTests(unittest.TestCase): + """Zadání 47: share-results needs every marker and all eight CS/EN screenshots.""" + + def test_markers_and_screenshots_are_required(self) -> None: + output = passing_output("share-results") + self.assertTrue(parse_output(output, phase="share-results", run_id=RUN_ID, exit_code=0).passed) + required = required_markers("share-results", RUN_ID) + for language in ("cs", "en"): + for kind in ("copy", "report", "devices", "speed"): + self.assertIn(f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/share-{kind}-{language}.png", required) + for marker in ("SHARE:COPY:BSSID_SENSITIVE:PASS", "SHARE:REPORT:DEFAULTS_OFF:PASS", "SHARE:REPORT:SAF_JSON:PASS", + "SHARE:DEVICES:CSV:SAF_FILE_VERIFIED:rows=", "SHARE:SPEED:en:UI_VERIFIED", + f"SCREENSHOT:files/m1-data/{RUN_ID}/m1-evidence/share-report-en.png"): + with self.subTest(marker=marker): + partial = "\n".join(line for line in output.splitlines() if not line.startswith(marker)) + result = parse_output(partial, phase="share-results", run_id=RUN_ID, exit_code=0) + self.assertFalse(result.passed) + self.assertIn(marker, result.missing_markers) + self.assertEqual(prepare_commands("share-results"), []) + + if __name__ == "__main__": unittest.main() diff --git a/tools/test_update_terminal_width.py b/tools/test_update_terminal_width.py new file mode 100644 index 0000000..8157dd2 --- /dev/null +++ b/tools/test_update_terminal_width.py @@ -0,0 +1,55 @@ +import tempfile +import unittest +from pathlib import Path + +import update_terminal_width as width + +EAST = """# EastAsianWidth-test.txt +0000..001F;N # Cc +1100..115F;W # Lo HANGUL CHOSEONG +3000;F # Zs IDEOGRAPHIC SPACE +3001..3003;W +4E00..9FFF;W +""" +CATEGORY = """# DerivedGeneralCategory-test.txt +00AD ; Cf # SOFT HYPHEN +0300..036F ; Mn +200B..200F ; Cf +20DD..20E0 ; Me +0041..005A ; Lu +""" + + +class TerminalWidthGeneratorTests(unittest.TestCase): + def test_parse_merges_adjacent_wide_ranges(self) -> None: + self.assertEqual(width.parse(EAST, width.WIDE_VALUES), [(0x1100, 0x115F), (0x3000, 0x3003), (0x4E00, 0x9FFF)]) + + def test_zero_width_keeps_soft_hyphen_and_adds_hangul_jamo(self) -> None: + generated = width.tables(EAST, CATEGORY) + self.assertIn("0x300, 0x36F", generated) + self.assertIn("0x1160, 0x11FF", generated) + self.assertNotIn("0xAD", generated) + self.assertEqual(width.without([(1, 5)], 3), [(1, 2), (4, 5)]) + + def test_replace_requires_one_table_block(self) -> None: + source = ("object TerminalWidth {\n private val WIDE = intArrayOf(\n 0x1, 0x2,\n )\n\n" + " private val ZERO = intArrayOf(\n 0x3, 0x4,\n )\n}\n") + result = width.replace_tables(source, width.tables(EAST, CATEGORY)) + self.assertIn("0x4E00, 0x9FFF", result) + self.assertTrue(result.endswith(" )\n}\n")) + with self.assertRaises(ValueError): + width.replace_tables("object TerminalWidth {}\n", "") + + def test_main_rewrites_target_file(self) -> None: + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "east.txt").write_text(EAST, encoding="utf-8") + (root / "category.txt").write_text(CATEGORY, encoding="utf-8") + target = root / "TerminalWidth.kt" + target.write_text(width.TARGET.read_text(encoding="utf-8"), encoding="utf-8") + self.assertEqual(width.main([str(root / "east.txt"), str(root / "category.txt"), str(target)]), 0) + self.assertIn("0x3000, 0x3003", target.read_text(encoding="utf-8")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/testsrv/iperf3_fixture.py b/tools/testsrv/iperf3_fixture.py new file mode 100644 index 0000000..3fb3de0 --- /dev/null +++ b/tools/testsrv/iperf3_fixture.py @@ -0,0 +1,155 @@ +"""One loopback-only TCP measurement. The first stdout line is the selected port.""" +import argparse +from contextlib import ExitStack +import json +import io +import selectors +import socket +import struct +import time +from typing import Any + +MAX_JSON = 65536 +BLOCK = 128 * 1024 +COOKIE_SIZE = 37 +CLIENT_TERMINATE = 12 +DONE = 16 + + +def exact(reader: io.IOBase, size: int) -> bytes: + data = bytearray() + while len(data) < size: + chunk = reader.read(size - len(data)) + if not chunk: + raise EOFError("short control message") + data.extend(chunk) + return bytes(data) + + +def read_json(reader: io.IOBase) -> dict[str, Any]: + length, = struct.unpack("!I", exact(reader, 4)) + if not 1 <= length <= MAX_JSON: + raise ValueError("JSON length") + value = json.loads(exact(reader, length).decode("utf-8")) + if not isinstance(value, dict): + raise ValueError("expected object") + return value + + +def frame(value: dict[str, Any]) -> bytes: + body = json.dumps(value, separators=(",", ":"), allow_nan=False).encode() + if not 1 <= len(body) <= MAX_JSON: + raise ValueError("JSON length") + return struct.pack("!I", len(body)) + body + + +def stream_id(index: int) -> int: + return 1 if index == 0 else index + 2 + + +def transfer(control: socket.socket, streams: list[socket.socket], reverse: bool, + seconds: int, rate: int) -> tuple[list[int], bool]: + counts = [0] * len(streams) + payload = memoryview(bytes(BLOCK)) + start = time.monotonic() + with selectors.DefaultSelector() as selector: + selector.register(control, selectors.EVENT_READ, None) + for index, stream in enumerate(streams): + stream.setblocking(False) + selector.register(stream, selectors.EVENT_WRITE if reverse else selectors.EVENT_READ, index) + while time.monotonic() - start < seconds + 10: + for key, _ in selector.select(0.1): + if key.data is None: + state = control.recv(1) + if state == bytes([CLIENT_TERMINATE]): + return counts, True + if state != b'\x04': + raise ValueError("expected TEST_END") + return counts, False + i = int(key.data) + try: + if reverse: + limit = BLOCK + if rate: + credit = int((time.monotonic() - start + 0.002) * rate / 8) - counts[i] + if credit <= 0: + continue + limit = min(BLOCK, credit) + counts[i] += streams[i].send(payload[:limit]) + else: + size = len(streams[i].recv(BLOCK)) + if not size: + selector.unregister(streams[i]) + counts[i] += size + except BlockingIOError: + pass + if reverse and rate: + time.sleep(0.001) + raise TimeoutError("client did not end test") + + +def serve(listener: socket.socket) -> None: + with ExitStack() as stack: + control = stack.enter_context(listener.accept()[0]) + control.settimeout(10) + reader = stack.enter_context(control.makefile("rb", buffering=0)) + cookie = exact(reader, COOKIE_SIZE) + if cookie[-1] != 0: + raise ValueError("cookie") + control.sendall(bytes([9])) + params = read_json(reader) + count = params["parallel"] + seconds = params["time"] + rate = params.get("bandwidth", 0) + if (params.get("tcp") is not True or type(count) is not int or not 1 <= count <= 8 + or type(seconds) is not int or not 3 <= seconds <= 30 + or type(rate) is not int or not 0 <= rate <= 10**12): + raise ValueError("test parameters") + reverse = params.get("reverse") is True + streams = [] + control.sendall(bytes([10])) + for _ in range(count): + stream = stack.enter_context(listener.accept()[0]) + stream.settimeout(10) + with stream.makefile("rb", buffering=0) as handshake: + if exact(handshake, COOKIE_SIZE) != cookie: + raise ValueError("stream cookie") + streams.append(stream) + start = time.monotonic() + control.sendall(bytes([1, 2])) + counts, cancelled = transfer(control, streams, reverse, seconds, rate) + end_time = time.monotonic() - start + if cancelled: + return + control.sendall(bytes([13])) + client = read_json(reader) + rows = client["streams"] + if ([row["id"] for row in rows] != [stream_id(i) for i in range(count)] + or any(row["bytes"] <= 0 for row in rows) or min(counts) <= 0): + raise ValueError("expected payload in every stream") + if client["sender_has_retransmits"] != (-1 if reverse else 0): + raise ValueError("wrong sender") + results = {"sender_has_retransmits": 1 if reverse else -1, "streams": [ + {"id": stream_id(i), "bytes": size, "end_time": end_time, "retransmits": i + 1 if reverse else -1} + for i, size in enumerate(counts)]} + control.sendall(frame(results) + bytes([14])) + if exact(reader, 1) != bytes([DONE]): + raise ValueError("expected IPERF_DONE") + print(sum(counts), end_time, flush=True) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--port", type=int, default=5201, help="0 selects an ephemeral port") + args = parser.parse_args() + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener: + listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + listener.bind(("127.0.0.1", args.port)) + listener.listen(9) + listener.settimeout(30) + print(listener.getsockname()[1], flush=True) + serve(listener) + + +if __name__ == "__main__": + main() diff --git a/tools/testsrv/m1_fixture.py b/tools/testsrv/m1_fixture.py index 2578d6c..98cffd4 100755 --- a/tools/testsrv/m1_fixture.py +++ b/tools/testsrv/m1_fixture.py @@ -4,16 +4,22 @@ from __future__ import annotations import argparse +import errno +import hashlib import hmac import io import json import os +import posixpath import queue import secrets +import select +import shutil import signal import socket import socketserver import stat +import struct import sys import tempfile import threading @@ -24,6 +30,13 @@ import paramiko # pyright: ignore[reportMissingModuleSource] from paramiko.common import AUTH_FAILED, AUTH_SUCCESSFUL, OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED, OPEN_SUCCEEDED # pyright: ignore[reportMissingModuleSource] from paramiko.server import InteractiveQuery # pyright: ignore[reportMissingModuleSource] +from paramiko.message import Message # pyright: ignore[reportMissingModuleSource] +from paramiko.sftp import (CMD_EXTENDED, CMD_INIT, CMD_NAME, CMD_REALPATH, CMD_VERSION, SFTP_FAILURE, # pyright: ignore[reportMissingModuleSource] + SFTP_OK, SFTP_OP_UNSUPPORTED, SFTPError) +from paramiko.sftp_attr import SFTPAttributes # pyright: ignore[reportMissingModuleSource] +from paramiko.sftp_handle import SFTPHandle # pyright: ignore[reportMissingModuleSource] +from paramiko.sftp_server import SFTPServer # pyright: ignore[reportMissingModuleSource] +from paramiko.sftp_si import SFTPServerInterface # pyright: ignore[reportMissingModuleSource] from cryptography.hazmat.primitives import serialization # pyright: ignore[reportMissingImports] from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # pyright: ignore[reportMissingImports] @@ -33,6 +46,15 @@ TCP_CLOSED_PORT = 18082 TCP_SILENT_PORT = 18083 SSH_PORT = 22222 +# Zadání 41: loopback TCP echo (target of -L/-D) and a second SSH server reachable through ProxyJump. +TCP_ECHO_PORT = 18084 +SSH_JUMP_TARGET_PORT = 22223 +FORWARD_ALLOWED_PORTS = frozenset({TCP_ECHO_PORT, SSH_JUMP_TARGET_PORT}) +FORWARD_ALLOWED_HOSTS = frozenset({"127.0.0.1", "localhost"}) +FORWARD_MAX_SECONDS = 300.0 +FORWARD_MAX_BYTES = 8 * 1024 * 1024 +MAX_FORWARDS_PER_TRANSPORT = 16 +ECHO_MAX_BYTES = 64 * 1024 MAX_DURATION_SECONDS = 600 MAX_ACTIVE_SESSIONS = 8 SSH_CHANNEL_ACCEPT_SECONDS = 120.0 @@ -43,6 +65,44 @@ INTERRUPT_LINE = b"\r\n^C\r\nNETKIT_INTERRUPT_OK\r\nfixture> " DISABLED_LINE = b"\r\nCommand disabled in NetKit fixture.\r\nfixture> " RESIZE_PREFIX = b"\r\nNETKIT_RESIZE_OK " +# Zadání 42: SFTP sandbox (see seed_sftp_root); limits keep a test from filling the host disk. +SFTP_ROOT_NAME = "sftp-root" +SFTP_HOME = "/home/netkit-test" +SFTP_HELLO = b"NETKIT_SFTP_HELLO\n" +SFTP_DATA_SIZE = 300_000 +SFTP_MAX_FILE_BYTES = 8 * 1024 * 1024 +SFTP_MAX_LIST = 1000 +SFTP_MAX_CHANNELS_PER_TRANSPORT = 4 # open at the same time; closed ones are not counted +# Review round 1: reading `hang.bin` blocks like a stuck peer (bounded so the fixture never leaks a thread). +SFTP_HANG_NAME = "hang.bin" +SFTP_HANG_SECONDS = 45.0 +SFTP_SUBSYSTEM_WAIT_SECONDS = 5.0 + + +def _xterm_colors() -> bytes: + """Zadani 43: canned output equivalent to printf of 256 SGR 48;5 swatches; byte-identical to + xtermColorDemo() in shared/src/commonTest/.../TerminalXtermTest.kt. Nothing is executed.""" + parts = ["\r\n256 colors\r\n"] + for line in range(16): + parts.extend(f"\x1b[48;5;{line * 16 + column}m " for column in range(16)) + parts.append("\x1b[0m\r\n") + parts.append("\x1b[38;2;255;100;0mTRUE\x1b[0m \x1b[1mBOLD\x1b[0m \x1b[2mDIM\x1b[0m \x1b[3mITAL\x1b[0m ") + parts.append("\x1b[4mUNDER\x1b[0m \x1b[7mINV\x1b[0m \u4e2d\u6587\r\n") + parts.append("NETKIT_XTERM_COLORS_OK\r\nfixture> ") + return "".join(parts).encode("utf-8") + + +XTERM_COLORS = _xterm_colors() +# Full-screen style output: alternate screen, OSC 2 title, DEC line drawing, scroll region and wide characters. +XTERM_ALT = ("\x1b[?1049h\x1b[H\x1b[2J\x1b]2;NetKit alt\x07" + "\x1b(0lqqqqqqqqqqqqqqqqk\x1b(B\r\n" + "\x1b(0x\x1b(B \x1b[1;33mALT SCREEN\x1b[0m \x1b(0x\x1b(B\r\n" + "\x1b(0x\x1b(B \u5bbd\u5b57\u7b26 \U0001F600 \x1b(0x\x1b(B\r\n" + "\x1b(0mqqqqqqqqqqqqqqqqj\x1b(B\r\n" + "\x1b[6;8r\x1b[6;1Hregion-1\r\nregion-2\r\nregion-3\r\nregion-4\x1b[r" + "\x1b[10;1HNETKIT_XTERM_ALT_OK\r\n").encode("utf-8") +XTERM_MAIN = b"\x1b[?1049l\r\nNETKIT_XTERM_MAIN_OK\r\nfixture> " +XTERM_RESPONSES = {"netkit-xterm-colors": XTERM_COLORS, "netkit-xterm-alt": XTERM_ALT, "netkit-xterm-main": XTERM_MAIN} def config_path(fixture_dir: Path) -> Path: @@ -92,6 +152,8 @@ def shell_response(command: str) -> bytes: """Pure response policy; never converts user input into an OS command.""" if command == "netkit-check": return SUCCESS_LINE + if command in XTERM_RESPONSES: + return XTERM_RESPONSES[command] if command: return DISABLED_LINE return b"\r\nfixture> " @@ -110,7 +172,10 @@ def create_fixture(requested_dir: str | None, include_rotated_host_key: bool) -> client_key = paramiko.Ed25519Key.from_private_key(io.StringIO(private_key_bytes.decode("ascii"))) host_path = fixture_dir / "ssh_host_rsa" client_key_path = fixture_dir / "ssh_client_ed25519" + jump_target_key = paramiko.RSAKey.generate(3072) + jump_target_path = fixture_dir / "ssh_jump_target_rsa" write_private_key(host_key, host_path) + write_private_key(jump_target_key, jump_target_path) write_private_bytes(private_key_bytes, client_key_path) rotated_host_path: Path | None = None rotated_host_fingerprint: str | None = None @@ -141,6 +206,20 @@ def create_fixture(requested_dir: str | None, include_rotated_host_key: bool) -> "rotatedHostKeyAlgorithm": "ssh-rsa" if rotated_host_path else None, "rotatedHostKeyPublicKey": rotated_host_public_key, "rotatedHostKeyFingerprint": rotated_host_fingerprint, + "tcpEchoPort": TCP_ECHO_PORT, + "jumpTargetSshPort": SSH_JUMP_TARGET_PORT, + "jumpTargetHostKeyPath": str(jump_target_path), + "jumpTargetHostKeyAlgorithm": jump_target_key.get_name(), + "jumpTargetHostKeyPublicKey": jump_target_key.get_base64(), + "jumpTargetHostKeyFingerprint": fingerprint(jump_target_key), + "forwardAllowedPorts": sorted(FORWARD_ALLOWED_PORTS), + }, + "sftp": { + "home": SFTP_HOME, + "helloText": SFTP_HELLO.decode("ascii"), + "dataSize": SFTP_DATA_SIZE, + "dataSha256": hashlib.sha256(sftp_seed_data()).hexdigest(), + "maxFileBytes": SFTP_MAX_FILE_BYTES, }, "client": { "profiles": [ @@ -174,6 +253,7 @@ def create_fixture(requested_dir: str | None, include_rotated_host_key: bool) -> "commandMarker": "NETKIT_TEST_OK", "interruptMarker": "NETKIT_INTERRUPT_OK", "resizeMarker": "NETKIT_RESIZE_OK", + "xtermCommands": sorted(XTERM_RESPONSES), "execRequests": "rejected; no commands are executed", }, } @@ -196,6 +276,8 @@ def create_fixture(requested_dir: str | None, include_rotated_host_key: bool) -> "tcpClosedPort": TCP_CLOSED_PORT, "tcpSilentPort": TCP_SILENT_PORT, "sshPort": SSH_PORT, + "tcpEchoPort": TCP_ECHO_PORT, + "jumpTargetSshPort": SSH_JUMP_TARGET_PORT, "hostKeyFingerprint": cfg["server"]["hostKeyFingerprint"], "rotatedHostKeyFingerprint": rotated_host_fingerprint, "username": USERNAME, @@ -258,6 +340,71 @@ def handle_error(self, request: Any, client_address: Any) -> None: del request, client_address +class EchoHandler(socketserver.BaseRequestHandler): + """Bounded echo: at most ECHO_MAX_BYTES, 5 s idle timeout; never interprets the data.""" + + def handle(self) -> None: + self.request.settimeout(5.0) + total = 0 + try: + while total < ECHO_MAX_BYTES: + data = self.request.recv(min(4096, ECHO_MAX_BYTES - total)) + if not data: + break + total += len(data) + self.request.sendall(data) + except OSError: + pass + print(f"TCP_ECHO_BYTES:{total}", flush=True) + + +def forward_allowed(destination: tuple[str, int]) -> bool: + """direct-tcpip policy: only the fixture's own loopback echo and jump-target ports.""" + host, port = destination + return host in FORWARD_ALLOWED_HOSTS and port in FORWARD_ALLOWED_PORTS + + +def bridge_forward(channel: paramiko.Channel, port: int, stop_event: threading.Event) -> None: + """Copies a direct-tcpip channel to 127.0.0.1:port; bounded in time and bytes.""" + try: + upstream = socket.create_connection((BIND_ADDRESS, port), timeout=5) + except OSError: + channel.close() + return + total = 0 + try: + upstream.settimeout(5.0) + deadline = time.monotonic() + FORWARD_MAX_SECONDS + client_open = upstream_open = True + # EOF of one direction only half-closes the other, so a reply after the client's EOF still arrives. + while (client_open or upstream_open) and not stop_event.is_set() and time.monotonic() < deadline \ + and total < FORWARD_MAX_BYTES: + sources = ([channel] if client_open else []) + ([upstream] if upstream_open else []) + readable, _, _ = select.select(sources, [], [], 0.2) + if channel in readable: + data = channel.recv(16384) + if not data: + client_open = False + upstream.shutdown(socket.SHUT_WR) + else: + total += len(data) + upstream.sendall(data) + if upstream in readable: + data = upstream.recv(16384) + if not data: + upstream_open = False + channel.shutdown_write() + else: + total += len(data) + channel.sendall(data) + except (OSError, paramiko.SSHException): + pass + finally: + upstream.close() + channel.close() + print(f"SSH_FORWARD_CLOSED:{port}", flush=True) + + class SilentHandler(socketserver.BaseRequestHandler): def handle(self) -> None: print("SILENT_ACCEPTED", flush=True) @@ -292,6 +439,11 @@ def __init__(self, config: dict[str, Any], stop_event: threading.Event) -> None: self.authorized_key = paramiko.Ed25519Key.from_private_key_file(config["client"]["clientPrivateKeyPath"]).asbytes() self.stop_event = stop_event self.resize_events: queue.Queue[tuple[int, int]] = queue.Queue(maxsize=8) + self.forward_destinations: dict[int, tuple[str, int]] = {} + self.forward_lock = threading.Lock() + self.sftp_channels: set[int] = set() + self.sftp_open: dict[int, paramiko.Channel] = {} + self.sftp_started = threading.Condition(self.forward_lock) def get_allowed_auths(self, username: str) -> str: return "publickey,password,keyboard-interactive" if username == self.username else "" @@ -328,6 +480,38 @@ def check_channel_request(self, kind: str, chanid: int) -> int: return OPEN_SUCCEEDED return OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED + def check_channel_direct_tcpip_request(self, chanid: int, origin: tuple[str, int], + destination: tuple[str, int]) -> int: + del origin + with self.forward_lock: + if not forward_allowed(destination) or len(self.forward_destinations) >= MAX_FORWARDS_PER_TRANSPORT: + print("SSH_DIRECT_TCPIP_DENIED", flush=True) + return OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED + self.forward_destinations[chanid] = (destination[0], int(destination[1])) + print(f"SSH_DIRECT_TCPIP:{int(destination[1])}", flush=True) + return OPEN_SUCCEEDED + + def take_forward(self, chanid: int) -> tuple[str, int] | None: + with self.forward_lock: + return self.forward_destinations.pop(chanid, None) + + def check_channel_subsystem_request(self, channel: paramiko.Channel, name: str) -> bool: + """Only `sftp`, at most SFTP_MAX_CHANNELS_PER_TRANSPORT per connection, on a sandboxed tree.""" + with self.forward_lock: + for chanid in [chanid for chanid, open_channel in self.sftp_open.items() if open_channel.closed]: + del self.sftp_open[chanid] + if name != "sftp" or len(self.sftp_open) >= SFTP_MAX_CHANNELS_PER_TRANSPORT: + print("SFTP_SUBSYSTEM_DENIED", flush=True) + return False + self.sftp_channels.add(channel.get_id()) + self.sftp_open[channel.get_id()] = channel + self.sftp_started.notify_all() + return bool(super().check_channel_subsystem_request(channel, name)) + + def wait_sftp(self, chanid: int, timeout: float) -> bool: + with self.forward_lock: + return self.sftp_started.wait_for(lambda: chanid in self.sftp_channels, timeout) + def check_channel_exec_request(self, channel: paramiko.Channel, command: bytes) -> bool: del channel, command return False @@ -356,6 +540,292 @@ def check_channel_window_change_request(self, channel: paramiko.Channel, width: return True +# --- Zadání 42: SFTP subsystem over a private, sandboxed directory ----------------------------------- +# The browser is tested against this server: a fresh tree under /sftp-root is seeded at each +# `serve`. Virtual paths are absolute and clamped at the sandbox root; every OS path is checked with +# os.path.realpath so a symlink can never lead outside the sandbox (it fails with PERMISSION_DENIED). +# It advertises posix-rename@openssh.com and hardlink@openssh.com like OpenSSH, so the app's no-overwrite +# publish (hardlink, never posix-rename) is exercised; plain RENAME refuses an existing target (SFTP v3). + + +def sftp_seed_data() -> bytes: + """Deterministic 300000-byte binary file (SHA-256 recorded in the config).""" + blocks = bytearray() + counter = 0 + while len(blocks) < SFTP_DATA_SIZE: + blocks += hashlib.sha256(b"netkit-sftp-%d" % counter).digest() + counter += 1 + return bytes(blocks[:SFTP_DATA_SIZE]) + + +def seed_sftp_root(fixture_dir: Path) -> Path: + root = fixture_dir / SFTP_ROOT_NAME + if root.is_symlink(): + raise ValueError("SFTP root must not be a symlink") + if root.exists(): + shutil.rmtree(root) + root.mkdir(mode=0o700) + home = root / SFTP_HOME.lstrip("/") + home.mkdir(mode=0o700, parents=True) + (home / "hello.txt").write_bytes(SFTP_HELLO) + (home / "data.bin").write_bytes(sftp_seed_data()) + (home / "docs").mkdir(mode=0o700) + (home / "docs" / "readme.md").write_bytes(b"docs\n") + (home / "empty").mkdir(mode=0o700) + (home / "star*.txt").write_bytes(b"star\n") + (home / "starfish.txt").write_bytes(b"fish\n") + (home / SFTP_HANG_NAME).write_bytes(b"h" * 65536) + (home / "bad\nname").write_bytes(b"hidden\n") + os.symlink("docs", home / "link-docs") + os.symlink("hello.txt", home / "link-hello") + os.symlink("../../..", home / "escape") # Leads out of the sandbox on the host: must be refused. + return root + + +class SftpSandbox(SFTPServerInterface): + """Per-channel SFTP interface; never follows a path outside [root].""" + + def __init__(self, server: Any, root: str, *args: Any, **kwargs: Any) -> None: + super().__init__(server, *args, **kwargs) + self.root = os.path.realpath(root) + + def session_started(self) -> None: + print("SFTP_SESSION_STARTED", flush=True) + + @staticmethod + def virtual(path: str) -> str: + if "\x00" in path: + raise PermissionError(errno.EACCES, "NUL") + joined = path if path.startswith("/") else posixpath.join(SFTP_HOME, path) + normal = posixpath.normpath("/" + joined.lstrip("/")) # `..` above / stays at / + return "/" if normal in ("/", "//") else normal + + def inside(self, real: str) -> bool: + return real == self.root or real.startswith(self.root + os.sep) + + def real(self, path: str, follow: bool = True) -> str: + """OS path of a virtual path; with follow=False the last element itself is not resolved.""" + virtual = self.virtual(path) + if virtual == "/": + return self.root + parent, name = posixpath.split(virtual) + parent_real = os.path.realpath(self.root + parent) + if not self.inside(parent_real): + print("SFTP_ESCAPE_DENIED", flush=True) + raise PermissionError(errno.EACCES, "outside") + candidate = os.path.join(parent_real, name) + if follow: + resolved = os.path.realpath(candidate) + if not self.inside(resolved): + print("SFTP_ESCAPE_DENIED", flush=True) + raise PermissionError(errno.EACCES, "outside") + return resolved + return candidate + + def to_virtual(self, real: str) -> str: + relative = os.path.relpath(real, self.root) + return "/" if relative == "." else "/" + relative.replace(os.sep, "/") + + @staticmethod + def failed(error: OSError) -> int: + return SFTPServer.convert_errno(error.errno or errno.EIO) + + def canonicalize(self, path: str) -> Any: + try: + real = self.real(path) + os.lstat(real) + return self.to_virtual(real) + except OSError as error: + return self.failed(error) + + def list_folder(self, path: str) -> Any: + try: + directory = self.real(path) + entries = [] + for name in sorted(os.listdir(directory))[:SFTP_MAX_LIST]: + attributes = SFTPAttributes.from_stat(os.lstat(os.path.join(directory, name))) + attributes.filename = name + entries.append(attributes) + print("SFTP_LIST", flush=True) + return entries + except OSError as error: + return self.failed(error) + + def stat(self, path: str) -> Any: + try: + return SFTPAttributes.from_stat(os.stat(self.real(path))) + except OSError as error: + return self.failed(error) + + def lstat(self, path: str) -> Any: + try: + return SFTPAttributes.from_stat(os.lstat(self.real(path, follow=False))) + except OSError as error: + return self.failed(error) + + def open(self, path: str, flags: int, attr: Any) -> Any: + try: + writing = flags & (os.O_WRONLY | os.O_RDWR) + real = self.real(path, follow=not writing) + descriptor = os.open(real, flags | os.O_NOFOLLOW, 0o600) + except OSError as error: + return self.failed(error) + return SftpSandboxHandle(descriptor, flags, bool(writing), hang=posixpath.basename(self.virtual(path)) == SFTP_HANG_NAME) + + def remove(self, path: str) -> int: + try: + os.remove(self.real(path, follow=False)) + print("SFTP_REMOVE", flush=True) + return SFTP_OK + except OSError as error: + return self.failed(error) + + def rename(self, oldpath: str, newpath: str) -> int: + """SFTP v3 RENAME: never replaces an existing target.""" + try: + source, target = self.real(oldpath, follow=False), self.real(newpath, follow=False) + if os.path.lexists(target): + print("SFTP_RENAME_EXISTS", flush=True) + return SFTP_FAILURE + os.rename(source, target) + print("SFTP_RENAME", flush=True) + return SFTP_OK + except OSError as error: + return self.failed(error) + + def posix_rename(self, oldpath: str, newpath: str) -> int: + """OpenSSH extension: replaces the target (POSIX rename). The app must never rely on it.""" + try: + os.rename(self.real(oldpath, follow=False), self.real(newpath, follow=False)) + print("SFTP_POSIX_RENAME", flush=True) + return SFTP_OK + except OSError as error: + return self.failed(error) + + def hardlink(self, oldpath: str, newpath: str) -> int: + """OpenSSH hardlink@openssh.com: link(2) fails when the target exists.""" + try: + os.link(self.real(oldpath, follow=False), self.real(newpath, follow=False), follow_symlinks=False) + print("SFTP_HARDLINK", flush=True) + return SFTP_OK + except FileExistsError: + print("SFTP_HARDLINK_EXISTS", flush=True) + return SFTP_FAILURE + except OSError as error: + return self.failed(error) + + def mkdir(self, path: str, attr: Any) -> int: + try: + os.mkdir(self.real(path, follow=False), 0o700) + print("SFTP_MKDIR", flush=True) + return SFTP_OK + except OSError as error: + return self.failed(error) + + def rmdir(self, path: str) -> int: + try: + os.rmdir(self.real(path, follow=False)) + print("SFTP_RMDIR", flush=True) + return SFTP_OK + except OSError as error: + return self.failed(error) + + def chattr(self, path: str, attr: Any) -> int: + return SFTP_OP_UNSUPPORTED + + def symlink(self, target_path: str, path: str) -> int: + return SFTP_OP_UNSUPPORTED + + def readlink(self, path: str) -> Any: + return SFTP_OP_UNSUPPORTED + + +class SftpSandboxHandle(SFTPHandle): + def __init__(self, descriptor: int, flags: int, writing: bool, hang: bool = False) -> None: + super().__init__(flags) + self.descriptor = descriptor + self.writing = writing + self.written = 0 + self.hang = hang + + def read(self, offset: int, length: int) -> Any: + if self.hang: + print("SFTP_HANG_READ", flush=True) + threading.Event().wait(SFTP_HANG_SECONDS) # the whole subsystem stalls, as with a stuck server + self.hang = False + try: + return os.pread(self.descriptor, min(length, 65536), offset) + except OSError as error: + return SFTPServer.convert_errno(error.errno or errno.EIO) + + def write(self, offset: int, data: Any) -> int: + if offset + len(data) > SFTP_MAX_FILE_BYTES: + return SFTP_FAILURE + try: + os.pwrite(self.descriptor, data, offset) + except OSError as error: + return SFTPServer.convert_errno(error.errno or errno.EIO) + self.written += len(data) + return SFTP_OK + + def stat(self) -> Any: + try: + return SFTPAttributes.from_stat(os.fstat(self.descriptor)) + except OSError as error: + return SFTPServer.convert_errno(error.errno or errno.EIO) + + def close(self) -> None: + if self.writing: + print(f"SFTP_UPLOAD_BYTES:{self.written}", flush=True) + else: + print("SFTP_DOWNLOAD", flush=True) + try: + os.close(self.descriptor) + except OSError: + pass + + +class SftpSandboxServer(SFTPServer): + """Adds what paramiko's server lacks: OpenSSH-style extensions and REALPATH errors.""" + + def _send_server_version(self) -> int: + base: Any = self # BaseSFTP internals are not in paramiko's type stubs + packet_type, data = base._read_packet() + if packet_type != CMD_INIT: + raise SFTPError("Incompatible sftp protocol") + version = struct.unpack(">I", data[:4])[0] + message = Message() + message.add_int(3) + message.add("posix-rename@openssh.com", "1", "hardlink@openssh.com", "1") + base._send_packet(CMD_VERSION, message) + return version + + def _process(self, t: int, request_number: int, msg: Any) -> None: + base: Any = self + sandbox: Any = self.server + if t == CMD_REALPATH: + path = msg.get_text() + resolved = sandbox.canonicalize(path) + if isinstance(resolved, int): + base._send_status(request_number, resolved) + else: + base._response(request_number, CMD_NAME, 1, resolved, "", SFTPAttributes()) + return + if t == CMD_EXTENDED: + tag = msg.get_text() + if tag == "hardlink@openssh.com": + oldpath, newpath = msg.get_text(), msg.get_text() + base._send_status(request_number, sandbox.hardlink(oldpath, newpath)) + return + if tag == "posix-rename@openssh.com": + oldpath, newpath = msg.get_text(), msg.get_text() + base._send_status(request_number, sandbox.posix_rename(oldpath, newpath)) + return + base._send_status(request_number, SFTP_OP_UNSUPPORTED) + return + super()._process(t, request_number, msg) # pyright: ignore[reportAttributeAccessIssue] + + class SshHandler(socketserver.BaseRequestHandler): def handle(self) -> None: stop_event: threading.Event = self.server.stop_event # type: ignore[attr-defined] @@ -363,6 +833,9 @@ def handle(self) -> None: config: dict[str, Any] = self.server.config # type: ignore[attr-defined] transport = paramiko.Transport(self.request) transport.add_server_key(host_key) + sftp_root = getattr(self.server, "sftp_root", None) + if sftp_root is not None: + transport.set_subsystem_handler("sftp", SftpSandboxServer, SftpSandbox, str(sftp_root)) if getattr(self.server, "legacy_algorithms", False): transport.get_security_options().ciphers = ("aes128-cbc",) auth = FixtureAuth(config, stop_event) @@ -370,12 +843,22 @@ def handle(self) -> None: transport.start_server(server=auth) deadline = time.monotonic() + SSH_CHANNEL_ACCEPT_SECONDS channel = None - while not stop_event.is_set() and time.monotonic() < deadline: - channel = transport.accept(timeout=min(0.2, max(0.01, deadline - time.monotonic()))) - if channel is not None: - break + forwarded = False + # A jump host or forward-only client may never open a shell: keep bridging while it is connected. + while not stop_event.is_set() and transport.is_active() and (forwarded or time.monotonic() < deadline): + accepted = transport.accept(timeout=0.2) + if accepted is None: + continue + destination = auth.take_forward(accepted.get_id()) + if destination is not None: + forwarded = True + threading.Thread(target=bridge_forward, args=(accepted, destination[1], stop_event), daemon=True).start() + continue + channel = accepted + break if channel is None: return + threading.Thread(target=self.accept_forwards, args=(transport, auth, stop_event), daemon=True).start() channel.settimeout(0.2) channel.sendall(READY_LINE) line_buffer = bytearray() @@ -406,6 +889,8 @@ def handle(self) -> None: channel.sendall(shell_response(command)) if command == "netkit-check": print("SSH_COMMAND_OK", flush=True) + elif command in XTERM_RESPONSES: + print(f"SSH_XTERM_SENT:{command}", flush=True) elif byte >= 32 and byte != 127: if len(line_buffer) < 256: line_buffer.append(byte) @@ -424,6 +909,28 @@ def handle(self) -> None: transport.close() print("SSH_SESSION_CLOSED", flush=True) + @staticmethod + def accept_forwards(transport: paramiko.Transport, auth: "FixtureAuth", stop_event: threading.Event) -> None: + """While the shell runs, -L/-D channels may arrive at any time; extra session channels are closed.""" + while not stop_event.is_set() and transport.is_active(): + try: + accepted = transport.accept(timeout=0.2) + except (OSError, paramiko.SSHException, EOFError): + return + if accepted is None: + continue + destination = auth.take_forward(accepted.get_id()) + if destination is None: + # A session channel may still ask for the sftp subsystem (zadání 42); anything else is closed. + threading.Thread(target=SshHandler.close_unless_sftp, args=(accepted, auth), daemon=True).start() + continue + threading.Thread(target=bridge_forward, args=(accepted, destination[1], stop_event), daemon=True).start() + + @staticmethod + def close_unless_sftp(channel: paramiko.Channel, auth: "FixtureAuth") -> None: + if not auth.wait_sftp(channel.get_id(), SFTP_SUBSYSTEM_WAIT_SECONDS): + channel.close() + class SshServer(BannerServer): allow_reuse_address = True @@ -434,6 +941,7 @@ def __init__(self, address: tuple[str, int], config: dict[str, Any], host_key_pa stop_event: threading.Event) -> None: super().__init__(address, SshHandler) self.legacy_algorithms = False + self.sftp_root: Path | None = None self.config = config self.host_key = paramiko.RSAKey.from_private_key_file(host_key_path) self.stop_event = stop_event @@ -462,7 +970,8 @@ def serve_fixture(fixture_dir_arg: str, host_key_choice: str, duration: int) -> else: host_key_path = config["server"]["hostKeyPath"] private_files = [Path(host_key_path), Path(config["client"]["clientPrivateKeyPath"])] - private_files.extend(Path(value) for value in (config["server"].get("rotatedHostKeyPath"),) if value) + private_files.extend(Path(value) for value in (config["server"].get("rotatedHostKeyPath"), + config["server"].get("jumpTargetHostKeyPath")) if value) for private_file in private_files: if private_file.is_symlink() or private_file.resolve(strict=True).parent != fixture_dir: raise ValueError("Private fixture key must be a direct file in the fixture directory") @@ -476,7 +985,12 @@ def serve_fixture(fixture_dir_arg: str, host_key_choice: str, duration: int) -> silent_server = SilentServer((BIND_ADDRESS, TCP_SILENT_PORT), stop_event) ssh_server = SshServer((BIND_ADDRESS, SSH_PORT), config, host_key_path, stop_event) ssh_server.legacy_algorithms = host_key_choice == "legacy" + ssh_server.sftp_root = seed_sftp_root(fixture_dir) # fresh tree for every serve servers: list[socketserver.ThreadingTCPServer] = [banner_server, silent_server, ssh_server] + jump_target_key_path = config["server"].get("jumpTargetHostKeyPath") + if jump_target_key_path: + servers.append(BannerServer((BIND_ADDRESS, TCP_ECHO_PORT), EchoHandler)) + servers.append(SshServer((BIND_ADDRESS, SSH_JUMP_TARGET_PORT), config, jump_target_key_path, stop_event)) workers = [threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.2}, daemon=True) for server in servers] for worker in workers: @@ -484,6 +998,8 @@ def serve_fixture(fixture_dir_arg: str, host_key_choice: str, duration: int) -> print(json.dumps({"event": "started", "bindAddress": BIND_ADDRESS, "tcpBannerPort": TCP_BANNER_PORT, "sshPort": SSH_PORT, + "tcpEchoPort": TCP_ECHO_PORT if jump_target_key_path else None, + "jumpTargetSshPort": SSH_JUMP_TARGET_PORT if jump_target_key_path else None, "tcpClosedPort": TCP_CLOSED_PORT, "tcpSilentPort": TCP_SILENT_PORT, "hostKeyChoice": host_key_choice, "maxDurationSeconds": duration}), flush=True) stopped = threading.Event() diff --git a/tools/testsrv/telnet_fixture.py b/tools/testsrv/telnet_fixture.py new file mode 100644 index 0000000..c0bdb9a --- /dev/null +++ b/tools/testsrv/telnet_fixture.py @@ -0,0 +1,49 @@ +"""Single-session Telnet peer for the NetKit JVM test. TCP binds only to localhost.""" + +import argparse +import socket +import sys +from typing import BinaryIO + + +def exchange(reader: BinaryIO, writer: BinaryIO) -> None: + def send(data: bytes) -> None: + writer.write(data) + writer.flush() + + def expect(data: bytes) -> None: + if reader.read(len(data)) != data: + raise ValueError("Unexpected client frame") + + # Remote ECHO, client TTYPE and NAWS, unknown DO. Split across IAC boundaries. + for fragment in ("ff", "fb01fffd18ff", "fd1ffffd55fffa1801ff", "f0"): + send(bytes.fromhex(fragment)) + send("Připraven\r\n".encode()) + expect(bytes.fromhex("fffd01 fffb18 fffb1f fffa1f00500018fff0 fffc55 fffa1800")) + expect(b"xterm-256color" + bytes.fromhex("fff0")) + expect(bytes.fromhex("fffa1f00780028fff0")) + expect(b"ok\r\n") + send(b"OK\r\n") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--stdio", action="store_true", help="use pipes for socket-restricted test hosts") + args = parser.parse_args() + if args.stdio: + exchange(sys.stdin.buffer, sys.stdout.buffer) + return + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + listener.settimeout(10) + print(listener.getsockname()[1], flush=True) + client, _ = listener.accept() + with client: + client.settimeout(10) + with client.makefile("rb") as reader, client.makefile("wb") as writer: + exchange(reader, writer) + + +if __name__ == "__main__": + main() diff --git a/tools/testsrv/test_iperf3_fixture.py b/tools/testsrv/test_iperf3_fixture.py new file mode 100644 index 0000000..e1f4b08 --- /dev/null +++ b/tools/testsrv/test_iperf3_fixture.py @@ -0,0 +1,38 @@ +import importlib.util +import io +from pathlib import Path +import struct +import unittest + +spec = importlib.util.spec_from_file_location("iperf3_fixture", Path(__file__).with_name("iperf3_fixture.py")) +assert spec is not None and spec.loader is not None +fixture = importlib.util.module_from_spec(spec) +spec.loader.exec_module(fixture) + + +class FragmentedReader(io.BytesIO): + def read(self, size: int | None = -1) -> bytes: + return super().read(2 if size is None or size < 0 else min(size, 2)) + + +class FrameTests(unittest.TestCase): + def test_fragmentation_and_coalescing(self) -> None: + obj = {"name": "měření", "streams": [1, 3]} + stream = FragmentedReader(fixture.frame(obj) + b'\x0e') + self.assertEqual(fixture.read_json(stream), obj) + self.assertEqual(stream.read(1), b'\x0e') + + def test_rejects_bad_lengths_before_payload(self) -> None: + for size in (0, 65537, 0xFFFFFFFF): + with self.assertRaises(ValueError): + fixture.read_json(io.BytesIO(struct.pack("!I", size))) + + def test_truncated_and_non_object(self) -> None: + with self.assertRaises(EOFError): + fixture.read_json(FragmentedReader(b'\x00\x00\x00\x05{}')) + with self.assertRaises(ValueError): + fixture.read_json(FragmentedReader(b'\x00\x00\x00\x02[]')) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/testsrv/test_m1_fixture.py b/tools/testsrv/test_m1_fixture.py index 06592b3..8285541 100644 --- a/tools/testsrv/test_m1_fixture.py +++ b/tools/testsrv/test_m1_fixture.py @@ -24,12 +24,40 @@ def test_fixed_ports_and_loopback_policy(self) -> None: self.assertEqual(fixture.MAX_ACTIVE_SESSIONS, 8) self.assertEqual(fixture.SSH_CHANNEL_ACCEPT_SECONDS, 120.0) + def test_forward_policy_allows_only_own_loopback_ports(self) -> None: + self.assertEqual((fixture.TCP_ECHO_PORT, fixture.SSH_JUMP_TARGET_PORT), (18084, 22223)) + self.assertTrue(fixture.forward_allowed(("127.0.0.1", 18084))) + self.assertTrue(fixture.forward_allowed(("localhost", 22223))) + for destination in (("127.0.0.1", 22), ("127.0.0.1", 18081), ("10.0.2.2", 18084), ("0.0.0.0", 18084), + ("192.0.2.1", 22223), ("::1", 18084)): + self.assertFalse(fixture.forward_allowed(destination), destination) + def test_shell_policy_never_executes_arbitrary_input(self) -> None: self.assertIn(b"NETKIT_TEST_OK", fixture.shell_response("netkit-check")) self.assertIn(b"Command disabled", fixture.shell_response("uname -a")) self.assertIn(b"Command disabled", fixture.shell_response("netkit-check; id")) self.assertEqual(fixture.shell_response(""), b"\r\nfixture> ") + def test_xterm_demo_responses_are_canned_bytes(self) -> None: + # Zadání 43: printf-equivalent output, byte-identical to xtermColorDemo() in TerminalXtermTest.kt + # (both pin the same FNV-1a checksum); the alternate-screen demo restores the primary screen. + def fnv1a(data: bytes) -> int: + value = 0x811C9DC5 + for byte in data: + value = ((value ^ byte) * 0x01000193) & 0xFFFFFFFF + return value + + colors = fixture.shell_response("netkit-xterm-colors") + self.assertEqual((fnv1a(colors), len(colors)), (0x9A12C5C8, 3459)) + self.assertEqual(colors.count(b"\x1b[48;5;"), 256) + self.assertIn(b"\x1b[48;5;255m ", colors) + alternate = fixture.shell_response("netkit-xterm-alt") + self.assertTrue(alternate.startswith(b"\x1b[?1049h")) + self.assertIn(b"\x1b]2;NetKit alt\x07", alternate) + self.assertNotIn(b"\x1b]52", alternate) + self.assertTrue(fixture.shell_response("netkit-xterm-main").startswith(b"\x1b[?1049l")) + self.assertIn(b"Command disabled", fixture.shell_response("netkit-xterm-colors; id")) + def test_generated_config_and_private_material_are_only_under_private_tmp_dir(self) -> None: output = fixture.create_fixture(None, include_rotated_host_key=False) directory = Path(output["fixtureDir"]) @@ -112,5 +140,134 @@ def process_request_thread(self, request: Any, client_address: Any) -> None: server._session_slots.release() +class SftpSandboxTests(unittest.TestCase): + """Zadání 42: the SFTP subsystem stays inside its sandbox and keeps SFTP v3 rename semantics.""" + + @classmethod + def setUpClass(cls) -> None: + output = fixture.create_fixture(None, include_rotated_host_key=False) + cls.directory = Path(output["fixtureDir"]) + cls.config = json.loads(Path(output["configPath"]).read_text(encoding="utf-8")) + cls.stop = threading.Event() + cls.server = fixture.SshServer(("127.0.0.1", 0), cls.config, cls.config["server"]["hostKeyPath"], cls.stop) + cls.server.sftp_root = fixture.seed_sftp_root(cls.directory) + cls.worker = threading.Thread(target=cls.server.serve_forever, kwargs={"poll_interval": 0.1}, daemon=True) + cls.worker.start() + + @classmethod + def tearDownClass(cls) -> None: + cls.stop.set() + cls.server.shutdown() + cls.server.server_close() + shutil.rmtree(cls.directory) + + def open(self) -> tuple[Any, Any, Any]: + client = fixture.paramiko.SSHClient() + client.set_missing_host_key_policy(fixture.paramiko.AutoAddPolicy()) + client.connect("127.0.0.1", port=self.server.server_address[1], username=fixture.USERNAME, + password=self.config["client"]["password"], look_for_keys=False, allow_agent=False, timeout=10) + shell = client.invoke_shell() # The fixture's first channel is the shell, as in the app. + return client, shell, client.open_sftp() + + def test_seed_realpath_and_sandbox(self) -> None: + client, _shell, sftp = self.open() + try: + home = self.config["sftp"]["home"] + self.assertEqual(sftp.normalize("."), home) + self.assertEqual(sftp.normalize(home + "/.."), "/home") + self.assertEqual(sftp.normalize("/.."), "/") + self.assertEqual(sftp.normalize("/../../etc/.."), "/") + self.assertEqual(sftp.normalize("link-docs"), home + "/docs") + names = set(sftp.listdir(home)) + self.assertTrue({"hello.txt", "data.bin", "docs", "empty", "link-docs", "link-hello", "escape", "bad\nname", + "star*.txt", "starfish.txt"} <= names) + with sftp.open("data.bin") as stream: + self.assertEqual(fixture.hashlib.sha256(stream.read()).hexdigest(), self.config["sftp"]["dataSha256"]) + for operation in (lambda: sftp.normalize("escape"), lambda: sftp.stat("escape"), + lambda: sftp.listdir("escape"), lambda: sftp.open("escape/m1-fixture.json")): + with self.assertRaises(PermissionError): + operation() + self.assertTrue(stat.S_ISLNK(sftp.lstat("escape").st_mode)) # the link itself is visible + with self.assertRaises(FileNotFoundError): + sftp.normalize("missing") + finally: + client.close() + + def test_plain_rename_never_replaces(self) -> None: + client, _shell, sftp = self.open() + try: + for name, data in (("r-a.txt", b"A"), ("r-b.txt", b"B")): + with sftp.open(name, "wb") as stream: + stream.write(data) + with self.assertRaises(OSError): + sftp.rename("r-a.txt", "r-b.txt") # SSH_FXP_RENAME (SFTP v3) + with sftp.open("r-b.txt") as stream: + self.assertEqual(stream.read(), b"B") + sftp.rename("r-a.txt", "r-c.txt") + self.assertEqual(sorted(n for n in sftp.listdir() if n.startswith("r-")), ["r-b.txt", "r-c.txt"]) + finally: + client.close() + + def test_hardlink_refuses_existing_target(self) -> None: + client, _shell, sftp = self.open() + try: + for name, data in (("h-a.txt", b"A"), ("h-b.txt", b"B")): + with sftp.open(name, "wb") as stream: + stream.write(data) + with self.assertRaises(OSError): + sftp._request(fixture.CMD_EXTENDED, "hardlink@openssh.com", "h-a.txt", "h-b.txt") + with sftp.open("h-b.txt") as stream: + self.assertEqual(stream.read(), b"B") + sftp._request(fixture.CMD_EXTENDED, "hardlink@openssh.com", "h-a.txt", "h-c.txt") + with sftp.open("h-c.txt") as stream: + self.assertEqual(stream.read(), b"A") + sftp.posix_rename("h-a.txt", "h-b.txt") # the overwriting extension the app avoids + with sftp.open("h-b.txt") as stream: + self.assertEqual(stream.read(), b"A") + finally: + client.close() + + def test_hanging_file_blocks_reads(self) -> None: + client, _shell, sftp = self.open() + previous = fixture.SFTP_HANG_SECONDS + fixture.SFTP_HANG_SECONDS = 1.0 + try: + started = time.monotonic() + with sftp.open(fixture.SFTP_HANG_NAME) as stream: + self.assertEqual(len(stream.read(10)), 10) + self.assertGreaterEqual(time.monotonic() - started, 0.9) + finally: + fixture.SFTP_HANG_SECONDS = previous + client.close() + + def test_closed_sftp_channels_free_their_slot(self) -> None: + client, _shell, sftp = self.open() + try: + sftp.close() + for _ in range(fixture.SFTP_MAX_CHANNELS_PER_TRANSPORT + 2): + extra = client.open_sftp() + self.assertEqual(extra.normalize("."), self.config["sftp"]["home"]) + extra.close() + time.sleep(0.1) + finally: + client.close() + + def test_write_limit_and_extra_channels(self) -> None: + client, _shell, sftp = self.open() + try: + with self.assertRaises(OSError): + with sftp.open("big.bin", "wb") as stream: + stream.write(b"x" * 1024) + stream.seek(fixture.SFTP_MAX_FILE_BYTES) + stream.write(b"y") + extra = [client.open_sftp() for _ in range(fixture.SFTP_MAX_CHANNELS_PER_TRANSPORT - 1)] + with self.assertRaises(Exception): + client.open_sftp() + for channel in extra: + channel.close() + finally: + client.close() + + if __name__ == "__main__": unittest.main() diff --git a/tools/testsrv/test_udp_services.py b/tools/testsrv/test_udp_services.py new file mode 100644 index 0000000..f9d3cae --- /dev/null +++ b/tools/testsrv/test_udp_services.py @@ -0,0 +1,83 @@ +"""Unit and loopback checks for the synthetic SNMP/NTP/DNS UDP fixture.""" + +from __future__ import annotations + +import socket +import subprocess +import sys +import unittest +from pathlib import Path + +try: + import udp_services as fixture +except ModuleNotFoundError: + from testsrv import udp_services as fixture + +COMMUNITY = b"fixture-community" + + +def snmp_get(request_id: int, community: bytes = COMMUNITY) -> bytes: + bindings = b"".join(fixture.tlv(0x30, fixture.encode_oid(oid) + b"\x05\x00") + for oid in (fixture.SYS_DESCR_OID, fixture.SYS_NAME_OID)) + pdu = fixture.tlv(0xA0, fixture.ber_int(request_id) + fixture.ber_int(0) + fixture.ber_int(0) + fixture.tlv(0x30, bindings)) + return fixture.tlv(0x30, fixture.ber_int(1) + fixture.tlv(0x04, community) + pdu) + + +class HandlerTests(unittest.TestCase): + def test_snmp_answers_only_matching_community(self) -> None: + reply = fixture.snmp_response(snmp_get(300), COMMUNITY) + assert reply is not None + self.assertIn(fixture.SYS_DESCR, reply) + self.assertIn(fixture.SYS_NAME, reply) + self.assertIn(fixture.ber_int(300), reply) + self.assertIsNone(fixture.snmp_response(snmp_get(300, b"wrong"), COMMUNITY)) + self.assertIsNone(fixture.snmp_response(b"\x30\x80\x00\x00", COMMUNITY)) + self.assertIsNone(fixture.snmp_response(snmp_get(300)[:-3], COMMUNITY)) + + def test_ntp_copies_transmit_into_origin(self) -> None: + request = bytearray(48) + request[0] = 0x23 + request[40:48] = bytes(range(1, 9)) + reply = fixture.ntp_response(bytes(request)) + assert reply is not None + self.assertEqual(reply[0] & 7, 4) + self.assertEqual(reply[1], 2) + self.assertEqual(reply[12:16], fixture.NTP_REFERENCE) + self.assertEqual(reply[24:32], bytes(range(1, 9))) + self.assertIsNone(fixture.ntp_response(bytes(47))) + + def test_dns_version_bind_and_refusal(self) -> None: + question = b"\x07version\x04bind\x00\x00\x10\x00\x03" + reply = fixture.dns_response(b"\x12\x34\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00" + question) + assert reply is not None + self.assertEqual(reply[:2], b"\x12\x34") + self.assertEqual(reply[3] & 0x0F, 0) + self.assertTrue(reply.endswith(fixture.DNS_VERSION)) + other = fixture.dns_response(b"\x12\x34\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00" + b"\x07example\x00\x00\x01\x00\x01") + assert other is not None + self.assertEqual(other[3] & 0x0F, 5) + + +class LoopbackTests(unittest.TestCase): + def test_server_binds_loopback_and_answers(self) -> None: + script = Path(__file__).with_name("udp_services.py") + process = subprocess.Popen([sys.executable, "-I", str(script), "--community", COMMUNITY.decode(), "--duration", "20"], + stdout=subprocess.PIPE, text=True) + try: + assert process.stdout is not None + line = process.stdout.readline().split() + self.assertEqual(line[0], "READY") + ports = {key: int(value) for key, value in (part.split("=") for part in line[1:])} + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client: + client.settimeout(3) + client.sendto(snmp_get(7), ("127.0.0.1", ports["snmp"])) + data, peer = client.recvfrom(4096) + self.assertEqual(peer[0], "127.0.0.1") + self.assertIn(fixture.SYS_NAME, data) + finally: + process.terminate() + process.wait(timeout=5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/testsrv/test_wol_listener.py b/tools/testsrv/test_wol_listener.py new file mode 100644 index 0000000..e083316 --- /dev/null +++ b/tools/testsrv/test_wol_listener.py @@ -0,0 +1,65 @@ +"""Loopback checks for wol_listener.py, including the SecureOn variant (assignment 39).""" + +from __future__ import annotations + +import socket +import subprocess +import sys +import time +import unittest +from pathlib import Path + +try: + import wol_listener as listener +except ModuleNotFoundError: + from testsrv import wol_listener as listener + +SCRIPT = Path(__file__).with_name("wol_listener.py") + + +def free_port() -> int: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe: + probe.bind(("127.0.0.1", 0)) + return probe.getsockname()[1] + + +class ListenerTests(unittest.TestCase): + def test_expected_packet_lengths(self) -> None: + self.assertEqual(len(listener.expected_packet()), 102) + self.assertEqual(len(listener.expected_packet(bytes(6))), 108) + self.assertEqual(len(listener.expected_packet(bytes(4))), 106) + with self.assertRaises(ValueError): + listener.expected_packet(bytes(5)) + self.assertEqual(listener.parse_secureon("11:22:33:44:55:66"), bytes.fromhex("112233445566")) + + def run_listener(self, secureon: str, packet: bytes) -> tuple[int, str]: + port = free_port() + process = subprocess.Popen([sys.executable, "-I", str(SCRIPT), "--timeout", "5", "--count", "1", "--port", str(port), + "--secureon", secureon], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + try: + assert process.stdout is not None + self.assertIn("LISTENING", process.stdout.readline()) + time.sleep(0.05) + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender: + sender.sendto(packet, ("127.0.0.1", port)) + output, _ = process.communicate(timeout=10) + return process.returncode, output + finally: + if process.poll() is None: + process.kill() + process.wait(timeout=5) + + def test_secureon_packet_of_108_bytes_passes(self) -> None: + code, output = self.run_listener("112233445566", listener.expected_packet(bytes.fromhex("112233445566"))) + self.assertEqual(code, 0, output) + self.assertIn("length=108", output) + self.assertNotIn("112233445566", output) + + def test_plain_packet_fails_when_secureon_is_expected(self) -> None: + code, output = self.run_listener("112233445566", listener.expected_packet()) + self.assertEqual(code, 1, output) + self.assertIn("102 B", output) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/testsrv/udp_services.py b/tools/testsrv/udp_services.py new file mode 100644 index 0000000..ef01c49 --- /dev/null +++ b/tools/testsrv/udp_services.py @@ -0,0 +1,230 @@ +#!/usr/bin/env python3 +"""Minimal loopback UDP responders for NetKit's "Identify services" probe (assignment 39). + +SNMPv2c GetRequest -> GetResponse with synthetic sysDescr/sysName (only for the configured +community; anything else is silently dropped like a real agent), NTP mode 3 -> mode 4 +(stratum 2, reference 192.0.2.1) and DNS ``version.bind CH TXT`` -> "netkit-fixture". +Standard library only; binds 127.0.0.1 exclusively. Prints one ``READY`` line with the ports. +""" + +from __future__ import annotations + +import argparse +import selectors +import socket +import sys +import time + +HOST = "127.0.0.1" +SYS_DESCR_OID = (1, 3, 6, 1, 2, 1, 1, 1, 0) +SYS_NAME_OID = (1, 3, 6, 1, 2, 1, 1, 5, 0) +SYS_DESCR = b"NetKit fixture SNMP agent (synthetic)" +SYS_NAME = b"netkit-fixture" +NTP_REFERENCE = bytes((192, 0, 2, 1)) +DNS_VERSION = b"netkit-fixture" +MAX_DATAGRAM = 4096 + + +class BerError(ValueError): + pass + + +def ber_read(data: bytes, offset: int, limit: int) -> tuple[int, int, int]: + """Return (tag, content_start, content_end) of one definite-length element.""" + if offset + 2 > limit: + raise BerError("short") + tag = data[offset] + first = data[offset + 1] + cursor = offset + 2 + if first < 0x80: + size = first + elif first in (0x81, 0x82): + count = first - 0x80 + if cursor + count > limit: + raise BerError("short length") + size = int.from_bytes(data[cursor:cursor + count], "big") + cursor += count + else: + raise BerError("unsupported length") + end = cursor + size + if end > limit: + raise BerError("element beyond parent") + return tag, cursor, end + + +def ber_children(data: bytes, start: int, end: int) -> list[tuple[int, int, int]]: + out = [] + cursor = start + while cursor < end: + child = ber_read(data, cursor, end) + out.append(child) + cursor = child[2] + if len(out) > 16: + raise BerError("too many children") + return out + + +def tlv(tag: int, content: bytes) -> bytes: + size = len(content) + if size < 0x80: + header = bytes((tag, size)) + elif size <= 0xFF: + header = bytes((tag, 0x81, size)) + else: + header = bytes((tag, 0x82)) + size.to_bytes(2, "big") + return header + content + + +def ber_int(value: int) -> bytes: + length = max(1, (value.bit_length() + 8) // 8) + return tlv(0x02, value.to_bytes(length, "big", signed=True)) + + +def decode_oid(content: bytes) -> tuple[int, ...]: + if not content: + raise BerError("empty oid") + arcs = [min(content[0] // 40, 2)] + arcs.append(content[0] - arcs[0] * 40) + value = 0 + for byte in content[1:]: + value = (value << 7) | (byte & 0x7F) + if not byte & 0x80: + arcs.append(value) + value = 0 + return tuple(arcs) + + +def encode_oid(arcs: tuple[int, ...]) -> bytes: + body = bytearray([arcs[0] * 40 + arcs[1]]) + for arc in arcs[2:]: + groups = [arc & 0x7F] + arc >>= 7 + while arc: + groups.append(0x80 | (arc & 0x7F)) + arc >>= 7 + body.extend(reversed(groups)) + return tlv(0x06, bytes(body)) + + +def snmp_response(request: bytes, community: bytes) -> bytes | None: + """GetResponse for a v2c GetRequest with [community]; None means stay silent.""" + try: + tag, start, end = ber_read(request, 0, len(request)) + if tag != 0x30 or end != len(request): + return None + version, given, pdu = ber_children(request, start, end) + if version[0] != 0x02 or request[version[1]:version[2]] != b"\x01": + return None + if given[0] != 0x04 or request[given[1]:given[2]] != community: + return None + if pdu[0] != 0xA0: + return None + request_id, _status, _index, bindings = ber_children(request, pdu[1], pdu[2]) + oids = [] + for _tag, b_start, b_end in ber_children(request, bindings[1], bindings[2]): + oid, _value = ber_children(request, b_start, b_end) + oids.append(decode_oid(request[oid[1]:oid[2]])) + except (BerError, ValueError): + return None + values = {SYS_DESCR_OID: SYS_DESCR, SYS_NAME_OID: SYS_NAME} + out = b"".join( + tlv(0x30, encode_oid(oid) + (tlv(0x04, values[oid]) if oid in values else tlv(0x80, b""))) + for oid in oids + ) + pdu_out = tlv(0xA2, tlv(0x02, request[request_id[1]:request_id[2]]) + ber_int(0) + ber_int(0) + tlv(0x30, out)) + return tlv(0x30, ber_int(1) + tlv(0x04, community) + pdu_out) + + +def ntp_response(request: bytes) -> bytes | None: + if len(request) < 48 or request[0] & 0x07 != 3: + return None + reply = bytearray(48) + reply[0] = (0 << 6) | (4 << 3) | 4 + reply[1] = 2 + reply[12:16] = NTP_REFERENCE + reply[24:32] = request[40:48] + return bytes(reply) + + +def dns_response(request: bytes) -> bytes | None: + if len(request) < 12 or request[2] & 0x80: + return None + cursor = 12 + labels = [] + while cursor < len(request) and request[cursor] != 0: + size = request[cursor] + if size > 63 or cursor + 1 + size > len(request): + return None + labels.append(request[cursor + 1:cursor + 1 + size].lower()) + cursor += 1 + size + if cursor + 5 > len(request): + return None + qtype = int.from_bytes(request[cursor + 1:cursor + 3], "big") + qclass = int.from_bytes(request[cursor + 3:cursor + 5], "big") + question = request[12:cursor + 5] + match = labels == [b"version", b"bind"] and qtype == 16 and qclass == 3 + rcode = 0 if match else 5 + header = request[0:2] + bytes((0x84, rcode)) + b"\x00\x01" + (b"\x00\x01" if match else b"\x00\x00") + b"\x00\x00\x00\x00" + answer = b"" + if match: + data = bytes((len(DNS_VERSION),)) + DNS_VERSION + answer = b"\xc0\x0c\x00\x10\x00\x03\x00\x00\x00\x00" + len(data).to_bytes(2, "big") + data + return header + question + answer + + +def open_socket(port: int) -> socket.socket: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.bind((HOST, port)) + sock.setblocking(False) + return sock + + +def serve(community: bytes, ports: tuple[int, int, int], duration: float) -> int: + handlers = {} + selector = selectors.DefaultSelector() + sockets = [] + try: + for port, handler in zip(ports, (lambda data: snmp_response(data, community), ntp_response, dns_response)): + sock = open_socket(port) + sockets.append(sock) + handlers[sock.fileno()] = handler + selector.register(sock, selectors.EVENT_READ) + actual = [sock.getsockname()[1] for sock in sockets] + print(f"READY snmp={actual[0]} ntp={actual[1]} dns={actual[2]}", flush=True) + deadline = time.monotonic() + duration + while (remaining := deadline - time.monotonic()) > 0: + for key, _events in selector.select(timeout=min(remaining, 0.5)): + sock = key.fileobj + assert isinstance(sock, socket.socket) + data, peer = sock.recvfrom(MAX_DATAGRAM + 1) + if peer[0] != HOST or len(data) > MAX_DATAGRAM: + continue + reply = handlers[sock.fileno()](data) + if reply is not None: + sock.sendto(reply, peer) + return 0 + finally: + selector.close() + for sock in sockets: + sock.close() + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--community", required=True, help="synthetic SNMP community the agent accepts") + parser.add_argument("--snmp-port", type=int, default=0) + parser.add_argument("--ntp-port", type=int, default=0) + parser.add_argument("--dns-port", type=int, default=0) + parser.add_argument("--duration", type=float, default=60.0, help="seconds to serve (default 60)") + args = parser.parse_args(argv) + ports = (args.snmp_port, args.ntp_port, args.dns_port) + if any(port < 0 or port > 65535 for port in ports) or not 0 < args.duration <= 3600: + parser.error("ports must be 0..65535 and duration 0..3600 s") + community = args.community.encode() + if not 1 <= len(community) <= 255: + parser.error("community must be 1..255 bytes") + return serve(community, ports, args.duration) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/testsrv/web_diagnostic.py b/tools/testsrv/web_diagnostic.py new file mode 100644 index 0000000..f40fbd0 --- /dev/null +++ b/tools/testsrv/web_diagnostic.py @@ -0,0 +1,70 @@ +"""Loopback HTTP/TLS fixture. Prints HTTP and HTTPS ports; Enter or stdin EOF stops it.""" +import argparse +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +import ssl +import subprocess +import sys +import tempfile +import threading +import time + + +class DiagnosticHandler(BaseHTTPRequestHandler): + def do_HEAD(self) -> None: + if self.path == "/local-location": + self.send_response(302) + assert isinstance(self.server, ThreadingHTTPServer) + self.send_header("Location", f"http://127.0.0.1:{self.server.server_port}/fallback") + elif self.path == "/user-agent": + self.send_response_only(200) + self.send_header("Server", self.headers.get("User-Agent", "")) + elif self.path in ("/redirect", "/loop"): + self.send_response(302) + self.send_header("Location", "/fallback" if self.path == "/redirect" else "/loop") + elif self.path == "/fallback": + self.send_response(405) + else: + self.send_response(200) + self.end_headers() + + def do_GET(self) -> None: + time.sleep(0.03) + self.send_response(200) + self.send_header("Strict-Transport-Security", "max-age=300") + self.send_header("Content-Length", "65537") + self.end_headers() + try: + self.wfile.write(bytes(65537)) + except (BrokenPipeError, ConnectionResetError): + pass # The diagnostic closes the connection after reading metadata. + + def log_message(self, format: str, *args: object) -> None: + pass + + +def serve(http_port: int) -> None: + with tempfile.TemporaryDirectory() as directory: + cert = Path(directory) / "cert.pem" + key = Path(directory) / "key.pem" + subprocess.run(["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1", + "-subj", "/CN=example.test", "-addext", "subjectAltName=DNS:example.test", + "-keyout", str(key), "-out", str(cert)], check=True, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + tls.load_cert_chain(cert, key) + with (ThreadingHTTPServer(("127.0.0.1", http_port), DiagnosticHandler) as plain, + ThreadingHTTPServer(("127.0.0.1", 0), DiagnosticHandler) as secure): + secure.socket = tls.wrap_socket(secure.socket, server_side=True) + for server in (plain, secure): + threading.Thread(target=server.serve_forever, daemon=True).start() + print(plain.server_port, secure.server_port, cert, flush=True) + sys.stdin.readline() + plain.shutdown() + secure.shutdown() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--http-port", type=int, default=0) + serve(parser.parse_args().http_port) diff --git a/tools/testsrv/wol_listener.py b/tools/testsrv/wol_listener.py index a451094..77f838c 100755 --- a/tools/testsrv/wol_listener.py +++ b/tools/testsrv/wol_listener.py @@ -1,5 +1,10 @@ #!/usr/bin/env python3 -"""Receive and validate exactly three NetKit WoL magic packets on loopback.""" +"""Receive and validate NetKit WoL magic packets on loopback. + +By default exactly three 102-byte packets for AA:BB:CC:DD:EE:FF on 127.0.0.1:9009 (the WoL E2E +contract). ``--secureon`` (assignment 39) expects the 4- or 6-byte SecureOn password appended, +i.e. 106 or 108 bytes; ``--count`` changes the number of packets. +""" import argparse import socket @@ -13,6 +18,19 @@ EXPECTED_PACKET = b"\xff" * 6 + EXPECTED_MAC * 16 +def expected_packet(secureon: bytes = b"") -> bytes: + """Magic packet for EXPECTED_MAC, followed by the optional SecureOn password.""" + if len(secureon) not in (0, 4, 6): + raise ValueError("SecureOn password must be 4 or 6 bytes") + return EXPECTED_PACKET + secureon + + +def parse_secureon(text: str) -> bytes: + value = bytes.fromhex(text.replace(":", "").replace("-", "")) + expected_packet(value) + return value + + def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( @@ -21,21 +39,31 @@ def main() -> int: default=60.0, help="seconds to wait for one datagram (default: 60)", ) + parser.add_argument("--count", type=int, default=3, help="packets expected (default: 3)") + parser.add_argument("--port", type=int, default=PORT, help=f"UDP port on {HOST} (default: {PORT})") + parser.add_argument("--secureon", default="", help="expected SecureOn password as hex (4 or 6 bytes)") args = parser.parse_args() if args.timeout <= 0: parser.error("--timeout must be greater than zero") + if not 1 <= args.count <= 10 or not 1 <= args.port <= 65535: + parser.error("--count must be 1..10 and --port 1..65535") + try: + secureon = parse_secureon(args.secureon) if args.secureon else b"" + except ValueError as error: + parser.error(f"--secureon: {error}") + expected = expected_packet(secureon) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as listener: listener.settimeout(args.timeout) - listener.bind((HOST, PORT)) - print(f"LISTENING {HOST}:{PORT} timeout={args.timeout:g}s", flush=True) + listener.bind((HOST, args.port)) + print(f"LISTENING {HOST}:{args.port} timeout={args.timeout:g}s", flush=True) packets = [] times = [] try: - for _ in range(3): + for _ in range(args.count): packet, peer = listener.recvfrom(2048) - if packet != EXPECTED_PACKET or peer[0] != HOST: - print("FAIL: invalid packet or non-loopback peer", flush=True) + if packet != expected or peer[0] != HOST: + print(f"FAIL: invalid packet ({len(packet)} B) or non-loopback peer", flush=True) return 1 packets.append((packet, peer)) times.append(time.monotonic()) @@ -43,25 +71,26 @@ def main() -> int: try: listener.recvfrom(2048) except TimeoutError: - pass # Exactly the configured three datagrams; no extra packet. + pass # Exactly the configured number of datagrams; no extra packet. else: print("FAIL: unexpected extra WoL packet", flush=True) return 1 except TimeoutError: - print("FAIL: timeout waiting for all three WoL packets", flush=True) + print(f"FAIL: timeout waiting for all {args.count} WoL packets", flush=True) return 1 - print("packet_count=3", flush=True) + print(f"packet_count={args.count}", flush=True) print("interval_ms=" + ",".join(str(round((b-a)*1000,3)) for a,b in zip(times,times[1:])), flush=True) packet, peer = packets[-1] print(f"peer={peer[0]}:{peer[1]}") print(f"length={len(packet)}") - print(f"payload_hex={packet.hex()}") - if packet != EXPECTED_PACKET: - print("FAIL: expected exactly 6*ff + 16*aa:bb:cc:dd:ee:ff (102 bytes)") + # The SecureOn password stays out of the log even in a test: only its length is printed. + print(f"payload_hex={packet[:102].hex()}" + (f"+secureon[{len(secureon)}B]" if secureon else "")) + if packet != expected: + print(f"FAIL: expected exactly 6*ff + 16*aa:bb:cc:dd:ee:ff ({len(expected)} bytes)") return 1 - print("PASS: exact 102-byte WoL packet for AA:BB:CC:DD:EE:FF") + print(f"PASS: exact {len(expected)}-byte WoL packet for AA:BB:CC:DD:EE:FF" + (" with SecureOn" if secureon else "")) return 0 diff --git a/tools/update_terminal_width.py b/tools/update_terminal_width.py new file mode 100644 index 0000000..161506b --- /dev/null +++ b/tools/update_terminal_width.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Regenerate the cell-width tables in TerminalWidth.kt from local Unicode UCD files (no network access). + +Usage: python3 -I tools/update_terminal_width.py EastAsianWidth.txt DerivedGeneralCategory.txt [TerminalWidth.kt] +Download the two files from https://www.unicode.org/Public/UCD/latest/ucd/ (the second one is under +extracted/) and record version, date and SHA-256 in docs/zavislosti.md (terminal section). +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +TARGET = Path(__file__).resolve().parent.parent / "shared/src/commonMain/kotlin/cz/netkit/shared/ssh/TerminalWidth.kt" +WIDE_VALUES = frozenset({"W", "F"}) +ZERO_CATEGORIES = frozenset({"Mn", "Me", "Cf"}) +# Hangul medial vowels and final consonants join the preceding syllable (zero width in wcwidth-style tables). +EXTRA_ZERO = [(0x1160, 0x11FF), (0xD7B0, 0xD7FF)] +# Soft hyphen is Cf but terminals print it with width 1. +NOT_ZERO = (0x00AD,) + +Ranges = list[tuple[int, int]] + + +def parse(text: str, accept: frozenset[str]) -> Ranges: + ranges: Ranges = [] + for raw in text.splitlines(): + line = raw.split("#", 1)[0].strip() + if not line: + continue + codes, value = (part.strip() for part in line.split(";", 1)) + if value not in accept: + continue + start, _, end = codes.partition("..") + ranges.append((int(start, 16), int(end or start, 16))) + return merge(ranges) + + +def merge(ranges: Ranges) -> Ranges: + merged: Ranges = [] + for start, end in sorted(ranges): + if merged and start <= merged[-1][1] + 1: + merged[-1] = (merged[-1][0], max(merged[-1][1], end)) + else: + merged.append((start, end)) + return merged + + +def without(ranges: Ranges, code: int) -> Ranges: + result: Ranges = [] + for start, end in ranges: + if start <= code <= end: + if start < code: + result.append((start, code - 1)) + if code < end: + result.append((code + 1, end)) + else: + result.append((start, end)) + return result + + +def kotlin_table(name: str, ranges: Ranges) -> str: + values = [f"0x{value:X}" for pair in ranges for value in pair] + lines = [" " + ", ".join(values[i:i + 12]) + "," for i in range(0, len(values), 12)] + return f" private val {name} = intArrayOf(\n" + "\n".join(lines) + "\n )\n" + + +def tables(east_asian_width: str, general_category: str) -> str: + wide = parse(east_asian_width, WIDE_VALUES) + zero = merge(parse(general_category, ZERO_CATEGORIES) + EXTRA_ZERO) + for code in NOT_ZERO: + zero = without(zero, code) + return kotlin_table("WIDE", wide) + "\n" + kotlin_table("ZERO", zero) + + +def replace_tables(source: str, generated: str) -> str: + pattern = re.compile(r" private val WIDE = intArrayOf\(.*?\n \)\n\n private val ZERO = intArrayOf\(.*?\n \)\n", re.S) + if len(pattern.findall(source)) != 1: + raise ValueError("TerminalWidth.kt does not contain exactly one WIDE/ZERO table block") + return pattern.sub(lambda _: generated, source) + + +def main(argv: list[str]) -> int: + if len(argv) not in (2, 3): + print(__doc__, file=sys.stderr) + return 2 + east, category = (Path(value).read_text(encoding="utf-8") for value in argv[:2]) + target = Path(argv[2]) if len(argv) == 3 else TARGET + target.write_text(replace_tables(target.read_text(encoding="utf-8"), tables(east, category)), encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:]))