903 Commits

Author SHA1 Message Date
Cooper Quintin
afeda3875d fmt 2026-05-01 14:34:11 -07:00
Cooper Quintin
ced4090be5 appease clippy 2026-05-01 13:43:26 -07:00
Cooper Quintin
1471bb6f0b cargo fmt 2026-05-01 12:34:38 -07:00
Cooper Quintin
ebc0ddb6b3 first pass at false positive removal 2026-05-01 12:31:50 -07:00
Markus Unterwaditzer
3c1a164361 Make WiFi tools optional on the orbic installer too (#1009) 2026-04-27 19:05:40 +02:00
Markus Unterwaditzer
8346f18a5b Fix dependabot config
PR #998 was supposed to filter dependabot PRs to security updates only.
But applies-to was on the wrong level of nesting.

Also renamed the group from "dependency-type" to "security", right now
we get PRs like "Bump the dependency-type group in /installer-gui with 7
updates#1010"

Search for applies-to on this page:
https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference
-- it's on the same level as patterns.

This PR was fully AI-generated, description hand-written though.
2026-04-27 09:16:39 -07:00
John
40070b9339 Add support for WebDAV (#982)
* Add support for WebDAV

* Fix get_unuploaded_entries_with_age to use start_time

* Use better pattern when matching join! result

Co-authored-by: Markus Unterwaditzer <markus-github@unterwaditzer.net>

* Refactor Webdav with better string ownership

* Unformat Cargo.toml

* Add timeout config

* Use a single url config instead of host and path

* QMDL store returns single unuploaded entry at a time

* Reset Cargo.lock

---------

Co-authored-by: Markus Unterwaditzer <markus-github@unterwaditzer.net>
2026-04-26 20:56:23 +02:00
Jack Lund
38b1dd3de2 Move creation of the diag device into read thread
Moved the creation of the DiagDevice into the diag read task thread.
2026-04-26 20:55:59 +02:00
Brad Warren
258fdd9d21 update contributing.md for installer-gui 2026-04-24 12:14:34 -07:00
Markus Unterwaditzer
100d1de04c Remove some global reset styles in favor of explicit border colors, restore button cursors 2026-04-24 11:34:56 -07:00
Markus Unterwaditzer
177262bc1d upgrade tailwind
* moved to vite plugin for tailwind (it's recommended now)
* removed autoprefixer (v4 uses its own CSS thing now)
* postcss.config.js was used to wire up tailwind and autoprefixer, so
  it's gone
* tailwind.config.ts is gone, because v4 stores config in app.css using
  css variables
* fixed some renamed classes
2026-04-24 11:34:56 -07:00
Markus Unterwaditzer
fe69dd1abf downgrade tailwind for now, and fix build errors 2026-04-24 11:34:56 -07:00
dependabot[bot]
d56386a7e5 Bump the dependency-type group across 1 directory with 18 updates
Bumps the dependency-type group with 18 updates in the /daemon/web directory:

| Package | From | To |
| --- | --- | --- |
| [@sveltejs/adapter-auto](https://github.com/sveltejs/kit/tree/HEAD/packages/adapter-auto) | `3.3.1` | `7.0.1` |
| [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) | `2.53.4` | `2.58.0` |
| [@sveltejs/vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte/tree/HEAD/packages/vite-plugin-svelte) | `6.2.1` | `7.0.0` |
| [@types/node](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/node) | `24.7.0` | `25.6.0` |
| [autoprefixer](https://github.com/postcss/autoprefixer) | `10.4.21` | `10.5.0` |
| [eslint](https://github.com/eslint/eslint) | `9.37.0` | `10.2.1` |
| [eslint-config-prettier](https://github.com/prettier/eslint-config-prettier) | `9.1.2` | `10.1.8` |
| [eslint-plugin-svelte](https://github.com/sveltejs/eslint-plugin-svelte/tree/HEAD/packages/eslint-plugin-svelte) | `2.46.1` | `3.17.1` |
| [globals](https://github.com/sindresorhus/globals) | `15.15.0` | `17.5.0` |
| [prettier](https://github.com/prettier/prettier) | `3.6.2` | `3.8.3` |
| [prettier-plugin-svelte](https://github.com/sveltejs/prettier-plugin-svelte) | `3.4.0` | `3.5.1` |
| [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) | `5.53.7` | `5.55.5` |
| [svelte-check](https://github.com/sveltejs/language-tools) | `4.3.2` | `4.4.6` |
| [tailwindcss](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/tailwindcss) | `3.4.18` | `4.2.4` |
| [typescript](https://github.com/microsoft/TypeScript) | `5.9.3` | `6.0.3` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.46.0` | `8.59.0` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `7.3.2` | `8.0.10` |
| [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest) | `3.2.4` | `4.1.5` |



Updates `@sveltejs/adapter-auto` from 3.3.1 to 7.0.1
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/adapter-auto/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/adapter-auto@7.0.1/packages/adapter-auto)

Updates `@sveltejs/kit` from 2.53.4 to 2.58.0
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.58.0/packages/kit)

Updates `@sveltejs/vite-plugin-svelte` from 6.2.1 to 7.0.0
- [Release notes](https://github.com/sveltejs/vite-plugin-svelte/releases)
- [Changelog](https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/vite-plugin-svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/vite-plugin-svelte/commits/@sveltejs/vite-plugin-svelte@7.0.0/packages/vite-plugin-svelte)

Updates `@types/node` from 24.7.0 to 25.6.0
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/node)

Updates `autoprefixer` from 10.4.21 to 10.5.0
- [Release notes](https://github.com/postcss/autoprefixer/releases)
- [Changelog](https://github.com/postcss/autoprefixer/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/autoprefixer/compare/10.4.21...10.5.0)

Updates `eslint` from 9.37.0 to 10.2.1
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/compare/v9.37.0...v10.2.1)

Updates `eslint-config-prettier` from 9.1.2 to 10.1.8
- [Release notes](https://github.com/prettier/eslint-config-prettier/releases)
- [Changelog](https://github.com/prettier/eslint-config-prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/eslint-config-prettier/commits/v10.1.8)

Updates `eslint-plugin-svelte` from 2.46.1 to 3.17.1
- [Release notes](https://github.com/sveltejs/eslint-plugin-svelte/releases)
- [Changelog](https://github.com/sveltejs/eslint-plugin-svelte/blob/main/packages/eslint-plugin-svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/eslint-plugin-svelte/commits/eslint-plugin-svelte@3.17.1/packages/eslint-plugin-svelte)

Updates `globals` from 15.15.0 to 17.5.0
- [Release notes](https://github.com/sindresorhus/globals/releases)
- [Commits](https://github.com/sindresorhus/globals/compare/v15.15.0...v17.5.0)

Updates `prettier` from 3.6.2 to 3.8.3
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.6.2...3.8.3)

Updates `prettier-plugin-svelte` from 3.4.0 to 3.5.1
- [Changelog](https://github.com/sveltejs/prettier-plugin-svelte/blob/v3.5.1/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/prettier-plugin-svelte/commits/v3.5.1)

Updates `svelte` from 5.53.7 to 5.55.5
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.55.5/packages/svelte)

Updates `svelte-check` from 4.3.2 to 4.4.6
- [Release notes](https://github.com/sveltejs/language-tools/releases)
- [Commits](https://github.com/sveltejs/language-tools/compare/svelte-check@4.3.2...svelte-check@4.4.6)

Updates `tailwindcss` from 3.4.18 to 4.2.4
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.2.4/packages/tailwindcss)

Updates `typescript` from 5.9.3 to 6.0.3
- [Release notes](https://github.com/microsoft/TypeScript/releases)
- [Commits](https://github.com/microsoft/TypeScript/compare/v5.9.3...v6.0.3)

Updates `typescript-eslint` from 8.46.0 to 8.59.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.59.0/packages/typescript-eslint)

Updates `vite` from 7.3.2 to 8.0.10
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v8.0.10/packages/vite)

Updates `vitest` from 3.2.4 to 4.1.5
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.5/packages/vitest)

---
updated-dependencies:
- dependency-name: "@sveltejs/adapter-auto"
  dependency-version: 7.0.1
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.57.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: "@sveltejs/vite-plugin-svelte"
  dependency-version: 7.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: "@types/node"
  dependency-version: 25.6.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: autoprefixer
  dependency-version: 10.5.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: eslint
  dependency-version: 10.2.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: eslint-config-prettier
  dependency-version: 10.1.8
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: eslint-plugin-svelte
  dependency-version: 3.17.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: globals
  dependency-version: 17.5.0
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: prettier
  dependency-version: 3.8.3
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: prettier-plugin-svelte
  dependency-version: 3.5.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: svelte
  dependency-version: 5.55.4
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: svelte-check
  dependency-version: 4.4.6
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: tailwindcss
  dependency-version: 4.2.2
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: typescript
  dependency-version: 6.0.2
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: typescript-eslint
  dependency-version: 8.58.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: vite
  dependency-version: 8.0.8
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
- dependency-name: vitest
  dependency-version: 4.1.4
  dependency-type: direct:development
  update-type: version-update:semver-major
  dependency-group: dependency-type
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-24 11:34:56 -07:00
dependabot[bot]
520d2e9a9e Bump postcss from 8.5.6 to 8.5.10 in /daemon/web
Bumps [postcss](https://github.com/postcss/postcss) from 8.5.6 to 8.5.10.
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/8.5.6...8.5.10)

---
updated-dependencies:
- dependency-name: postcss
  dependency-version: 8.5.10
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-24 09:51:33 -07:00
Brad Warren
cf9384c841 set open-pull-requests-limit 2026-04-24 09:39:57 -07:00
Brad Warren
e61802fe1d group dependabot security updates 2026-04-24 09:39:57 -07:00
Markus Unterwaditzer
1c8a498d70 Make WiFi tools optional to build, refactor installer file handling
PR #888 introduced more files that the installer needs to bundle. Those
files in particular are annoying to deal with because now every
developer needs a working C crosscompiler to get the installer working.
This prompted me to do some other refactoring.

Refactor install-dev to not build the wifi tools if there is no
crosscompiler, and refactor the installer so that these files are loaded
at runtime when built in debug mode.

The build script only ever warns if files are missing, and depending on
debug/release mode, the get_file!() macro either panics at runtime or
fails compiling.

Now the installer can be built again without any files, clippy can be
run directly without any envvars, and the installer runs atleast for
devices that don't need those files. The orbic installer will panic at
runtime if the wifi tools haven't been built. Building the installer in
release mode still requires all files.

Another nicety of loading these files on runtime is that the installer
does not need to be recompiled when the daemon has been rebuilt. This
should make things like make.sh really obsolete, which bypass the
installer for speed.
2026-04-24 09:00:19 -07:00
Cooper Quintin
7daacb3b65 Revert "web: target older mobile browsers"
This reverts commit a8aae16fa1.
2026-04-23 09:16:28 -07:00
Cooper Quintin
4a9e9c507b ignore wifi tools builds 2026-04-23 09:16:28 -07:00
DeoJin
a8aae16fa1 web: target older mobile browsers 2026-04-22 12:03:17 -07:00
Ember
5fc6925d35 doc: document Wi-Fi auto-shutdown workaround for TMOHS1 and CT2MHS01 (#951)
Both devices ship with a Wi-Fi Standby timer that turns off the AP
after ~10 minutes with no clients, blocking remote access to Rayhunter
until a power cycle. Previous attempt (this PR's earlier commits) added
a Rayhunter config toggle to flip gWlanAutoShutdown in WCNSS_qcom_cfg.ini,
but the same setting is already exposed in each device's native admin UI
under Settings -> Sleep -> Wi-Fi Standby, so a code change is not needed.

Replace the config toggle with:
- Device-page walkthroughs with screenshots of each native UI setting
- FAQ entry for "can't reach the web UI after leaving it alone"
- Post-install hint from the tmobile/wingtech installers pointing at
  the docs and the setting location
2026-04-22 11:52:33 -07:00
Ember
3455adbf95 client mode added (#888)
* client mode added

* Prevent OTA daemons dmclient and upgrade from running and phoning home to Verizon

* Fix workflow

* WIFI changes to support moxee. May need to rebase as delivering refactoring under other PR.

* code changes for rust based wifi client mode docs next

* Doc changes & security fixes

* Added watchdog and recover if crash occurs for wifi.

* Remove changes which were from device UI work (seperate feature which snuck into this branch)

* Add missing wifi and firewall module declarations

* cleaning up the code a bit

* Gate wpa_suplicant in installer and workflow to avoid building binary every push

* fix to check diskspace

* Improved support for subnet colisions, and attempts to rejoin network.

* Add WiFi client support and S01iptables to T-Mobile and Wingtech installers

Both installers now deploy wpa_supplicant, wpa_cli, udhcpc-hook.sh, and
the S01iptables boot-time firewall script. Config generation uses the
shared install_config/install_wifi_creds helpers instead of manual string
replacement.

* Revert "Add WiFi client support and S01iptables to T-Mobile and Wingtech installers"

This reverts commit 944b369c4f.

* Fix build: ignore unused wifi_ssid/wifi_password fields in T-Mobile and Wingtech installers

* Moved to a wifi crate

* Add host route and arp_filter to prevent subnet collisions

* add wakelock so kernel doesn't shut down wifi on battery when wifi is enabled

* Move wifi to external wifi-station crate, remove wifi from installer, extract OTA blocking

* fixed outdated info, moved udhcpc hook to wifi-station crate.

* Update to new version of wifi-station

* Address PR review feedback: replace Docker wpa build, add iw, remove OTA, revert unrelated changes

- Replace Docker-based wpa_supplicant build with shell script (scripts/build-wpa-supplicant.sh)
- Add iw cross-compilation and deployment to Orbic installer
- Skip wifi tool install if binary already exists on device
- Remove OTA daemon blocker (extracted for separate PR)
- Revert unrelated UZ801 and T-Mobile installer changes
- Remove connection.rs test scaffolding
- Rewrite S01iptables init script to read config.toml directly
- Pin url crate to 2.5.4 to fix MSRV

* Fix build script: use bash for parameter substitution

The ${VAR//pattern/replacement} syntax is a bash extension that
doesn't work in dash (Ubuntu's /bin/sh).

* Fix iw build: export PKG_CONFIG_LIBDIR as env var

Passing PKG_CONFIG_LIBDIR as a make variable doesn't export it to
$(shell pkg-config ...) calls. Set it as an environment variable
so pkg-config finds the cross-compiled libnl.

* Point wifi-station to GitHub rev 97c579a

* add comment

* Update daemon/src/config.rs

Add decorators

Co-authored-by: Andrej Walilko <walilkoa@gmail.com>

* Update daemon/src/server.rs

add utopia doc support

Co-authored-by: Andrej Walilko <walilkoa@gmail.com>

* Update daemon/src/server.rs

add utopia doc support

Co-authored-by: Andrej Walilko <walilkoa@gmail.com>

* Update to wifi-station with utoipa doc strings

* add utoipa to wifi-station

* added WPA3 support

* fix firewall port detection, update wifi-station to c267d37

fix ntfy port_or_known_default, comment out ntfy_url in config
template, update wifi-station with resolv.conf bind mount
fallback, udhcpc_bin config, and module path fix for UZ801

* show wifi UI for tmobile and wingtech, add udhcpc_bin config

both devices have wifi hardware and backend support. wingtech
verified on hardware (QCA6174 via PCIe). uz801 excluded for now
due to driver scan limitations with hostapd active.

* install wifi tools from orbic-usb installer, fix DNS default to Quad9, bump wifi-station rev

* fix Modal scroll listener leak, correct file transfer timeout math, document firewall fail-open, clarify UZ801 wifi status

* build-dev.sh: build wifi tools so install-dev works for orbic-family devices

* update Cargo.lock for wifi-station e8ec5b4

* fix setup_timeout_server crypto provider install, apply rustfmt

* Update installer/src/connection.rs

Co-authored-by: Cooper Quintin <cooperq@users.noreply.github.com>

* Update installer/src/orbic.rs

Co-authored-by: Cooper Quintin <cooperq@users.noreply.github.com>

* apply rustfmt to AdbConnection::run_command

---------

Co-authored-by: Andrej Walilko <walilkoa@gmail.com>
Co-authored-by: Cooper Quintin <cooperq@users.noreply.github.com>
2026-04-22 10:02:48 -07:00
dependabot[bot]
416f03159a Bump the dependency-type group in /installer-gui with 3 updates
Bumps the dependency-type group in /installer-gui with 3 updates: [eslint](https://github.com/eslint/eslint), [typescript](https://github.com/microsoft/TypeScript) and [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite).


Updates `eslint` from 10.2.0 to 10.2.1
- [Release notes](https://github.com/eslint/eslint/releases)
- [Commits](https://github.com/eslint/eslint/compare/v10.2.0...v10.2.1)

Updates `typescript` from 6.0.2 to 6.0.3
- [Release notes](https://github.com/microsoft/TypeScript/releases)
- [Commits](https://github.com/microsoft/TypeScript/compare/v6.0.2...v6.0.3)

Updates `vite` from 8.0.8 to 8.0.9
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v8.0.9/packages/vite)

---
updated-dependencies:
- dependency-name: eslint
  dependency-version: 10.2.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependency-type
- dependency-name: typescript
  dependency-version: 6.0.3
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependency-type
- dependency-name: vite
  dependency-version: 8.0.9
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: dependency-type
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-20 09:43:15 -07:00
Brad Warren
bf08066c58 run cargo update tauri --precise 2.10.3 2026-04-16 12:59:04 -07:00
dependabot[bot]
d5f01847fc Bump the dependency-type group in /installer-gui with 18 updates
Dependabot couldn't find the original pull request head commit, ecdd7baeae.
2026-04-16 12:59:04 -07:00
Markus Unterwaditzer
ca30a146b2 Fix clippy for Rust 1.95 2026-04-16 12:31:08 -07:00
Markus Unterwaditzer
a1a29b5ec8 Upgrade rustls-webpki to fix CVE
We have two versions of rustls-webpki in our deptree:

- One used in the ring backend, which we're upgrading here
- One used in the rustcrypto backend, which we can't upgrade and
  therefore have to ignore the CVE anyway.

The ring backend is the one we actually use in release builds.
rustcrypto is only used during development builds to make compilation
simpler.
2026-04-16 10:13:53 -07:00
Markus Unterwaditzer
dc1d193b8e Move from ring to aws-lc-rs
There is some recent progress on quantum computers being discussed on
HackerNews and lobste.rs, and as a result of that timelines for when PQ
crypto would become essentially mandatory are being adjusted. Example:
https://words.filippo.io/crqc-timeline/

We pretty much have only one place in this entire codebase where any
sort of crypto happens, which is HTTPS for notifications support.

It seems that ring has essentially no plans to support PQ crypto for our
purposes. rustls/rustls#2801 briansmith/ring#1685

There's not really a reason to stick with ring, other than that it is a
prod-ready backend. But so is aws-lc-rs, and it seems to be the way
forward if you want PQ crypto today. Maybe that will change again in a
few years.

**The local dev workflow stays the same**, `cargo
build-daemon-firmware-devel` still uses rustcrypto which doesn't require
CC and doesn't have PQ crypto at all. We have no contribution docs for
how to build anything else anyway.

**Implementation:**

This opens a can of worms in building rayhunter-daemon in CI: We're
currently building ring using GCC cross-compilation toolchain from
Debian, which will build ring against **glibc**. Then we take that
library and try to link it against MUSL libc. The reason this works is
because ring's libc usage is very minimal, and the required symbols end
up being just the same as what MUSL libc exposes. The same can't be said
for aws-lc:

```
error: linking with `rust-lld` failed: exit status: 1
    = note: rust-lld: error: undefined symbol: __nanosleep64
            >>> referenced by urandom.c
            >>>               urandom.c.o:(do_backoff) in archive
```

So we fix that and link everything we build against MUSL libc (something
we should've done from the start anyway). The problem is that Debian
doesn't ship a MUSL cross-compilation toolchain, and the toolchain
available on https://musl.cc should not be downloaded directly in CI.
Which leaves us with a docker container from messense... That docker
container seems to be extremely popular for cross compilation across
GitHub projects, at least. I couldn't get other options to run reliably
(cross), or they were a too extreme change for my taste (using zig cc)
2026-04-16 10:12:24 -07:00
dependabot[bot]
11608427bb Bump the dependency-type group in /tools with 4 updates
Bumps the dependency-type group in /tools with 4 updates: [asn1tools](https://github.com/eerimoq/asn1tools), [bitstruct](https://github.com/eerimoq/bitstruct), [pycrate](https://github.com/pycrate-org/pycrate) and [pyparsing](https://github.com/pyparsing/pyparsing).


Updates `asn1tools` from 0.166.0 to 0.167.0
- [Release notes](https://github.com/eerimoq/asn1tools/releases)
- [Commits](https://github.com/eerimoq/asn1tools/compare/0.166.0...0.167.0)

Updates `bitstruct` from 8.19.0 to 8.22.1
- [Commits](https://github.com/eerimoq/bitstruct/compare/8.19.0...8.22.1)

Updates `pycrate` from 0.7.8 to 0.7.11
- [Release notes](https://github.com/pycrate-org/pycrate/releases)
- [Commits](https://github.com/pycrate-org/pycrate/compare/0.7.8...0.7.11)

Updates `pyparsing` from 3.1.2 to 3.3.2
- [Release notes](https://github.com/pyparsing/pyparsing/releases)
- [Changelog](https://github.com/pyparsing/pyparsing/blob/master/CHANGES)
- [Commits](https://github.com/pyparsing/pyparsing/compare/pyparsing_3.1.2...3.3.2)

---
updated-dependencies:
- dependency-name: asn1tools
  dependency-version: 0.167.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: bitstruct
  dependency-version: 8.22.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependency-type
- dependency-name: pycrate
  dependency-version: 0.7.11
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: dependency-type
- dependency-name: pyparsing
  dependency-version: 3.3.2
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: dependency-type
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-15 11:16:12 -07:00
Markus Unterwaditzer
1bab75830b Use grouped dependabot updates
When there is a CVE in some JS package, it seems to coincide with an
avalanche of security releases of random other packages.

Dependabot can actually create bulk PRs, let's try those.
2026-04-15 20:12:37 +02:00
Markus Unterwaditzer
853ad3763c apply suggestions from code review (github UI is broken) 2026-04-15 10:58:17 -07:00
Markus Unterwaditzer
059a5028d1 Update doc/porting.md
Co-authored-by: Cooper Quintin <cooperq@users.noreply.github.com>
2026-04-15 10:58:17 -07:00
Ember
c1270cc3e9 Suggested edits 2026-04-15 10:58:17 -07:00
Markus Unterwaditzer
e935904204 Add docs for porting to new devices 2026-04-15 10:58:17 -07:00
Cooper Quintin
87975181c1 Update CONTRIBUTING.md
Co-authored-by: Markus Unterwaditzer <markus-tarpit+git@unterwaditzer.net>
2026-04-15 10:57:34 -07:00
Cooper Quintin
c2d8d55296 limit PR to 400 LOC 2026-04-15 10:57:34 -07:00
Jack Lund
188bf812b4 Add notification timeout
Adds a default timeout of 10 seconds for sending notifications so they
don't hang indefinitely. This can happen if the server connected to is
not responding or the case where there's a SIM card in the device, but
it's unactivated so that DNS works but the connection doesn't
2026-04-13 18:17:42 +02:00
dependabot[bot]
ccd96de5cc Bump vite from 6.4.1 to 6.4.2 in /installer-gui
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 6.4.1 to 6.4.2.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v6.4.2/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v6.4.2/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 6.4.2
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-06 15:41:18 -07:00
dependabot[bot]
a3072a2632 Bump vite from 7.1.11 to 7.3.2 in /daemon/web
Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 7.1.11 to 7.3.2.
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/v7.3.2/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v7.3.2/packages/vite)

---
updated-dependencies:
- dependency-name: vite
  dependency-version: 7.3.2
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-04-07 00:14:54 +02:00
Markus Unterwaditzer
0580a8af33 Revise moxee warning
Ref #865

I think we should still make it clear the Orbic is a better device, but
there's not really any danger anymore.
2026-03-30 15:12:12 -07:00
Markus Unterwaditzer
a80a985b40 Fix wrong docs on key input
We explain in the docs what this key input mode actually does, but it is
named poorly.

ref #952.
2026-03-30 15:11:45 -07:00
Markus Unterwaditzer
228596ef30 Bump tower to 0.5.3
There are no important changes in the new tower version. The only reason
i'm bumping it is because it exposes our mis-configuration of tokio: We
depend on API surface enabled by `io-std`, but don't enable that
feature. Tower 0.5.2 pulls in that feature though, and our code works
anyway. Tower 0.5.3 no longer requires this feature and our code stops
compiling.
2026-03-30 15:10:59 -07:00
Markus Unterwaditzer
a7409b281b Move config form to modal
It's pretty annoying to have to scroll past all the old recordings to
be able to set the config. Since logs we already have figured out how to
create modals, so let's reuse that code.
2026-03-30 15:10:12 -07:00
dependabot[bot]
6a57bdebc4 Bump picomatch from 2.3.1 to 2.3.2 in /installer-gui
Bumps [picomatch](https://github.com/micromatch/picomatch) from 2.3.1 to 2.3.2.
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

---
updated-dependencies:
- dependency-name: picomatch
  dependency-version: 2.3.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-26 14:14:11 +01:00
dependabot[bot]
7cb405c465 Bump picomatch from 2.3.1 to 2.3.2 in /daemon/web
Bumps [picomatch](https://github.com/micromatch/picomatch) from 2.3.1 to 2.3.2.
- [Release notes](https://github.com/micromatch/picomatch/releases)
- [Changelog](https://github.com/micromatch/picomatch/blob/master/CHANGELOG.md)
- [Commits](https://github.com/micromatch/picomatch/compare/2.3.1...2.3.2)

---
updated-dependencies:
- dependency-name: picomatch
  dependency-version: 2.3.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-26 14:14:09 +01:00
Ember
bada3846dc Get rid of the 'verify' which is flakey 2026-03-26 11:44:23 +01:00
Ember
f0849340cf Improve Moxee/orbic Wingtech/tmobile installers for network stability 2026-03-26 11:44:23 +01:00
Terence
512cf784a7 provide additional info to help users set up for frontend dev environment (#917) 2026-03-25 20:09:24 +01:00
dependabot[bot]
100960bbe1 Bump flatted from 3.3.3 to 3.4.2 in /installer-gui
Bumps [flatted](https://github.com/WebReflection/flatted) from 3.3.3 to 3.4.2.
- [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2)

---
updated-dependencies:
- dependency-name: flatted
  dependency-version: 3.4.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-22 14:03:42 +01:00
dependabot[bot]
9d275e1793 Bump flatted from 3.3.3 to 3.4.2 in /daemon/web
Bumps [flatted](https://github.com/WebReflection/flatted) from 3.3.3 to 3.4.2.
- [Commits](https://github.com/WebReflection/flatted/compare/v3.3.3...v3.4.2)

---
updated-dependencies:
- dependency-name: flatted
  dependency-version: 3.4.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-22 13:08:45 +01:00
dependabot[bot]
fd190c4b75 Bump quinn-proto from 0.11.12 to 0.11.14
Bumps [quinn-proto](https://github.com/quinn-rs/quinn) from 0.11.12 to 0.11.14.
- [Release notes](https://github.com/quinn-rs/quinn/releases)
- [Commits](https://github.com/quinn-rs/quinn/compare/quinn-proto-0.11.12...quinn-proto-0.11.14)

---
updated-dependencies:
- dependency-name: quinn-proto
  dependency-version: 0.11.14
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-16 15:55:12 +01:00
dependabot[bot]
ff838c41fa Bump devalue from 5.6.3 to 5.6.4 in /daemon/web
Bumps [devalue](https://github.com/sveltejs/devalue) from 5.6.3 to 5.6.4.
- [Release notes](https://github.com/sveltejs/devalue/releases)
- [Changelog](https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/devalue/compare/v5.6.3...v5.6.4)

---
updated-dependencies:
- dependency-name: devalue
  dependency-version: 5.6.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-12 11:25:27 -07:00
dependabot[bot]
a031e8ccfc Bump devalue from 5.6.3 to 5.6.4 in /installer-gui
Bumps [devalue](https://github.com/sveltejs/devalue) from 5.6.3 to 5.6.4.
- [Release notes](https://github.com/sveltejs/devalue/releases)
- [Changelog](https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/devalue/compare/v5.6.3...v5.6.4)

---
updated-dependencies:
- dependency-name: devalue
  dependency-version: 5.6.4
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-12 11:13:04 -07:00
Brad Warren
a6f5faa80e wrap report in $derived 2026-03-04 15:44:35 -08:00
dependabot[bot]
43f1dfce64 Bump svelte from 5.39.10 to 5.53.6 in /daemon/web
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 5.39.10 to 5.53.6.
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.53.6/packages/svelte)

---
updated-dependencies:
- dependency-name: svelte
  dependency-version: 5.53.6
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-04 15:44:35 -08:00
dependabot[bot]
54adaf913d Bump @sveltejs/kit from 2.49.5 to 2.53.0 in /daemon/web
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.49.5 to 2.53.0.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.53.0/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.53.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-03 15:29:21 -08:00
dependabot[bot]
ab418ecc84 Bump devalue from 5.6.2 to 5.6.3 in /daemon/web
Bumps [devalue](https://github.com/sveltejs/devalue) from 5.6.2 to 5.6.3.
- [Release notes](https://github.com/sveltejs/devalue/releases)
- [Changelog](https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/devalue/compare/v5.6.2...v5.6.3)

---
updated-dependencies:
- dependency-name: devalue
  dependency-version: 5.6.3
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-03 15:25:20 -08:00
dependabot[bot]
2fd028dc78 Bump rollup from 4.52.4 to 4.59.0 in /daemon/web
Bumps [rollup](https://github.com/rollup/rollup) from 4.52.4 to 4.59.0.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v4.52.4...v4.59.0)

---
updated-dependencies:
- dependency-name: rollup
  dependency-version: 4.59.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-03 15:21:42 -08:00
dependabot[bot]
d413840c08 Bump minimatch in /daemon/web
Bumps  and [minimatch](https://github.com/isaacs/minimatch). These dependencies needed to be updated together.

Updates `minimatch` from 3.1.2 to 3.1.5
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5)

Updates `minimatch` from 9.0.5 to 9.0.9
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 3.1.5
  dependency-type: indirect
- dependency-name: minimatch
  dependency-version: 9.0.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-03 15:20:51 -08:00
Markus Unterwaditzer
2f1b583e00 orbic-network: Disable connection pooling
Every once in a while, I get the error posted in #901:

    Caused by:
        0: Failed to send login request
        1: error sending request
        2: client error (SendRequest)
        3: connection closed before message completed

(either this or "failed to start telnet" -- in either case there's a
request happening before it, and it's always "connection closed before
message completed")

Disabling connection pooling seems to reduce the amount of flakiness.

Here is what I used to test this fix:

    while echo | cargo run -p installer util orbic-shell --admin-password 96df5476 ; do true; done

Usually it would stop <100 iterations, now it can do 800+ iterations.
2026-03-03 10:59:42 -08:00
dependabot[bot]
adeeb75166 Bump minimatch in /installer-gui
Bumps  and [minimatch](https://github.com/isaacs/minimatch). These dependencies needed to be updated together.

Updates `minimatch` from 3.1.2 to 3.1.5
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5)

Updates `minimatch` from 9.0.5 to 9.0.9
- [Changelog](https://github.com/isaacs/minimatch/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/minimatch/compare/v3.1.2...v3.1.5)

---
updated-dependencies:
- dependency-name: minimatch
  dependency-version: 3.1.5
  dependency-type: indirect
- dependency-name: minimatch
  dependency-version: 9.0.9
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-02 12:07:03 -08:00
dependabot[bot]
4ca23f37c3 Bump rollup from 4.52.5 to 4.59.0 in /installer-gui
Bumps [rollup](https://github.com/rollup/rollup) from 4.52.5 to 4.59.0.
- [Release notes](https://github.com/rollup/rollup/releases)
- [Changelog](https://github.com/rollup/rollup/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rollup/rollup/compare/v4.52.5...v4.59.0)

---
updated-dependencies:
- dependency-name: rollup
  dependency-version: 4.59.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-02 12:06:24 -08:00
dependabot[bot]
15b80ecdd5 Bump svelte from 5.53.0 to 5.53.6 in /installer-gui
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 5.53.0 to 5.53.6.
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.53.6/packages/svelte)

---
updated-dependencies:
- dependency-name: svelte
  dependency-version: 5.53.6
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-03-02 12:03:39 -08:00
Lawrence Kwan
c5de9b045a fix: fix typo in connection error message
Change 'do loss' to 'due to loss' in the connection error message.

Fixes #864
2026-02-26 14:19:09 -08:00
oopsbagel
37283deddb CONTRIBUTING: add genai policy with links 2026-02-24 14:45:28 -08:00
oopsbagel
49d7bbca34 pr templates: add checkboxes for our genai policy
This commit introduces checkboxes where users can certify that either
they did not use generative AI to create their pull request, or that
they did but they understand the code and wrote all comments and
descriptions themselves, per our recently publicised open source policy.
2026-02-24 14:45:28 -08:00
Will Greenberg
a4c32f49ae also bump installer-guis version 2026-02-24 14:25:45 -08:00
Will Greenberg
ec30a9557c bump to v10.2 2026-02-24 14:19:08 -08:00
Markus Unterwaditzer
a7d38730f5 fix botched rebase 2026-02-24 13:42:31 -08:00
Markus Unterwaditzer
d9facdf6cb add one missing single quote 2026-02-24 13:42:31 -08:00
Markus Unterwaditzer
90f49f73c8 slightly better escaping for user input 2026-02-24 13:42:31 -08:00
Markus Unterwaditzer
8aa45f4b53 better errorhandling 2026-02-24 13:42:31 -08:00
Markus Unterwaditzer
d8da6118da Update installer/src/lib.rs
Co-authored-by: Will Greenberg <willg@eff.org>
2026-02-24 13:42:31 -08:00
Markus Unterwaditzer
3e38f500a9 Install to /cache/rayhunter-data for tplink, add --data-dir parameter
This fixes several space-related issues at once.

We have observed the following phenomenon on TP-Link, Orbic and Moxee:

- Filling /data bricks the device (broken wifi, broken rndis, broken
  display)

- Filling /cache does not (it only bricks rayhunter if it's installed
  there, and it might break firmware updates)

Therefore it would make sense to store the entire rayhunter installation
in /cache.

This is a great idea for TP-Link and Moxee, because /cache is
significantly larger than /data. However, on Orbic, /data is
significantly larger than /cache!

This PR refactors orbic-network and tplink to use a shared codepath for
setting up the data directory. A symlink is created at /data/rayhunter,
and what it points to is device-specific:

- Orbic will have its data at `/data/rayhunter-data`

- There is a new alias `installer moxee` that overrides this to
  `/cache/rayhunter-data`

- TP-Link will have its data at /cache/rayhunter-data when there's no SD
  card, and /media/whatever when there is one.

In all cases, existing data is migrated to the new location. The user
can switch back and forth between two values of --data-dir and the data
will be moved over every time.

This PR has one huge wart, and that is that the USB installer for Orbic
remains untouched. The annoying reason for this is that the
DeviceConnection trait is insufficient to reflect all the different
kinds of shells you can have over USB: adb with fakeroot, and serial
with real root. I think it's not possible to create the right
directories with 'rootshell -c'.

I'm thinking of spawning a telnet server over serial, so that we can
just do telnet again, but this is for another time.
2026-02-24 13:42:31 -08:00
dependabot[bot]
83664e23f2 Bump @sveltejs/kit from 2.50.1 to 2.53.0 in /installer-gui
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.50.1 to 2.53.0.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.53.0/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.53.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-23 16:41:36 -08:00
dependabot[bot]
44c7f31fec Bump svelte from 5.43.2 to 5.53.0 in /installer-gui
Bumps [svelte](https://github.com/sveltejs/svelte/tree/HEAD/packages/svelte) from 5.43.2 to 5.53.0.
- [Release notes](https://github.com/sveltejs/svelte/releases)
- [Changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/svelte/commits/svelte@5.53.0/packages/svelte)

---
updated-dependencies:
- dependency-name: svelte
  dependency-version: 5.53.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-23 16:41:10 -08:00
Markus Unterwaditzer
301107be6c add context to background nc 2026-02-23 11:18:47 -08:00
Markus Unterwaditzer
7b97ffc01d raise error for timeout 2026-02-23 11:18:47 -08:00
Markus Unterwaditzer
b72712faa2 error case 2026-02-23 11:18:47 -08:00
Markus Unterwaditzer
05fdc0eee2 do not use debug_assert 2026-02-23 11:18:47 -08:00
Markus Unterwaditzer
8fb27b08f9 Fix telnet_send_command_with_output returning the input
telnet_send_command_with_output returns output with the original command
contained. This leads to higher-level bugs. Fix #894

Also, change telnet_send_command_with_output to not return any "exit
code" related output. This is now only part of telnet_send_command,
which means this output does not leak into users of the DeviceConnection
trait.
2026-02-23 11:18:47 -08:00
Matthew Martin
062db87572 Use Vec::with_capacity (#891)
Co-authored-by: Matthew Martin <phy1729@Matthews-Mac-mini.local>
2026-02-17 18:55:34 +01:00
Andrej Walilko
9b6c4cee0b api documentation (#876)
* api documentation

* utoipa openapi docs generator

---------

Co-authored-by: Andrej Walilko <awalilko@liquidweb.com>
2026-02-17 01:41:15 +01:00
Jake P
9d50db40b9 docs: add note about insecure download (#883)
* docs: add note about insecure download

* Apply suggestion from @untitaker

---------

Co-authored-by: Markus Unterwaditzer <markus-github@unterwaditzer.net>
2026-02-15 16:50:16 +01:00
Ember
d41c4bba3e messages could be larger than 1MB when 100 messages are combined, changed to every 256KB space is checked. 2026-02-12 18:06:42 -08:00
Ember
1d5ed54033 deduplicated code a bit with a wrapper 2026-02-12 18:06:42 -08:00
Ember
24e79aad9d Handled suggestions from PR. 2026-02-12 18:06:42 -08:00
Ember
bc7dcc97c6 Removed redundant annotations inlined the defaults 2026-02-12 18:06:42 -08:00
Ember
480b6f8681 Add visual for GUI; fix clippy issue. 2026-02-12 18:06:42 -08:00
Ember
0c624c2bc2 Add disk space monitoring to recording lifecycle 2026-02-12 18:06:42 -08:00
Ember
ec6967e2a1 Revert silent IPC error drop, restore expect per review 2026-02-12 09:23:13 -08:00
Ember
912f7dfeaa Disable autocorrect/autocapitalize on CLI args input 2026-02-12 09:23:13 -08:00
Ember
51f1a33e86 Update Cargo.lock for shlex dependency 2026-02-12 09:23:13 -08:00
Ember
87c79bddf7 Input validation fix, along with changing expect so it won't crash 2026-02-12 09:23:13 -08:00
TERR-inss
5efa12f358 fix conditional rendering and conditional text logic, use more-stable faq url 2026-02-12 13:00:36 +01:00
TERR-inss
e77fe469da add direct link to FAQ in web UI where rayhunter log analysis returns warnings 2026-02-12 13:00:36 +01:00
Markus Unterwaditzer
ed8b1903f8 Re-add API_TARGET envvar 2026-02-10 17:06:20 -08:00
Markus Unterwaditzer
89d1d71ec9 Improve the default of FIRMWARE_DEVEL again, fix brew install gcc command 2026-02-10 17:06:20 -08:00
Markus Unterwaditzer
9be35de90e Address review feedback 2026-02-10 17:06:20 -08:00
Markus Unterwaditzer
8f9be746d3 Trim down documentation and script verbosity 2026-02-10 17:06:20 -08:00
BeigeBox
1347e3107a Support for admin pass 2026-02-10 17:06:20 -08:00
BeigeBox
715efc4b0d Basic scripts to build from source and run install. Nothing fancy. 2026-02-10 17:06:20 -08:00
Markus Unterwaditzer
836ec2169d Revamp installing-from-source docs 2026-02-10 17:06:20 -08:00
Markus Unterwaditzer
9128eefcfc advise against upgrading and add some dramatic styling to this 2026-02-10 17:06:00 -08:00
Markus Unterwaditzer
4f3c7fb7a9 Add warning to moxee page
see #865
2026-02-10 17:06:00 -08:00
BeigeBox
2d3824072d Added check if retcode was 201 when getting the login_response, and giving an error that says it's the pw 2026-02-08 15:08:14 +01:00
Cooper Quintin
ed2781a4be appease clippy 2026-02-05 15:41:54 -08:00
Cooper Quintin
ffcf683ae5 appease npm 2026-02-05 15:41:54 -08:00
Cooper Quintin
49fd777c83 fix nits and add to config.toml 2026-02-05 15:41:54 -08:00
Cooper Quintin
84a3155a1f remove broken attach request and format 2026-02-05 15:41:54 -08:00
Cooper Quintin
184f4bd7a2 rename to diagnostic and add docs 2026-02-05 15:41:54 -08:00
Cooper Quintin
f7759721e3 rebase against main 2026-02-05 15:41:54 -08:00
Cooper Quintin
744d0772c2 add message type 2026-02-05 15:41:54 -08:00
Cooper Quintin
2cd49b3757 show false postive attach reject message 2026-02-05 15:41:54 -08:00
Cooper Quintin
e44230c043 imsi revealing message diagnostic heuristic 2026-02-05 15:41:54 -08:00
Cooper Quintin
e27da68b5d bump version to 0.10.1 2026-02-05 12:27:09 -08:00
Markus Unterwaditzer
2a68c99897 Revert "Add warning about default routes"
This reverts commit 9ae1563286.

Reverts #804
Reverts #830

Reopens #345
2026-02-05 12:21:07 -08:00
dependabot[bot]
987d95c23e Bump rsa from 0.9.8 to 0.9.10 (#853)
Bumps [rsa](https://github.com/RustCrypto/RSA) from 0.9.8 to 0.9.10.
- [Changelog](https://github.com/RustCrypto/RSA/blob/v0.9.10/CHANGELOG.md)
- [Commits](https://github.com/RustCrypto/RSA/compare/v0.9.8...v0.9.10)

---
updated-dependencies:
- dependency-name: rsa
  dependency-version: 0.9.10
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-05 21:06:41 +01:00
dependabot[bot]
9ef6b43dac Bump time from 0.3.41 to 0.3.47
Bumps [time](https://github.com/time-rs/time) from 0.3.41 to 0.3.47.
- [Release notes](https://github.com/time-rs/time/releases)
- [Changelog](https://github.com/time-rs/time/blob/main/CHANGELOG.md)
- [Commits](https://github.com/time-rs/time/compare/v0.3.41...v0.3.47)

---
updated-dependencies:
- dependency-name: time
  dependency-version: 0.3.47
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-05 10:45:54 -08:00
Cooper Quintin
ffc42f6ffd bump version to 0.10.0 2026-02-04 13:42:38 -08:00
Markus Unterwaditzer
2781b3c7ed Remove wrong timestamp correction from diag 2026-02-04 13:36:46 -08:00
Markus Unterwaditzer
fd63210bf9 Fix prettier lint 2026-02-04 13:36:46 -08:00
Markus Unterwaditzer
a271c4ddf4 Update wording in the clock sync UI (apply suggestions from code review)
Co-authored-by: Will Greenberg <willg@eff.org>
2026-02-04 13:36:46 -08:00
Markus Unterwaditzer
bef6b51e28 Add button to set current time
When there is a significant difference between the user's browser's time
and the system time, a button appears in the web UI to fix the system
time. This time will then be used to correct both data inside of PCAPs
and any metadata.

We don't actually set the system time to this value. Instead, rayhunter
adjusts any timestamps it handles by an offset. That offset defaults to
zero, and the user adjusts it by hitting the button in the web UI. The
main reason for this is device portability.

I haven't investigated whether it would actually be easy to set the real
system time. It's possible that it works the same way across all
devices.
2026-02-04 13:36:46 -08:00
Markus Unterwaditzer
781d07230c Correct FAQ entries to refer to correct shell
The orbic now has many different shells, crosslink to the docs on shells
to find the right one.

Fix #753
Ref https://github.com/EFForg/rayhunter/discussions/842
2026-02-04 10:57:22 -08:00
Markus Unterwaditzer
1f171521e4 Filter out asn1_codecs warnings in rayhunter-daemon
...and make a small UI change so that folks won't get concerned about parsing errors.

Right now all the "undecoded extensions" noise goes into
rayhunter-daemon.log, and users get concerned about it when browsing
that through the UI.
2026-02-04 10:55:54 -08:00
Harrison Marley
5b2cf3cec4 Mention Vodafone Pocket Wifi 5 availability
Added information about 'Vodafone Pocket Wifi 5' availability in Australia.
2026-02-04 10:55:39 -08:00
Cooper Quintin
62e8d4c40f appease untitaker 2026-02-04 10:54:23 -08:00
Cooper Quintin
72c19e0f04 update docs and version 2026-02-04 10:54:23 -08:00
Cooper Quintin
9b52f46c1a appease clippy 2026-02-04 10:54:23 -08:00
Cooper Quintin
51d4e86b3a cargo fmt 2026-02-04 10:54:23 -08:00
Cooper Quintin
33fafd4707 report lack of LTE neighbors 2026-02-04 10:54:23 -08:00
Cooper Quintin
6e4cbac4b1 convert int to option 2026-02-04 10:54:23 -08:00
Cooper Quintin
b453c92d6a Update lib/src/analysis/priority_2g_downgrade.rs
Co-authored-by: Will Greenberg <willg@eff.org>
2026-02-04 10:54:23 -08:00
Cooper Quintin
733c8b227d Update lib/src/analysis/analyzer.rs
Co-authored-by: Will Greenberg <willg@eff.org>
2026-02-04 10:54:23 -08:00
Markus Unterwaditzer
b43217ef35 Fix compilation errors 2026-02-04 10:54:23 -08:00
Cooper Quintin
40a0dec361 appease clippy 2026-02-04 10:54:23 -08:00
Cooper Quintin
b2d5ed356f cargo fmt 2026-02-04 10:54:23 -08:00
Cooper Quintin
6033757ddb compare gsm and 3g priorities to LTE priorities and only alert if higher priority or only non LTE neighbors exist 2026-02-04 10:54:23 -08:00
dependabot[bot]
6b4f98183e Bump bytes from 1.10.1 to 1.11.1 (#847)
Bumps [bytes](https://github.com/tokio-rs/bytes) from 1.10.1 to 1.11.1.
- [Release notes](https://github.com/tokio-rs/bytes/releases)
- [Changelog](https://github.com/tokio-rs/bytes/blob/master/CHANGELOG.md)
- [Commits](https://github.com/tokio-rs/bytes/compare/v1.10.1...v1.11.1)

---
updated-dependencies:
- dependency-name: bytes
  dependency-version: 1.11.1
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-02-03 20:38:53 +01:00
kmille
bd2329d6cc Show tracking area code for test heuristic in UI (#843) 2026-02-03 10:59:15 +01:00
Michael S.
d1311e0ba3 Docs: Add note about non-default credentials to install instructions and modify link target (#839) 2026-02-02 11:44:20 +01:00
Markus Unterwaditzer
75cf03d638 Fix rayhunter chugging on when diag device failed to initialize
Ref #676 -- this is a partial fix for one of the issues mentioned there.

I expect that as a result we'll get more bugreports about rayhunter not
starting, since right now those errors are "masked" by this bug.
2026-02-01 20:32:40 +01:00
Markus Unterwaditzer
be15035ad4 Use /proc/net/route instead of ip route command
Fix #811, allegedly /proc/net/route is almost always available, and no
additional dependency is needed at all.
2026-01-30 12:16:32 -08:00
Markus Unterwaditzer
a3d0d8f4f9 Better support for firmware-devel profile
Currently you have to override a bunch of paths to use firmware-devel
when building the installer. This changes that, and adds a new
FIRMWARE_PROFILE envvar that can be used to fix both rootshell and
rayhunter-daemon paths at the same time.

There is now also a new cargo command for building rootshell, similar to
how building the daemon firmware works.

I'm not sure what to do with make.sh. I have personally never used it.
2026-01-30 21:09:12 +01:00
Markus Unterwaditzer
2c30218743 Add donation button to UI 2026-01-30 10:14:57 -08:00
Markus Unterwaditzer
eb65214989 Add FAQ to issue templates 2026-01-30 10:14:57 -08:00
Markus Unterwaditzer
8d86aeb591 Restructure docs, make FAQ more prominent 2026-01-30 10:14:57 -08:00
Markus Unterwaditzer
23cef7349e Upgrade num-bigint-dig
This dependency is causing warnings during compilation, vieable with `cargo report future-incompatibilities --id 1`
2026-01-29 20:03:22 +01:00
Markus Unterwaditzer
07e0115192 Add disclaimer about flickering 2026-01-29 20:02:09 +01:00
Markus Unterwaditzer
82b53c6187 Display: Implement High Vis Mode
Work around #722 (we should probably still fix it properly)
Fix #779
2026-01-29 20:02:09 +01:00
Markus Unterwaditzer
883175aa59 Disable blank issues again
There are too many questions in the issue tracker recently.
2026-01-29 11:01:46 -08:00
Brad Warren
bd52718ea7 add {daemon,rootshell}_needed GHA outputs 2026-01-28 15:31:27 -08:00
Markus Unterwaditzer
d607c63cc8 Do not overwrite configs by default
On tplink and orbic, do not overwrite config files by default. There is
a new flag `installer orbic --reset-config` that one can use to restore
the old behavior. This fixes #778, a long-standing issue existent since
0.3.0.

The businesslogic for config file overrides is shared to some degree.
The Install trait from pinephone.rs has been moved out and renamed to
DeviceConnection for that purpose, so that `install_config` can be
shared across installers, which in turn can delegate to the trait for
running commands and copying files. This also works towards #542.

However, the pinephone and other installers have not been adapted to
support --reset-config out of fear of regressions. A future refactor by
somebody with ability to test on pinephone should probably also consider
using the same DeviceConnection impl as orbic, if possible.
2026-01-28 10:35:57 -08:00
Will Greenberg
9e08e662ff installer-gui: add an npm prepare step
seems this is required due to
https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md#minor-changes-34
2026-01-27 11:54:36 -08:00
dependabot[bot]
08920e02b8 Bump @sveltejs/kit from 2.48.3 to 2.50.1 in /installer-gui
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.48.3 to 2.50.1.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.50.1/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.50.1
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-27 11:54:36 -08:00
Markus Unterwaditzer
7e2df91702 Fix battery warnings on unsupported devices
Fix #644, break early if battery is unsupported.
2026-01-26 11:22:47 -08:00
Markus Unterwaditzer
262f583355 Add price information to the orbic page
Since rayhunter is getting more popular let's set some expectations
around pricing. There are currently offers ranging from 20 to 90 USD,
and people should understand that the 20 USD offer is not a fake, or
anything like that.
2026-01-26 11:13:21 -08:00
Markus Unterwaditzer
9ae1563286 Add warning about default routes
I hope this puts a lot of questions about SIM cards to rest. I found
that the warning also sometimes applies to "dead" SIM cards which have
expired a long time ago.

Run `busybox ip route` to determine whether the device has an active SIM
card. That command has been manually tested on Moxee, Orbic and TP-Link.
It's prefixed with `busybox` because that makes it more likely it would
work on UZ801, though it wasn't tested there. If the command invocation
fails, the alert is suppressed and a warning is logged.

The command is only run once on pageload. It could've been part of the
status endpoint, but then the UI would poll it way too often.
2026-01-26 11:08:38 -08:00
Markus Unterwaditzer
2bd6efa503 UI: Enforce snake case for functions
It's more common to write functions in camelCase in JS, so some people
started doing it, including me. But the majority of the codebase is
snake_case, so let's enforce that.
2026-01-26 10:35:22 -08:00
Markus Unterwaditzer
e06769158b add #build-all functionality to CI 2026-01-26 10:33:56 -08:00
Markus Unterwaditzer
b341ef2d1e Fix stuck green display after restarting recording
Rayhunter keeps track of the highest-severity warning seen during a
recording, and only updates the display color when a new event
exceeds that level. When a double-tap restarts recording, this
threshold isn't reset, so it retains the old session's maximum. Since no
new event can surpass the stale threshold, the display stays stuck on
green even when warnings are detected.

Fix #794
2026-01-26 10:33:56 -08:00
dependabot[bot]
3a807f48b2 Bump @sveltejs/kit from 2.46.2 to 2.49.5 in /daemon/web
Bumps [@sveltejs/kit](https://github.com/sveltejs/kit/tree/HEAD/packages/kit) from 2.46.2 to 2.49.5.
- [Release notes](https://github.com/sveltejs/kit/releases)
- [Changelog](https://github.com/sveltejs/kit/blob/main/packages/kit/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/kit/commits/@sveltejs/kit@2.49.5/packages/kit)

---
updated-dependencies:
- dependency-name: "@sveltejs/kit"
  dependency-version: 2.49.5
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-15 23:55:28 +01:00
dependabot[bot]
bc3f0bf515 Bump devalue from 5.4.2 to 5.6.2 in /installer-gui
Bumps [devalue](https://github.com/sveltejs/devalue) from 5.4.2 to 5.6.2.
- [Release notes](https://github.com/sveltejs/devalue/releases)
- [Changelog](https://github.com/sveltejs/devalue/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/devalue/compare/v5.4.2...v5.6.2)

---
updated-dependencies:
- dependency-name: devalue
  dependency-version: 5.6.2
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-01-15 23:55:13 +01:00
Rupert Carr
d3290a2c2d Add test notification endpoint and UI button
- Add POST /api/test-notification endpoint to send test to saved config URL
- Refactor send_notification to return Result instead of bool
- Add NotificationError enum for proper error handling
- Add test notification button in config UI with explanatory text
- Button tests saved configuration URL, not input field value
2026-01-07 14:18:18 +01:00
Rupert Carr
579c2c1f3f Add e2e tests for notification worker and extract send_notification helper 2026-01-07 14:18:18 +01:00
Cooper Quintin
7977a01a88 version bump 2026-01-06 09:45:58 -08:00
Cooper Quintin
78dd2f74a4 version bump 2026-01-06 09:28:40 -08:00
Markus Unterwaditzer
dd70a2a15d Add mount logs to rayhunter installer
We sometimes, but rarely, get bug reports where the sdcard fails
mounting. Write a dedicated log file for the mounting action to /tmp,
separately from the rayhunter logfile that is on the sdcard itself. That
log file is probably going to be small so it can fit in /tmp.
2026-01-06 17:42:40 +01:00
Markus Unterwaditzer
81a193959c fix another diff in behavior 2026-01-06 17:42:26 +01:00
Markus Unterwaditzer
7209910c11 Fix deku 0.20 discriminant double-read in Nas4GMessage
Applied workaround from sharksforarms/deku#305 using:
  #[deku(skip, default = "log_type")]

Found using differential fuzzing.

This may be a bug in deku.
2026-01-06 17:42:26 +01:00
Markus Unterwaditzer
3615cbf2dd Upgrade deku to 0.20
Fix #748
2026-01-05 14:32:32 -08:00
Markus Unterwaditzer
61793179e5 Fix Message parser crashes found by fuzzing
These payloads would previous cause panic on underflow.

The fuzzing setup lives in
https://github.com/untitaker/rayhunter/tree/fuzz-wip -- I can eventually
upstream it though right now it runs very inefficiently.
2025-12-09 21:31:08 +01:00
Vicente Reyes
cdc7a46162 Small grammar change 2025-12-03 09:56:25 -08:00
Markus Unterwaditzer
ffe58ab72b Remove powershell script (#715)
* Remove powershell script

Currently install.ps1 and installer are both released in the root of the
zipfile. I think that's a bit confusing. We also don't really support
the ps1 script since a while.

* Remove rootshell and config.toml.in from release folder
2025-12-03 12:08:51 +01:00
Markus Unterwaditzer
7906bf7d67 use cfmakeraw 2025-11-25 13:52:07 -08:00
Markus Unterwaditzer
5e4174c9f3 address review feedback 2025-11-25 13:52:07 -08:00
Markus Unterwaditzer
2a8fee25f9 Remove mentions of tplink-start-telnet and orbic-start-telnet 2025-11-25 13:52:07 -08:00
Markus Unterwaditzer
516e878661 fix installation instructions for orbic 2025-11-25 13:52:07 -08:00
Markus Unterwaditzer
5fbc540fa0 Implement basic telnet shell for both orbic and tplink 2025-11-25 13:52:07 -08:00
Brad Warren
676cd3c862 update installer-gui version to 0.8.0 2025-11-24 11:56:26 -08:00
Brad Warren
a8cb363112 run zizmor --fix=all . 2025-11-24 11:54:01 -08:00
dependabot[bot]
6172236a3c Bump glob from 10.4.5 to 10.5.0 in /daemon/web
Bumps [glob](https://github.com/isaacs/node-glob) from 10.4.5 to 10.5.0.
- [Changelog](https://github.com/isaacs/node-glob/blob/main/changelog.md)
- [Commits](https://github.com/isaacs/node-glob/compare/v10.4.5...v10.5.0)

---
updated-dependencies:
- dependency-name: glob
  dependency-version: 10.5.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-18 21:31:21 +01:00
Markus Unterwaditzer
485d1a99f6 Revert back to the CLI using Clap more directly 2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
f6e118a5cc convert arg parsing errors into stderr printing, remove main_cli 2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
4cdc9961d3 fix argv0 bug and update lockfile 2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
c18579583c remove shell:default permission 2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
565b6d188d remove unused gen folder 2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
80f12ffaaa fix github actions for windows/mac 2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
3e9af006e1 remove tauri-shell entirely 2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
73a5d324c4 clean up run_with_callback api 2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
bb6135c682 Apply suggestion from @oopsbagel
Co-authored-by: oopsbagel <99793478+oopsbagel@users.noreply.github.com>
2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
3b44234ae1 implement installer as library and use it in gui 2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
9e9fe4d392 write new main.rs 2025-11-18 21:05:22 +01:00
Markus Unterwaditzer
2c92315125 rename installer main.rs to lib.rs 2025-11-18 21:05:22 +01:00
dependabot[bot]
7bc55bf432 Bump js-yaml from 4.1.0 to 4.1.1 in /daemon/web (#705)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-11-18 15:41:31 +01:00
Will Greenberg
2a7c5b4365 Add logo SVGs
Fixes #680
2025-11-17 12:09:25 -08:00
dependabot[bot]
d48d5755c6 Bump js-yaml from 4.1.0 to 4.1.1 in /installer-gui (#702)
Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.1.0 to 4.1.1.
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.1.0...4.1.1)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 4.1.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-11-16 15:31:24 +01:00
Cooper Quintin
1cf1d6d5b9 fix 642 2025-11-12 11:37:27 -08:00
Dylan Buel
c8d1b52ca7 Removed reference to deleted documentation and added language about updating to landing page (#697)
* Removed references to installing-from-release-windows.md removed in commit ea5aa6cee2

* Added language referencing the upgrade instructions in installation landing page

* Update doc/installation.md

---------

Co-authored-by: Markus Unterwaditzer <markus-github@unterwaditzer.net>
2025-11-09 12:36:36 +01:00
Markus Unterwaditzer
04efe7bb75 One pass of cargo-audit
Upgrade some yanked dependencies to non-yanked (windows-core) and ignore
the other two warnings.
2025-11-06 17:01:41 +01:00
Brad Warren
3f3b6168b3 remove license 2025-11-05 10:53:41 -08:00
Brad Warren
992a28af57 add README 2025-11-05 10:53:41 -08:00
Brad Warren
39c8844967 update ci config 2025-11-05 10:53:41 -08:00
Brad Warren
ef006d83a6 write plumbing to & from CLI installer 2025-11-05 10:53:41 -08:00
Brad Warren
bc9022530a cargo add anyhow --package installer-gui 2025-11-05 10:53:41 -08:00
Brad Warren
af2445cc38 remove frontend boilerplate 2025-11-05 10:53:41 -08:00
Brad Warren
e33f143830 add rayhunter banner 2025-11-05 10:53:41 -08:00
Brad Warren
f5360b042c set up tailwindcss 2025-11-05 10:53:41 -08:00
Brad Warren
a16fb9b678 set up eslint 2025-11-05 10:53:41 -08:00
Brad Warren
3349895a3e set up prettier 2025-11-05 10:53:41 -08:00
Brad Warren
30b517069a bundle cli-installer 2025-11-05 10:53:41 -08:00
Brad Warren
4efc2d5db3 npm run tauri add shell 2025-11-05 10:53:41 -08:00
Brad Warren
5e066682b3 run npm run tauri icon & exclude mobile icons 2025-11-05 10:53:41 -08:00
Brad Warren
01aefe25c9 update Cargo.toml and run npm run tauri dev 2025-11-05 10:53:41 -08:00
Brad Warren
e8e9f9366c clean up tauri boilerplate 2025-11-05 10:53:41 -08:00
Brad Warren
fa346989e6 run npm install
we need to track package-lock.json to keep the tauri JS packages in sync
with tauri's rust packages in cargo.lock
2025-11-05 10:53:41 -08:00
Brad Warren
d942545ac3 run create-tauri-app
command was: sh <(curl https://create.tauri.app/sh)

the chosen options were:

Project name · installer-gui
Identifier · com.rayhunter-installer.app
Choose which language to use for your frontend · TypeScript / JavaScript - (pnpm, yarn, npm, deno, bun)
Choose your package manager · npm
Choose your UI template · Svelte - (https://svelte.dev/)
Choose your UI flavor · TypeScript
2025-11-05 10:53:41 -08:00
Cooper Quintin
e162070a04 bump to version 0.8.0 2025-11-04 12:41:01 -08:00
Markus Unterwaditzer
2e42750b09 Spawn in background, just in case 2025-11-04 11:24:21 -08:00
Markus Unterwaditzer
e375e4587a change openPort to be non-overlapping 2025-11-04 11:24:21 -08:00
Markus Unterwaditzer
2a30e2d709 fix ci to build rootshell if installer changed 2025-11-04 11:24:21 -08:00
Markus Unterwaditzer
fe2b8b3456 TP-Link: Space out HTTP requests a bit, retry connection for sending files
On firmware M7350(EU)_V9_9.0.2 Build 241021 (but not sooner), entryId=2
was being sent before entryId=1. entryId=2 is invalid if entryId=1 does
not exist yet. The reason it works is due to both requests firing
simultaneously, so sometimes entryId=1 is indeed being registered first.

We may also be hitting random race conditions on the backend, not 100%
sure. Try to alleviate them by sleeping 1 second between started
requests and waiting until the DOM is ready.

Also, on sluggish devices, it can happen that nc is not ready within
100ms. Fixing that with exponential backoff.
2025-11-04 11:24:21 -08:00
Markus Unterwaditzer
cedfe2d4d7 Update doc/installing-from-release.md
Co-authored-by: Cooper Quintin <cooperq@users.noreply.github.com>
2025-11-04 11:22:43 -08:00
Markus Unterwaditzer
22be337f62 rephrase warning msg 2025-11-04 11:22:43 -08:00
Markus Unterwaditzer
6326c5e783 remove old network installer docs 2025-11-04 11:22:43 -08:00
Markus Unterwaditzer
ea5aa6cee2 Make orbic-network the default, update documentation, add deprecation warnings 2025-11-04 11:22:43 -08:00
Markus Unterwaditzer
65d4f22e09 correct port in documentation 2025-11-04 11:22:43 -08:00
Markus Unterwaditzer
450434b4f9 update a broken link 2025-11-03 14:56:59 -08:00
Markus Unterwaditzer
4e93e03e6a Link to CONTRIBUTING.md from issue templates. 2025-11-03 14:56:59 -08:00
Hal Mueller
e416d6e311 Doc spelling and punctuation corrections:
- standardize on American English spellings (behavior, analyze)
- consistent bullet line end punctuation.
- wifi -> WiFi, usb -> USB where needed.
- some comma and article edits.
2025-10-27 01:04:41 +01:00
Hal Mueller
0eebe890c1 Noisey -> noisy 2025-10-27 01:04:41 +01:00
Hal Mueller
28c9f44f73 orcas are whales, not fish 2025-10-27 01:04:41 +01:00
dependabot[bot]
85fa73ddd6 Bump vite from 7.1.9 to 7.1.11 in /daemon/web (#666)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-10-21 13:13:23 +02:00
bsickler
b8b90268b9 Enhancement: Remove unnecessary component renders for difference screen sizes (#661)
* adds breakpoint stores to allow selective rendering on screen size

* removes unused type

* formatting
2025-10-19 04:43:15 +02:00
Adrien Thebo
9e5de4a445 check: add flag help documentation (#662) 2025-10-19 04:09:33 +02:00
Adrien Thebo
643fb802be make: install node deps when node_modules absent (#660)
* Install node deps via make.sh when absent

* Unconditionally install node modules
2025-10-19 01:24:44 +02:00
esp323277
93f22172cc Added HTTP GET request to check if uz801 device is online (#648)
Co-authored-by: Your Name <you@example.com>
Co-authored-by: Markus Unterwaditzer <markus-tarpit+git@unterwaditzer.net>
2025-10-16 18:54:32 +02:00
John DeGood
d5f2dd9813 update uninstall filenames (#646) 2025-10-13 16:54:04 +02:00
Cooper Quintin
d413a76b30 bump version 0.7.1 2025-10-08 13:13:50 -07:00
Markus Unterwaditzer
fc532682df fix some type inference issues by installing @types/node
ProxyServer (first arg in vite.config.ts configure) inherits from
EventEmitter which has no type definition, so on() is not defined.
2025-10-08 10:51:51 -07:00
dependabot[bot]
8569a88f86 Bump esbuild, @sveltejs/vite-plugin-svelte, vite and vitest
Bumps [esbuild](https://github.com/evanw/esbuild) to 0.25.10 and updates ancestor dependencies [esbuild](https://github.com/evanw/esbuild), [@sveltejs/vite-plugin-svelte](https://github.com/sveltejs/vite-plugin-svelte/tree/HEAD/packages/vite-plugin-svelte), [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) and [vitest](https://github.com/vitest-dev/vitest/tree/HEAD/packages/vitest). These dependencies need to be updated together.


Updates `esbuild` from 0.21.5 to 0.25.10
- [Release notes](https://github.com/evanw/esbuild/releases)
- [Changelog](https://github.com/evanw/esbuild/blob/main/CHANGELOG-2024.md)
- [Commits](https://github.com/evanw/esbuild/compare/v0.21.5...v0.25.10)

Updates `@sveltejs/vite-plugin-svelte` from 4.0.4 to 6.2.1
- [Release notes](https://github.com/sveltejs/vite-plugin-svelte/releases)
- [Changelog](https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/vite-plugin-svelte/CHANGELOG.md)
- [Commits](https://github.com/sveltejs/vite-plugin-svelte/commits/@sveltejs/vite-plugin-svelte@6.2.1/packages/vite-plugin-svelte)

Updates `vite` from 5.4.20 to 7.1.9
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v7.1.9/packages/vite)

Updates `vitest` from 2.1.9 to 3.2.4
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Commits](https://github.com/vitest-dev/vitest/commits/v3.2.4/packages/vitest)

---
updated-dependencies:
- dependency-name: esbuild
  dependency-version: 0.25.10
  dependency-type: indirect
- dependency-name: "@sveltejs/vite-plugin-svelte"
  dependency-version: 6.2.1
  dependency-type: direct:development
- dependency-name: vite
  dependency-version: 7.1.9
  dependency-type: direct:development
- dependency-name: vitest
  dependency-version: 3.2.4
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-10-08 10:51:51 -07:00
Cooper Quintin
e60035f744 use port 24 2025-10-08 10:46:41 -07:00
Markus Unterwaditzer
1a80a0576c Add --admin-password to orbic-network installer, update docs
Also add some more debug-logging to telnet_send_file since it appears
to be janky on my device.

see #599
2025-10-08 10:46:41 -07:00
Markus Unterwaditzer
fa5c2bf5d1 Fix installation from source again
Fix https://github.com/EFForg/rayhunter/issues/630

A better fix would be to automatically infer the right path based on
what's available. Maybe based on cfg!(debug_assertions)? idk too fancy.
2025-10-08 09:25:17 -07:00
Markus Unterwaditzer
ce8cbb743f Add TP-Link M7350 bands 2025-10-07 16:59:59 -07:00
Markus Unterwaditzer
13c1602f76 Check in package-lock.json
It seems we never checked in our package-lock.json, which means there's
no effective checksum verification or version pinning going on.
2025-10-07 16:59:08 -07:00
Markus Unterwaditzer
e2cde3be90 Update CONTRIBUTING.md
Co-authored-by: Cooper Quintin <cooperq@users.noreply.github.com>
2025-10-06 10:40:54 -07:00
Markus Unterwaditzer
8ed3459349 Add CONTRIBUTING.md 2025-10-06 10:40:54 -07:00
Evan Anderson
5ccdcc8685 tplink: Implement battery level support 2025-10-01 10:10:46 -07:00
Markus Unterwaditzer
dac838eea9 Improve log message 2025-10-01 09:57:02 -07:00
Markus Unterwaditzer
9d33c161b6 Replace wrong make.sh command 2025-10-01 09:57:02 -07:00
Markus Unterwaditzer
f6ff61f26b CI: Fix missing components in rust setup 2025-10-01 09:57:02 -07:00
Markus Unterwaditzer
9f57edd385 Fix support for M7350 v6 2025-10-01 09:57:02 -07:00
Cooper Quintin
69260d21ac bump version to 0.7.0 2025-09-24 11:17:39 -07:00
Cooper Quintin
f65e5708fc downgarde incomplete sib heuristic to informational 2025-09-24 11:07:48 -07:00
Brad Warren
6eba455e42 suggest using different usb to troubleshoot 2025-09-24 10:52:13 -07:00
Markus Unterwaditzer
dd0b8050b8 Clarify documentation around TLS backends 2025-09-23 10:05:05 -07:00
Markus Unterwaditzer
6009123649 try to simplify workflows 2025-09-23 10:05:05 -07:00
Markus Unterwaditzer
549d3a6a8f Avoid rustcrypto backend for release builds 2025-09-23 10:05:05 -07:00
Markus Unterwaditzer
3dc807fc63 Do not print instructions for admin UI when telnet is already running 2025-09-22 12:33:38 -07:00
Markus Unterwaditzer
95fe938eeb Refactor and comment JS code 2025-09-22 12:33:38 -07:00
Markus Unterwaditzer
3ada0fa259 fix CI: Daemon should build if installer changed 2025-09-22 12:33:38 -07:00
Markus Unterwaditzer
48a4b43a39 Attempt to fix TP-Link race condition 2025-09-22 12:33:38 -07:00
Simon Fondrie-Teitler
f3c34ce0d3 Fix issue where low battery alert is fired on reboot when batter is 10% 2025-09-22 12:31:57 -07:00
Simon Fondrie-Teitler
1b5575e5a6 Update ConfigForm.svelte
Signed-off-by: Simon Fondrie-Teitler <simonft@riseup.net>
2025-09-22 12:31:57 -07:00
Evan Anderson
1cf6f5d339 installer: Fix installation in skip-sdcard case (#604) 2025-09-19 18:40:18 +02:00
Simon Fondrie-Teitler
b00f17d8fc Use a cancellation token for restart logic as well (#602) 2025-09-18 10:00:07 +02:00
Simon Fondrie-Teitler
766f3461d3 Simplify shutdown with cancellation tokens (#601) 2025-09-18 00:33:44 +02:00
Simon Fondrie-Teitler
d30dd6fd9d Don't show scroll bars with no overflow 2025-09-17 11:38:53 -07:00
bsickler
10e76e351e Maintenance: Removes unused PNG (#598) 2025-09-14 00:09:46 +02:00
Burton Sickler
301d130cdd adds filter to incoming events 2025-09-12 11:34:28 +02:00
Hu8r1z
7a602b577d Update AnalysisTable.svelte
corrected ususally to usually
2025-09-12 11:24:19 +02:00
Tom Plant
f52c673b25 Fix several typos in docs
Ran `typos doc --write-changes` from https://github.com/crate-ci/typos and reviewed
2025-09-10 10:44:53 +02:00
Matthew Callis
e6b9624a34 Fix typo in heuristics.md phoen ➜ phone
Fix typo in `doc/heuristics.md` `phoen` ➜ `phone`
2025-09-09 20:08:11 +02:00
Cooper Quintin
15c0ba3805 cargo fmt 2025-09-05 13:22:42 -07:00
Cooper Quintin
de4a622c68 decode with correct byte order. Fixes #562 2025-09-05 13:22:42 -07:00
Cooper Quintin
a582715177 handle 2 digit MNC. Fixes #580 2025-09-05 13:22:42 -07:00
Markus Unterwaditzer
e68ba6ba52 Always run all builds with -p
Running without -p can confuse cargo to enable the wrong set of
featureflags.

Fix #581
2025-09-03 00:19:17 +02:00
Brad Warren
e216043a14 make analyze_information_element private 2025-09-02 15:18:33 -07:00
Brad Warren
e2bc3a0a67 append packet num in harness & fix packet count 2025-09-02 15:18:33 -07:00
Brad Warren
87d6d1691a track packet num in analysis harness 2025-09-02 15:18:33 -07:00
Sashanoraa
7475cd5cd9 Hide error count in error toast if there is only 1 error 2025-08-28 16:20:16 -07:00
Sashanoraa
cef94ba6b0 Add log view modal to web UI 2025-08-28 16:19:17 -07:00
Sashanoraa
d7c973ea95 Add api for getting rayhunter's log file 2025-08-28 16:19:17 -07:00
Simon Fondrie-Teitler
64d657efd6 Don't return an error if there's an issue parsing battery status 2025-08-28 16:09:09 -07:00
Simon Fondrie-Teitler
16447ed8bf Use percentage battery in frontend and not levels 2025-08-28 16:09:09 -07:00
Simon Fondrie-Teitler
663d0abb57 Add battery level to web UI 2025-08-28 16:09:09 -07:00
Simon Fondrie-Teitler
f49d11f034 Skip updating web UI when browser tab isn't visible
This will save bandwith and battery on the hotspot in cases where the UI
tab is left open. See #564.
2025-08-27 22:52:34 +02:00
Cooper Quintin
56dcfdb47c Update orbic.md 2025-08-26 10:17:54 -07:00
Markus Unterwaditzer
a46ede37b6 Fix links in README 2025-08-26 09:22:07 -07:00
Cooper Quintin
69dc528f34 bump version to 0.6.1 2025-08-25 22:28:10 +02:00
Cooper Quintin
29ce6729ee fix readme links 2025-08-25 11:23:34 -07:00
Cooper Quintin
5919a19aba revert removing link 2025-08-25 09:29:28 -07:00
Cooper Quintin
35ca590e46 improvements to documentation 2025-08-25 09:29:28 -07:00
Sashanoraa
56122f6559 Add error reporting to the daemon web UI
This error reporting comes in two forms:
- Errors updating the UI
- Errors with user actions

The former is displayed as one error until a refresh succeeds again. The
latter creates an number of persistent errors until they are cleared by
the user.
2025-08-25 03:15:25 -04:00
Cooper Quintin
bbab29ae0b Update lib/src/analysis/imsi_requested.rs
Co-authored-by: Markus Unterwaditzer <markus-tarpit+git@unterwaditzer.net>
2025-08-22 15:37:18 -07:00
Cooper Quintin
2a620fd1fb cargo fmt 2025-08-22 15:37:18 -07:00
Cooper Quintin
515bb40a76 fix false positive on identity requested without attach described in #557 2025-08-22 15:37:18 -07:00
Cooper Quintin
a5ec1c9505 more verbosity 2025-08-22 23:55:40 +02:00
Markus Unterwaditzer
806bd62a0e Document reanalyzing feature, and include rayhunter-check in release 2025-08-22 23:55:40 +02:00
Cooper Quintin
6ceced2d31 bump version to 0.6.0 2025-08-20 17:58:45 -07:00
Cooper Quintin
856374c05a revert framerate change 2025-08-20 17:11:04 -07:00
Cooper Quintin
983867c2a6 make web ui reflect screen ui colors 2025-08-20 17:11:04 -07:00
Cooper Quintin
145d0a295a cargo fmt 2025-08-20 17:11:04 -07:00
Cooper Quintin
c021b9150d slight refactor 2025-08-20 17:11:04 -07:00
Cooper Quintin
ce916dcd10 display colors as well as patterns for severity 2025-08-20 17:11:04 -07:00
Cooper Quintin
898bdbb6cd include event severity in message 2025-08-20 17:11:04 -07:00
Markus Unterwaditzer
375789aad9 cargo fmt 2025-08-20 17:11:04 -07:00
Cooper Quintin
85f7b2cc81 refactor test analyzer for new format 2025-08-20 17:11:04 -07:00
Markus Unterwaditzer
781d11ed72 Expose severity to display
See https://github.com/EFForg/rayhunter/issues/334

Severity levels low, medium, high are now exposed to the UI in form of
dotted, dashed and solid lines. The line on the UI represents the
highest-so-far severity seen.

Originally this was intended to be represented by Yellow/Orange/Red, but
this would mean yet another divergence for colorblind mode. This is
colorblind-friendly by default (I think...)

As part of this, simplify EventType so that it becomes a flat "level"
enum without nested variants.

There is also a new debug endpoint that allows one to overwrite the
display level directly for testing.
2025-08-20 17:11:04 -07:00
Cooper Quintin
6927da49b4 cargo fmt 2025-08-20 14:48:47 -07:00
Cooper Quintin
479505f738 appease clippy 2025-08-20 14:48:47 -07:00
Cooper Quintin
468b07faf0 proper formatting for CID and PLMN 2025-08-20 14:48:47 -07:00
Cooper Quintin
493fdfa227 add docs 2025-08-20 14:48:47 -07:00
Cooper Quintin
ffdad4aed8 add test analyzer 2025-08-20 14:48:47 -07:00
Markus Unterwaditzer
33e4fbc544 Fix wrong analyzer name in AnalysisTable
Each event index corresponds to an index in analyzers. But some events
may be null. We're skipping those events without incrementing the index,
leading to wrong analyzer names.
2025-08-20 14:39:09 -07:00
Markus Unterwaditzer
8c510b43c9 Merge pull request #429 from simonft/notifications 2025-08-20 21:56:45 +02:00
Markus Unterwaditzer
46850e2739 Update installer/src/tplink.rs
Co-authored-by: Cooper Quintin <cooperq@users.noreply.github.com>
2025-08-20 09:53:10 -07:00
Markus Unterwaditzer
53e3b8ee34 Mention required SD card for tplink 2025-08-20 09:53:10 -07:00
Markus Unterwaditzer
0fc51d79f4 Fix issue template and improve one error message
The current error message is not very useful for remote-debugging. Add
enough context to allow technically adept users to figure out a way.

See #544
2025-08-20 09:53:10 -07:00
Markus Unterwaditzer
ad4e971e77 Restyle download links in table view
They're taking up too much space as individual columns.

Also change DownloadLink to be a real link, so that "Copy URL" works.
2025-08-20 09:48:37 -07:00
Markus Unterwaditzer
c5a79e545d Add documentation for Orbic Network installer 2025-08-20 09:41:43 -07:00
Markus Unterwaditzer
9d92ab3c01 Simplify remounting procedure 2025-08-19 17:36:10 -07:00
Markus Unterwaditzer
cf254b66ff Address review comments and update wingtech docs 2025-08-19 17:36:10 -07:00
Markus Unterwaditzer
cddc590c77 Try to use the same rust version as in other jobs 2025-08-19 17:36:10 -07:00
Markus Unterwaditzer
9d736f5bf0 Add a orbic network installer
There is a shell injection vulnerability after all, so we can just
launch a remote shell, tplink-style. Except there's no telnetd on this
device so we need to use netcat.

This was found in the goahead binary on the device using Ghidra. The
decompiled code for this endpoint looks like this:

```c
void FUN_0003c614(int param_1)

{
  int iVar1;
  undefined4 uVar2;
  int local_160;
  undefined1 auStack_15c [64];
  char acStack_11c [256];
  int local_1c;

  local_1c = __stack_chk_guard;
  if (param_1 == 0) {
    error("input parameter is NULL!");
    uVar2 = 0x66;
    goto LAB_0003c808;
  }
  iVar1 = websGetJsonItemValue(param_1,"password",10,auStack_15c,0x40);
  if (iVar1 != 0) {
    iVar1 = get_log_level_something();
    if (1 < iVar1) {
      some_logging_func(2,"modifying root password(%s)...",auStack_15c);
    }
    iVar1 = sprintf(acStack_11c,"echo root:\"%s\"|chpasswd",auStack_15c);
    acStack_11c[iVar1] = '\0';
    system(acStack_11c);
  }
```

Usage is `./installer orbic-network`, as an alternative to `./installer
orbic`. It should work on Windows without any kind of drivers.

This installer also works on the Moxee device.
2025-08-19 17:36:10 -07:00
oopsbagel
e5df43d7f5 Merge pull request #520 from simonft/update-install-commands-in-doc
Update instructions for installing from source
2025-08-13 20:22:33 +00:00
Simon Fondrie-Teitler
a8667cc3a0 Pass notification_channel in diag_task constructor 2025-08-11 13:59:42 -04:00
Markus Unterwaditzer
3239daa011 Merge pull request #529 from EFForg/macos-intel-ci
Move MacOS intel builds to macos-latest
2025-08-11 16:50:14 +02:00
Markus Unterwaditzer
651511cc63 Merge pull request #530 from EFForg/windows-installer
Rename windows installer file to installer.exe
2025-08-11 16:50:02 +02:00
Simon Fondrie-Teitler
211066ec7b Record last attempt time when notification connection fails 2025-08-09 15:18:04 -04:00
Simon Fondrie-Teitler
16ec9e28df Remove a couple unnecssary whitespace changes 2025-08-09 15:03:08 -04:00
Simon Fondrie-Teitler
4462f02c10 Properly close notification service channel 2025-08-09 14:55:13 -04:00
Simon Fondrie-Teitler
5bd2d9a58e Merge branch 'main' into notifications 2025-08-09 14:17:22 -04:00
Markus Unterwaditzer
603d65a3bd Move MacOS intel builds to macos-latest
We're now using ARM runners which crosscompile to Intel.

Fix #525
2025-08-08 21:53:20 +02:00
Markus Unterwaditzer
c0a9cf62df Rename windows installer file to installer.exe
Fix #521
2025-08-08 21:53:02 +02:00
Markus Unterwaditzer
0a20e659be Merge pull request #527 from EFForg/fix-rust-warnings
Fix clippy lints and warnings in Rust 1.89
2025-08-08 21:52:46 +02:00
Markus Unterwaditzer
ce599dc432 specify package.rust-version for daemon 2025-08-08 18:02:40 +02:00
Markus Unterwaditzer
85b50bc301 Remove unpack! macro 2025-08-08 03:12:38 +02:00
Markus Unterwaditzer
5249714717 Fix clippy lints and warnings in Rust 1.89
This will also require Rust 1.89 due to if-let.
2025-08-08 03:02:07 +02:00
Simon Fondrie-Teitler
67974264f9 Update Config object in svelte to add ntfy url 2025-08-06 13:12:10 -04:00
Simon Fondrie-Teitler
f562d33be3 Document notification configuration 2025-08-06 13:08:16 -04:00
Simon Fondrie-Teitler
0531aa0e3a Require rust 1.88 so we can use let chains 2025-08-06 13:08:08 -04:00
Simon Fondrie-Teitler
dd78f5007d Specify ntfy notification is from rayhunter 2025-08-06 13:07:25 -04:00
Simon Fondrie-Teitler
1c08708bc4 Set full ntfy url in config instead of just topic 2025-08-06 13:07:08 -04:00
Simon Fondrie-Teitler
0f53da58bc Better document options when installing from source 2025-08-06 10:55:05 -04:00
Simon Fondrie-Teitler
01010df4ec Update instructions for installing from source
Command changed in #460
2025-08-05 17:59:13 -04:00
Simon Fondrie-Teitler
481f02f81f Merge branch 'main' into notifications 2025-08-05 17:30:07 -04:00
Markus Unterwaditzer
8c67a92b07 Merge pull request #511 from Tunas1337/uz801
Add UZ801 support
2025-08-05 21:23:27 +02:00
Markus Unterwaditzer
31bd60dea1 cargo fmt 2025-08-05 21:11:17 +02:00
Markus Unterwaditzer
13877f7209 cargo clippy 2025-08-05 21:05:31 +02:00
Andrej
f4522dbe3d cargo fmt run 2025-08-05 14:21:19 -04:00
Matej Kovacic
30bb18016e Update heuristics.md 2025-08-05 08:17:51 -07:00
Matej Kovacic
c6aa53acd2 Update heuristics.md
More explanation of logic behind analysers.
2025-08-05 08:17:51 -07:00
oopsbagel
c6882ed173 Merge pull request #515 from EFForg/installer-faster
Speed up file transfer for network-based installers
2025-08-05 00:30:46 +00:00
Markus Unterwaditzer
5c03f6ea03 Add reanalyze button
Add a reanalyze button for individual recordings in the analysis dropdown

As part of this, split out ApiRequestButton so that state transitions
(clickable -> loading/disabled -> done) can be shared across start/stop
recording and this new button. Other buttons might benefit from this as
well.

Also fix a broken checkbox while we're here.
2025-08-04 17:19:42 -07:00
Andrej
5184c6138d uz801: Add uninstalling instructions 2025-08-04 13:23:14 -04:00
Andrej
c893f8e2a9 uz801: update docs 2025-08-04 13:16:46 -04:00
Andrej
2e6343c343 uz801: clippy fixes 2025-08-04 11:35:23 -04:00
Andrej
da4a86be13 uz801: Installer improvements 2025-08-04 11:33:37 -04:00
Andrej
55794cbdd5 uz801: Fix clippy warnings 2025-08-03 20:03:01 -04:00
Andrej
e36b490d15 uz801: installer: Add file transfer verify, other fixes 2025-08-03 19:27:25 -04:00
Andrej
574e897610 cargo fmt pass 2025-08-03 18:49:38 -04:00
Andrej
1f19bc880f uz801: Force LED updates every 5s to beat MifiService 2025-08-03 18:35:54 -04:00
Markus Unterwaditzer
8dc6206683 Speed up file transfer for network-based installers
There is a bug in `telnet_send_file` where we never close the connection
to nc, and instead wait for it to time out.

This means every file transfer takes at least 5 seconds.
2025-08-04 00:06:57 +02:00
Andrej
7184ccd5c1 uz801: installer: Update VID/PID, add remount 2025-08-03 18:06:13 -04:00
Andrej
cb22e179d6 uz801: installer: Add missing dependency 2025-08-03 17:30:15 -04:00
Andrej
a3db5029ad uz801: Update installer 2025-08-03 16:51:46 -04:00
Andrej
9f661ab398 uz801: Update documentation 2025-08-03 16:51:36 -04:00
Andrej
412ad3d8bf cargo fmt run 2025-08-03 16:29:59 -04:00
Andrej
4d2d49326a uz801: Update installer usb backdoor trigger code 2025-08-03 11:12:46 -04:00
Andrej
c26ad29ffb uz801: Fix installer defaults, fix docs for admin IP 2025-08-03 11:05:50 -04:00
Andrej
f57fc611c2 uz801: Use busybox coreutils (they were hiding all along) 2025-08-03 10:54:47 -04:00
Andrej
38a408757a Add uz801 to supported devices list 2025-08-03 10:28:43 -04:00
Andrej
0540504eea uz801: Correct LED definition comment 2025-08-03 10:25:56 -04:00
Andrej
28a0c06017 uz801: Add purchase links to documentation 2025-08-03 00:51:35 -04:00
Andrej
6141087f9d uz801: Added docs 2025-08-03 00:41:40 -04:00
Andrej
7a053a4f89 uz801: cargo fmt run 2025-08-02 21:03:28 -04:00
Andrej
6473c05e3e uz801: Refactor strings, since &&'static str can be coerced into &dyn AsRef<str>: & 2025-08-02 20:59:09 -04:00
Andrej
c697773244 uz801: Add initial (experimental) support 2025-08-02 20:58:19 -04:00
oopsbagel
fe6afac817 Merge pull request #499 from EFForg/installer-issue-tmpl
Add an issue template for Installer issues
2025-08-02 18:50:13 +00:00
oopsbagel
8e708f145e doc/pinephone: the installer runs on the phone 2025-08-01 09:42:34 -07:00
oopsbagel
03c00a1f19 installer/orbic: warn windows users this may brick
The windows installer seems to sometimes brick the Orbic's ARM core,
resulting in the DSP returning "Qmi Send Message Fail" when sent AT
commands.

This commit adds a loud warning and confirmation dialog for Windows
users before installing.
2025-07-31 22:22:55 -07:00
oopsbagel
64842c7140 release v0.5.1 2025-07-31 22:22:55 -07:00
Markus Unterwaditzer
e108c21fc2 Use ./installer in docs
See https://github.com/EFForg/rayhunter/discussions/490
2025-07-31 20:55:41 +02:00
Sashanoraa
49a2108214 Add an issue template for Installer issues 2025-07-31 14:42:17 -04:00
Markus Unterwaditzer
53a6cbe95a Fix line endings on Windows
Fix #489
2025-07-31 18:06:52 +02:00
Sashanoraa
398997af67 Refactor diag thread to have full control over the QMDL store
Fixes #269. Refactor also pull diag thread logic out into state machine
object for better encapsulation and reuse.
2025-07-31 11:47:11 +02:00
oopsbagel
6b109a9d76 Merge pull request #498 from oopsbagel/wingtech-wifi-install-fix
wingtech: install without disabling wifi
2025-07-31 03:29:53 +00:00
oopsbagel
d9688b1796 wingtech: install without disabling wifi
Previously, the unlocking method for the wingtech hotspot would add a
invalid mac address to the blocklist. This would prevent the wifi from
coming online after rebooting until the invalid mac was removed.

This commit changes the unlocking method to attempt to *remove* an
invalid mac, creating a no-op condition that still works for unlocking
root access to the hotspot.

This commit also adds documentation for a problem where the hotspot
would occasionally not reboot while completely disconnected and
installing over wifi.

Fixes #466
2025-07-30 20:09:26 -07:00
Sashanoraa
7466c1c669 Fixes #381 UI no longer X overflows on mobile
Button will horizontally shrink a little on smaller screens and buttons
and tables will X scroll if needed.
2025-07-30 14:13:16 -04:00
Cooper Quintin
6a51050921 Update doc/configuration.md
Co-authored-by: Will Greenberg <ifnspifn@gmail.com>
2025-07-28 16:05:58 -07:00
Matej Kovacic
0935cf8239 Delete doc/Rayhunter_0.3.2.png 2025-07-28 16:05:58 -07:00
Matej Kovacic
d25e9588e2 Update heuristics.md 2025-07-28 16:05:58 -07:00
Matej Kovacic
a8ff95a07b Update using-rayhunter.md 2025-07-28 16:05:58 -07:00
Matej Kovacic
ac86277903 Add files via upload 2025-07-28 16:05:58 -07:00
Matej Kovacic
8e9abc718a Update configuration.md 2025-07-28 16:05:58 -07:00
Matej Kovacic
d92fb16c57 Add files via upload 2025-07-28 16:05:58 -07:00
Markus Unterwaditzer
f8824ce7e7 Remove blocking code and spawn_blocking
Rayhunter uses a mixture of spawn and spawn_blocking, then also does
some blocking operations inside of async code.

Move everything to async. This allows us to use the single-threaded
runtime.

Now the binary is 100kB smaller, and the memory usage also improved by
~100kB on tplink.
2025-07-28 16:04:24 -07:00
Sashanoraa
9694aa826b Use firmware-devel profile for make.sh 2025-07-28 11:09:48 -07:00
Sashanoraa
b859dde0c8 Add firmware-devel profile to cargo config
This speeds up compile time in exchange for binary size,
which is often a worthy trade-off in development when iteration speed
matters.
2025-07-28 11:09:48 -07:00
oopsbagel
5b6a73bc44 Merge pull request #477 from EFForg/release-0.5.0
Bump version to 0.5.0
2025-07-25 20:11:00 +00:00
Will Greenberg
8cbdbf5ebe Bump version to 0.5.0 2025-07-25 12:58:48 -07:00
Cooper Quintin
ccce63e90c address comments 2025-07-24 16:44:59 -07:00
Cooper Quintin
68b13ea09e Update lib/src/analysis/incomplete_sib.rs
Co-authored-by: Will Greenberg <willg@eff.org>
2025-07-24 16:44:59 -07:00
Cooper Quintin
672d825bdb rm stray char 2025-07-24 16:44:59 -07:00
Cooper Quintin
fd216ecb72 add incomplete sib heuristic 2025-07-24 16:44:59 -07:00
Cooper Quintin
07d43b5924 remove unused heuristic 2025-07-24 16:44:59 -07:00
Will Greenberg
bd3e439a1d lib: pycrate-rs now lives in EFF's github org 2025-07-24 15:19:33 -07:00
oopsbagel
5491c3f3a0 installer: remove struct NoArgs
An empty struct indicating no arguments is superfluous if the caller
doesn't specify a tuple in its corresponding match arm.
2025-07-24 09:48:41 -07:00
oopsbagel
fa14e4ecfc doc: add pinephone to supported devices 2025-07-24 09:48:41 -07:00
oopsbagel
8583064e46 installer: add pinephone and pinephonepro support 2025-07-24 09:48:41 -07:00
oopsbagel
d3bd8d9dfc feat: add headless display mode 2025-07-24 09:48:41 -07:00
oopsbagel
b16a351727 Merge pull request #471 from oopsbagel/framebuffer-usually-display-status-bar
generic_framebuffer: show status when ui_level!=0
2025-07-24 04:44:26 +00:00
oopsbagel
cd781fe8d8 Merge pull request #472 from oopsbagel/doc-orbic-disable-wifi
doc: add how to disable wifi entirely to the faq
2025-07-24 04:43:59 +00:00
oopsbagel
df00e00076 doc: add how to disable wifi entirely to the faq
Fixes #234

Co-authored-by: joelishness <joelishness@gmail.com>
2025-07-23 16:14:56 -07:00
oopsbagel
1a810cfb33 generic_framebuffer: show status when ui_level!=0
Unless ui_level = 0 (invisible mode), display the status bar on
framebuffer displays even when running in demo mode.

Fixes #445
2025-07-23 15:48:09 -07:00
Sashanoraa
b16b1af65e Fixes #433 do not stop recording when deleting a past entry 2025-07-20 18:07:24 -04:00
Cooper Quintin
a346449ec5 cargo fmt 2025-07-18 11:19:07 -07:00
Cooper Quintin
464740a1a7 fix another false positive 2025-07-18 11:19:07 -07:00
Cooper Quintin
e07b0b05e7 imsi requested version 2; remove most false positives 2025-07-17 18:43:07 -07:00
Cooper Quintin
578bc0d234 modifications to rayhunter-check 2025-07-17 18:43:07 -07:00
oopsbagel
751d504440 rename config.toml.example to config.toml.in
Since we now replace a value in this file, it's more of a template than
an example.
2025-07-17 16:06:09 -07:00
oopsbagel
29c944af45 diag_device: accept rayhunter::Device arg
Move daemon's config::Device to lib and toggle the extra tplink ioctl
based on Device::Tplink rather than passing a boolean.
2025-07-17 16:06:09 -07:00
oopsbagel
e239653a44 config: rename display to device
Because we toggle some ioctl settings based on this field, change the
name to better capture that we're selecting which device we want to load
settings for, not just the display module to load. This creates room for
future per-device settings without needing more config file fields.
2025-07-17 16:06:09 -07:00
oopsbagel
841bc7b015 ci: use unified rayhunter-daemon in main workflow 2025-07-17 16:06:09 -07:00
oopsbagel
22d927aa25 unified rayhunter-daemon binary for all devices
Replace per-device features with config "display" field with the value
set at install time.
2025-07-17 16:06:09 -07:00
Will Greenberg
5b59efa4c8 cargo fmt 2025-07-17 10:41:54 -07:00
Will Greenberg
f273d28728 daemon: fix recovery timestamp 2025-07-17 10:41:54 -07:00
Will Greenberg
f1e283b52c daemon: do a best-effort manifest recovery
Revises @cooperq's recovery a bit by preventing any panics, recovering
whichever files we can and skipping the ones we can't.
2025-07-17 10:41:54 -07:00
Will Greenberg
1011c4b123 daemon: don't track analysis file bytes written
We don't actually use this for anything
2025-07-17 10:41:54 -07:00
Cooper Quintin
5db24e4b21 recreate manifest entries if manifest is recreated due to error fixes #199 2025-07-17 10:41:54 -07:00
oopsbagel
a72e4b2234 docs: minor fixes for <links>, npm from daemon/web 2025-07-16 17:29:38 -07:00
oopsbagel
ca0151f656 chore: cargo fmt 2025-07-16 16:56:16 -07:00
oopsbagel
56930db130 doc(tmohs1): add bands 2, 4, 5
These were originally excluded because they weren't tested, as they are
subsets of bands 25, 26, and 66, but are worth enumerating.
2025-07-16 16:56:16 -07:00
oopsbagel
f018b8f662 ci: build rayhunter-daemon for tmobile 2025-07-16 16:56:16 -07:00
oopsbagel
7e0f12f1c5 doc(tmohs1): one must change the default password 2025-07-16 16:56:16 -07:00
oopsbagel
e32a6f5b2e fix(installer/tmobile): wait 200ms for telnet 2025-07-16 16:56:16 -07:00
oopsbagel
58618f3412 doc: support the Tmobile TMOHS1 hotspot 2025-07-16 16:56:16 -07:00
oopsbagel
003a8b280b chore: cargo fmt 2025-07-16 16:56:16 -07:00
oopsbagel
27bf20fbf4 fix(installer): de-duplicate common wingtech/tmohs
The Tmobile TMOHS1 is clearly based on the Wingtech CT2MHS01, and thus
the installation process looks very similar between them.
2025-07-16 16:56:16 -07:00
oopsbagel
b7636386fc feat: support Tmobile TMOHS1 hotspot
Add support for the Tmobile TMOHS1, a Wingtech CT2MHS01-based hotspot
with a Qualcomm mdm9607. The TMOHS1 has no screen, only 5 LEDs, two of
which are RGB.
2025-07-16 16:56:16 -07:00
Cooper Quintin
f23cc07652 Update doc/heuristics.md
Co-authored-by: Will Greenberg <willg@eff.org>
2025-07-16 15:25:11 -07:00
Cooper Quintin
f9b621bde9 Update lib/src/analysis/nas_null_cipher.rs
Co-authored-by: Will Greenberg <willg@eff.org>
2025-07-16 15:25:11 -07:00
Cooper Quintin
a4cb9454bd add version 2025-07-16 15:25:11 -07:00
Cooper Quintin
fbac464b46 add config option and documentation 2025-07-16 15:25:11 -07:00
Cooper Quintin
b923d9d5a6 cargo fmt 2025-07-16 15:25:11 -07:00
Cooper Quintin
790c0963cd add nas null cipher analyzer 2025-07-16 15:25:11 -07:00
Will Greenberg
32106ac0f4 daemon: rm vestigial dummy_analyzer remnants 2025-07-16 13:20:14 -07:00
Will Greenberg
1ce4d99c59 web: consider unversioned heuristics to be v0
This lets us cleanly differentiate old heuristics (which we know contain
some false positives) from our current set.
2025-07-16 13:20:14 -07:00
Will Greenberg
b055ddc670 web: more linting 2025-07-16 13:20:14 -07:00
Will Greenberg
09d4328dc2 web: lint fixes 2025-07-16 13:20:14 -07:00
Will Greenberg
1a4deb7524 appease clippy 2025-07-16 13:20:14 -07:00
Will Greenberg
0585e0f996 run cargo fmt 2025-07-16 13:20:14 -07:00
Will Greenberg
c783831e78 check: support pcaps
rayhunter-check will now analyze any PCAP files it finds in addition to
QMDL
2025-07-16 13:20:14 -07:00
Will Greenberg
3ddbaa07ca CI: fix paths to daemon workspace 2025-07-16 13:20:14 -07:00
Will Greenberg
83f246e9af lib: bump the analysis report version 2025-07-16 13:20:14 -07:00
Will Greenberg
0d96b4c103 frontend: bump sveltekit version
We're using a config setting that's only present in sveltekit v2.13
onwards
2025-07-16 13:20:14 -07:00
Will Greenberg
7cd8835cab frontend: handle both old and new analysis reports
Adds support for versioned analysis reports (and defaults to v1 for
reports with no version).
2025-07-16 13:20:14 -07:00
Will Greenberg
e81df18315 check: crawl input dir for QMDL, update to new analysis format 2025-07-16 13:20:14 -07:00
Will Greenberg
0915103ede Flattens analysis structure a bit
Instead of mirroring the QMDL container format exactly, let our analysis
files just be flat lists of packet analysis. Also removes the dummy
analyzer and adds version numbers to analysis reports and Analyzers
2025-07-16 13:20:14 -07:00
Will Greenberg
da18a1f9da Split bin dir into separate daemon and check dirs
This lets us manage their increasingly disparate dependencies separately
2025-07-16 13:20:14 -07:00
oopsbagel
5bb3dc9db5 Merge pull request #455 from oopsbagel/ci-release-one-zip-per-platform
ci: release one zip{,.sha256sum} per platform
2025-07-16 14:43:52 +00:00
oopsbagel
c2c6004f4e ci: release one zip{,.sha256sum} per platform 2025-07-16 00:22:49 -07:00
Markus Unterwaditzer
e320874854 Remove PartialEq, Clone, Serialize from LTE RRC parser
Compiling telecom-parser takes 2 minutes on my machine. After removing
those derives it takes 1:15. I suspect it's mostly serde though.
2025-07-15 15:21:02 -07:00
Markus Unterwaditzer
300215206c Inline all assets into index.html, compress it, saves 300kB 2025-07-10 12:24:26 -07:00
Markus Unterwaditzer
5e328b889b Fix eslint issues 2025-07-10 12:24:26 -07:00
Markus Unterwaditzer
97cbe62f42 Fix all issues in npm run check 2025-07-10 12:24:26 -07:00
Markus Unterwaditzer
27408dd64a Add web frontend linter to CI 2025-07-10 12:24:26 -07:00
Markus Unterwaditzer
e5c0e13d32 run prettier 2025-07-10 12:24:26 -07:00
Markus Unterwaditzer
41133ba793 Changes to web configs 2025-07-10 12:24:26 -07:00
Markus Unterwaditzer
0be2b02349 Define missing stop_recording/start_recording_classes
These variables were referenced but not actually defined. Define them
and make the button disabled when rayhunter is stopping/starting
2025-07-10 12:24:26 -07:00
oopsbagel
81eb3eac57 Merge pull request #440 from oopsbagel/tokio-rt-current-thread
installer: tokio runtime flavor current_thread
2025-07-09 23:33:16 +00:00
Markus Unterwaditzer
3247d35b7e Fix clippy lints
https://github.com/EFForg/rayhunter/pull/451 is failing because we got
auto-upgraded to a new clippy, which lints against more things
2025-07-10 01:17:58 +02:00
oopsbagel
355242fa71 Merge pull request #448 from oopsbagel/arm32-installer
ci: build installer and rayhunter-check for armv7, rename ubuntu -> linux in release bundles
2025-07-07 18:34:19 +00:00
oopsbagel
72d6c65f29 ci: use soft float target for armv7
Support more platforms by using a the soft float musl target for
aarch32/armv7/v8. The installer is not performance bound by floating
point operations.
2025-07-06 16:04:17 -07:00
oopsbagel
5e66c26e70 ci: build installer and rayhunter-check for armv7
Support installing on aarch32/armv7 linux systems.
2025-07-04 12:18:12 -07:00
Markus Unterwaditzer
b0d8307a14 Add send-file utilities for wingtech and tplink
Since we never turn on ADB, it's a bit cumbersome to send files to the
device.
2025-07-04 11:21:51 +02:00
oopsbagel
cf0875f2e3 Merge pull request #442 from oopsbagel/release-independent-zips
ci: release platform independent installer zips
2025-07-03 08:33:45 +00:00
oopsbagel
1c51e5ed6f ci: release platform independent installer zips
Release one zip file for each operating system / architecture
combination supported by the installer.
2025-07-03 01:03:29 -07:00
oopsbagel
3a393fc29f installer: tokio runtime flavor current_thread
Slightly reduce binary size by using the smaller 'rt' feature and the
current_thread runtime flavor in the installer, since there is no
benefit to true multithreading.
2025-07-01 22:07:47 -07:00
oopsbagel
b97421d220 Merge pull request #438 from oopsbagel/doc-supported-devices
documentation: Attempt to clarify supported devices
2025-06-29 19:23:50 +00:00
oopsbagel
1bf386d5b7 doc: supported devices: say "recommended region"
Individual device pages can go into detail about specific bands and
roaming. This page is primarily for steering users towards which device
to buy, and we only want to recommend devices that are affordable in
their region.
2025-06-29 12:16:07 -07:00
oopsbagel
8de4dcfd18 doc: add white background to map for dark mode 2025-06-29 12:14:54 -07:00
QuietEngineer
c0b1d4608a docs: standardize rayhunter casing
Use uppercase Rayhunter throughout docs when refering to the project and software.
Does not change pathnames.
2025-06-29 21:02:09 +02:00
QuietEngineer
ee8bf0107a docs: misc typo fixes 2025-06-29 21:02:09 +02:00
oopsbagel
664ffc8c75 doc: move wingtech developer details to the bottom 2025-06-29 02:07:22 -07:00
oopsbagel
d03debe67c doc: add region table, map for recommended devices
Implement reordering from untitaker's suggested changes.
2025-06-29 02:05:58 -07:00
oopsbagel
60922afc87 Merge pull request #436 from oopsbagel/smaller-installer
Smaller installer
2025-06-29 00:34:05 +00:00
oopsbagel
932fef32b9 Merge pull request #421 from EFForg/doc-recommended-devices
doc: Give guidance on which device to get
2025-06-29 00:33:50 +00:00
Markus Unterwaditzer
e259417f35 Revert some of the changes in supported-devices index 2025-06-29 02:07:13 +02:00
Markus Unterwaditzer
3889c89b5a Fix autolinks 2025-06-29 00:51:01 +02:00
Markus Unterwaditzer
bd074066c5 Adjust language around supported versions, to be similar across pages 2025-06-29 00:38:47 +02:00
Markus Unterwaditzer
8b44f604ea sort orbic to the top 2025-06-29 00:38:47 +02:00
Markus Unterwaditzer
ef7b8129ef Fix version number in docs, 0.3.5 does not exist 2025-06-29 00:38:47 +02:00
Markus Unterwaditzer
c3fd724ac1 doc: Give guidance on which device to get 2025-06-29 00:38:47 +02:00
oopsbagel
28ead37111 cargo/config: drop inherited firmware profile opts
These options are shared with the release profile.
2025-06-28 15:25:15 -07:00
oopsbagel
6efe83b36d cargo/config: build release bins with opt-level z
This yields a smaller binary and faster compile times than the default.

cf 5.6M binary in 2m 12s vs. 4.7M in 1m 39s on my machine.
2025-06-28 14:40:12 -07:00
oopsbagel
4d0427fe68 installer: fewer tokio and axum crate features 2025-06-28 05:26:59 -07:00
oopsbagel
1ee35dad71 cargo/config: build release binaries with fat lto
Reduce installer binary size with link-time optimisation.
2025-06-28 05:19:52 -07:00
oopsbagel
5d2a5a2577 Merge pull request #434 from oopsbagel/profile-release-strip-debuginfo
cargo/config: strip debuginfo from --release bins for a significantly smaller installer size
2025-06-28 11:00:28 +00:00
oopsbagel
a4f4e12a57 ci: build everything when .cargo changes 2025-06-28 01:06:56 -07:00
oopsbagel
55178e60fd cargo/config: strip debuginfo from release bins
rustc -C strip=debuginfo leaves the symbol table intact, meaning
RUST_BACKTRACE=1 on the installer still produces helpful output.

This significantly reduces the binary size, eg the amd64 installer goes
from 93M to 21M. Stripping the symbol table only reclaims a further ~2M.
2025-06-28 01:06:51 -07:00
Simon Fondrie-Teitler
5019f2a9d1 Bump Rust edition to 2024
Includes new cargo fmt changes
2025-06-28 00:13:15 +02:00
Simon Fondrie-Teitler
f55d9128d4 Merge branch 'main' into notifications 2025-06-27 17:25:01 -04:00
Simon Fondrie-Teitler
25978a4da4 Fix tplink clippy warnings 2025-06-27 23:23:27 +02:00
Simon Fondrie-Teitler
4ad79707bb Add two too_many_arguments exceptions 2025-06-27 23:23:27 +02:00
Simon Fondrie-Teitler
5f45ae31d8 Fail build on cargo check and clippy warnings 2025-06-27 23:23:27 +02:00
Simon Fondrie-Teitler
ed3072eb8e also run formatter 2025-06-27 23:23:27 +02:00
Simon Fondrie-Teitler
94289dcad5 Fix clippy complaints 2025-06-27 23:23:27 +02:00
Simon Fondrie-Teitler
84534bbb2c Clippy fixes 2025-06-27 13:56:30 -04:00
Simon Fondrie-Teitler
1d50440c85 Use RustCrypto TLS provider so we don't need to depend on LLVM 2025-06-27 11:44:35 -04:00
Simon Fondrie-Teitler
2c05f3d94e Add notifications with ntfy 2025-06-26 18:01:29 -04:00
Markus Unterwaditzer
2b86691e57 Bump hampi to 0.7.1 (#423)
It's not clear for how long this revision will exist upstream now that
the PR is (squash) merged
2025-06-25 09:59:39 +02:00
oopsbagel
0a15ca1b1a Merge pull request #420 from oopsbagel/wingtech-docs
doc: Wingtech CT2MHS01
2025-06-25 02:44:54 +00:00
oopsbagel
eeef42f4cb doc(wingtech): ./installer not ./install 2025-06-24 17:08:39 -07:00
oopsbagel
04cf0ab73a doc(Wingtech): device tiers, wt installation
Documents:
- supported device tiers
- wingtech installation
- wingtech shell unlocking
- wingtech rayhunter supported version
- links to wingtech fcc emissions lte test report
2025-06-24 16:23:04 -07:00
Cooper Quintin
23a0f72c2f cargo fmt 2025-06-24 12:52:33 -07:00
Will Greenberg
efae6203a9 rm unneeded comment 2025-06-24 12:52:33 -07:00
Will Greenberg
2e4de4a2df lib: Use pycrate-rs NAS parser 2025-06-24 12:52:33 -07:00
Will Greenberg
deeab1f1b0 Fix make script
Only build the daemon for make's purposes
2025-06-24 10:30:49 -07:00
Will Greenberg
83dba77cba Bump version to 0.4.0 2025-06-24 10:30:49 -07:00
Markus Unterwaditzer
542aff4fdf Merge pull request #351 from untitaker/restart
Config change and restart UI
2025-06-24 19:23:30 +02:00
oopsbagel
aac0c34eaa doc: Wingtech CT2MHS01 2025-06-24 01:10:50 -07:00
Markus Unterwaditzer
2ececf9c58 Fix tests 2025-06-24 02:09:22 +02:00
Markus Unterwaditzer
2cba26a4cc Remove unused import 2025-06-24 01:25:01 +02:00
Markus Unterwaditzer
48c0592b18 Merge remote-tracking branch 'origin/main' into restart 2025-06-24 01:24:43 +02:00
Markus Unterwaditzer
a21c9af354 Restart when config is set 2025-06-24 01:12:46 +02:00
Markus Unterwaditzer
0c241aba23 Address review comments 2025-06-23 14:30:40 -07:00
Markus Unterwaditzer
b2502847a1 Add ZIP download endpoint 2025-06-23 14:30:40 -07:00
Markus Unterwaditzer
be6f29dcf1 Add exponential backoff 2025-06-23 22:47:34 +02:00
Markus Unterwaditzer
2114206909 Remove advanced options 2025-06-23 21:24:04 +02:00
Markus Unterwaditzer
f735f033d3 Fix indentation 2025-06-23 21:13:41 +02:00
Markus Unterwaditzer
b825174a07 Apply suggestions from code review
Co-authored-by: Will Greenberg <ifnspifn@gmail.com>
2025-06-23 21:03:01 +02:00
Markus Unterwaditzer
29823d3e82 Update documentation and fix broken links
* Add a new configuration page and move content out from TP-Link. The
  Configuration section in TP-Link is duplicating what is already in
  config.toml.example, and given that we have recently added a lot of
  new options I don't want to maintain multiple copies.

* Lots of anchor links were broken since we moved docs from README into
  mdbook. Fix them all.

* Document that the key input feature is disabled since 0.4.0.

* Smaller cosmetic changes:

  * Make TP-Link M7350 page consistent with TP-Link M7310 page.
  * Fix indentation on some bullet points.
  * Center-align the rayhunter logo in introduction.md to calm my soul.
    It is still misaligned with the page title above itself.
  * Add "edit on github" link in mdbook settings.
2025-06-23 09:40:20 -07:00
Markus Unterwaditzer
e52d382514 Make SvelteKit build reproducible 2025-06-23 09:38:00 -07:00
Markus Unterwaditzer
a17e255148 un-skip jobs for testing 2025-06-23 09:38:00 -07:00
Markus Unterwaditzer
0f98b05475 Try out rust-cache action 2025-06-23 09:38:00 -07:00
Markus Unterwaditzer
5e5514a11f Fix key_input blocking shutdown
Discovered in #351 where restart would hang forever.

key_input.rs never properly implemented shutdown because it didn't have
to do anything interesting on shutdown.

Wire up oneshot channels so that it falls in line with other services.

I do wonder though if there's a more clever way of handling this. For
example I could just not use the task_tracker, use tokio::spawn and let
the task get cancelled by tokio.
2025-06-21 23:57:54 +02:00
Markus Unterwaditzer
9904b74d21 basic ui 2025-06-20 11:47:40 +02:00
Markus Unterwaditzer
d166dfc13d get config and set config 2025-06-20 11:47:40 +02:00
Markus Unterwaditzer
9b759e6b42 add basic restart endpoint 2025-06-20 11:47:40 +02:00
oopsbagel
5614c725a0 Merge pull request #418 from EFForg/tplink-hotfix-v9
Fix broken installer on TP-Link M7350 v9
2025-06-20 08:09:40 +00:00
oopsbagel
5a7fc2a063 Merge pull request #387 from oopsbagel/wingtech-ct2mhs01
feat: support Wingtech CT2MHS01 hotspot
2025-06-20 08:00:56 +00:00
Markus Unterwaditzer
e601320b3f Fix broken installer on TP-Link M7350 v9
TP-Link v9 was inadvertently broken via https://github.com/EFForg/rayhunter/pull/390
2025-06-20 02:01:55 +02:00
Cooper Quintin
0b05d1617c enable null cipher heuristic by default in config 2025-06-18 13:32:37 -07:00
Cooper Quintin
e7ba02173a update heuristic docs 2025-06-18 13:32:37 -07:00
Cooper Quintin
0b0dd4ed43 add file extensions to downloads, fixes #397 2025-06-18 13:32:37 -07:00
Markus Unterwaditzer
f2ff1be2ec Disable input keys by default
People say it's too easy to press, see #404
2025-06-18 08:44:26 -07:00
Markus Unterwaditzer
9f9adea5a1 Debounce key input events 2025-06-18 08:05:35 -07:00
Markus Unterwaditzer
cb2092d14f Fix last_message_time showing as 1970 when capture is 0 bytes
This is the same bug as #224, but regressed in the new UI
2025-06-17 16:38:49 -07:00
Cooper Quintin
76cdb3ecf1 re-add warning again 2025-06-17 16:30:22 -07:00
Cooper Quintin
bee5152381 re enable null cipher test 2025-06-17 16:30:22 -07:00
Cooper Quintin
2634271715 re-enable null cipher and update docs 2025-06-17 16:30:22 -07:00
Cooper Quintin
58913314aa helpful comment 2025-06-17 16:30:22 -07:00
Cooper Quintin
4f5bf4aa78 silence logging and point to specific revision and re-add warning 2025-06-17 16:30:22 -07:00
Cooper Quintin
bfc85c5103 re enable null cipher test 2025-06-17 16:30:22 -07:00
Cooper Quintin
7923327ba9 update binary name. Fixes #128 2025-06-17 16:30:22 -07:00
oopsbagel
3ff714972c fix(installer/wingtech): parse json login response
Use serde via reqwest to deserialize the login response from qcmap_auth
when obtaining an authentication token instead of golfing based on the
specific token length.
2025-06-16 00:38:28 -07:00
oopsbagel
a5d8e601d9 Merge pull request #399 from oopsbagel/fix-blame-ignore-rev-file
chore/fix: fix blame ignore rev file rev
2025-06-16 03:42:57 +00:00
oopsbagel
5272a99fb5 chore/fix: fix blame ignore rev file rev
Due to rebasing, this pointed to a nonexistent commit.
2025-06-15 20:40:50 -07:00
oopsbagel
5d61ad53b4 Merge pull request #394 from EFForg/readme-404
Fix broken CI badge in README
2025-06-16 03:32:22 +00:00
Markus Unterwaditzer
88ee4fc87e Fix broken CI badge in README 2025-06-14 17:13:30 +02:00
oopsbagel
8aadfc20f2 fix(installer/wingtech): remove duplicated struct 2025-06-13 22:00:20 -07:00
oopsbagel
a234df1e1e fix(installer/wingtech): only say ok if telnet connected 2025-06-13 21:39:12 -07:00
oopsbagel
de25008742 Merge pull request #392 from EFForg/ci-restore-main-workflow-call
fix(ci): restore deleted workflow_call trigger
2025-06-14 02:45:25 +00:00
oopsbagel
185da9cb36 fix(ci): explain why workflow_call: is needed 2025-06-13 19:42:38 -07:00
oopsbagel
c366eb9e4d fix(ci): restore deleted workflow_call trigger
This is required to call this workflow from another workflow, such as
the release.yml workflow.
2025-06-13 19:38:49 -07:00
oopsbagel
5dfbeaef64 Merge pull request #390 from EFForg/m7310
Add support for TP-Link M7310
2025-06-14 02:36:14 +00:00
oopsbagel
62e4c15eb5 Merge pull request #391 from EFForg/fix-workflow-main
Do not publish docs from any branch
2025-06-14 02:34:35 +00:00
Markus Unterwaditzer
02c98a8e8e Do not publish docs from any branch
Documentation was being pushed from an unrelated PR that I opened,
because that PR was created from a branch pushed to efforg instead of my
own fork.
2025-06-14 02:10:56 +02:00
Markus Unterwaditzer
6c02f56250 Add support for TP-Link M7310
The device is very similar to the M7350, and might as well just be
another hardware version.
2025-06-13 16:04:13 +02:00
oopsbagel
f56acdf89d fix(installer/wingtech): better Response variable 2025-06-12 12:46:08 -07:00
oopsbagel
cb6f79f67a ci: build wingtech 2025-06-12 01:11:01 -07:00
oopsbagel
95951c5c38 fix(display/mod.rs): remove "no device" check
This check is unnecessary, cargo will not build if fn update_ui is
undefined.
2025-06-12 01:04:29 -07:00
oopsbagel
241fb2789b fix(display/mod.rs): remove "many devices" check
This check is unnecessary, cargo will not build if multiple versions of
fn update_ui are defined.
2025-06-12 01:01:05 -07:00
oopsbagel
3a3adb055b fix(installer): wingtech adb error message 2025-06-12 00:45:52 -07:00
oopsbagel
3ae2636d9e chore(installer/build.rs): cargo clippy 2025-06-12 00:44:36 -07:00
oopsbagel
79b2628d2f chore: cargo fmt 2025-06-12 00:43:00 -07:00
oopsbagel
cba898daf6 feat(installer/util): telnet functions in util.rs
Add installer util wingtech-start-telnet command.
Add installer util wingtech-start-adb command.
2025-06-12 00:39:27 -07:00
oopsbagel
cb1df974e4 feat: support Wingtech CT2MHS01 hotspot
Add support for the Wingtech CT2MHS01 hotspot, a Qualcomm mdm9650-based
device with a screen available for US$15-35. This device is often used
as a base platform for while labeled versions like the T-Mobile TMOHS1.
AT&T branded versions of the hotspot seem to be the most abundant.

The device has a framebuffer-driven screen at /dev/fb0 that behaves
similarly to the Orbic RC400L, although the userspace program
`displaygui` refreshes the screen significantly more often than on the
Orbic. This causes the green line on the screen to subtly flicker and
only be displayed during some frames. Subsequent work to fully control
the display without removing the OEM interface is desired.
2025-06-11 18:06:50 -07:00
Markus Unterwaditzer
86e08f9a85 Allow enabling/disabling analyzers from config file (#382)
Co-authored-by: Will Greenberg <willg@eff.org>
2025-06-10 21:37:38 +02:00
Markus Unterwaditzer
fb2149f0c8 Loosen up issue templates
A lot of the bug report we receive are about the web UI or the installer
failing, and there things like capture date just don't matter. We could
create separate templates for these types of bugs, but I'd think it's
probably better to just have one textbox with a few "reminder" questions
that are all optional.

Feature request template I think doesn't have this issue.

Also allow the creation of blank issues, because some issues are more
related to CI or devenv and don't neatly fit in any category. Let's just
hope nobody abuses that?
2025-06-10 11:49:56 -07:00
oopsbagel
bf2b00ce47 doc(faq): send commands with installer util shell 2025-06-10 11:49:20 -07:00
oopsbagel
fd453900c2 doc(faq): format code correctly 2025-06-10 11:49:20 -07:00
oopsbagel
3d29c5f306 doc: add re-enabling USB tethering to the FAQ
Fixes issue #294
2025-06-10 11:49:20 -07:00
jrddupont
74623dea02 doc: Fix instructions for mac quarantine bit (#385) 2025-06-10 00:33:12 +02:00
Cooper Quintin
48e73a0a41 revert accidental futures upgrade 2025-06-06 12:44:39 -07:00
Cooper Quintin
a36863e002 bump version 2025-06-06 12:44:39 -07:00
oopsbagel
48aac0f0bb Merge pull request #380 from oopsbagel/fix-ci-env
ci: don't try to use env:
2025-06-06 19:33:50 +00:00
oopsbagel
5749c305c6 ci: don't try to use env:
I apparently don't know how this works.
2025-06-06 12:30:36 -07:00
oopsbagel
f53688086d ci: minor syntax and workflow order fixes 2025-06-06 12:21:24 -07:00
oopsbagel
bd2e0b4394 ci: release from actions, only test changed files
This commit introduces release automation triggered by button clicks in
Github Actions, guarded by a check on whether all the Cargo.toml files
contain the same version string.

On PRs, changes to documentation no longer trigger code tests.
Similarly, changes to code that don't update documentation do not
trigger documentation tests. Changes that fail at the `cargo check`
stage abort early to prevent lengthy CI builds of the installer and
firmware.

Commits on the `main` branch always run the full test suite regardless
of what changed.

Releases also run the full check, test, build and publish suite.
2025-06-06 12:21:24 -07:00
alli.sys
1eea086199 Merge pull request #375 from EFForg/eff-adb
Switch to the EFF org fork of adb_client
2025-06-05 21:28:06 -04:00
Sashanoraa
d36c1f10cd Switch to the EFF org fork of adb_client 2025-06-05 20:22:43 -04:00
Markus Unterwaditzer
8d8d2bd8ec Fix crash when deleting recordings
Due to a refactor in https://github.com/EFForg/rayhunter/pull/350, we
had to move more into the shared codepath of StopRecording. The todo!()
used to be unreachable when it was just in the stop-recording endpoint.

Fix #367
2025-06-05 09:28:31 -07:00
Cooper Quintin
f2b722ad5f version update 2025-06-04 10:12:08 -07:00
Cooper Quintin
5e2058e7ac update make to use firmware profile 2025-06-04 10:12:08 -07:00
cooperq
60daf4b716 update win docs 2025-06-04 10:11:12 -07:00
Cooper Quintin
4df317b028 dig deeper in the json tree. Fixes #360 2025-06-04 10:10:18 -07:00
Sashanoraa
d7fb8b9c85 Move most serial commands to usb shared USB claim with adb 2025-06-04 09:11:06 -07:00
Markus Unterwaditzer
d399532494 Add documentation for key input 2025-06-03 14:29:04 -07:00
Cooper Quintin
45df91a364 Update using-rayhunter.md 2025-06-03 14:23:50 -07:00
Matej Kovacic
672ed8c6c6 Update using-rayhunter.md 2025-06-03 14:23:50 -07:00
Matej Kovacic
5c7c7cd766 Add files via upload 2025-06-03 14:21:19 -07:00
Markus Unterwaditzer
f41a8d38fe move analysis into diag reader thread as well 2025-06-03 13:58:47 -07:00
Markus Unterwaditzer
f9c8c4671e Add basic key input 2025-06-03 13:58:47 -07:00
Markus Unterwaditzer
723b20541e Move business logic out of axum handlers 2025-06-03 13:58:47 -07:00
cooperq
272a4aeabf update docs 2025-06-03 11:49:20 -07:00
cooperq
6ae70556ba fix windows powershell installer and rust installer root process 2025-06-03 11:49:20 -07:00
Markus Unterwaditzer
2915dea9e9 Remove dead code and default features 2025-05-30 10:21:30 -07:00
Markus Unterwaditzer
6941bc57b6 Fix issues on TP-Link v9
* Fix autostart by adding another port trigger for rayhunter-daemon
* Use Orbic's IOCTL params as fallback
* Fix sdcard path and make it configurable
* Update docs to indicate support
* Add uninstalling instructions for TP-Link
2025-05-30 10:14:51 -07:00
Cooper Quintin
5b9dd856a8 version bump 2025-05-30 10:13:34 -07:00
Cooper Quintin
5007cb0b36 cargo fmt 2025-05-30 10:13:34 -07:00
Cooper Quintin
1b244122df add adb shell command 2025-05-30 10:13:34 -07:00
Cooper Quintin
3c4cb56ce6 surpress error messages by default, fixes #347 2025-05-30 10:13:34 -07:00
Cooper Quintin
58843413b5 update adb version which fixes adb key missing error. Fixes #330 2025-05-30 10:13:34 -07:00
Cooper Quintin
4ee504fed7 bump version to 0.3.1 2025-05-28 17:31:58 -07:00
Matej Kovacic
894af5da0d Update installing-from-release.md 2025-05-27 08:48:49 -07:00
Matej Kovacic
d810e8e3c0 Update tplink-m7350.md 2025-05-27 08:45:57 -07:00
Markus Unterwaditzer
8755d5694c Fix installing from source
Due to recent build changes, --release no longer applies the right
optimization settings, and --profile firmware has to be used.
2025-05-27 08:36:00 -07:00
Caleb
70a7d81d05 Add spinning orca for loading 2025-05-23 15:01:56 -07:00
Caleb
c182543dfa Resize logo images 2025-05-23 15:01:56 -07:00
Caleb
056f4c02e5 Fix table overflowing 2025-05-23 15:01:56 -07:00
Caleb
237983a8cb Add logo 2025-05-23 15:01:56 -07:00
Cooper Quintin
9967f93af2 foo 2025-05-23 11:54:14 -07:00
Cooper Quintin
3358a06454 look for other orbic PID 2025-05-23 11:54:14 -07:00
cooperq
382702a9ee blah 2025-05-23 11:54:14 -07:00
cooperq
67c3eb7d91 experiment 2025-05-23 11:54:14 -07:00
cooperq
98b05bfdb0 add install.ps1 to release zip 2025-05-23 11:54:14 -07:00
cooperq
01d10b87b3 more bugfix 2025-05-23 11:54:14 -07:00
Cooper Quintin
410e902848 fix more issues with windows installer 2025-05-23 11:54:14 -07:00
cooperq
f03f9fcdae more bugfix 2025-05-23 11:54:14 -07:00
Markus Unterwaditzer
4b68c30ed3 add note about sleep 2025-05-23 11:02:18 -07:00
Markus Unterwaditzer
b5481331c2 add windows instructions for tplink 2025-05-23 11:02:18 -07:00
Markus Unterwaditzer
ace65a8e55 Update docs for tplink to make clear which versions don't work 2025-05-23 11:02:18 -07:00
Markus Unterwaditzer
920044a5b2 Mention quarantine bit on macOS
See #323
2025-05-23 10:53:05 -07:00
Sashanoraa
6cb9a195ed Add env_logger to installer
Some libraries, namely nusb, produce debug logging that we might want to
access in the field.
2025-05-23 10:43:14 -07:00
Markus Unterwaditzer
90e2bddbbb Make Delete All Recordings more robust against missing recordings
For some reason, some QMDL files are missing on my device. In this
situation Delete All Recordings should not fail on the first missing
file.
2025-05-19 11:02:25 -07:00
Sashanoraa
3fa583f671 Re-enable debug info and unwind for non-firmware binaries 2025-05-19 09:51:36 -07:00
Caleb
8e6b86b26f Add ability to get qmdl file size in user readable values 2025-05-19 09:49:44 -07:00
Caleb
d40d4fb9c1 Fix alignment for analysis views 2025-05-19 09:49:44 -07:00
Caleb
a12bc4075e Tweak UI and text 2025-05-19 09:49:44 -07:00
Caleb
51327917b0 Change system information table 2025-05-19 09:49:44 -07:00
Caleb
4982463b57 Add seperate card for current recording and recording controls 2025-05-19 09:49:44 -07:00
Caleb
68aafd41e1 Add arrow for analysis view toggle 2025-05-19 09:49:44 -07:00
Caleb
8b053a9ef8 Add pill css for warnings 2025-05-19 09:49:44 -07:00
Caleb
ace325a38a Fix alignment of Analysis view 2025-05-19 09:49:44 -07:00
Caleb
6d02731a81 Additional mobile manifest card UI tweaks 2025-05-19 09:49:44 -07:00
Caleb
69b7fecb17 Add links to github and docs 2025-05-19 09:49:44 -07:00
Caleb
279169257d Add card based manifest entries for mobile 2025-05-19 09:49:44 -07:00
Caleb
9a60e3f820 Add dropshadows and other small UI changes 2025-05-19 09:49:44 -07:00
Caleb
77e51ec2f6 Fix Table UI and ControlBar UI 2025-05-19 09:49:44 -07:00
Caleb
c9c92706bc Fix margins 2025-05-19 09:49:44 -07:00
Caleb
643fa9f979 Add header 2025-05-19 09:49:44 -07:00
Caleb
96a02763e4 Fix margins sizes based on screen size 2025-05-19 09:49:44 -07:00
Caleb
ff421de127 Fix max height of analysis view for better mobile experiance 2025-05-19 09:49:44 -07:00
Caleb
635c8a0188 Fix capitalization of version 2025-05-19 09:49:44 -07:00
Cooper Quintin
5b8a0ef8d4 Update installing-from-release.md 2025-05-19 09:31:00 -07:00
Caleb
757b053a33 [DOCS] Fix install extract instructions 2025-05-19 09:31:00 -07:00
oopsbagel
5d9bc27ac9 Merge pull request #319 from EFForg/powershell
fix issues with powershell installer
2025-05-17 00:02:05 +00:00
cooperq
7d45be4f0c fix issues with powershell installer 2025-05-16 16:50:07 -07:00
Cooper Quintin
d58881c1f5 Merge branch 'kevstewa-main' 2025-05-16 13:16:24 -07:00
Kevin Stewart
4e16c7f9ce Merge remote-tracking branch 'upstream' 2025-05-16 13:10:50 -07:00
Kevin Stewart
c6d0cccb76 Switch release artifact to zip with SHA256
This change updates the build_release_zip workflow job to create and
upload a .zip archive and its corresponding .sha256 checksum file
instead of a .tar archive.
2025-05-16 12:37:47 -07:00
Cooper Quintin
f2d32512aa bump installer version 2025-05-16 12:19:03 -07:00
Cooper Quintin
e463d40c07 bump version to 0.3.0 2025-05-16 12:19:03 -07:00
Markus Unterwaditzer
c8edacf1ed rootshell, and add missing --release 2025-05-16 11:59:39 -07:00
Markus Unterwaditzer
ce8260b92c Update documentation for Rust installer 2025-05-16 11:59:39 -07:00
Sashanoraa
d6e4f6a71d Always include firmware binaries statically into installer 2025-05-16 11:48:23 -07:00
Sashanoraa
a2269fb5f7 Clean up function names and fix clippy warning 2025-05-16 11:48:23 -07:00
Sashanoraa
1c4e9b8499 Switch to having the rev for adb_client in Cargo.toml 2025-05-16 11:48:23 -07:00
Sashanoraa
fce30a78a2 Add special case to avoid hang on macOS 2025-05-16 11:48:23 -07:00
Sashanoraa
6a16ad7f15 Add special case for PermissionDenied on macOS
On macOS this can mean the device is busy.
2025-05-16 11:48:23 -07:00
Sashanoraa
ec5bd81a70 Update adb_client, now with usb lib being a feature flag
This update also fixes libusb throwing timeouts when it shouldn't
2025-05-16 11:48:23 -07:00
Sashanoraa
fbce9c8b04 Update adb_client to usb libusb on window and macOS 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
92b825a9e3 reset language for v3 after installation 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
c285e2ca08 Various fixes for TP-Link
* explicitly mount the SD card to improve reliability
* do not crash when the SD card is already mounted
* address some review feedback
2025-05-16 11:48:23 -07:00
Sashanoraa
4a7452806d Update adb_client with session fix 2025-05-16 11:48:23 -07:00
Sashanoraa
2e85d4f186 Switch adb_client back to the rayhunter branch
We've confirmed nusb works so I've merged it into the rayhunter branch.
2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
e3acfe9144 Update documentation and remove old installer scripts 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
7418cc19b3 fix for tplink v5.2 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
cc72f1eabc fix clipppy 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
e071bc6619 Add basic installer for TP-Link v5 2025-05-16 11:48:23 -07:00
Sashanoraa
60015e0ff6 Add serial subcommand to installer 2025-05-16 11:48:23 -07:00
Sashanoraa
bbcf23899e Remove the "install-*" prefix from the install commands 2025-05-16 11:48:23 -07:00
Sashanoraa
c97212cdc8 Switch to read_exact in tp-link telnet_send_command 2025-05-16 11:48:23 -07:00
Sashanoraa
894f457751 Update adb_client to remove unneeded deps from tcp 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
da34c05364 Simplify the tplink installer
Found an exploit that requires fewer HTTP requests and can be run
without auth.
2025-05-16 11:48:23 -07:00
Sashanoraa
30d62b8d7b Add Orbic support for the Rust installer and some common improvements 2025-05-16 11:48:23 -07:00
Sashanoraa
1f7b7f0f1a Move serial into the installer in prep for Orbic support 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
da53ec9df2 move to tplink module 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
0beff5ea63 fix path 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
a946ebbe92 remove default features from hyper 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
64a87534ee fix up ci, build installer in actions 2025-05-16 11:48:23 -07:00
Markus Unterwaditzer
4a94545498 Tplink M7350 installer v3 in Rust
It does the same thing as https://github.com/EFForg/rayhunter/pull/272
but only installs necessary files. Installation happens entirely over
the network so there is no dependency on ADB.

Currently can be used like this:

1. cargo build --bin rayhunter-daemon --target armv7-unknown-linux-gnueabihf --release --no-default-features --features tplink
2. cp target/armv7-unknown-linux-gnueabihf/release/rayhunter-daemon dist/rayhunter-daemon-tplink
3. cargo run --bin installer -- install-tplink
2025-05-16 11:48:23 -07:00
Caleb
9e532ac975 Fix mismatch in padding from table header and table rows 2025-05-16 11:29:39 -07:00
Caleb
35e3c80313 Add RayHunter branding colors to TailwindCSS 2025-05-16 11:29:39 -07:00
Caleb
221c3591fd Change trashcan icon to white 2025-05-16 11:29:39 -07:00
Caleb
cf0061fe53 fix analysis collapsing 2025-05-16 11:29:39 -07:00
strasharo
5bd2909c0d Fix typo in SUMMARY.md 2025-05-14 10:14:55 -07:00
Kevin Stewart
3e1eb9d5e6 Create versioned release tarball
The release workflow now produces a tarball named
`rayhunter-v<version>.tar`, where the version is dynamically extracted
from `rayhunter/bin/Cargo.toml`. Additionally, the archive contains a
top-level directory named `rayhunter-v<version>/`, making each release
artifact clearly identifiable and self-contained by version. This change
improves clarity for downstream consumers and simplifies managing
multiple versions.
2025-05-13 15:12:03 -07:00
oopsbagel
adfe081eaf Merge pull request #309 from untitaker/tplink-doc
Add basic docs for TP-Link
2025-05-13 03:03:46 +00:00
Markus Unterwaditzer
f165dddd0c fix check mark on orbic.md 2025-05-13 01:22:55 +02:00
Markus Unterwaditzer
214375ead2 split out orbic too 2025-05-13 01:21:57 +02:00
Markus Unterwaditzer
0d4514a332 Add basic docs for TP-Link 2025-05-13 01:18:52 +02:00
oopsbagel
5180205144 doc: uninstalling.md: fix code block 2025-05-12 16:10:39 -07:00
Will Greenberg
5ed1a9bae3 rm broken doc link 2025-05-12 16:10:39 -07:00
Will Greenberg
abc3c07201 Migrate README content to the mdbook 2025-05-12 16:10:39 -07:00
oopsbagel
98ee6dacf8 doc(building bin/web): also run npm install 2025-05-12 13:01:15 -07:00
oopsbagel
a9f1284fa6 docs: publish mdbook in doc to github pages
This commit adds an mdbook for rayhunter documentation in `doc`, and
actions workflows to publish that documentation to github pages.

This commit configures actions to publish to pages via artifact uploads,
but but can be adjusted to publish based solely on a branch.[0]
This was chosen to allow for future flexibility in generating multiple
outputs (such as a single page html document or pdf).

[0] https://docs.github.com/en/pages/getting-started-with-github-pages/configuring-a-publishing-source-for-your-github-pages-site
2025-05-12 13:00:45 -07:00
oopsbagel
d31bf45f95 Merge pull request #304 from EFForg/docs/update-frequency
[DOCS] Update README.md to Explicitly State Supported Bands
2025-05-06 03:25:50 +00:00
Alexis
8e8a28ae26 Update README.md to Explicitly State Supported Bands
Had to check around forums and docs just to find this info so just dumped here. Take it or leave it though if this exists somewhere else.

Also, areWiFi bands needed? Probably not but left it just in case.
2025-05-06 11:17:04 +09:00
oopsbagel
a7a5221c90 ci: remove duplicated ISSUE_TEMPLATE directory
We only need the files in .github/ISSUE_TEMPLATE
2025-04-28 17:31:00 -07:00
Cooper Quintin
469a716b7c add make script using docker 2025-04-28 17:19:46 -07:00
Cooper Quintin
c569101c36 Merge branch 'main' into frontend-rework 2025-04-28 17:19:28 -07:00
oopsbagel
b9945827c4 Merge pull request #298 from untitaker/ref/readme-orbic
Add disclaimer about country support
2025-04-28 19:28:32 +00:00
Markus Unterwaditzer
f97bc56f2c Add disclaimer about country support
More users are discovering this repo and buy Orbic devices for countries
where the device doesn't work.
2025-04-26 01:06:03 +02:00
oopsbagel
55ba316046 Merge pull request #297 from EFForg/wgreenberg-patch-1
unzip -> decompress
2025-04-25 19:21:39 +00:00
Will Greenberg
5ae6f0c5ce unzip -> decompress 2025-04-25 12:05:31 -07:00
Markus Unterwaditzer
7e1b410f89 add clippy to CI 2025-04-25 11:57:33 -07:00
Markus Unterwaditzer
32b67df55d Fix clippy lints and upgrade deku
Old version of deku was throwing clippy lints in generated code
2025-04-25 11:57:33 -07:00
oopsbagel
a8087c6840 cargo/config: show apt pkgs for gnueabihf 2025-04-25 11:55:23 -07:00
oopsbagel
f2028a704f tools: target armv7 musleabihf 2025-04-25 11:55:23 -07:00
oopsbagel
e04b78f0e0 ci: use rust-lld for all release targets
Removes dependency on gcc-based cross-compilation toolchain.
2025-04-25 11:55:23 -07:00
Will Greenberg
ece589331f bin: rm unused debug mode functionality
With the new svelte-based frontend, there's a better local debug mode
using `npm run dev`
2025-04-24 13:52:11 -07:00
Will Greenberg
b95ff90e5e cargo fmt 2025-04-24 13:23:29 -07:00
Will Greenberg
33745bc4e2 add rayhunter version to web UI, better row colors 2025-04-24 10:33:18 -07:00
Will Greenberg
73682240d6 fix more CI 2025-04-23 11:27:56 -07:00
Will Greenberg
43324c0ad7 add title and darken the green 2025-04-23 11:09:52 -07:00
Will Greenberg
f559e10d44 rm git detritus 2025-04-23 11:09:10 -07:00
Will Greenberg
f28022920a fix CI 2025-04-23 11:08:54 -07:00
Cooper Quintin
63b07b83f5 darker links 2025-04-22 16:37:35 -07:00
Cooper Quintin
934e0d70d8 change refresh time to 1sec 2025-04-22 16:27:57 -07:00
Cooper Quintin
769826dcea check if metadata exists and handle gracefully 2025-04-22 12:11:23 -07:00
Cooper Quintin
e4bfa7a1f3 Merge branch 'main' into frontend-rework 2025-04-22 11:41:51 -07:00
Tyler Cipriani
d95da9b382 README: clarify "unzip" instructions
The current `release.tar` (v0.2.7)  lacks a `release` directory -- all
files live at the root of the tar archive. But the README's Unzip
instructions mention `cd`ing to `~/Downloads/release`, which implies
that there is a `release` directory inside the tar.

Rather than verify with `tar --list --file ~/Downloads/release.tar` I
made a bad assumption, ran `tar xvf ./release.tar` in my `~/Downloads`,
and then had to clean up my `~/Downloads` directory.

This update clarifies that users should create the directory and extract
the tar into that directory.
2025-04-22 11:39:06 -07:00
Cooper Quintin
941ea59e11 I forgot rootshell and telecom parser 2025-04-22 11:04:42 -07:00
Cooper Quintin
8082e013f4 bump version 2025-04-22 11:04:42 -07:00
Cooper Quintin
f72194ab3e remove demo file 2025-04-22 10:12:45 -07:00
Cooper Quintin
3b1547c749 delete package lock and yarn lock from repo 2025-04-22 10:11:37 -07:00
Cooper Quintin
af17788a36 add package lock to gitignore 2025-04-22 10:10:41 -07:00
Cooper Quintin
1a8010964e Merge branch 'main' into frontend-rework 2025-04-22 10:09:26 -07:00
Cooper Quintin
a7ce1ad4d3 update mm invite 2025-04-18 12:41:25 -07:00
Markus Unterwaditzer
531e9aa6fb this documentation is also not useful to end users 2025-04-17 09:46:23 -07:00
Markus Unterwaditzer
833d0e41b4 more cleanup 2025-04-17 09:46:23 -07:00
Markus Unterwaditzer
056cdac546 remove Silicon from Mac, we do support intel 2025-04-17 09:46:23 -07:00
Markus Unterwaditzer
6ea2b0a4e6 Remove outdated instructions from README
`cargo test_pc` is not a thing, remove these instructions although there
currently is no replacement.
2025-04-17 09:46:23 -07:00
Will Greenberg
d3f70fee01 show informational logs, skipped reasons, and some formatting fixes 2025-04-16 14:31:16 -07:00
Will Greenberg
2ee4ab5082 update location of static images 2025-04-16 13:03:33 -07:00
Will Greenberg
7708efd0c9 Update README w/ frontend info, clarify some parts
Also fixes a typo in `install-dev.sh`
2025-04-16 13:02:54 -07:00
Will Greenberg
6b15f807df bring back images 2025-04-16 11:00:01 -07:00
Will Greenberg
0a1f9f4de1 rm unused import 2025-04-16 10:57:46 -07:00
Will Greenberg
fb1d550793 when deleting all, close the current recording first 2025-04-16 10:57:33 -07:00
Will Greenberg
2fc0144905 update make script to build site 2025-04-16 10:57:18 -07:00
Will Greenberg
fb1657676e rm old frontend code, add favicon 2025-04-15 18:21:58 -07:00
Will Greenberg
bb5c288c2f rm unused function 2025-04-15 18:21:10 -07:00
Will Greenberg
d63f419fbc parity with current UI 2025-04-15 18:08:18 -07:00
Will Greenberg
a33c7511eb better controls, formatting, etc 2025-04-14 20:05:00 -07:00
Markus Unterwaditzer
1cc5eb4c4c README: Do not mention SD card
Apparently SD card is not a thing on Orbic, only on TP-Link.
2025-04-14 16:42:09 -07:00
Will Greenberg
c4b2c3bbe2 better start/stop buttons 2025-04-14 15:52:51 -07:00
Will Greenberg
d9c58129ff longer poll period 2025-04-14 15:06:08 -07:00
Will Greenberg
41d3b4ed39 wip 2025-04-14 12:01:41 -07:00
Will Greenberg
4113b71baf fixed most svelte issues 2025-04-14 11:59:55 -07:00
Will Greenberg
4f0bc3ad93 update prerender location 2025-04-14 11:59:55 -07:00
Will Greenberg
cf2d406d88 wip 2025-04-14 11:59:55 -07:00
Will Greenberg
057c9acb40 wip 2025-04-14 11:59:54 -07:00
Will Greenberg
57b0455363 wip 2025-04-14 11:55:50 -07:00
Will Greenberg
fa96520fe5 wip 2025-04-14 11:54:27 -07:00
Will Greenberg
a269a45244 wip 2025-04-14 11:54:27 -07:00
oopsbagel
99676f1590 chore: add blame ignore rev file
Do not display formatting commit in git blame. Use this file locally by running:

git config blame.ignoreRevsFile .git-blame-ignore-revs

This file is read by github automatically.[0]

[0] https://docs.github.com/en/repositories/working-with-files/using-files/viewing-and-understanding-files#ignore-commits-in-the-blame-view
2025-04-14 11:49:24 -07:00
oopsbagel
9fe75ac961 chore: cargo fmt 2025-04-14 11:49:24 -07:00
Markus Unterwaditzer
151e186ef9 Fix delete all recordings, and panic on server startup
* Delete All Recordings did not work when recording was paused
* Because of the upgrade to axum 0.8, the webserver did not actually
  start but panic.
2025-04-11 12:42:23 -07:00
Cooper Quintin
06c4dd468e Merge branch 'untitaker-build-features' 2025-04-11 11:30:23 -07:00
Markus Unterwaditzer
740f979293 Merge remote-tracking branch 'origin/main' into build-features 2025-04-11 20:15:18 +02:00
oopsbagel
700258b0f2 ci: test build release on PRs 2025-04-11 11:13:07 -07:00
oopsbagel
f661e2e318 ci(windows): compile serial for x86_64-pc-windows-gnu 2025-04-11 11:13:07 -07:00
Markus Unterwaditzer
b12a159f0a Merge remote-tracking branch 'origin/main' into build-features 2025-04-11 19:57:15 +02:00
oopsbagel
4e40994577 ci: add windows target for serial 2025-04-11 10:42:29 -07:00
Cooper Quintin
1b29cf0dee Merge branch 'main' into build-features 2025-04-11 10:38:49 -07:00
Markus Unterwaditzer
aafd83d636 Upgrade axum to reduce binary size
For some reason upgrading axum to 0.8 reduces the binary size by 300kB
2025-04-11 10:32:02 -07:00
oopsbagel
dd67fbf645 ci: statically compile serial binary
fix unreleased rayhunter-check binary names
2025-04-11 10:30:38 -07:00
Markus Unterwaditzer
e440dab736 Add dockerfile for easier building on MacOS 2025-04-11 10:09:35 -07:00
oopsbagel
30e543898b ci: add windows-latest (x86_64) release 2025-04-11 10:07:02 -07:00
oopsbagel
01e762a3d6 fix(lib): enable building for windows targets
- conditionally build diag_device.rs only for unix
- use build time target for runtime metadata on unix
2025-04-11 10:07:02 -07:00
oopsbagel
fa9e9319c2 fix(serial.enable_command_mode): claim usb device interface
Windows does not support nusb::Device.control_out_blocking

Claim the interface before writing as required on Windows.
2025-04-11 10:07:02 -07:00
oopsbagel
b317200307 ci: add windows serial cargo check and test 2025-04-11 10:07:02 -07:00
Markus Unterwaditzer
55f78cf749 Document what the red line means
Fix https://github.com/EFForg/rayhunter/issues/134
2025-04-10 16:51:28 -07:00
Markus Unterwaditzer
cb9e8254a8 cargo fmt 2025-04-09 15:37:20 +02:00
Markus Unterwaditzer
a9afa347f0 turn pixelart macro into const expr 2025-04-09 15:37:03 +02:00
zoracon
75944a7d16 Fix template bugs 2025-04-08 15:53:27 -07:00
Markus Unterwaditzer
e11bb2518e fix tests 2025-04-08 21:33:41 +02:00
Markus Unterwaditzer
31076ec8b2 replace with exclamation mark 2025-04-08 21:24:33 +02:00
Markus Unterwaditzer
5e22b5c6a8 Update bin/src/display/tplink_onebit.rs
Co-authored-by: Will Greenberg <ifnspifn@gmail.com>
2025-04-08 21:21:36 +02:00
Markus Unterwaditzer
3dc373f0d3 add code comment 2025-04-08 21:21:20 +02:00
Markus Unterwaditzer
bccdcf36e1 Merge remote-tracking branch 'origin/main' into build-features 2025-04-08 21:16:08 +02:00
Will Greenberg
fb9c4ab85b Update pull_request_template.md 2025-04-08 09:57:23 -07:00
Will Greenberg
e864ce0a51 Add PR template 2025-04-08 09:57:23 -07:00
zoracon
7f990ae4bd Move issue templates to correct location 2025-04-08 09:56:13 -07:00
Sashanoraa
3ac4acd83c Indent rootshell's code to 4 space like everything else
It was three for some reason.
2025-04-08 08:59:40 -07:00
Markus Unterwaditzer
5c5333f0c7 Remove RecordingCBM
Colorblind mode is a property of the respective display, and decision
whether to display something in colorblind mode should lie with the
display thread. The display thread already needs to know about
colorblind mode for the initial state.

In #226, there are multiple implementations of display thread, and at
least one of them is dealing with a one-bit display anyway.

Aside, I think rayhunter should send an initial DisplayState on startup,
UI threads should not assume that the device is already recording. But
this can be discussed separately.
2025-04-08 08:58:08 -07:00
Sashanoraa
60934e593b Add the content length header to the qmdl file response 2025-04-08 08:54:39 -07:00
oopsbagel
4099eb30a5 ci: build on ubuntu-24.04-arm (aarch64) 2025-04-08 08:53:56 -07:00
Evan Rusmisel
f81adad897 rusty 2025-04-08 08:47:54 -07:00
dependabot[bot]
775468f037 Bump tokio from 1.44.1 to 1.44.2
Bumps [tokio](https://github.com/tokio-rs/tokio) from 1.44.1 to 1.44.2.
- [Release notes](https://github.com/tokio-rs/tokio/releases)
- [Commits](https://github.com/tokio-rs/tokio/compare/tokio-1.44.1...tokio-1.44.2)

---
updated-dependencies:
- dependency-name: tokio
  dependency-version: 1.44.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-04-08 08:44:46 -07:00
Will Greenberg
91e825adff mac installer: if we've already removed quarantine bit, continue 2025-04-07 16:16:54 -07:00
Markus Unterwaditzer
499b86aca6 Add build features for multiple device types
The bin crate now has two features, one for each supported device.

* The IOCTL change from #142 is compiled in conditionally.
* Tp-link display is supported & tested for HW rev 3 and HW rev 5.

The release tarballs now contain two rayhunter-daemon binaries, for
orbic and tplink. An installer for tplink is not yet included.

Co-authored-by: m0veax <m0veax@chaospott.de>
2025-04-07 21:15:32 +02:00
Sashanoraa
7b897c335d Remove unneeded image dependencies
This removes a bunch of dependencies we aren't using and reduces the
binary size by 0.7 MB.
2025-04-04 12:30:57 -07:00
Sashanoraa
c47be1074b Add delete all recordings button to web ui 2025-04-04 12:21:51 -07:00
Sashanoraa
326d4106bd Add a delete option to each recording in the web view 2025-04-04 12:21:51 -07:00
Markus Unterwaditzer
df8a1f5606 Fix RecordingStore::create
Bug introduced in #225
2025-04-03 15:22:08 -07:00
Markus Unterwaditzer
b0f5296c20 disable quirks mode 2025-04-03 12:15:33 -07:00
Markus Unterwaditzer
4e792b1402 Fix rendering of last_message_time in UI
* last_message_time is shown inconsistently for current entry vs other
  entries -- deduplicate code
* last_message_time is N/A for undefined -- but the API response was
  null instead of undefined.
2025-04-03 12:15:33 -07:00
zoracon
9144259202 Add issue templates 2025-04-03 12:14:15 -07:00
Markus Unterwaditzer
58f0071864 Fix malformed QMDL store writes
Fix https://github.com/EFForg/rayhunter/issues/199
Fix https://github.com/EFForg/rayhunter/issues/151

rayhunter updates manifest files using write **without truncation**.
This means that if the new manifest is shorter than the old one,
trailing bytes of the old data will persist in the new file.

Switch over to atomic file writes so that this bug is fixed + rayhunter
behaves correctly if it is killed mid-write.

https://github.com/EFForg/rayhunter/pull/182 could be reverted as it
seems to mostly be a workaround.
2025-04-03 12:09:19 -07:00
oopsbagel
3c0716c877 feat(serial): replace all panics with error handling from anyhow
Support -h and --help arguments.
Print a better error message when the Orbic device is not found.
Replace every panic! with anyhow::bail!
Replace .expect() with .context()?
Wraps all function returns with anyhow::Result
2025-04-01 13:40:01 -07:00
Jeremy Blanchard
bf8f1fb8eb Add troubleshooting step for macOS 2025-04-01 12:23:39 -07:00
Jeremy Blanchard
2a808245fb Fix anchor link for setup section 2025-04-01 12:23:39 -07:00
Jeremy Blanchard
208ccbafaa Fix another rebase merge issue 2025-04-01 12:23:39 -07:00
Jeremy Blanchard
b150f9dc4f Fix header issue from the rebase 2025-04-01 12:23:39 -07:00
Jeremy Blanchard
b6ef48e0f6 Corrent path of unzipped folder 2025-04-01 12:23:39 -07:00
Jeremy Blanchard
fddb18546c Unify install scripts in docs 2025-04-01 12:23:39 -07:00
Jeremy Blanchard
2911838b1c Cleanup language and formatting 2025-04-01 12:23:39 -07:00
Jeremy Blanchard
adbe3991dd Improve installation doc clarity. Cleanup capitalization. 2025-04-01 12:23:39 -07:00
Sashanoraa
fbc47187c5 Create ServerState outside of run_server
This reduces the number of arguments of run_server to make clippy happy
and also makes the code easier to understand.
2025-03-27 11:57:01 -07:00
Sashanoraa
5f601a209e Collapse nested if statements 2025-03-27 11:57:01 -07:00
Sashanoraa
04652d2097 Add implement Default on types with ::new
This fixes a clippy lint warning
2025-03-27 11:57:01 -07:00
Sashanoraa
034e0632e4 Box some of the larger information element enum variants
An enum is always the size needed to store its largest variant. Some of
the variants of the InformationElement and LteInformationElement are
substantially larger than the rest. Boxing the larger variants reduces
the size of the enum, in some cases by several kilobytes.

Since Rust does not currently support destructing a Box via pattern
matching, some code that destructures these enums had to be modified.
2025-03-27 11:57:01 -07:00
Sashanoraa
4edf001ca4 Fix small clippy warnings 2025-03-27 11:57:01 -07:00
Sashanoraa
b41f61bfa6 Replace unnecessary File::options with File::create 2025-03-27 11:57:01 -07:00
Will Greenberg
46a5bf8a84 Add signal link 2025-03-27 11:18:39 -07:00
Will Greenberg
2ee45382fc Update README.md 2025-03-27 11:18:39 -07:00
cycloarcane
f507cc0269 Added an FAQ entry on how to use the rootshell to delete data from the device 2025-03-27 09:52:19 -07:00
Tim Kerby
0780b527b9 Update rayhunter_daemon for TPLINK Compatibility
TPLink devices dont have bash - only sh
2025-03-26 10:41:15 -07:00
Sashanoraa
b0a1b14160 Remove unused import due to e79dc4a
The referenced commit disabled the null-cipher but did not remove the
now unused import.
2025-03-26 10:41:05 -07:00
Sashanoraa
b7243dae62 Add missing Cargo.lock updates from 0.2.6 version bump 2025-03-26 10:40:26 -07:00
Sashanoraa
0c4a0123aa Add missing Cargo.lock changes from 9af8e00 2025-03-26 10:40:26 -07:00
Will Greenberg
9bc8a7892b fix typo in installer script 2025-03-26 10:22:17 -07:00
oopsbagel
431a97ca65 chore: bump all Cargo.toml versions to 0.2.6 2025-03-25 17:02:01 -07:00
Will Greenberg
0364bfbc98 bump version number
we uhh forgot to do this for every release lol
2025-03-25 16:53:20 -07:00
Ben Brown
996e47684c Fix typo on readme
sensetive -> sensitive
2025-03-25 16:52:16 -07:00
Cooper Quintin
266f2b2e53 more nesting 2025-03-25 16:49:08 -07:00
Will Greenberg
2080cd7845 web ui: fix issue causing no entries
We weren't correctly handling all possible events from the heuristics
list
2025-03-25 16:49:08 -07:00
oopsbagel
9af8e006b0 fix(serial): use tokio's timeout with USB bulk in/out
Replace futures_lite::future::block_on (which will block indefinitely) with
tokio::time::timeout to restore the original behaviour of this utility, where
communication over USB interface bulk endpoints times out after 1 second.
2025-03-25 16:46:35 -07:00
oopsbagel
e841e22774 refactor(serial): replace rusb with nusb
nusb is a pure Rust library providing the same low level access to USB devices
that rusb/libusb provide.

This commit removes rusb (and thus the dependence on libusb) and replaces it
with nusb in the serial utility.

The only functional change is that nusb does not support timeouts for bulk data
commands. nusb is async. This commit contains a naïve implementation that simply
blocks on bulk reads and writes in send_command().
2025-03-25 16:46:35 -07:00
Will Greenberg
0d9f53f602 Update make.sh
reboot the orbic instead of starting up the process again, since rootshell seems to have insufficient privileges to start rayhunter
2025-03-25 16:34:23 -07:00
Will Greenberg
c9dcbbe5d6 daemon: if we fail to parse the QMDL manifest, make a new one
If rayhunter doesn't exit cleanly (e.g. during a battery outage), the
QMDL manifest may end up in a corrupted state. If that's the case,
rayhunter should try to recover by creating a new manifest. This'll let
it continue, and will preserve previous recordings, but they won't be
visible through the UI.
2025-03-25 15:36:12 -07:00
Will Greenberg
61d6ff6510 Add an update section 2025-03-25 15:14:54 -07:00
Will Greenberg
e79dc4a8f0 lib: diable null-cipher heuristic due to false positives
Due to an upstream hampi bug (https://github.com/ystero-dev/hampi/issues/133),
our RRC parser is reporting false-positives for the null cipher
heuristic.
2025-03-25 15:13:36 -07:00
Will Greenberg
6204bc0195 update installer script for macOS Intel 2025-03-24 16:42:58 -07:00
Will Greenberg
65b9843e39 test macOS intel builds 2025-03-24 16:42:58 -07:00
Sashanoraa
d0d01089dd Fix various clippy warnings
This commit fixes various clippy warnings that do not affect the
function of the code and aren't stylistic in nature.
2025-03-24 13:47:20 -07:00
Sashanoraa
9c26e89b24 Modify config load to use serde default
This commit refactors the config loading code to no longer require a
separate ConfigFile struct by taking advantage of serde's `default`
attribute. This causes serde to use the Config struct's default value
for that attribute for any missing attributes, which is what the
existing code was doing anyway.

This also fixes several clippy warnings.

Serde docs: https://serde.rs/container-attrs.html#default
2025-03-24 13:47:20 -07:00
Sashanoraa
1f4786db19 Have rootshell print errors and exit 1 if exec fails
Previously was ignoring the possible error retuned by exec, this commit
has rootshell print the error if exec returns and have the process exit
with a code of 1 instead of 0.
2025-03-24 13:47:20 -07:00
Kirk Strauser
88f81d86fa Remove the quarantine bit from the serial command on macOS 2025-03-20 10:49:07 -07:00
oopsbagel
0b3c0de481 fix(lib/util): use better names for runtime metadata
- document RuntimeMetadata fields
- rename RayhunterMetadata to RuntimeMetadata
- rename RuntimeMetadata.os to RuntimeMetadata.system_os
- remove unpopulated hardware field
- remove unnecessary duplication of datastructure in analyzer harness
2025-03-19 11:48:54 -07:00
oopsbagel
188e9f436b fix(qmdl-manifest): store os/arch/hardware in qmdl manifest.toml
Do not superfluously prefix these names with rayhunter_, as they describe the
hardware and not the binary.
2025-03-19 11:48:54 -07:00
oopsbagel
f2b5aa2743 feat: show rayhunter version/os/arch in pcap, ndjson, qmdl manifest
Create a util mod to provide information about the rayhunter binary and
system.
2025-03-19 11:48:54 -07:00
oopsbagel
b785a7f21c feat(qmdl): add rayhunter version and os to manifest.toml 2025-03-19 11:48:54 -07:00
oopsbagel
09d35ccec7 feat(pcap): add operating system kernel name and release
Display the uname sysname and release as the OS option in the pcap Section
Header Block, falling back on just the std::env::consts::OS name ("linux") in
the case of runtime errors.

Co-authored-by: Nat Budin <natbudin@gmail.com>
2025-03-19 11:48:54 -07:00
oopsbagel
5ae186bc73 feat(pcap): add rayhunter name and version to metadata
Add the compile-time name and version to the pcap's Section Header Block
as the shb_userappl option, the canonical place for storing the name of
the application used to create the pcap.[0]

[0] https://ietf-opsawg-wg.github.io/draft-ietf-opsawg-pcap/draft-ietf-opsawg-pcapng.html#section-4.1-10
2025-03-19 11:48:54 -07:00
Inhishonor
c765a40426 Improve grammer. 2025-03-19 09:27:01 -07:00
Inhishonor
93cfbea361 Fix various sentences in README. 2025-03-19 09:27:01 -07:00
Cooper Quintin
8e6bed97b7 Merge branch 'allpoints-132_Merge_OS_variant_install_scripts' 2025-03-18 18:22:33 -07:00
Cooper Quintin
4214b27c0f fix nits in install.sh and update readme with new instructions 2025-03-18 18:21:43 -07:00
rbomze
f69487853a minimized the binary size 2025-03-18 17:59:07 -07:00
Jeremy
7eb61748d7 Update readme: Add link to PGP key for contact email address 2025-03-18 17:59:07 -07:00
Will Greenberg
ca4e560e92 Update README.md 2025-03-18 17:59:07 -07:00
Alexis
2ffb1d4620 Update SECURITY.md
Just fixing the relative link to this project
2025-03-18 17:59:07 -07:00
Cooper Quintin
77944dd17c add security file 2025-03-18 17:59:07 -07:00
rbomze
50301076f0 minimized the binary size 2025-03-18 17:37:24 -07:00
Jeremy
21c839678b Update readme: Add link to PGP key for contact email address 2025-03-17 11:24:19 -07:00
Will Greenberg
332a7ffbd0 Update README.md 2025-03-12 11:56:12 -07:00
Alexis
8d250553b7 Update SECURITY.md
Just fixing the relative link to this project
2025-03-11 15:35:47 -07:00
Cooper Quintin
fa897e73fa add security file 2025-03-11 14:53:28 -07:00
Paul Beltrani
c3494e338f Merge install scripts into a single, isntall.sh 2025-03-09 22:27:48 -04:00
Cooper Quintin
f9b2cd6a59 add link to code of conduct 2025-03-07 11:40:37 -08:00
Will Greenberg
eb072fb38c fix various typos 2025-03-07 11:28:29 -08:00
Will Greenberg
91f82fc71d add curl to apt install list 2025-03-07 11:21:36 -08:00
Will Greenberg
6fda8450dc a few more FAQ adjustments 2025-03-07 11:21:36 -08:00
Cooper Quintin
bbfe5877fe More FAQ work 2025-03-07 11:21:36 -08:00
Will Greenberg
75d3740f66 Add FAQ to readme 2025-03-07 11:21:36 -08:00
oopsbagel
94c576fd96 fix(tools): add pycrate dependency to requirements.txt
nasparse.py and nasparse_test.py require the pycrate_mobile and
pycrate_core libraries provided by the pycrate package.

This commit adds the required package to requirements.txt.
2025-03-07 11:08:20 -08:00
Cooper Quintin
ee83613757 update readme 2025-02-27 17:29:48 -08:00
Cooper Quintin
840f8ad8b0 stop before upload in case file is locked from writing by running process 2025-02-10 11:26:27 -08:00
Cooper Quintin
c9ac834ca7 show warnings in web UI 2025-02-10 11:26:27 -08:00
Cooper Quintin
8629aacf6b switch default to not see trace messages, switch arg from quiet to verbose 2025-02-10 11:26:27 -08:00
Cooper Quintin
a3fd1479f9 rename qmdl path so that downloaded files have a qmdl extension 2025-02-10 11:26:27 -08:00
Cooper Quintin
049c563f02 fix shortcodes on rayhunter_check 2025-02-10 11:26:27 -08:00
Cooper Quintin
a33b5a3418 Update README.md
Co-authored-by: Will Greenberg <willg@eff.org>
2025-01-31 17:00:44 -08:00
Cooper Quintin
107ba58296 warn if running install scritps from git tree 2025-01-31 17:00:44 -08:00
Cooper Quintin
d016279172 some tweaks to readme 2025-01-31 17:00:44 -08:00
Will Greenberg
5a084f1abb lib: set uplink flag for NAS 2025-01-30 11:33:14 -08:00
Will Greenberg
3619df32ab check: give qmdl-path a shorthand arg 2025-01-28 11:02:19 -08:00
Will Greenberg
34d87d1fd7 this macro isn't public, so docstrings won't work 2025-01-28 11:02:19 -08:00
Will Greenberg
da4952e70f fix docstring code 2025-01-28 11:02:19 -08:00
Will Greenberg
30323b8329 Keep old 2G downgrade analyzer 2025-01-28 11:02:19 -08:00
Will Greenberg
28b0f409db fix attribution 2025-01-28 11:02:19 -08:00
Will Greenberg
12640cc878 Rewrite our 2G downgrade analyzer 2025-01-28 11:02:19 -08:00
Will Greenberg
26eda5904f Better wording on IMSI requested warning 2025-01-28 11:02:19 -08:00
Will Greenberg
3e26e61b05 check: don't count informational events as warnings, better logging 2025-01-28 11:02:19 -08:00
Will Greenberg
565c0f1e67 serial: fix UTF-8 panic on macOS 2025-01-26 17:05:42 -08:00
267 changed files with 51948 additions and 10402 deletions

15
.cargo/audit.toml Normal file
View File

@@ -0,0 +1,15 @@
[advisories]
ignore = [
# RSA Marvin Attack in `rsa`, dragged in through rustcrypto (dev builds)
# and adb_client (USB signing only, unrelated to marvin attack which
# targets decryption).
"RUSTSEC-2023-0071",
# paste crate being unmaintained is not important. it's not dealing with
# user-input. we could get rid of this warning by disabling the image
# dependency in adb-client.
"RUSTSEC-2024-0436",
# rustls-webpki 0.102.8 CRL Distribution Point flaw (via rustls-rustcrypto).
# Only affects dev builds, production firmware uses ring-tls.
# TODO: Remove once rustls-rustcrypto releases a version newer than 0.0.2-alpha.
"RUSTSEC-2026-0049",
]

View File

@@ -1,3 +1,64 @@
[alias]
# Build the daemon with "firmware" profile and post-quantum TLS backend.
# Needs an arm-linux-musleabihf cross-compiler in PATH, e.g. a toolchain
# from https://musl.cc, or run inside messense/rust-musl-cross:armv7-musleabihf
# (which is what CI does, see .github/workflows/main.yml).
build-daemon-firmware = "build -p rayhunter-daemon --bin rayhunter-daemon --target armv7-unknown-linux-musleabihf --profile firmware --no-default-features --features pq-tls"
# Build the daemon with "firmware-devel" profile and "rustcrypto" backend.
# Works with just the Rust toolchain, and is medium-slow to build. Binaries are slightly larger.
build-daemon-firmware-devel = "build -p rayhunter-daemon --bin rayhunter-daemon --target armv7-unknown-linux-musleabihf --profile firmware-devel"
# Build rootshell for firmware
build-rootshell-firmware = "build -p rootshell --bin rootshell --target armv7-unknown-linux-musleabihf --profile firmware"
# Build rootshell for development
build-rootshell-firmware-devel = "build -p rootshell --bin rootshell --target armv7-unknown-linux-musleabihf --profile firmware-devel"
[target.aarch64-apple-darwin]
linker = "rust-lld"
rustflags = ["-C", "target-feature=+crt-static"]
[target.aarch64-unknown-linux-musl]
linker = "rust-lld"
rustflags = ["-C", "target-feature=+crt-static"]
# apt install build-essential libc6-armhf-cross libc6-dev-armhf-cross gcc-arm-linux-gnueabihf
[target.armv7-unknown-linux-gnueabihf] [target.armv7-unknown-linux-gnueabihf]
linker = "arm-linux-gnueabihf-gcc" linker = "arm-linux-gnueabihf-gcc"
rustflags = ["-C", "target-feature=+crt-static"] rustflags = ["-C", "target-feature=+crt-static"]
[target.armv7-unknown-linux-musleabihf]
linker = "rust-lld"
rustflags = ["-C", "target-feature=+crt-static"]
[target.armv7-unknown-linux-musleabi]
linker = "rust-lld"
rustflags = ["-C", "target-feature=+crt-static"]
# Disable rust-lld for x86 macOS because the linker crashers when compiling
# the installer in release mode with debug info on.
# [target.x86_64-apple-darwin]
# linker = "rust-lld"
# rustflags = ["-C", "target-feature=+crt-static"]
[target.x86_64-unknown-linux-musl]
linker = "rust-lld"
rustflags = ["-C", "target-feature=+crt-static"]
[profile.release]
# keep line numbers in stack traces for non-firmware binaries
debug = "limited"
lto = "fat"
opt-level = "z"
strip = "debuginfo"
[profile.firmware-devel]
inherits = "release"
opt-level = "s"
lto = false
# optimizations to reduce the binary size of firmware binaries
[profile.firmware]
inherits = "release"
strip = true
codegen-units = 1
panic = "abort"
debug = false

2
.git-blame-ignore-revs Normal file
View File

@@ -0,0 +1,2 @@
9fe75ac961c57e508bf7488ce51d596750fa8d37
76ffdf6bada515c9a5f63a600e6f1502288c147a

10
.gitattributes vendored Normal file
View File

@@ -0,0 +1,10 @@
# Files that are distributed onto the Rayhunter device always have to have
# Unix-style line endings, even if the installer is built on Windows with
# autocrlf enabled.
# Using CRLF for the init scripts will make them fail to execute on TP-Link.
# See https://github.com/EFForg/rayhunter/issues/489
dist/config.toml.in eol=lf
dist/scripts/misc-daemon eol=lf
dist/scripts/rayhunter_daemon eol=lf
scripts/*.sh eol=lf

25
.github/ISSUE_TEMPLATE/bug.yaml vendored Normal file
View File

@@ -0,0 +1,25 @@
name: Bug Report
description: File a bug report.
labels: ["bug"]
body:
- type: checkboxes
attributes:
label: Prerequisites
options:
- label: I have read [CONTRIBUTING.md](https://github.com/EFForg/rayhunter/blob/main/CONTRIBUTING.md)
required: true
- type: textarea
attributes:
label: Bug Report Details
description: |
Please provide the following information, if applicable:
placeholder: |
• **Rayhunter Version**: (e.g., v0.2.6)
• **Capture Date**: (YYYY-MM-DD, e.g., 2025-05-01)
• **Capture Location**: (If comfortable disclosing, what region or country were you in? e.g., Washington State)
• **Device and Model**: (Device you installed Rayhunter on, e.g., Orbic RC400L)
• **What happened?**: (What steps did you take to get to your issue? Tell us what you see!)
• **Expected behavior**: (Rayhunter's behavior differed from what I expected because...)
• **Relevant log output**: (Rayhunter data captures - QMDL and PCAP logs - or error codes)
validations:
required: true

10
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1,10 @@
blank_issues_enabled: false
contact_links:
- name: Frequently Asked Questions
url: https://efforg.github.io/rayhunter/faq.html
- name: Questions and community
url: https://efforg.github.io/rayhunter/support-feedback-community.html
about: If you're having trouble using Rayhunter and aren't sure you've found a bug or request for a new feature, please first try asking for help on GitHub discussions or Mattermost
- name: Rayhunter Security Policy
url: https://github.com/EFForg/rayhunter/security/advisories/new
about: Please report security vulnerabilities here.

32
.github/ISSUE_TEMPLATE/feature.yaml vendored Normal file
View File

@@ -0,0 +1,32 @@
name: Feature Request
description: Suggest a new feature or improvement to Rayhunter
labels: ["enhancement"]
body:
- type: checkboxes
attributes:
label: Prerequisites
options:
- label: I have read [CONTRIBUTING.md](https://github.com/EFForg/rayhunter/blob/main/CONTRIBUTING.md)
required: true
- type: textarea
id: problem
attributes:
label: What problem does this feature solve or what does it enhance?
description: Explain what this feature addresses, ors the benefit it provides.
placeholder: For example, "Currently, users have to manually do X, which is time-consuming."
validations:
required: true
- type: textarea
id: solution
attributes:
label: Proposed Solution
description: Describe the solution you'd like to see implemented.
placeholder: For example, "Implement a new button that automatically does X."
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives Considered
description: Have you considered any alternative solutions?
placeholder: For example, "We considered Y, but Z is a better approach because..."

View File

@@ -0,0 +1,53 @@
name: Installer Issue
description: File an bug related to an installer issue.
labels: ["bug", "installer"]
body:
- type: checkboxes
attributes:
label: Prerequisites
options:
- label: I have read [CONTRIBUTING.md](https://github.com/EFForg/rayhunter/blob/main/CONTRIBUTING.md)
required: true
- type: input
attributes:
label: Rayhunter Version
placeholder: 'v0.5.0'
validations:
required: true
- type: dropdown
attributes:
label: Device
description: |
What device are you trying to install Rayhunter on?
options:
- Orbic RC400L
- Tplink M7350
- Tplink M7310
- Tmobile TMOHS1
- Wingtech CT2MHS0
- Pinephone
- Other / I'm not sure
validations:
required: true
- type: dropdown
attributes:
label: Installer OS
description: What operating system are running the installer from
multiple: false
options:
- Linux
- macOS
- Windows
validations:
required: true
- type: textarea
attributes:
label: Describe the Issue
description: |
Please describe the issue you're having installing Rayhunter.
Include the logs outputed by the installer program. If the installer
is crashing, please try running the installer with `RUST_BACKTRACE=1`
environment variable set so we can see exactly where the installer is
crashing.
validations:
required: true

53
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,53 @@
# open-pull-requests-limit is used to disable automated version updates
# security updates are unaffected. see
# * https://docs.github.com/en/code-security/how-tos/secure-your-supply-chain/secure-your-dependencies/configuring-dependabot-version-updates#disabling-dependabot-version-updates
# * https://docs.github.com/en/code-security/reference/supply-chain-security/dependabot-options-reference#open-pull-requests-limit-
version: 2
updates:
# Rust dependencies
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 0
groups:
security:
applies-to: "security-updates"
patterns:
- "*"
# Python dependencies
- package-ecosystem: "pip"
directory: "/tools"
schedule:
interval: "weekly"
open-pull-requests-limit: 0
groups:
security:
applies-to: "security-updates"
patterns:
- "*"
# daemon/web Node.js dependencies
- package-ecosystem: "npm"
directory: "/daemon/web"
schedule:
interval: "weekly"
open-pull-requests-limit: 0
groups:
security:
applies-to: "security-updates"
patterns:
- "*"
# installer-gui Node.js dependencies
- package-ecosystem: "npm"
directory: "/installer-gui"
schedule:
interval: "weekly"
open-pull-requests-limit: 0
groups:
security:
applies-to: "security-updates"
patterns:
- "*"

13
.github/pull_request_template.md vendored Normal file
View File

@@ -0,0 +1,13 @@
## Pull Request Checklist
- [ ] The Rayhunter team has recently expressed interest in reviewing a PR for this.
- If not, this PR may be closed due our limited resources and need to prioritize how we spend them.
- [ ] Added or updated any documentation as needed to support the changes in this PR.
- [ ] Code has been linted and run through `cargo fmt`.
- [ ] If any new functionality has been added, unit tests were also added.
- [ ] [CONTRIBUTING.md](https://github.com/EFForg/rayhunter/blob/main/CONTRIBUTING.md) has been read.
- [ ] Your pull request is fewer than ~400 lines of code.
You must check one of:
- [ ] No generative AI (including LLMs) tools were used to create this PR.
- [ ] Generative AI was used to create this PR. I certify that I have read and understand the code, and *that all comments and descriptions were authored by myself* and are not the product of generative AI.

View File

@@ -1,85 +0,0 @@
name: Build Release
on:
push:
branches: [main, "release-*"]
env:
CARGO_TERM_COLOR: always
jobs:
build_serial_and_check:
strategy:
matrix:
platform:
- os: ubuntu-latest
serial_build_name: serial
check_build_name: rayhunter-check
- os: macos-latest
serial_build_name: serial
check_build_name: rayhunter-check
runs-on: ${{ matrix.platform.os }}
steps:
- uses: actions/checkout@v4
- name: Build serial
run: cargo build --bin serial --release
- uses: actions/upload-artifact@v4
with:
name: serial-${{ matrix.platform.os }}
path: ./target/release/${{ matrix.platform.serial_build_name }}
if-no-files-found: error
- uses: actions/checkout@v4
- name: Build check
run: cargo build --bin rayhunter-check --release
- uses: actions/upload-artifact@v4
with:
name: rayhunter-check-${{ matrix.platform.os }}
path: ./target/release/${{ matrix.platform.check_build_name }}
if-no-files-found: error
build_rootshell_and_rayhunter:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: armv7-unknown-linux-gnueabihf
- name: Install cross-compilation dependencies
uses: awalsh128/cache-apt-pkgs-action@latest
with:
packages: build-essential libc6-armhf-cross libc6-dev-armhf-cross gcc-arm-linux-gnueabihf
version: 1.0
- name: Build rootshell (arm32)
run: cargo build --bin rootshell --target armv7-unknown-linux-gnueabihf --release
- uses: actions/upload-artifact@v4
with:
name: rootshell
path: target/armv7-unknown-linux-gnueabihf/release/rootshell
if-no-files-found: error
- name: Build rayhunter-daemon (arm32)
run: cargo build --bin rayhunter-daemon --target armv7-unknown-linux-gnueabihf --release
- uses: actions/upload-artifact@v4
with:
name: rayhunter-daemon
path: target/armv7-unknown-linux-gnueabihf/release/rayhunter-daemon
if-no-files-found: error
build_release_zip:
needs:
- build_serial_and_check
- build_rootshell_and_rayhunter
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
- name: Fix executable permissions on binaries
run: chmod +x serial-*/serial rayhunter-check-*/rayhunter-check rayhunter-daemon/rayhunter-daemon
- name: Setup release directory
run: mv rayhunter-daemon/rayhunter-daemon rootshell/rootshell serial-* dist
- name: Archive release directory
run: tar -cvf release.tar -C dist .
# TODO: have this create a release directly
- name: Upload release
uses: actions/upload-artifact@v4
with:
name: release.tar
path: release.tar
if-no-files-found: error

View File

@@ -1,20 +0,0 @@
name: Check and Test
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
env:
CARGO_TERM_COLOR: always
jobs:
check_and_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Check
run: cargo check --verbose
- name: Run tests
run: cargo test --verbose

662
.github/workflows/main.yml vendored Normal file
View File

@@ -0,0 +1,662 @@
name: main
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
workflow_call: # required to call this workflow from another workflow like release.yml
env:
CARGO_TERM_COLOR: always
FILE_ROOTSHELL: ../../rootshell/rootshell
FILE_RAYHUNTER_DAEMON: ../../rayhunter-daemon/rayhunter-daemon
FILE_WPA_SUPPLICANT: ../../wpa-supplicant/wpa_supplicant
FILE_WPA_CLI: ../../wpa-supplicant/wpa_cli
FILE_IW: ../../wpa-supplicant/iw
RUSTFLAGS: "-Dwarnings"
jobs:
files_changed:
name: Detect file changes
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
code_changed: ${{ steps.files_changed.outputs.code_count != '0' }}
daemon_changed: ${{ steps.files_changed.outputs.daemon_count != '0' }}
daemon_needed: ${{ steps.files_changed.outputs.daemon_count != '0' || steps.files_changed.outputs.installer_build != '0' }}
web_changed: ${{ steps.files_changed.outputs.web_count != '0' }}
docs_changed: ${{ steps.files_changed.outputs.docs_count != '0' || steps.files_changed.outputs.daemon_count != '0' }}
installer_changed: ${{ steps.files_changed.outputs.installer_count != '0' }}
installer_gui_changed: ${{ steps.files_changed.outputs.installer_gui_count != '0' }}
rootshell_needed: ${{ steps.files_changed.outputs.rootshell_count != '0' || steps.files_changed.outputs.installer_build != '0' }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: detect file changes
id: files_changed
run: |
lcommit=${{ github.event.pull_request.base.sha || 'origin/main' }}
# If we are on main, if workflow/cargo config files changed, or if
# the latest commit message contains "#build-all", run everything.
# Use #build-all in a commit message to force a full build on a PR
# branch (useful for testing release builds without merging to main).
if [ ${GITHUB_REF} = 'refs/heads/main' ] || git diff --name-only $lcommit..HEAD | grep -qe ^.github/workflows/ -e ^.cargo || git log -1 --format='%s %b' | grep -qF '#build-all'
then
echo "building everything"
echo code_count=forced >> "$GITHUB_OUTPUT"
echo daemon_count=forced >> "$GITHUB_OUTPUT"
echo web_count=forced >> "$GITHUB_OUTPUT"
echo docs_count=forced >> "$GITHUB_OUTPUT"
echo installer_build=forced >> "$GITHUB_OUTPUT"
echo installer_count=forced >> "$GITHUB_OUTPUT"
echo installer_gui_count=forced >> "$GITHUB_OUTPUT"
echo rootshell_count=forced >> "$GITHUB_OUTPUT"
else
echo "code_count=$(git diff --name-only $lcommit...HEAD | grep -e ^daemon -e ^installer -e ^check -e ^lib -e ^rootshell -e ^telcom-parser | wc -l)" >> "$GITHUB_OUTPUT"
echo "daemon_count=$(git diff --name-only $lcommit...HEAD | grep -e ^daemon -e ^lib -e ^telcom-parser | wc -l)" >> "$GITHUB_OUTPUT"
echo "web_count=$(git diff --name-only $lcommit...HEAD | grep -e ^daemon/web | wc -l)" >> "$GITHUB_OUTPUT"
echo "docs_count=$(git diff --name-only $lcommit...HEAD | grep -e ^book.toml -e ^doc | wc -l)" >> "$GITHUB_OUTPUT"
echo "rootshell_count=$(git diff --name-only $lcommit...HEAD | grep -e ^rootshell | wc -l)" >> "$GITHUB_OUTPUT"
installer_count=$(git diff --name-only $lcommit...HEAD | grep -e ^installer/ | wc -l)
installer_gui_count=$(git diff --name-only $lcommit...HEAD | grep -e ^installer-gui | wc -l)
if [ $installer_count != "0" ] || [ $installer_gui_count != "0" ]; then
echo "installer_build=1" >> "$GITHUB_OUTPUT"
else
echo "installer_build=0" >> "$GITHUB_OUTPUT"
fi
echo "installer_count=$installer_count" >> "$GITHUB_OUTPUT"
echo "installer_gui_count=$installer_gui_count" >> "$GITHUB_OUTPUT"
fi
mdbook_test:
name: Test mdBook Documentation builds
needs: files_changed
if: needs.files_changed.outputs.docs_changed == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: Swatinem/rust-cache@v2
- name: Install mdBook
run: |
cargo install mdbook --no-default-features --features search --vers "^0.4" --locked
- name: Test mdBook
run: mdbook test
mdbook_build:
name: Build mdBook for Github Pages
needs: mdbook_test
if: ${{ github.ref == 'refs/heads/main' }}
permissions:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: Swatinem/rust-cache@v2
- name: Install mdBook
run: |
cargo install mdbook --no-default-features --features search --vers "^0.4" --locked
- name: Build mdBook
run: mdbook build
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: book
path: book
check_and_test:
needs: files_changed
if: needs.files_changed.outputs.code_changed == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- uses: Swatinem/rust-cache@v2
- name: Check formatting
run: cargo fmt --all --check
- name: Check
run: |
pushd daemon/web
npm install
npm run build
popd
cargo check --verbose
- name: Run tests
run: |
cargo test --verbose
- name: Run clippy
run: |
cargo clippy --verbose
installer_gui_check:
# we test the GUI installer separately to:
# 1) mimic the default behavior of cargo commands for rayhunter devs where
# installer-gui isn't one of the default workspace packages
# 2) avoid slowing down development on changes unrelated to the GUI installer
needs: files_changed
if: needs.files_changed.outputs.installer_gui_changed == 'true'
# we run this on macos simply because no additional OS packages need to be
# installed
runs-on: macos-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- uses: Swatinem/rust-cache@v2
# we don't need to run cargo fmt here because both cargo fmt and cargo
# fmt --all runs on all workspace packages so this is handled by
# check_and_test above
- name: Check
run: cargo check --package installer-gui --verbose
- name: Run clippy
run: cargo clippy --package installer-gui --verbose
test_daemon_frontend:
needs: files_changed
if: needs.files_changed.outputs.web_changed == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
defaults:
run:
working-directory: daemon/web
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- run: npm install
- run: npm run lint
- run: npm run check
- run: npm run test
test_installer_frontend:
needs: files_changed
if: needs.files_changed.outputs.installer_gui_changed == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
defaults:
run:
working-directory: installer-gui
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- run: npm install
- run: npm run lint
- run: npm run check
windows_installer_check_and_test:
needs: files_changed
if: needs.files_changed.outputs.installer_changed == 'true'
runs-on: windows-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: Swatinem/rust-cache@v2
- name: cargo check
shell: bash
run: |
cd installer
cargo check --verbose
- name: cargo test
shell: bash
run: |
cd installer
cargo test --verbose --no-default-features
build_rayhunter_check:
if: needs.files_changed.outputs.daemon_changed == 'true'
needs:
- check_and_test
- files_changed
permissions:
contents: read
packages: write
strategy:
matrix:
platform:
- name: linux-x64
os: ubuntu-latest
target: x86_64-unknown-linux-musl
- name: linux-armv7
os: ubuntu-latest
target: armv7-unknown-linux-musleabi
- name: linux-aarch64
os: ubuntu-24.04-arm
target: aarch64-unknown-linux-musl
- name: macos-arm
os: macos-latest
target: aarch64-apple-darwin
- name: macos-intel
os: macos-latest
target: x86_64-apple-darwin
- name: windows-x86_64
os: windows-latest
target: x86_64-pc-windows-gnu
runs-on: ${{ matrix.platform.os }}
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.platform.target }}
- uses: Swatinem/rust-cache@v2
- name: Build rayhunter-check
run: cargo build --bin rayhunter-check --release --target ${{ matrix.platform.target }}
- uses: actions/upload-artifact@v4
with:
name: rayhunter-check-${{ matrix.platform.name }}
path: target/${{ matrix.platform.target }}/release/rayhunter-check${{ matrix.platform.os == 'windows-latest' && '.exe' || '' }}
if-no-files-found: error
build_rootshell:
if: needs.files_changed.outputs.rootshell_needed == 'true'
needs:
- check_and_test
- files_changed
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
targets: armv7-unknown-linux-musleabihf
- uses: Swatinem/rust-cache@v2
- name: Build rootshell (armv7)
run: cargo build -p rootshell --bin rootshell --target armv7-unknown-linux-musleabihf --profile=firmware
- uses: actions/upload-artifact@v4
with:
name: rootshell
path: target/armv7-unknown-linux-musleabihf/firmware/rootshell
if-no-files-found: error
build_wpa_supplicant:
if: needs.files_changed.outputs.installer_changed == 'true'
needs:
- files_changed
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Install cross-compiler
run: sudo apt-get update && sudo apt-get install -y gcc-arm-linux-gnueabihf
- name: Build wpa_supplicant (armv7)
run: CC=arm-linux-gnueabihf-gcc STRIP=arm-linux-gnueabihf-strip HOST=arm-linux-gnueabihf scripts/build-wpa-supplicant.sh
- uses: actions/upload-artifact@v4
with:
name: wpa-supplicant
path: |
tools/build-wpa-supplicant/out/wpa_supplicant
tools/build-wpa-supplicant/out/wpa_cli
tools/build-wpa-supplicant/out/iw
if-no-files-found: error
build_rayhunter:
if: needs.files_changed.outputs.daemon_needed == 'true'
needs:
- check_and_test
- files_changed
permissions:
contents: read
packages: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Build frontend
run: |
pushd daemon/web
npm install
npm run build
popd
- name: Build rayhunter-daemon (armv7)
# Cross-compile inside messense/rust-musl-cross, which bundles an
# arm-linux-musleabihf cross gcc that aws-lc-sys needs.
run: |
mkdir -p "$HOME/.cargo-musl-cross"
docker run --rm \
--user "$(id -u):$(id -g)" \
-v "$PWD":/work \
-v "$HOME/.cargo-musl-cross":/cargo-home \
-e CARGO_HOME=/cargo-home \
-w /work \
messense/rust-musl-cross:armv7-musleabihf \
cargo build-daemon-firmware
- uses: actions/upload-artifact@v4
with:
name: rayhunter-daemon
path: target/armv7-unknown-linux-musleabihf/firmware/rayhunter-daemon
if-no-files-found: error
build_rust_installer:
if: needs.files_changed.outputs.installer_changed == 'true'
permissions:
contents: read
packages: write
needs:
- build_rayhunter
- build_rootshell
- build_wpa_supplicant
- files_changed
- windows_installer_check_and_test
strategy:
matrix:
platform:
- name: linux-x64
os: ubuntu-latest
target: x86_64-unknown-linux-musl
- name: linux-armv7
os: ubuntu-latest
target: armv7-unknown-linux-musleabi
- name: linux-aarch64
os: ubuntu-24.04-arm
target: aarch64-unknown-linux-musl
- name: macos-arm
os: macos-latest
target: aarch64-apple-darwin
- name: macos-intel
os: macos-latest
target: x86_64-apple-darwin
- name: windows-x86_64
os: windows-latest
target: x86_64-pc-windows-gnu
runs-on: ${{ matrix.platform.os }}
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/download-artifact@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.platform.target }}
- uses: Swatinem/rust-cache@v2
- run: cargo build --package installer --bin installer --release --target ${{ matrix.platform.target }}
- uses: actions/upload-artifact@v4
with:
name: installer-${{ matrix.platform.name }}
path: target/${{ matrix.platform.target }}/release/installer${{ matrix.platform.os == 'windows-latest' && '.exe' || '' }}
if-no-files-found: error
build_installer_gui_linux:
if: needs.files_changed.outputs.installer_gui_changed == 'true'
permissions:
contents: read
packages: write
needs:
- build_rayhunter
- build_rootshell
- files_changed
- installer_gui_check
- test_installer_frontend
strategy:
matrix:
platform:
# we want to use the oldest supported version of ubuntu here to
# maximize compatibility with older versions of glibc
- name: linux-x64
os: ubuntu-22.04
target: x86_64-unknown-linux-gnu
- name: linux-aarch64
os: ubuntu-22.04-arm
target: aarch64-unknown-linux-gnu
runs-on: ${{ matrix.platform.os }}
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/download-artifact@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.platform.target }}
- uses: Swatinem/rust-cache@v2
- name: Install tauri dependencies
run: sudo apt-get update && sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential curl wget file libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev xdg-utils
- name: Build GUI installer
shell: bash
run: |
cd installer-gui
npm install
npm run tauri build -- --target ${{ matrix.platform.target }}
- uses: actions/upload-artifact@v4
with:
name: gui-installer-${{ matrix.platform.name }}-appimage
path: target/${{ matrix.platform.target }}/release/bundle/appimage/*.AppImage
if-no-files-found: error
- uses: actions/upload-artifact@v4
with:
name: gui-installer-${{ matrix.platform.name }}-deb
path: target/${{ matrix.platform.target }}/release/bundle/deb/*.deb
if-no-files-found: error
- uses: actions/upload-artifact@v4
with:
name: gui-installer-${{ matrix.platform.name }}-rpm
path: target/${{ matrix.platform.target }}/release/bundle/rpm/*.rpm
if-no-files-found: error
build_installer_gui_macos:
if: needs.files_changed.outputs.installer_gui_changed == 'true'
permissions:
contents: read
packages: write
needs:
- build_rayhunter
- build_rootshell
- files_changed
- installer_gui_check
- test_installer_frontend
strategy:
matrix:
platform:
- name: macos-arm
target: aarch64-apple-darwin
- name: macos-intel
target: x86_64-apple-darwin
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/download-artifact@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.platform.target }}
- uses: Swatinem/rust-cache@v2
- name: Build GUI installer
shell: bash
run: |
cd installer-gui
npm install
npm run tauri build -- --target ${{ matrix.platform.target }}
cd ..
mv "target/${{ matrix.platform.target }}/release/bundle/macos/"*.app .
zip -r "rayhunter-installer-${{ matrix.platform.name }}.app.zip" ./*.app
- uses: actions/upload-artifact@v4
with:
name: gui-installer-${{ matrix.platform.name }}-app
path: ./*.app.zip
if-no-files-found: error
build_installer_gui_windows:
if: needs.files_changed.outputs.installer_gui_changed == 'true'
permissions:
contents: read
packages: write
needs:
- build_rayhunter
- build_rootshell
- files_changed
- installer_gui_check
- test_installer_frontend
env:
TARGET: x86_64-pc-windows-msvc
runs-on: windows-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/download-artifact@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ env.TARGET }}
- uses: Swatinem/rust-cache@v2
- name: Build GUI installer
shell: bash
run: |
cd installer-gui
npm install
npm run tauri build -- --target ${{ env.TARGET }}
- uses: actions/upload-artifact@v4
with:
name: gui-installer-msi
path: target/${{ env.TARGET }}/release/bundle/msi/*.msi
if-no-files-found: error
- uses: actions/upload-artifact@v4
with:
name: gui-installer-exe
path: target/${{ env.TARGET }}/release/bundle/nsis/*.exe
if-no-files-found: error
build_release_zip:
permissions:
contents: read
packages: write
needs:
- build_rayhunter_check
- build_rootshell
- build_rayhunter
- build_rust_installer
runs-on: ubuntu-latest
strategy:
matrix:
platform:
- linux-x64
- linux-aarch64
- linux-armv7
- macos-intel
- macos-arm
- windows-x86_64
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/download-artifact@v4
- name: Fix executable permissions on binaries
run: chmod +x installer-*/installer rayhunter-check-*/rayhunter-check rayhunter-daemon/rayhunter-daemon
- name: Get Rayhunter version
id: get_version
run: echo "VERSION=$(grep '^version' daemon/Cargo.toml | head -n 1 | cut -d'"' -f2)" >> $GITHUB_ENV
- name: Setup versioned release directory
run: |
platform="${{ matrix.platform }}"
dest="rayhunter-v${VERSION}-${{ matrix.platform }}"
mkdir "$dest"
# Handle installer with proper extension for Windows
if [ "$platform" = "windows-x86_64" ]; then
mv installer-$platform/installer.exe "$dest"/installer.exe
else
mv installer-$platform/installer "$dest"/installer
fi
cp -r rayhunter-check-* rayhunter-daemon dist/scripts "$dest"/
zip -r "$dest.zip" "$dest"
sha256sum "$dest.zip" > "$dest.zip.sha256"
- name: Upload zip release and sha256
uses: actions/upload-artifact@v4
with:
name: rayhunter-v${{ env.VERSION }}-${{ matrix.platform }}
path: |
rayhunter-v${{ env.VERSION }}-${{ matrix.platform }}.zip
rayhunter-v${{ env.VERSION }}-${{ matrix.platform }}.zip.sha256
if-no-files-found: error
openapi_build:
if: needs.files_changed.outputs.docs_changed == 'true'
needs:
- files_changed
permissions:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
targets: armv7-unknown-linux-musleabihf
- uses: Swatinem/rust-cache@v2
- name: Build rayhunter-daemon openapi docs
run: |
mkdir -p daemon/web/build
touch daemon/web/build/{favicon.png,index.html.gz,rayhunter_orca_only.png,rayhunter_text.png}
cargo run --bin gen_api --features apidocs -- ./rayhunter-openapi.json
- name: Make swagger folder
run: |
mkdir api-docs
mv doc/swagger-ui.html api-docs/index.html
mv rayhunter-openapi.json api-docs/
- uses: actions/upload-artifact@v4
with:
name: api-docs
path: api-docs
github_pages_publish:
name: Upload new documentation to Github Pages
if: ${{ github.ref == 'refs/heads/main' }}
permissions:
pages: write
contents: write
id-token: write
needs:
- mdbook_build
- openapi_build
runs-on: ubuntu-latest
steps:
- name: Setup Pages
uses: actions/configure-pages@v4
- uses: actions/download-artifact@v4
- name: Organize pages into directory
run: cp -a api-docs book/
- name: Upload pages
uses: actions/upload-pages-artifact@v3
with:
path: book
- name: Deploy Github Pages
uses: actions/deploy-pages@v4

52
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,52 @@
# To use: navigate on Github to Actions, select "Release rayhunter" on the left, click "Run workflow" > "Run workflow" on the right.
# https://github.com/EFForg/rayhunter/actions/workflows/release.yml
name: Release rayhunter
on:
workflow_dispatch:
env:
GH_TOKEN: ${{ github.token }}
jobs:
check_version_same:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Ensure all Cargo.toml files have the same version defined.
run: |
defined_versions=$(find lib check daemon installer installer-gui rootshell telcom-parser -name Cargo.toml -exec grep ^version {} \; | sort -u | wc -l)
find lib check daemon installer installer-gui rootshell telcom-parser -name Cargo.toml -exec grep ^version {} \;
echo number of defined versions = $defined_versions
if [ $defined_versions != "1" ]
then
echo "all Cargo.toml files must have the same version defined"
exit 1
fi
main:
needs: check_version_same
permissions:
contents: write
id-token: write
packages: write
pages: write
uses: ./.github/workflows/main.yml
release:
runs-on: ubuntu-latest
needs: main
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: actions/download-artifact@v4
- name: Create release
run: |
version=$(grep ^version lib/Cargo.toml | cut -d' ' -f3 | tr -d '"')
gh release create --generate-notes -t "Rayhunter v$version" "v$version" rayhunter-v${version}-*/rayhunter-v${version}*.zi*

3
.gitignore vendored
View File

@@ -1 +1,4 @@
/target /target
/book
.DS_Store
/tools/build-wpa-supplicant

1
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1 @@
This project is governed by [EFF's Public Projects Code of Conduct](https://www.eff.org/pages/eppcode).

85
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,85 @@
# How to contribute to Rayhunter
## Filing issues and starting discussions
Our issue tracker is [on GitHub](https://github.com/EFForg/rayhunter/issues).
- If your rayhunter has found an IMSI-catcher, we strongly encourage you to
[send us that information
privately.](https://efforg.github.io/rayhunter/faq.html#help-rayhunters-line-is-redorangeyellowdotteddashed-what-should-i-do) via Signal.
- Issues should be actionable. If you don't have a
specific feature request or bug report, consider [creating a
discussion](https://github.com/EFForg/rayhunter/discussions) or [joining our Mattermost](https://efforg.github.io/rayhunter/support-feedback-community.html) instead.
Example of a good bug report:
- "Installer broken on TP-Link M7350 v3.0"
- "Display does not update to green after finding"
- "The documentation is wrong" (though we encourage you to file a pull request directly)
Example of a good feature request:
- "Use LED on device XYZ for showing recording status"
Example of something that belongs into discussion:
- "In region XYZ, do I need an activated SIM?"
- "Where to buy this device in region XYZ?"
- "Can this device be supported?" While this is a valid feature
request, we just get this request too often, and without some exploratory
work done upfront it's often unclear initially if that device can be
supported at all.
- The issue templates are mostly there to give you a clue what kind of
information is needed from you, and whether your request belongs into the issue
tracker. Fill them out to be on the safe side, but they are not mandatory.
## Contributing patches
To edit documentation or fix a bug, make a pull request. If you're about to
write a substantial amount of code or implement a new feature, we strongly
encourage you to talk to us before implementing it or check if any issues have
been opened for it already. Otherwise there is a chance we will reject your
contribution after you have spent time on it.
On the other hand, for small documentation fixes you can file a PR without
filing an issue.
Otherwise:
- Refer to [installing from
source](https://efforg.github.io/rayhunter/installing-from-source.html) for
how to build Rayhunter from the git repository.
- Ensure that `cargo fmt` and `cargo clippy` have been run.
- If you add new features, please do your best to both write tests for and also
manually test them. Our test coverage isn't great, but as new features are
added we are trying to prevent it from becoming worse.
- Please keep your contributions to less than approximately 400 lines of code not counting tests, (going slightly over is fine, we aren't dogmatic about it.) This is because we are not able to give quality code review to contributions larger than that and risk introducing bugs into the system. [There was a study showing 400 LOC is the max most humans can handle.](https://smartbear.com/learn/code-review/best-practices-for-peer-code-review/)
If you have any questions [feel free to open a discussion or chat with us on Mattermost.](https://efforg.github.io/rayhunter/support-feedback-community.html)
### Policy regarding AI-generated contributions:
- Please refrain from submissions that you haven't thoroughly understood, reviewed, and tested.
- Please disclose if your contribution was AI-generated
- Descriptions and comments should be made by you
You can read our [full policy](https://www.eff.org/about/opportunities/volunteer/coding-with-eff) and some writing on [our motivations](https://www.eff.org/deeplinks/2026/02/effs-policy-llm-assisted-contributions-our-open-source-projects).
## Making releases
This one is for maintainers of Rayhunter.
1. Make a PR changing the versions in `Cargo.toml` and other files.
This could be automated better but right now it's manual. You can do this easily with sed:
`sed -i "" -E 's/x.x.x/y.y.y/g' */Cargo.toml installer-gui/src-tauri/Cargo.toml`
2. Merge PR and make a tag.
3. [Run release workflow.](https://github.com/EFForg/rayhunter/actions/workflows/release.yml)
4. Write changelog, edit it into the release, announce on mattermost.

6185
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -2,9 +2,22 @@
members = [ members = [
"lib", "lib",
"bin", "daemon",
"serial", "check",
"rootshell", "rootshell",
"telcom-parser", "telcom-parser",
"installer",
"installer-gui/src-tauri",
]
# at least for now, let's keep installer-gui out of the list of default
# packages. installer-gui is still experimental and requires many new packages
# both from cargo and the underlying operating system
default-members = [
"lib",
"daemon",
"check",
"rootshell",
"telcom-parser",
"installer",
] ]
resolver = "2" resolver = "2"

View File

@@ -1,97 +1,19 @@
# Rayhunter # Rayhunter
![Tests](https://github.com/EFForg/rayhunter/actions/workflows/main.yml/badge.svg)
``` ![Rayhunter Logo - An Orca taking a bite out of a cellular signal bar](https://www.eff.org/files/styles/media_browser_preview/public/banner_library/rayhunter-banner.png)
@@@@@@@ @@@@@@ @@@ @@@ @@@ @@@ @@@ @@@ @@@ @@@ @@@@@@@ @@@@@@@@ @@@@@@@
@@! @@@ @@! @@@ @@! !@@ @@! @@@ @@! @@@ @@!@!@@@ @@! @@! @@! @@@
@!@!!@! @!@!@!@! !@!@! @!@!@!@! @!@ !@! @!@@!!@! @!! @!!!:! @!@!!@!
!!: :!! !!: !!! !!: !!: !!! !!: !!! !!: !!! !!: !!: !!: :!!
: : : : : : .: : : : :.:: : :: : : : :: ::: : : :
Rayhunter is a project for detecting IMSI catchers, also known as cell-site simulators or stingrays. It was first designed to run on a cheap mobile hotspot called the Orbic RC400L, but thanks to community efforts, it can [support some other devices as well](https://efforg.github.io/rayhunter/supported-devices.html).
It's also designed to be as easy to install and use as possible, regardless of your level of technical skills, and to minimize false positives.
_ _ _ _ _ _ _ _ &rarr; Check out the [installation guide](https://efforg.github.io/rayhunter/installation.html) to get started.
)`'-.,_)`'-.,_)`'-.,_)`'-.,_)`'-.,_)`'-.,_)`'-.,_)`'-.,_
O . &rarr; To learn more about the aim of the project, and about IMSI catchers in general, please check out our [introductory blog post](https://www.eff.org/deeplinks/2025/03/meet-rayhunter-new-open-source-tool-eff-detect-cellular-spying).
O ' '
o ' .
o .'
__________.-' '...___
.-' ### '''...__
/ a### ## ''--.._ ______
'. # ######## ' .-'
'-._ ..**********#### ___...---'''\ '
'-._ __________...---''' \ l
\ | apc '._|
\__;
```
![Tests](https://github.com/EFForg/rayhunter/actions/workflows/check-and-test.yml/badge.svg)
Rayhunter is an IMSI Catcher Catcher for the Orbic mobile hotspot. &rarr; For discussion, help, or to join the mattermost channel and get involved with the project and community check out the [many ways listed here](https://efforg.github.io/rayhunter/support-feedback-community.html)!
**THIS CODE IS PROOF OF CONCEPT AND SHOULD NOT BE RELIED UPON IN HIGH RISK SITUATIONS** &rarr; To learn more about the project in general check out the [Rayhunter Book](https://efforg.github.io/rayhunter/).
Code is built and tested for the Orbic RC400L mobile hotspot, it may work on other orbics and other **LEGAL DISCLAIMER:** Use this program at your own risk. We believe running this program does not currently violate any laws or regulations in the United States. However, we are not responsible for civil or criminal liability resulting from the use of this software. If you are located outside of the US please consult with an attorney in your country to help you assess the legal risks of running this program.
linux/qualcom devices but this is the only one we have tested on. Buy the orbic [using bezos bucks](https://www.amazon.com/gp/product/B09CLS6Z7X/)
## Setup
*NOTE: We don't currently support automated installs on windows, you will have to follow the manual install instructions below*
1. Download the latest [rayhunter release bundle](https://github.com/EFForg/rayhunter/releases) and extract it.
2. Run the install script inside the bundle corresponding to your platform (`install-linux.sh`, `install-mac.sh`).
3. Once finished, rayhunter should be running! You can verify this by visiting the web UI as described below.
## Usage
Once installed, rayhunter will run automatically whenever your Orbic device is running. It serves a web UI that provides some basic controls, such as being able to start/stop recordings, download captures, and view heuristic analyses of captures. You can access this UI in one of two ways:
1. Over wifi: Connect your phone/laptop to the Orbic's wifi network and visit `http://192.168.1.1:8080` (click past your browser warning you about the connection not being secure, rayhunter doesn't have HTTPS yet!)
* Note that you'll need the Orbic's wifi password for this, which can be retrieved by pressing the "MENU" button on the device and opening the 2.4 GHz menu.
2. Over usb: Connect the Orbic device to your laptop via usb. Run `adb forward tcp:8080 tcp:8080`, then visit `http://localhost:8080`. For this you will need to install the Android Debug Bridge (ADB) on your computer, you can copy the version that was downloaded inside the releases/platform-tools/` folder to somewhere else in your path or you can install it manually. You can find instructions for doing so on your platform [here](https://www.xda-developers.com/install-adb-windows-macos-linux/#how-to-set-up-adb-on-your-computer), (don't worry about instructions for installing it on a phone/device yet).
## Development
* Install ADB on your computer using the instructions above, and make sure it's in your terminal's PATH
* You can verify if ADB is in your PATH by running `which adb` in a terminal. If it prints the filepath to where ADB is installed, you're set! Otherwise, try following one of these guides:
* [linux](https://askubuntu.com/questions/652936/adding-android-sdk-platform-tools-to-path-downloaded-from-umake)
* [macOS](https://www.repeato.app/setting-up-adb-on-macos-a-step-by-step-guide/)
* [Windows](https://medium.com/@yadav-ajay/a-step-by-step-guide-to-setting-up-adb-path-on-windows-0b833faebf18)
### If your are on x86 linux
* on your linux laptop install rust the usual way and then install cross compiling dependences.
* run `sudo apt install build-essential libc6-armhf-cross libc6-dev-armhf-cross gcc-arm-linux-gnueabihf`
* set up cross compliing for rust:
```
rustup target add x86_64-unknown-linux-gnu
rustup target add armv7-unknown-linux-gnueabihf
```
Now you can root your device and install rayhunter by running `./tools/install-dev.sh`
### If you are on windows or can't run the install scripts
* Root your device on windows using the instructions here: https://xdaforums.com/t/resetting-verizon-orbic-speed-rc400l-firmware-flash-kajeet.4334899/#post-87855183
* Build for arm using `cargo build`
* Run tests using `cargo test_pc`
* Push the scripts in `scripts/` to /etc/init.d on device and make a directory called /data/rayhunter using `adb shell` (and sshell for your root shell if you followed the steps above)
* you also need to copy `config.toml.example` to /data/rayhunter/config.toml
* Then run `./make.sh` this will build the binary and push it over adb. Restart your device or run `/etc/init.d/rayhunter_daemon start` on the device and you are good to go.
* Write your code and write tests
* Build for arm using `cargo build`
* Run tests using `cargo test_pc`
* push to the device with `./make.sh`
## Documentation
* Build docs locallly using `RUSTDOCFLAGS="--cfg docsrs" cargo doc --no-deps --all-features --open`
**LEGAL DISCLAIMER:** Use this program at your own risk. We beilieve running this program does not currently violate any laws or regulations in the United States. However, we are not responsible for civil or criminal liability resulting from the use of this software. If you are located outside of the US please consult with an attorney in your country to help you assess the legal risks of running this program.
*Good Hunting!* *Good Hunting!*

5
SECURITY.md Normal file
View File

@@ -0,0 +1,5 @@
# Security Policy
## Reporting a Vulnerability
Security vulnerabilities can be reported using GitHub's [private vulnerability reporting tool](https://github.com/EFForg/rayhunter/security/advisories/new).

View File

@@ -1,34 +0,0 @@
[package]
name = "rayhunter-daemon"
version = "0.1.0"
edition = "2021"
[[bin]]
name = "rayhunter-daemon"
path = "src/daemon.rs"
[[bin]]
name = "rayhunter-check"
path = "src/check.rs"
[dependencies]
rayhunter = { path = "../lib" }
toml = "0.8.8"
serde = { version = "1.0.193", features = ["derive"] }
tokio = { version = "1.35.1", features = ["full"] }
axum = "0.7.3"
futures-core = "0.3.30"
thiserror = "1.0.52"
log = "0.4.20"
env_logger = "0.10.1"
tokio-util = { version = "0.7.10", features = ["rt"] }
futures-macro = "0.3.30"
include_dir = "0.7.3"
mime_guess = "2.0.4"
chrono = { version = "0.4.31", features = ["serde"] }
tokio-stream = "0.1.14"
futures = "0.3.30"
clap = { version = "4.5.2", features = ["derive"] }
serde_json = "1.0.114"
image = "0.25.1"
tempfile = "3.10.1"

View File

@@ -1,117 +0,0 @@
use std::{collections::HashMap, future, path::PathBuf, pin::pin};
use rayhunter::{analysis::analyzer::Harness, diag::DataType, gsmtap_parser, pcap::GsmtapPcapWriter, qmdl::QmdlReader};
use tokio::fs::{metadata, read_dir, File};
use clap::Parser;
use futures::TryStreamExt;
mod dummy_analyzer;
#[derive(Parser, Debug)]
#[command(version, about)]
struct Args {
#[arg(short, long)]
qmdl_path: PathBuf,
#[arg(short, long)]
pcapify: bool,
#[arg(long)]
show_skipped: bool,
#[arg(long)]
enable_dummy_analyzer: bool,
}
async fn analyze_file(harness: &mut Harness, qmdl_path: &str, show_skipped: bool) {
let qmdl_file = &mut File::open(&qmdl_path).await.expect("failed to open file");
let file_size = qmdl_file.metadata().await.expect("failed to get QMDL file metadata").len();
let mut qmdl_reader = QmdlReader::new(qmdl_file, Some(file_size as usize));
let mut qmdl_stream = pin!(qmdl_reader.as_stream()
.try_filter(|container| future::ready(container.data_type == DataType::UserSpace)));
let mut skipped_reasons: HashMap<String, i32> = HashMap::new();
let mut total_messages = 0;
let mut warnings = 0;
let mut skipped = 0;
while let Some(container) = qmdl_stream.try_next().await.expect("failed getting QMDL container") {
let row = harness.analyze_qmdl_messages(container);
total_messages += 1;
for reason in row.skipped_message_reasons {
*skipped_reasons.entry(reason).or_insert(0) += 1;
skipped += 1;
}
for analysis in row.analysis {
for maybe_event in analysis.events {
if let Some(event) = maybe_event {
warnings += 1;
println!("{}: {:?}", analysis.timestamp, event);
}
}
}
}
if show_skipped && skipped > 0 {
println!("{}: messages skipped:", qmdl_path);
for (reason, count) in skipped_reasons.iter() {
println!(" - {}: \"{}\"", count, reason);
}
}
println!("{}: {} messages analyzed, {} warnings, {} messages skipped", qmdl_path, total_messages, warnings, skipped);
}
async fn pcapify(qmdl_path: &PathBuf) {
let qmdl_file = &mut File::open(&qmdl_path).await.expect("failed to open qmdl file");
let qmdl_file_size = qmdl_file.metadata().await.unwrap().len();
let mut qmdl_reader = QmdlReader::new(qmdl_file, Some(qmdl_file_size as usize));
let mut pcap_path = qmdl_path.clone();
pcap_path.set_extension("pcap");
let pcap_file = &mut File::create(&pcap_path).await.expect("failed to open pcap file");
let mut pcap_writer = GsmtapPcapWriter::new(pcap_file).await.unwrap();
pcap_writer.write_iface_header().await.unwrap();
while let Some(container) = qmdl_reader.get_next_messages_container().await.expect("failed to get container") {
for maybe_msg in container.into_messages() {
if let Ok(msg) = maybe_msg {
if let Ok(Some((timestamp, parsed))) = gsmtap_parser::parse(msg) {
pcap_writer.write_gsmtap_message(parsed, timestamp).await.expect("failed to write");
}
}
}
}
println!("wrote pcap to {:?}", &pcap_path);
}
#[tokio::main]
async fn main() {
env_logger::init();
let args = Args::parse();
let mut harness = Harness::new_with_all_analyzers();
if args.enable_dummy_analyzer {
harness.add_analyzer(Box::new(dummy_analyzer::TestAnalyzer { count: 0 }));
}
println!("Analyzers:");
for analyzer in harness.get_metadata().analyzers {
println!(" - {}: {}", analyzer.name, analyzer.description);
}
let metadata = metadata(&args.qmdl_path).await.expect("failed to get metadata");
if metadata.is_dir() {
let mut dir = read_dir(&args.qmdl_path).await.expect("failed to read dir");
while let Some(entry) = dir.next_entry().await.expect("failed to get entry") {
let name = entry.file_name();
let name_str = name.to_str().unwrap();
if name_str.ends_with(".qmdl") {
let path = entry.path();
let path_str = path.to_str().unwrap();
analyze_file(&mut harness, path_str, args.show_skipped).await;
if args.pcapify {
pcapify(&path).await;
}
}
}
} else {
let path = args.qmdl_path.to_str().unwrap();
analyze_file(&mut harness, path, args.show_skipped).await;
if args.pcapify {
pcapify(&args.qmdl_path).await;
}
}
}

View File

@@ -1,66 +0,0 @@
use crate::error::RayhunterError;
use serde::Deserialize;
#[derive(Deserialize)]
struct ConfigFile {
qmdl_store_path: Option<String>,
port: Option<u16>,
debug_mode: Option<bool>,
ui_level: Option<u8>,
enable_dummy_analyzer: Option<bool>,
colorblind_mode: Option<bool>,
}
#[derive(Debug)]
pub struct Config {
pub qmdl_store_path: String,
pub port: u16,
pub debug_mode: bool,
pub ui_level: u8,
pub enable_dummy_analyzer: bool,
pub colorblind_mode: bool,
}
impl Default for Config {
fn default() -> Self {
Config {
qmdl_store_path: "/data/rayhunter/qmdl".to_string(),
port: 8080,
debug_mode: false,
ui_level: 1,
enable_dummy_analyzer: false,
colorblind_mode: false,
}
}
}
pub fn parse_config<P>(path: P) -> Result<Config, RayhunterError> where P: AsRef<std::path::Path> {
let mut config = Config::default();
if let Ok(config_file) = std::fs::read_to_string(&path) {
let parsed_config: ConfigFile = toml::from_str(&config_file)
.map_err(RayhunterError::ConfigFileParsingError)?;
parsed_config.qmdl_store_path.map(|v| config.qmdl_store_path = v);
parsed_config.port.map(|v| config.port = v);
parsed_config.debug_mode.map(|v| config.debug_mode = v);
parsed_config.ui_level.map(|v| config.ui_level = v);
parsed_config.enable_dummy_analyzer.map(|v| config.enable_dummy_analyzer = v);
parsed_config.colorblind_mode.map(|v| config.colorblind_mode = v);
}
Ok(config)
}
pub struct Args {
pub config_path: String,
}
pub fn parse_args() -> Args {
let args: Vec<String> = std::env::args().collect();
if args.len() != 2 {
println!("Usage: {} /path/to/config/file", args[0]);
std::process::exit(1);
}
Args {
config_path: args[1].clone(),
}
}

View File

@@ -1,249 +0,0 @@
mod analysis;
mod config;
mod error;
mod pcap;
mod server;
mod stats;
mod qmdl_store;
mod diag;
mod framebuffer;
mod dummy_analyzer;
use crate::config::{parse_config, parse_args};
use crate::diag::run_diag_read_thread;
use crate::qmdl_store::RecordingStore;
use crate::server::{ServerState, get_qmdl, serve_static};
use crate::pcap::get_pcap;
use crate::stats::get_system_stats;
use crate::error::RayhunterError;
use crate::framebuffer::Framebuffer;
use analysis::{get_analysis_status, run_analysis_thread, start_analysis, AnalysisCtrlMessage, AnalysisStatus};
use axum::response::Redirect;
use diag::{get_analysis_report, start_recording, stop_recording, DiagDeviceCtrlMessage};
use log::{info, error};
use rayhunter::diag_device::DiagDevice;
use axum::routing::{get, post};
use axum::Router;
use stats::get_qmdl_manifest;
use tokio::sync::mpsc::{self, Sender, Receiver};
use tokio::sync::oneshot::error::TryRecvError;
use tokio::task::JoinHandle;
use tokio_util::task::TaskTracker;
use std::net::SocketAddr;
use std::thread::sleep;
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::sync::{RwLock, oneshot};
use std::sync::Arc;
use include_dir::{include_dir, Dir};
// Runs the axum server, taking all the elements needed to build up our
// ServerState and a oneshot Receiver that'll fire when it's time to shutdown
// (i.e. user hit ctrl+c)
async fn run_server(
task_tracker: &TaskTracker,
config: &config::Config,
qmdl_store_lock: Arc<RwLock<RecordingStore>>,
server_shutdown_rx: oneshot::Receiver<()>,
ui_update_tx: Sender<framebuffer::DisplayState>,
diag_device_sender: Sender<DiagDeviceCtrlMessage>,
analysis_sender: Sender<AnalysisCtrlMessage>,
analysis_status_lock: Arc<RwLock<AnalysisStatus>>,
) -> JoinHandle<()> {
info!("spinning up server");
let state = Arc::new(ServerState {
qmdl_store_lock,
diag_device_ctrl_sender: diag_device_sender,
ui_update_sender: ui_update_tx,
debug_mode: config.debug_mode,
analysis_status_lock,
analysis_sender,
colorblind_mode: config.colorblind_mode,
});
let app = Router::new()
.route("/api/pcap/*name", get(get_pcap))
.route("/api/qmdl/*name", get(get_qmdl))
.route("/api/system-stats", get(get_system_stats))
.route("/api/qmdl-manifest", get(get_qmdl_manifest))
.route("/api/start-recording", post(start_recording))
.route("/api/stop-recording", post(stop_recording))
.route("/api/analysis-report/*name", get(get_analysis_report))
.route("/api/analysis", get(get_analysis_status))
.route("/api/analysis/*name", post(start_analysis))
.route("/", get(|| async { Redirect::permanent("/index.html") }))
.route("/*path", get(serve_static))
.with_state(state);
let addr = SocketAddr::from(([0, 0, 0, 0], config.port));
let listener = TcpListener::bind(&addr).await.unwrap();
task_tracker.spawn(async move {
info!("The orca is hunting for stingrays...");
axum::serve(listener, app)
.with_graceful_shutdown(server_shutdown_signal(server_shutdown_rx))
.await.unwrap();
})
}
async fn server_shutdown_signal(server_shutdown_rx: oneshot::Receiver<()>) {
server_shutdown_rx.await.unwrap();
info!("Server received shutdown signal, exiting...");
}
// Loads a QmdlStore if one exists, and if not, only create one if we're not in
// debug mode.
async fn init_qmdl_store(config: &config::Config) -> Result<RecordingStore, RayhunterError> {
match (RecordingStore::exists(&config.qmdl_store_path).await?, config.debug_mode) {
(true, _) => Ok(RecordingStore::load(&config.qmdl_store_path).await?),
(false, false) => Ok(RecordingStore::create(&config.qmdl_store_path).await?),
(false, true) => Err(RayhunterError::NoStoreDebugMode(config.qmdl_store_path.clone())),
}
}
// Start a thread that'll track when user hits ctrl+c. When that happens,
// trigger various cleanup tasks, including sending signals to other threads to
// shutdown
fn run_ctrl_c_thread(
task_tracker: &TaskTracker,
diag_device_sender: Sender<DiagDeviceCtrlMessage>,
server_shutdown_tx: oneshot::Sender<()>,
maybe_ui_shutdown_tx: Option<oneshot::Sender<()>>,
qmdl_store_lock: Arc<RwLock<RecordingStore>>,
analysis_tx: Sender<AnalysisCtrlMessage>,
) -> JoinHandle<Result<(), RayhunterError>> {
task_tracker.spawn(async move {
match tokio::signal::ctrl_c().await {
Ok(()) => {
let mut qmdl_store = qmdl_store_lock.write().await;
if qmdl_store.current_entry.is_some() {
info!("Closing current QMDL entry...");
qmdl_store.close_current_entry().await?;
info!("Done!");
}
server_shutdown_tx.send(())
.expect("couldn't send server shutdown signal");
info!("sending UI shutdown");
if let Some(ui_shutdown_tx) = maybe_ui_shutdown_tx {
ui_shutdown_tx.send(())
.expect("couldn't send ui shutdown signal");
}
diag_device_sender.send(DiagDeviceCtrlMessage::Exit).await
.expect("couldn't send Exit message to diag thread");
analysis_tx.send(AnalysisCtrlMessage::Exit).await
.expect("couldn't send Exit message to analysis thread");
},
Err(err) => {
error!("Unable to listen for shutdown signal: {}", err);
}
}
Ok(())
})
}
fn update_ui(task_tracker: &TaskTracker, config: &config::Config, mut ui_shutdown_rx: oneshot::Receiver<()>, mut ui_update_rx: Receiver<framebuffer::DisplayState>) -> JoinHandle<()> {
static IMAGE_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/static/images/");
let mut display_color: framebuffer::Color565;
let display_level = config.ui_level;
if display_level == 0 {
info!("Invisible mode, not spawning UI.");
}
if config.colorblind_mode {
display_color = framebuffer::Color565::Blue;
} else {
display_color = framebuffer::Color565::Green;
}
task_tracker.spawn_blocking(move || {
let mut fb: Framebuffer = Framebuffer::new();
// this feels wrong, is there a more rusty way to do this?
let mut img: Option<&[u8]> = None;
if display_level == 2 {
img = Some(IMAGE_DIR.get_file("orca.gif").expect("failed to read orca.gif").contents());
} else if display_level == 3 {
img = Some(IMAGE_DIR.get_file("eff.png").expect("failed to read eff.png").contents());
}
loop {
match ui_shutdown_rx.try_recv() {
Ok(_) => {
info!("received UI shutdown");
break;
},
Err(TryRecvError::Empty) => {},
Err(e) => panic!("error receiving shutdown message: {e}")
}
match ui_update_rx.try_recv() {
Ok(state) => {
display_color = state.into();
},
Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {},
Err(e) => error!("error receiving framebuffer update message: {e}")
}
match display_level {
2 => {
fb.draw_gif(img.unwrap());
},
3 => {
fb.draw_img(img.unwrap())
},
128 => {
fb.draw_line(framebuffer::Color565::Cyan, 128);
fb.draw_line(framebuffer::Color565::Pink, 102);
fb.draw_line(framebuffer::Color565::White, 76);
fb.draw_line(framebuffer::Color565::Pink, 50);
fb.draw_line(framebuffer::Color565::Cyan, 25);
},
1 | _ => {
fb.draw_line(display_color, 2);
},
};
sleep(Duration::from_millis(1000));
}
})
}
#[tokio::main]
async fn main() -> Result<(), RayhunterError> {
env_logger::init();
let args = parse_args();
let config = parse_config(&args.config_path)?;
// TaskTrackers give us an interface to spawn tokio threads, and then
// eventually await all of them ending
let task_tracker = TaskTracker::new();
println!("R A Y H U N T E R 🐳");
let qmdl_store_lock = Arc::new(RwLock::new(init_qmdl_store(&config).await?));
let (tx, rx) = mpsc::channel::<DiagDeviceCtrlMessage>(1);
let (ui_update_tx, ui_update_rx) = mpsc::channel::<framebuffer::DisplayState>(1);
let (analysis_tx, analysis_rx) = mpsc::channel::<AnalysisCtrlMessage>(5);
let mut maybe_ui_shutdown_tx = None;
if !config.debug_mode {
let (ui_shutdown_tx, ui_shutdown_rx) = oneshot::channel();
maybe_ui_shutdown_tx = Some(ui_shutdown_tx);
let mut dev = DiagDevice::new().await
.map_err(RayhunterError::DiagInitError)?;
dev.config_logs().await
.map_err(RayhunterError::DiagInitError)?;
info!("Starting Diag Thread");
run_diag_read_thread(&task_tracker, dev, rx, ui_update_tx.clone(), qmdl_store_lock.clone(), config.enable_dummy_analyzer);
info!("Starting UI");
update_ui(&task_tracker, &config, ui_shutdown_rx, ui_update_rx);
}
let (server_shutdown_tx, server_shutdown_rx) = oneshot::channel::<()>();
info!("create shutdown thread");
let analysis_status_lock = Arc::new(RwLock::new(AnalysisStatus::default()));
run_analysis_thread(&task_tracker, analysis_rx, qmdl_store_lock.clone(), analysis_status_lock.clone(), config.enable_dummy_analyzer);
run_ctrl_c_thread(&task_tracker, tx.clone(), server_shutdown_tx, maybe_ui_shutdown_tx, qmdl_store_lock.clone(), analysis_tx.clone());
run_server(&task_tracker, &config, qmdl_store_lock.clone(), server_shutdown_rx, ui_update_tx, tx, analysis_tx, analysis_status_lock).await;
task_tracker.close();
task_tracker.wait().await;
info!("see you space cowboy...");
Ok(())
}

View File

@@ -1,179 +0,0 @@
use std::pin::pin;
use std::sync::Arc;
use axum::body::Body;
use axum::extract::{Path, State};
use axum::http::header::CONTENT_TYPE;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use rayhunter::diag::DataType;
use rayhunter::diag_device::DiagDevice;
use tokio::sync::RwLock;
use tokio::sync::mpsc::{Receiver, Sender};
use rayhunter::qmdl::QmdlWriter;
use log::{debug, error, info};
use tokio::fs::File;
use tokio_util::io::ReaderStream;
use tokio_util::task::TaskTracker;
use futures::{StreamExt, TryStreamExt};
use crate::framebuffer;
use crate::qmdl_store::RecordingStore;
use crate::server::ServerState;
use crate::analysis::AnalysisWriter;
pub enum DiagDeviceCtrlMessage {
StopRecording,
StartRecording((QmdlWriter<File>, File)),
Exit,
}
pub fn run_diag_read_thread(
task_tracker: &TaskTracker,
mut dev: DiagDevice,
mut qmdl_file_rx: Receiver<DiagDeviceCtrlMessage>,
ui_update_sender: Sender<framebuffer::DisplayState>,
qmdl_store_lock: Arc<RwLock<RecordingStore>>,
enable_dummy_analyzer: bool,
) {
task_tracker.spawn(async move {
let (initial_qmdl_file, initial_analysis_file) = qmdl_store_lock.write().await.new_entry().await.expect("failed creating QMDL file entry");
let mut maybe_qmdl_writer: Option<QmdlWriter<File>> = Some(QmdlWriter::new(initial_qmdl_file));
let mut diag_stream = pin!(dev.as_stream().into_stream());
let mut maybe_analysis_writer = Some(AnalysisWriter::new(initial_analysis_file, enable_dummy_analyzer).await
.expect("failed to create analysis writer"));
loop {
tokio::select! {
msg = qmdl_file_rx.recv() => {
match msg {
Some(DiagDeviceCtrlMessage::StartRecording((new_writer, new_analysis_file))) => {
maybe_qmdl_writer = Some(new_writer);
if let Some(analysis_writer) = maybe_analysis_writer {
analysis_writer.close().await.expect("failed to close analysis writer");
}
maybe_analysis_writer = Some(AnalysisWriter::new(new_analysis_file, enable_dummy_analyzer).await
.expect("failed to write to analysis file"));
},
Some(DiagDeviceCtrlMessage::StopRecording) => {
maybe_qmdl_writer = None;
if let Some(analysis_writer) = maybe_analysis_writer {
analysis_writer.close().await.expect("failed to close analysis writer");
}
maybe_analysis_writer = None;
},
// None means all the Senders have been dropped, so it's
// time to go
Some(DiagDeviceCtrlMessage::Exit) | None => {
info!("Diag reader thread exiting...");
if let Some(analysis_writer) = maybe_analysis_writer {
analysis_writer.close().await.expect("failed to close analysis writer");
}
return Ok(())
},
}
}
maybe_container = diag_stream.next() => {
match maybe_container.unwrap() {
Ok(container) => {
if container.data_type != DataType::UserSpace {
debug!("skipping non-userspace diag messages...");
continue;
}
// keep track of how many bytes were written to the QMDL file so we can read
// a valid block of data from it in the HTTP server
if let Some(qmdl_writer) = maybe_qmdl_writer.as_mut() {
qmdl_writer.write_container(&container).await.expect("failed to write to QMDL writer");
debug!("total QMDL bytes written: {}, updating manifest...", qmdl_writer.total_written);
let mut qmdl_store = qmdl_store_lock.write().await;
let index = qmdl_store.current_entry.expect("DiagDevice had qmdl_writer, but QmdlStore didn't have current entry???");
qmdl_store.update_entry_qmdl_size(index, qmdl_writer.total_written).await
.expect("failed to update qmdl file size");
debug!("done!");
} else {
debug!("no qmdl_writer set, continuing...");
}
if let Some(analysis_writer) = maybe_analysis_writer.as_mut() {
let analysis_output = analysis_writer.analyze(container).await
.expect("failed to analyze container");
let (analysis_file_len, heuristic_warning) = analysis_output;
if heuristic_warning {
info!("a heuristic triggered on this run!");
ui_update_sender.send(framebuffer::DisplayState::WarningDetected).await
.expect("couldn't send ui update message: {}");
}
let mut qmdl_store = qmdl_store_lock.write().await;
let index = qmdl_store.current_entry.expect("DiagDevice had qmdl_writer, but QmdlStore didn't have current entry???");
qmdl_store.update_entry_analysis_size(index, analysis_file_len as usize).await
.expect("failed to update analysis file size");
}
},
Err(err) => {
error!("error reading diag device: {}", err);
return Err(err);
}
}
}
}
}
});
}
pub async fn start_recording(State(state): State<Arc<ServerState>>) -> Result<(StatusCode, String), (StatusCode, String)> {
if state.debug_mode {
return Err((StatusCode::FORBIDDEN, "server is in debug mode".to_string()));
}
let mut qmdl_store = state.qmdl_store_lock.write().await;
let (qmdl_file, analysis_file) = qmdl_store.new_entry().await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't create new qmdl entry: {}", e)))?;
let qmdl_writer = QmdlWriter::new(qmdl_file);
state.diag_device_ctrl_sender.send(DiagDeviceCtrlMessage::StartRecording((qmdl_writer, analysis_file))).await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't send stop recording message: {}", e)))?;
let display_state: framebuffer::DisplayState;
if state.colorblind_mode {
display_state = framebuffer::DisplayState::RecordingCBM;
} else {
display_state = framebuffer::DisplayState::Recording;
}
state.ui_update_sender.send(display_state).await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't send ui update message: {}", e)))?;
Ok((StatusCode::ACCEPTED, "ok".to_string()))
}
pub async fn stop_recording(State(state): State<Arc<ServerState>>) -> Result<(StatusCode, String), (StatusCode, String)> {
if state.debug_mode {
return Err((StatusCode::FORBIDDEN, "server is in debug mode".to_string()));
}
let mut qmdl_store = state.qmdl_store_lock.write().await;
qmdl_store.close_current_entry().await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't close current qmdl entry: {}", e)))?;
state.diag_device_ctrl_sender.send(DiagDeviceCtrlMessage::StopRecording).await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't send stop recording message: {}", e)))?;
state.ui_update_sender.send(framebuffer::DisplayState::Paused).await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't send ui update message: {}", e)))?;
Ok((StatusCode::ACCEPTED, "ok".to_string()))
}
pub async fn get_analysis_report(State(state): State<Arc<ServerState>>, Path(qmdl_name): Path<String>) -> Result<Response, (StatusCode, String)> {
let qmdl_store = state.qmdl_store_lock.read().await;
let (entry_index, _) = if qmdl_name == "live" {
qmdl_store.get_current_entry().ok_or((
StatusCode::SERVICE_UNAVAILABLE,
"No QMDL data's being recorded to analyze, try starting a new recording!".to_string()
))?
} else {
qmdl_store.entry_for_name(&qmdl_name).ok_or((
StatusCode::NOT_FOUND,
format!("Couldn't find QMDL entry with name \"{}\"", qmdl_name)
))?
};
let analysis_file = qmdl_store.open_entry_analysis(entry_index).await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("{:?}", e)))?;
let analysis_stream = ReaderStream::new(analysis_file);
let headers = [(CONTENT_TYPE, "application/x-ndjson")];
let body = Body::from_stream(analysis_stream);
Ok((headers, body).into_response())
}

View File

@@ -1,45 +0,0 @@
use std::borrow::Cow;
use rayhunter::telcom_parser::lte_rrc::{PCCH_MessageType, PCCH_MessageType_c1, PagingUE_Identity};
use rayhunter::analysis::analyzer::{Analyzer, Event, EventType, Severity};
use rayhunter::analysis::information_element::{InformationElement, LteInformationElement};
pub struct TestAnalyzer{
pub count: i32,
}
impl Analyzer for TestAnalyzer{
fn get_name(&self) -> Cow<str> {
Cow::from("Example Analyzer")
}
fn get_description(&self) -> Cow<str> {
Cow::from("Always returns true, if you are seeing this you are either a developer or you are about to have problems.")
}
fn analyze_information_element(&mut self, ie: &InformationElement) -> Option<Event> {
self.count += 1;
if self.count % 100 == 0 {
return Some(Event {
event_type: EventType::Informational ,
message: "multiple of 100 events processed".to_string(),
})
}
let InformationElement::LTE(LteInformationElement::PCCH(pcch_msg)) = ie else {
return None;
};
let PCCH_MessageType::C1(PCCH_MessageType_c1::Paging(paging)) = &pcch_msg.message else {
return None;
};
for record in &paging.paging_record_list.as_ref()?.0 {
if let PagingUE_Identity::S_TMSI(_) = record.ue_identity {
return Some(Event {
event_type: EventType::QualitativeWarning { severity: Severity::Low },
message: "TMSI was provided to cell".to_string(),
})
}
}
None
}
}

View File

@@ -1,111 +0,0 @@
use image::{codecs::gif::GifDecoder, imageops::FilterType, AnimationDecoder, DynamicImage};
use std::{io::Cursor, time::Duration};
const FB_PATH:&str = "/dev/fb0";
#[derive(Copy, Clone)]
// TODO actually poll for this, maybe w/ fbset?
struct Dimensions {
height: u32,
width: u32,
}
#[allow(dead_code)]
#[derive(Copy, Clone)]
pub enum Color565 {
Red = 0b1111100000000000,
Green = 0b0000011111100000,
Blue = 0b0000000000011111,
White = 0b1111111111111111,
Black = 0b0000000000000000,
Cyan = 0b0000011111111111,
Yellow = 0b1111111111100000,
Pink = 0b1111010010011111,
}
pub enum DisplayState {
Recording,
Paused,
WarningDetected,
RecordingCBM,
}
impl From<DisplayState> for Color565 {
fn from(state: DisplayState) -> Self {
match state {
DisplayState::Paused => Color565::White,
DisplayState::Recording => Color565::Green,
DisplayState::RecordingCBM => Color565::Blue,
DisplayState::WarningDetected => Color565::Red,
}
}
}
#[derive(Copy, Clone)]
pub struct Framebuffer<'a> {
dimensions: Dimensions,
path: &'a str,
}
impl Framebuffer<'_>{
pub const fn new() -> Self {
Framebuffer{
dimensions: Dimensions{height: 128, width: 128},
path: FB_PATH,
}
}
fn write(&mut self, img: DynamicImage) {
let mut width = img.width();
let mut height = img.height();
let resized_img: DynamicImage;
if height > self.dimensions.height ||
width > self.dimensions.width {
resized_img = img.resize( self.dimensions.width, self.dimensions.height, FilterType::CatmullRom);
width = self.dimensions.width.min(resized_img.width());
height = self.dimensions.height.min(resized_img.height());
} else {
resized_img = img;
}
let img_rgba8 = resized_img.as_rgba8().unwrap();
let mut buf = Vec::new();
for y in 0..height {
for x in 0..width {
let px = img_rgba8.get_pixel(x, y);
let mut rgb565: u16 = (px[0] as u16 & 0b11111000) << 8;
rgb565 |= (px[1] as u16 & 0b11111100) << 3;
rgb565 |= (px[2] as u16) >> 3;
buf.extend(rgb565.to_le_bytes());
}
}
std::fs::write(self.path, &buf).unwrap();
}
pub fn draw_gif(&mut self, img_buffer: &[u8]) {
// this is dumb and i'm sure there's a better way to loop this
let cursor = Cursor::new(img_buffer);
let decoder = GifDecoder::new(cursor).unwrap();
for maybe_frame in decoder.into_frames() {
let frame = maybe_frame.unwrap();
let (numerator, _) = frame.delay().numer_denom_ms();
let img = DynamicImage::from(frame.into_buffer());
self.write(img);
std::thread::sleep(Duration::from_millis(numerator as u64));
}
}
pub fn draw_img(&mut self, img_buffer: &[u8]) {
let img = image::load_from_memory(img_buffer).unwrap();
self.write(img);
}
pub fn draw_line(&mut self, color: Color565, height: u32){
let px_num= height * self.dimensions.width;
let color: u16 = color as u16;
let mut buffer: Vec<u8> = Vec::new();
for _ in 0..px_num {
buffer.extend(color.to_le_bytes());
}
std::fs::write(self.path, &buffer).unwrap();
}
}

View File

@@ -1,66 +0,0 @@
use crate::ServerState;
use rayhunter::diag::DataType;
use rayhunter::gsmtap_parser;
use rayhunter::pcap::GsmtapPcapWriter;
use rayhunter::qmdl::QmdlReader;
use axum::body::Body;
use axum::http::header::CONTENT_TYPE;
use axum::extract::{State, Path};
use axum::http::StatusCode;
use axum::response::{Response, IntoResponse};
use tokio::io::duplex;
use tokio_util::io::ReaderStream;
use std::{future, pin::pin};
use std::sync::Arc;
use log::error;
use futures::TryStreamExt;
// Streams a pcap file chunk-by-chunk to the client by reading the QMDL data
// written so far. This is done by spawning a thread which streams chunks of
// pcap data to a channel that's piped to the client.
pub async fn get_pcap(State(state): State<Arc<ServerState>>, Path(qmdl_name): Path<String>) -> Result<Response, (StatusCode, String)> {
let qmdl_store = state.qmdl_store_lock.read().await;
let (entry_index, entry) = qmdl_store.entry_for_name(&qmdl_name)
.ok_or((StatusCode::NOT_FOUND, format!("couldn't find qmdl file with name {}", qmdl_name)))?;
if entry.qmdl_size_bytes == 0 {
return Err((
StatusCode::SERVICE_UNAVAILABLE,
"QMDL file is empty, try again in a bit!".to_string()
));
}
let qmdl_size_bytes = entry.qmdl_size_bytes;
let qmdl_file = qmdl_store.open_entry_qmdl(entry_index).await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("{:?}", e)))?;
// the QMDL reader should stop at the last successfully written data chunk
// (entry.size_bytes)
let (reader, writer) = duplex(1024);
let mut pcap_writer = GsmtapPcapWriter::new(writer).await.unwrap();
pcap_writer.write_iface_header().await.unwrap();
tokio::spawn(async move {
let mut reader = QmdlReader::new(qmdl_file, Some(qmdl_size_bytes));
let mut messages_stream = pin!(reader.as_stream()
.try_filter(|container| future::ready(container.data_type == DataType::UserSpace)));
while let Some(container) = messages_stream.try_next().await.expect("failed getting QMDL container") {
for maybe_msg in container.into_messages() {
match maybe_msg {
Ok(msg) => {
let maybe_gsmtap_msg = gsmtap_parser::parse(msg)
.expect("error parsing gsmtap message");
if let Some((timestamp, gsmtap_msg)) = maybe_gsmtap_msg {
pcap_writer.write_gsmtap_message(gsmtap_msg, timestamp).await
.expect("error writing pcap packet");
}
},
Err(e) => error!("error parsing message: {:?}", e),
}
}
}
});
let headers = [(CONTENT_TYPE, "application/vnd.tcpdump.pcap")];
let body = Body::from_stream(ReaderStream::new(reader));
Ok((headers, body).into_response())
}

View File

@@ -1,335 +0,0 @@
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use thiserror::Error;
use tokio::{
fs::{self, try_exists, File, OpenOptions},
io::AsyncWriteExt,
};
#[derive(Debug, Error)]
pub enum RecordingStoreError {
#[error("Can't close an entry when there's no current entry")]
NoCurrentEntry,
#[error("Couldn't create file: {0}")]
CreateFileError(tokio::io::Error),
#[error("Couldn't read file: {0}")]
ReadFileError(tokio::io::Error),
#[error("Couldn't open directory at path: {0}")]
OpenDirError(tokio::io::Error),
#[error("Couldn't read manifest file: {0}")]
ReadManifestError(tokio::io::Error),
#[error("Couldn't write manifest file: {0}")]
WriteManifestError(tokio::io::Error),
#[error("Couldn't parse QMDL store manifest file: {0}")]
ParseManifestError(toml::de::Error),
}
pub struct RecordingStore {
pub path: PathBuf,
pub manifest: Manifest,
pub current_entry: Option<usize>, // index into manifest
}
#[derive(Deserialize, Serialize, Clone, PartialEq, Debug)]
pub struct Manifest {
pub entries: Vec<ManifestEntry>,
}
#[derive(Deserialize, Serialize, Clone, PartialEq, Debug)]
pub struct ManifestEntry {
pub name: String,
pub start_time: DateTime<Local>,
pub last_message_time: Option<DateTime<Local>>,
pub qmdl_size_bytes: usize,
pub analysis_size_bytes: usize,
}
impl ManifestEntry {
fn new() -> Self {
let now = Local::now();
ManifestEntry {
name: format!("{}", now.timestamp()),
start_time: now,
last_message_time: None,
qmdl_size_bytes: 0,
analysis_size_bytes: 0,
}
}
pub fn get_qmdl_filepath<P: AsRef<Path>>(&self, path: P) -> PathBuf {
let mut filepath = path.as_ref().join(&self.name);
filepath.set_extension("qmdl");
filepath
}
pub fn get_analysis_filepath<P: AsRef<Path>>(&self, path: P) -> PathBuf {
let mut filepath = path.as_ref().join(&self.name);
filepath.set_extension("ndjson");
filepath
}
}
impl RecordingStore {
// Returns whether a directory with a "manifest.toml" exists at the given
// path (though doesn't check if that manifest is valid)
pub async fn exists<P>(path: P) -> Result<bool, RecordingStoreError>
where
P: AsRef<Path>,
{
let manifest_path = path.as_ref().join("manifest.toml");
let dir_exists = try_exists(path)
.await
.map_err(RecordingStoreError::OpenDirError)?;
let manifest_exists = try_exists(manifest_path)
.await
.map_err(RecordingStoreError::ReadManifestError)?;
Ok(dir_exists && manifest_exists)
}
// Loads an existing RecordingStore at the given path. Errors if no store exists,
// or if it's malformed.
pub async fn load<P>(path: P) -> Result<Self, RecordingStoreError>
where
P: AsRef<Path>,
{
let path: PathBuf = path.as_ref().to_path_buf();
let manifest = RecordingStore::read_manifest(&path).await?;
Ok(RecordingStore {
path,
manifest,
current_entry: None,
})
}
// Creates a new RecordingStore at the given path. This involves creating a dir
// and writing an empty manifest.
pub async fn create<P>(path: P) -> Result<Self, RecordingStoreError>
where
P: AsRef<Path>,
{
let manifest_path = path.as_ref().join("manifest.toml");
fs::create_dir_all(&path)
.await
.map_err(RecordingStoreError::OpenDirError)?;
let mut manifest_file = File::create(&manifest_path)
.await
.map_err(RecordingStoreError::WriteManifestError)?;
let empty_manifest = Manifest {
entries: Vec::new(),
};
let empty_manifest_contents =
toml::to_string_pretty(&empty_manifest).expect("failed to serialize manifest");
manifest_file
.write_all(empty_manifest_contents.as_bytes())
.await
.map_err(RecordingStoreError::WriteManifestError)?;
RecordingStore::load(path).await
}
async fn read_manifest<P>(path: P) -> Result<Manifest, RecordingStoreError>
where
P: AsRef<Path>,
{
let manifest_path = path.as_ref().join("manifest.toml");
let file_contents = fs::read_to_string(&manifest_path)
.await
.map_err(RecordingStoreError::ReadManifestError)?;
toml::from_str(&file_contents).map_err(RecordingStoreError::ParseManifestError)
}
// Closes the current entry (if needed), creates a new entry based on the
// current time, and updates the manifest. Returns a tuple of the entry's
// newly created QMDL file and analysis file.
pub async fn new_entry(&mut self) -> Result<(File, File), RecordingStoreError> {
// if we've already got an entry open, close it
if self.current_entry.is_some() {
self.close_current_entry().await?;
}
let new_entry = ManifestEntry::new();
let qmdl_filepath = new_entry.get_qmdl_filepath(&self.path);
let qmdl_file = File::options()
.create(true)
.write(true)
.open(&qmdl_filepath)
.await
.map_err(RecordingStoreError::CreateFileError)?;
let analysis_filepath = new_entry.get_analysis_filepath(&self.path);
let analysis_file = File::options()
.create(true)
.write(true)
.open(&analysis_filepath)
.await
.map_err(RecordingStoreError::CreateFileError)?;
self.manifest.entries.push(new_entry);
self.current_entry = Some(self.manifest.entries.len() - 1);
self.write_manifest().await?;
Ok((qmdl_file, analysis_file))
}
// Returns the corresponding QMDL file for a given entry
pub async fn open_entry_qmdl(
&self,
entry_index: usize,
) -> Result<File, RecordingStoreError> {
let entry = &self.manifest.entries[entry_index];
File::open(entry.get_qmdl_filepath(&self.path))
.await
.map_err(RecordingStoreError::ReadFileError)
}
// Returns the corresponding QMDL file for a given entry
pub async fn open_entry_analysis(
&self,
entry_index: usize,
) -> Result<File, RecordingStoreError> {
let entry = &self.manifest.entries[entry_index];
File::open(entry.get_analysis_filepath(&self.path))
.await
.map_err(RecordingStoreError::ReadFileError)
}
pub async fn clear_and_open_entry_analysis(
&mut self,
entry_index: usize,
) -> Result<File, RecordingStoreError> {
let entry = &self.manifest.entries[entry_index];
let file = OpenOptions::new()
.write(true)
.truncate(true)
.open(entry.get_analysis_filepath(&self.path))
.await
.map_err(RecordingStoreError::ReadFileError)?;
self.update_entry_analysis_size(entry_index, 0)
.await?;
Ok(file)
}
// Unsets the current entry
pub async fn close_current_entry(&mut self) -> Result<(), RecordingStoreError> {
match self.current_entry {
Some(_) => {
self.current_entry = None;
Ok(())
}
None => Err(RecordingStoreError::NoCurrentEntry),
}
}
// Sets the given entry's size and updates the last_message_time to now, updating the manifest
pub async fn update_entry_qmdl_size(
&mut self,
entry_index: usize,
size_bytes: usize,
) -> Result<(), RecordingStoreError> {
self.manifest.entries[entry_index].qmdl_size_bytes = size_bytes;
self.manifest.entries[entry_index].last_message_time = Some(Local::now());
self.write_manifest().await
}
// Sets the given entry's analysis file size
pub async fn update_entry_analysis_size(
&mut self,
entry_index: usize,
size_bytes: usize,
) -> Result<(), RecordingStoreError> {
self.manifest.entries[entry_index].analysis_size_bytes = size_bytes;
self.write_manifest().await
}
async fn write_manifest(&mut self) -> Result<(), RecordingStoreError> {
let mut manifest_file = File::options()
.write(true)
.open(self.path.join("manifest.toml"))
.await
.map_err(RecordingStoreError::WriteManifestError)?;
let manifest_contents =
toml::to_string_pretty(&self.manifest).expect("failed to serialize manifest");
manifest_file
.write_all(manifest_contents.as_bytes())
.await
.map_err(RecordingStoreError::WriteManifestError)?;
Ok(())
}
// Finds an entry by filename
pub fn entry_for_name(&self, name: &str) -> Option<(usize, &ManifestEntry)> {
let entry_index = self.manifest
.entries
.iter()
.position(|entry| entry.name == name)?;
Some((entry_index, &self.manifest.entries[entry_index]))
}
pub fn get_current_entry(&self) -> Option<(usize, &ManifestEntry)> {
let entry_index = self.current_entry?;
Some((entry_index, &self.manifest.entries[entry_index]))
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::{Builder, TempDir};
fn make_temp_dir() -> TempDir {
Builder::new().prefix("qmdl_store_test").tempdir().unwrap()
}
#[tokio::test]
async fn test_load_from_empty_dir() {
let dir = make_temp_dir();
assert!(!RecordingStore::exists(dir.path()).await.unwrap());
let _created_store = RecordingStore::create(dir.path()).await.unwrap();
assert!(RecordingStore::exists(dir.path()).await.unwrap());
let loaded_store = RecordingStore::load(dir.path()).await.unwrap();
assert_eq!(loaded_store.manifest.entries.len(), 0);
}
#[tokio::test]
async fn test_creating_updating_and_closing_entries() {
let dir = make_temp_dir();
let mut store = RecordingStore::create(dir.path()).await.unwrap();
let _ = store.new_entry().await.unwrap();
let entry_index = store.current_entry.unwrap();
assert_eq!(
RecordingStore::read_manifest(dir.path()).await.unwrap(),
store.manifest
);
assert!(store.manifest.entries[entry_index]
.last_message_time
.is_none());
store
.update_entry_qmdl_size(entry_index, 1000)
.await
.unwrap();
let (entry_index, entry) = store
.entry_for_name(&store.manifest.entries[entry_index].name)
.unwrap();
assert!(entry.last_message_time.is_some());
assert_eq!(store.manifest.entries[entry_index].qmdl_size_bytes, 1000);
assert_eq!(
RecordingStore::read_manifest(dir.path()).await.unwrap(),
store.manifest
);
store.close_current_entry().await.unwrap();
assert!(matches!(
store.close_current_entry().await,
Err(RecordingStoreError::NoCurrentEntry)
));
}
#[tokio::test]
async fn test_repeated_new_entries() {
let dir = make_temp_dir();
let mut store = RecordingStore::create(dir.path()).await.unwrap();
let _ = store.new_entry().await.unwrap();
let entry_index = store.current_entry.unwrap();
let _ = store.new_entry().await.unwrap();
let new_entry_index = store.current_entry.unwrap();
assert_ne!(entry_index, new_entry_index);
assert_eq!(store.manifest.entries.len(), 2);
}
}

View File

@@ -1,93 +0,0 @@
use axum::body::Body;
use axum::http::header::{CONTENT_TYPE, self};
use axum::extract::State;
use axum::http::{StatusCode, HeaderValue};
use axum::response::{Response, IntoResponse};
use axum::extract::Path;
use tokio::fs::File;
use tokio::io::AsyncReadExt;
use tokio::sync::mpsc::Sender;
use std::sync::Arc;
use tokio::sync::RwLock;
use tokio_util::io::ReaderStream;
use include_dir::{include_dir, Dir};
use crate::{framebuffer, DiagDeviceCtrlMessage};
use crate::analysis::{AnalysisCtrlMessage, AnalysisStatus};
use crate::qmdl_store::RecordingStore;
pub struct ServerState {
pub qmdl_store_lock: Arc<RwLock<RecordingStore>>,
pub diag_device_ctrl_sender: Sender<DiagDeviceCtrlMessage>,
pub ui_update_sender: Sender<framebuffer::DisplayState>,
pub analysis_status_lock: Arc<RwLock<AnalysisStatus>>,
pub analysis_sender: Sender<AnalysisCtrlMessage>,
pub debug_mode: bool,
pub colorblind_mode: bool,
}
pub async fn get_qmdl(State(state): State<Arc<ServerState>>, Path(qmdl_name): Path<String>) -> Result<Response, (StatusCode, String)> {
let qmdl_store = state.qmdl_store_lock.read().await;
let (entry_index, entry) = qmdl_store.entry_for_name(&qmdl_name)
.ok_or((StatusCode::NOT_FOUND, format!("couldn't find qmdl file with name {}", qmdl_name)))?;
let qmdl_file = qmdl_store.open_entry_qmdl(entry_index).await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("error opening QMDL file: {}", e)))?;
let limited_qmdl_file = qmdl_file.take(entry.qmdl_size_bytes as u64);
let qmdl_stream = ReaderStream::new(limited_qmdl_file);
let headers = [(CONTENT_TYPE, "application/octet-stream")];
let body = Body::from_stream(qmdl_stream);
Ok((headers, body).into_response())
}
// Bundles the server's static files (html/css/js) into the binary for easy distribution
static STATIC_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/static");
pub async fn serve_static(State(state): State<Arc<ServerState>>, Path(path): Path<String>) -> impl IntoResponse {
let path = path.trim_start_matches('/');
let mime_type = mime_guess::from_path(path).first_or_text_plain();
// if we're in debug mode, return the files from the build directory so we
// don't have to rebuild every time the JS/HTML change
if state.debug_mode {
let mut build_path = std::path::PathBuf::new();
build_path.push("bin");
build_path.push("static");
for part in path.split("/") {
build_path.push(part);
}
return match File::open(build_path).await {
Ok(mut file) => {
let mut body = String::new();
file.read_to_string(&mut body).await.expect("failed to read file");
Response::builder()
.status(StatusCode::OK)
.header(
header::CONTENT_TYPE,
HeaderValue::from_str(mime_type.as_ref()).unwrap(),
)
.body(Body::from(body))
.unwrap()
},
Err(_) => Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap()
};
}
match STATIC_DIR.get_file(path) {
None => Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::empty())
.unwrap(),
Some(file) => Response::builder()
.status(StatusCode::OK)
.header(
header::CONTENT_TYPE,
HeaderValue::from_str(mime_type.as_ref()).unwrap(),
)
.body(Body::from(file.contents()))
.unwrap(),
}
}

View File

@@ -1,128 +0,0 @@
use std::sync::Arc;
use crate::qmdl_store::ManifestEntry;
use crate::server::ServerState;
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use log::error;
use serde::Serialize;
use tokio::process::Command;
#[derive(Debug, Serialize)]
pub struct SystemStats {
pub disk_stats: DiskStats,
pub memory_stats: MemoryStats,
}
impl SystemStats {
pub async fn new(qmdl_path: &str) -> Result<Self, String> {
Ok(Self {
disk_stats: DiskStats::new(qmdl_path).await?,
memory_stats: MemoryStats::new().await?,
})
}
}
#[derive(Debug, Serialize)]
pub struct DiskStats {
partition: String,
total_size: String,
used_size: String,
available_size: String,
used_percent: String,
mounted_on: String,
}
impl DiskStats {
// runs "df -h <qmdl_path>" to get storage statistics for the partition containing
// the QMDL file
pub async fn new(qmdl_path: &str) -> Result<Self, String> {
let mut df_cmd = Command::new("df");
df_cmd.arg("-h");
df_cmd.arg(qmdl_path);
let stdout = get_cmd_output(df_cmd).await?;
let mut parts = stdout.split_whitespace().skip(7).to_owned();
Ok(Self {
partition: parts.next().ok_or("error parsing df output")?.to_string(),
total_size: parts.next().ok_or("error parsing df output")?.to_string(),
used_size: parts.next().ok_or("error parsing df output")?.to_string(),
available_size: parts.next().ok_or("error parsing df output")?.to_string(),
used_percent: parts.next().ok_or("error parsing df output")?.to_string(),
mounted_on: parts.next().ok_or("error parsing df output")?.to_string(),
})
}
}
#[derive(Debug, Serialize)]
pub struct MemoryStats {
total: String,
used: String,
free: String,
}
// runs the given command and returns its stdout as a string
async fn get_cmd_output(mut cmd: Command) -> Result<String, String> {
let cmd_str = format!("{:?}", &cmd);
let output = cmd.output().await
.map_err(|e| format!("error running command {}: {}", &cmd_str, e))?;
if !output.status.success() {
return Err(format!("command {} failed with exit code {}", &cmd_str, output.status.code().unwrap()));
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
impl MemoryStats {
// runs "free -k" and parses the output to retrieve memory stats
pub async fn new() -> Result<Self, String> {
let mut free_cmd = Command::new("free");
free_cmd.arg("-k");
let stdout = get_cmd_output(free_cmd).await?;
let mut numbers = stdout.split_whitespace()
.flat_map(|part| part.parse::<usize>());
Ok(Self {
total: humanize_kb(numbers.next().ok_or("error parsing free output")?),
used: humanize_kb(numbers.next().ok_or("error parsing free output")?),
free: humanize_kb(numbers.next().ok_or("error parsing free output")?),
})
}
}
// turns a number of kilobytes (like 28293) into a human-readable string (like "28.3M")
fn humanize_kb(kb: usize) -> String {
if kb < 1000{
return format!("{}K", kb);
}
format!("{:.1}M", kb as f64 / 1024.0)
}
pub async fn get_system_stats(State(state): State<Arc<ServerState>>) -> Result<Json<SystemStats>, (StatusCode, String)> {
let qmdl_store = state.qmdl_store_lock.read().await;
match SystemStats::new(qmdl_store.path.to_str().unwrap()).await {
Ok(stats) => Ok(Json(stats)),
Err(err) => {
error!("error getting system stats: {}", err);
Err((
StatusCode::INTERNAL_SERVER_ERROR,
"error getting system stats".to_string()
))
},
}
}
#[derive(Serialize)]
pub struct ManifestStats {
pub entries: Vec<ManifestEntry>,
pub current_entry: Option<ManifestEntry>,
}
pub async fn get_qmdl_manifest(State(state): State<Arc<ServerState>>) -> Result<Json<ManifestStats>, (StatusCode, String)> {
let qmdl_store = state.qmdl_store_lock.read().await;
let mut entries = qmdl_store.manifest.entries.clone();
let current_entry = qmdl_store.current_entry.map(|index| entries.remove(index));
Ok(Json(ManifestStats {
entries,
current_entry,
}))
}

View File

@@ -1,45 +0,0 @@
td,
th {
border: 1px solid rgb(190, 190, 190);
padding: 10px;
}
td {
text-align: center;
}
tr:nth-child(even) {
background-color: #eee;
}
th[scope='col'] {
background-color: #696969;
color: #fff;
}
th[scope='row'] {
background-color: #d7d9f2;
}
tr.current {
background-color: #53fe7b;
font-weight: bold;
}
tr.warning {
background-color: #fe537b;
font-weight: bold;
}
caption {
padding: 10px;
caption-side: bottom;
}
table {
border-collapse: collapse;
border: 2px solid rgb(200, 200, 200);
letter-spacing: 1px;
font-family: sans-serif;
font-size: 0.8rem;
}

View File

@@ -1,43 +0,0 @@
<html>
<head>
<title>rayhunter</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/main.js"></script>
<script>
async function repeatedlyPopulate() {
await populateDivs();
setTimeout(repeatedlyPopulate, 1000);
}
window.onload = function() {
repeatedlyPopulate();
}
</script>
</head>
<body>
<div>
<button onclick="startRecording()">Start Recording</button>
<button onclick="stopRecording()">Stop Recording</button>
</div>
<table id="qmdl-manifest-table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Date Started</th>
<th scope="col">Date of Last Message</th>
<th scope="col">Size (bytes)</th>
<th scope="col">PCAP</th>
<th scope="col">QMDL</th>
<th scope="col">Analysis Result</th>
</tr>
</thead>
</table>
<div>
<h3>Live System stats</h3>
<pre id="system-stats">Loading...</pre>
</div>
<div>
<h3>Analysis Report of Current Capture</h3>
<pre id="analysis-report">Loading...</pre>
</div>
</body>
</html>

View File

@@ -1,206 +0,0 @@
const STATUS_RUNNING = 'running';
const STATUS_QUEUED = 'queued';
const STATUS_NEEDS_UPDATE = 'needs-update';
const STATUS_COMPLETE = 'complete';
async function populateDivs() {
const systemStats = await getSystemStats();
const systemStatsDiv = document.getElementById('system-stats');
systemStatsDiv.innerHTML = JSON.stringify(systemStats, null, 2);
const analysisReportDiv = document.getElementById('analysis-report');
try {
const analysisReport = await getAnalysisReport('live');
analysisReportDiv.innerHTML = JSON.stringify(analysisReport, null, 2);
} catch (e) {
analysisReportDiv.innerHTML = e.toString();
}
const qmdlManifest = await getQmdlManifest();
await updateAnalysisStatus(qmdlManifest);
await updateAnalysisResults(qmdlManifest);
updateQmdlManifestTable(qmdlManifest);
}
function setStatus(qmdlManifest, name, status) {
// ignore qmdlManifest.current_entry, it's always running
for (const entry of qmdlManifest.entries) {
if (entry.name === name) {
entry['status'] = status;
return;
}
}
}
async function updateAnalysisStatus(qmdlManifest) {
const status = JSON.parse(await req('GET', '/api/analysis'));
if (status.running) {
setStatus(qmdlManifest, status.running, STATUS_RUNNING);
}
for (const queued in status.queued) {
setStatus(qmdlManifest, queued, STATUS_QUEUED);
}
}
function parseNewlineDelimitedJSON(inputStr) {
const lines = inputStr.split('\n');
const result = [];
let currentLine = '';
while (lines.length > 0) {
currentLine += lines.shift();
try {
const entry = JSON.parse(currentLine);
result.push(entry);
currentLine = '';
// if this chunk wasn't valid JSON, there was an escaped newline in the
// JSON line, so simply continue to the next one
} catch (e) {}
}
return result;
}
async function updateEntryAnalysisResult(entry) {
entry.analysis = {
warnings: [],
};
const report = parseNewlineDelimitedJSON(await req('GET', `/api/analysis-report/${entry.name}`));
for (const row of report) {
if (row["analysis"]) {
const timestamp = new Date(row["timestamp"]);
const analysis = row["analysis"];
for (const warning of analysis) {
entry.analysis.warnings.push({
timestamp,
warning,
})
}
}
}
if (entry.analysis.warnings.length === 0) {
entry.analysis_result = `0 warnings!`;
} else {
entry.analysis_result = `!!! ${entry.analysis.warnings.length} warnings !!!`;
}
}
async function updateAnalysisResults(qmdlManifest) {
if (qmdlManifest.current_entry) {
await updateEntryAnalysisResult(qmdlManifest.current_entry);
}
for (const entry of qmdlManifest.entries) {
if (entry.status === STATUS_NEEDS_UPDATE) {
await updateEntryAnalysisResult(entry);
entry.status = STATUS_COMPLETE;
}
}
}
function updateQmdlManifestTable(manifest) {
const table = document.getElementById('qmdl-manifest-table');
const numRows = table.rows.length;
for (let i=1; i<numRows; i++) {
table.deleteRow(1);
}
if (manifest.current_entry) {
const row = createEntryRow(manifest.current_entry, true);
row.classList.add('current');
table.appendChild(row)
}
for (let entry of manifest.entries) {
table.appendChild(createEntryRow(entry), false);
}
}
function createLink(uri, text) {
const link = document.createElement('a');
link.href = uri;
link.innerText = text;
return link;
}
function createEntryRow(entry, isCurrent) {
const row = document.createElement('tr');
const name = document.createElement('th');
name.scope = 'row';
name.innerText = entry.name;
row.appendChild(name);
for (const key of ['start_time', 'last_message_time', 'qmdl_size_bytes']) {
const td = document.createElement('td');
td.innerText = entry[key];
row.appendChild(td);
}
const pcapTd = document.createElement('td');
pcapTd.appendChild(createLink(`/api/pcap/${entry.name}`, 'pcap'));
row.appendChild(pcapTd);
const qmdlTd = document.createElement('td');
qmdlTd.appendChild(createLink(`/api/qmdl/${entry.name}`, 'qmdl'));
row.appendChild(qmdlTd);
const analysisResult = document.createElement('td');
analysisResult.innerText = entry.analysis_result;
if (entry.analysis.warnings.length > 0) {
row.classList.add("warning");
}
row.appendChild(analysisResult);
return row;
}
async function getAnalysisReport(name) {
const rows = await req('GET', `/api/analysis-report/${name}`);
return rows.split('\n')
.filter(row => row.length > 0)
.map(row => JSON.parse(row));
}
async function getSystemStats() {
return JSON.parse(await req('GET', '/api/system-stats'));
}
async function getQmdlManifest() {
const manifest = JSON.parse(await req('GET', '/api/qmdl-manifest'));
if (manifest.current_entry) {
manifest.current_entry.status = STATUS_NEEDS_UPDATE;
manifest.current_entry.analysis_result = 'Waiting...';
manifest.current_entry.start_time = new Date(manifest.current_entry.start_time);
if (manifest.current_entry.last_message_time === undefined) {
manifest.current_entry.last_message_time = "N/A";
} else {
manifest.current_entry.last_message_time = new Date(manifest.current_entry.last_message_time);
}
}
for (entry of manifest.entries) {
entry.status = STATUS_NEEDS_UPDATE;
entry.analysis_result = 'Waiting...';
entry.start_time = new Date(entry.start_time);
entry.last_message_time = new Date(entry.last_message_time);
}
// sort them in reverse chronological order
manifest.entries.reverse();
return manifest;
}
async function startRecording() {
await req('POST', '/api/start-recording');
populateDivs();
}
async function stopRecording() {
await req('POST', '/api/stop-recording');
populateDivs();
}
async function req(method, url) {
const response = await fetch(url, {
method: method,
});
const body = await response.text();
if (response.status >= 200 && response.status < 300) {
return body;
} else {
throw new Error(body);
}
}

9
book.toml Normal file
View File

@@ -0,0 +1,9 @@
[book]
authors = ["The Rayhunter Team"]
language = "en"
src = "doc"
title = "Rayhunter - An IMSI Catcher Catcher"
[output.html]
edit-url-template = "https://github.com/efforg/rayhunter/edit/main/{path}"
additional-css = ["doc/custom.css"]

13
check/Cargo.toml Normal file
View File

@@ -0,0 +1,13 @@
[package]
name = "rayhunter-check"
version = "0.10.2"
edition = "2024"
[dependencies]
rayhunter = { path = "../lib" }
futures = { version = "0.3.30", default-features = false }
log = "0.4.20"
tokio = { version = "1.44.2", default-features = false, features = ["fs", "signal", "process", "rt-multi-thread"] }
pcap-file-tokio = "0.1.0"
clap = { version = "4.5.2", features = ["derive"] }
walkdir = "2.5.0"

214
check/src/main.rs Normal file
View File

@@ -0,0 +1,214 @@
use clap::Parser;
use futures::TryStreamExt;
use log::{debug, error, info, warn};
use pcap_file_tokio::pcapng::{Block, PcapNgReader};
use rayhunter::{
analysis::analyzer::{AnalysisRow, AnalyzerConfig, EventType, Harness},
diag::DataType,
gsmtap_parser,
pcap::GsmtapPcapWriter,
qmdl::QmdlReader,
};
use std::{collections::HashMap, future, path::PathBuf, pin::pin};
use tokio::fs::File;
use walkdir::WalkDir;
#[derive(Parser, Debug)]
#[command(version, about)]
struct Args {
#[arg(short = 'p', long, help = "A file or directory of packet captures")]
path: PathBuf,
#[arg(short = 'P', long, help = "Convert qmdl files to pcap before analysis")]
pcapify: bool,
#[arg(long, help = "Show why some packets were skipped during analysis")]
show_skipped: bool,
#[arg(short, long, help = "Only print warnings/errors to stdout")]
quiet: bool,
#[arg(short, long, help = "Show debug messages")]
debug: bool,
}
#[derive(Default)]
struct Report {
skipped_reasons: HashMap<String, u32>,
total_messages: u32,
warnings: u32,
skipped: u32,
file_path: String,
}
impl Report {
fn new(file_path: &str) -> Self {
Report {
file_path: file_path.to_string(),
..Default::default()
}
}
fn process_row(&mut self, row: AnalysisRow) {
self.total_messages += 1;
if let Some(reason) = row.skipped_message_reason {
*self.skipped_reasons.entry(reason).or_insert(0) += 1;
self.skipped += 1;
return;
}
for maybe_event in row.events {
let Some(event) = maybe_event else { continue };
let Some(timestamp) = row.packet_timestamp else {
continue;
};
match event.event_type {
EventType::Informational => {
info!("{}: INFO - {} {}", self.file_path, timestamp, event.message,);
}
EventType::Low | EventType::Medium | EventType::High => {
warn!(
"{}: WARNING (Severity: {:?}) - {} {}",
self.file_path, event.event_type, timestamp, event.message,
);
self.warnings += 1;
}
}
}
}
fn print_summary(&self, show_skipped: bool) {
if show_skipped && self.skipped > 0 {
info!("{}: messages skipped:", self.file_path);
for (reason, count) in self.skipped_reasons.iter() {
info!(" - {count}: \"{reason}\"");
}
}
info!(
"{}: {} messages analyzed, {} warnings, {} messages skipped",
self.file_path, self.total_messages, self.warnings, self.skipped
);
}
}
async fn analyze_pcap(pcap_path: &str, show_skipped: bool) {
let mut harness = Harness::new_with_config(&AnalyzerConfig::default());
let pcap_file = &mut File::open(&pcap_path).await.expect("failed to open file");
let mut pcap_reader = PcapNgReader::new(pcap_file)
.await
.expect("failed to read PCAP file");
let mut report = Report::new(pcap_path);
while let Some(Ok(block)) = pcap_reader.next_block().await {
let row = match block {
Block::EnhancedPacket(packet) => harness.analyze_pcap_packet(packet),
other => {
debug!("{pcap_path}: skipping pcap packet {other:?}");
continue;
}
};
report.process_row(row);
}
report.print_summary(show_skipped);
}
async fn analyze_qmdl(qmdl_path: &str, show_skipped: bool) {
let mut harness = Harness::new_with_config(&AnalyzerConfig::default());
let qmdl_file = &mut File::open(&qmdl_path).await.expect("failed to open file");
let file_size = qmdl_file
.metadata()
.await
.expect("failed to get QMDL file metadata")
.len();
let mut qmdl_reader = QmdlReader::new(qmdl_file, Some(file_size as usize));
let mut qmdl_stream = pin!(
qmdl_reader
.as_stream()
.try_filter(|container| future::ready(container.data_type == DataType::UserSpace))
);
let mut report = Report::new(qmdl_path);
while let Some(container) = qmdl_stream
.try_next()
.await
.expect("failed getting QMDL container")
{
for row in harness.analyze_qmdl_messages(container) {
report.process_row(row);
}
}
report.print_summary(show_skipped);
}
async fn pcapify(qmdl_path: &PathBuf) {
let qmdl_file = &mut File::open(&qmdl_path)
.await
.expect("failed to open qmdl file");
let qmdl_file_size = qmdl_file.metadata().await.unwrap().len();
let mut qmdl_reader = QmdlReader::new(qmdl_file, Some(qmdl_file_size as usize));
let mut pcap_path = qmdl_path.clone();
pcap_path.set_extension("pcapng");
let pcap_file = &mut File::create(&pcap_path)
.await
.expect("failed to open pcap file");
let mut pcap_writer = GsmtapPcapWriter::new(pcap_file).await.unwrap();
pcap_writer.write_iface_header().await.unwrap();
while let Some(container) = qmdl_reader
.get_next_messages_container()
.await
.expect("failed to get container")
{
for msg in container.into_messages().into_iter().flatten() {
if let Ok(Some((timestamp, parsed))) = gsmtap_parser::parse(msg) {
pcap_writer
.write_gsmtap_message(parsed, timestamp)
.await
.expect("failed to write");
}
}
}
info!("wrote pcap to {:?}", &pcap_path);
}
#[tokio::main]
async fn main() {
let args = Args::parse();
let level = if args.debug {
log::LevelFilter::Debug
} else if args.quiet {
log::LevelFilter::Warn
} else {
log::LevelFilter::Info
};
rayhunter::init_logging(level);
let harness = Harness::new_with_config(&AnalyzerConfig::default());
info!("Analyzers:");
for analyzer in harness.get_metadata().analyzers {
info!(
" - {} (v{}): {}",
analyzer.name, analyzer.version, analyzer.description
);
}
for maybe_entry in WalkDir::new(&args.path) {
let Ok(entry) = maybe_entry else {
error!("failed to open dir entry {maybe_entry:?}");
continue;
};
let name = entry.file_name();
let name_str = name.to_str().unwrap();
let path = entry.path();
let path_str = path.to_str().unwrap();
// instead of relying on the QMDL extension, can we check if a file is
// QMDL by inspecting the contents?
if name_str.ends_with(".qmdl") {
info!("**** Beginning analysis of {name_str}");
analyze_qmdl(path_str, args.show_skipped).await;
if args.pcapify {
pcapify(&path.to_path_buf()).await;
}
} else if name_str.ends_with(".pcap") || name_str.ends_with(".pcapng") {
// TODO: if we've already analyzed a QMDL, skip its corresponding pcap
info!("**** Beginning analysis of {name_str}");
analyze_pcap(path_str, args.show_skipped).await;
}
}
}

48
daemon/Cargo.toml Normal file
View File

@@ -0,0 +1,48 @@
[package]
name = "rayhunter-daemon"
version = "0.10.2"
edition = "2024"
rust-version = "1.88.0"
[lib]
name = "rayhunter_daemon"
path = "src/lib.rs"
[[bin]]
name = "gen_api"
path = "src/bin/gen_api.rs"
required-features = ["apidocs"]
[features]
default = ["rustcrypto-tls"]
rustcrypto-tls = ["reqwest/rustls-tls-webpki-roots-no-provider", "dep:rustls-rustcrypto"]
pq-tls = ["reqwest/rustls-tls-webpki-roots-no-provider", "dep:rustls-post-quantum"]
apidocs = ["dep:utoipa", "wifi-station/utoipa"]
[dependencies]
rayhunter = { path = "../lib" }
wifi-station = { git = "https://github.com/BeigeBox/wifi-station", rev = "e8ec5b4" }
toml = "0.8.8"
serde = { version = "1.0.193", features = ["derive"] }
tokio = { version = "1.44.2", default-features = false, features = ["fs", "signal", "process", "rt"] }
axum = { version = "0.8", default-features = false, features = ["http1", "tokio", "json"] }
thiserror = "1.0.52"
libc = "0.2.150"
log = "0.4.20"
tokio-util = { version = "0.7.10", features = ["rt", "io", "compat"] }
futures-macro = "0.3.30"
include_dir = "0.7.3"
chrono = { version = "0.4.31", features = ["serde"] }
tokio-stream = { version = "0.1.14", default-features = false, features = ["io-util"] }
futures = { version = "0.3.30", default-features = false }
serde_json = "1.0.114"
image = { version = "0.25.1", default-features = false, features = ["png", "gif"] }
tempfile = "3.10.2"
async_zip = { version = "0.0.17", features = ["tokio"] }
anyhow = "1.0.98"
reqwest = { version = "0.12.20", default-features = false, features = ["stream"] }
rustls-rustcrypto = { version = "0.0.2-alpha", optional = true }
rustls-post-quantum = { version = "0.2.4", optional = true }
async-trait = "0.1.88"
utoipa = { version = "5.4.0", optional = true }
url = "2.5.4"

View File

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 88 KiB

View File

@@ -1,5 +1,5 @@
use std::sync::Arc; use std::sync::Arc;
use std::{future, pin}; use std::{cmp, future, pin};
use axum::Json; use axum::Json;
use axum::{ use axum::{
@@ -7,8 +7,8 @@ use axum::{
http::StatusCode, http::StatusCode,
}; };
use futures::TryStreamExt; use futures::TryStreamExt;
use log::{debug, error, info}; use log::{error, info};
use rayhunter::analysis::analyzer::Harness; use rayhunter::analysis::analyzer::{AnalyzerConfig, EventType, Harness};
use rayhunter::diag::{DataType, MessagesContainer}; use rayhunter::diag::{DataType, MessagesContainer};
use rayhunter::qmdl::QmdlReader; use rayhunter::qmdl::QmdlReader;
use serde::Serialize; use serde::Serialize;
@@ -20,12 +20,10 @@ use tokio_util::task::TaskTracker;
use crate::qmdl_store::RecordingStore; use crate::qmdl_store::RecordingStore;
use crate::server::ServerState; use crate::server::ServerState;
use crate::dummy_analyzer::TestAnalyzer;
pub struct AnalysisWriter { pub struct AnalysisWriter {
writer: BufWriter<File>, writer: BufWriter<File>,
harness: Harness, harness: Harness,
bytes_written: usize,
} }
// We write our analysis results to a file immediately to minimize the amount of // We write our analysis results to a file immediately to minimize the amount of
@@ -35,15 +33,11 @@ pub struct AnalysisWriter {
// lets us simply append new rows to the end without parsing the entire JSON // lets us simply append new rows to the end without parsing the entire JSON
// object beforehand. // object beforehand.
impl AnalysisWriter { impl AnalysisWriter {
pub async fn new(file: File, enable_dummy_analyzer: bool) -> Result<Self, std::io::Error> { pub async fn new(file: File, analyzer_config: &AnalyzerConfig) -> Result<Self, std::io::Error> {
let mut harness = Harness::new_with_all_analyzers(); let harness = Harness::new_with_config(analyzer_config);
if enable_dummy_analyzer {
harness.add_analyzer(Box::new(TestAnalyzer { count: 0 }));
}
let mut result = Self { let mut result = Self {
writer: BufWriter::new(file), writer: BufWriter::new(file),
bytes_written: 0,
harness, harness,
}; };
let metadata = result.harness.get_metadata(); let metadata = result.harness.get_metadata();
@@ -52,19 +46,25 @@ impl AnalysisWriter {
} }
// Runs the analysis harness on the given container, serializing the results // Runs the analysis harness on the given container, serializing the results
// to the analysis file and returning the file's new length. // to the analysis file, returning the whether any warnings were detected
pub async fn analyze(&mut self, container: MessagesContainer) -> Result<(usize, bool), std::io::Error> { pub async fn analyze(
let row = self.harness.analyze_qmdl_messages(container); &mut self,
if !row.is_empty() { container: MessagesContainer,
self.write(&row).await?; ) -> Result<EventType, std::io::Error> {
let mut max_type = EventType::Informational;
for row in self.harness.analyze_qmdl_messages(container) {
if !row.is_empty() {
self.write(&row).await?;
}
max_type = cmp::max(max_type, row.get_max_event_type());
} }
Ok((self.bytes_written, row.contains_warnings())) Ok(max_type)
} }
async fn write<T: Serialize>(&mut self, value: &T) -> Result<(), std::io::Error> { async fn write<T: Serialize>(&mut self, value: &T) -> Result<(), std::io::Error> {
let mut value_str = serde_json::to_string(value).unwrap(); let mut value_str = serde_json::to_string(value).unwrap();
value_str.push('\n'); value_str.push('\n');
self.bytes_written += value_str.len();
self.writer.write_all(value_str.as_bytes()).await?; self.writer.write_all(value_str.as_bytes()).await?;
self.writer.flush().await?; self.writer.flush().await?;
Ok(()) Ok(())
@@ -77,14 +77,37 @@ impl AnalysisWriter {
} }
} }
#[derive(Debug, Serialize, Clone, Default)] /// The system status relating to QMDL file analysis
#[derive(Debug, Serialize, Clone)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct AnalysisStatus { pub struct AnalysisStatus {
/// The vector array of queued files
queued: Vec<String>, queued: Vec<String>,
/// The file currently being analyzed
running: Option<String>, running: Option<String>,
/// The vector array of finished files
finished: Vec<String>,
}
impl AnalysisStatus {
pub fn new(store: &RecordingStore) -> Self {
let existing_recordings: Vec<String> = store
.manifest
.entries
.iter()
.map(|entry| entry.name.clone())
.collect();
AnalysisStatus {
queued: Vec::new(),
running: None,
finished: existing_recordings,
}
}
} }
pub enum AnalysisCtrlMessage { pub enum AnalysisCtrlMessage {
NewFilesQueued, NewFilesQueued,
RecordingFinished(String),
Exit, Exit,
} }
@@ -100,70 +123,67 @@ async fn dequeue_to_running(analysis_status_lock: Arc<RwLock<AnalysisStatus>>) -
name name
} }
async fn clear_running(analysis_status_lock: Arc<RwLock<AnalysisStatus>>) { async fn finish_running_analysis(analysis_status_lock: Arc<RwLock<AnalysisStatus>>) {
let mut analysis_status = analysis_status_lock.write().await; let mut analysis_status = analysis_status_lock.write().await;
analysis_status.running = None; let finished = analysis_status.running.take().unwrap();
analysis_status.finished.push(finished);
} }
async fn perform_analysis( async fn perform_analysis(
name: &str, name: &str,
qmdl_store_lock: Arc<RwLock<RecordingStore>>, qmdl_store_lock: Arc<RwLock<RecordingStore>>,
enable_dummy_analyzer: bool, analyzer_config: &AnalyzerConfig,
) -> Result<(), String> { ) -> Result<(), String> {
info!("Opening QMDL and analysis file for {}...", name); info!("Opening QMDL and analysis file for {name}...");
let (analysis_file, qmdl_file, entry_index) = { let (analysis_file, qmdl_file) = {
let mut qmdl_store = qmdl_store_lock.write().await; let mut qmdl_store = qmdl_store_lock.write().await;
let (entry_index, _) = qmdl_store let (entry_index, _) = qmdl_store
.entry_for_name(&name) .entry_for_name(name)
.ok_or(format!("failed to find QMDL store entry for {}", name))?; .ok_or(format!("failed to find QMDL store entry for {name}"))?;
let analysis_file = qmdl_store let analysis_file = qmdl_store
.clear_and_open_entry_analysis(entry_index) .clear_and_open_entry_analysis(entry_index)
.await .await
.map_err(|e| format!("{:?}", e))?; .map_err(|e| format!("{e:?}"))?;
let qmdl_file = qmdl_store let qmdl_file = qmdl_store
.open_entry_qmdl(entry_index) .open_entry_qmdl(entry_index)
.await .await
.map_err(|e| format!("{:?}", e))?; .map_err(|e| format!("{e:?}"))?;
(analysis_file, qmdl_file, entry_index) (analysis_file, qmdl_file)
}; };
let mut analysis_writer = AnalysisWriter::new(analysis_file, enable_dummy_analyzer) let mut analysis_writer = AnalysisWriter::new(analysis_file, analyzer_config)
.await .await
.map_err(|e| format!("{:?}", e))?; .map_err(|e| format!("{e:?}"))?;
let file_size = qmdl_file let file_size = qmdl_file
.metadata() .metadata()
.await .await
.expect("failed to get QMDL file metadata") .expect("failed to get QMDL file metadata")
.len(); .len();
let mut qmdl_reader = QmdlReader::new(qmdl_file, Some(file_size as usize)); let mut qmdl_reader = QmdlReader::new(qmdl_file, Some(file_size as usize));
let mut qmdl_stream = pin::pin!(qmdl_reader let mut qmdl_stream = pin::pin!(
.as_stream() qmdl_reader
.try_filter(|container| future::ready(container.data_type == DataType::UserSpace))); .as_stream()
.try_filter(|container| future::ready(container.data_type == DataType::UserSpace))
);
info!("Starting analysis for {}...", name); info!("Starting analysis for {name}...");
while let Some(container) = qmdl_stream while let Some(container) = qmdl_stream
.try_next() .try_next()
.await .await
.expect("failed getting QMDL container") .expect("failed getting QMDL container")
{ {
let (size_bytes, _) = analysis_writer let _ = analysis_writer
.analyze(container) .analyze(container)
.await .await
.map_err(|e| format!("{:?}", e))?; .map_err(|e| format!("{e:?}"))?;
debug!("{} analysis: {} bytes written", name, size_bytes);
let mut qmdl_store = qmdl_store_lock.write().await;
qmdl_store
.update_entry_analysis_size(entry_index, size_bytes)
.await
.map_err(|e| format!("{:?}", e))?;
} }
analysis_writer analysis_writer
.close() .close()
.await .await
.map_err(|e| format!("{:?}", e))?; .map_err(|e| format!("{e:?}"))?;
info!("Analysis for {} complete!", name); info!("Analysis for {name} complete!");
Ok(()) Ok(())
} }
@@ -173,7 +193,7 @@ pub fn run_analysis_thread(
mut analysis_rx: Receiver<AnalysisCtrlMessage>, mut analysis_rx: Receiver<AnalysisCtrlMessage>,
qmdl_store_lock: Arc<RwLock<RecordingStore>>, qmdl_store_lock: Arc<RwLock<RecordingStore>>,
analysis_status_lock: Arc<RwLock<AnalysisStatus>>, analysis_status_lock: Arc<RwLock<AnalysisStatus>>,
enable_dummy_analyzer: bool, analyzer_config: AnalyzerConfig,
) { ) {
task_tracker.spawn(async move { task_tracker.spawn(async move {
loop { loop {
@@ -182,18 +202,34 @@ pub fn run_analysis_thread(
let count = queued_len(analysis_status_lock.clone()).await; let count = queued_len(analysis_status_lock.clone()).await;
for _ in 0..count { for _ in 0..count {
let name = dequeue_to_running(analysis_status_lock.clone()).await; let name = dequeue_to_running(analysis_status_lock.clone()).await;
if let Err(err) = perform_analysis(&name, qmdl_store_lock.clone(), enable_dummy_analyzer).await { if let Err(err) =
error!("failed to analyze {}: {}", name, err); perform_analysis(&name, qmdl_store_lock.clone(), &analyzer_config).await
{
error!("failed to analyze {name}: {err}");
} }
clear_running(analysis_status_lock.clone()).await; finish_running_analysis(analysis_status_lock.clone()).await;
} }
} }
Some(AnalysisCtrlMessage::RecordingFinished(name)) => {
let mut status = analysis_status_lock.write().await;
status.finished.push(name);
}
Some(AnalysisCtrlMessage::Exit) | None => return, Some(AnalysisCtrlMessage::Exit) | None => return,
} }
} }
}); });
} }
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/analysis",
tag = "Recordings",
responses(
(status = StatusCode::OK, description = "Success", body = AnalysisStatus)
),
summary = "Analysis status",
description = "Show analysis status for all QMDL files."
))]
pub async fn get_analysis_status( pub async fn get_analysis_status(
State(state): State<Arc<ServerState>>, State(state): State<Arc<ServerState>>,
) -> Result<Json<AnalysisStatus>, (StatusCode, String)> { ) -> Result<Json<AnalysisStatus>, (StatusCode, String)> {
@@ -210,6 +246,20 @@ fn queue_qmdl(name: &str, analysis_status: &mut RwLockWriteGuard<AnalysisStatus>
true true
} }
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/analysis/{name}",
tag = "Recordings",
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Unable to queue analysis file")
),
params(
("name" = String, Path, description = "QMDL file to analyze")
),
summary = "Start analysis",
description = "Begin analysis of QMDL file {name}."
))]
pub async fn start_analysis( pub async fn start_analysis(
State(state): State<Arc<ServerState>>, State(state): State<Arc<ServerState>>,
Path(qmdl_name): Path<String>, Path(qmdl_name): Path<String>,
@@ -240,7 +290,7 @@ pub async fn start_analysis(
.map_err(|e| { .map_err(|e| {
( (
StatusCode::INTERNAL_SERVER_ERROR, StatusCode::INTERNAL_SERVER_ERROR,
format!("failed to queue new analysis files: {:?}", e), format!("failed to queue new analysis files: {e:?}"),
) )
})?; })?;
} }

121
daemon/src/battery/mod.rs Normal file
View File

@@ -0,0 +1,121 @@
use std::{path::Path, time::Duration};
use log::{info, warn};
use rayhunter::Device;
use serde::Serialize;
use tokio::select;
use tokio_util::{sync::CancellationToken, task::TaskTracker};
use crate::{
error::RayhunterError,
notifications::{Notification, NotificationType},
};
pub mod orbic;
pub mod tmobile;
pub mod tplink;
pub mod wingtech;
const LOW_BATTERY_LEVEL: u8 = 10;
/// Device battery information
#[derive(Clone, Copy, PartialEq, Debug, Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct BatteryState {
/// The current level in percentage of the device battery
level: u8,
/// A boolean indicating whether the battery is currently being charged
is_plugged_in: bool,
}
async fn is_plugged_in_from_file(path: &Path) -> Result<bool, RayhunterError> {
match tokio::fs::read_to_string(path)
.await
.map_err(RayhunterError::TokioError)?
.chars()
.next()
{
Some('0') => Ok(false),
Some('1') => Ok(true),
_ => Err(RayhunterError::BatteryPluggedInStatusParseError),
}
}
async fn get_level_from_percentage_file(path: &Path) -> Result<u8, RayhunterError> {
tokio::fs::read_to_string(path)
.await
.map_err(RayhunterError::TokioError)?
.trim_end()
.parse()
.or(Err(RayhunterError::BatteryLevelParseError))
}
pub async fn get_battery_status(device: &Device) -> Result<BatteryState, RayhunterError> {
Ok(match device {
Device::Orbic => orbic::get_battery_state().await?,
Device::Wingtech => wingtech::get_battery_state().await?,
Device::Tmobile => tmobile::get_battery_state().await?,
Device::Tplink => tplink::get_battery_state().await?,
_ => return Err(RayhunterError::FunctionNotSupportedForDeviceError),
})
}
pub fn run_battery_notification_worker(
task_tracker: &TaskTracker,
device: Device,
notification_channel: tokio::sync::mpsc::Sender<Notification>,
shutdown_token: CancellationToken,
) {
task_tracker.spawn(async move {
// Don't send a notification initially if the device starts at a low battery level.
let mut triggered = match get_battery_status(&device).await {
Err(RayhunterError::FunctionNotSupportedForDeviceError) => {
info!("Battery status not supported for this device, disabling battery notifications");
return;
}
Err(e) => {
warn!("Failed to get battery status: {e}");
true
}
Ok(status) => status.level <= LOW_BATTERY_LEVEL,
};
loop {
select! {
_ = shutdown_token.cancelled() => break,
_ = tokio::time::sleep(Duration::from_secs(15)) => {}
}
let status = match get_battery_status(&device).await {
Err(RayhunterError::FunctionNotSupportedForDeviceError) => {
info!("Battery status not supported for this device, disabling battery notifications");
break;
}
Err(e) => {
warn!("Failed to get battery status: {e}");
continue;
}
Ok(status) => status,
};
// To avoid flapping, if the notification has already been triggered
// wait until the device has been plugged in and the battery level
// is high enough to re-enable notifications.
if triggered && status.is_plugged_in && status.level > LOW_BATTERY_LEVEL {
triggered = false;
continue;
}
if !triggered && !status.is_plugged_in && status.level <= LOW_BATTERY_LEVEL {
notification_channel
.send(Notification::new(
NotificationType::LowBattery,
"Rayhunter's battery is low".to_string(),
None,
))
.await
.expect("Failed to send to notification channel");
triggered = true;
}
}
});
}

View File

@@ -0,0 +1,28 @@
use std::path::Path;
use crate::{
battery::{BatteryState, is_plugged_in_from_file},
error::RayhunterError,
};
const BATTERY_LEVEL_FILE: &str = "/sys/kernel/chg_info/level";
const PLUGGED_IN_STATE_FILE: &str = "/sys/kernel/chg_info/chg_en";
pub async fn get_battery_state() -> Result<BatteryState, RayhunterError> {
Ok(BatteryState {
level: match tokio::fs::read_to_string(&BATTERY_LEVEL_FILE)
.await
.map_err(RayhunterError::TokioError)?
.chars()
.next()
{
Some('1') => Ok(10),
Some('2') => Ok(25),
Some('3') => Ok(50),
Some('4') => Ok(75),
Some('5') => Ok(100),
_ => Err(RayhunterError::BatteryLevelParseError),
}?,
is_plugged_in: is_plugged_in_from_file(Path::new(PLUGGED_IN_STATE_FILE)).await?,
})
}

View File

@@ -0,0 +1,16 @@
use std::path::Path;
use crate::{
battery::{BatteryState, get_level_from_percentage_file, is_plugged_in_from_file},
error::RayhunterError,
};
const BATTERY_LEVEL_FILE: &str = "/sys/class/power_supply/bms/capacity";
const PLUGGED_IN_STATE_FILE: &str = "/sys/devices/78d9000.usb/power_supply/usb/online";
pub async fn get_battery_state() -> Result<BatteryState, RayhunterError> {
Ok(BatteryState {
level: get_level_from_percentage_file(Path::new(BATTERY_LEVEL_FILE)).await?,
is_plugged_in: is_plugged_in_from_file(Path::new(PLUGGED_IN_STATE_FILE)).await?,
})
}

View File

@@ -0,0 +1,39 @@
use crate::{battery::BatteryState, error::RayhunterError};
pub async fn get_battery_state() -> Result<BatteryState, RayhunterError> {
let uci_battery = tokio::process::Command::new("uci")
.arg("get")
.arg("battery.battery_mgr.power_level")
.output()
.await?;
let uci_plugged_in = tokio::process::Command::new("uci")
.arg("get")
.arg("battery.battery_mgr.is_charging")
.output()
.await?;
if !uci_battery.status.success() {
return Err(RayhunterError::BatteryLevelParseError);
}
if !uci_plugged_in.status.success() {
return Err(RayhunterError::BatteryPluggedInStatusParseError);
}
let uci_battery = String::from_utf8_lossy(&uci_battery.stdout)
.trim_end()
.parse()
.map_err(|_| RayhunterError::BatteryLevelParseError)?;
let uci_plugged_in = match String::from_utf8_lossy(&uci_plugged_in.stdout).trim_end() {
"0" => Ok(false),
"1" => Ok(true),
_ => Err(RayhunterError::BatteryPluggedInStatusParseError),
}?;
Ok(BatteryState {
level: uci_battery,
is_plugged_in: uci_plugged_in,
})
}

View File

@@ -0,0 +1,17 @@
use std::path::Path;
use crate::{
battery::{BatteryState, get_level_from_percentage_file, is_plugged_in_from_file},
error::RayhunterError,
};
const BATTERY_LEVEL_FILE: &str =
"/sys/devices/78b7000.i2c/i2c-3/3-0063/power_supply/cw2017-bat/capacity";
const PLUGGED_IN_STATE_FILE: &str = "/sys/devices/8a00000.ssusb/power_supply/usb/online";
pub async fn get_battery_state() -> Result<BatteryState, RayhunterError> {
Ok(BatteryState {
level: get_level_from_percentage_file(Path::new(BATTERY_LEVEL_FILE)).await?,
is_plugged_in: is_plugged_in_from_file(Path::new(PLUGGED_IN_STATE_FILE)).await?,
})
}

12
daemon/src/bin/gen_api.rs Normal file
View File

@@ -0,0 +1,12 @@
use std::{env, fs};
fn main() {
let content = rayhunter_daemon::ApiDocs::generate();
let mut filename = "openapi.json".to_string();
let args: Vec<String> = env::args().collect();
if args.len() > 1 {
filename = args[1].to_string();
}
fs::write(filename, content).unwrap();
}

200
daemon/src/config.rs Normal file
View File

@@ -0,0 +1,200 @@
use log::warn;
use serde::{Deserialize, Serialize};
use rayhunter::Device;
use rayhunter::analysis::analyzer::AnalyzerConfig;
use crate::error::RayhunterError;
use crate::notifications::NotificationType;
/// The structure of a valid rayhunter configuration
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct Config {
/// Path to store QMDL files
pub qmdl_store_path: String,
/// Listening port
pub port: u16,
/// Debug mode
pub debug_mode: bool,
/// Internal device name
pub device: Device,
/// UI level
pub ui_level: u8,
/// Colorblind mode
pub colorblind_mode: bool,
/// Key input mode
pub key_input_mode: u8,
/// ntfy.sh URL
pub ntfy_url: Option<String>,
/// Vector containing the types of enabled notifications
pub enabled_notifications: Vec<NotificationType>,
/// Vector containing the list of enabled analyzers
pub analyzers: AnalyzerConfig,
/// Minimum disk space required to start a recording
pub min_space_to_start_recording_mb: u64,
/// Minimum disk space required to continue a recording
pub min_space_to_continue_recording_mb: u64,
/// Wifi client SSID
pub wifi_ssid: Option<String>,
/// Wifi client password
pub wifi_password: Option<String>,
/// Wifi security type (wpa_psk or sae)
pub wifi_security: Option<wifi_station::SecurityType>,
/// Wifi client mode
pub wifi_enabled: bool,
/// Vector containing wifi client DNS servers
pub dns_servers: Option<Vec<String>>,
/// Wifi client firewall mode
pub firewall_restrict_outbound: bool,
/// Vector containing additional wifi client firewall ports to open
pub firewall_allowed_ports: Option<Vec<u16>>,
/// Optional WebDAV upload configuration. When unset, no upload worker runs.
pub webdav: Option<WebdavConfig>,
}
/// Configuration for uploading finished QMDL recordings to a WebDAV server.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct WebdavConfig {
/// WebDAV server base URL, e.g. "https://example.com/remote.php/files/untitaker/my-subfolder/"
pub url: String,
/// Optional username for HTTP Basic auth
pub username: Option<String>,
/// Optional password for HTTP Basic auth
pub password: Option<String>,
/// Timeout (in seconds) for each upload request
pub upload_timeout_secs: u64,
/// How often (in seconds) the worker scans for entries to upload
pub poll_interval_secs: u64,
/// Minimum age (in seconds) an entry must have before it becomes eligible for upload
pub min_age_secs: i64,
/// Delete the file locally after a successful upload
pub delete_on_upload: bool,
}
impl Default for WebdavConfig {
fn default() -> Self {
WebdavConfig {
url: String::new(),
username: None,
password: None,
upload_timeout_secs: 300,
poll_interval_secs: 3600,
min_age_secs: 86400,
delete_on_upload: false,
}
}
}
impl Default for Config {
fn default() -> Self {
Config {
qmdl_store_path: "/data/rayhunter/qmdl".to_string(),
port: 8080,
debug_mode: false,
device: Device::Orbic,
ui_level: 1,
colorblind_mode: false,
key_input_mode: 0,
analyzers: AnalyzerConfig::default(),
ntfy_url: None,
enabled_notifications: vec![NotificationType::Warning, NotificationType::LowBattery],
min_space_to_start_recording_mb: 1,
min_space_to_continue_recording_mb: 1,
wifi_ssid: None,
wifi_password: None,
wifi_security: None,
wifi_enabled: false,
dns_servers: None,
firewall_restrict_outbound: true,
firewall_allowed_ports: None,
webdav: None,
}
}
}
impl Config {
pub fn wifi_config(&self) -> wifi_station::WifiConfig {
let (wpa_bin, hostapd_conf, ctrl_interface) = match self.device {
Device::Tmobile | Device::Wingtech => (
Some("/usr/sbin/wpa_supplicant".into()),
Some("/data/configs/hostapd.conf".into()),
None,
),
Device::Uz801 => (
Some("/system/bin/wpa_supplicant".into()),
Some("/data/misc/wifi/hostapd.conf".into()),
Some("/data/misc/wifi/sockets".into()),
),
_ => (None, None, None),
};
wifi_station::WifiConfig {
wifi_enabled: self.wifi_enabled,
dns_servers: self.dns_servers.clone(),
wifi_ssid: self.wifi_ssid.clone(),
wifi_password: self.wifi_password.clone(),
security_type: self.wifi_security,
wpa_supplicant_bin: wpa_bin.or_else(|| resolve_bin("wpa_supplicant")),
hostapd_conf,
ctrl_interface,
udhcpc_hook_path: Some("/data/rayhunter/udhcpc-hook.sh".into()),
dhcp_lease_path: Some("/data/rayhunter/dhcp_lease".into()),
wpa_conf_path: Some("/data/rayhunter/wpa_sta.conf".into()),
iw_bin: resolve_bin("iw"),
udhcpc_bin: resolve_bin("udhcpc"),
crash_log_dir: Some("/data/rayhunter/crash-logs".into()),
wakelock_name: Some("rayhunter".into()),
}
}
}
fn resolve_bin(name: &str) -> Option<String> {
let local = format!("/data/rayhunter/bin/{name}");
if std::path::Path::new(&local).exists() {
return Some(local);
}
None
}
pub async fn parse_config<P>(path: P) -> Result<Config, RayhunterError>
where
P: AsRef<std::path::Path>,
{
let mut config = if let Ok(config_file) = tokio::fs::read_to_string(&path).await {
toml::from_str(&config_file).map_err(RayhunterError::ConfigFileParsingError)?
} else {
warn!("unable to read config file, using default config");
Config::default()
};
if let Some((ssid, security)) =
wifi_station::read_network_from_wpa_conf("/data/rayhunter/wpa_sta.conf")
{
config.wifi_ssid = Some(ssid);
config.wifi_security = Some(security);
} else {
config.wifi_ssid = None;
config.wifi_security = None;
}
config.wifi_password = None;
Ok(config)
}
pub struct Args {
pub config_path: String,
}
pub fn parse_args() -> Args {
let args: Vec<String> = std::env::args().collect();
if args.len() != 2 {
println!("Usage: {} /path/to/config/file", args[0]);
std::process::exit(1);
}
Args {
config_path: args[1].clone(),
}
}

View File

@@ -0,0 +1,23 @@
use std::sync::Once;
static INSTALL: Once = Once::new();
/// Install the default rustls `CryptoProvider` for the current process.
///
/// This is idempotent so that it's easier to use in tests, but also panics loudly if the
/// initialization fails.
pub fn install_default() {
// Crypto providers fail if they get initialized multiple times, but we don't want to just
// ignore all errors, hence the use of once.
INSTALL.call_once(|| {
#[cfg(feature = "rustcrypto-tls")]
rustls_rustcrypto::provider()
.install_default()
.expect("failed to install rustcrypto crypto provider");
#[cfg(feature = "pq-tls")]
rustls_post_quantum::provider()
.install_default()
.expect("failed to install aws-lc-rs post-quantum crypto provider");
});
}

682
daemon/src/diag.rs Normal file
View File

@@ -0,0 +1,682 @@
use std::ops::DerefMut;
use std::pin::pin;
use std::sync::Arc;
use std::time::Duration;
use axum::body::Body;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::http::header::CONTENT_TYPE;
use axum::response::{IntoResponse, Response};
use futures::{StreamExt, TryStreamExt, future};
use log::{debug, error, info, warn};
use rayhunter::Device;
use tokio::fs::File;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::sync::{RwLock, oneshot};
use tokio_stream::wrappers::LinesStream;
use tokio_util::task::TaskTracker;
#[cfg(feature = "apidocs")]
use rayhunter::analysis::analyzer::ReportMetadata;
use rayhunter::analysis::analyzer::{AnalysisLineNormalizer, AnalyzerConfig, EventType};
use rayhunter::diag::{DataType, MessagesContainer};
use rayhunter::diag_device::DiagDevice;
use rayhunter::qmdl::QmdlWriter;
use crate::analysis::{AnalysisCtrlMessage, AnalysisWriter};
use crate::display;
use crate::notifications::{Notification, NotificationType};
use crate::qmdl_store::{RecordingStore, RecordingStoreError};
use crate::server::ServerState;
use crate::stats::DiskStats;
const DISK_CHECK_BYTES_INTERVAL: usize = 256 * 1024;
pub enum DiagDeviceCtrlMessage {
StopRecording,
StartRecording {
response_tx: Option<oneshot::Sender<Result<(), String>>>,
},
DeleteEntry {
name: String,
response_tx: oneshot::Sender<Result<(), RecordingStoreError>>,
},
DeleteAllEntries {
response_tx: oneshot::Sender<Result<(), RecordingStoreError>>,
},
Exit,
}
pub struct DiagTask {
ui_update_sender: Sender<display::DisplayState>,
analysis_sender: Sender<AnalysisCtrlMessage>,
analyzer_config: AnalyzerConfig,
notification_channel: tokio::sync::mpsc::Sender<Notification>,
min_space_to_start_mb: u64,
min_space_to_continue_mb: u64,
state: DiagState,
max_type_seen: EventType,
bytes_since_space_check: usize,
low_space_warned: bool,
}
enum DiagState {
Recording {
qmdl_writer: QmdlWriter<File>,
analysis_writer: Box<AnalysisWriter>,
},
Stopped,
}
enum DiskSpaceCheck {
Ok(u64),
Warning(u64),
Critical(u64),
Failed,
}
fn check_disk_space(path: &std::path::Path, warning_mb: u64, critical_mb: u64) -> DiskSpaceCheck {
match DiskStats::new(path.to_str().unwrap()) {
Ok(stats) => {
let available_mb = stats.available_bytes.unwrap_or(0) / 1024 / 1024;
if available_mb < critical_mb {
DiskSpaceCheck::Critical(available_mb)
} else if available_mb < warning_mb {
DiskSpaceCheck::Warning(available_mb)
} else {
DiskSpaceCheck::Ok(available_mb)
}
}
Err(e) => {
warn!("Failed to check disk space: {e}");
DiskSpaceCheck::Failed
}
}
}
impl DiagTask {
fn new(
ui_update_sender: Sender<display::DisplayState>,
analysis_sender: Sender<AnalysisCtrlMessage>,
analyzer_config: AnalyzerConfig,
notification_channel: tokio::sync::mpsc::Sender<Notification>,
min_space_to_start_mb: u64,
min_space_to_continue_mb: u64,
) -> Self {
Self {
ui_update_sender,
analysis_sender,
analyzer_config,
notification_channel,
min_space_to_start_mb,
min_space_to_continue_mb,
state: DiagState::Stopped,
max_type_seen: EventType::Informational,
bytes_since_space_check: 0,
low_space_warned: false,
}
}
/// Start recording, returning an error if disk space is too low.
async fn start(&mut self, qmdl_store: &mut RecordingStore) -> Result<(), String> {
self.max_type_seen = EventType::Informational;
self.bytes_since_space_check = 0;
self.low_space_warned = false;
match check_disk_space(
&qmdl_store.path,
self.min_space_to_start_mb,
self.min_space_to_continue_mb,
) {
DiskSpaceCheck::Critical(mb) | DiskSpaceCheck::Warning(mb) => {
let msg = format!(
"Insufficient disk space: {}MB available, {}MB required",
mb, self.min_space_to_start_mb
);
error!("{msg}");
return Err(msg);
}
DiskSpaceCheck::Ok(mb) => {
info!("Starting recording with {}MB disk space available", mb);
}
DiskSpaceCheck::Failed => {}
}
let (qmdl_file, analysis_file) = match qmdl_store.new_entry().await {
Ok(files) => files,
Err(e) => {
let msg = format!("failed creating QMDL file entry: {e}");
error!("{msg}");
return Err(msg);
}
};
self.stop_current_recording().await;
let qmdl_writer = QmdlWriter::new(qmdl_file);
let analysis_writer = match AnalysisWriter::new(analysis_file, &self.analyzer_config).await
{
Ok(writer) => Box::new(writer),
Err(e) => {
let msg = format!("failed to create analysis writer: {e}");
error!("{msg}");
return Err(msg);
}
};
self.state = DiagState::Recording {
qmdl_writer,
analysis_writer,
};
if let Err(e) = self
.ui_update_sender
.send(display::DisplayState::Recording)
.await
{
warn!("couldn't send ui update message: {e}");
}
Ok(())
}
/// Stop recording, optionally annotating the entry with a reason.
async fn stop(&mut self, qmdl_store: &mut RecordingStore, reason: Option<String>) {
self.stop_current_recording().await;
if let Some(reason) = reason
&& let Err(e) = qmdl_store.set_current_stop_reason(reason).await
{
warn!("couldn't set stop reason: {e}");
}
if let Some((_, entry)) = qmdl_store.get_current_entry()
&& let Err(e) = self
.analysis_sender
.send(AnalysisCtrlMessage::RecordingFinished(
entry.name.to_string(),
))
.await
{
warn!("couldn't send analysis message: {e}");
}
if let Err(e) = qmdl_store.close_current_entry().await {
error!("couldn't close current entry: {e}");
}
if let Err(e) = self
.ui_update_sender
.send(display::DisplayState::Paused)
.await
{
warn!("couldn't send ui update message: {e}");
}
}
async fn delete_entry(
&mut self,
qmdl_store: &mut RecordingStore,
name: &str,
) -> Result<(), RecordingStoreError> {
if qmdl_store.is_current_entry(name) {
self.stop(qmdl_store, None).await;
}
let res = qmdl_store.delete_entry(name).await;
if let Err(e) = res.as_ref() {
error!("Error deleting QMDL entry {e}");
}
res
}
async fn delete_all_entries(
&mut self,
qmdl_store: &mut RecordingStore,
) -> Result<(), RecordingStoreError> {
self.stop(qmdl_store, None).await;
let res = qmdl_store.delete_all_entries().await;
if let Err(e) = res.as_ref() {
error!("Error deleting QMDL entries {e}");
}
res
}
async fn stop_current_recording(&mut self) {
let mut state = DiagState::Stopped;
std::mem::swap(&mut self.state, &mut state);
if let DiagState::Recording {
analysis_writer, ..
} = state
{
analysis_writer
.close()
.await
.expect("failed to close analysis writer");
}
}
async fn process_container(
&mut self,
qmdl_store: &mut RecordingStore,
container: MessagesContainer,
) {
if container.data_type != DataType::UserSpace {
debug!("skipping non-userspace diag messages...");
return;
}
// keep track of how many bytes were written to the QMDL file so we can read
// a valid block of data from it in the HTTP server
if let DiagState::Recording {
qmdl_writer,
analysis_writer,
} = &mut self.state
{
if self.bytes_since_space_check >= DISK_CHECK_BYTES_INTERVAL {
self.bytes_since_space_check = 0;
match check_disk_space(
&qmdl_store.path,
self.min_space_to_start_mb,
self.min_space_to_continue_mb,
) {
DiskSpaceCheck::Critical(mb) => {
let reason = format!(
"Disk space critically low ({}MB free), recording stopped automatically",
mb
);
error!("{reason}");
self.notification_channel
.send(Notification::new(
NotificationType::Warning,
reason.clone(),
None,
))
.await
.ok();
self.stop(qmdl_store, Some(reason)).await;
return;
}
DiskSpaceCheck::Warning(mb) if !self.low_space_warned => {
self.low_space_warned = true;
warn!("Disk space low: {}MB remaining", mb);
self.notification_channel
.send(Notification::new(
NotificationType::Warning,
format!("Disk space low: {}MB free", mb),
Some(Duration::from_secs(30)),
))
.await
.ok();
}
_ => {}
}
}
if let Err(e) = qmdl_writer.write_container(&container).await {
let reason = format!("failed to write to QMDL (disk full?): {e}");
error!("{reason}");
self.stop(qmdl_store, Some(reason)).await;
return;
}
debug!(
"total QMDL bytes written: {}, updating manifest...",
qmdl_writer.total_written
);
let index = qmdl_store
.current_entry
.expect("DiagDevice had qmdl_writer, but QmdlStore didn't have current entry???");
if let Err(e) = qmdl_store
.update_entry_qmdl_size(index, qmdl_writer.total_written)
.await
{
let reason = format!("failed to update manifest (disk full?): {e}");
error!("{reason}");
self.stop(qmdl_store, Some(reason)).await;
return;
}
debug!("done!");
let container_bytes: usize = container.messages.iter().map(|m| m.data.len()).sum();
self.bytes_since_space_check += container_bytes;
let max_type = match analysis_writer.analyze(container).await {
Ok(t) => t,
Err(e) => {
warn!("failed to analyze container: {e}");
EventType::Informational
}
};
if max_type > EventType::Informational {
info!("a heuristic triggered on this run!");
self.notification_channel
.send(Notification::new(
NotificationType::Warning,
format!("Rayhunter has detected a {:?} severity event", max_type),
Some(Duration::from_secs(60 * 5)),
))
.await
.expect("Failed to send to notification channel");
}
if max_type > self.max_type_seen {
self.max_type_seen = max_type;
if self.max_type_seen > EventType::Informational {
self.ui_update_sender
.send(display::DisplayState::WarningDetected {
event_type: self.max_type_seen,
})
.await
.expect("couldn't send ui update message: {}");
}
}
} else {
debug!("no qmdl_writer set, continuing...");
}
}
}
#[allow(clippy::too_many_arguments)]
pub fn run_diag_read_thread(
task_tracker: &TaskTracker,
device: Device,
mut qmdl_file_rx: Receiver<DiagDeviceCtrlMessage>,
qmdl_file_tx: Sender<DiagDeviceCtrlMessage>,
ui_update_sender: Sender<display::DisplayState>,
qmdl_store_lock: Arc<RwLock<RecordingStore>>,
analysis_sender: Sender<AnalysisCtrlMessage>,
analyzer_config: AnalyzerConfig,
notification_channel: tokio::sync::mpsc::Sender<Notification>,
min_space_to_start_mb: u64,
min_space_to_continue_mb: u64,
) {
task_tracker.spawn(async move {
info!("Using configuration for device: {0:?}", device);
let mut dev = DiagDevice::new(&device)
.await?;
dev.config_logs()
.await?;
let mut diag_stream = pin!(dev.as_stream().into_stream());
let mut diag_task = DiagTask::new(
ui_update_sender,
analysis_sender,
analyzer_config,
notification_channel,
min_space_to_start_mb,
min_space_to_continue_mb
);
qmdl_file_tx
.send(DiagDeviceCtrlMessage::StartRecording { response_tx: None })
.await
.unwrap();
loop {
tokio::select! {
msg = qmdl_file_rx.recv() => {
match msg {
Some(DiagDeviceCtrlMessage::StartRecording { response_tx }) => {
let mut qmdl_store = qmdl_store_lock.write().await;
let result = diag_task.start(qmdl_store.deref_mut()).await;
if let Some(tx) = response_tx {
tx.send(result).ok();
}
},
Some(DiagDeviceCtrlMessage::StopRecording) => {
let mut qmdl_store = qmdl_store_lock.write().await;
diag_task.stop(qmdl_store.deref_mut(), None).await;
},
// None means all the Senders have been dropped, so it's
// time to go
Some(DiagDeviceCtrlMessage::Exit) | None => {
info!("Diag reader thread exiting...");
diag_task.stop_current_recording().await;
return Ok(())
},
Some(DiagDeviceCtrlMessage::DeleteEntry { name, response_tx }) => {
let mut qmdl_store = qmdl_store_lock.write().await;
let resp = diag_task.delete_entry(qmdl_store.deref_mut(), name.as_str()).await;
if response_tx.send(resp).is_err() {
error!("Failed to send delete entry respons, receiver dropped");
}
},
Some(DiagDeviceCtrlMessage::DeleteAllEntries { response_tx }) => {
let mut qmdl_store = qmdl_store_lock.write().await;
let resp = diag_task.delete_all_entries(qmdl_store.deref_mut()).await;
if response_tx.send(resp).is_err() {
error!("Failed to send delete all entries respons, receiver dropped");
}
},
}
}
maybe_container = diag_stream.next() => {
match maybe_container.unwrap() {
Ok(container) => {
let mut qmdl_store = qmdl_store_lock.write().await;
diag_task.process_container(qmdl_store.deref_mut(), container).await
},
Err(err) => {
error!("error reading diag device: {err}");
return Err(err);
}
}
}
}
}
});
}
/// Start recording API for web thread
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/start-recording",
tag = "Recordings",
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::FORBIDDEN, description = "System is in debug mode"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Recording action unsuccessful")
),
summary = "Start recording",
description = "Begin a new data capture."
))]
pub async fn start_recording(
State(state): State<Arc<ServerState>>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
if state.config.debug_mode {
return Err((StatusCode::FORBIDDEN, "server is in debug mode".to_string()));
}
let (response_tx, response_rx) = oneshot::channel();
state
.diag_device_ctrl_sender
.send(DiagDeviceCtrlMessage::StartRecording {
response_tx: Some(response_tx),
})
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't send start recording message: {e}"),
)
})?;
match response_rx.await {
Ok(Ok(())) => Ok((StatusCode::ACCEPTED, "ok".to_string())),
Ok(Err(reason)) => Err((StatusCode::INSUFFICIENT_STORAGE, reason)),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("failed to receive start recording response: {e}"),
)),
}
}
/// Stop recording API for web thread
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/stop-recording",
tag = "Recordings",
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::FORBIDDEN, description = "System is in debug mode"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Recording action unsuccessful")
),
summary = "Stop recording",
description = "Stop current data capture."
))]
pub async fn stop_recording(
State(state): State<Arc<ServerState>>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
if state.config.debug_mode {
return Err((StatusCode::FORBIDDEN, "server is in debug mode".to_string()));
}
state
.diag_device_ctrl_sender
.send(DiagDeviceCtrlMessage::StopRecording)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't send stop recording message: {e}"),
)
})?;
Ok((StatusCode::ACCEPTED, "ok".to_string()))
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/delete-recording/{name}",
tag = "Recordings",
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::FORBIDDEN, description = "System is in debug mode"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Delete action unsuccessful"),
(status = StatusCode::BAD_REQUEST, description = "Bad recording name or no such recording")
),
params(
("name" = String, Path, description = "QMDL file to delete")
),
summary = "Delete recording",
description = "Remove data capture file named {name}."
))]
pub async fn delete_recording(
State(state): State<Arc<ServerState>>,
Path(qmdl_name): Path<String>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
if state.config.debug_mode {
return Err((StatusCode::FORBIDDEN, "server is in debug mode".to_string()));
}
let (response_tx, response_rx) = oneshot::channel();
state
.diag_device_ctrl_sender
.send(DiagDeviceCtrlMessage::DeleteEntry {
name: qmdl_name.clone(),
response_tx,
})
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't send delete entry message: {e}"),
)
})?;
match response_rx.await.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("failed to receive delete response: {e}"),
)
})? {
Ok(_) => Ok((StatusCode::ACCEPTED, "ok".to_string())),
Err(RecordingStoreError::NoSuchEntryError) => Err((
StatusCode::BAD_REQUEST,
format!("no recording with name {qmdl_name}"),
)),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't delete recording: {e}"),
)),
}
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/delete-all-recordings",
tag = "Recordings",
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::FORBIDDEN, description = "System is in debug mode"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Delete action unsuccessful")
),
summary = "Delete all recordings",
description = "Remove all saved data capture files."
))]
pub async fn delete_all_recordings(
State(state): State<Arc<ServerState>>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
if state.config.debug_mode {
return Err((StatusCode::FORBIDDEN, "server is in debug mode".to_string()));
}
let (response_tx, response_rx) = oneshot::channel();
state
.diag_device_ctrl_sender
.send(DiagDeviceCtrlMessage::DeleteAllEntries { response_tx })
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't send delete all entries message: {e}"),
)
})?;
match response_rx.await.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("failed to receive delete all response: {e}"),
)
})? {
Ok(_) => Ok((StatusCode::ACCEPTED, "ok".to_string())),
Err(e) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("couldn't delete recordings: {e}"),
)),
}
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/analysis-report/{name}",
tag = "Recordings",
responses(
(status = StatusCode::OK, description = "Success", body = ReportMetadata, content_type = "application/x-ndjson"),
(status = StatusCode::SERVICE_UNAVAILABLE, description = "No QMDL files available; start a new recording."),
(status = StatusCode::NOT_FOUND, description = "File {name} not found")
),
params(
("name" = String, Path, description = "QMDL file to analyze")
),
summary = "Analysis report",
description = "Download processed analysis report for QMDL file {name}, as well as the types (and versions) of analyzers used."
))]
pub async fn get_analysis_report(
State(state): State<Arc<ServerState>>,
Path(qmdl_name): Path<String>,
) -> Result<Response, (StatusCode, String)> {
let qmdl_store = state.qmdl_store_lock.read().await;
let (entry_index, _) = if qmdl_name == "live" {
qmdl_store.get_current_entry().ok_or((
StatusCode::SERVICE_UNAVAILABLE,
"No QMDL data's being recorded to analyze, try starting a new recording!".to_string(),
))?
} else {
qmdl_store.entry_for_name(&qmdl_name).ok_or((
StatusCode::NOT_FOUND,
format!("Couldn't find QMDL entry with name \"{qmdl_name}\""),
))?
};
let analysis_file = qmdl_store
.open_entry_analysis(entry_index)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")))?;
// Read and normalize the NDJSON file
let reader = BufReader::new(analysis_file);
let lines_stream = LinesStream::new(reader.lines());
let mut normalizer = AnalysisLineNormalizer::new();
let normalized_stream = lines_stream
.try_filter(|line| future::ready(!line.is_empty()))
.map_ok(move |line| normalizer.normalize_line(line));
let headers = [(CONTENT_TYPE, "application/x-ndjson")];
let body = Body::from_stream(normalized_stream);
Ok((headers, body).into_response())
}

View File

@@ -0,0 +1,242 @@
use async_trait::async_trait;
use image::{AnimationDecoder, DynamicImage, codecs::gif::GifDecoder, imageops::FilterType};
use std::io::Cursor;
use std::time::Duration;
use crate::config;
use crate::display::DisplayState;
use rayhunter::analysis::analyzer::EventType;
use log::{error, info};
use tokio::sync::mpsc::Receiver;
use tokio_util::{sync::CancellationToken, task::TaskTracker};
use include_dir::{Dir, include_dir};
const REFRESH_RATE: u64 = 1000; //how often in milliseconds to refresh the display
#[derive(Copy, Clone)]
pub struct Dimensions {
pub height: u32,
pub width: u32,
}
#[derive(Copy, Clone)]
pub enum LinePattern {
Solid,
Dashed, // _ _ _ _
Dotted, // . . . .
}
#[allow(dead_code)]
#[derive(Copy, Clone)]
pub enum Color {
Red,
Green,
Blue,
White,
Black,
Cyan,
Yellow,
Pink,
Orange,
}
impl Color {
fn rgb(self) -> (u8, u8, u8) {
match self {
Color::Red => (0xff, 0, 0),
Color::Green => (0, 0xff, 0),
Color::Blue => (0, 0, 0xff),
Color::White => (0xff, 0xff, 0xff),
Color::Black => (0, 0, 0),
Color::Cyan => (0, 0xff, 0xff),
Color::Yellow => (0xff, 0xff, 0),
Color::Pink => (0xfe, 0x24, 0xff),
Color::Orange => (0xff, 0xa5, 0),
}
}
}
fn display_style_from_state(state: DisplayState, colorblind_mode: bool) -> (Color, LinePattern) {
match state {
DisplayState::Paused => (Color::White, LinePattern::Solid),
DisplayState::Recording => {
if colorblind_mode {
(Color::Blue, LinePattern::Solid)
} else {
(Color::Green, LinePattern::Solid)
}
}
DisplayState::WarningDetected { event_type } => match event_type {
EventType::Informational => {
if colorblind_mode {
(Color::Blue, LinePattern::Solid)
} else {
(Color::Green, LinePattern::Solid)
}
}
EventType::Low => (Color::Yellow, LinePattern::Dotted),
EventType::Medium => (Color::Orange, LinePattern::Dashed),
EventType::High => (Color::Red, LinePattern::Solid),
},
}
}
#[async_trait]
pub trait GenericFramebuffer: Send + 'static {
fn dimensions(&self) -> Dimensions;
async fn write_buffer(&mut self, buffer: Vec<(u8, u8, u8)>); // rgb, row-wise, left-to-right, top-to-bottom
async fn write_dynamic_image(&mut self, img: DynamicImage) {
let dimensions = self.dimensions();
let mut width = img.width();
let mut height = img.height();
let resized_img: DynamicImage;
if height > dimensions.height || width > dimensions.width {
resized_img = img.resize(dimensions.width, dimensions.height, FilterType::CatmullRom);
width = dimensions.width.min(resized_img.width());
height = dimensions.height.min(resized_img.height());
} else {
resized_img = img;
}
let img_rgba8 = resized_img.as_rgba8().unwrap();
let mut buf = Vec::with_capacity((height * width).try_into().unwrap());
for y in 0..height {
for x in 0..width {
let px = img_rgba8.get_pixel(x, y);
buf.push((px[0], px[1], px[2]));
}
}
self.write_buffer(buf).await
}
async fn draw_gif(&mut self, img_buffer: &[u8]) {
let cursor = Cursor::new(img_buffer);
if let Ok(decoder) = GifDecoder::new(cursor) {
let frames: Vec<_> = decoder
.into_frames()
.filter_map(|f| f.ok())
.map(|frame| {
let (numerator, _) = frame.delay().numer_denom_ms();
let img = DynamicImage::from(frame.into_buffer());
(img, numerator as u64)
})
.collect();
for (img, delay_ms) in frames {
self.write_dynamic_image(img).await;
tokio::time::sleep(Duration::from_millis(delay_ms)).await;
}
}
}
async fn draw_img(&mut self, img_buffer: &[u8]) {
let img = image::load_from_memory(img_buffer).unwrap();
self.write_dynamic_image(img).await
}
async fn draw_line(&mut self, color: Color, height: u32) {
self.draw_patterned_line(color, height, LinePattern::Solid)
.await
}
async fn draw_patterned_line(&mut self, color: Color, height: u32, pattern: LinePattern) {
let width = self.dimensions().width;
let mut buffer = Vec::with_capacity((height * width).try_into().unwrap());
for _row in 0..height {
for col in 0..width {
let should_draw = match pattern {
LinePattern::Solid => true,
LinePattern::Dashed => (col / 4) % 2 == 0, // 4 pixels on, 4 pixels off
LinePattern::Dotted => col % 4 == 0, // 1 pixel on, 3 pixels off
};
if should_draw {
buffer.push(color.rgb());
} else {
buffer.push((0, 0, 0)); // Black background
}
}
}
self.write_buffer(buffer).await
}
}
pub fn update_ui(
task_tracker: &TaskTracker,
config: &config::Config,
mut fb: impl GenericFramebuffer,
shutdown_token: CancellationToken,
mut ui_update_rx: Receiver<DisplayState>,
) {
static IMAGE_DIR: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/images/");
let display_level = config.ui_level;
if display_level == 0 {
info!("Invisible mode, not spawning UI.");
return;
}
let colorblind_mode = config.colorblind_mode;
let mut display_style = display_style_from_state(DisplayState::Recording, colorblind_mode);
task_tracker.spawn(async move {
// this feels wrong, is there a more rusty way to do this?
let mut img: Option<&[u8]> = None;
if display_level == 2 {
img = Some(
IMAGE_DIR
.get_file("orca.gif")
.expect("failed to read orca.gif")
.contents(),
);
} else if display_level == 3 {
img = Some(
IMAGE_DIR
.get_file("eff.png")
.expect("failed to read eff.png")
.contents(),
);
}
loop {
if shutdown_token.is_cancelled() {
info!("received UI shutdown");
break;
}
match ui_update_rx.try_recv() {
Ok(state) => {
display_style = display_style_from_state(state, colorblind_mode);
}
Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {}
Err(e) => error!("error receiving framebuffer update message: {e}"),
}
let mut status_bar_height = 2;
match display_level {
2 => fb.draw_gif(img.unwrap()).await,
3 => fb.draw_img(img.unwrap()).await,
4 => {
status_bar_height = fb.dimensions().height;
}
128 => {
fb.draw_line(Color::Cyan, 128).await;
fb.draw_line(Color::Pink, 102).await;
fb.draw_line(Color::White, 76).await;
fb.draw_line(Color::Pink, 50).await;
fb.draw_line(Color::Cyan, 25).await;
}
// this branch is for ui_level 1, which is also the default if an
// unknown value is used
_ => {}
};
let (color, pattern) = display_style;
fb.draw_patterned_line(color, status_bar_height, pattern)
.await;
tokio::time::sleep(Duration::from_millis(REFRESH_RATE)).await;
}
});
}

View File

@@ -0,0 +1,16 @@
use log::info;
use tokio::sync::mpsc::Receiver;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use crate::config;
use crate::display::DisplayState;
pub fn update_ui(
_task_tracker: &TaskTracker,
_config: &config::Config,
_shutdown_token: CancellationToken,
_ui_update_rx: Receiver<DisplayState>,
) {
info!("Headless mode, not spawning UI.");
}

28
daemon/src/display/mod.rs Normal file
View File

@@ -0,0 +1,28 @@
use rayhunter::analysis::analyzer::EventType;
use serde::{Deserialize, Serialize};
mod generic_framebuffer;
pub mod headless;
pub mod orbic;
pub mod tmobile;
pub mod tplink;
pub mod tplink_framebuffer;
pub mod tplink_onebit;
pub mod uz801;
pub mod wingtech;
/// A list of available display states
#[derive(Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub enum DisplayState {
/// We're recording but no warning has been found yet.
Recording,
/// We're not recording.
Paused,
/// A non-informational event has been detected.
///
/// Note that EventType::Informational is never sent through this. If it is, it's the same as
/// Recording
WarningDetected { event_type: EventType },
}

View File

@@ -0,0 +1,51 @@
use crate::config;
use crate::display::DisplayState;
use crate::display::generic_framebuffer::{self, Dimensions, GenericFramebuffer};
use async_trait::async_trait;
use tokio::sync::mpsc::Receiver;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
const FB_PATH: &str = "/dev/fb0";
#[derive(Copy, Clone, Default)]
struct Framebuffer;
#[async_trait]
impl GenericFramebuffer for Framebuffer {
fn dimensions(&self) -> Dimensions {
// TODO actually poll for this, maybe w/ fbset?
Dimensions {
height: 128,
width: 128,
}
}
async fn write_buffer(&mut self, buffer: Vec<(u8, u8, u8)>) {
let mut raw_buffer = Vec::with_capacity(buffer.len() * 2);
for (r, g, b) in buffer {
let mut rgb565: u16 = (r as u16 & 0b11111000) << 8;
rgb565 |= (g as u16 & 0b11111100) << 3;
rgb565 |= (b as u16) >> 3;
raw_buffer.extend(rgb565.to_le_bytes());
}
tokio::fs::write(FB_PATH, &raw_buffer).await.unwrap();
}
}
pub fn update_ui(
task_tracker: &TaskTracker,
config: &config::Config,
shutdown_token: CancellationToken,
ui_update_rx: Receiver<DisplayState>,
) {
generic_framebuffer::update_ui(
task_tracker,
config,
Framebuffer,
shutdown_token,
ui_update_rx,
)
}

View File

@@ -0,0 +1,77 @@
/// Display module for Tmobile TMOHS1, blink LEDs on the front of the device.
/// DisplayState::Recording => Signal LED slowly blinks blue.
/// DisplayState::Paused => WiFi LED blinks white.
/// DisplayState::WarningDetected { .. } => Signal LED slowly blinks red.
use log::{error, info};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use std::time::Duration;
use crate::config;
use crate::display::DisplayState;
macro_rules! led {
($l:expr) => {{ format!("/sys/class/leds/led:{}/blink", $l) }};
}
async fn start_blinking(path: String) {
tokio::fs::write(&path, "1").await.ok();
}
async fn stop_blinking(path: String) {
tokio::fs::write(&path, "0").await.ok();
}
pub fn update_ui(
task_tracker: &TaskTracker,
config: &config::Config,
shutdown_token: CancellationToken,
mut ui_update_rx: mpsc::Receiver<DisplayState>,
) {
let mut invisible: bool = false;
if config.ui_level == 0 {
info!("Invisible mode, not spawning UI.");
invisible = true;
}
task_tracker.spawn(async move {
let mut state = DisplayState::Recording;
let mut last_state = DisplayState::Paused;
loop {
if shutdown_token.is_cancelled() {
info!("received UI shutdown");
break;
}
match ui_update_rx.try_recv() {
Ok(new_state) => state = new_state,
Err(mpsc::error::TryRecvError::Empty) => {}
Err(e) => error!("error receiving ui update message: {e}"),
};
if invisible || state == last_state {
tokio::time::sleep(Duration::from_secs(1)).await;
continue;
}
match state {
DisplayState::Paused => {
stop_blinking(led!("signal_blue")).await;
stop_blinking(led!("signal_red")).await;
start_blinking(led!("wlan_white")).await;
}
DisplayState::Recording => {
stop_blinking(led!("wlan_white")).await;
stop_blinking(led!("signal_red")).await;
start_blinking(led!("signal_blue")).await;
}
DisplayState::WarningDetected { .. } => {
stop_blinking(led!("wlan_white")).await;
stop_blinking(led!("signal_blue")).await;
start_blinking(led!("signal_red")).await;
}
}
last_state = state;
tokio::time::sleep(Duration::from_secs(1)).await;
}
});
}

View File

@@ -0,0 +1,31 @@
use log::info;
use tokio::sync::mpsc::Receiver;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use crate::config;
use crate::display::{DisplayState, tplink_framebuffer, tplink_onebit};
use std::fs;
pub fn update_ui(
task_tracker: &TaskTracker,
config: &config::Config,
shutdown_token: CancellationToken,
ui_update_rx: Receiver<DisplayState>,
) {
let display_level = config.ui_level;
if display_level == 0 {
info!("Invisible mode, not spawning UI.");
}
// Since this is a one-time check at startup, using sync is acceptable
// The alternative would be to make the entire initialization async
if fs::exists(tplink_onebit::OLED_PATH).unwrap_or_default() {
info!("detected one-bit display");
tplink_onebit::update_ui(task_tracker, config, shutdown_token, ui_update_rx)
} else {
info!("fallback to framebuffer");
tplink_framebuffer::update_ui(task_tracker, config, shutdown_token, ui_update_rx)
}
}

View File

@@ -0,0 +1,93 @@
use async_trait::async_trait;
use std::os::fd::AsRawFd;
use tokio::fs::OpenOptions;
use tokio::io::AsyncWriteExt;
use tokio_util::sync::CancellationToken;
use crate::config;
use crate::display::DisplayState;
use crate::display::generic_framebuffer::{self, Dimensions, GenericFramebuffer};
use tokio::sync::mpsc::Receiver;
use tokio_util::task::TaskTracker;
const FB_PATH: &str = "/dev/fb0";
struct Framebuffer;
#[repr(C)]
struct fb_fillrect {
dx: u32,
dy: u32,
width: u32,
height: u32,
color: u32,
rop: u32,
}
#[async_trait]
impl GenericFramebuffer for Framebuffer {
fn dimensions(&self) -> Dimensions {
// TODO actually poll for this, maybe w/ fbset?
Dimensions {
height: 128,
width: 128,
}
}
async fn write_buffer(&mut self, buffer: Vec<(u8, u8, u8)>) {
// for how to write to the buffer, consult M7350v5_en_gpl/bootable/recovery/recovery_color_oled.c
let dimensions = self.dimensions();
let width = dimensions.width;
let height = buffer.len() as u32 / width;
let mut f = OpenOptions::new().write(true).open(FB_PATH).await.unwrap();
let mut arg = fb_fillrect {
dx: 0,
dy: 0,
width,
height,
color: 0xffff, // not sure what this is
rop: 0,
};
let mut raw_buffer = Vec::with_capacity(buffer.len() * 2);
for (r, g, b) in buffer {
let mut rgb565: u16 = (r as u16 & 0b11111000) << 8;
rgb565 |= (g as u16 & 0b11111100) << 3;
rgb565 |= (b as u16) >> 3;
// note: big-endian!
raw_buffer.extend(rgb565.to_be_bytes());
}
f.write_all(&raw_buffer).await.unwrap();
// ioctl is a synchronous operation, but it's fast enough that it shouldn't block
unsafe {
let res = libc::ioctl(
f.as_raw_fd(),
0x4619, // FBIORECT_DISPLAY
&mut arg as *mut _,
std::mem::size_of::<fb_fillrect>(),
);
if res < 0 {
panic!("failed to send FBIORECT_DISPLAY ioctl, {res}");
}
}
}
}
pub fn update_ui(
task_tracker: &TaskTracker,
config: &config::Config,
shutdown_token: CancellationToken,
ui_update_rx: Receiver<DisplayState>,
) {
generic_framebuffer::update_ui(
task_tracker,
config,
Framebuffer,
shutdown_token,
ui_update_rx,
)
}

View File

@@ -0,0 +1,163 @@
/// Display module for the TP-Link M7350 oled one-bit display.
///
/// https://github.com/m0veax/tplink_m7350/tree/main/oled
use crate::config;
use crate::display::DisplayState;
use log::{error, info};
use tokio::sync::mpsc::Receiver;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use std::time::Duration;
pub const OLED_PATH: &str = "/sys/class/display/oled/oled_buffer";
// those coordinates were mainly chosen for a spot that doesn't get regularly updated by the main
// oledd service. otherwise we'd have to write to the display more than once per second to prevent
// the icon from flickering.
const STATUS_X: u8 = 104;
const STATUS_Y: u8 = 40;
const STATUS_W: u8 = 16;
const STATUS_H: u8 = 16;
macro_rules! pixel {
(x) => {
0
};
(_) => {
1
};
}
macro_rules! pixelart {
(x=$x:expr, y=$y:expr, width=$width:expr, height=$height:expr; $($a:tt $b:tt $c:tt $d:tt $e:tt $f:tt $g:tt $h:tt)*) => {{
// one bit per pixel + 4 bytes for header
const BUF_SIZE: usize = ($width as usize * $height as usize) / 8 + 4;
const BUF_BYTES: [u8; BUF_SIZE] = [
$x,
$y,
$width,
$height,
$(
(pixel!($a) << 7 | pixel!($b) << 6 | pixel!($c) << 5 | pixel!($d) << 4 | pixel!($e) << 3 | pixel!($f) << 2 | pixel!($g) << 1 | pixel!($h)),
)*
];
&BUF_BYTES
}}
}
const STATUS_PAUSED: &[u8] = pixelart! {
x=STATUS_X, y=STATUS_Y, width=STATUS_W, height=STATUS_H;
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ x x x x x x x x x x _ _ _
_ x x _ _ _ _ _ _ _ _ _ _ x x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ x _ _ _ _ x _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x x _ _ _ _ _ _ _ _ _ _ x x _
_ _ _ x x x x x x x x x x _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
};
const STATUS_SMILING: &[u8] = pixelart! {
x=STATUS_X, y=STATUS_Y, width=STATUS_W, height=STATUS_H;
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ x x x x x x x x x x _ _ _
_ x x _ _ _ _ _ _ _ _ _ _ x x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ x _ _ _ _ x _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ x _ _ _ _ x _ _ _ x _
_ x _ _ _ x _ _ _ _ x _ _ _ x _
_ x _ _ _ x x x x x x _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x x _ _ _ _ _ _ _ _ _ _ x x _
_ _ _ x x x x x x x x x x _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
};
const STATUS_WARNING: &[u8] = pixelart! {
x=STATUS_X, y=STATUS_Y, width=STATUS_W, height=STATUS_H;
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_ _ _ x x x x x x x x x x _ _ _
_ x x _ _ _ _ _ _ _ _ _ _ x x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ x x _ _ _ _ _ x _
_ x _ _ _ _ _ x x _ _ _ _ _ x _
_ x _ _ _ _ _ x x _ _ _ _ _ x _
_ x _ _ _ _ _ x x _ _ _ _ _ x _
_ x _ _ _ _ _ x x _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x _ _ _ _ _ x x _ _ _ _ _ x _
_ x _ _ _ _ _ x x _ _ _ _ _ x _
_ x _ _ _ _ _ _ _ _ _ _ _ _ x _
_ x x _ _ _ _ _ _ _ _ _ _ x x _
_ _ _ x x x x x x x x x x _ _ _
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
};
pub fn update_ui(
task_tracker: &TaskTracker,
config: &config::Config,
shutdown_token: CancellationToken,
mut ui_update_rx: Receiver<DisplayState>,
) {
let display_level = config.ui_level;
if display_level == 0 {
info!("Invisible mode, not spawning UI.");
}
task_tracker.spawn(async move {
let mut pixels = STATUS_SMILING;
loop {
if shutdown_token.is_cancelled() {
info!("received UI shutdown");
break;
}
match ui_update_rx.try_recv() {
Ok(DisplayState::Paused) => pixels = STATUS_PAUSED,
Ok(DisplayState::Recording) => pixels = STATUS_SMILING,
Ok(DisplayState::WarningDetected { .. }) => pixels = STATUS_WARNING,
Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {}
Err(e) => {
error!("error receiving framebuffer update message: {e}");
}
};
// we write the status every second because it may have been overwritten through menu
// navigation.
if display_level != 0
&& let Err(e) = tokio::fs::write(OLED_PATH, pixels).await
{
error!("failed to write to display: {e}");
}
tokio::time::sleep(Duration::from_millis(1000)).await;
}
});
}
#[test]
fn test_pixelart_macro() {
assert_eq!(
STATUS_WARNING,
[
104, 40, 16, 16, 255, 255, 224, 7, 159, 249, 191, 253, 190, 125, 190, 125, 190, 125,
190, 125, 190, 125, 191, 253, 190, 125, 190, 125, 191, 253, 159, 249, 224, 7, 255, 255
]
);
}

View File

@@ -0,0 +1,85 @@
/// Display module for Uz801, light LEDs on the front of the device.
/// DisplayState::Recording => Green LED is solid.
/// DisplayState::Paused => Signal LED is solid blue (wifi LED).
/// DisplayState::WarningDetected => Signal LED is solid red.
use log::{error, info};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use std::time::Duration;
use crate::config;
use crate::display::DisplayState;
macro_rules! led {
($l:expr) => {{ format!("/sys/class/leds/{}/brightness", $l) }};
}
async fn led_on(path: String) {
tokio::fs::write(&path, "1").await.ok();
}
async fn led_off(path: String) {
tokio::fs::write(&path, "0").await.ok();
}
pub fn update_ui(
task_tracker: &TaskTracker,
config: &config::Config,
shutdown_token: CancellationToken,
mut ui_update_rx: mpsc::Receiver<DisplayState>,
) {
let mut invisible: bool = false;
if config.ui_level == 0 {
info!("Invisible mode, not spawning UI.");
invisible = true;
}
task_tracker.spawn(async move {
let mut state = DisplayState::Recording;
let mut last_state = DisplayState::Paused;
let mut last_update = std::time::Instant::now();
loop {
if shutdown_token.is_cancelled() {
info!("received UI shutdown");
break;
}
match ui_update_rx.try_recv() {
Ok(new_state) => state = new_state,
Err(mpsc::error::TryRecvError::Empty) => {}
Err(e) => error!("error receiving ui update message: {e}"),
};
// Update LEDs if state changed or if 5 seconds have passed since last update
let now = std::time::Instant::now();
let should_update = !invisible
&& (state != last_state
|| now.duration_since(last_update) >= Duration::from_secs(5));
if should_update {
match state {
DisplayState::Paused => {
led_off(led!("red")).await;
led_off(led!("green")).await;
led_on(led!("wifi")).await;
}
DisplayState::Recording => {
led_off(led!("red")).await;
led_off(led!("wifi")).await;
led_on(led!("green")).await;
}
DisplayState::WarningDetected { .. } => {
led_off(led!("green")).await;
led_off(led!("wifi")).await;
led_on(led!("red")).await;
}
}
last_state = state;
last_update = now;
}
tokio::time::sleep(Duration::from_secs(1)).await;
}
});
}

View File

@@ -0,0 +1,56 @@
use crate::config;
use crate::display::DisplayState;
use crate::display::generic_framebuffer::{self, Dimensions, GenericFramebuffer};
/// Display support for the Wingtech CT2MHS01 hotspot.
///
/// Tested on (from `/etc/wt_version`):
/// WT_INNER_VERSION=SW_Q89323AA1_V057_M10_CRICKET_USR_MP
/// WT_PRODUCTION_VERSION=CT2MHS01_0.04.55
/// WT_HARDWARE_VERSION=89323_1_20
use async_trait::async_trait;
use tokio::sync::mpsc::Receiver;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
const FB_PATH: &str = "/dev/fb0";
#[derive(Copy, Clone, Default)]
struct Framebuffer;
#[async_trait]
impl GenericFramebuffer for Framebuffer {
fn dimensions(&self) -> Dimensions {
Dimensions {
height: 128,
width: 160,
}
}
async fn write_buffer(&mut self, buffer: Vec<(u8, u8, u8)>) {
let mut raw_buffer = Vec::with_capacity(buffer.len() * 2);
for (r, g, b) in buffer {
let mut rgb565: u16 = (r as u16 & 0b11111000) << 8;
rgb565 |= (g as u16 & 0b11111100) << 3;
rgb565 |= (b as u16) >> 3;
raw_buffer.extend(rgb565.to_le_bytes());
}
tokio::fs::write(FB_PATH, &raw_buffer).await.unwrap();
}
}
pub fn update_ui(
task_tracker: &TaskTracker,
config: &config::Config,
shutdown_token: CancellationToken,
ui_update_rx: Receiver<DisplayState>,
) {
generic_framebuffer::update_ui(
task_tracker,
config,
Framebuffer,
shutdown_token,
ui_update_rx,
)
}

View File

@@ -1,18 +1,21 @@
use thiserror::Error; use thiserror::Error;
use rayhunter::diag_device::DiagDeviceError;
use crate::qmdl_store::RecordingStoreError; use crate::qmdl_store::RecordingStoreError;
#[derive(Error, Debug)] #[derive(Error, Debug)]
pub enum RayhunterError{ pub enum RayhunterError {
#[error("Config file parsing error: {0}")] #[error("Config file parsing error: {0}")]
ConfigFileParsingError(#[from] toml::de::Error), ConfigFileParsingError(#[from] toml::de::Error),
#[error("Diag intialization error: {0}")]
DiagInitError(DiagDeviceError),
#[error("Tokio error: {0}")] #[error("Tokio error: {0}")]
TokioError(#[from] tokio::io::Error), TokioError(#[from] tokio::io::Error),
#[error("QmdlStore error: {0}")] #[error("QmdlStore error: {0}")]
QmdlStoreError(#[from] RecordingStoreError), QmdlStoreError(#[from] RecordingStoreError),
#[error("No QMDL store found at path {0}, but can't create a new one due to debug mode")] #[error("No QMDL store found at path {0}, but can't create a new one due to debug mode")]
NoStoreDebugMode(String), NoStoreDebugMode(String),
#[error("Error parsing file to determine battery level")]
BatteryLevelParseError,
#[error("Error parsing file to determine whether device is plugged in")]
BatteryPluggedInStatusParseError,
#[error("The requested functionality is not supported for this device")]
FunctionNotSupportedForDeviceError,
} }

92
daemon/src/firewall.rs Normal file
View File

@@ -0,0 +1,92 @@
use anyhow::{Result, bail};
use log::{info, warn};
use tokio::process::Command;
use wifi_station::detect_bridge_iface;
use crate::config::Config;
async fn run_iptables(args: &[&str]) -> Result<()> {
let out = Command::new("iptables").args(args).output().await?;
if !out.status.success() {
bail!(
"iptables {} failed: {}",
args.join(" "),
String::from_utf8_lossy(&out.stderr)
);
}
Ok(())
}
pub async fn apply(config: &Config) {
let _ = Command::new("iptables")
.args(["-F", "OUTPUT"])
.output()
.await;
if config.firewall_restrict_outbound {
// Fail open on partial setup error: reachability beats restriction when recovery means physical access.
match setup_outbound_whitelist(&config.firewall_allowed_ports, &config.ntfy_url).await {
Ok(()) => info!("outbound firewall active: allowing DHCP, DNS, HTTPS only"),
Err(e) => warn!("firewall setup failed: {e} (fail-open, outbound unrestricted)"),
}
}
}
async fn setup_outbound_whitelist(
extra_ports: &Option<Vec<u16>>,
ntfy_url: &Option<String>,
) -> Result<()> {
run_iptables(&["-A", "OUTPUT", "-o", "lo", "-j", "ACCEPT"]).await?;
run_iptables(&["-A", "OUTPUT", "-o", detect_bridge_iface(), "-j", "ACCEPT"]).await?;
run_iptables(&[
"-A",
"OUTPUT",
"-m",
"state",
"--state",
"ESTABLISHED,RELATED",
"-j",
"ACCEPT",
])
.await?;
run_iptables(&[
"-A", "OUTPUT", "-p", "udp", "--dport", "67:68", "-j", "ACCEPT",
])
.await?;
run_iptables(&["-A", "OUTPUT", "-p", "udp", "--dport", "53", "-j", "ACCEPT"]).await?;
run_iptables(&["-A", "OUTPUT", "-p", "tcp", "--dport", "53", "-j", "ACCEPT"]).await?;
run_iptables(&[
"-A", "OUTPUT", "-p", "tcp", "--dport", "443", "-j", "ACCEPT",
])
.await?;
if let Some(url) = ntfy_url
&& let Ok(parsed) = url::Url::parse(url)
&& let Some(port) = parsed.port_or_known_default()
&& port != 443
{
let port_str = port.to_string();
run_iptables(&[
"-A", "OUTPUT", "-p", "tcp", "--dport", &port_str, "-j", "ACCEPT",
])
.await?;
info!("firewall: auto-allowed port {port} for ntfy");
}
if let Some(ports) = extra_ports {
for port in ports {
let port_str = port.to_string();
run_iptables(&[
"-A", "OUTPUT", "-p", "tcp", "--dport", &port_str, "-j", "ACCEPT",
])
.await?;
}
}
run_iptables(&["-A", "OUTPUT", "-j", "DROP"]).await?;
let _ = tokio::fs::write("/proc/sys/net/bridge/bridge-nf-call-iptables", "0").await;
Ok(())
}

132
daemon/src/key_input.rs Normal file
View File

@@ -0,0 +1,132 @@
use log::{error, info};
use std::time::{Duration, Instant};
use tokio::fs::File;
use tokio::io::AsyncReadExt;
use tokio::sync::mpsc::Sender;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
use crate::config;
use crate::diag::DiagDeviceCtrlMessage;
#[derive(Debug)]
enum Event {
KeyDown,
KeyUp,
}
const INPUT_EVENT_SIZE: usize = 32;
pub fn run_key_input_thread(
task_tracker: &TaskTracker,
config: &config::Config,
diag_tx: Sender<DiagDeviceCtrlMessage>,
cancellation_token: CancellationToken,
) {
if config.key_input_mode == 0 {
return;
}
task_tracker.spawn(async move {
// Open the input device
let mut file = match File::open("/dev/input/event0").await {
Ok(file) => file,
Err(e) => {
error!("Failed to open /dev/input/event0: {e}");
return;
}
};
let mut buffer = [0u8; INPUT_EVENT_SIZE];
let mut last_keyup: Option<Instant> = None;
let mut last_event_time: Option<Instant> = None;
loop {
tokio::select! {
_ = cancellation_token.cancelled() => {
info!("received key input shutdown");
return;
}
result = file.read_exact(&mut buffer) => {
if let Err(e) = result {
error!("failed to read key input: {e}");
return;
}
}
}
let event = parse_event(buffer);
let now = Instant::now();
// On orbic it was observed that pressing the power button can trigger many successive
// events. Drop events that are too close together.
if let Some(last_time) = last_event_time
&& now.duration_since(last_time) < Duration::from_millis(50)
{
last_event_time = Some(now);
continue;
}
last_event_time = Some(now);
match event {
Event::KeyUp => {
if let Some(last_keyup_instant) = last_keyup {
let elapsed = now.duration_since(last_keyup_instant);
if elapsed >= Duration::from_millis(100)
&& elapsed <= Duration::from_millis(800)
{
if let Err(e) = diag_tx.send(DiagDeviceCtrlMessage::StopRecording).await
{
error!("Failed to send StopRecording: {e}");
}
if let Err(e) = diag_tx
.send(DiagDeviceCtrlMessage::StartRecording { response_tx: None })
.await
{
error!("Failed to send StartRecording: {e}");
}
last_keyup = None;
continue;
}
}
last_keyup = Some(now);
}
Event::KeyDown => {}
}
}
});
}
fn parse_event(input: [u8; INPUT_EVENT_SIZE]) -> Event {
if input[12] == 0 {
Event::KeyUp
} else {
Event::KeyDown
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_event_keydown_m7350_v5() {
let input = [
0x57, 0x6c, 0x09, 0x00, 0x7c, 0xfb, 0x03, 0x00, 0x01, 0x00, 0x74, 0x00, 0x01, 0x00,
0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
assert!(matches!(parse_event(input), Event::KeyDown));
}
#[test]
fn test_parse_event_keyup_m7350_v5() {
let input = [
0x57, 0x6c, 0x09, 0x00, 0x1b, 0x15, 0x05, 0x00, 0x01, 0x00, 0x74, 0x00, 0x00, 0x00,
0x00, 0x00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
assert!(matches!(parse_event(input), Event::KeyUp));
}
}

74
daemon/src/lib.rs Normal file
View File

@@ -0,0 +1,74 @@
pub mod analysis;
pub mod battery;
pub mod config;
pub mod crypto_provider;
pub mod diag;
pub mod display;
pub mod error;
pub mod firewall;
pub mod key_input;
pub mod notifications;
pub mod pcap;
pub mod qmdl_store;
pub mod server;
pub mod stats;
pub mod webdav;
#[cfg(feature = "apidocs")]
use utoipa::OpenApi;
// Add anotated paths to api docs
#[cfg(feature = "apidocs")]
#[derive(OpenApi)]
#[openapi(
info(
description = "OpenAPI documentation for Rayhunter daemon\n\n**Note:** API endpoints are subject to change as needs arise, though we will try to keep them as stable as possible and notify about breaking changes in the changelogs for new versions.\n\nNo endpoints require any authentication. To use the in-browser execution on this page, you may need to disable CORS temporarily for your browser.",
license(
name = "GNU General Public License v3.0",
url = "https://github.com/EFForg/rayhunter/blob/main/LICENSE"
)
),
paths(
pcap::get_pcap,
server::get_qmdl,
server::get_zip,
stats::get_system_stats,
stats::get_qmdl_manifest,
stats::get_log,
diag::start_recording,
diag::stop_recording,
diag::delete_recording,
diag::delete_all_recordings,
diag::get_analysis_report,
analysis::get_analysis_status,
analysis::start_analysis,
server::get_config,
server::set_config,
server::test_notification,
server::get_time,
server::set_time_offset,
server::debug_set_display_state
),
servers(
(
url = "http://localhost:8080",
description = "ADB port bridge"
),
(
url = "http://192.168.1.1:8080",
description = "Orbic WiFi GUI"
),
(
url = "http://192.168.0.1:8080",
description = "TPLink WiFi GUI"
),
)
)]
pub struct ApiDocs;
#[cfg(feature = "apidocs")]
impl ApiDocs {
pub fn generate() -> String {
ApiDocs::openapi().to_pretty_json().unwrap()
}
}

332
daemon/src/main.rs Normal file
View File

@@ -0,0 +1,332 @@
mod analysis;
mod battery;
mod config;
mod crypto_provider;
mod diag;
mod display;
mod error;
mod firewall;
mod key_input;
mod notifications;
mod pcap;
mod qmdl_store;
mod server;
mod stats;
mod webdav;
use std::net::SocketAddr;
use std::sync::Arc;
use crate::battery::run_battery_notification_worker;
use crate::config::{parse_args, parse_config};
use crate::diag::run_diag_read_thread;
use crate::error::RayhunterError;
use crate::notifications::{NotificationService, run_notification_worker};
use crate::pcap::get_pcap;
use crate::qmdl_store::RecordingStore;
use crate::server::{
ServerState, debug_set_display_state, get_config, get_qmdl, get_time, get_wifi_status, get_zip,
scan_wifi, serve_static, set_config, set_time_offset, test_notification,
};
use crate::stats::{get_qmdl_manifest, get_system_stats};
use crate::webdav::run_webdav_upload_worker;
use wifi_station::WifiStatus;
use analysis::{
AnalysisCtrlMessage, AnalysisStatus, get_analysis_status, run_analysis_thread, start_analysis,
};
use axum::Router;
use axum::response::Redirect;
use axum::routing::{get, post};
use diag::{
DiagDeviceCtrlMessage, delete_all_recordings, delete_recording, get_analysis_report,
start_recording, stop_recording,
};
use log::{error, info};
use qmdl_store::RecordingStoreError;
use rayhunter::Device;
use stats::get_log;
use tokio::net::TcpListener;
use tokio::select;
use tokio::sync::RwLock;
use tokio::sync::mpsc::{self, Sender};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tokio_util::task::TaskTracker;
type AppRouter = Router<Arc<ServerState>>;
fn get_router() -> AppRouter {
Router::new()
.route("/api/pcap/{name}", get(get_pcap))
.route("/api/qmdl/{name}", get(get_qmdl))
.route("/api/zip/{name}", get(get_zip))
.route("/api/system-stats", get(get_system_stats))
.route("/api/qmdl-manifest", get(get_qmdl_manifest))
.route("/api/log", get(get_log))
.route("/api/start-recording", post(start_recording))
.route("/api/stop-recording", post(stop_recording))
.route("/api/delete-recording/{name}", post(delete_recording))
.route("/api/delete-all-recordings", post(delete_all_recordings))
.route("/api/analysis-report/{name}", get(get_analysis_report))
.route("/api/analysis", get(get_analysis_status))
.route("/api/analysis/{name}", post(start_analysis))
.route("/api/config", get(get_config))
.route("/api/config", post(set_config))
.route("/api/test-notification", post(test_notification))
.route("/api/wifi-status", get(get_wifi_status))
.route("/api/wifi-scan", post(scan_wifi))
.route("/api/time", get(get_time))
.route("/api/time-offset", post(set_time_offset))
.route("/api/debug/display-state", post(debug_set_display_state))
.route("/", get(|| async { Redirect::permanent("/index.html") }))
.route("/{*path}", get(serve_static))
}
// Runs the axum server, taking all the elements needed to build up our
// ServerState and a oneshot Receiver that'll fire when it's time to shutdown
// (i.e. user hit ctrl+c)
async fn run_server(
task_tracker: &TaskTracker,
state: Arc<ServerState>,
shutdown_token: CancellationToken,
) -> JoinHandle<()> {
info!("spinning up server");
let addr = SocketAddr::from(([0, 0, 0, 0], state.config.port));
let listener = TcpListener::bind(&addr).await.unwrap();
let app = get_router().with_state(state);
task_tracker.spawn(async move {
info!("The orca is hunting for stingrays...");
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_token.cancelled_owned())
.await
.unwrap();
})
}
// Loads a RecordingStore if one exists, and if not, only create one if we're
// not in debug mode. If we fail to parse the manifest AND we're not in debug
// mode, try to recover the manifest from the existing QMDL files
async fn init_qmdl_store(config: &config::Config) -> Result<RecordingStore, RayhunterError> {
let store_exists = RecordingStore::exists(&config.qmdl_store_path).await?;
if config.debug_mode {
if store_exists {
Ok(RecordingStore::load(&config.qmdl_store_path).await?)
} else {
Err(RayhunterError::NoStoreDebugMode(
config.qmdl_store_path.clone(),
))
}
} else if store_exists {
match RecordingStore::load(&config.qmdl_store_path).await {
Ok(store) => Ok(store),
Err(RecordingStoreError::ParseManifestError(err)) => {
error!("failed to parse QMDL manifest: {err}");
info!("recovering manifest from existing QMDL files...");
Ok(RecordingStore::recover(&config.qmdl_store_path).await?)
}
Err(err) => Err(err.into()),
}
} else {
Ok(RecordingStore::create(&config.qmdl_store_path).await?)
}
}
// Start a thread that'll track when user hits ctrl+c. When that happens,
// trigger various cleanup tasks, including sending signals to other threads to
// shutdown
fn run_shutdown_thread(
task_tracker: &TaskTracker,
diag_device_sender: Sender<DiagDeviceCtrlMessage>,
shutdown_token: CancellationToken,
qmdl_store_lock: Arc<RwLock<RecordingStore>>,
analysis_tx: Sender<AnalysisCtrlMessage>,
) -> JoinHandle<Result<(), RayhunterError>> {
info!("create shutdown thread");
task_tracker.spawn(async move {
select! {
res = tokio::signal::ctrl_c() => {
if let Err(err) = res {
error!("Unable to listen for shutdown signal: {err}");
}
}
_ = shutdown_token.cancelled() => {}
}
let mut qmdl_store = qmdl_store_lock.write().await;
if qmdl_store.current_entry.is_some() {
info!("Closing current QMDL entry...");
qmdl_store.close_current_entry().await?;
info!("Done!");
}
shutdown_token.cancel();
diag_device_sender
.send(DiagDeviceCtrlMessage::Exit)
.await
.expect("couldn't send Exit message to diag thread");
analysis_tx
.send(AnalysisCtrlMessage::Exit)
.await
.expect("couldn't send Exit message to analysis thread");
Ok(())
})
}
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), RayhunterError> {
rayhunter::init_logging(log::LevelFilter::Info);
crate::crypto_provider::install_default();
let args = parse_args();
loop {
let config = parse_config(&args.config_path).await?;
if !run_with_config(&args, config).await? {
return Ok(());
}
}
}
async fn run_with_config(
args: &config::Args,
config: config::Config,
) -> Result<bool, RayhunterError> {
// TaskTrackers give us an interface to spawn tokio threads, and then
// eventually await all of them ending
let task_tracker = TaskTracker::new();
println!("R A Y H U N T E R 🐳");
let store = init_qmdl_store(&config).await?;
let analysis_status = AnalysisStatus::new(&store);
let qmdl_store_lock = Arc::new(RwLock::new(store));
let (diag_tx, diag_rx) = mpsc::channel::<DiagDeviceCtrlMessage>(1);
let (ui_update_tx, ui_update_rx) = mpsc::channel::<display::DisplayState>(1);
let (analysis_tx, analysis_rx) = mpsc::channel::<AnalysisCtrlMessage>(5);
let restart_token = CancellationToken::new();
let shutdown_token = restart_token.child_token();
// Ensure shutdown_token is cancelled when this function exits for any
// reason (e.g. diag device init failure), so all spawned tasks get
// signaled to stop.
let _shutdown_guard = shutdown_token.clone().drop_guard();
let notification_service = NotificationService::new(config.ntfy_url.clone());
if !config.debug_mode {
info!("Starting Diag Thread");
run_diag_read_thread(
&task_tracker,
config.device.clone(),
diag_rx,
diag_tx.clone(),
ui_update_tx.clone(),
qmdl_store_lock.clone(),
analysis_tx.clone(),
config.analyzers.clone(),
notification_service.new_handler(),
config.min_space_to_start_recording_mb,
config.min_space_to_continue_recording_mb,
);
info!("Starting UI");
let update_ui = match &config.device {
Device::Orbic | Device::Moxee => display::orbic::update_ui,
Device::Tplink => display::tplink::update_ui,
Device::Tmobile => display::tmobile::update_ui,
Device::Wingtech => display::wingtech::update_ui,
Device::Pinephone => display::headless::update_ui,
Device::Uz801 => display::uz801::update_ui,
};
update_ui(&task_tracker, &config, shutdown_token.clone(), ui_update_rx);
info!("Starting Key Input service");
key_input::run_key_input_thread(
&task_tracker,
&config,
diag_tx.clone(),
shutdown_token.clone(),
);
}
let analysis_status_lock = Arc::new(RwLock::new(analysis_status));
run_analysis_thread(
&task_tracker,
analysis_rx,
qmdl_store_lock.clone(),
analysis_status_lock.clone(),
config.analyzers.clone(),
);
run_shutdown_thread(
&task_tracker,
diag_tx.clone(),
shutdown_token.clone(),
qmdl_store_lock.clone(),
analysis_tx.clone(),
);
run_battery_notification_worker(
&task_tracker,
config.device.clone(),
notification_service.new_handler(),
shutdown_token.clone(),
);
run_notification_worker(
&task_tracker,
notification_service,
config.enabled_notifications.clone(),
);
let wifi_status = Arc::new(RwLock::new(WifiStatus::default()));
wifi_station::run_wifi_client(
&task_tracker,
&config.wifi_config(),
shutdown_token.clone(),
wifi_status.clone(),
);
firewall::apply(&config).await;
if let Some(webdav_config) = config.webdav.clone() {
run_webdav_upload_worker(
&task_tracker,
shutdown_token.clone(),
qmdl_store_lock.clone(),
webdav_config.into(),
);
}
let state = Arc::new(ServerState {
config_path: args.config_path.clone(),
config,
qmdl_store_lock: qmdl_store_lock.clone(),
diag_device_ctrl_sender: diag_tx,
analysis_status_lock,
analysis_sender: analysis_tx,
daemon_restart_token: restart_token.clone(),
ui_update_sender: Some(ui_update_tx),
wifi_status,
wifi_scan_lock: tokio::sync::Mutex::new(()),
});
run_server(&task_tracker, state, shutdown_token.clone()).await;
task_tracker.close();
task_tracker.wait().await;
info!("see you space cowboy...");
Ok(restart_token.is_cancelled())
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_get_router() {
// assert that creating the router does not panic from invalid route patterns.
let _ = get_router();
}
}

441
daemon/src/notifications.rs Normal file
View File

@@ -0,0 +1,441 @@
use std::{
cmp::min,
collections::HashMap,
time::{Duration, Instant},
};
use log::error;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::sync::mpsc::{self, error::TryRecvError};
use tokio_util::task::TaskTracker;
pub const DEFAULT_NOTIFICATION_TIMEOUT: u64 = 10; //seconds
#[derive(Error, Debug)]
pub enum NotificationError {
#[error("HTTP request failed: {0}")]
RequestFailed(#[from] reqwest::Error),
#[error("Server returned error status: {0}")]
HttpError(reqwest::StatusCode),
}
/// Enum of valid notification types
#[derive(Hash, Eq, PartialEq, Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub enum NotificationType {
Warning,
LowBattery,
}
pub struct Notification {
notification_type: NotificationType,
message: String,
debounce: Option<Duration>,
}
impl Notification {
pub fn new(
notification_type: NotificationType,
message: String,
debounce: Option<Duration>,
) -> Self {
Notification {
notification_type,
message,
debounce,
}
}
}
struct NotificationStatus {
message: String,
needs_sending: bool,
last_sent: Option<Instant>,
last_attempt: Option<Instant>,
failed_since_last_success: u32,
}
pub struct NotificationService {
url: Option<String>,
timeout: u64,
tx: mpsc::Sender<Notification>,
rx: mpsc::Receiver<Notification>,
}
impl NotificationService {
pub fn new(url: Option<String>) -> Self {
let (tx, rx) = mpsc::channel(10);
Self {
url,
timeout: DEFAULT_NOTIFICATION_TIMEOUT,
tx,
rx,
}
}
pub fn new_handler(&self) -> mpsc::Sender<Notification> {
self.tx.clone()
}
}
/// Sends a notification message to the specified URL.
pub async fn send_notification(
http_client: &reqwest::Client,
url: &str,
message: String,
timeout: u64,
) -> Result<(), NotificationError> {
let response = http_client
.post(url)
.body(message)
.timeout(Duration::from_secs(timeout))
.send()
.await?;
if response.status().is_success() {
Ok(())
} else {
Err(NotificationError::HttpError(response.status()))
}
}
pub fn run_notification_worker(
task_tracker: &TaskTracker,
mut notification_service: NotificationService,
enabled_notifications: Vec<NotificationType>,
) {
task_tracker.spawn(async move {
if let Some(url) = notification_service.url
&& !url.is_empty()
{
let mut notification_statuses = HashMap::new();
let http_client = reqwest::Client::new();
loop {
// Get any notifications since the last time we checked
loop {
match notification_service.rx.try_recv() {
Ok(notification) => {
if !enabled_notifications.contains(&notification.notification_type) {
continue;
}
let status = notification_statuses
.entry(notification.notification_type)
.or_insert_with(|| NotificationStatus {
message: "".to_string(),
needs_sending: true,
last_sent: None,
last_attempt: None,
failed_since_last_success: 0,
});
// Ignore if we're in the debounce period
if let Some(debounce) = notification.debounce
&& let Some(last_sent) = status.last_sent
&& last_sent.elapsed() < debounce
{
continue;
}
status.message = notification.message;
status.needs_sending = true;
}
Err(TryRecvError::Empty) => {
break;
}
Err(TryRecvError::Disconnected) => {
return;
}
}
}
// Attempt to send pending notifications
for notification in notification_statuses.values_mut() {
if !notification.needs_sending {
continue;
}
// Backoff retries, up to a maximum of 256 seconds.
if let Some(last_attempt) = notification.last_attempt {
let min_wait_time = Duration::from_secs(
2u64.pow(min(notification.failed_since_last_success, 8)),
);
if last_attempt.elapsed() < min_wait_time {
continue;
}
}
match send_notification(
&http_client,
&url,
notification.message.clone(),
notification_service.timeout,
)
.await
{
Ok(()) => {
notification.last_sent = Some(Instant::now());
notification.failed_since_last_success = 0;
notification.needs_sending = false;
}
Err(e) => {
error!("Failed to send notification: {e}");
notification.failed_since_last_success += 1;
notification.last_attempt = Some(Instant::now());
}
}
}
tokio::time::sleep(Duration::from_secs(2)).await;
}
}
// If there's no url to send to we'll just discard the notifications
else {
loop {
if notification_service.rx.recv().await.is_none() {
break;
}
}
}
});
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{Router, body::Bytes, extract::State, routing::post};
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::sync::Mutex;
#[derive(Clone)]
struct TestServerState {
received_messages: Arc<Mutex<Vec<String>>>,
}
async fn capture_notification(
State(state): State<TestServerState>,
body: Bytes,
) -> &'static str {
let message = String::from_utf8_lossy(&body).to_string();
state.received_messages.lock().await.push(message);
"OK"
}
async fn setup_test_server() -> (Arc<Mutex<Vec<String>>>, String) {
crate::crypto_provider::install_default();
let received_messages = Arc::new(Mutex::new(Vec::new()));
let test_state = TestServerState {
received_messages: received_messages.clone(),
};
let app = Router::new()
.route("/", post(capture_notification))
.with_state(test_state);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let url = format!("http://{}", addr);
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
tokio::time::sleep(Duration::from_millis(100)).await;
(received_messages, url)
}
async fn setup_timeout_server(timeout: u64) -> String {
crate::crypto_provider::install_default();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let url = format!("http://{}", addr);
tokio::spawn(async move {
// Accept the connection but don't respond in the timeout
let (_socket, _addr) = listener.accept().await.unwrap();
tokio::time::sleep(Duration::from_secs(timeout * 2)).await;
});
tokio::time::sleep(Duration::from_millis(100)).await;
url
}
async fn cleanup_worker(sender: mpsc::Sender<Notification>, tracker: TaskTracker) {
drop(sender);
tracker.close();
tracker.wait().await;
}
#[tokio::test]
async fn test_send_notification_times_out() {
let timeout: u64 = 2;
let url = setup_timeout_server(timeout).await;
let http_client = reqwest::Client::new();
let result = send_notification(
&http_client,
&url,
"test warning message".to_string(),
timeout,
)
.await;
match result {
Err(NotificationError::RequestFailed(reqwest_error)) => {
println!("error = {:?}", reqwest_error);
assert!(reqwest_error.is_timeout());
}
_ => assert!(false),
}
}
#[tokio::test]
async fn test_notification_worker_sends_message() {
let (received_messages, url) = setup_test_server().await;
let task_tracker = TaskTracker::new();
let notification_service = NotificationService::new(Some(url));
let notification_sender = notification_service.new_handler();
run_notification_worker(
&task_tracker,
notification_service,
vec![NotificationType::Warning],
);
notification_sender
.send(Notification::new(
NotificationType::Warning,
"test warning message".to_string(),
None,
))
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(3)).await;
let messages = received_messages.lock().await;
assert_eq!(messages.len(), 1);
assert_eq!(messages[0], "test warning message");
drop(messages);
cleanup_worker(notification_sender, task_tracker).await;
}
#[tokio::test]
async fn test_notification_worker_filters_disabled_types() {
let (received_messages, url) = setup_test_server().await;
let task_tracker = TaskTracker::new();
let notification_service = NotificationService::new(Some(url));
let notification_sender = notification_service.new_handler();
run_notification_worker(
&task_tracker,
notification_service,
vec![NotificationType::Warning],
);
notification_sender
.send(Notification::new(
NotificationType::Warning,
"test warning".to_string(),
None,
))
.await
.unwrap();
notification_sender
.send(Notification::new(
NotificationType::LowBattery,
"test low battery".to_string(),
None,
))
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(3)).await;
let messages = received_messages.lock().await;
assert_eq!(messages.len(), 1);
assert_eq!(messages[0], "test warning");
drop(messages);
cleanup_worker(notification_sender, task_tracker).await;
}
#[tokio::test]
async fn test_notification_worker_sends_enabled_types() {
let (received_messages, url) = setup_test_server().await;
let task_tracker = TaskTracker::new();
let notification_service = NotificationService::new(Some(url));
let notification_sender = notification_service.new_handler();
run_notification_worker(
&task_tracker,
notification_service,
vec![NotificationType::Warning, NotificationType::LowBattery],
);
notification_sender
.send(Notification::new(
NotificationType::Warning,
"test warning".to_string(),
None,
))
.await
.unwrap();
notification_sender
.send(Notification::new(
NotificationType::LowBattery,
"test low battery".to_string(),
None,
))
.await
.unwrap();
tokio::time::sleep(Duration::from_secs(3)).await;
let messages = received_messages.lock().await;
assert_eq!(messages.len(), 2);
// these are interchangeable, ordering not guaranteed
assert!(messages.contains(&"test warning".to_string()));
assert!(messages.contains(&"test low battery".to_string()));
drop(messages);
cleanup_worker(notification_sender, task_tracker).await;
}
#[tokio::test]
async fn test_notification_worker_with_no_url() {
let task_tracker = TaskTracker::new();
let notification_service = NotificationService::new(None);
let notification_sender = notification_service.new_handler();
run_notification_worker(
&task_tracker,
notification_service,
vec![NotificationType::Warning],
);
notification_sender
.send(Notification::new(
NotificationType::Warning,
"test warning".to_string(),
None,
))
.await
.unwrap();
tokio::time::sleep(Duration::from_millis(500)).await;
cleanup_worker(notification_sender, task_tracker).await;
}
}

108
daemon/src/pcap.rs Normal file
View File

@@ -0,0 +1,108 @@
use crate::server::ServerState;
use anyhow::Error;
use axum::body::Body;
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::http::header::CONTENT_TYPE;
use axum::response::{IntoResponse, Response};
use log::error;
use rayhunter::diag::DataType;
use rayhunter::gsmtap_parser;
use rayhunter::pcap::GsmtapPcapWriter;
use rayhunter::qmdl::QmdlReader;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncWrite, duplex};
use tokio_util::io::ReaderStream;
// Streams a pcap file chunk-by-chunk to the client by reading the QMDL data
// written so far. This is done by spawning a thread which streams chunks of
// pcap data to a channel that's piped to the client.
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/pcap/{name}",
tag = "Recordings",
responses(
(status = StatusCode::OK, description = "PCAP conversion successful", content_type = "application/vnd.tcpdump.pcap"),
(status = StatusCode::NOT_FOUND, description = "Could not find file {name}"),
(status = StatusCode::SERVICE_UNAVAILABLE, description = "QMDL file is empty")
),
params(
("name" = String, Path, description = "QMDL filename to convert and download")
),
summary = "Download a PCAP file",
description = "Stream a PCAP file to a client in chunks by converting the QMDL data for file {name} written so far."
))]
pub async fn get_pcap(
State(state): State<Arc<ServerState>>,
Path(mut qmdl_name): Path<String>,
) -> Result<Response, (StatusCode, String)> {
let qmdl_store = state.qmdl_store_lock.read().await;
if qmdl_name.ends_with("pcapng") {
qmdl_name = qmdl_name.trim_end_matches(".pcapng").to_string();
}
let (entry_index, entry) = qmdl_store.entry_for_name(&qmdl_name).ok_or((
StatusCode::NOT_FOUND,
format!("couldn't find manifest entry with name {qmdl_name}"),
))?;
if entry.qmdl_size_bytes == 0 {
return Err((
StatusCode::SERVICE_UNAVAILABLE,
"QMDL file is empty, try again in a bit!".to_string(),
));
}
let qmdl_size_bytes = entry.qmdl_size_bytes;
let qmdl_file = qmdl_store
.open_entry_qmdl(entry_index)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("{e:?}")))?;
// the QMDL reader should stop at the last successfully written data chunk
// (entry.size_bytes)
let (reader, writer) = duplex(1024);
tokio::spawn(async move {
if let Err(e) = generate_pcap_data(writer, qmdl_file, qmdl_size_bytes).await {
error!("failed to generate PCAP: {e:?}");
}
});
let headers = [(CONTENT_TYPE, "application/vnd.tcpdump.pcap")];
let body = Body::from_stream(ReaderStream::new(reader));
Ok((headers, body).into_response())
}
pub async fn generate_pcap_data<R, W>(
writer: W,
qmdl_file: R,
qmdl_size_bytes: usize,
) -> Result<(), Error>
where
W: AsyncWrite + Unpin + Send,
R: AsyncRead + Unpin,
{
let mut pcap_writer = GsmtapPcapWriter::new(writer).await?;
pcap_writer.write_iface_header().await?;
let mut reader = QmdlReader::new(qmdl_file, Some(qmdl_size_bytes));
while let Some(container) = reader.get_next_messages_container().await? {
if container.data_type != DataType::UserSpace {
continue;
}
for maybe_msg in container.into_messages() {
match maybe_msg {
Ok(msg) => {
let maybe_gsmtap_msg = gsmtap_parser::parse(msg)?;
if let Some((timestamp, gsmtap_msg)) = maybe_gsmtap_msg {
pcap_writer
.write_gsmtap_message(gsmtap_msg, timestamp)
.await?;
}
}
Err(e) => error!("error parsing message: {e:?}"),
}
}
}
Ok(())
}

659
daemon/src/qmdl_store.rs Normal file
View File

@@ -0,0 +1,659 @@
use std::io::{self, ErrorKind};
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use chrono::{DateTime, Local, TimeDelta};
use log::{info, warn};
use rayhunter::util::RuntimeMetadata;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use tokio::{
fs::{self, File, OpenOptions, try_exists},
io::AsyncWriteExt,
};
#[derive(Debug, Error)]
pub enum RecordingStoreError {
#[error("Can't close an entry when there's no current entry")]
NoCurrentEntry,
#[error("An entry with that name doesn't exist")]
NoSuchEntryError,
#[error("Couldn't create file: {0}")]
CreateFileError(tokio::io::Error),
#[error("Couldn't read file: {0}")]
ReadFileError(tokio::io::Error),
#[error("Couldn't delete file: {0}")]
DeleteFileError(tokio::io::Error),
#[error("Couldn't open directory at path: {0}")]
OpenDirError(tokio::io::Error),
#[error("Couldn't read manifest file: {0}")]
ReadManifestError(tokio::io::Error),
#[error("Couldn't write manifest file: {0}")]
WriteManifestError(tokio::io::Error),
#[error("Couldn't parse QMDL store manifest file: {0}")]
ParseManifestError(toml::de::Error),
}
pub struct RecordingStore {
pub path: PathBuf,
pub manifest: Manifest,
pub current_entry: Option<usize>, // index into manifest
}
#[derive(Deserialize, Serialize, Clone, PartialEq, Debug)]
pub struct Manifest {
pub entries: Vec<ManifestEntry>,
}
/// The structure of an entry in the QMDL manifest table
#[derive(Deserialize, Serialize, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct ManifestEntry {
/// The name of the entry
pub name: String,
/// The system time when recording began
#[cfg_attr(feature = "apidocs", schema(value_type = String))]
pub start_time: DateTime<Local>,
/// The system time when the last message was recorded to the file
#[cfg_attr(feature = "apidocs", schema(value_type = String))]
pub last_message_time: Option<DateTime<Local>>,
/// The size of the QMDL file in bytes
pub qmdl_size_bytes: usize,
/// The rayhunter daemon version which generated the file
pub rayhunter_version: Option<String>,
/// The OS which created the file
pub system_os: Option<String>,
/// The architecture on which the OS was running
pub arch: Option<String>,
#[serde(default)]
pub stop_reason: Option<String>,
/// When the manifest was uploaded to a WebDAV server
#[cfg_attr(feature = "apidocs", schema(value_type = String))]
pub upload_time: Option<DateTime<Local>>,
}
impl ManifestEntry {
fn new() -> Self {
let now = rayhunter::clock::get_adjusted_now();
let metadata = RuntimeMetadata::new();
ManifestEntry {
name: format!("{}", now.timestamp()),
start_time: now,
last_message_time: None,
qmdl_size_bytes: 0,
rayhunter_version: Some(metadata.rayhunter_version),
system_os: Some(metadata.system_os),
arch: Some(metadata.arch),
stop_reason: None,
upload_time: None,
}
}
pub fn get_qmdl_filepath<P: AsRef<Path>>(&self, path: P) -> PathBuf {
let mut filepath = path.as_ref().join(&self.name);
filepath.set_extension("qmdl");
filepath
}
pub fn get_analysis_filepath<P: AsRef<Path>>(&self, path: P) -> PathBuf {
let mut filepath = path.as_ref().join(&self.name);
filepath.set_extension("ndjson");
filepath
}
}
impl RecordingStore {
// Returns whether a directory with a "manifest.toml" exists at the given
// path (though doesn't check if that manifest is valid)
pub async fn exists<P>(path: P) -> Result<bool, RecordingStoreError>
where
P: AsRef<Path>,
{
let manifest_path = path.as_ref().join("manifest.toml");
let dir_exists = try_exists(path)
.await
.map_err(RecordingStoreError::OpenDirError)?;
let manifest_exists = try_exists(manifest_path)
.await
.map_err(RecordingStoreError::ReadManifestError)?;
Ok(dir_exists && manifest_exists)
}
// Loads an existing RecordingStore at the given path. Errors if no store exists,
// or if it's malformed.
pub async fn load<P>(path: P) -> Result<Self, RecordingStoreError>
where
P: AsRef<Path>,
{
let path: PathBuf = path.as_ref().to_path_buf();
let manifest = RecordingStore::read_manifest(&path).await?;
Ok(RecordingStore {
path,
manifest,
current_entry: None,
})
}
// Creates a new RecordingStore at the given path. This involves creating a dir
// and writing an empty manifest.
pub async fn create<P>(path: P) -> Result<Self, RecordingStoreError>
where
P: AsRef<Path>,
{
fs::create_dir_all(&path)
.await
.map_err(RecordingStoreError::OpenDirError)?;
let mut store = RecordingStore {
path: path.as_ref().to_owned(),
manifest: Manifest {
entries: Vec::new(),
},
current_entry: None,
};
store.write_manifest().await?;
Ok(store)
}
// Does a best-effort attempt to recover the manifest from a directory of
// QMDL files. We expect these files to be named like "<timestamp>.qmdl",
// and skip any files which don't match that pattern.
pub async fn recover<P>(path: P) -> Result<Self, RecordingStoreError>
where
P: AsRef<Path>,
{
let mut dir_entries = fs::read_dir(path.as_ref())
.await
.map_err(RecordingStoreError::OpenDirError)?;
let mut manifest_entries = Vec::new();
while let Some(entry) = dir_entries
.next_entry()
.await
.map_err(RecordingStoreError::OpenDirError)?
{
let os_filename = entry.file_name();
let Some(filename) = os_filename.to_str() else {
continue;
};
if !filename.ends_with(".qmdl") {
continue;
}
let stem = filename.trim_end_matches(".qmdl");
let Ok(start_timestamp) = stem.parse::<i64>() else {
warn!("QMDL file has invalid name {os_filename:?}, skipping");
continue;
};
let metadata = match entry.metadata().await {
Ok(metadata) => metadata,
Err(err) => {
warn!("failed to read QMDL file metadata: {err:?}, skipping");
continue;
}
};
let Some(start_time) = DateTime::from_timestamp(start_timestamp, 0) else {
warn!("QMDL filename {os_filename:?} gave an invalid timestamp, skipping");
continue;
};
let Ok(last_message_time) = metadata.modified() else {
warn!("failed to get modified time for QMDL file {os_filename:?}, skipping");
continue;
};
info!("successfully recovered QMDL entry {os_filename:?}!");
manifest_entries.push(ManifestEntry {
name: stem.to_string(),
start_time: start_time.into(),
last_message_time: Some(last_message_time.into()),
qmdl_size_bytes: metadata.size() as usize,
rayhunter_version: None,
system_os: None,
arch: None,
stop_reason: None,
upload_time: None,
});
}
// sort chronologically
manifest_entries.sort_by_key(|a| a.start_time);
let mut store = RecordingStore {
path: path.as_ref().to_path_buf(),
manifest: Manifest {
entries: manifest_entries,
},
current_entry: None,
};
store.write_manifest().await?;
Ok(store)
}
async fn read_manifest<P>(path: P) -> Result<Manifest, RecordingStoreError>
where
P: AsRef<Path>,
{
let manifest_path = path.as_ref().join("manifest.toml");
let file_contents = fs::read_to_string(&manifest_path)
.await
.map_err(RecordingStoreError::ReadManifestError)?;
toml::from_str(&file_contents).map_err(RecordingStoreError::ParseManifestError)
}
// Closes the current entry (if needed), creates a new entry based on the
// current time, and updates the manifest. Returns a tuple of the entry's
// newly created QMDL file and analysis file.
pub async fn new_entry(&mut self) -> Result<(File, File), RecordingStoreError> {
// if we've already got an entry open, close it
if self.current_entry.is_some() {
self.close_current_entry().await?;
}
let new_entry = ManifestEntry::new();
let qmdl_filepath = new_entry.get_qmdl_filepath(&self.path);
let qmdl_file = File::create(&qmdl_filepath)
.await
.map_err(RecordingStoreError::CreateFileError)?;
let analysis_filepath = new_entry.get_analysis_filepath(&self.path);
let analysis_file = File::create(&analysis_filepath)
.await
.map_err(RecordingStoreError::CreateFileError)?;
self.manifest.entries.push(new_entry);
self.current_entry = Some(self.manifest.entries.len() - 1);
self.write_manifest().await?;
Ok((qmdl_file, analysis_file))
}
// Returns the corresponding QMDL file for a given entry
pub async fn open_entry_qmdl(&self, entry_index: usize) -> Result<File, RecordingStoreError> {
let entry = &self.manifest.entries[entry_index];
File::open(entry.get_qmdl_filepath(&self.path))
.await
.map_err(RecordingStoreError::ReadFileError)
}
// Returns the corresponding QMDL file for a given entry
pub async fn open_entry_analysis(
&self,
entry_index: usize,
) -> Result<File, RecordingStoreError> {
let entry = &self.manifest.entries[entry_index];
File::open(entry.get_analysis_filepath(&self.path))
.await
.map_err(RecordingStoreError::ReadFileError)
}
pub async fn clear_and_open_entry_analysis(
&mut self,
entry_index: usize,
) -> Result<File, RecordingStoreError> {
let entry = &self.manifest.entries[entry_index];
let file = OpenOptions::new()
.write(true)
.truncate(true)
.open(entry.get_analysis_filepath(&self.path))
.await
.map_err(RecordingStoreError::ReadFileError)?;
Ok(file)
}
// Unsets the current entry
pub async fn close_current_entry(&mut self) -> Result<(), RecordingStoreError> {
match self.current_entry {
Some(_) => {
self.current_entry = None;
Ok(())
}
None => Err(RecordingStoreError::NoCurrentEntry),
}
}
// Sets the given entry's size and updates the last_message_time to now, updating the manifest
pub async fn update_entry_qmdl_size(
&mut self,
entry_index: usize,
size_bytes: usize,
) -> Result<(), RecordingStoreError> {
self.manifest.entries[entry_index].qmdl_size_bytes = size_bytes;
self.manifest.entries[entry_index].last_message_time =
Some(rayhunter::clock::get_adjusted_now());
self.write_manifest().await
}
async fn write_manifest(&mut self) -> Result<(), RecordingStoreError> {
// we don't technically need a mutable reference to `self` here, but it
// does prevent multiple concurrent writes across different threads
let tmp_path = self.path.join("manifest.toml.new");
let mut manifest_tmp_file = File::create(&tmp_path)
.await
.map_err(RecordingStoreError::WriteManifestError)?;
let manifest_contents =
toml::to_string_pretty(&self.manifest).expect("failed to serialize manifest");
manifest_tmp_file
.write_all(manifest_contents.as_bytes())
.await
.map_err(RecordingStoreError::WriteManifestError)?;
fs::rename(tmp_path, self.path.join("manifest.toml"))
.await
.map_err(RecordingStoreError::WriteManifestError)?;
Ok(())
}
pub fn get_next_unuploaded_entry(&self, min_age: TimeDelta) -> Option<String> {
let now = rayhunter::clock::get_adjusted_now();
self.manifest
.entries
.iter()
.filter_map(|entry| {
if self.is_current_entry(&entry.name) || entry.upload_time.is_some() {
return None;
}
let age = now - entry.last_message_time.unwrap_or(entry.start_time);
(age > min_age).then_some((&entry.name, age))
})
.max_by_key(|(_, age)| *age)
.map(|(name, _)| name.clone())
}
// Finds an entry by filename
pub fn entry_for_name(&self, name: &str) -> Option<(usize, &ManifestEntry)> {
let entry_index = self
.manifest
.entries
.iter()
.position(|entry| entry.name == name)?;
Some((entry_index, &self.manifest.entries[entry_index]))
}
pub fn get_current_entry(&self) -> Option<(usize, &ManifestEntry)> {
let entry_index = self.current_entry?;
Some((entry_index, &self.manifest.entries[entry_index]))
}
pub async fn set_current_stop_reason(
&mut self,
reason: String,
) -> Result<(), RecordingStoreError> {
if let Some(idx) = self.current_entry {
self.manifest.entries[idx].stop_reason = Some(reason);
self.write_manifest().await?;
}
Ok(())
}
pub async fn mark_entry_as_uploaded(
&mut self,
name: &str,
upload_time: DateTime<Local>,
) -> Result<(), RecordingStoreError> {
let entry_index = self
.manifest
.entries
.iter()
.position(|entry| entry.name == name)
.ok_or(RecordingStoreError::NoSuchEntryError)?;
self.manifest.entries[entry_index].upload_time = Some(upload_time);
self.write_manifest().await?;
Ok(())
}
pub fn is_current_entry(&self, name: &str) -> bool {
match self.current_entry {
Some(idx) => match self.manifest.entries.get(idx) {
Some(entry) => entry.name == name,
None => false,
},
None => false,
}
}
pub async fn delete_entry(&mut self, name: &str) -> Result<(), RecordingStoreError> {
let entry_to_delete_idx = self
.manifest
.entries
.iter()
.position(|entry| entry.name == name)
.ok_or(RecordingStoreError::NoSuchEntryError)?;
match self.current_entry {
Some(current_entry) if current_entry == entry_to_delete_idx => {
self.close_current_entry().await?;
}
Some(current_entry) => {
self.current_entry = Some(current_entry - 1);
}
None => {}
};
let entry_to_delete = self.manifest.entries.remove(entry_to_delete_idx);
self.write_manifest().await?;
let qmdl_filepath = entry_to_delete.get_qmdl_filepath(&self.path);
let analysis_filepath = entry_to_delete.get_analysis_filepath(&self.path);
remove_file_if_exists(&qmdl_filepath)
.await
.map_err(RecordingStoreError::DeleteFileError)?;
remove_file_if_exists(&analysis_filepath)
.await
.map_err(RecordingStoreError::DeleteFileError)?;
Ok(())
}
pub async fn delete_all_entries(&mut self) -> Result<(), RecordingStoreError> {
if self.current_entry.is_some() {
self.close_current_entry().await?;
}
let mut keep = Vec::new();
for entry in &self.manifest.entries {
let qmdl_filepath = entry.get_qmdl_filepath(&self.path);
let analysis_filepath = entry.get_analysis_filepath(&self.path);
if let Err(e) = remove_file_if_exists(&qmdl_filepath).await {
log::warn!("failed to remove {qmdl_filepath:?}: {e:?}");
keep.push(true);
continue;
}
if let Err(e) = remove_file_if_exists(&analysis_filepath).await {
log::warn!("failed to remove {analysis_filepath:?}: {e:?}");
keep.push(true);
continue;
}
keep.push(false);
}
let mut keep_iter = keep.into_iter();
self.manifest.entries.retain(|_| keep_iter.next().unwrap());
self.write_manifest().await?;
Ok(())
}
}
async fn remove_file_if_exists(path: &Path) -> Result<(), io::Error> {
match tokio::fs::remove_file(path).await {
Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
res => res,
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::{Builder, TempDir};
fn make_temp_dir() -> TempDir {
Builder::new().prefix("qmdl_store_test").tempdir().unwrap()
}
#[tokio::test]
async fn test_load_from_empty_dir() {
let dir = make_temp_dir();
assert!(!RecordingStore::exists(dir.path()).await.unwrap());
let _created_store = RecordingStore::create(dir.path()).await.unwrap();
assert!(RecordingStore::exists(dir.path()).await.unwrap());
let loaded_store = RecordingStore::load(dir.path()).await.unwrap();
assert_eq!(loaded_store.manifest.entries.len(), 0);
}
#[tokio::test]
async fn test_creating_updating_and_closing_entries() {
let dir = make_temp_dir();
let mut store = RecordingStore::create(dir.path()).await.unwrap();
let _ = store.new_entry().await.unwrap();
let entry_index = store.current_entry.unwrap();
assert_eq!(
RecordingStore::read_manifest(dir.path()).await.unwrap(),
store.manifest
);
assert!(
store.manifest.entries[entry_index]
.last_message_time
.is_none()
);
store
.update_entry_qmdl_size(entry_index, 1000)
.await
.unwrap();
let (entry_index, entry) = store
.entry_for_name(&store.manifest.entries[entry_index].name)
.unwrap();
assert!(entry.last_message_time.is_some());
assert_eq!(store.manifest.entries[entry_index].qmdl_size_bytes, 1000);
assert_eq!(
RecordingStore::read_manifest(dir.path()).await.unwrap(),
store.manifest
);
store.close_current_entry().await.unwrap();
assert!(matches!(
store.close_current_entry().await,
Err(RecordingStoreError::NoCurrentEntry)
));
}
#[tokio::test]
async fn test_create_on_existing_store() {
let dir = make_temp_dir();
let mut store = RecordingStore::create(dir.path()).await.unwrap();
let _ = store.new_entry().await.unwrap();
let entry_index = store.current_entry.unwrap();
store
.update_entry_qmdl_size(entry_index, 1000)
.await
.unwrap();
let store = RecordingStore::create(dir.path()).await.unwrap();
assert_eq!(store.manifest.entries.len(), 0);
}
#[tokio::test]
async fn test_repeated_new_entries() {
let dir = make_temp_dir();
let mut store = RecordingStore::create(dir.path()).await.unwrap();
let _ = store.new_entry().await.unwrap();
let entry_index = store.current_entry.unwrap();
let _ = store.new_entry().await.unwrap();
let new_entry_index = store.current_entry.unwrap();
assert_ne!(entry_index, new_entry_index);
assert_eq!(store.manifest.entries.len(), 2);
}
#[tokio::test]
async fn test_delete_all_entries() {
let dir = make_temp_dir();
let mut store = RecordingStore::create(dir.path()).await.unwrap();
let _ = store.new_entry().await.unwrap();
assert!(store.current_entry.is_some());
store.delete_all_entries().await.unwrap();
assert!(store.current_entry.is_none());
// regression test: deleting all entries should also work when there's no current
// recording.
store.delete_all_entries().await.unwrap();
assert!(store.current_entry.is_none());
}
#[tokio::test]
async fn test_mark_entry_as_uploaded_sets_time_and_persists() {
let dir = make_temp_dir();
let mut store = RecordingStore::create(dir.path()).await.unwrap();
let _ = store.new_entry().await.unwrap();
let name = store.manifest.entries[0].name.clone();
store.close_current_entry().await.unwrap();
let upload_time = Local::now();
store
.mark_entry_as_uploaded(&name, upload_time)
.await
.unwrap();
assert_eq!(store.manifest.entries[0].upload_time, Some(upload_time));
let reloaded = RecordingStore::load(dir.path()).await.unwrap();
assert_eq!(reloaded.manifest.entries[0].upload_time, Some(upload_time));
}
#[tokio::test]
async fn test_mark_entry_as_uploaded_missing_entry() {
let dir = make_temp_dir();
let mut store = RecordingStore::create(dir.path()).await.unwrap();
assert!(matches!(
store.mark_entry_as_uploaded("nope", Local::now()).await,
Err(RecordingStoreError::NoSuchEntryError)
));
}
#[tokio::test]
async fn test_get_next_unuploaded_entry() {
let dir = make_temp_dir();
let mut store = RecordingStore::create(dir.path()).await.unwrap();
for _ in 0..3 {
let _ = store.new_entry().await.unwrap();
}
store.manifest.entries[0].name = "entry-0".to_owned();
store.manifest.entries[0].start_time = Local::now() - TimeDelta::seconds(10);
store.manifest.entries[0].last_message_time = None;
store.manifest.entries[1].name = "entry-1".to_owned();
store.manifest.entries[1].start_time = Local::now() - TimeDelta::seconds(10);
store.manifest.entries[1].last_message_time = Some(Local::now() - TimeDelta::seconds(5));
store.manifest.entries[2].name = "entry-2".to_owned();
store.manifest.entries[2].start_time = Local::now() - TimeDelta::seconds(10);
store.manifest.entries[2].last_message_time = Some(Local::now() - TimeDelta::seconds(1));
assert_eq!(
store.get_next_unuploaded_entry(TimeDelta::seconds(3600)),
None,
);
assert_eq!(
store.get_next_unuploaded_entry(TimeDelta::seconds(3)),
Some("entry-0".to_owned())
);
store
.mark_entry_as_uploaded("entry-0", Local::now())
.await
.unwrap();
assert_eq!(
store.get_next_unuploaded_entry(TimeDelta::seconds(3)),
Some("entry-1".to_owned())
);
store
.mark_entry_as_uploaded("entry-1", Local::now())
.await
.unwrap();
assert_eq!(store.get_next_unuploaded_entry(TimeDelta::seconds(3)), None);
}
}

604
daemon/src/server.rs Normal file
View File

@@ -0,0 +1,604 @@
use anyhow::Error;
use async_zip::Compression;
use async_zip::ZipEntryBuilder;
use async_zip::tokio::write::ZipFileWriter;
use axum::Json;
use axum::body::Body;
use axum::extract::Path;
use axum::extract::State;
use axum::http::header::{self, CONTENT_LENGTH, CONTENT_TYPE};
use axum::http::{HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use chrono::{DateTime, Local};
use log::{error, warn};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::fs::write;
use tokio::io::{AsyncReadExt, copy, duplex};
use tokio::sync::RwLock;
use tokio::sync::mpsc::Sender;
use tokio_util::compat::FuturesAsyncWriteCompatExt;
use tokio_util::io::ReaderStream;
use tokio_util::sync::CancellationToken;
use crate::analysis::{AnalysisCtrlMessage, AnalysisStatus};
use crate::config::Config;
use crate::diag::DiagDeviceCtrlMessage;
use crate::display::DisplayState;
use crate::notifications::DEFAULT_NOTIFICATION_TIMEOUT;
use crate::pcap::generate_pcap_data;
use crate::qmdl_store::RecordingStore;
pub struct ServerState {
pub config_path: String,
pub config: Config,
pub qmdl_store_lock: Arc<RwLock<RecordingStore>>,
pub diag_device_ctrl_sender: Sender<DiagDeviceCtrlMessage>,
pub analysis_status_lock: Arc<RwLock<AnalysisStatus>>,
pub analysis_sender: Sender<AnalysisCtrlMessage>,
pub daemon_restart_token: CancellationToken,
pub ui_update_sender: Option<Sender<DisplayState>>,
pub wifi_status: Arc<RwLock<wifi_station::WifiStatus>>,
pub wifi_scan_lock: tokio::sync::Mutex<()>,
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/qmdl/{name}",
tag = "Recordings",
responses(
(status = StatusCode::OK, description = "QMDL download successful", content_type = "application/octet-stream"),
(status = StatusCode::NOT_FOUND, description = "Could not find file {name}"),
(status = StatusCode::SERVICE_UNAVAILABLE, description = "QMDL file is empty, or error opening file")
),
params(
("name" = String, Path, description = "QMDL filename to convert and download")
),
summary = "Download a QMDL file",
description = "Stream the QMDL file {name} to the client."
))]
pub async fn get_qmdl(
State(state): State<Arc<ServerState>>,
Path(qmdl_name): Path<String>,
) -> Result<Response, (StatusCode, String)> {
let qmdl_idx = qmdl_name.trim_end_matches(".qmdl");
let qmdl_store = state.qmdl_store_lock.read().await;
let (entry_index, entry) = qmdl_store.entry_for_name(qmdl_idx).ok_or((
StatusCode::NOT_FOUND,
format!("couldn't find qmdl file with name {qmdl_idx}"),
))?;
let qmdl_file = qmdl_store
.open_entry_qmdl(entry_index)
.await
.map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("error opening QMDL file: {err}"),
)
})?;
let limited_qmdl_file = qmdl_file.take(entry.qmdl_size_bytes as u64);
let qmdl_stream = ReaderStream::new(limited_qmdl_file);
let headers = [
(CONTENT_TYPE, "application/octet-stream"),
(CONTENT_LENGTH, &entry.qmdl_size_bytes.to_string()),
];
let body = Body::from_stream(qmdl_stream);
Ok((headers, body).into_response())
}
pub async fn serve_static(
State(_): State<Arc<ServerState>>,
Path(path): Path<String>,
) -> impl IntoResponse {
let path = path.trim_start_matches('/');
match path {
"rayhunter_orca_only.png" => (
[(header::CONTENT_TYPE, HeaderValue::from_static("image/png"))],
include_bytes!("../web/build/rayhunter_orca_only.png"),
)
.into_response(),
"rayhunter_text.png" => (
[(header::CONTENT_TYPE, HeaderValue::from_static("image/png"))],
include_bytes!("../web/build/rayhunter_text.png"),
)
.into_response(),
"favicon.png" => (
[(header::CONTENT_TYPE, HeaderValue::from_static("image/png"))],
include_bytes!("../web/build/favicon.png"),
)
.into_response(),
"index.html" => (
[
(header::CONTENT_TYPE, HeaderValue::from_static("text/html")),
(header::CONTENT_ENCODING, HeaderValue::from_static("gzip")),
],
include_bytes!("../web/build/index.html.gz"),
)
.into_response(),
path => {
warn!("404 on path: {path}");
StatusCode::NOT_FOUND.into_response()
}
}
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/config",
tag = "Configuration",
responses(
(status = StatusCode::OK, description = "Success", body = Config)
),
summary = "Get config",
description = "Show the running configuration for Rayhunter."
))]
pub async fn get_config(
State(state): State<Arc<ServerState>>,
) -> Result<Json<Config>, (StatusCode, String)> {
let mut config = state.config.clone();
config.wifi_password = None;
Ok(Json(config))
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/config",
tag = "Configuration",
request_body(
content = Option<[Config]>,
description = "Any or all configuration elements from the valid config schema to be altered may be passed. Invalid keys will be discarded. Invalid values or value types will return an error."
),
responses(
(status = StatusCode::ACCEPTED, description = "Success"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Failed to parse or write config file"),
(status = 422, description = "Failed to deserialize JSON body")
),
summary = "Set config",
description = "Write a new configuration for Rayhunter and trigger a restart."
))]
pub async fn set_config(
State(state): State<Arc<ServerState>>,
Json(config): Json<Config>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
let mut config_to_write = config.clone();
config_to_write.wifi_ssid = None;
config_to_write.wifi_password = None;
config_to_write.wifi_security = None;
let config_str = toml::to_string_pretty(&config_to_write).map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("failed to serialize config as TOML: {err}"),
)
})?;
write(&state.config_path, config_str).await.map_err(|err| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("failed to write config file: {err}"),
)
})?;
wifi_station::update_wpa_conf(&config.wifi_config()).await;
// Trigger daemon restart after writing config
state.daemon_restart_token.cancel();
Ok((
StatusCode::ACCEPTED,
"wrote config and triggered restart".to_string(),
))
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/test-notification",
tag = "Configuration",
responses(
(status = StatusCode::OK, description = "Success"),
(status = StatusCode::BAD_REQUEST, description = "No notification URL set"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Failed to send HTTP request. Ensure your device can reach the internet.")
),
summary = "Test ntfy notification",
description = "Send a test notification to the ntfy_url in the running configuration for Rayhunter."
))]
pub async fn test_notification(
State(state): State<Arc<ServerState>>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
let url = state.config.ntfy_url.as_ref().ok_or((
StatusCode::BAD_REQUEST,
"No notification URL configured".to_string(),
))?;
if url.is_empty() {
return Err((
StatusCode::BAD_REQUEST,
"Notification URL is empty".to_string(),
));
}
let http_client = reqwest::Client::new();
let message = "Test notification from Rayhunter".to_string();
crate::notifications::send_notification(
&http_client,
url,
message,
DEFAULT_NOTIFICATION_TIMEOUT,
)
.await
.map(|()| {
(
StatusCode::OK,
"Test notification sent successfully".to_string(),
)
})
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("Failed to send test notification: {e}"),
)
})
}
/// Response for GET /api/time
#[derive(Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct TimeResponse {
/// The raw system time (without clock offset)
#[cfg_attr(feature = "apidocs", schema(value_type = String))]
pub system_time: DateTime<Local>,
/// The adjusted time (system time + offset)
#[cfg_attr(feature = "apidocs", schema(value_type = String))]
pub adjusted_time: DateTime<Local>,
/// The current offset in seconds
pub offset_seconds: i64,
}
/// Request for POST /api/time-offset
#[derive(Deserialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct SetTimeOffsetRequest {
/// The offset to set, in seconds
pub offset_seconds: i64,
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/time",
tag = "Configuration",
responses(
(status = StatusCode::OK, description = "Success", body = TimeResponse)
),
summary = "Get time",
description = "Get the current time and offset (in seconds) of the device."
))]
pub async fn get_time() -> Json<TimeResponse> {
let system_time = Local::now();
let adjusted_time = rayhunter::clock::get_adjusted_now();
let offset_seconds = adjusted_time
.signed_duration_since(system_time)
.num_seconds();
Json(TimeResponse {
system_time,
adjusted_time,
offset_seconds,
})
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/time-offset",
tag = "Configuration",
request_body(
content = SetTimeOffsetRequest
),
responses(
(status = StatusCode::OK, description = "Success", body = TimeResponse)
),
summary = "Set time offset",
description = "Set the difference (in seconds) between the system time and the adjusted time for Rayhunter."
))]
pub async fn set_time_offset(Json(req): Json<SetTimeOffsetRequest>) -> StatusCode {
rayhunter::clock::set_offset(chrono::TimeDelta::seconds(req.offset_seconds));
StatusCode::OK
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/zip/{name}",
tag = "Recordings",
responses(
(status = StatusCode::OK, description = "ZIP download successful. It is possible that if the PCAP fails to convert, the same status will be returned, but the file will contain only the QMDL file.", content_type = "application/zip"),
(status = StatusCode::NOT_FOUND, description = "Could not find file {name}"),
(status = StatusCode::SERVICE_UNAVAILABLE, description = "QMDL file is empty, or error opening file")
),
params(
("name" = String, Path, description = "QMDL filename to convert and download")
),
summary = "Download a ZIP file",
description = "Stream a ZIP file to the client which contains the QMDL file {name} and a PCAP generated from the same file."
))]
pub async fn get_zip(
State(state): State<Arc<ServerState>>,
Path(entry_name): Path<String>,
) -> Result<Response, (StatusCode, String)> {
let qmdl_idx = entry_name.trim_end_matches(".zip").to_owned();
let (entry_index, qmdl_size_bytes) = {
let qmdl_store = state.qmdl_store_lock.read().await;
let (entry_index, entry) = qmdl_store.entry_for_name(&qmdl_idx).ok_or((
StatusCode::NOT_FOUND,
format!("couldn't find entry with name {qmdl_idx}"),
))?;
if entry.qmdl_size_bytes == 0 {
return Err((
StatusCode::SERVICE_UNAVAILABLE,
"QMDL file is empty, try again in a bit!".to_string(),
));
}
(entry_index, entry.qmdl_size_bytes)
};
let qmdl_store_lock = state.qmdl_store_lock.clone();
let (reader, writer) = duplex(8192);
tokio::spawn(async move {
let result: Result<(), Error> = async {
let mut zip = ZipFileWriter::with_tokio(writer);
// Add QMDL file
{
let entry =
ZipEntryBuilder::new(format!("{qmdl_idx}.qmdl").into(), Compression::Stored);
// FuturesAsyncWriteCompatExt::compat_write because async-zip's entrystream does
// not impl tokio's AsyncWrite, but only future's AsyncWrite. This can be removed
// once https://github.com/Majored/rs-async-zip/pull/160 is released.
let mut entry_writer = zip.write_entry_stream(entry).await?.compat_write();
let mut qmdl_file = {
let qmdl_store = qmdl_store_lock.read().await;
qmdl_store
.open_entry_qmdl(entry_index)
.await?
.take(qmdl_size_bytes as u64)
};
copy(&mut qmdl_file, &mut entry_writer).await?;
entry_writer.into_inner().close().await?;
}
// Add PCAP file
{
let entry =
ZipEntryBuilder::new(format!("{qmdl_idx}.pcapng").into(), Compression::Stored);
let mut entry_writer = zip.write_entry_stream(entry).await?.compat_write();
let qmdl_file_for_pcap = {
let qmdl_store = qmdl_store_lock.read().await;
qmdl_store
.open_entry_qmdl(entry_index)
.await?
.take(qmdl_size_bytes as u64)
};
if let Err(e) =
generate_pcap_data(&mut entry_writer, qmdl_file_for_pcap, qmdl_size_bytes).await
{
// if we fail to generate the PCAP file, we should still continue and give the
// user the QMDL.
error!("Failed to generate PCAP: {e:?}");
}
entry_writer.into_inner().close().await?;
}
zip.close().await?;
Ok(())
}
.await;
if let Err(e) = result {
error!("Error generating ZIP file: {e:?}");
}
});
let headers = [(CONTENT_TYPE, "application/zip")];
let body = Body::from_stream(ReaderStream::new(reader));
Ok((headers, body).into_response())
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/wifi-status",
tag = "Configuration",
responses(
(status = StatusCode::OK, description = "Success", body = wifi_station::WifiStatus)
),
summary = "Get wifi status",
description = "Show the status of the wifi client."
))]
pub async fn get_wifi_status(
State(state): State<Arc<ServerState>>,
) -> Json<wifi_station::WifiStatus> {
let status = state.wifi_status.read().await;
Json(status.clone())
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/wifi-scan",
tag = "Configuration",
responses(
(status = StatusCode::OK, description = "Scan success", body = inline(Vec<wifi_station::WifiNetwork>), content_type = "application/json"),
(status = StatusCode::TOO_MANY_REQUESTS, description = "Scan already in progress"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Scan failed"),
),
summary = "Wifi SSID scan",
description = "Poll for a list of available wifi networks. Returns an array of WifiNetwork objects."
))]
pub async fn scan_wifi(
State(state): State<Arc<ServerState>>,
) -> Result<Json<Vec<wifi_station::WifiNetwork>>, (StatusCode, String)> {
let _guard = state.wifi_scan_lock.try_lock().map_err(|_| {
(
StatusCode::TOO_MANY_REQUESTS,
"WiFi scan already in progress".to_string(),
)
})?;
let networks = wifi_station::scan_wifi_networks(wifi_station::STA_IFACE)
.await
.map_err(|e| {
(
StatusCode::INTERNAL_SERVER_ERROR,
format!("WiFi scan failed: {e}"),
)
})?;
Ok(Json(networks))
}
#[cfg_attr(feature = "apidocs", utoipa::path(
post,
path = "/api/debug/display-state",
tag = "Configuration",
request_body(
content = DisplayState
),
responses(
(status = StatusCode::OK, description = "Display state updated successfully"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Error sending update to the display"),
(status = StatusCode::SERVICE_UNAVAILABLE, description = "Display system not available")
),
summary = "Set display state",
description = "Change the display state (color bar or otherwise) of the device for debugging purposes."
))]
pub async fn debug_set_display_state(
State(state): State<Arc<ServerState>>,
Json(display_state): Json<DisplayState>,
) -> Result<(StatusCode, String), (StatusCode, String)> {
if let Some(ui_sender) = &state.ui_update_sender {
ui_sender.send(display_state).await.map_err(|_| {
(
StatusCode::INTERNAL_SERVER_ERROR,
"failed to send display state update".to_string(),
)
})?;
Ok((
StatusCode::OK,
"display state updated successfully".to_string(),
))
} else {
Err((
StatusCode::SERVICE_UNAVAILABLE,
"display system not available".to_string(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use async_zip::base::read::mem::ZipFileReader;
use axum::extract::{Path, State};
use tempfile::TempDir;
async fn create_test_qmdl_store() -> (TempDir, Arc<RwLock<crate::qmdl_store::RecordingStore>>) {
let temp_dir = TempDir::new().unwrap();
let store_path = temp_dir.path().to_path_buf();
let store = crate::qmdl_store::RecordingStore::create(&store_path)
.await
.unwrap();
(temp_dir, Arc::new(RwLock::new(store)))
}
async fn create_test_entry_with_data(
store_lock: &Arc<RwLock<crate::qmdl_store::RecordingStore>>,
test_data: &[u8],
) -> String {
let entry_name = {
let mut store = store_lock.write().await;
let (mut qmdl_file, _analysis_file) = store.new_entry().await.unwrap();
if !test_data.is_empty() {
use tokio::io::AsyncWriteExt;
qmdl_file.write_all(test_data).await.unwrap();
qmdl_file.flush().await.unwrap();
}
let current_entry = store.current_entry.unwrap();
let entry = &store.manifest.entries[current_entry];
let entry_name = entry.name.clone();
store
.update_entry_qmdl_size(current_entry, test_data.len())
.await
.unwrap();
entry_name
};
let mut store = store_lock.write().await;
store.close_current_entry().await.unwrap();
entry_name
}
fn create_test_server_state(
store_lock: Arc<RwLock<crate::qmdl_store::RecordingStore>>,
) -> Arc<ServerState> {
let (tx, _rx) = tokio::sync::mpsc::channel(1);
let (analysis_tx, _analysis_rx) = tokio::sync::mpsc::channel(1);
let analysis_status = {
let store = store_lock.try_read().unwrap();
crate::analysis::AnalysisStatus::new(&store)
};
Arc::new(ServerState {
config_path: "/tmp/test_config.toml".to_string(),
config: Config::default(),
qmdl_store_lock: store_lock,
diag_device_ctrl_sender: tx,
analysis_status_lock: Arc::new(RwLock::new(analysis_status)),
analysis_sender: analysis_tx,
daemon_restart_token: CancellationToken::new(),
ui_update_sender: None,
wifi_status: Arc::new(RwLock::new(wifi_station::WifiStatus::default())),
wifi_scan_lock: tokio::sync::Mutex::new(()),
})
}
#[tokio::test]
async fn test_get_zip_success() {
let (_temp_dir, store_lock) = create_test_qmdl_store().await;
let test_qmdl_data = vec![0x7E, 0x00, 0x00, 0x00, 0x10, 0x00, 0x7E];
let entry_name = create_test_entry_with_data(&store_lock, &test_qmdl_data).await;
let state = create_test_server_state(store_lock);
let result = get_zip(State(state), Path(entry_name.clone())).await;
assert!(result.is_ok());
let response = result.unwrap();
let headers = response.headers();
assert_eq!(headers.get("content-type").unwrap(), "application/zip");
let body = response.into_body();
let body_bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
let zip_reader = ZipFileReader::new(body_bytes.to_vec()).await.unwrap();
let filenames = zip_reader
.file()
.entries()
.iter()
.map(|entry| entry.filename().as_str().unwrap().to_owned())
.collect::<Vec<String>>();
assert_eq!(
filenames,
vec![format!("{entry_name}.qmdl"), format!("{entry_name}.pcapng"),]
);
}
}

238
daemon/src/stats.rs Normal file
View File

@@ -0,0 +1,238 @@
use std::ffi::CString;
use std::sync::Arc;
use crate::battery::get_battery_status;
use crate::error::RayhunterError;
use crate::server::ServerState;
use crate::{battery::BatteryState, qmdl_store::ManifestEntry};
use axum::Json;
use axum::extract::State;
use axum::http::StatusCode;
use log::error;
use rayhunter::{Device, util::RuntimeMetadata};
use serde::Serialize;
use tokio::process::Command;
/// Structure of device system statistics
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct SystemStats {
pub disk_stats: DiskStats,
pub memory_stats: MemoryStats,
pub runtime_metadata: RuntimeMetadata,
#[serde(skip_serializing_if = "Option::is_none")]
pub battery_status: Option<BatteryState>,
}
impl SystemStats {
pub async fn new(qmdl_path: &str, device: &Device) -> Result<Self, String> {
Ok(Self {
disk_stats: DiskStats::new(qmdl_path)?,
memory_stats: MemoryStats::new(device).await?,
runtime_metadata: RuntimeMetadata::new(),
battery_status: match get_battery_status(device).await {
Ok(status) => Some(status),
Err(RayhunterError::FunctionNotSupportedForDeviceError) => None,
Err(err) => {
log::error!("Failed to get battery status: {err}");
None
}
},
})
}
}
/// Device storage information
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct DiskStats {
/// The partition to which the daemon is installed
partition: String,
/// The total disk size of the partition
total_size: String,
/// Total used size of the partition
used_size: String,
/// Remaining free space of the partition
available_size: String,
/// Disk usage displayed as percentage
used_percent: String,
/// The root folder to which the partition is mounted
mounted_on: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub available_bytes: Option<u64>,
}
impl DiskStats {
#[allow(clippy::unnecessary_cast)] // c_ulong is u32 on ARM, u64 on macOS
pub fn new(qmdl_path: &str) -> Result<Self, String> {
let c_path =
CString::new(qmdl_path).map_err(|e| format!("invalid path {qmdl_path}: {e}"))?;
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(c_path.as_ptr(), &mut stat) } != 0 {
return Err(format!(
"statvfs({qmdl_path}) failed: {}",
std::io::Error::last_os_error()
));
}
let block_size = stat.f_frsize as u64;
let total_kb = (stat.f_blocks as u64 * block_size / 1024) as usize;
let free_kb = (stat.f_bfree as u64 * block_size / 1024) as usize;
let available_kb = (stat.f_bavail as u64 * block_size / 1024) as usize;
let used_kb = total_kb.saturating_sub(free_kb);
let used_percent = format!(
"{}%",
((stat.f_blocks - stat.f_bfree) * 100)
.checked_div(stat.f_blocks)
.unwrap_or(0)
);
Ok(Self {
partition: qmdl_path.to_string(),
total_size: humanize_kb(total_kb),
used_size: humanize_kb(used_kb),
available_size: humanize_kb(available_kb),
used_percent,
mounted_on: qmdl_path.to_string(),
available_bytes: Some(stat.f_bavail as u64 * block_size),
})
}
}
/// Device memory information
#[derive(Debug, Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct MemoryStats {
/// The total memory available on the device
total: String,
/// The currently used memory
used: String,
/// Remaining free memory
free: String,
}
// runs the given command and returns its stdout as a string
async fn get_cmd_output(mut cmd: Command) -> Result<String, String> {
let cmd_str = format!("{:?}", &cmd);
let output = cmd
.output()
.await
.map_err(|e| format!("error running command {}: {}", &cmd_str, e))?;
if !output.status.success() {
return Err(format!(
"command {} failed with exit code {}",
&cmd_str,
output.status.code().unwrap()
));
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
impl MemoryStats {
// runs "free -k" and parses the output to retrieve memory stats for most devices,
pub async fn new(device: &Device) -> Result<Self, String> {
// Use busybox for Uz801
let mut free_cmd: Command;
if matches!(device, Device::Uz801) {
free_cmd = Command::new("busybox");
free_cmd.arg("free");
} else {
free_cmd = Command::new("free");
}
free_cmd.arg("-k");
let stdout = get_cmd_output(free_cmd).await?;
let mut numbers = stdout
.split_whitespace()
.flat_map(|part| part.parse::<usize>());
Ok(Self {
total: humanize_kb(numbers.next().ok_or("error parsing free output")?),
used: humanize_kb(numbers.next().ok_or("error parsing free output")?),
free: humanize_kb(numbers.next().ok_or("error parsing free output")?),
})
}
}
// turns a number of kilobytes (like 28293) into a human-readable string (like "28.3M")
fn humanize_kb(kb: usize) -> String {
if kb < 1000 {
return format!("{kb}K");
}
format!("{:.1}M", kb as f64 / 1024.0)
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/system-stats",
tag = "Statistics",
responses(
(status = StatusCode::OK, description = "Success", body = SystemStats),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Error collecting statistics")
),
summary = "Get system info",
description = "Display system/device statistics."
))]
pub async fn get_system_stats(
State(state): State<Arc<ServerState>>,
) -> Result<Json<SystemStats>, (StatusCode, String)> {
let qmdl_store = state.qmdl_store_lock.read().await;
match SystemStats::new(qmdl_store.path.to_str().unwrap(), &state.config.device).await {
Ok(stats) => Ok(Json(stats)),
Err(err) => {
error!("error getting system stats: {err}");
Err((
StatusCode::INTERNAL_SERVER_ERROR,
"error getting system stats".to_string(),
))
}
}
}
/// QMDL manifest information
#[derive(Serialize)]
#[cfg_attr(feature = "apidocs", derive(utoipa::ToSchema))]
pub struct ManifestStats {
/// A vector containing the names of the QMDL files
pub entries: Vec<ManifestEntry>,
/// The currently open QMDL file
pub current_entry: Option<ManifestEntry>,
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/qmdl-manifest",
tag = "Statistics",
responses(
(status = StatusCode::OK, description = "Success", body = ManifestStats)
),
summary = "QMDL Manifest",
description = "List QMDL files available on the device and some of their basic statistics."
))]
pub async fn get_qmdl_manifest(
State(state): State<Arc<ServerState>>,
) -> Result<Json<ManifestStats>, (StatusCode, String)> {
let qmdl_store = state.qmdl_store_lock.read().await;
let mut entries = qmdl_store.manifest.entries.clone();
let current_entry = qmdl_store.current_entry.map(|index| entries.remove(index));
Ok(Json(ManifestStats {
entries,
current_entry,
}))
}
#[cfg_attr(feature = "apidocs", utoipa::path(
get,
path = "/api/log",
tag = "Statistics",
responses(
(status = StatusCode::OK, description = "Success", content_type = "text/plain"),
(status = StatusCode::INTERNAL_SERVER_ERROR, description = "Could not read /data/rayhunter/rayhunter.log file")
),
summary = "Display log",
description = "Download the current device log in UTF-8 plaintext."
))]
pub async fn get_log() -> Result<String, (StatusCode, String)> {
tokio::fs::read_to_string("/data/rayhunter/rayhunter.log")
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
}

446
daemon/src/webdav.rs Normal file
View File

@@ -0,0 +1,446 @@
use std::fmt::Display;
use std::{sync::Arc, time::Duration};
use chrono::TimeDelta;
use log::{info, warn};
use reqwest::header::{CONTENT_LENGTH, CONTENT_TYPE};
use reqwest::{Body, Client, Response};
use tokio::fs::File;
use tokio::join;
use tokio::{select, sync::RwLock, time};
use tokio_util::io::ReaderStream;
use tokio_util::{sync::CancellationToken, task::TaskTracker};
use crate::config::WebdavConfig;
use crate::qmdl_store::RecordingStore;
pub struct WebdavUploadWorkerConfig {
poll_interval: Duration,
min_age: TimeDelta,
url: String,
username: Option<String>,
password: Option<String>,
timeout: Duration,
delete_on_upload: bool,
}
impl From<WebdavConfig> for WebdavUploadWorkerConfig {
fn from(value: WebdavConfig) -> Self {
WebdavUploadWorkerConfig {
poll_interval: Duration::from_secs(value.poll_interval_secs),
min_age: TimeDelta::seconds(value.min_age_secs),
url: value.url,
username: value.username,
password: value.password,
timeout: Duration::from_secs(value.upload_timeout_secs),
delete_on_upload: value.delete_on_upload,
}
}
}
enum FileKind {
Analysis,
Qmdl,
}
impl FileKind {
fn as_extension(&self) -> &'static str {
match self {
FileKind::Analysis => ".ndjson",
FileKind::Qmdl => ".qmdl",
}
}
}
impl Display for FileKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
FileKind::Analysis => write!(f, "analysis"),
FileKind::Qmdl => write!(f, "QMDL"),
}
}
}
#[derive(Debug, Clone)]
struct WebDavClient {
client: Client,
url: String,
username: Option<String>,
password: Option<String>,
}
impl WebDavClient {
fn new(
mut url: String,
username: Option<String>,
password: Option<String>,
timeout: Duration,
) -> Result<Self, reqwest::Error> {
if !url.ends_with('/') {
url.push('/');
}
Ok(Self {
client: reqwest::Client::builder().timeout(timeout).build()?,
url,
username,
password,
})
}
async fn try_upload_file(&self, file: File, name: &str) -> anyhow::Result<Response> {
let file_size = file.metadata().await?.len();
let stream = ReaderStream::new(file);
let body = Body::wrap_stream(stream);
let target = format!("{}{}", self.url, name);
let client = self
.client
.put(&target)
.header(CONTENT_TYPE, "application/octet-stream")
.header(CONTENT_LENGTH, file_size);
let client = match (&self.username, &self.password) {
(Some(username), Some(password)) => client.basic_auth(username, Some(password)),
(Some(username), None) => client.basic_auth(username, None::<&str>),
(None, None) => client,
(None, Some(_)) => {
warn!(
"Got WebDAV auth setting with no username but with a password, skipping authentication"
);
client
}
};
let resp = client.body(body).send().await?.error_for_status();
Ok(resp?)
}
}
async fn try_upload_entry(
client: WebDavClient,
store: Arc<RwLock<RecordingStore>>,
entry_name: String,
file_kind: FileKind,
shutdown_token: CancellationToken,
) -> Option<()> {
let read_lock = store.read().await;
let entry_idx = read_lock.entry_for_name(&entry_name)?.0;
let file = match file_kind {
FileKind::Analysis => read_lock.open_entry_analysis(entry_idx).await,
FileKind::Qmdl => read_lock.open_entry_qmdl(entry_idx).await,
};
drop(read_lock);
let Ok(file) = file.map_err(|err| {
warn!(
"Unable to open entry: {} {} file: {:?}",
entry_name, file_kind, err
)
}) else {
return None;
};
let file_name = format!("{}{}", entry_name, file_kind.as_extension());
let res = select! {
_ = shutdown_token.cancelled() => {
warn!(
"Cancelling upload for entry {} {} file: received shutdown signal",
entry_name, file_kind
);
return None;
},
res = client.try_upload_file(file, &file_name) => res,
};
match res {
Ok(_) => {
info!("Uploaded {} file for entry {}", file_kind, entry_name);
Some(())
}
Err(err) => {
warn!(
"Failed to upload {} file for entry {}: {:?}",
file_kind, entry_name, err
);
None
}
}
}
pub fn run_webdav_upload_worker(
task_tracker: &TaskTracker,
shutdown_token: CancellationToken,
qmdl_store_lock: Arc<RwLock<RecordingStore>>,
config: WebdavUploadWorkerConfig,
) {
task_tracker.spawn(async move {
let mut interval = time::interval(config.poll_interval);
interval.set_missed_tick_behavior(time::MissedTickBehavior::Skip);
let webdav_client = match WebDavClient::new(
config.url,
config.username,
config.password,
config.timeout,
) {
Ok(client) => client,
Err(err) => {
warn!("Unable to create WebDAV client: {:?}", err);
return;
}
};
loop {
select! {
_ = shutdown_token.cancelled() => break,
_ = interval.tick() => {
loop {
let Some(unuploaded_entry) = qmdl_store_lock
.read()
.await
.get_next_unuploaded_entry(config.min_age) else {
break;
};
let (Some(()), Some(())) = join!(
try_upload_entry(
webdav_client.clone(),
qmdl_store_lock.clone(),
unuploaded_entry.clone(),
FileKind::Qmdl,
shutdown_token.clone(),
),
try_upload_entry(
webdav_client.clone(),
qmdl_store_lock.clone(),
unuploaded_entry.clone(),
FileKind::Analysis,
shutdown_token.clone()
),
) else {
break;
};
if config.delete_on_upload {
match qmdl_store_lock.write().await.delete_entry(&unuploaded_entry).await {
Ok(_) => info!("Successfully deleted entry: {} after upload to WebDAV", unuploaded_entry),
Err(err) => warn!("Unable to delete entry: {} after upload to WebDAV: {}", unuploaded_entry, err),
}
} else {
match qmdl_store_lock.write().await.mark_entry_as_uploaded(&unuploaded_entry, rayhunter::clock::get_adjusted_now()).await {
Ok(_) => info!("Successfully marked entry: {} as uploaded", unuploaded_entry),
Err(err) => warn!("Unable to mark entry: {} as uploaded: {}", unuploaded_entry, err),
}
}
}
}
}
}
});
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
Router,
body::Bytes,
extract::{Path as AxumPath, State},
http::{HeaderMap, StatusCode},
routing::put,
};
use tempfile::Builder;
use tokio::io::AsyncWriteExt;
use tokio::net::TcpListener;
use tokio::sync::Mutex;
#[derive(Clone, Debug)]
struct RecordedPut {
path: String,
auth: Option<String>,
body: Vec<u8>,
}
async fn capture_put(
State(state): State<Arc<Mutex<Vec<RecordedPut>>>>,
AxumPath(path): AxumPath<String>,
headers: HeaderMap,
body: Bytes,
) -> StatusCode {
let auth = headers
.get("authorization")
.and_then(|v| v.to_str().ok())
.map(String::from);
state.lock().await.push(RecordedPut {
path,
auth,
body: body.to_vec(),
});
StatusCode::CREATED
}
async fn setup_webdav_server() -> (Arc<Mutex<Vec<RecordedPut>>>, String) {
crate::crypto_provider::install_default();
let state = Arc::new(Mutex::new(Vec::new()));
let app = Router::new()
.route("/{*path}", put(capture_put))
.with_state(state.clone());
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let url = format!("http://{}/dav", addr);
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
tokio::time::sleep(Duration::from_millis(100)).await;
(state, url)
}
async fn cleanup_worker(shutdown: CancellationToken, tracker: TaskTracker) {
shutdown.cancel();
tracker.close();
tracker.wait().await;
}
async fn make_store_with_closed_entry(
dir: &std::path::Path,
) -> (Arc<RwLock<RecordingStore>>, String) {
let mut store = RecordingStore::create(dir).await.unwrap();
let (mut qmdl_file, mut analysis_file) = store.new_entry().await.unwrap();
qmdl_file.write_all(b"fake qmdl payload").await.unwrap();
qmdl_file.flush().await.unwrap();
analysis_file
.write_all(b"fake ndjson payload")
.await
.unwrap();
analysis_file.flush().await.unwrap();
let entry_index = store.current_entry.unwrap();
let name = store.manifest.entries[entry_index].name.clone();
store.update_entry_qmdl_size(entry_index, 17).await.unwrap();
store.close_current_entry().await.unwrap();
(Arc::new(RwLock::new(store)), name)
}
#[tokio::test]
async fn test_webdav_upload_worker_uploads_entry() {
let (captured, url) = setup_webdav_server().await;
let dir = Builder::new().prefix("webdav_test").tempdir().unwrap();
let (store, entry_name) = make_store_with_closed_entry(dir.path()).await;
let shutdown = CancellationToken::new();
let tracker = TaskTracker::new();
let config = WebdavUploadWorkerConfig {
poll_interval: Duration::from_millis(50),
min_age: TimeDelta::seconds(-1),
url,
username: Some("user".to_string()),
password: Some("password".to_string()),
timeout: Duration::from_secs(1),
delete_on_upload: false,
};
run_webdav_upload_worker(&tracker, shutdown.clone(), store.clone(), config);
tokio::time::sleep(Duration::from_millis(500)).await;
cleanup_worker(shutdown, tracker).await;
let recorded = captured.lock().await;
assert_eq!(recorded.len(), 2);
let paths: Vec<&str> = recorded.iter().map(|r| r.path.as_str()).collect();
let qmdl_path = format!("dav/{}.qmdl", entry_name);
let ndjson_path = format!("dav/{}.ndjson", entry_name);
assert!(paths.contains(&qmdl_path.as_str()));
assert!(paths.contains(&ndjson_path.as_str()));
for put in recorded.iter() {
assert_eq!(put.auth.as_deref(), Some("Basic dXNlcjpwYXNzd29yZA=="));
}
let qmdl_body = recorded
.iter()
.find(|r| r.path == qmdl_path)
.unwrap()
.body
.clone();
let ndjson_body = recorded
.iter()
.find(|r| r.path == ndjson_path)
.unwrap()
.body
.clone();
drop(recorded);
assert_eq!(qmdl_body, b"fake qmdl payload");
assert_eq!(ndjson_body, b"fake ndjson payload");
let store_read = store.read().await;
let (_, entry) = store_read.entry_for_name(&entry_name).unwrap();
assert!(entry.upload_time.is_some());
}
#[tokio::test]
async fn test_webdav_upload_worker_deletes_when_configured() {
let (captured, url) = setup_webdav_server().await;
let dir = Builder::new().prefix("webdav_test").tempdir().unwrap();
let (store, entry_name) = make_store_with_closed_entry(dir.path()).await;
let shutdown = CancellationToken::new();
let tracker = TaskTracker::new();
let config = WebdavUploadWorkerConfig {
poll_interval: Duration::from_millis(50),
min_age: TimeDelta::seconds(-1),
url,
username: None,
password: None,
timeout: Duration::from_secs(1),
delete_on_upload: true,
};
run_webdav_upload_worker(&tracker, shutdown.clone(), store.clone(), config);
tokio::time::sleep(Duration::from_millis(500)).await;
cleanup_worker(shutdown, tracker).await;
assert_eq!(captured.lock().await.len(), 2);
let store_read = store.read().await;
assert!(store_read.entry_for_name(&entry_name).is_none());
}
#[tokio::test]
async fn test_webdav_upload_worker_respects_min_age() {
let (captured, url) = setup_webdav_server().await;
let dir = Builder::new().prefix("webdav_test").tempdir().unwrap();
let (store, entry_name) = make_store_with_closed_entry(dir.path()).await;
let shutdown = CancellationToken::new();
let tracker = TaskTracker::new();
let config = WebdavUploadWorkerConfig {
poll_interval: Duration::from_millis(50),
min_age: TimeDelta::seconds(3600),
url,
username: None,
password: None,
timeout: Duration::from_secs(1),
delete_on_upload: false,
};
run_webdav_upload_worker(&tracker, shutdown.clone(), store.clone(), config);
tokio::time::sleep(Duration::from_millis(500)).await;
cleanup_worker(shutdown, tracker).await;
assert!(captured.lock().await.is_empty());
let store_read = store.read().await;
let (_, entry) = store_read.entry_for_name(&entry_name).unwrap();
assert!(entry.upload_time.is_none());
}
}

21
daemon/web/.gitignore vendored Normal file
View File

@@ -0,0 +1,21 @@
node_modules
# Output
.output
.vercel
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

1
daemon/web/.npmrc Normal file
View File

@@ -0,0 +1 @@
engine-strict=true

View File

@@ -0,0 +1,7 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock
# Static Assets
static/pico.min.css

15
daemon/web/.prettierrc Normal file
View File

@@ -0,0 +1,15 @@
{
"singleQuote": true,
"tabWidth": 4,
"trailingComma": "es5",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte"],
"overrides": [
{
"files": "*.svelte",
"options": {
"parser": "svelte"
}
}
]
}

View File

@@ -0,0 +1,58 @@
import prettier from 'eslint-config-prettier';
import js from '@eslint/js';
import svelte from 'eslint-plugin-svelte';
import globals from 'globals';
import ts from 'typescript-eslint';
export default ts.config(
{
ignores: ['build/', '.svelte-kit/**', 'dist/'],
},
js.configs.recommended,
...ts.configs.recommended,
...svelte.configs['flat/recommended'],
prettier,
...svelte.configs['flat/prettier'],
{
languageOptions: {
globals: {
...globals.browser,
...globals.node,
},
},
},
{
files: ['**/*.svelte', '**/*.svelte.ts', '**/*.svelte.js'],
languageOptions: {
parserOptions: {
parser: ts.parser,
},
},
},
{
rules: {
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
],
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/naming-convention': [
'error',
{
selector: 'function',
format: ['snake_case'],
},
{
selector: 'method',
format: ['snake_case'],
},
],
// these rules should eventually be enabled, just disabled them to
// make dependency upgrades easier.
'svelte/prefer-svelte-reactivity': 'off',
'svelte/require-each-key': 'off',
'svelte/no-navigation-without-resolve': 'off',
},
}
);

3612
daemon/web/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
daemon/web/package.json Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "web",
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build && gzip -9 ./build/index.html",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"test:unit": "vitest",
"test": "npm run test:unit -- --run",
"format": "prettier --write .",
"lint": "prettier --check . && eslint .",
"fix": "eslint --fix ."
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@sveltejs/adapter-auto": "^7.0.1",
"@sveltejs/adapter-static": "^3.0.5",
"@sveltejs/kit": "^2.58.0",
"@sveltejs/vite-plugin-svelte": "^7.0.0",
"@tailwindcss/vite": "^4.2.2",
"@types/eslint": "^9.6.0",
"@types/node": "^25.6.0",
"eslint": "^10.2.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-svelte": "^3.17.1",
"globals": "^17.5.0",
"prettier": "^3.8.3",
"prettier-plugin-svelte": "^3.5.1",
"svelte": "^5.55.5",
"svelte-check": "^4.4.6",
"tailwindcss": "^4.2.2",
"typescript": "^6.0.3",
"typescript-eslint": "^8.59.0",
"vite": "^8.0.10",
"vitest": "^4.1.5"
}
}

16
daemon/web/src/app.css Normal file
View File

@@ -0,0 +1,16 @@
@import 'tailwindcss';
@theme {
--color-rayhunter-blue: #4e4eb1;
--color-rayhunter-dark-blue: #3f3da0;
--color-rayhunter-green: #94ea18;
}
/* v4 dropped the v3 preflight rule that set `cursor: pointer` on buttons.
* Restore it so enabled buttons get the pointer cursor. */
@layer base {
button:not(:disabled),
[role='button']:not(:disabled) {
cursor: pointer;
}
}

13
daemon/web/src/app.d.ts vendored Normal file
View File

@@ -0,0 +1,13 @@
// See https://svelte.dev/docs/kit/types#app
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

12
daemon/web/src/app.html Normal file
View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover" style="width: 100%">
<div style="display: contents" class="m-4 xl:m-8">%sveltekit.body%</div>
</body>
</html>

View File

@@ -0,0 +1,24 @@
export class ActionError extends Error {
// The number of this an identical error has happened.
// This is shown as a number next to the error in the UI.
times = $state(1);
constructor(message: string, cause: Error) {
super(message);
this.cause = cause;
}
}
export const action_errors: ActionError[] = $state([]);
export function add_error(e: Error, msg: string): void {
for (const existing of action_errors) {
if (existing.message === msg) {
existing.times += 1;
return;
}
}
const action_error = new ActionError(msg, e);
action_errors.unshift(action_error);
console.log(action_errors.length);
}

View File

@@ -0,0 +1,66 @@
import { describe, it, expect } from 'vitest';
import { AnalysisRowType, parse_finished_report } from './analysis.svelte';
import { type NewlineDeliminatedJson } from './ndjson';
const SAMPLE_V2_REPORT_NDJSON: NewlineDeliminatedJson = [
{
analyzers: [
{
name: 'Analyzer 1',
description: 'A first analyzer',
version: 2,
},
{
name: 'Analyzer 2',
description: 'A second analyzer',
version: 2,
},
],
report_version: 2,
},
{
skipped_message_reason: 'The reason why the message was skipped',
},
{
packet_timestamp: '2024-08-19T03:33:54.318Z',
events: [
null,
{
event_type: 'Low',
message: 'Something nasty happened',
},
],
},
];
describe('analysis report parsing', () => {
it('parses v2 example analysis', () => {
const report = parse_finished_report(SAMPLE_V2_REPORT_NDJSON);
expect(report.metadata.report_version).toEqual(2);
expect(report.metadata.analyzers).toEqual([
{
name: 'Analyzer 1',
description: 'A first analyzer',
version: 2,
},
{
name: 'Analyzer 2',
description: 'A second analyzer',
version: 2,
},
]);
expect(report.rows).toHaveLength(2);
expect(report.rows[0].type).toBe(AnalysisRowType.Skipped);
if (report.rows[1].type === AnalysisRowType.Analysis) {
const row = report.rows[1];
expect(row.events).toHaveLength(2);
expect(row.events[0]).toBeNull();
const event = row.events[1];
const expected_timestamp = new Date('2024-08-19T03:33:54.318Z');
expect(row.packet_timestamp.getTime()).toEqual(expected_timestamp.getTime());
expect(event!.event_type).toEqual('Low');
} else {
throw 'wrong row type';
}
});
});

View File

@@ -0,0 +1,138 @@
import { parse_ndjson, type NewlineDeliminatedJson } from './ndjson';
import { req } from './utils.svelte';
export type AnalysisReport = {
metadata: ReportMetadata;
rows: AnalysisRow[];
statistics: ReportStatistics;
};
export type ReportStatistics = {
num_warnings: number;
num_informational_logs: number;
num_skipped_packets: number;
};
export class ReportMetadata {
public analyzers: AnalyzerMetadata[];
public rayhunter: RayhunterMetadata;
public report_version: number;
constructor(ndjson: any) {
this.analyzers = ndjson.analyzers;
this.rayhunter = ndjson.rayhunter;
this.report_version = ndjson.report_version || 2; // Default to v2
}
}
export type RayhunterMetadata = {
rayhunter_version: string;
system_os: string;
arch: string;
};
export type AnalyzerMetadata = {
name: string;
description: string;
version: number;
};
export type AnalysisRow = SkippedPacket | PacketAnalysis;
export enum AnalysisRowType {
Skipped,
Analysis,
}
export type SkippedPacket = {
type: AnalysisRowType.Skipped;
reason: string;
};
export type PacketAnalysis = {
type: AnalysisRowType.Analysis;
packet_timestamp: Date;
events: Event[];
};
export type EventType = 'Informational' | 'Low' | 'Medium' | 'High';
export type Event = {
event_type: EventType;
message: string;
} | null;
function get_event(event_json: any): Event {
if (!['Informational', 'Low', 'Medium', 'High'].includes(event_json.event_type)) {
throw `Invalid/unhandled event type: ${event_json.event_type}`;
}
return event_json;
}
function get_rows(row_jsons: any[]): AnalysisRow[] {
const rows: AnalysisRow[] = [];
for (const row_json of row_jsons) {
if (row_json.skipped_message_reason) {
rows.push({
type: AnalysisRowType.Skipped,
reason: row_json.skipped_message_reason,
});
} else {
const events: Event[] = row_json.events.map((event_json: any): Event | null => {
if (event_json === null) {
return null;
} else {
return get_event(event_json);
}
});
rows.push({
type: AnalysisRowType.Analysis,
packet_timestamp: new Date(row_json.packet_timestamp),
events,
});
}
}
return rows;
}
function get_report_stats(rows: AnalysisRow[]): ReportStatistics {
let num_warnings = 0;
let num_informational_logs = 0;
let num_skipped_packets = 0;
for (const row of rows) {
if (row.type === AnalysisRowType.Skipped) {
num_skipped_packets++;
} else {
for (const event of row.events) {
if (event !== null) {
if (event.event_type === 'Informational') {
num_informational_logs++;
} else {
num_warnings++;
}
}
}
}
}
return {
num_warnings,
num_informational_logs,
num_skipped_packets,
};
}
export function parse_finished_report(report_json: NewlineDeliminatedJson): AnalysisReport {
const metadata = new ReportMetadata(report_json[0]);
const rows = get_rows(report_json.slice(1));
const statistics = get_report_stats(rows);
return {
statistics,
metadata,
rows,
};
}
export async function get_report(name: string): Promise<AnalysisReport> {
const report_json = parse_ndjson(await req('GET', `/api/analysis-report/${name}`));
return parse_finished_report(report_json);
}

View File

@@ -0,0 +1,62 @@
import { get_report, type AnalysisReport } from './analysis.svelte';
import { req } from './utils.svelte';
export enum AnalysisStatus {
// rayhunter is currently analyzing this entry (note that this is distinct
// from the currently-recording entry)
Running,
// this entry is queued to be analyzed
Queued,
// analysis is finished, and the new report can be accessed
Finished,
}
type AnalysisStatusJson = {
running: string | null;
queued: string[];
finished: string[];
};
export type AnalysisResult = {
name: string;
status: AnalysisStatus;
};
export class AnalysisManager {
public status: Map<string, AnalysisStatus> = $state(new Map());
public reports: Map<string, AnalysisReport | string> = $state(new Map());
public set_queued_status(name: string) {
this.status.set(name, AnalysisStatus.Queued);
this.reports.delete(name);
}
public async update() {
const status: AnalysisStatusJson = JSON.parse(await req('GET', '/api/analysis'));
if (status.running) {
this.status.set(status.running, AnalysisStatus.Running);
}
for (const entry of status.queued) {
this.status.set(entry, AnalysisStatus.Queued);
}
for (const entry of status.finished) {
// if entry was already finished, nothing to do
if (this.status.get(entry) === AnalysisStatus.Finished) {
continue;
}
this.status.set(entry, AnalysisStatus.Finished);
// fetch the analysis report
this.reports.delete(entry);
get_report(entry)
.then((report) => {
this.reports.set(entry, report);
})
.catch((err) => {
this.reports.set(entry, `Failed to get analysis: ${err}`);
});
}
}
}

View File

@@ -0,0 +1,100 @@
<script lang="ts">
import { action_errors } from '../action_errors.svelte';
let pos = $state(0);
let current_error = $derived(action_errors[pos]);
function prev_error() {
if (pos > 0) pos -= 1;
else pos = action_errors.length - 1;
}
function next_error() {
if (pos + 1 < action_errors.length) pos += 1;
else pos = 0;
}
function clear_errors() {
pos = 0;
action_errors.length = 0;
}
</script>
{#if action_errors.length > 0}
<div
class="bg-red-100 border-red-100 drop-shadow-sm p-4 flex flex-col gap-2
border rounded-md flex-1 justify-between fixed z-10 right-3 bottom-3 ml-3"
>
<div class="flex flex-row justify-between">
<span class="text-xl font-bold mb-2 mr-5 flex flex-row items-center gap-1 text-red-600">
<svg
class="w-6 h-6 text-red-600"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="currentColor"
viewBox="0 0 24 24"
>
<path
fill-rule="evenodd"
d="M2 12C2 6.477 6.477 2 12 2s10 4.477 10 10-4.477 10-10 10S2 17.523 2 12Zm11-4a1 1 0 1 0-2 0v5a1 1 0 1 0 2 0V8Zm-1 7a1 1 0 1 0 0 2h.01a1 1 0 1 0 0-2H12Z"
clip-rule="evenodd"
/>
</svg>
Error Completing Action {current_error.times > 1 ? `x${current_error.times}` : ''}
</span>
<div class="flex items-center mb-2">
{#if action_errors.length > 1}
<span>{pos + 1}/{action_errors.length}</span>
<button title="previous error" aria-label="previous error" onclick={prev_error}>
<svg
aria-hidden="true"
width="24"
height="24"
fill="none"
viewBox="0 0 24 24"
>
<path
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="m 15.499979,19.499979 -6.9999997,-7 6.9999997,-6.9999997"
/>
</svg>
</button>
<button title="next error" aria-label="next error" onclick={next_error}>
<svg
aria-hidden="true"
width="24"
height="24"
fill="none"
viewBox="0 0 24 24"
>
<path
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="m 8.5000207,5.4999793 7.0000003,6.9999997 -7.0000003,7"
/>
</svg>
</button>
{/if}
<button title="clear errors" aria-label="clear errors" onclick={clear_errors}>
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path
d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"
/>
</svg>
</button>
</div>
</div>
<span>{current_error.message}</span>
{#if current_error.cause}
<details>
<summary>Details</summary>
<code>{current_error.cause}</code>
</details>
{/if}
</div>
{/if}

View File

@@ -0,0 +1,92 @@
<script lang="ts">
import { AnalysisStatus } from '$lib/analysisManager.svelte';
import type { ManifestEntry } from '$lib/manifest.svelte';
let {
entry,
onclick,
analysis_visible,
}: {
entry: ManifestEntry;
onclick: () => void;
analysis_visible: boolean;
} = $props();
let summary = $derived.by(() => {
if (entry.analysis_status === AnalysisStatus.Queued) {
return 'Queued...';
} else if (entry.analysis_status === AnalysisStatus.Running) {
return 'Running...';
} else if (entry.analysis_status === AnalysisStatus.Finished) {
if (entry.analysis_report === undefined) {
return 'Loading...';
} else if (typeof entry.analysis_report === 'string') {
return entry.analysis_report;
} else {
return `${entry.analysis_report.statistics.num_warnings} warnings`;
}
} else {
return 'Loading...';
}
});
let ready = $derived.by(() => {
let finished = entry.analysis_status === AnalysisStatus.Finished;
let report_available = entry.analysis_report !== undefined;
return finished && report_available;
});
let button_class = $derived.by(() => {
if (!ready) {
return 'text-gray-700';
} else if ((entry.get_num_warnings() || 0) < 1) {
return 'text-green-700 border-green-500 bg-green-200 text-blue-600 border rounded-full px-2';
} else {
return 'text-red-700 border-red-500 bg-red-200 text-blue-600 border rounded-full px-2';
}
});
</script>
<button class="flex flex-row gap-1 lg:gap-2" disabled={!ready} {onclick}>
<span class="flex flex-row items-center gap-1">
{#if entry.analysis_status === AnalysisStatus.Queued || entry.analysis_status === AnalysisStatus.Running || (entry.analysis_status === AnalysisStatus.Finished && entry.analysis_report === undefined)}
<svg
class="animate-spin h-4 w-4 text-blue-600"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
{/if}
<span class={button_class}>{summary}</span>
</span>
<svg
class="w-6 h-6 text-gray-800 transition-transform {analysis_visible ? 'rotate-180' : ''}"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="none"
viewBox="0 0 24 24"
>
<path
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="m19 9-7 7-7-7"
/>
</svg>
</button>

View File

@@ -0,0 +1,103 @@
<script lang="ts">
import { AnalysisRowType, type AnalysisReport } from '$lib/analysis.svelte';
let {
report,
}: {
report: AnalysisReport;
} = $props();
const date_formatter = new Intl.DateTimeFormat(undefined, {
timeStyle: 'long',
dateStyle: 'short',
});
const analyzers = $derived(report.metadata.analyzers);
const skipped_messages: Map<string, number> = $derived.by(() => {
let map = new Map();
for (const row of report.rows) {
if (row.type === AnalysisRowType.Skipped) {
let count = map.get(row.reason);
if (count === undefined) {
count = 0;
}
map.set(row.reason, count + 1);
}
}
return map;
});
</script>
<div>
<p class="text-lg underline">Warnings and Informational Logs</p>
{#if report.statistics.num_warnings === 0 && report.statistics.num_informational_logs === 0}
<p>Nothing to show!</p>
{:else}
<div class="overflow-x-auto">
<table class="table-auto text-left">
<thead class="p-2">
<tr class="bg-gray-300">
<th class="p-2">Timestamp</th>
<th class="p-2">Heuristic</th>
<th class="p-2">Warning</th>
<th class="p-2">Severity</th>
</tr>
</thead>
<tbody>
{#each report.rows as row}
{#if row.type === AnalysisRowType.Analysis}
{@const parsed_date = new Date(row.packet_timestamp)}
{#each row.events as event, analyzerIndex}
{#if event !== null}
{@const analyzer = analyzers[analyzerIndex]}
{@const event_type_class = {
Informational: '',
Low: 'bg-yellow-200',
Medium: 'bg-orange-400',
High: 'bg-red-600',
}[event.event_type]}
<tr class="even:bg-gray-200 odd:bg-white">
<td class="p-2">{date_formatter.format(parsed_date)}</td>
<td class="p-2">{analyzer.name} v{analyzer.version}</td>
<td class="p-2">{event.message}</td>
<td class="p-2 {event_type_class} text-center"
>{event.event_type}</td
>
</tr>
{/if}
{/each}
{/if}
{/each}
</tbody>
</table>
</div>
{/if}
</div>
{#if report.statistics.num_skipped_packets > 0}
<div>
<p class="text-lg underline">Unparsed Messages</p>
<p>
These are due to a limitation or bug in Rayhunter's parser, and aren't usually a
problem. We'll not accept bug reports about them unless something else is going wrong
(such as false-positives or definite false-negatives)
</p>
<div class="overflow-x-auto">
<table class="table-auto text-left">
<thead class="p-2">
<tr class="bg-gray-300">
<th scope="col" class="p-2">Total Msgs Affected</th>
<th scope="col">Reason/Error</th>
</tr>
</thead>
<tbody>
{#each skipped_messages.entries() as [message, count]}
<tr class="even:bg-gray-200 odd:bg-white">
<td class="text-center">{count}</td>
<td>{message}</td>
</tr>
{/each}
</tbody>
</table>
</div>
</div>
{/if}

View File

@@ -0,0 +1,69 @@
<script lang="ts">
import { type ReportMetadata } from '$lib/analysis.svelte';
import type { ManifestEntry } from '$lib/manifest.svelte';
import { AnalysisManager } from '$lib/analysisManager.svelte';
import AnalysisTable from './AnalysisTable.svelte';
import ReAnalyzeButton from './ReAnalyzeButton.svelte';
let {
entry,
manager,
current,
}: {
entry: ManifestEntry;
manager: AnalysisManager;
current: boolean;
} = $props();
</script>
<div class="container mt-2">
{#if entry.analysis_report === undefined}
<p>Report unavailable, try refreshing.</p>
{:else if typeof entry.analysis_report === 'string'}
<p>Error getting analysis report: {entry.analysis_report}</p>
{:else}
{@const metadata: ReportMetadata = entry.analysis_report.metadata}
{@const numWarnings: number = entry.get_num_warnings() || 0}
<div class="flex flex-col gap-2">
{#if !!numWarnings || !current}
<div class="flex flex-row justify-between items-center">
{#if !!numWarnings}
<div
class="text-red-700 border-red-500 border rounded-lg text-blue-600 px-2 py-1 mr-12"
>
Your Rayhunter device raised {`${numWarnings}`} warning{`${
numWarnings > 1 ? 's' : ''
}`}!
<a
href="https://efforg.github.io/rayhunter/faq.html#red"
class="text-blue-600 underline">Read the FAQ</a
> to learn what you can do about it
</div>
{/if}
{#if !current}
<ReAnalyzeButton {entry} {manager} />
{/if}
</div>
{/if}
{#if entry.analysis_report.rows.length > 0}
<AnalysisTable report={entry.analysis_report} />
{:else}
<p>No warnings to display!</p>
{/if}
{#if metadata !== undefined && metadata.rayhunter !== undefined}
<div>
<p class="text-lg underline">Metadata</p>
<p>Analysis by Rayhunter version {metadata.rayhunter.rayhunter_version}</p>
<p><b>Device system OS:</b> {metadata.rayhunter.system_os}</p>
</div>
<div>
<p class="text-lg underline">Analyzers</p>
{#each metadata.analyzers as analyzer}
<p><b>{analyzer.name}:</b> {analyzer.description}</p>
{/each}
</div>
{:else}
<p>N/A (analysis generated by an older version of rayhunter)</p>
{/if}
</div>
{/if}
</div>

View File

@@ -0,0 +1,100 @@
<script lang="ts">
import { user_action_req } from '$lib/utils.svelte';
let {
url,
method = 'POST',
label,
loadingLabel,
disabled = false,
variant = 'blue',
icon,
onclick,
ariaLabel,
errorMessage,
jsonBody,
}: {
url: string;
method?: string;
label: string;
loadingLabel?: string;
disabled?: boolean;
variant?: 'blue' | 'red' | 'green';
icon?: any; // Svelte snippet
onclick?: () => void | Promise<void>;
ariaLabel?: string;
errorMessage?: string;
jsonBody?: unknown;
} = $props();
let is_requesting = $state(false);
let is_disabled = $derived(disabled || is_requesting);
const variantClasses = {
blue: {
enabled: 'bg-blue-500 hover:bg-blue-700',
disabled: 'bg-blue-500 opacity-50 cursor-not-allowed',
},
red: {
enabled: 'bg-red-500 hover:bg-red-700',
disabled: 'bg-red-500 opacity-50 cursor-not-allowed',
},
green: {
enabled: 'bg-green-500 hover:bg-green-700',
disabled: 'bg-green-500 opacity-50 cursor-not-allowed',
},
};
async function handle_click() {
if (is_disabled) return;
is_requesting = true;
try {
await user_action_req(
method,
url,
errorMessage ? errorMessage : 'Error performing action',
jsonBody
);
if (onclick) {
await onclick();
}
} catch (err) {
console.error(`Failed to ${method} ${url}:`, err);
alert(`Request failed. Please try again.`);
} finally {
is_requesting = false;
}
}
let buttonClasses = $derived(
is_disabled ? variantClasses[variant].disabled : variantClasses[variant].enabled
);
</script>
<button
class="text-white font-bold py-2 px-2 sm:px-4 rounded-md flex flex-row items-center gap-1 {buttonClasses}"
onclick={handle_click}
disabled={is_disabled}
aria-label={ariaLabel || label}
>
<span>{is_requesting && loadingLabel ? loadingLabel : label}</span>
{#if is_requesting}
<svg
class="w-4 h-4 text-white animate-spin"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
{:else if icon}
{@render icon()}
{/if}
</button>

View File

@@ -0,0 +1,121 @@
<script lang="ts">
import { get_daemon_time } from '$lib/utils.svelte';
import ApiRequestButton from './ApiRequestButton.svelte';
let show_alert = $state(false);
let device_system_time = $state('');
let device_adjusted_time = $state('');
let browser_time = $state('');
let has_offset = $state(false);
let computed_offset = $state(0);
let dismissed = $state(false);
let check_completed = $state(false);
const DRIFT_THRESHOLD_SECONDS = 30;
function format_time(date: Date): string {
return date.toLocaleString();
}
async function check_clock_drift() {
if (check_completed) return;
try {
const daemon_time_response = await get_daemon_time();
const browser_now = new Date();
const daemon_system_ms = new Date(daemon_time_response.system_time).getTime();
const device_adjusted_ms = new Date(daemon_time_response.adjusted_time).getTime();
const drift_seconds = Math.round((browser_now.getTime() - device_adjusted_ms) / 1000);
if (Math.abs(drift_seconds) > DRIFT_THRESHOLD_SECONDS && !dismissed) {
device_system_time = format_time(new Date(daemon_time_response.system_time));
device_adjusted_time = format_time(new Date(daemon_time_response.adjusted_time));
browser_time = format_time(browser_now);
has_offset = daemon_time_response.offset_seconds !== 0;
// Calculate offset needed: browser_time - daemon_system_time
computed_offset = Math.round((browser_now.getTime() - daemon_system_ms) / 1000);
show_alert = true;
}
} catch (err) {
console.error('Failed to check clock drift:', err);
}
check_completed = true;
}
function dismiss() {
show_alert = false;
dismissed = true;
}
// Check clock drift on component mount
$effect(() => {
check_clock_drift();
});
</script>
{#if show_alert}
<div
class="bg-yellow-100 border-yellow-400 drop-shadow-sm p-4 flex flex-col gap-2 border rounded-md"
>
<span class="text-xl font-bold flex flex-row items-center gap-2 text-yellow-700">
<svg
class="w-6 h-6 text-yellow-600"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="currentColor"
viewBox="0 0 24 24"
>
<path
fill-rule="evenodd"
d="M2 12C2 6.477 6.477 2 12 2s10 4.477 10 10-4.477 10-10 10S2 17.523 2 12Zm11-4a1 1 0 1 0-2 0v4a1 1 0 0 0 .293.707l3 3a1 1 0 0 0 1.414-1.414L13 11.586V8Z"
clip-rule="evenodd"
/>
</svg>
Clock Mismatch Detected
</span>
<p>
Rayhunter's clock doesn't match your browser's, and may be incorrect. This can happen if
Rayhunter is unable to get the correct time from the internet. Consider synchronizing
your browser's clock with the button below, or using another SIM card for better
results.
</p>
<table class="w-fit">
<tbody>
<tr>
<td class="pr-2">Rayhunter clock (system):</td>
<td class="font-mono">{device_system_time}</td>
</tr>
{#if has_offset}
<tr>
<td class="pr-2">Rayhunter clock (adjusted):</td>
<td class="font-mono">{device_adjusted_time}</td>
</tr>
{/if}
<tr>
<td class="pr-2">Browser clock:</td>
<td class="font-mono">{browser_time}</td>
</tr>
</tbody>
</table>
<p>Copy browser clock to device?</p>
<div class="flex flex-row gap-2 justify-end">
<button
class="font-medium py-2 px-4 rounded-md border border-gray-400 hover:bg-yellow-200"
onclick={dismiss}
>
Dismiss
</button>
<ApiRequestButton
url="/api/time-offset"
label="Sync Clock"
loadingLabel="Syncing..."
variant="green"
jsonBody={{ offset_seconds: computed_offset }}
onclick={dismiss}
errorMessage="Error syncing clock"
/>
</div>
</div>
{/if}

View File

@@ -0,0 +1,716 @@
<script lang="ts">
import {
get_config,
set_config,
test_notification,
get_wifi_status,
scan_wifi_networks,
type Config,
type WifiStatus,
type WifiNetwork,
} from '../utils.svelte';
import Modal from './Modal.svelte';
let { shown = $bindable() }: { shown: boolean } = $props();
let config = $state<Config | null>(null);
let loading = $state(false);
let saving = $state(false);
let testingNotification = $state(false);
let message = $state('');
let messageType = $state<'success' | 'error' | null>(null);
let testMessage = $state('');
let testMessageType = $state<'success' | 'error' | null>(null);
let wifiStatus = $state<WifiStatus | null>(null);
let wifiStatusTimer = $state<ReturnType<typeof setInterval> | null>(null);
let scanning = $state(false);
let scanResults = $state<WifiNetwork[]>([]);
let dnsServersInput = $state('');
async function load_config() {
try {
loading = true;
config = await get_config();
dnsServersInput = config.dns_servers ? config.dns_servers.join(', ') : '';
message = '';
messageType = null;
poll_wifi_status();
} catch (error) {
message = `Failed to load config: ${error}`;
messageType = 'error';
} finally {
loading = false;
}
}
async function save_config() {
if (!config) return;
const trimmed = dnsServersInput.trim();
config.dns_servers =
trimmed.length > 0
? trimmed
.split(',')
.map((s) => s.trim())
.filter((s) => s.length > 0)
: null;
try {
saving = true;
await set_config(config);
message =
'Config saved successfully! Rayhunter is restarting now. Reload the page in a few seconds.';
messageType = 'success';
} catch (error) {
message = `Failed to save config: ${error}`;
messageType = 'error';
} finally {
saving = false;
}
}
async function poll_wifi_status() {
if (wifiStatusTimer) clearInterval(wifiStatusTimer);
try {
wifiStatus = await get_wifi_status();
} catch {
wifiStatus = null;
}
wifiStatusTimer = setInterval(async () => {
try {
wifiStatus = await get_wifi_status();
} catch {
wifiStatus = null;
}
}, 5000);
}
let scanError = $state('');
async function do_scan() {
scanning = true;
scanError = '';
try {
scanResults = await scan_wifi_networks();
} catch (error) {
scanResults = [];
scanError = `Scan failed: ${error}`;
} finally {
scanning = false;
}
}
function select_network(network: WifiNetwork) {
if (config) {
config.wifi_ssid = network.ssid;
config.wifi_password = '';
config.wifi_security =
network.security === 'WPA3' || network.security === 'WPA3 (transition)'
? 'sae'
: 'wpa_psk';
scanResults = [];
}
}
async function send_test_notification() {
try {
testingNotification = true;
testMessage = '';
testMessageType = null;
await test_notification();
testMessage = 'Test notification sent successfully!';
testMessageType = 'success';
} catch (error) {
testMessage = `${error}`;
testMessageType = 'error';
} finally {
testingNotification = false;
}
}
$effect(() => {
if (shown && !config) {
load_config();
}
if (!shown && wifiStatusTimer) {
clearInterval(wifiStatusTimer);
wifiStatusTimer = null;
}
return () => {
if (wifiStatusTimer) {
clearInterval(wifiStatusTimer);
wifiStatusTimer = null;
}
};
});
</script>
<Modal bind:shown title="Configuration">
<div class="p-2">
{#if loading}
<div class="text-center py-4">Loading config...</div>
{:else if config}
<form
class="space-y-4"
onsubmit={(e) => {
e.preventDefault();
save_config();
}}
>
<div>
<label for="ui_level" class="block text-sm font-medium text-gray-700 mb-1">
Device UI Level
</label>
<select
id="ui_level"
bind:value={config.ui_level}
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
>
<option value={0}>0 - Invisible mode</option>
<option value={1}>1 - Subtle mode (colored line)</option>
<option value={2}>2 - Demo mode (orca gif)</option>
<option value={3}>3 - EFF logo</option>
<option value={4}>4 - High visibility (full screen color)</option>
</select>
<p class="text-xs text-gray-500 mt-1">
Note: Rayhunter draws over the device's native UI, so some flickering is
expected
</p>
</div>
<div>
<label
for="key_input_mode"
class="block text-sm font-medium text-gray-700 mb-1"
>
Device Input Mode
</label>
<select
id="key_input_mode"
bind:value={config.key_input_mode}
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
>
<option value={0}>0 - Disable button control</option>
<option value={1}>1 - Double-tap power button to start new recording</option
>
</select>
</div>
<div class="space-y-3">
<div class="flex items-center">
<input
id="colorblind_mode"
type="checkbox"
bind:checked={config.colorblind_mode}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label for="colorblind_mode" class="ml-2 block text-sm text-gray-700">
Colorblind Mode
</label>
</div>
</div>
<div class="border-t border-gray-200 pt-4 mt-6 space-y-3">
<h3 class="text-lg font-semibold text-gray-800 mb-4">Notification Settings</h3>
<div>
<label for="ntfy_url" class="block text-sm font-medium text-gray-700 mb-1">
ntfy URL for Sending Notifications (if unset you will not receive
notifications)
</label>
<input
id="ntfy_url"
type="url"
bind:value={config.ntfy_url}
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
/>
<p class="text-xs text-gray-500 mt-1">
Test button below uses the saved configuration URL, not the input above
</p>
</div>
<div>
<button
type="button"
onclick={send_test_notification}
disabled={testingNotification}
class="bg-rayhunter-blue hover:bg-rayhunter-dark-blue disabled:opacity-50 disabled:cursor-not-allowed text-white font-bold py-2 px-4 rounded-md flex flex-row gap-1 items-center"
>
{#if testingNotification}
<div
class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"
></div>
Sending...
{:else}
<svg
class="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
></path>
</svg>
Send Test Notification
{/if}
</button>
{#if testMessage}
<div
class="mt-2 p-2 rounded-sm text-sm {testMessageType === 'error'
? 'bg-red-100 text-red-700'
: 'bg-green-100 text-green-700'}"
>
{testMessage}
</div>
{/if}
</div>
<div class="space-y-2">
<div class="block text-sm font-medium text-gray-700 mb-1">
Enabled Notification Types
</div>
<div class="flex items-center">
<input
type="checkbox"
id="enable_warning_notifications"
value="Warning"
bind:group={config.enabled_notifications}
/>
<label
for="enable_warning_notifications"
class="ml-2 block text-sm text-gray-700"
>
Warnings
</label>
</div>
<div class="flex items-center">
<input
type="checkbox"
id="enable_lowbattery_notifications"
value="LowBattery"
bind:group={config.enabled_notifications}
/>
<label
for="enable_lowbattery_notifications"
class="ml-2 block text-sm text-gray-700"
>
Low Battery
</label>
</div>
</div>
</div>
<div class="border-t border-gray-200 pt-4 mt-6 space-y-3">
<h3 class="text-lg font-semibold text-gray-800 mb-4">Storage Management</h3>
<div>
<label
for="min_space_to_start_recording_mb"
class="block text-sm font-medium text-gray-700 mb-1"
>
Minimum Space to Start Recording (MB)
</label>
<input
id="min_space_to_start_recording_mb"
type="number"
min="1"
bind:value={config.min_space_to_start_recording_mb}
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
/>
<p class="text-xs text-gray-500 mt-1">
Recording will not start if less than this amount of disk space is free
</p>
</div>
<div>
<label
for="min_space_to_continue_recording_mb"
class="block text-sm font-medium text-gray-700 mb-1"
>
Minimum Space to Continue Recording (MB)
</label>
<input
id="min_space_to_continue_recording_mb"
type="number"
min="1"
bind:value={config.min_space_to_continue_recording_mb}
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
/>
<p class="text-xs text-gray-500 mt-1">
Recording will stop automatically if disk space drops below this level
</p>
</div>
</div>
{#if config.device === 'orbic' || config.device === 'moxee' || config.device === 'tmobile' || config.device === 'wingtech'}
<div class="border-t border-gray-200 pt-4 mt-6 space-y-3">
<h3 class="text-lg font-semibold text-gray-800 mb-4">WiFi Client Mode</h3>
<p class="text-xs text-gray-500">
Connect the device to an existing WiFi network for internet access (e.g.
notifications, remote access). The hotspot AP stays running alongside
WiFi client mode.
</p>
<div class="flex items-center">
<input
id="wifi_enabled"
type="checkbox"
bind:checked={config.wifi_enabled}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label for="wifi_enabled" class="ml-2 block text-sm text-gray-700">
Enable WiFi
</label>
</div>
<p class="text-xs text-gray-500">
Unchecking stops WiFi without clearing saved credentials.
</p>
{#if wifiStatus && config.wifi_enabled}
{#if wifiStatus.state === 'connected'}
<p class="text-xs text-green-600">
Connected to "{wifiStatus.ssid}" ({wifiStatus.ip})
</p>
{:else if wifiStatus.state === 'connecting'}
<p class="text-xs text-amber-600">Connecting...</p>
{:else if wifiStatus.state === 'recovering'}
<p class="text-xs text-amber-600">Recovering connection...</p>
{:else if wifiStatus.state === 'dataPathDead'}
<p class="text-xs text-amber-600">
Data path stalled, attempting recovery...
</p>
{:else if wifiStatus.state === 'failed'}
<p class="text-xs text-red-600">
Failed: {wifiStatus.error}
</p>
{/if}
{/if}
<div>
<label
for="wifi_ssid"
class="block text-sm font-medium text-gray-700 mb-1"
>
WiFi Network Name (SSID)
</label>
<div class="flex gap-2">
<input
id="wifi_ssid"
type="text"
bind:value={config.wifi_ssid}
placeholder="MyWiFiNetwork"
class="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
/>
<button
type="button"
onclick={do_scan}
disabled={scanning}
class="px-3 py-2 text-sm bg-gray-100 hover:bg-gray-200 disabled:opacity-50 border border-gray-300 rounded-md"
>
{scanning ? 'Scanning...' : 'Scan'}
</button>
</div>
</div>
{#if scanError}
<p class="text-xs text-red-600">{scanError}</p>
{/if}
{#if scanResults.length > 0}
<div
class="border border-gray-200 rounded-md max-h-40 overflow-y-auto divide-y divide-gray-200"
>
{#each scanResults as network}
<button
type="button"
class="w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex justify-between"
onclick={() => select_network(network)}
>
<span>{network.ssid}</span>
<span class="text-gray-400"
>{network.signal_dbm} dBm &middot; {network.security}</span
>
</button>
{/each}
</div>
{/if}
{#if config.wifi_ssid}
<div>
<label
for="wifi_security"
class="block text-sm font-medium text-gray-700 mb-1"
>
Security Type
</label>
<select
id="wifi_security"
bind:value={config.wifi_security}
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
>
<option value="wpa_psk">WPA2 (WPA-PSK)</option>
<option value="sae">WPA3 (SAE)</option>
</select>
</div>
{/if}
<div>
<label
for="wifi_password"
class="block text-sm font-medium text-gray-700 mb-1"
>
WiFi Password
</label>
<input
id="wifi_password"
type="password"
bind:value={config.wifi_password}
placeholder="Enter password"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
/>
<p class="text-xs text-gray-500 mt-1">
Changing the network requires re-entering the password.
</p>
</div>
{#if config.wifi_ssid}
<div>
<label
for="dns_servers"
class="block text-sm font-medium text-gray-700 mb-1"
>
DNS Servers
</label>
<input
id="dns_servers"
type="text"
bind:value={dnsServersInput}
placeholder="9.9.9.9, 149.112.112.112"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
/>
<p class="text-xs text-gray-500 mt-1">
Comma-separated. Used when WiFi is active. Defaults to 9.9.9.9,
149.112.112.112 (Quad9).
</p>
</div>
{/if}
</div>
{/if}
<div class="border-t border-gray-200 pt-4 mt-6 space-y-3">
<h3 class="text-lg font-semibold text-gray-800 mb-4">Device Security</h3>
<div class="flex items-center">
<input
id="firewall_restrict_outbound"
type="checkbox"
bind:checked={config.firewall_restrict_outbound}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label
for="firewall_restrict_outbound"
class="ml-2 block text-sm text-gray-700"
>
Restrict outbound traffic
</label>
</div>
<p class="text-xs text-gray-500">
Only allows DNS, DHCP, and HTTPS (port 443) outbound. Blocks all other
outbound connections on every interface (WiFi and cellular). Loopback and
hotspot traffic are always allowed. Changes take effect immediately.
</p>
{#if config.firewall_restrict_outbound}
<div>
<label
for="firewall_allowed_ports"
class="block text-sm font-medium text-gray-700 mb-1"
>
Additional Allowed Ports
</label>
<input
id="firewall_allowed_ports"
type="text"
value={config.firewall_allowed_ports
? config.firewall_allowed_ports.join(', ')
: ''}
oninput={(e) => {
const val = (e.target as HTMLInputElement).value.trim();
config!.firewall_allowed_ports =
val.length > 0
? val
.split(',')
.map((s) => parseInt(s.trim()))
.filter((n) => !isNaN(n) && n >= 1 && n <= 65535)
: null;
}}
placeholder="22, 80"
class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-hidden focus:ring-2 focus:ring-rayhunter-blue"
/>
<p class="text-xs text-gray-500 mt-1">
Comma-separated TCP ports, e.g. 22, 80
</p>
</div>
{/if}
</div>
<div class="border-t border-gray-200 pt-4 mt-6">
<h3 class="text-lg font-semibold text-gray-800 mb-4">
Analyzer Heuristic Settings
</h3>
<div class="space-y-3">
<div class="flex items-center">
<input
id="imsi_requested"
type="checkbox"
bind:checked={config.analyzers.imsi_requested}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label for="imsi_requested" class="ml-2 block text-sm text-gray-700">
IMSI Requested Heuristic
</label>
</div>
<div class="flex items-center">
<input
id="connection_redirect_2g_downgrade"
type="checkbox"
bind:checked={config.analyzers.connection_redirect_2g_downgrade}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label
for="connection_redirect_2g_downgrade"
class="ml-2 block text-sm text-gray-700"
>
Connection Redirect 2G Downgrade Heuristic
</label>
</div>
<div class="flex items-center">
<input
id="lte_sib6_and_7_downgrade"
type="checkbox"
bind:checked={config.analyzers.lte_sib6_and_7_downgrade}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label
for="lte_sib6_and_7_downgrade"
class="ml-2 block text-sm text-gray-700"
>
LTE SIB6 and SIB7 Downgrade Heuristic
</label>
</div>
<div class="flex items-center">
<input
id="null_cipher"
type="checkbox"
bind:checked={config.analyzers.null_cipher}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label for="null_cipher" class="ml-2 block text-sm text-gray-700">
Null Cipher Heuristic
</label>
</div>
<div class="flex items-center">
<input
id="nas_null_cipher"
type="checkbox"
bind:checked={config.analyzers.nas_null_cipher}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label for="nas_null_cipher" class="ml-2 block text-sm text-gray-700">
NAS Null Cipher Heuristic
</label>
</div>
<div class="flex items-center">
<input
id="incomplete_sib"
type="checkbox"
bind:checked={config.analyzers.incomplete_sib}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label for="incomplete_sib" class="ml-2 block text-sm text-gray-700">
Incomplete SIB Heuristic
</label>
</div>
<div class="flex items-center">
<input
id="test_analyzer"
type="checkbox"
bind:checked={config.analyzers.test_analyzer}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label for="test_analyzer" class="ml-2 block text-sm text-gray-700">
Test Heuristic (noisy!)
</label>
</div>
<div class="flex items-center">
<input
id="diagnostic_analyzer"
type="checkbox"
bind:checked={config.analyzers.diagnostic_analyzer}
class="h-4 w-4 text-rayhunter-blue focus:ring-rayhunter-blue border-gray-300 rounded-sm"
/>
<label
for="diagnostic_analyzer"
class="ml-2 block text-sm text-gray-700"
>
Diagnostic Analyzer
</label>
</div>
</div>
</div>
<div class="flex gap-2 pt-4">
<button
type="submit"
disabled={saving}
class="bg-blue-500 hover:bg-blue-700 disabled:opacity-50 text-white font-bold py-2 px-4 rounded-md flex flex-row gap-1 items-center"
>
{#if saving}
<div
class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"
></div>
Saving...
{:else}
<svg
class="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M5 13l4 4L19 7"
></path>
</svg>
Apply and restart
{/if}
</button>
</div>
</form>
{#if message}
<div
class="mt-4 p-3 rounded-sm {messageType === 'error'
? 'bg-red-100 text-red-700'
: 'bg-green-100 text-green-700'}"
>
{message}
</div>
{/if}
{:else}
<div class="text-center py-4 text-red-600">
Failed to load configuration. Please try reloading the page.
</div>
{/if}
</div>
</Modal>

View File

@@ -0,0 +1,12 @@
<script lang="ts">
import DeleteButton from './DeleteButton.svelte';
</script>
<div class="flex flex-row justify-end gap-2">
<DeleteButton
text="Delete ALL Recordings"
prompt="Are you sure you want to delete ALL recordings?"
url="/api/delete-all-recordings"
name="all recodings"
/>
</div>

View File

@@ -0,0 +1,34 @@
<script lang="ts">
import { user_action_req } from '$lib/utils.svelte';
let {
text,
url,
prompt,
name,
}: {
text?: string;
url: string;
prompt: string;
name: string;
} = $props();
function confirm_delete() {
if (window.confirm(prompt)) {
user_action_req('POST', url, 'Unable to delete recording ' + name);
}
}
</script>
<button
class="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-2 sm:px-4 rounded-md flex flex-row"
onclick={confirm_delete}
aria-label="delete"
>
<p>{text}</p>
<svg style="width:24px;height:24px" viewBox="0 0 24 24">
<path
fill="white"
d="M19,4H15.5L14.5,3H9.5L8.5,4H5V6H19M6,19A2,2 0 0,0 8,21H16A2,2 0 0,0 18,19V7H6V19Z"
/>
</svg>
</button>

View File

@@ -0,0 +1,23 @@
<script lang="ts">
let {
url,
text,
full_button = false,
}: {
url: string;
text: string;
full_button?: boolean;
} = $props();
</script>
<a
href={url}
class="flex flex-row {full_button
? 'bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-2 sm:px-4 rounded-md'
: 'text-blue-600 underline'}"
>
{text}
<svg class="fill-current w-4 h-4 m-1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path d="M13 8V2H7v6H2l8 8 8-8h-5zM0 18h20v2H0v-2z" />
</svg>
</a>

View File

@@ -0,0 +1,28 @@
<script lang="ts">
import { get_logs } from '$lib/utils.svelte';
import Modal from './Modal.svelte';
let { shown = $bindable() }: { shown: boolean } = $props();
let content: string | undefined = $state(undefined);
$effect(() => {
const interval = setInterval(async () => {
try {
if (content !== undefined && (document.hidden || !shown)) {
return;
}
content = await get_logs();
} catch (error) {
console.log(error);
}
}, 1000);
return () => clearInterval(interval);
});
</script>
<Modal bind:shown title="Logs">
<div class="bg-gray-100 border border-gray-100 rounded-md overflow-scroll">
<pre class="m-2">{content}</pre>
</div>
</Modal>

View File

@@ -0,0 +1,106 @@
<script lang="ts">
import { ManifestEntry } from '$lib/manifest.svelte';
import { AnalysisManager } from '$lib/analysisManager.svelte';
import DownloadLink from '$lib/components/DownloadLink.svelte';
import DeleteButton from '$lib/components/DeleteButton.svelte';
import AnalysisStatus from './AnalysisStatus.svelte';
import AnalysisView from './AnalysisView.svelte';
import RecordingControls from './RecordingControls.svelte';
let {
entry,
current,
server_is_recording,
manager,
}: {
entry: ManifestEntry;
current: boolean;
server_is_recording: boolean;
manager: AnalysisManager;
} = $props();
// passing `undefined` as the locale uses the browser default
const date_formatter = new Intl.DateTimeFormat(undefined, {
timeStyle: 'long',
dateStyle: 'short',
});
let status_row_color = $derived.by(() => {
const num_warnings = entry.get_num_warnings();
if (num_warnings !== undefined && num_warnings > 0) {
return 'bg-red-100';
}
return current ? 'bg-green-100' : 'bg-gray-100';
});
let status_border_color = $derived.by(() => {
const num_warnings = entry.get_num_warnings();
if (num_warnings !== undefined && num_warnings > 0) {
return 'border-red-100';
}
return current ? 'border-green-100' : 'border-gray-100';
});
let analysis_visible = $state(false);
function toggle_analysis_visibility() {
analysis_visible = !analysis_visible;
}
</script>
<div
class="{status_row_color} {status_border_color} drop-shadow-sm p-4 flex flex-col gap-2 border rounded-md flex-1 overflow-x-auto overflow-y-hidden"
>
{#if current}
<div class="flex flex-row justify-between gap-2">
<span class="text-xl mb-2">Current Recording</span>
<span class=""
><AnalysisStatus
onclick={toggle_analysis_visibility}
{entry}
{analysis_visible}
/></span
>
</div>
{/if}
<div class="flex flex-col">
<div class="flex flex-row justify-between">
<span class="font-bold">ID: {entry.name}</span>
{#if !current}
<span class=""
><AnalysisStatus
onclick={toggle_analysis_visibility}
{entry}
{analysis_visible}
/></span
>
{/if}
</div>
<span class="">{entry.get_readable_qmdl_size()}</span>
</div>
<div class="flex flex-col">
<span class="">Start: {date_formatter.format(entry.start_time)}</span>
<span class=""
>Last Message: {(entry.last_message_time &&
date_formatter.format(entry.last_message_time)) ||
'N/A'}</span
>
</div>
{#if entry.stop_reason}
<div class="bg-yellow-50 border border-yellow-300 rounded-sm p-2 text-yellow-800 text-sm">
{entry.stop_reason}
</div>
{/if}
<div class="flex flex-row justify-between lg:justify-end gap-1 mt-2 overflow-x-auto">
<DownloadLink url={entry.get_pcap_url()} text="pcap" full_button />
<DownloadLink url={entry.get_qmdl_url()} text="qmdl" full_button />
<DownloadLink url={entry.get_zip_url()} text="zip" full_button />
{#if current}
<RecordingControls {server_is_recording} />
{:else}
<DeleteButton
prompt={`Are you sure you want to delete entry ${entry.name}?`}
url={entry.get_delete_url()}
name={entry.name}
/>
{/if}
</div>
<div class="border-b border-gray-200 {analysis_visible ? '' : 'hidden'}">
<AnalysisView {entry} {manager} {current} />
</div>
</div>

View File

@@ -0,0 +1,42 @@
<script lang="ts">
import { ManifestEntry } from '$lib/manifest.svelte';
import { AnalysisManager } from '$lib/analysisManager.svelte';
import { screenIsLgUp } from '$lib/stores/breakpoint';
import TableRow from './ManifestTableRow.svelte';
import Card from './ManifestCard.svelte';
interface Props {
entries: ManifestEntry[];
server_is_recording: boolean;
manager: AnalysisManager;
}
let { entries, server_is_recording, manager }: Props = $props();
</script>
<!--For larger screens we use a table-->
{#if $screenIsLgUp}
<table class="table-auto text-left table">
<thead>
<tr class="bg-gray-100 drop-shadow-sm">
<th class="p-2" scope="col">ID</th>
<th class="p-2" scope="col">Started</th>
<th class="p-2" scope="col">Last Message</th>
<th class="p-2" scope="col">Size</th>
<th class="p-2" scope="col">Download</th>
<th class="p-2" scope="col">Analysis</th>
<th class="p-2" scope="col"></th>
</tr>
</thead>
<tbody>
{#each entries as entry, i}
<TableRow {entry} current={false} {i} {manager} />
{/each}
</tbody>
</table>
{:else}
<!--For smaller screens we use cards-->
<div class="flex flex-col gap-4">
{#each entries as entry}
<Card {entry} current={false} {server_is_recording} {manager} />
{/each}
</div>
{/if}

View File

@@ -0,0 +1,72 @@
<script lang="ts">
import { ManifestEntry } from '$lib/manifest.svelte';
import { AnalysisManager } from '$lib/analysisManager.svelte';
import DownloadLink from '$lib/components/DownloadLink.svelte';
import DeleteButton from '$lib/components/DeleteButton.svelte';
import AnalysisStatus from './AnalysisStatus.svelte';
import AnalysisView from './AnalysisView.svelte';
let {
entry,
current,
i,
manager,
}: {
entry: ManifestEntry;
current: boolean;
i: number;
manager: AnalysisManager;
} = $props();
// passing `undefined` as the locale uses the browser default
const date_formatter = new Intl.DateTimeFormat(undefined, {
timeStyle: 'long',
dateStyle: 'short',
});
let alternating_row_color = $derived(i % 2 == 0 ? 'bg-white' : 'bg-gray-100');
let status_row_color = $derived.by(() => {
const num_warnings = entry.get_num_warnings();
if (num_warnings !== undefined && num_warnings > 0) {
return 'bg-red-100';
}
return current ? 'bg-green-100' : alternating_row_color;
});
let analysis_visible = $state(false);
function toggle_analysis_visibility() {
analysis_visible = !analysis_visible;
}
</script>
<tr class="{status_row_color} drop-shadow-sm">
<td class="p-2">{entry.name}</td>
<td class="p-2">{date_formatter.format(entry.start_time)}</td>
<td class="p-2"
>{(entry.last_message_time && date_formatter.format(entry.last_message_time)) || 'N/A'}</td
>
<td class="p-2">{entry.get_readable_qmdl_size()}</td>
<td class="p-2">
<div class="flex flex-row gap-2">
<DownloadLink url={entry.get_pcap_url()} text="pcap" />
<DownloadLink url={entry.get_qmdl_url()} text="qmdl" />
<DownloadLink url={entry.get_zip_url()} text="zip" />
</div>
</td>
<td class="p-2"
><AnalysisStatus onclick={toggle_analysis_visibility} {entry} {analysis_visible} /></td
>
{#if current}
<td class="p-2"></td>
{:else}
<td class="p-2">
<DeleteButton
prompt={`Are you sure you want to delete entry ${entry.name}?`}
url={entry.get_delete_url()}
name={entry.name}
/>
</td>
{/if}
</tr>
<tr class="{alternating_row_color} border-b border-gray-200 {analysis_visible ? '' : 'hidden'}">
<td class="border-t border-gray-200 border-dashed p-2" colspan="9">
<AnalysisView {entry} {manager} {current} />
</td>
</tr>

Some files were not shown because too many files have changed in this diff Show More