Compare commits
No commits in common. "main" and "modules-v0.1.3" have entirely different histories.
main
...
modules-v0
193 changed files with 1171 additions and 9526 deletions
|
|
@ -1,16 +1,7 @@
|
|||
# Build multi-platform streamd binaries + Android MITM and attach them to a Forgejo release.
|
||||
# Build multi-platform drm binaries + Android MITM and attach them to a Forgejo release.
|
||||
#
|
||||
# Triggers:
|
||||
# Stable: git tag v1.2.3 && git push origin v1.2.3
|
||||
# Beta: git tag v1.2.3-beta.1 && git push origin v1.2.3-beta.1
|
||||
#
|
||||
# Each version tag gets its own release. CI also retargets a rolling channel tag:
|
||||
# vX.Y.Z → release + update `stable` (always-latest download URL)
|
||||
# vX.Y.Z-<pre> → prerelease + update `beta` (always-latest beta URL)
|
||||
#
|
||||
# Download without pinning a version:
|
||||
# .../releases/download/stable/streamd-linux-amd64
|
||||
# .../releases/download/beta/streamd-linux-amd64
|
||||
# Trigger: push a version tag
|
||||
# git tag v1.2.3 && git push origin v1.2.3
|
||||
#
|
||||
# Requires a Forgejo Actions runner registered against this instance
|
||||
# (label must match runs-on below — default act_runner often uses "docker").
|
||||
|
|
@ -32,35 +23,6 @@ jobs:
|
|||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Classify tag (stable vs beta)
|
||||
id: meta
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG="${{ github.ref_name }}"
|
||||
# Strict SemVer: v1.2.3 = stable; v1.2.3-beta.1 / -rc.1 / -alpha.1 = beta channel
|
||||
if echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
|
||||
CHANNEL=stable
|
||||
PRERELEASE=false
|
||||
TITLE="$TAG"
|
||||
NOTES_KIND=stable
|
||||
elif echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+-(beta|rc|alpha)(\.[0-9]+)?$'; then
|
||||
CHANNEL=beta
|
||||
PRERELEASE=true
|
||||
TITLE="$TAG (beta)"
|
||||
NOTES_KIND=beta
|
||||
else
|
||||
echo "Unsupported host tag '$TAG'." >&2
|
||||
echo "Use vX.Y.Z for stable or vX.Y.Z-beta.N / -rc.N / -alpha.N for beta." >&2
|
||||
exit 1
|
||||
fi
|
||||
{
|
||||
echo "channel=$CHANNEL"
|
||||
echo "prerelease=$PRERELEASE"
|
||||
echo "title=$TITLE"
|
||||
echo "notes_kind=$NOTES_KIND"
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
echo "tag=$TAG channel=$CHANNEL prerelease=$PRERELEASE"
|
||||
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
|
|
@ -75,91 +37,44 @@ jobs:
|
|||
./scripts/build-release.sh "${{ github.ref_name }}"
|
||||
ls -la dist/release
|
||||
|
||||
- name: Prepare release notes
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG="${{ github.ref_name }}"
|
||||
CHANNEL="${{ steps.meta.outputs.channel }}"
|
||||
NOTES="docs/releases/${TAG}.md"
|
||||
if [ -f "$NOTES" ]; then
|
||||
cp "$NOTES" /tmp/release-notes.md
|
||||
echo "Using $NOTES"
|
||||
else
|
||||
cat > /tmp/release-notes.md <<EOF
|
||||
Multi-platform **Streamd** host CLI + on-device MITM (\`proxy-android-arm64\`).
|
||||
|
||||
Channel: **${CHANNEL}** (rolling download tag \`${CHANNEL}\` also updated).
|
||||
|
||||
| Asset | Platform |
|
||||
|---|---|
|
||||
| \`streamd-windows-amd64.exe\` | Windows x86_64 |
|
||||
| \`streamd-windows-arm64.exe\` | Windows ARM64 |
|
||||
| \`streamd-linux-amd64\` | Linux x86_64 |
|
||||
| \`streamd-linux-arm64\` | Linux ARM64 |
|
||||
| \`streamd-darwin-amd64\` | macOS Intel |
|
||||
| \`streamd-darwin-arm64\` | macOS Apple Silicon |
|
||||
| \`proxy-android-arm64\` | On-device MITM (push with \`streamd proxy\`) |
|
||||
| \`SHA256SUMS.txt\` | Checksums |
|
||||
|
||||
Always-latest URLs (no version pin):
|
||||
- Stable: \`…/releases/download/stable/<asset>\`
|
||||
- Beta: \`…/releases/download/beta/<asset>\`
|
||||
|
||||
Built with \`CGO_ENABLED=0\` via \`scripts/build-release.sh\`.
|
||||
Phone capture still needs Magisk + \`streamd proxy install-ca --reinject\`.
|
||||
EOF
|
||||
echo "No $NOTES — using generic notes"
|
||||
fi
|
||||
cat > /tmp/channel-notes.md <<EOF
|
||||
Rolling **${CHANNEL}** channel for Streamd.
|
||||
|
||||
Currently points at **${TAG}**.
|
||||
Prefer versioned tags for pinned installs; use this channel for always-latest downloads.
|
||||
|
||||
\`\`\`text
|
||||
…/releases/download/${CHANNEL}/streamd-linux-amd64
|
||||
…/releases/download/${CHANNEL}/streamd-windows-amd64.exe
|
||||
…/releases/download/${CHANNEL}/proxy-android-arm64
|
||||
\`\`\`
|
||||
EOF
|
||||
|
||||
- name: Upload versioned Forgejo release
|
||||
- name: Upload to Forgejo release
|
||||
uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2
|
||||
with:
|
||||
direction: upload
|
||||
# Defaults to this runner's Forgejo URL when omitted.
|
||||
url: https://git.nulldrm.com
|
||||
repo: ${{ github.repository }}
|
||||
# Built-in job token (write:repository). Override with a PAT secret if needed.
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag: ${{ github.ref_name }}
|
||||
sha: ${{ github.sha }}
|
||||
release-dir: dist/release
|
||||
title: ${{ steps.meta.outputs.title }}
|
||||
prerelease: ${{ steps.meta.outputs.prerelease }}
|
||||
title: ${{ github.ref_name }}
|
||||
override: true
|
||||
release-notes-file: /tmp/release-notes.md
|
||||
release-notes: |
|
||||
Multi-platform `drm` host CLI + on-device MITM (`proxy-android-arm64`).
|
||||
|
||||
- name: Upload rolling channel release (stable / beta)
|
||||
uses: https://data.forgejo.org/actions/forgejo-release@v2.7.2
|
||||
with:
|
||||
direction: upload
|
||||
url: https://git.nulldrm.com
|
||||
repo: ${{ github.repository }}
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
tag: ${{ steps.meta.outputs.channel }}
|
||||
sha: ${{ github.sha }}
|
||||
release-dir: dist/release
|
||||
title: ${{ steps.meta.outputs.channel }} ← ${{ github.ref_name }}
|
||||
prerelease: ${{ steps.meta.outputs.prerelease }}
|
||||
override: true
|
||||
release-notes-file: /tmp/channel-notes.md
|
||||
| Asset | Platform |
|
||||
|---|---|
|
||||
| `drm-windows-amd64.exe` | Windows x86_64 |
|
||||
| `drm-windows-arm64.exe` | Windows ARM64 |
|
||||
| `drm-linux-amd64` | Linux x86_64 |
|
||||
| `drm-linux-arm64` | Linux ARM64 |
|
||||
| `drm-darwin-amd64` | macOS Intel |
|
||||
| `drm-darwin-arm64` | macOS Apple Silicon |
|
||||
| `proxy-android-arm64` | On-device MITM (push with `drm proxy`) |
|
||||
| `SHA256SUMS.txt` | Checksums |
|
||||
|
||||
Built with `CGO_ENABLED=0` via `scripts/build-release.sh`.
|
||||
Phone capture still needs Magisk + `drm proxy install-ca --reinject`.
|
||||
|
||||
- name: Announce on Telegram
|
||||
env:
|
||||
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
|
||||
# Private DM chat (@error404developer). Override via secret if needed.
|
||||
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
RELEASE_KIND: host
|
||||
RELEASE_CHANNEL: ${{ steps.meta.outputs.channel }}
|
||||
RELEASE_URL: https://git.nulldrm.com/${{ github.repository }}/releases/tag/${{ github.ref_name }}
|
||||
run: |
|
||||
if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
|
||||
|
|
@ -169,10 +84,5 @@ jobs:
|
|||
# Null DRM Telegram group → Releases topic (t.me/c/3721978702/16).
|
||||
export TELEGRAM_CHAT_ID="-1003721978702"
|
||||
export TELEGRAM_MESSAGE_THREAD_ID="16"
|
||||
if [ "${{ steps.meta.outputs.channel }}" = "beta" ]; then
|
||||
export RELEASE_TITLE="Streamd ${{ github.ref_name }} (beta)"
|
||||
else
|
||||
export RELEASE_TITLE="Streamd ${{ github.ref_name }}"
|
||||
fi
|
||||
chmod +x scripts/notify-telegram.sh
|
||||
./scripts/notify-telegram.sh "${{ github.ref_name }}"
|
||||
|
|
|
|||
4
.gitignore
vendored
4
.gitignore
vendored
|
|
@ -218,7 +218,7 @@ apps/proxy/proxy-android-arm64
|
|||
apps/proxy/rteproxy-android-arm64
|
||||
# local / VPS deploy + operator scripts (test stuff; keep out of git)
|
||||
deploy/
|
||||
# Ignore local scripts, but keep release builders + server helpers tracked.
|
||||
# Ignore local scripts, but keep the release builders tracked for Forgejo Actions.
|
||||
scripts/*
|
||||
!scripts/build-release.sh
|
||||
!scripts/build-release.ps1
|
||||
|
|
@ -226,8 +226,6 @@ scripts/*
|
|||
!scripts/build-modules-release.ps1
|
||||
!scripts/notify-telegram.sh
|
||||
!scripts/notify-telegram.ps1
|
||||
!scripts/streamd-bg.sh
|
||||
!scripts/streamd-update.sh
|
||||
# Shared library packages under apps/modules/ (imported by external module CLIs).
|
||||
# module.yaml stays local; module-publish.yaml is the tracked universal template.
|
||||
apps/modules/**
|
||||
|
|
|
|||
108
README.md
108
README.md
|
|
@ -1,9 +1,9 @@
|
|||
# 📺 Streamd
|
||||
# 🔓 Null DRM
|
||||
|
||||
**Next-generation open-source DRM decryption for Android streaming apps.**
|
||||
|
||||
Capture live sessions from phones (BBC iPlayer, RTÉ, TG4, ITVX, Channel 4, …), pull manifests
|
||||
and licenses through a transparent MITM, and restream. One host binary — **`streamd`** —
|
||||
and licenses through a transparent MITM, and restream. One host binary — **`drm`** —
|
||||
plus drop-in providers under **`modules/`**.
|
||||
|
||||
📦 Releases: [git.nulldrm.com](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases)
|
||||
|
|
@ -30,7 +30,7 @@ traffic.
|
|||
|
||||
## 🖥️ streamd dashboard
|
||||
|
||||
Run `streamd serve`, open the panel in a browser, manage streams and API keys:
|
||||
Run `drm serve`, open the panel in a browser, manage streams and API keys:
|
||||
|
||||
<p align="center">
|
||||
<img src="docs/images/streamd/dashboard.jpg" alt="streamd Dashboard — overview, live Channel 4, HLS link" width="720" />
|
||||
|
|
@ -64,55 +64,15 @@ Server setup guide: [docs/streamd-server-setup.md](docs/streamd-server-setup.md)
|
|||
|
||||
### 1️⃣ Download
|
||||
|
||||
Host binaries ship on two rolling channels (always the newest build — no version pin):
|
||||
|
||||
| Channel | Tag | When to use |
|
||||
|---------|-----|-------------|
|
||||
| **Stable** | [`stable`](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/tag/stable) | Everyday installs |
|
||||
| **Beta** | [`beta`](https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/tag/beta) | Try pre-releases (`vX.Y.Z-beta.N`) |
|
||||
|
||||
Provider zips still come from **`modules-v*`** releases (`bbc.zip`, `rte.zip`, …).
|
||||
Pick **one** host binary block for your machine, then run `chmod +x streamd` on Linux/macOS.
|
||||
|
||||
**Linux Intel / AMD 64-bit (stable)**
|
||||
|
||||
```bash
|
||||
curl -fL -o streamd \
|
||||
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-amd64"
|
||||
chmod +x streamd
|
||||
```
|
||||
|
||||
**Linux ARM 64-bit (stable)** — Raspberry Pi 4+, many cloud ARM VMs
|
||||
|
||||
```bash
|
||||
curl -fL -o streamd \
|
||||
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-arm64"
|
||||
chmod +x streamd
|
||||
```
|
||||
|
||||
**Beta channel (Linux Intel / AMD 64-bit pre-release)**
|
||||
|
||||
```bash
|
||||
curl -fL -o streamd \
|
||||
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/beta/streamd-linux-amd64"
|
||||
chmod +x streamd
|
||||
```
|
||||
|
||||
**Windows Intel / AMD 64-bit (stable, PowerShell)**
|
||||
|
||||
```powershell
|
||||
Invoke-WebRequest -Uri "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-windows-amd64.exe" -OutFile streamd.exe
|
||||
```
|
||||
|
||||
Other stable assets: `streamd-windows-arm64.exe`, `streamd-darwin-amd64`, `streamd-darwin-arm64`,
|
||||
`proxy-android-arm64`. For beta, swap `/download/stable/` → `/download/beta/` in any URL.
|
||||
Pinned install: swap `stable` / `beta` for a concrete tag such as `v0.1.5` or `v0.2.0-beta.1`.
|
||||
From the latest **`v*`** release grab your host binary (e.g. `drm-windows-amd64.exe`)
|
||||
and `proxy-android-arm64`. From a **`modules-v*`** release grab the zips you need
|
||||
(`bbc.zip`, `rte.zip`, `tg4.zip`, `itv.zip`, `c4.zip`, `my5.zip`).
|
||||
|
||||
```text
|
||||
Streamd/
|
||||
streamd.exe # or ./streamd on Linux/macOS
|
||||
bin/proxy-android-arm64 # optional; also embedded in the release binary
|
||||
modules/ # or upload zips in the streamd Modules page
|
||||
Null-DRM/
|
||||
drm.exe # or ./drm on Linux/macOS
|
||||
bin/proxy-android-arm64 # optional; also embedded in release drm
|
||||
modules/
|
||||
bbc/ # unzip bbc.zip here
|
||||
rte/
|
||||
tg4/
|
||||
|
|
@ -121,7 +81,7 @@ Streamd/
|
|||
outputs/ # created on first run
|
||||
```
|
||||
|
||||
On first run, `streamd` creates the install scaffold next to the exe.
|
||||
On first run, `drm` creates the install scaffold next to the exe.
|
||||
|
||||
### 2️⃣ Prerequisites
|
||||
|
||||
|
|
@ -139,14 +99,14 @@ Unzip into `modules/<name>/`. Edit **`module.yaml`** — fill sensitive fields o
|
|||
almost nothing extra.
|
||||
|
||||
```bash
|
||||
streamd modules
|
||||
# or: streamd --modules-dir D:\mods modules
|
||||
drm modules
|
||||
# or: drm --modules-dir D:\mods modules
|
||||
```
|
||||
|
||||
### 4️⃣ Phone CA (once per device / CA)
|
||||
|
||||
```bash
|
||||
streamd proxy install-ca --reinject
|
||||
drm proxy install-ca --reinject
|
||||
adb shell am force-stop bbc.iplayer.android # or the app you will capture
|
||||
```
|
||||
|
||||
|
|
@ -154,25 +114,25 @@ adb shell am force-stop bbc.iplayer.android # or the app you will capture
|
|||
|
||||
```bash
|
||||
# BBC + NordVPN UK on the phone (transparent MITM; --channel auto-plays)
|
||||
streamd capture --app bbc --channel bbcone --wait 120
|
||||
streamd capture --app bbc --channel s4c --wait 120
|
||||
drm capture --app bbc --channel bbcone --wait 120
|
||||
drm capture --app bbc --channel s4c --wait 120
|
||||
|
||||
# ITVX (UK VPN; Live tab autoplay)
|
||||
streamd capture --app itv --channel itv1 --wait 90
|
||||
drm capture --app itv --channel itv1 --wait 90
|
||||
|
||||
# Channel 4 — one channel, or every Live channel
|
||||
streamd capture --app c4 --channel channel4 --wait 90
|
||||
streamd capture --app c4 --all --wait 90
|
||||
drm capture --app c4 --channel channel4 --wait 90
|
||||
drm capture --app c4 --all --wait 90
|
||||
|
||||
# Grab every channel for any module
|
||||
streamd capture --app itv --all --wait 90
|
||||
drm capture --app itv --all --wait 90
|
||||
|
||||
# RTE / TG4 (keys via --wvd when needed)
|
||||
streamd capture --app rte --channel rteone --wvd data/device.wvd
|
||||
streamd capture --app tg4 --channel ioi --wvd data/device.wvd
|
||||
drm capture --app rte --channel rteone --wvd data/device.wvd
|
||||
drm capture --app tg4 --channel ioi --wvd data/device.wvd
|
||||
|
||||
# Catalog only (no phone) — TG4
|
||||
streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
|
||||
drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
|
||||
```
|
||||
|
||||
📁 Results land in `outputs/<app>/<stamp>/` (and `latest/`).
|
||||
|
|
@ -180,7 +140,7 @@ streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
|
|||
### 6️⃣ Clean the phone after a run
|
||||
|
||||
```bash
|
||||
streamd proxy reset
|
||||
drm proxy reset
|
||||
```
|
||||
|
||||
Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fresh.
|
||||
|
|
@ -190,19 +150,19 @@ Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fr
|
|||
## 🧾 Command cheat sheet
|
||||
|
||||
```text
|
||||
streamd [--modules-dir DIR] <command> …
|
||||
drm [--modules-dir DIR] <command> …
|
||||
|
||||
streamd modules
|
||||
streamd capture --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S]
|
||||
streamd catalog --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list]
|
||||
streamd proxy install-ca [--reinject] | reset [--keep-captures]
|
||||
drm modules
|
||||
drm capture --app NAME [--channel ID] [--wait N] [--wvd PATH] [--serial S]
|
||||
drm catalog --app NAME --channel ID [--keys] [--wvd PATH] [--json] [--list]
|
||||
drm proxy install-ca [--reinject] | reset [--keep-captures]
|
||||
| transparent --package PKG [--mitm-host HOST]
|
||||
| start | stop | push | discover | pull
|
||||
streamd serve [--bind …] [--data …] [--token …]
|
||||
streamd agent run|status|devices|enqueue|cancel [--config …]
|
||||
drm serve [--bind …] [--data …] [--token …]
|
||||
drm agent run|status|devices|enqueue|cancel [--config …]
|
||||
```
|
||||
|
||||
🌍 Global: `--modules-dir DIR` or `$STREAMD_MODULES_DIR` (default: `./modules`).
|
||||
🌍 Global: `--modules-dir DIR` or `$DRM_MODULES_DIR` (default: `./modules`).
|
||||
|
||||
🎯 `--channel` implies interactive auto-play (provider-specific Live UI flow).
|
||||
|
||||
|
|
@ -225,7 +185,7 @@ with `module.yaml` only (no `module-publish.yaml` inside the zip).
|
|||
```bash
|
||||
git clone https://git.nulldrm.com/nulldrm/Null-DRM-Official.git
|
||||
cd Null-DRM-Official
|
||||
go -C apps/cli build -o ../../bin/streamd.exe . # Windows
|
||||
go -C apps/cli build -o ../../bin/drm.exe . # Windows
|
||||
# Host release: .\scripts\build-release.ps1 -Version v0.1.1
|
||||
# Modules: .\scripts\build-modules-release.ps1 -Version modules-v0.1.1
|
||||
```
|
||||
|
|
@ -236,7 +196,7 @@ More detail: [docs/quickstart.md](docs/quickstart.md) · [docs/architecture.md](
|
|||
|
||||
## 💚 Support the project
|
||||
|
||||
If Streamd saves you time, donations keep development going:
|
||||
If Null DRM saves you time, donations keep development going:
|
||||
|
||||
| Coin | Address |
|
||||
|------|---------|
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# agent
|
||||
|
||||
Always-on credentials refresher, hosted by the single binary as `streamd agent`.
|
||||
Always-on credentials refresher, hosted by the single binary as `drm agent`.
|
||||
|
||||
```text
|
||||
apps/agent/
|
||||
|
|
@ -26,54 +26,43 @@ expire by themselves if the agent dies.
|
|||
|
||||
```bash
|
||||
# terminal 1 — control plane
|
||||
./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
|
||||
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd
|
||||
|
||||
# terminal 2 — agent in the background (Linux / macOS / Windows)
|
||||
# terminal 2 — agent (operator API key from streamd Settings → API keys)
|
||||
export STREAMD_API_KEY=ndk_…
|
||||
./bin/streamd agent start --config apps/agent/agent.yaml
|
||||
./bin/streamd agent status --config apps/agent/agent.yaml
|
||||
# foreground debug: ./bin/streamd agent run --config apps/agent/agent.yaml
|
||||
# stop / restart: ./bin/streamd agent stop|restart --config …
|
||||
# self-update: ./bin/streamd agent update [--beta] [--tag vX.Y.Z]
|
||||
# or legacy: export STREAMD_TOKEN=…
|
||||
./bin/drm agent run --config apps/agent/agent.yaml
|
||||
```
|
||||
|
||||
```bash
|
||||
./bin/streamd agent devices
|
||||
./bin/streamd agent enqueue --stream tg4-ioi --reason manual
|
||||
./bin/streamd agent cancel --job 3
|
||||
./bin/drm agent status
|
||||
./bin/drm agent devices
|
||||
./bin/drm agent enqueue --stream tg4-ioi --reason manual
|
||||
./bin/drm agent cancel --job 3
|
||||
```
|
||||
|
||||
With `sync_modules: true` (default in the sample config), the agent **pulls**
|
||||
provider modules from the streamd Modules page into `<data_dir>/modules/`. You do
|
||||
not need a hand-maintained `modules/` tree on each agent host. The agent drives
|
||||
whichever module a stream names and contains no provider logic.
|
||||
App modules are discovered under `modules/`. The agent drives whichever module a
|
||||
stream names and contains no provider logic.
|
||||
|
||||
## Config
|
||||
|
||||
`agent.yaml` — `streamd_url`, **`api_key`** (preferred) or `token` (alias), or
|
||||
env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`,
|
||||
`max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device),
|
||||
`wvd`, `user_agent`, `agent_id`, `data_dir`, `sync_modules`, `modules_dir`
|
||||
(default `<data_dir>/modules`), `modules_sync_interval_sec`, `modules_prune`,
|
||||
`job_backoff` (default false — exponential delays only when several agents
|
||||
share work), plus daemon fields `log_file`, `pid_file`, `channel`, `asset`,
|
||||
`keep_old` for `agent start|stop|update`.
|
||||
`wvd`, `user_agent`, `agent_id`, `data_dir`.
|
||||
|
||||
Create the key in the streamd dashboard (role **operator**). The legacy shared
|
||||
`--token` / `STREAMD_TOKEN` still works but is meant for migration only.
|
||||
|
||||
`wvd` must be set or key fetches fail. On first `agent start`/`run`, streamd
|
||||
bootstraps `apps/wvkey/` and creates `<install>/.venv` with `pywidevine` using
|
||||
the system Python (Windows, Linux, or macOS) so Widevine key fetch works without
|
||||
a hand-made venv.
|
||||
`wvd` must be set or key fetches fail.
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
go -C apps/cli build -o ../../bin/streamd .
|
||||
go -C apps/cli build -o ../../bin/drm .
|
||||
|
||||
# cross-compile
|
||||
GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/streamd .
|
||||
GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/drm .
|
||||
```
|
||||
|
||||
**Full guide: [docs/streamd.md](../../docs/streamd.md)**
|
||||
|
|
|
|||
|
|
@ -14,23 +14,12 @@ workers: 1 # concurrent ADB jobs
|
|||
max_attempts: 5
|
||||
capture_wait_sec: 180
|
||||
devices: [] # empty = all adb "device" serials; never installs apps
|
||||
# Pull modules from the streamd panel into the local cache (package.zip + yaml).
|
||||
# Push local modules/<name>/module.yaml to streamd when missing or SHA differs.
|
||||
sync_modules: true
|
||||
# modules_dir: # optional; default <data_dir>/modules
|
||||
# modules_dir: modules # optional override (default: repo modules/)
|
||||
# modules_sync_interval_sec: 300
|
||||
# modules_prune: false # delete local modules absent from the panel
|
||||
# Exponential retry delays (1m, 2m, 4m…). Default false — lone agents retry ASAP.
|
||||
# Set true only when several agents share the same streams.
|
||||
# job_backoff: false
|
||||
# Background daemon (streamd agent start|stop|update):
|
||||
# log_file: agent.log
|
||||
# pid_file: agent.pid
|
||||
# channel: stable # or beta — used by agent update
|
||||
# asset: # optional streamd-* override
|
||||
# keep_old: 10
|
||||
# Required for key fetch. Relative paths resolve from the install/repo root.
|
||||
# Agent auto-creates .venv + installs pywidevine on first run (Win/Linux/macOS).
|
||||
# python: # optional override; default = <root>/.venv/…
|
||||
wvd: data/device.wvd
|
||||
# Required for key fetch. Relative paths resolve from the repo root
|
||||
# (DRM-Decryption/), not from C:\Users\admin\Programming\.
|
||||
wvd:
|
||||
# user_agent: "" # optional license-request User-Agent
|
||||
|
||||
|
|
|
|||
|
|
@ -9,21 +9,17 @@ import (
|
|||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"text/tabwriter"
|
||||
|
||||
"streamd/apps/agent/internal/client"
|
||||
"streamd/apps/agent/internal/config"
|
||||
"streamd/apps/agent/internal/device"
|
||||
"streamd/apps/agent/internal/modsync"
|
||||
"streamd/apps/agent/internal/poller"
|
||||
"streamd/apps/agent/internal/queue"
|
||||
"streamd/apps/agent/internal/worker"
|
||||
"streamd/apps/agent/internal/wsclient"
|
||||
"streamd/modhost"
|
||||
"streamd/repo"
|
||||
"streamd/wvkey"
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
"drmdecryption/apps/agent/internal/config"
|
||||
"drmdecryption/apps/agent/internal/device"
|
||||
"drmdecryption/apps/agent/internal/modsync"
|
||||
"drmdecryption/apps/agent/internal/poller"
|
||||
"drmdecryption/apps/agent/internal/queue"
|
||||
"drmdecryption/apps/agent/internal/worker"
|
||||
"drmdecryption/apps/agent/internal/wsclient"
|
||||
)
|
||||
|
||||
// Run dispatches an agent subcommand. args[0] is the subcommand name.
|
||||
|
|
@ -39,14 +35,6 @@ func Run(args []string) error {
|
|||
switch sub {
|
||||
case "run":
|
||||
runCmd(sub, rest)
|
||||
case "start":
|
||||
return startDaemonCmd(rest)
|
||||
case "stop":
|
||||
return stopDaemonCmd(rest)
|
||||
case "restart":
|
||||
return restartDaemonCmd(rest)
|
||||
case "update":
|
||||
return updateDaemonCmd(rest)
|
||||
case "status":
|
||||
statusCmd(sub, rest)
|
||||
case "devices":
|
||||
|
|
@ -69,13 +57,8 @@ func Usage() {
|
|||
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
|
||||
|
||||
Usage:
|
||||
agent start [--config agent.yaml] # background (pid + log)
|
||||
agent stop [--config ...]
|
||||
agent restart [--config ...]
|
||||
agent status [--config ...] # process + recent jobs
|
||||
agent update [--config ...] [--beta] [--tag vX.Y.Z] [--no-restart]
|
||||
agent run [--config ...] # foreground (debug)
|
||||
|
||||
agent run [--config apps/agent/agent.yaml]
|
||||
agent status [--config ...]
|
||||
agent devices [--config ...]
|
||||
agent enqueue --stream NAME [--reason manual] [--config ...]
|
||||
agent cancel --job ID [--config ...]
|
||||
|
|
@ -84,9 +67,6 @@ Polls streamd for enabled streams that are down / missing credentials,
|
|||
enqueues jobs, claims a free phone that already has the app, captures
|
||||
via MITM, POSTs credentials, then force-stops the app.
|
||||
|
||||
Job retries default to immediate (job_backoff: false). Set job_backoff: true
|
||||
in agent.yaml for exponential delays when several agents share work.
|
||||
|
||||
Does not install apps. Does not run NRE/ffmpeg.
|
||||
`)
|
||||
}
|
||||
|
|
@ -136,18 +116,6 @@ func runCmd(sub string, args []string) {
|
|||
"create an operator API key in the streamd dashboard", me.Role)
|
||||
}
|
||||
log.Printf("authenticated to streamd as %q (role %s)", me.Name, me.Role)
|
||||
|
||||
// Widevine keys need apps/wvkey + a local .venv (pywidevine). Create them
|
||||
// once per install root so Windows / Linux / macOS agents all work.
|
||||
if rt, err := wvkey.EnsureRuntime(repo.Root()); err != nil {
|
||||
log.Fatalf("widevine helper: %v", err)
|
||||
} else {
|
||||
log.Printf("widevine helper ready python=%s script=%s", rt.Python, rt.Script)
|
||||
if strings.TrimSpace(cfg.Python) == "" {
|
||||
cfg.Python = rt.Python
|
||||
}
|
||||
}
|
||||
|
||||
q := openQueue(cfg)
|
||||
defer q.Close()
|
||||
|
||||
|
|
@ -156,16 +124,6 @@ func runCmd(sub string, args []string) {
|
|||
} else if n > 0 {
|
||||
log.Printf("re-queued %d stuck running job(s) from previous run", n)
|
||||
}
|
||||
if n, err := q.ClearAllBackoffs(); err != nil {
|
||||
log.Printf("clear backoffs: %v", err)
|
||||
} else if n > 0 {
|
||||
log.Printf("cleared backoff on %d queued job(s) — runnable now", n)
|
||||
}
|
||||
if cfg.JobBackoffEnabled() {
|
||||
log.Printf("job_backoff=true (exponential delays after failures)")
|
||||
} else {
|
||||
log.Printf("job_backoff=false (retry failed captures immediately)")
|
||||
}
|
||||
|
||||
pool := device.New("", cfg.Devices)
|
||||
stop := make(chan struct{})
|
||||
|
|
@ -179,25 +137,15 @@ func runCmd(sub string, args []string) {
|
|||
}
|
||||
go p.Loop(stop)
|
||||
|
||||
// Prefer the panel-synced modules cache for capture jobs.
|
||||
if cfg.ModulesDir != "" {
|
||||
if err := modhost.SetModulesDir(cfg.ModulesDir); err != nil {
|
||||
log.Fatalf("modules dir: %v", err)
|
||||
}
|
||||
log.Printf("modules dir %s", cfg.ModulesDir)
|
||||
}
|
||||
|
||||
var ms *modsync.Syncer
|
||||
if cfg.SyncModules {
|
||||
ms = &modsync.Syncer{
|
||||
ms := &modsync.Syncer{
|
||||
API: api,
|
||||
ModulesDir: cfg.ModulesDir,
|
||||
Interval: cfg.ModulesSyncInterval(),
|
||||
Prune: cfg.ModulesPrune,
|
||||
Log: log.Default(),
|
||||
}
|
||||
go ms.Loop(stop)
|
||||
log.Printf("modules pull sync enabled interval=%s dir=%s", cfg.ModulesSyncInterval(), cfg.ModulesDir)
|
||||
log.Printf("modules sync enabled interval=%s", cfg.ModulesSyncInterval())
|
||||
}
|
||||
|
||||
ws := wsclient.New(cfg.StreamdURL, cfg.Token, cfg.AgentID, log.Default())
|
||||
|
|
@ -223,16 +171,6 @@ func runCmd(sub string, args []string) {
|
|||
}
|
||||
}()
|
||||
}
|
||||
ws.OnModulesChanged = func(name, reason string) {
|
||||
if ms == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
if err := ms.Once(); err != nil {
|
||||
log.Printf("modules sync after change to %s: %v", name, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
go ws.Loop()
|
||||
|
||||
for i := 0; i < cfg.Workers; i++ {
|
||||
|
|
@ -246,7 +184,6 @@ func runCmd(sub string, args []string) {
|
|||
Python: cfg.Python,
|
||||
WVD: cfg.WVD,
|
||||
UserAgent: cfg.UserAgent,
|
||||
JobBackoff: cfg.JobBackoffEnabled(),
|
||||
Log: log.Default(),
|
||||
}
|
||||
go w.Loop(stop)
|
||||
|
|
@ -267,7 +204,6 @@ func runCmd(sub string, args []string) {
|
|||
|
||||
func statusCmd(sub string, args []string) {
|
||||
cfg, _ := loadCfg(sub, args)
|
||||
printDaemonStatus(cfg)
|
||||
q := openQueue(cfg)
|
||||
defer q.Close()
|
||||
jobs, err := q.ListRecent(40)
|
||||
|
|
|
|||
|
|
@ -1,177 +0,0 @@
|
|||
package agentcmd
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/apps/agent/internal/config"
|
||||
"streamd/repo"
|
||||
)
|
||||
|
||||
func readPID(pidFile string) (int, error) {
|
||||
b, err := os.ReadFile(pidFile)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return strconv.Atoi(strings.TrimSpace(string(b)))
|
||||
}
|
||||
|
||||
func writePID(pidFile string, pid int) error {
|
||||
if err := os.MkdirAll(filepath.Dir(pidFile), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(pidFile, []byte(strconv.Itoa(pid)+"\n"), 0o644)
|
||||
}
|
||||
|
||||
func removePID(pidFile string) { _ = os.Remove(pidFile) }
|
||||
|
||||
func runningPID(cfg config.Config) (int, bool) {
|
||||
pid, err := readPID(cfg.PIDFile)
|
||||
if err != nil || pid <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
if !signalAlive(pid) {
|
||||
removePID(cfg.PIDFile)
|
||||
return pid, false
|
||||
}
|
||||
return pid, true
|
||||
}
|
||||
|
||||
func printDaemonStatus(cfg config.Config) {
|
||||
fmt.Printf("config: %s\n", cfgPathHint(cfg))
|
||||
fmt.Printf("pid: %s\n", cfg.PIDFile)
|
||||
fmt.Printf("log: %s\n", cfg.LogFile)
|
||||
if pid, ok := runningPID(cfg); ok {
|
||||
fmt.Printf("agent: running pid=%d\n", pid)
|
||||
} else {
|
||||
fmt.Println("agent: stopped")
|
||||
}
|
||||
}
|
||||
|
||||
func cfgPathHint(cfg config.Config) string {
|
||||
// Best-effort: show data dir; exact yaml path was already resolved by Load.
|
||||
return cfg.DataDir
|
||||
}
|
||||
|
||||
func startDaemonCmd(args []string) error {
|
||||
cfg, cfgFile := loadCfgWithPath("start", args)
|
||||
if pid, ok := runningPID(cfg); ok {
|
||||
fmt.Printf("agent already running (pid %d)\n", pid)
|
||||
return nil
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
|
||||
exe = resolved
|
||||
}
|
||||
runArgs := []string{"agent", "run"}
|
||||
if cfgFile != "" {
|
||||
runArgs = append(runArgs, "--config", cfgFile)
|
||||
}
|
||||
cmd := exec.Command(exe, runArgs...)
|
||||
if err := os.MkdirAll(filepath.Dir(cfg.LogFile), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
logF, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd.Stdout = logF
|
||||
cmd.Stderr = logF
|
||||
cmd.Stdin = nil
|
||||
detachProcess(cmd)
|
||||
if err := cmd.Start(); err != nil {
|
||||
_ = logF.Close()
|
||||
return fmt.Errorf("start agent: %w", err)
|
||||
}
|
||||
pid := cmd.Process.Pid
|
||||
_ = cmd.Process.Release()
|
||||
_ = logF.Close()
|
||||
if err := writePID(cfg.PIDFile, pid); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
if !signalAlive(pid) {
|
||||
removePID(cfg.PIDFile)
|
||||
return fmt.Errorf("agent exited immediately — see %s", cfg.LogFile)
|
||||
}
|
||||
fmt.Printf("agent started pid=%d\n", pid)
|
||||
fmt.Printf("logs: %s\n", cfg.LogFile)
|
||||
return nil
|
||||
}
|
||||
|
||||
func stopDaemonCmd(args []string) error {
|
||||
cfg, _ := loadCfgWithPath("stop", args)
|
||||
pid, err := readPID(cfg.PIDFile)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
fmt.Println("agent is not running")
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if !signalAlive(pid) {
|
||||
removePID(cfg.PIDFile)
|
||||
fmt.Println("agent is not running (stale pid file removed)")
|
||||
return nil
|
||||
}
|
||||
if err := signalTerminate(pid); err != nil {
|
||||
return fmt.Errorf("stop pid %d: %w", pid, err)
|
||||
}
|
||||
deadline := time.Now().Add(8 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if !signalAlive(pid) {
|
||||
removePID(cfg.PIDFile)
|
||||
fmt.Printf("agent stopped (was pid %d)\n", pid)
|
||||
return nil
|
||||
}
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
_ = signalKill(pid)
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
removePID(cfg.PIDFile)
|
||||
fmt.Printf("agent killed (pid %d)\n", pid)
|
||||
return nil
|
||||
}
|
||||
|
||||
func restartDaemonCmd(args []string) error {
|
||||
_ = stopDaemonCmd(args)
|
||||
return startDaemonCmd(args)
|
||||
}
|
||||
|
||||
// loadCfgWithPath returns config and the resolved --config path (may be empty).
|
||||
func loadCfgWithPath(sub string, args []string) (config.Config, string) {
|
||||
fs := flag.NewFlagSet(sub, flag.ExitOnError)
|
||||
cfgPath := fs.String("config", "", "path to agent.yaml")
|
||||
_ = fs.Parse(args)
|
||||
path := strings.TrimSpace(*cfgPath)
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "[!]", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if path == "" {
|
||||
// Mirror config.Load default discovery for daemon child argv.
|
||||
path = defaultConfigPath()
|
||||
} else if !filepath.IsAbs(path) {
|
||||
abs, err := filepath.Abs(path)
|
||||
if err == nil {
|
||||
path = abs
|
||||
}
|
||||
}
|
||||
return cfg, path
|
||||
}
|
||||
|
||||
// defaultConfigPath matches config.Load("") discovery so the background child
|
||||
// reopens the same yaml the parent resolved.
|
||||
func defaultConfigPath() string {
|
||||
return filepath.Join(repo.Root(), "apps", "agent", "agent.yaml")
|
||||
}
|
||||
|
|
@ -1,37 +0,0 @@
|
|||
//go:build unix
|
||||
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func detachProcess(cmd *exec.Cmd) {
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
|
||||
}
|
||||
|
||||
func signalAlive(pid int) bool {
|
||||
p, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return p.Signal(syscall.Signal(0)) == nil
|
||||
}
|
||||
|
||||
func signalTerminate(pid int) error {
|
||||
p, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.Signal(syscall.SIGTERM)
|
||||
}
|
||||
|
||||
func signalKill(pid int) error {
|
||||
p, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.Signal(syscall.SIGKILL)
|
||||
}
|
||||
|
|
@ -1,46 +0,0 @@
|
|||
//go:build windows
|
||||
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func detachProcess(cmd *exec.Cmd) {
|
||||
// CREATE_NEW_PROCESS_GROUP so stop can target the child; keep stdio so
|
||||
// stdout/stderr still reach the log file opened by the parent.
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{
|
||||
CreationFlags: windows.CREATE_NEW_PROCESS_GROUP,
|
||||
}
|
||||
}
|
||||
|
||||
func signalAlive(pid int) bool {
|
||||
// On Windows, FindProcess always succeeds; use OpenProcess exit code instead.
|
||||
h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer windows.CloseHandle(h)
|
||||
var code uint32
|
||||
if err := windows.GetExitCodeProcess(h, &code); err != nil {
|
||||
return false
|
||||
}
|
||||
const stillActive = 259 // STILL_ACTIVE
|
||||
return code == stillActive
|
||||
}
|
||||
|
||||
func signalTerminate(pid int) error {
|
||||
p, err := os.FindProcess(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return p.Kill()
|
||||
}
|
||||
|
||||
func signalKill(pid int) error {
|
||||
return signalTerminate(pid)
|
||||
}
|
||||
|
|
@ -1,282 +0,0 @@
|
|||
package agentcmd
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/apps/agent/internal/config"
|
||||
"streamd/repo"
|
||||
)
|
||||
|
||||
const (
|
||||
releaseBaseURL = "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download"
|
||||
defaultChannel = "stable"
|
||||
)
|
||||
|
||||
// errUpdateDeferred means the binary swap finishes after process exit (Windows self-update).
|
||||
var errUpdateDeferred = fmt.Errorf("update deferred until process exit")
|
||||
|
||||
func defaultAssetName() string {
|
||||
switch runtime.GOOS {
|
||||
case "linux":
|
||||
switch runtime.GOARCH {
|
||||
case "amd64":
|
||||
return "streamd-linux-amd64"
|
||||
case "arm64":
|
||||
return "streamd-linux-arm64"
|
||||
}
|
||||
case "darwin":
|
||||
switch runtime.GOARCH {
|
||||
case "amd64":
|
||||
return "streamd-darwin-amd64"
|
||||
case "arm64":
|
||||
return "streamd-darwin-arm64"
|
||||
}
|
||||
case "windows":
|
||||
switch runtime.GOARCH {
|
||||
case "amd64":
|
||||
return "streamd-windows-amd64.exe"
|
||||
case "arm64":
|
||||
return "streamd-windows-arm64.exe"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func updateURL(base, ref, asset string) string {
|
||||
base = strings.TrimRight(base, "/")
|
||||
return fmt.Sprintf("%s/%s/%s", base, ref, asset)
|
||||
}
|
||||
|
||||
func updateDaemonCmd(args []string) error {
|
||||
fs := flag.NewFlagSet("update", flag.ExitOnError)
|
||||
cfgPath := fs.String("config", "", "path to agent.yaml")
|
||||
beta := fs.Bool("beta", false, "use beta channel")
|
||||
tag := fs.String("tag", "", "pin to release tag (e.g. v0.2.1)")
|
||||
noRestart := fs.Bool("no-restart", false, "install only; do not start agent")
|
||||
keep := fs.Int("keep", -1, "archived binaries to keep under old/ (-1 = config)")
|
||||
_ = fs.Parse(args)
|
||||
|
||||
path := strings.TrimSpace(*cfgPath)
|
||||
cfg, err := config.Load(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if path == "" {
|
||||
path = defaultConfigPath()
|
||||
} else if !filepath.IsAbs(path) {
|
||||
if abs, err := filepath.Abs(path); err == nil {
|
||||
path = abs
|
||||
}
|
||||
}
|
||||
|
||||
channel := cfg.Channel
|
||||
if channel == "" {
|
||||
channel = defaultChannel
|
||||
}
|
||||
if *beta {
|
||||
channel = "beta"
|
||||
}
|
||||
ref := channel
|
||||
if strings.TrimSpace(*tag) != "" {
|
||||
ref = strings.TrimSpace(*tag)
|
||||
}
|
||||
asset := cfg.Asset
|
||||
if asset == "" {
|
||||
asset = defaultAssetName()
|
||||
}
|
||||
if asset == "" {
|
||||
return fmt.Errorf("unsupported platform %s/%s — set asset: in agent.yaml", runtime.GOOS, runtime.GOARCH)
|
||||
}
|
||||
keepN := 10
|
||||
if cfg.KeepOld != nil {
|
||||
keepN = *cfg.KeepOld
|
||||
}
|
||||
if *keep >= 0 {
|
||||
keepN = *keep
|
||||
}
|
||||
|
||||
installRoot := repo.Root()
|
||||
url := updateURL(releaseBaseURL, ref, asset)
|
||||
fmt.Printf("agent update: downloading %s\n", url)
|
||||
|
||||
tmp, err := downloadToTemp(installRoot, url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(tmp)
|
||||
|
||||
if err := smokeTestBinary(tmp); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
|
||||
exe = resolved
|
||||
}
|
||||
target := exe
|
||||
wantName := "streamd"
|
||||
if runtime.GOOS == "windows" {
|
||||
wantName = "streamd.exe"
|
||||
}
|
||||
// Prefer well-known names in the install / Downloads tree.
|
||||
for _, candidate := range []string{
|
||||
filepath.Join(installRoot, wantName),
|
||||
filepath.Join(installRoot, "streamd-windows-amd64.exe"),
|
||||
filepath.Join(installRoot, "streamd-linux-amd64"),
|
||||
filepath.Join(installRoot, "bin", wantName),
|
||||
} {
|
||||
if st, err := os.Stat(candidate); err == nil && !st.IsDir() {
|
||||
target = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
// If the running exe is already a streamd binary in this tree, prefer it.
|
||||
if strings.Contains(strings.ToLower(filepath.Base(exe)), "streamd") {
|
||||
if st, err := os.Stat(exe); err == nil && !st.IsDir() {
|
||||
target = exe
|
||||
}
|
||||
}
|
||||
|
||||
if _, ok := runningPID(cfg); ok {
|
||||
fmt.Println("agent update: stopping running agent…")
|
||||
if err := stopDaemonCmd([]string{"--config", path}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
oldDir := filepath.Join(filepath.Dir(target), "old")
|
||||
if err := os.MkdirAll(oldDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
stamp := time.Now().UTC().Format("20060102T150405Z")
|
||||
archive := filepath.Join(oldDir, "streamd."+stamp)
|
||||
if runtime.GOOS == "windows" {
|
||||
archive += ".exe"
|
||||
}
|
||||
if _, err := os.Stat(archive); err == nil {
|
||||
archive += "." + fmt.Sprint(os.Getpid())
|
||||
}
|
||||
|
||||
if *noRestart {
|
||||
_ = os.Setenv("STREAMD_UPDATE_RESTART", "0")
|
||||
} else {
|
||||
_ = os.Setenv("STREAMD_UPDATE_RESTART", "1")
|
||||
_ = os.Setenv("STREAMD_UPDATE_AGENT_CONFIG", path)
|
||||
}
|
||||
if err := replaceBinary(target, tmp, archive); err != nil {
|
||||
if err == errUpdateDeferred {
|
||||
return nil // helper finishes after exit; treat as success for CLI
|
||||
}
|
||||
return err
|
||||
}
|
||||
fmt.Printf("agent update: archived previous → %s\n", archive)
|
||||
fmt.Printf("agent update: installed %s (%s)\n", target, ref)
|
||||
pruneOldBinaries(oldDir, keepN)
|
||||
|
||||
if *noRestart {
|
||||
fmt.Println("agent update: done (--no-restart). Start with: streamd agent start")
|
||||
return nil
|
||||
}
|
||||
fmt.Println("agent update: starting…")
|
||||
return startDaemonCmd([]string{"--config", path})
|
||||
}
|
||||
|
||||
func downloadToTemp(dir, url string) (string, error) {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", err
|
||||
}
|
||||
f, err := os.CreateTemp(dir, ".streamd-download-*")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path := f.Name()
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
_ = os.Remove(path)
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
_ = f.Close()
|
||||
_ = os.Remove(path)
|
||||
return "", fmt.Errorf("download %s: HTTP %s", url, resp.Status)
|
||||
}
|
||||
n, err := io.Copy(f, resp.Body)
|
||||
closeErr := f.Close()
|
||||
if err != nil {
|
||||
_ = os.Remove(path)
|
||||
return "", err
|
||||
}
|
||||
if closeErr != nil {
|
||||
_ = os.Remove(path)
|
||||
return "", closeErr
|
||||
}
|
||||
if n < 1024 {
|
||||
_ = os.Remove(path)
|
||||
return "", fmt.Errorf("download too small (%d bytes) — check URL %s", n, url)
|
||||
}
|
||||
head, _ := os.ReadFile(path)
|
||||
if len(head) > 32 {
|
||||
h := strings.ToLower(string(head[:32]))
|
||||
if strings.Contains(h, "<!doctype") || strings.Contains(h, "<html") {
|
||||
_ = os.Remove(path)
|
||||
return "", fmt.Errorf("download looks like HTML, not a binary: %s", url)
|
||||
}
|
||||
}
|
||||
_ = os.Chmod(path, 0o755)
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func smokeTestBinary(path string) error {
|
||||
cmd := exec.Command(path, "help")
|
||||
out, err := cmd.CombinedOutput()
|
||||
text := string(out)
|
||||
if err != nil {
|
||||
if !strings.Contains(text, "serve") && !strings.Contains(text, "agent") && !strings.Contains(text, "streamd") {
|
||||
return fmt.Errorf("new binary failed smoke test: %w\n%s", err, out)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func pruneOldBinaries(oldDir string, keep int) {
|
||||
if keep <= 0 {
|
||||
return
|
||||
}
|
||||
ents, err := os.ReadDir(oldDir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var names []string
|
||||
for _, e := range ents {
|
||||
if e.IsDir() {
|
||||
continue
|
||||
}
|
||||
n := e.Name()
|
||||
if strings.HasPrefix(n, "streamd.") {
|
||||
names = append(names, n)
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
if len(names) <= keep {
|
||||
return
|
||||
}
|
||||
for _, n := range names[:len(names)-keep] {
|
||||
_ = os.Remove(filepath.Join(oldDir, n))
|
||||
fmt.Printf("agent update: pruned %s\n", filepath.Join(oldDir, n))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
//go:build unix
|
||||
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// replaceBinary moves the live binary to archive, then moves next into place.
|
||||
func replaceBinary(target, next, archive string) error {
|
||||
if err := os.Rename(target, archive); err != nil {
|
||||
return fmt.Errorf("archive current binary: %w", err)
|
||||
}
|
||||
if err := os.Rename(next, target); err != nil {
|
||||
_ = os.Rename(archive, target)
|
||||
return fmt.Errorf("install new binary: %w", err)
|
||||
}
|
||||
_ = os.Chmod(target, 0o755)
|
||||
return nil
|
||||
}
|
||||
|
|
@ -1,125 +0,0 @@
|
|||
//go:build windows
|
||||
|
||||
package agentcmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
// replaceBinary on Windows cannot overwrite the running updater exe. Strategy:
|
||||
// 1. Move target → archive when target is not our own running image.
|
||||
// 2. If target is us, write next beside as *.new and spawn a helper cmd that
|
||||
// waits for this PID to exit, then swaps and optionally starts the agent.
|
||||
func replaceBinary(target, next, archive string) error {
|
||||
self, _ := os.Executable()
|
||||
if resolved, err := filepath.EvalSymlinks(self); err == nil {
|
||||
self = resolved
|
||||
}
|
||||
same, _ := sameFile(self, target)
|
||||
|
||||
if !same {
|
||||
if err := os.Rename(target, archive); err != nil {
|
||||
if err2 := copyFile(target, archive); err2 != nil {
|
||||
return fmt.Errorf("archive current binary: %v / %w", err, err2)
|
||||
}
|
||||
_ = os.Remove(target)
|
||||
}
|
||||
if err := os.Rename(next, target); err != nil {
|
||||
if err2 := copyFile(next, target); err2 != nil {
|
||||
_ = os.Rename(archive, target)
|
||||
return fmt.Errorf("install new binary: %v / %w", err, err2)
|
||||
}
|
||||
_ = os.Remove(next)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
newPath := target + ".new"
|
||||
_ = os.Remove(newPath)
|
||||
if err := os.Rename(next, newPath); err != nil {
|
||||
if err2 := copyFile(next, newPath); err2 != nil {
|
||||
return fmt.Errorf("stage new binary: %v / %w", err, err2)
|
||||
}
|
||||
_ = os.Remove(next)
|
||||
}
|
||||
|
||||
helper := filepath.Join(filepath.Dir(target), "streamd-agent-update-finish.cmd")
|
||||
pid := os.Getpid()
|
||||
startLine := ""
|
||||
if os.Getenv("STREAMD_UPDATE_RESTART") != "0" {
|
||||
cfg := os.Getenv("STREAMD_UPDATE_AGENT_CONFIG")
|
||||
if cfg != "" {
|
||||
startLine = fmt.Sprintf("\"%s\" agent start --config \"%s\"\r\n", escapeCmd(target), escapeCmd(cfg))
|
||||
} else {
|
||||
startLine = fmt.Sprintf("\"%s\" agent start\r\n", escapeCmd(target))
|
||||
}
|
||||
}
|
||||
script := fmt.Sprintf(""+
|
||||
"@echo off\r\n"+
|
||||
":wait\r\n"+
|
||||
"timeout /t 1 /nobreak >nul\r\n"+
|
||||
"tasklist /FI \"PID eq %d\" 2>nul | find \"%d\" >nul\r\n"+
|
||||
"if not errorlevel 1 goto wait\r\n"+
|
||||
"move /Y \"%s\" \"%s\"\r\n"+
|
||||
"move /Y \"%s\" \"%s\"\r\n"+
|
||||
"%s"+
|
||||
"del \"%%~f0\"\r\n",
|
||||
pid, pid,
|
||||
escapeCmd(target), escapeCmd(archive),
|
||||
escapeCmd(newPath), escapeCmd(target),
|
||||
startLine,
|
||||
)
|
||||
if err := os.WriteFile(helper, []byte(script), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
cmd := exec.Command("cmd.exe", "/C", helper)
|
||||
cmd.Stdout = nil
|
||||
cmd.Stderr = nil
|
||||
detachProcess(cmd)
|
||||
if err := cmd.Start(); err != nil {
|
||||
return fmt.Errorf("start update helper: %w", err)
|
||||
}
|
||||
_ = cmd.Process.Release()
|
||||
fmt.Println("agent update: scheduled file swap after this process exits")
|
||||
fmt.Println("agent update: agent will restart automatically in 1–2s")
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
return errUpdateDeferred
|
||||
}
|
||||
|
||||
func escapeCmd(p string) string {
|
||||
return p
|
||||
}
|
||||
|
||||
func sameFile(a, b string) (bool, error) {
|
||||
absA, err := filepath.Abs(a)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
absB, err := filepath.Abs(b)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return filepath.Clean(absA) == filepath.Clean(absB), nil
|
||||
}
|
||||
|
||||
func copyFile(src, dst string) error {
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer in.Close()
|
||||
out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, copyErr := out.ReadFrom(in)
|
||||
closeErr := out.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
return closeErr
|
||||
}
|
||||
|
|
@ -1,12 +1,12 @@
|
|||
module streamd/apps/agent
|
||||
module drmdecryption/apps/agent
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
drmdecryption v0.0.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
modernc.org/sqlite v1.34.5
|
||||
streamd v0.0.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
|
@ -15,10 +15,11 @@ require (
|
|||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
modernc.org/libc v1.55.3 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.8.0 // indirect
|
||||
)
|
||||
|
||||
replace streamd => ../pkg
|
||||
replace drmdecryption => ../pkg
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
|
|
@ -12,6 +14,8 @@ github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdh
|
|||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
|
||||
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
|
||||
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
|
||||
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
|
|
@ -19,6 +23,8 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
|||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
|
||||
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import (
|
|||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
|
@ -184,10 +183,6 @@ type ModuleInfo struct {
|
|||
Name string `json:"name"`
|
||||
HasYAML bool `json:"has_yaml"`
|
||||
YAMLSHA256 string `json:"yaml_sha256,omitempty"`
|
||||
HasPackage bool `json:"has_package"`
|
||||
PackageSHA256 string `json:"package_sha256,omitempty"`
|
||||
Arches []string `json:"arches,omitempty"`
|
||||
SizeBytes int64 `json:"size_bytes,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Client) ListModules() ([]ModuleInfo, error) {
|
||||
|
|
@ -204,64 +199,30 @@ func (c *Client) ListModules() ([]ModuleInfo, error) {
|
|||
return wrap.Modules, nil
|
||||
}
|
||||
|
||||
// GetModuleYAML downloads raw module.yaml bytes for name.
|
||||
func (c *Client) GetModuleYAML(name string) ([]byte, error) {
|
||||
req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/yaml", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.setHeaders(req)
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
|
||||
if resp.StatusCode >= 300 {
|
||||
return nil, c.statusError(http.MethodGet, "/api/modules/"+name+"/yaml", resp, body)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// DownloadModulePackage writes the module zip to destPath.
|
||||
func (c *Client) DownloadModulePackage(name, destPath string) error {
|
||||
req, err := http.NewRequest(http.MethodGet, c.BaseURL+"/api/modules/"+name+"/package", nil)
|
||||
// PutModuleYAML uploads raw module.yaml bytes for name (Content-Type text/yaml).
|
||||
func (c *Client) PutModuleYAML(name string, yamlBytes []byte) error {
|
||||
req, err := http.NewRequest(http.MethodPut, c.BaseURL+"/api/modules/"+name, bytes.NewReader(yamlBytes))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/yaml")
|
||||
c.setHeaders(req)
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode >= 300 {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
return c.statusError(http.MethodGet, "/api/modules/"+name+"/package", resp, body)
|
||||
if resp.StatusCode >= 300 {
|
||||
return c.statusError(http.MethodPut, "/api/modules/"+name, resp, body)
|
||||
}
|
||||
tmp := destPath + ".partial"
|
||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(f, io.LimitReader(resp.Body, 100<<20))
|
||||
closeErr := f.Close()
|
||||
if copyErr != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return copyErr
|
||||
}
|
||||
if closeErr != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return closeErr
|
||||
}
|
||||
_ = os.Remove(destPath)
|
||||
return os.Rename(tmp, destPath)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) setHeaders(req *http.Request) {
|
||||
ua := c.UserAgent
|
||||
if ua == "" {
|
||||
ua = "streamd-agent/" + Version
|
||||
ua = "drm-agent/" + Version
|
||||
}
|
||||
req.Header.Set("User-Agent", ua)
|
||||
if c.Token != "" {
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import (
|
|||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"streamd/repo"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
|
|
@ -27,25 +27,14 @@ type Config struct {
|
|||
WVD string `yaml:"wvd"` // path to .wvd device file (required for key fetch)
|
||||
UserAgent string `yaml:"user_agent"`
|
||||
AgentID string `yaml:"agent_id"`
|
||||
// SyncModules pulls modules from streamd into the local cache when missing/stale.
|
||||
// SyncModules pushes local modules/<name>/module.yaml to streamd when missing/stale.
|
||||
SyncModules bool `yaml:"sync_modules"`
|
||||
ModulesDir string `yaml:"modules_dir"` // empty = <data_dir>/modules
|
||||
ModulesDir string `yaml:"modules_dir"` // empty = repo modules/
|
||||
ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"`
|
||||
ModulesPrune bool `yaml:"modules_prune"` // remove local modules absent from panel
|
||||
// OnDemandPriority lets a capture that streamd pushed — a viewer waking
|
||||
// an on-demand stream, or a scheduled event about to start — jump ahead
|
||||
// of routine refreshes in the queue.
|
||||
OnDemandPriority *bool `yaml:"ondemand_priority"`
|
||||
// JobBackoff enables exponential retry delays after a failed capture
|
||||
// (1m, 2m, 4m, 8m…). Default off — a single agent should retry ASAP.
|
||||
// Set job_backoff: true when several agents share the same streams.
|
||||
JobBackoff *bool `yaml:"job_backoff"`
|
||||
// Daemon / update (streamd agent start|stop|update)
|
||||
LogFile string `yaml:"log_file"` // default agent.log next to config / install root
|
||||
PIDFile string `yaml:"pid_file"` // default agent.pid
|
||||
Channel string `yaml:"channel"` // stable|beta for agent update
|
||||
Asset string `yaml:"asset"` // optional streamd-* asset override
|
||||
KeepOld *int `yaml:"keep_old"` // archived binaries under old/ (default 10)
|
||||
}
|
||||
|
||||
// PushedCapturesArePriority reports whether pushed captures jump the queue.
|
||||
|
|
@ -54,12 +43,6 @@ func (c Config) PushedCapturesArePriority() bool {
|
|||
return c.OnDemandPriority == nil || *c.OnDemandPriority
|
||||
}
|
||||
|
||||
// JobBackoffEnabled is the exponential multi-agent retry delay.
|
||||
// Defaults to false so a lone agent retries immediately after a failure.
|
||||
func (c Config) JobBackoffEnabled() bool {
|
||||
return c.JobBackoff != nil && *c.JobBackoff
|
||||
}
|
||||
|
||||
func (c Config) PollInterval() time.Duration {
|
||||
if c.PollIntervalSec <= 0 {
|
||||
return 30 * time.Second
|
||||
|
|
@ -141,36 +124,12 @@ func applyDefaults(cfg Config, root string) Config {
|
|||
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
|
||||
cfg.WVD = filepath.Join(root, cfg.WVD)
|
||||
}
|
||||
if cfg.Python != "" && !filepath.IsAbs(cfg.Python) {
|
||||
cfg.Python = filepath.Join(root, cfg.Python)
|
||||
}
|
||||
if cfg.ModulesDir == "" {
|
||||
cfg.ModulesDir = filepath.Join(cfg.DataDir, "modules")
|
||||
} else if !filepath.IsAbs(cfg.ModulesDir) {
|
||||
if cfg.ModulesDir != "" && !filepath.IsAbs(cfg.ModulesDir) {
|
||||
cfg.ModulesDir = filepath.Join(root, cfg.ModulesDir)
|
||||
}
|
||||
if cfg.ModulesSyncIntervalSec <= 0 {
|
||||
cfg.ModulesSyncIntervalSec = 300
|
||||
}
|
||||
if cfg.LogFile == "" {
|
||||
cfg.LogFile = "agent.log"
|
||||
}
|
||||
if !filepath.IsAbs(cfg.LogFile) {
|
||||
cfg.LogFile = filepath.Join(root, cfg.LogFile)
|
||||
}
|
||||
if cfg.PIDFile == "" {
|
||||
cfg.PIDFile = "agent.pid"
|
||||
}
|
||||
if !filepath.IsAbs(cfg.PIDFile) {
|
||||
cfg.PIDFile = filepath.Join(root, cfg.PIDFile)
|
||||
}
|
||||
if cfg.Channel == "" {
|
||||
cfg.Channel = "stable"
|
||||
}
|
||||
if cfg.KeepOld == nil {
|
||||
k := 10
|
||||
cfg.KeepOld = &k
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import (
|
|||
"fmt"
|
||||
"sync"
|
||||
|
||||
"streamd/adb"
|
||||
"drmdecryption/adb"
|
||||
)
|
||||
|
||||
// Pool tracks free/busy ADB devices. Never installs apps.
|
||||
|
|
|
|||
|
|
@ -1,32 +1,26 @@
|
|||
// Package modsync pulls provider modules from streamd into a local cache.
|
||||
// The panel is the source of truth: agents download package.zip when the
|
||||
// package hash changes, and module.yaml alone when only YAML changed.
|
||||
// Package modsync pushes local modules/<name>/module.yaml to streamd
|
||||
// when the remote copy is missing or the SHA-256 differs.
|
||||
package modsync
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/apps/agent/internal/client"
|
||||
"streamd/modhost"
|
||||
"streamd/repo"
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
// Syncer keeps the local modules cache aligned with streamd.
|
||||
// Syncer compares local module.yaml files to streamd and PUTs updates.
|
||||
type Syncer struct {
|
||||
API *client.Client
|
||||
ModulesDir string // empty = <data_dir>/modules resolved by caller, or modhost default
|
||||
ModulesDir string // empty = modhost.ModulesDir(repo.Root())
|
||||
Interval time.Duration
|
||||
Prune bool // remove local modules absent from the panel
|
||||
Log *log.Logger
|
||||
}
|
||||
|
||||
|
|
@ -37,10 +31,15 @@ func (s *Syncer) modulesDir() string {
|
|||
return modhost.ModulesDir(repo.Root())
|
||||
}
|
||||
|
||||
// Once pulls every remote module that is missing or stale locally.
|
||||
// Once uploads every local module.yaml that is missing or stale on streamd.
|
||||
func (s *Syncer) Once() error {
|
||||
dir := s.modulesDir()
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
ents, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
s.logf("modules sync: no local dir %s", dir)
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
|
|
@ -48,139 +47,42 @@ func (s *Syncer) Once() error {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
byName := make(map[string]client.ModuleInfo, len(remote))
|
||||
for _, m := range remote {
|
||||
seen[m.Name] = struct{}{}
|
||||
if err := s.syncOne(dir, m); err != nil {
|
||||
s.logf("modules sync: %s: %v", m.Name, err)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if s.Prune {
|
||||
s.pruneLocal(dir, seen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Syncer) syncOne(dir string, m client.ModuleInfo) error {
|
||||
modDir := filepath.Join(dir, m.Name)
|
||||
localPkg := localSHA(filepath.Join(modDir, "package.sha256"))
|
||||
localYAML := ""
|
||||
if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
|
||||
sum := sha256.Sum256(raw)
|
||||
localYAML = hex.EncodeToString(sum[:])
|
||||
byName[m.Name] = m
|
||||
}
|
||||
|
||||
needPackage := m.HasPackage && (localPkg == "" || !strings.EqualFold(localPkg, m.PackageSHA256))
|
||||
needYAML := m.HasYAML && (localYAML == "" || !strings.EqualFold(localYAML, m.YAMLSHA256))
|
||||
|
||||
if !needPackage && !needYAML {
|
||||
return nil
|
||||
}
|
||||
|
||||
if needPackage {
|
||||
if !m.HasPackage {
|
||||
return fmt.Errorf("panel has no package.zip")
|
||||
}
|
||||
if err := s.pullPackage(modDir, m); err != nil {
|
||||
return err
|
||||
}
|
||||
s.logf("modules sync: pulled package %s", m.Name)
|
||||
// Package extract includes yaml; refresh localYAML check.
|
||||
if raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")); err == nil {
|
||||
sum := sha256.Sum256(raw)
|
||||
localYAML = hex.EncodeToString(sum[:])
|
||||
needYAML = m.HasYAML && !strings.EqualFold(localYAML, m.YAMLSHA256)
|
||||
} else {
|
||||
needYAML = m.HasYAML
|
||||
}
|
||||
}
|
||||
|
||||
if needYAML {
|
||||
raw, err := s.API.GetModuleYAML(m.Name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(modDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := atomicWrite(filepath.Join(modDir, "module.yaml"), raw, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
s.logf("modules sync: updated yaml %s", m.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Syncer) pullPackage(modDir string, m client.ModuleInfo) error {
|
||||
if err := os.MkdirAll(modDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
zipPath := filepath.Join(modDir, "package.zip")
|
||||
if err := s.API.DownloadModulePackage(m.Name, zipPath); err != nil {
|
||||
return err
|
||||
}
|
||||
sum, err := fileSHA256(zipPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if m.PackageSHA256 != "" && !strings.EqualFold(sum, m.PackageSHA256) {
|
||||
return fmt.Errorf("package sha mismatch: got %s want %s", sum, m.PackageSHA256)
|
||||
}
|
||||
|
||||
extractDir := filepath.Join(modDir, ".extract-tmp")
|
||||
_ = os.RemoveAll(extractDir)
|
||||
if err := os.MkdirAll(extractDir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(extractDir)
|
||||
|
||||
if err := unzipSafe(zipPath, extractDir); err != nil {
|
||||
return err
|
||||
}
|
||||
// Flatten a single top-level folder (bbc/...) into extractDir root.
|
||||
if err := flattenSingleRoot(extractDir); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := promoteHostBinary(extractDir, m.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Move extracted contents into modDir (keep package.zip + sha sidecar).
|
||||
ents, err := os.ReadDir(extractDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range ents {
|
||||
src := filepath.Join(extractDir, e.Name())
|
||||
dst := filepath.Join(modDir, e.Name())
|
||||
_ = os.RemoveAll(dst)
|
||||
if err := os.Rename(src, dst); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return atomicWrite(filepath.Join(modDir, "package.sha256"), []byte(sum+"\n"), 0o644)
|
||||
}
|
||||
|
||||
func (s *Syncer) pruneLocal(dir string, keep map[string]struct{}) {
|
||||
ents, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, e := range ents {
|
||||
if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
|
||||
continue
|
||||
}
|
||||
if _, ok := keep[e.Name()]; ok {
|
||||
name := e.Name()
|
||||
yamlPath := filepath.Join(dir, name, "module.yaml")
|
||||
raw, err := os.ReadFile(yamlPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
continue
|
||||
}
|
||||
path := filepath.Join(dir, e.Name())
|
||||
if err := os.RemoveAll(path); err != nil {
|
||||
s.logf("modules sync: prune %s: %v", e.Name(), err)
|
||||
s.logf("modules sync: read %s: %v", yamlPath, err)
|
||||
continue
|
||||
}
|
||||
s.logf("modules sync: pruned %s", e.Name())
|
||||
sum := sha256.Sum256(raw)
|
||||
localSHA := hex.EncodeToString(sum[:])
|
||||
rm, ok := byName[name]
|
||||
if ok && rm.HasYAML && strings.EqualFold(rm.YAMLSHA256, localSHA) {
|
||||
continue
|
||||
}
|
||||
if err := s.API.PutModuleYAML(name, raw); err != nil {
|
||||
s.logf("modules sync: PUT %s: %v", name, err)
|
||||
continue
|
||||
}
|
||||
if !ok || !rm.HasYAML {
|
||||
s.logf("modules sync: uploaded %s (new)", name)
|
||||
} else {
|
||||
s.logf("modules sync: updated %s", name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Loop runs Once immediately, then on Interval until stop closes.
|
||||
|
|
@ -217,161 +119,3 @@ func (s *Syncer) logf(format string, args ...any) {
|
|||
}
|
||||
log.Printf(format, args...)
|
||||
}
|
||||
|
||||
func localSHA(path string) string {
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
|
||||
func fileSHA256(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
h := sha256.New()
|
||||
if _, err := io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func atomicWrite(path string, data []byte, mode os.FileMode) error {
|
||||
tmp := path + ".tmp"
|
||||
if err := os.WriteFile(tmp, data, mode); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Rename(tmp, path); err != nil {
|
||||
_ = os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unzipSafe(zipPath, destDir string) error {
|
||||
r, err := zip.OpenReader(zipPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer r.Close()
|
||||
absDest, err := filepath.Abs(destDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, f := range r.File {
|
||||
name := strings.ReplaceAll(f.Name, "\\", "/")
|
||||
name = strings.TrimPrefix(name, "./")
|
||||
if name == "" || strings.HasPrefix(name, "__MACOSX/") || strings.HasSuffix(name, ".DS_Store") {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(name, "..") {
|
||||
return fmt.Errorf("zip slip: %s", f.Name)
|
||||
}
|
||||
target := filepath.Join(destDir, filepath.FromSlash(name))
|
||||
absTarget, err := filepath.Abs(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rel, err := filepath.Rel(absDest, absTarget)
|
||||
if err != nil || strings.HasPrefix(rel, "..") {
|
||||
return fmt.Errorf("zip slip: %s", f.Name)
|
||||
}
|
||||
if f.FileInfo().IsDir() || strings.HasSuffix(name, "/") {
|
||||
if err := os.MkdirAll(target, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
rc, err := f.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mode := os.FileMode(0o644)
|
||||
if f.Mode()&0o111 != 0 {
|
||||
mode = 0o755
|
||||
}
|
||||
out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
|
||||
if err != nil {
|
||||
_ = rc.Close()
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(out, rc)
|
||||
_ = out.Close()
|
||||
_ = rc.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func flattenSingleRoot(dir string) error {
|
||||
ents, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var dirs []os.DirEntry
|
||||
var files []os.DirEntry
|
||||
for _, e := range ents {
|
||||
if strings.HasPrefix(e.Name(), ".") {
|
||||
continue
|
||||
}
|
||||
if e.IsDir() {
|
||||
dirs = append(dirs, e)
|
||||
} else {
|
||||
files = append(files, e)
|
||||
}
|
||||
}
|
||||
if len(files) > 0 || len(dirs) != 1 {
|
||||
return nil
|
||||
}
|
||||
root := filepath.Join(dir, dirs[0].Name())
|
||||
inner, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range inner {
|
||||
src := filepath.Join(root, e.Name())
|
||||
dst := filepath.Join(dir, e.Name())
|
||||
if err := os.Rename(src, dst); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return os.RemoveAll(root)
|
||||
}
|
||||
|
||||
func promoteHostBinary(modDir, name string) error {
|
||||
want := name
|
||||
if runtime.GOOS == "windows" {
|
||||
want += ".exe"
|
||||
}
|
||||
dest := filepath.Join(modDir, ".bin", want)
|
||||
if st, err := os.Stat(dest); err == nil && !st.IsDir() {
|
||||
return nil
|
||||
}
|
||||
src := filepath.Join(modDir, ".bin", runtime.GOOS+"-"+runtime.GOARCH, want)
|
||||
in, err := os.Open(src)
|
||||
if err != nil {
|
||||
return nil // soft: host arch may be missing
|
||||
}
|
||||
defer in.Close()
|
||||
if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, copyErr := io.Copy(out, in)
|
||||
closeErr := out.Close()
|
||||
if copyErr != nil {
|
||||
return copyErr
|
||||
}
|
||||
return closeErr
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,154 +0,0 @@
|
|||
package modsync
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"streamd/apps/agent/internal/client"
|
||||
)
|
||||
|
||||
func TestPullPackageThenYAMLOnly(t *testing.T) {
|
||||
arch := runtime.GOOS + "-" + runtime.GOARCH
|
||||
binName := "demo"
|
||||
if runtime.GOOS == "windows" {
|
||||
binName += ".exe"
|
||||
}
|
||||
zip1 := mustZip(t, map[string][]byte{
|
||||
"module.yaml": []byte("package: a\n"),
|
||||
".bin/" + arch + "/" + binName: []byte("bin-v1"),
|
||||
})
|
||||
sum1 := sha256.Sum256(zip1)
|
||||
pkgSHA1 := hex.EncodeToString(sum1[:])
|
||||
yaml1SHA := sha256Hex([]byte("package: a\n"))
|
||||
|
||||
zip2 := mustZip(t, map[string][]byte{
|
||||
"module.yaml": []byte("package: a\n"),
|
||||
".bin/" + arch + "/" + binName: []byte("bin-v2"),
|
||||
})
|
||||
sum2 := sha256.Sum256(zip2)
|
||||
pkgSHA2 := hex.EncodeToString(sum2[:])
|
||||
|
||||
yamlEdited := []byte("package: a\nchannels: {}\n")
|
||||
yamlEditedSHA := sha256Hex(yamlEdited)
|
||||
|
||||
state := struct {
|
||||
pkg []byte
|
||||
pkgSHA string
|
||||
yaml []byte
|
||||
yamlSHA string
|
||||
}{pkg: zip1, pkgSHA: pkgSHA1, yaml: []byte("package: a\n"), yamlSHA: yaml1SHA}
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.URL.Path == "/api/modules" && r.Method == http.MethodGet:
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"modules": []map[string]any{{
|
||||
"name": "demo",
|
||||
"has_yaml": true,
|
||||
"yaml_sha256": state.yamlSHA,
|
||||
"has_package": true,
|
||||
"package_sha256": state.pkgSHA,
|
||||
}},
|
||||
})
|
||||
case r.URL.Path == "/api/modules/demo/package":
|
||||
w.Header().Set("Content-Type", "application/zip")
|
||||
_, _ = w.Write(state.pkg)
|
||||
case r.URL.Path == "/api/modules/demo/yaml":
|
||||
w.Header().Set("Content-Type", "text/yaml")
|
||||
_, _ = w.Write(state.yaml)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
api := &client.Client{BaseURL: srv.URL, HTTP: srv.Client()}
|
||||
s := &Syncer{API: api, ModulesDir: dir}
|
||||
|
||||
if err := s.Once(); err != nil {
|
||||
t.Fatalf("first sync: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "demo", "module.yaml")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
promoted := filepath.Join(dir, "demo", ".bin", binName)
|
||||
if b, err := os.ReadFile(promoted); err != nil || string(b) != "bin-v1" {
|
||||
t.Fatalf("promoted binary: %v %q", err, b)
|
||||
}
|
||||
|
||||
// YAML-only change on panel.
|
||||
state.yaml = yamlEdited
|
||||
state.yamlSHA = yamlEditedSHA
|
||||
if err := s.Once(); err != nil {
|
||||
t.Fatalf("yaml sync: %v", err)
|
||||
}
|
||||
raw, _ := os.ReadFile(filepath.Join(dir, "demo", "module.yaml"))
|
||||
if !bytes.Equal(raw, yamlEdited) {
|
||||
t.Fatalf("yaml not updated: %s", raw)
|
||||
}
|
||||
if b, _ := os.ReadFile(promoted); string(b) != "bin-v1" {
|
||||
t.Fatalf("binary should be unchanged after yaml-only sync, got %q", b)
|
||||
}
|
||||
|
||||
// Package change.
|
||||
state.pkg = zip2
|
||||
state.pkgSHA = pkgSHA2
|
||||
state.yaml = []byte("package: a\n")
|
||||
state.yamlSHA = yaml1SHA
|
||||
if err := s.Once(); err != nil {
|
||||
t.Fatalf("package sync: %v", err)
|
||||
}
|
||||
if b, _ := os.ReadFile(promoted); string(b) != "bin-v2" {
|
||||
t.Fatalf("binary not updated: %q", b)
|
||||
}
|
||||
}
|
||||
|
||||
func mustZip(t *testing.T, files map[string][]byte) []byte {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
for name, body := range files {
|
||||
w, err := zw.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := w.Write(body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := zw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func sha256Hex(b []byte) string {
|
||||
sum := sha256.Sum256(b)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func TestUnzipSlip(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
var buf bytes.Buffer
|
||||
zw := zip.NewWriter(&buf)
|
||||
w, _ := zw.Create("../evil")
|
||||
_, _ = w.Write([]byte("x"))
|
||||
_ = zw.Close()
|
||||
zipPath := filepath.Join(dir, "bad.zip")
|
||||
_ = os.WriteFile(zipPath, buf.Bytes(), 0o644)
|
||||
err := unzipSafe(zipPath, filepath.Join(dir, "out"))
|
||||
if err == nil || !strings.Contains(err.Error(), "slip") {
|
||||
t.Fatalf("want zip slip error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
|
@ -6,8 +6,8 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/apps/agent/internal/client"
|
||||
"streamd/apps/agent/internal/queue"
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
"drmdecryption/apps/agent/internal/queue"
|
||||
)
|
||||
|
||||
type Poller struct {
|
||||
|
|
|
|||
|
|
@ -232,18 +232,17 @@ func (s *Store) MarkOK(id int64) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// MarkFailed increments attempts. Re-queues unless maxed out.
|
||||
// MarkFailed increments attempts. Re-queues with backoff unless maxed out.
|
||||
// waitingDevice=true keeps status queued without burning an attempt.
|
||||
// backoff is how long to wait before the job is runnable again (0 = immediate).
|
||||
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool, backoff time.Duration) error {
|
||||
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error {
|
||||
j, err := s.Get(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if waitingDevice {
|
||||
_, err = s.DB.Exec(`
|
||||
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`,
|
||||
msg, now(), id)
|
||||
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='' WHERE id=?`,
|
||||
msg, id)
|
||||
return err
|
||||
}
|
||||
attempts := j.Attempts + 1
|
||||
|
|
@ -253,8 +252,9 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i
|
|||
attempts, msg, now(), id)
|
||||
return err
|
||||
}
|
||||
if backoff < 0 {
|
||||
backoff = 0
|
||||
backoff := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
|
||||
if backoff > 15*time.Minute {
|
||||
backoff = 15 * time.Minute
|
||||
}
|
||||
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
|
||||
_, err = s.DB.Exec(`
|
||||
|
|
@ -263,29 +263,6 @@ UPDATE jobs SET status='queued', attempts=?, last_error=?, not_before=?, device_
|
|||
return err
|
||||
}
|
||||
|
||||
// ExponentialBackoff is the old multi-agent delay: 1m, 2m, 4m, 8m (cap 15m).
|
||||
func ExponentialBackoff(attempts int) time.Duration {
|
||||
if attempts < 1 {
|
||||
attempts = 1
|
||||
}
|
||||
d := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
|
||||
if d > 15*time.Minute {
|
||||
d = 15 * time.Minute
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// ClearAllBackoffs makes every queued job runnable now (e.g. agent restart
|
||||
// after fixing modules, or when job_backoff is disabled).
|
||||
func (s *Store) ClearAllBackoffs() (int, error) {
|
||||
res, err := s.DB.Exec(`UPDATE jobs SET not_before=? WHERE status='queued'`, now())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, _ := res.RowsAffected()
|
||||
return int(n), nil
|
||||
}
|
||||
|
||||
func min(a, b int) int {
|
||||
if a < b {
|
||||
return a
|
||||
|
|
|
|||
|
|
@ -7,14 +7,14 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/modhost"
|
||||
"streamd/phonecap"
|
||||
"streamd/repo"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/phonecap"
|
||||
"drmdecryption/repo"
|
||||
|
||||
"streamd/apps/agent/internal/client"
|
||||
"streamd/apps/agent/internal/device"
|
||||
"streamd/apps/agent/internal/poller"
|
||||
"streamd/apps/agent/internal/queue"
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
"drmdecryption/apps/agent/internal/device"
|
||||
"drmdecryption/apps/agent/internal/poller"
|
||||
"drmdecryption/apps/agent/internal/queue"
|
||||
)
|
||||
|
||||
type Worker struct {
|
||||
|
|
@ -27,9 +27,6 @@ type Worker struct {
|
|||
Python string
|
||||
WVD string
|
||||
UserAgent string
|
||||
// JobBackoff enables exponential delays between failed capture attempts.
|
||||
// When false (default), failed jobs are re-queued immediately.
|
||||
JobBackoff bool
|
||||
Log *log.Logger
|
||||
|
||||
lastDelayLog time.Time
|
||||
|
|
@ -70,18 +67,13 @@ func (w *Worker) tick() {
|
|||
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
|
||||
// Config/environment issues — do not burn attempts or multi-minute backoff.
|
||||
w.logf("job=%d waiting: %v", job.ID, err)
|
||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
|
||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), true)
|
||||
return
|
||||
}
|
||||
w.logf("job=%d failed: %v", job.ID, err)
|
||||
w.event(job, client.EventCaptureFailed, err.Error(),
|
||||
map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
|
||||
backoff := time.Duration(0)
|
||||
if w.JobBackoff {
|
||||
backoff = queue.ExponentialBackoff(job.Attempts + 1)
|
||||
w.logf("job=%d re-queue in %s (job_backoff=true)", job.ID, backoff)
|
||||
}
|
||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), false, backoff)
|
||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), false)
|
||||
return
|
||||
}
|
||||
_ = w.Queue.MarkOK(job.ID)
|
||||
|
|
@ -127,8 +119,8 @@ func (w *Worker) runJob(job queue.Job) error {
|
|||
_ = w.Queue.SetDevice(job.ID, serial)
|
||||
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
|
||||
|
||||
// Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
|
||||
if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
|
||||
// Short TTL; /ws/agent heartbeats renew while this process is alive.
|
||||
if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil {
|
||||
return fmt.Errorf("streamd claim: %w", err)
|
||||
}
|
||||
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
|
||||
|
|
@ -148,19 +140,6 @@ func (w *Worker) runJob(job queue.Job) error {
|
|||
return err
|
||||
}
|
||||
|
||||
needsKeys := true
|
||||
if km := strings.ToLower(strings.TrimSpace(a.KeyMode())); km == "none" || km == "clear" {
|
||||
needsKeys = false
|
||||
}
|
||||
hasKey := poller.ValidKeyPair(res.Key)
|
||||
if needsKeys && !hasKey {
|
||||
return fmt.Errorf("refusing to post credentials without valid Widevine key (got mpd=%q key_empty=%v)",
|
||||
trimURL(res.MPD), strings.TrimSpace(res.Key) == "")
|
||||
}
|
||||
if strings.TrimSpace(res.MPD) == "" {
|
||||
return fmt.Errorf("refusing to post credentials without mpd")
|
||||
}
|
||||
|
||||
cred := client.Credentials{
|
||||
MPD: res.MPD,
|
||||
Key: res.Key,
|
||||
|
|
@ -171,25 +150,15 @@ func (w *Worker) runJob(job queue.Job) error {
|
|||
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
|
||||
return fmt.Errorf("post credentials: %w", err)
|
||||
}
|
||||
w.logf("job=%d posted credentials to streamd has_key=%v key_valid=%v mpd=%s",
|
||||
job.ID, strings.TrimSpace(res.Key) != "", hasKey, trimURL(res.MPD))
|
||||
// Report what was captured, never the key itself.
|
||||
w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
|
||||
"device": serial,
|
||||
"has_key": strings.TrimSpace(res.Key) != "",
|
||||
"key_valid": hasKey,
|
||||
"key_valid": poller.ValidKeyPair(res.Key),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func trimURL(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) <= 96 {
|
||||
return s
|
||||
}
|
||||
return s[:96] + "…"
|
||||
}
|
||||
|
||||
// event posts a stream event to streamd. A timeline entry is never worth
|
||||
// failing a capture over, so errors are logged and dropped.
|
||||
func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import (
|
|||
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"streamd/apps/agent/internal/client"
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
)
|
||||
|
||||
// Message is one push from streamd.
|
||||
|
|
@ -42,9 +42,6 @@ type Client struct {
|
|||
// OnStreamChanged is called when a stream was edited, so the agent can
|
||||
// re-poll instead of waiting out its interval.
|
||||
OnStreamChanged func(name, reason string)
|
||||
// OnModulesChanged is called when the panel uploaded/edited/deleted a
|
||||
// module, so the agent can pull without waiting for the sync interval.
|
||||
OnModulesChanged func(name, reason string)
|
||||
|
||||
stop chan struct{}
|
||||
}
|
||||
|
|
@ -114,7 +111,7 @@ func (c *Client) session() error {
|
|||
if c.AgentID != "" {
|
||||
hdr.Set("X-Agent-ID", c.AgentID)
|
||||
}
|
||||
hdr.Set("User-Agent", "streamd-agent/"+client.Version)
|
||||
hdr.Set("User-Agent", "drm-agent/"+client.Version)
|
||||
dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
|
||||
conn, resp, err := dialer.Dial(u.String(), hdr)
|
||||
if err != nil {
|
||||
|
|
@ -193,11 +190,6 @@ func (c *Client) handle(msg Message) {
|
|||
if c.OnStreamChanged != nil {
|
||||
c.OnStreamChanged(msg.StreamName, msg.Reason)
|
||||
}
|
||||
case "modules_changed":
|
||||
c.Log.Printf("ws: modules changed module=%s reason=%s", msg.StreamName, msg.Reason)
|
||||
if c.OnModulesChanged != nil {
|
||||
c.OnModulesChanged(msg.StreamName, msg.Reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# capture
|
||||
|
||||
One-shot phone MITM capture, hosted by the single binary as `streamd capture`.
|
||||
One-shot phone MITM capture, hosted by the single binary as `drm capture`.
|
||||
|
||||
```text
|
||||
apps/capture/
|
||||
|
|
@ -8,17 +8,17 @@ apps/capture/
|
|||
```
|
||||
|
||||
```bash
|
||||
./bin/streamd capture # passive: play anything
|
||||
./bin/streamd capture --app rte # launch, navigate by hand
|
||||
./bin/streamd capture --app rte --channel rteone --auto-play \
|
||||
./bin/drm capture # passive: play anything
|
||||
./bin/drm capture --app rte # launch, navigate by hand
|
||||
./bin/drm capture --app rte --channel rteone --auto-play \
|
||||
--wvd data/device.wvd # fully automated
|
||||
```
|
||||
|
||||
Writes `outputs/<app>/<stamp>/` plus `latest/`. App modules are compiled in, so
|
||||
there is no modules directory to point at; `streamd modules` lists what is available.
|
||||
there is no modules directory to point at; `drm modules` lists what is available.
|
||||
|
||||
**Full guide: [docs/capture.md](../../docs/capture.md)** — device setup, flags,
|
||||
discovering a new app, and troubleshooting.
|
||||
|
||||
The catalog lookup that used to be a separate `tg4info` binary is now the
|
||||
provider-agnostic `streamd catalog` (`apps/cli/catalogcmd`).
|
||||
provider-agnostic `drm catalog` (`apps/cli/catalogcmd`).
|
||||
|
|
|
|||
|
|
@ -12,16 +12,16 @@ import (
|
|||
"time"
|
||||
"unicode"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/app"
|
||||
"streamd/modcfg"
|
||||
"streamd/modhost"
|
||||
"streamd/phonecap"
|
||||
"streamd/repo"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/app"
|
||||
"drmdecryption/modcfg"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/phonecap"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
// Run performs one capture. Providers live under modules/<name>/ and are built
|
||||
// and executed by modhost — they are not linked into streamd.
|
||||
// and executed by modhost — they are not linked into drm.exe.
|
||||
func Run(args []string) error {
|
||||
args = normalizeArgs(args)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,13 @@
|
|||
module streamd/apps/capture
|
||||
module drmdecryption/apps/capture
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require streamd v0.0.0
|
||||
require drmdecryption v0.0.0
|
||||
|
||||
require gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
require (
|
||||
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
replace streamd => ../pkg
|
||||
replace drmdecryption => ../pkg
|
||||
|
|
|
|||
|
|
@ -1,3 +1,11 @@
|
|||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac h1:pNA9PRXGPFURORAsI3IqfQJ4RLsRXqghCFdvypd/4GY=
|
||||
go.starlark.net v0.0.0-20260930220527-d7438c5a85ac/go.mod h1:Iue6g6iirlfLoVi/DYCi5/x0h/bAOuWF3dULTKpt2Vo=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import (
|
|||
"strings"
|
||||
"testing"
|
||||
|
||||
"streamd/apps/capture/capturecmd"
|
||||
"drmdecryption/apps/capture/capturecmd"
|
||||
)
|
||||
|
||||
func TestCaptureRejectsChannelAsApp(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -11,9 +11,9 @@ import (
|
|||
"sort"
|
||||
"strings"
|
||||
|
||||
"streamd/modhost"
|
||||
"streamd/repo"
|
||||
"streamd/session"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/repo"
|
||||
"drmdecryption/session"
|
||||
)
|
||||
|
||||
// Run performs a catalog lookup for one channel.
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
module streamd/apps/cli
|
||||
module drmdecryption/apps/cli
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
streamd v0.0.0
|
||||
streamd/apps/agent v0.0.0
|
||||
streamd/apps/capture v0.0.0
|
||||
streamd/apps/proxy v0.0.0
|
||||
streamd/apps/streamd v0.0.0
|
||||
drmdecryption v0.0.0
|
||||
drmdecryption/apps/agent v0.0.0
|
||||
drmdecryption/apps/capture v0.0.0
|
||||
drmdecryption/apps/proxy v0.0.0
|
||||
drmdecryption/apps/streamd v0.0.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
|
@ -26,9 +26,9 @@ require (
|
|||
)
|
||||
|
||||
replace (
|
||||
streamd => ../pkg
|
||||
streamd/apps/agent => ../agent
|
||||
streamd/apps/capture => ../capture
|
||||
streamd/apps/proxy => ../proxy
|
||||
streamd/apps/streamd => ../streamd
|
||||
drmdecryption => ../pkg
|
||||
drmdecryption/apps/agent => ../agent
|
||||
drmdecryption/apps/capture => ../capture
|
||||
drmdecryption/apps/proxy => ../proxy
|
||||
drmdecryption/apps/streamd => ../streamd
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
// Command streamd is the single entry point for the toolchain: phone capture,
|
||||
// Command drm is the single entry point for the toolchain: phone capture,
|
||||
// catalog lookups, the always-on agent, the streamd control plane and the
|
||||
// on-device MITM. Providers live under modules/<name>/ and are discovered,
|
||||
// built, and executed by the host — they are not linked into this binary.
|
||||
|
|
@ -13,14 +13,14 @@ import (
|
|||
"os"
|
||||
"strings"
|
||||
|
||||
"streamd/apps/agent/agentcmd"
|
||||
"streamd/apps/capture/capturecmd"
|
||||
"streamd/apps/cli/catalogcmd"
|
||||
"streamd/apps/cli/modulescmd"
|
||||
"streamd/apps/proxy/proxyctlcmd"
|
||||
"streamd/apps/streamd/servecmd"
|
||||
"streamd/bootstrap"
|
||||
"streamd/modhost"
|
||||
"drmdecryption/apps/agent/agentcmd"
|
||||
"drmdecryption/apps/capture/capturecmd"
|
||||
"drmdecryption/apps/cli/catalogcmd"
|
||||
"drmdecryption/apps/cli/modulescmd"
|
||||
"drmdecryption/apps/proxy/proxyctlcmd"
|
||||
"drmdecryption/apps/streamd/servecmd"
|
||||
"drmdecryption/bootstrap"
|
||||
"drmdecryption/modhost"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
|
@ -39,12 +39,12 @@ func main() {
|
|||
os.Exit(1)
|
||||
}
|
||||
} else if err := modhost.ApplyEnvModulesDir(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "[!] STREAMD_MODULES_DIR / DRM_MODULES_DIR:", err)
|
||||
fmt.Fprintln(os.Stderr, "[!] DRM_MODULES_DIR:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Materialise apps/, bin/, modules/, outputs/, … next to this exe when
|
||||
// missing so a lone downloaded streamd.exe becomes a usable install tree.
|
||||
// missing so a lone downloaded drm.exe becomes a GitHub-like install tree.
|
||||
if cmd != "help" && cmd != "-h" && cmd != "--help" {
|
||||
if err := bootstrap.EnsureAndLogFor(cmd); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "[!] bootstrap:", err)
|
||||
|
|
@ -102,19 +102,18 @@ func peelGlobalFlags(args []string) (modulesDir string, rest []string) {
|
|||
}
|
||||
|
||||
func usage() {
|
||||
fmt.Fprint(os.Stderr, `streamd — capture / restream toolchain
|
||||
fmt.Fprint(os.Stderr, `drm — DRM capture / restream toolchain
|
||||
|
||||
Usage:
|
||||
streamd [--modules-dir DIR] modules
|
||||
streamd [--modules-dir DIR] capture --app NAME [--channel ID | --all] [--wvd PATH]
|
||||
streamd [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json]
|
||||
streamd agent run|status|devices|enqueue|cancel [--config …]
|
||||
streamd serve start|stop|restart|status|update|run [flags]
|
||||
streamd serve [--bind …] [--data …] # foreground (same as run)
|
||||
streamd proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
|
||||
drm [--modules-dir DIR] modules
|
||||
drm [--modules-dir DIR] capture --app NAME [--channel ID | --all] [--wvd PATH]
|
||||
drm [--modules-dir DIR] catalog --app NAME --channel ID [--keys] [--json]
|
||||
drm agent run|status|devices|enqueue|cancel [--config …]
|
||||
drm serve [--bind …] [--data …] [--token …]
|
||||
drm proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
|
||||
|
||||
Global flags:
|
||||
--modules-dir DIR provider folder (default: <install>/modules, or $STREAMD_MODULES_DIR)
|
||||
--modules-dir DIR provider folder (default: <install>/modules, or $DRM_MODULES_DIR)
|
||||
|
||||
Providers live under modules/<name>/ (Go source + module-publish.yaml).
|
||||
Local module.yaml holds secrets and is never published; release zips ship
|
||||
|
|
|
|||
|
|
@ -9,8 +9,8 @@ import (
|
|||
"sort"
|
||||
"text/tabwriter"
|
||||
|
||||
"streamd/modhost"
|
||||
"streamd/repo"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
// Run prints external modules under modules/.
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ One Go package per streaming app. Every module is **compiled into the binary**
|
|||
there is no plugin loading and no modules directory to point a binary at.
|
||||
|
||||
```text
|
||||
apps/modules/ Go module: streamd/modules
|
||||
go.mod replace streamd => ../pkg
|
||||
apps/modules/ Go module: drmdecryption/modules
|
||||
go.mod replace drmdecryption => ../pkg
|
||||
all/all.go blank-imports every module — the link point
|
||||
provider/ shared base: values loading, channel aliases, durations
|
||||
<name>/*.go TRACKED: the app's logic
|
||||
|
|
@ -37,7 +37,7 @@ Values arrive by **flag → environment → module.yaml → Go default**, and on
|
|||
mechanical defaults (timeouts, DASH timescales, card geometry) live in code:
|
||||
|
||||
```bash
|
||||
./bin/streamd catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
|
||||
./bin/drm catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
|
||||
export TG4_POLICY_KEY=BCpkAD... # same thing
|
||||
```
|
||||
|
||||
|
|
@ -46,9 +46,9 @@ export TG4_POLICY_KEY=BCpkAD... # same thing
|
|||
1. Create `apps/modules/myapp/` with `config.go` and `myapp.go`
|
||||
2. Register from `init()`: `appreg.Register(Name, New)` and
|
||||
`appreg.RegisterFlags(bindFlags)`
|
||||
3. Add one line to `all/all.go`: `_ "streamd/modules/myapp"`
|
||||
3. Add one line to `all/all.go`: `_ "drmdecryption/modules/myapp"`
|
||||
4. Create `apps/modules/myapp/module.yaml` with your values
|
||||
5. `go -C apps/cli build -o ../../bin/streamd .` then `./bin/streamd modules`
|
||||
5. `go -C apps/cli build -o ../../bin/drm .` then `./bin/drm modules`
|
||||
|
||||
**Authoring guide: [docs/modules.md](../../docs/modules.md)** — the full contract,
|
||||
`uiflow` reference, optional capability interfaces, and a checklist.
|
||||
|
|
@ -59,9 +59,9 @@ export TG4_POLICY_KEY=BCpkAD... # same thing
|
|||
## Run
|
||||
|
||||
```bash
|
||||
./bin/streamd modules # what is compiled in
|
||||
./bin/streamd capture --app rte --channel rteone --auto-play
|
||||
./bin/streamd capture --app bbc --channel bbcone # transparent MITM; play on phone; MPD only
|
||||
./bin/streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
|
||||
./bin/streamd agent run --config apps/agent/agent.yaml
|
||||
./bin/drm modules # what is compiled in
|
||||
./bin/drm capture --app rte --channel rteone --auto-play
|
||||
./bin/drm capture --app bbc --channel bbcone # transparent MITM; play on phone; MPD only
|
||||
./bin/drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd
|
||||
./bin/drm agent run --config apps/agent/agent.yaml
|
||||
```
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@
|
|||
package all
|
||||
|
||||
import (
|
||||
_ "streamd/modules/bbc"
|
||||
_ "streamd/modules/rte"
|
||||
_ "streamd/modules/tg4"
|
||||
_ "drmdecryption/modules/bbc"
|
||||
_ "drmdecryption/modules/rte"
|
||||
_ "drmdecryption/modules/tg4"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import (
|
|||
"flag"
|
||||
"testing"
|
||||
|
||||
appreg "streamd/app"
|
||||
appreg "drmdecryption/app"
|
||||
)
|
||||
|
||||
// Every module must be constructible with no module.yaml present — a fresh clone
|
||||
|
|
|
|||
|
|
@ -9,12 +9,12 @@ import (
|
|||
"os"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
appreg "streamd/app"
|
||||
"streamd/capture"
|
||||
"streamd/modules/provider"
|
||||
"streamd/mpd"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
appreg "drmdecryption/app"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/modules/provider"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
|
|
|||
|
|
@ -3,11 +3,11 @@ package bbc
|
|||
import (
|
||||
"testing"
|
||||
|
||||
appreg "streamd/app"
|
||||
"streamd/capture"
|
||||
"streamd/modcfg"
|
||||
"streamd/modules/provider"
|
||||
"streamd/mpd"
|
||||
appreg "drmdecryption/app"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/modcfg"
|
||||
"drmdecryption/modules/provider"
|
||||
"drmdecryption/mpd"
|
||||
)
|
||||
|
||||
var (
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import (
|
|||
"regexp"
|
||||
"time"
|
||||
|
||||
"streamd/modcfg"
|
||||
"streamd/modules/provider"
|
||||
"drmdecryption/modcfg"
|
||||
"drmdecryption/modules/provider"
|
||||
)
|
||||
|
||||
// Name is the module id (--app bbc).
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
// openExplorePage taps the Explore bottom-nav tab and waits for the channel rail.
|
||||
|
|
|
|||
|
|
@ -9,12 +9,12 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
appreg "streamd/app"
|
||||
"streamd/capture"
|
||||
"streamd/modules/provider"
|
||||
"streamd/mpd"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
appreg "drmdecryption/app"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/modules/provider"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ package c4
|
|||
import (
|
||||
"time"
|
||||
|
||||
"streamd/modcfg"
|
||||
"streamd/modules/provider"
|
||||
"drmdecryption/modcfg"
|
||||
"drmdecryption/modules/provider"
|
||||
)
|
||||
|
||||
// Name is the module id (--app c4).
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
func (a *App) openLiveTab(c *adb.Client) error {
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
module streamd/modules
|
||||
module drmdecryption/modules
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require streamd v0.0.0
|
||||
require drmdecryption v0.0.0
|
||||
|
||||
require gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
||||
replace streamd => ../pkg
|
||||
replace drmdecryption => ../pkg
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ package itv
|
|||
import (
|
||||
"time"
|
||||
|
||||
"streamd/modcfg"
|
||||
"streamd/modules/provider"
|
||||
"drmdecryption/modcfg"
|
||||
"drmdecryption/modules/provider"
|
||||
)
|
||||
|
||||
// Name is the module id (--app itv).
|
||||
|
|
|
|||
|
|
@ -10,12 +10,12 @@ import (
|
|||
"os"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
appreg "streamd/app"
|
||||
"streamd/capture"
|
||||
"streamd/modules/provider"
|
||||
"streamd/mpd"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
appreg "drmdecryption/app"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/modules/provider"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
// openLiveTab taps bottom-nav Live. Accessibility desc is obfuscated as "Lyve";
|
||||
|
|
|
|||
|
|
@ -3,8 +3,8 @@ package my5
|
|||
import (
|
||||
"time"
|
||||
|
||||
"streamd/modcfg"
|
||||
"streamd/modules/provider"
|
||||
"drmdecryption/modcfg"
|
||||
"drmdecryption/modules/provider"
|
||||
)
|
||||
|
||||
// Name is the module id (--app my5).
|
||||
|
|
|
|||
|
|
@ -9,12 +9,12 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
appreg "streamd/app"
|
||||
"streamd/capture"
|
||||
"streamd/modules/provider"
|
||||
"streamd/mpd"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
appreg "drmdecryption/app"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/modules/provider"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
|
|
|||
|
|
@ -6,8 +6,8 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
func (a *App) appFocused(c *adb.Client) bool {
|
||||
|
|
|
|||
|
|
@ -10,10 +10,10 @@ import (
|
|||
"sort"
|
||||
"strings"
|
||||
|
||||
"streamd/capture"
|
||||
"streamd/modcfg"
|
||||
"streamd/phonecap"
|
||||
"streamd/repo"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/modcfg"
|
||||
"drmdecryption/phonecap"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
// Common is the part of a module.yaml that every module has. Modules embed it in
|
||||
|
|
@ -57,7 +57,7 @@ func (b *Base) ConfigPath() string { return b.cfg.Path }
|
|||
func (b *Base) ConfigLoaded() bool { return b.cfg.Loaded }
|
||||
|
||||
// ProxyBin resolves the on-device MITM binary. Empty means “auto” (caller uses
|
||||
// proxy.FindLocalBin — next to streamd, then repo bin/).
|
||||
// proxy.FindLocalBin — next to drm.exe, then repo bin/).
|
||||
func (b *Base) ProxyBin() string {
|
||||
if b.common.ProxyBin != "" {
|
||||
return modcfg.Resolve(b.common.ProxyBin)
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ package rte
|
|||
import (
|
||||
"time"
|
||||
|
||||
"streamd/modcfg"
|
||||
"streamd/modules/provider"
|
||||
"streamd/mpd"
|
||||
"drmdecryption/modcfg"
|
||||
"drmdecryption/modules/provider"
|
||||
"drmdecryption/mpd"
|
||||
)
|
||||
|
||||
// Name is the module id (--app rte).
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import (
|
|||
"strings"
|
||||
"testing"
|
||||
|
||||
"streamd/mpd"
|
||||
"drmdecryption/mpd"
|
||||
)
|
||||
|
||||
// The rewriter must publish a usable manifest from the KID alone — this is the
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import (
|
|||
"strings"
|
||||
"sync"
|
||||
|
||||
"streamd/mpd"
|
||||
"drmdecryption/mpd"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
|
|
|||
|
|
@ -9,12 +9,12 @@ import (
|
|||
"fmt"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
appreg "streamd/app"
|
||||
"streamd/capture"
|
||||
"streamd/modules/provider"
|
||||
"streamd/mpd"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
appreg "drmdecryption/app"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/modules/provider"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import (
|
|||
"strings"
|
||||
"testing"
|
||||
|
||||
appreg "streamd/app"
|
||||
"streamd/mpd"
|
||||
appreg "drmdecryption/app"
|
||||
"drmdecryption/mpd"
|
||||
)
|
||||
|
||||
// Compile-time proof the plugin satisfies every interface the host expects.
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import (
|
|||
"regexp"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
// openLiveTab taps the bottom-nav Live tab and waits for channel chips.
|
||||
|
|
|
|||
|
|
@ -6,9 +6,9 @@ import (
|
|||
"net/http"
|
||||
"strings"
|
||||
|
||||
appreg "streamd/app"
|
||||
"streamd/brightcove"
|
||||
"streamd/session"
|
||||
appreg "drmdecryption/app"
|
||||
"drmdecryption/brightcove"
|
||||
"drmdecryption/session"
|
||||
)
|
||||
|
||||
// playbackConfig is the app's remote config blob. It is decoded generically: the
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ package tg4
|
|||
import (
|
||||
"time"
|
||||
|
||||
"streamd/modcfg"
|
||||
"streamd/modules/provider"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/modcfg"
|
||||
"drmdecryption/modules/provider"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
// Name is the module id (--app tg4).
|
||||
|
|
|
|||
|
|
@ -5,10 +5,10 @@ import (
|
|||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"streamd/brightcove"
|
||||
"streamd/repo"
|
||||
"streamd/session"
|
||||
"streamd/wvkey"
|
||||
"drmdecryption/brightcove"
|
||||
"drmdecryption/repo"
|
||||
"drmdecryption/session"
|
||||
"drmdecryption/wvkey"
|
||||
)
|
||||
|
||||
// EnrichWithKeys fetches the HLS master, extracts the Widevine PSSH and resolves
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
// openLivePage navigates to the Live page: if a menu entry is visible tap it,
|
||||
|
|
|
|||
|
|
@ -10,12 +10,12 @@ import (
|
|||
"fmt"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
appreg "streamd/app"
|
||||
"streamd/capture"
|
||||
"streamd/modules/provider"
|
||||
"streamd/mpd"
|
||||
"streamd/uiflow"
|
||||
"drmdecryption/adb"
|
||||
appreg "drmdecryption/app"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/modules/provider"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/uiflow"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
|
|
|||
|
|
@ -3,9 +3,9 @@ package tg4
|
|||
import (
|
||||
"testing"
|
||||
|
||||
appreg "streamd/app"
|
||||
"streamd/modcfg"
|
||||
"streamd/modules/provider"
|
||||
appreg "drmdecryption/app"
|
||||
"drmdecryption/modcfg"
|
||||
"drmdecryption/modules/provider"
|
||||
)
|
||||
|
||||
// Compile-time proof the plugin satisfies every interface the host expects.
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
# pkg — shared Go libraries
|
||||
|
||||
Imported by `apps/capture`, `apps/agent`, `apps/streamd`, `apps/proxy`, `apps/cli`
|
||||
and `apps/modules` as module `streamd` via:
|
||||
and `apps/modules` as module `drmdecryption` via:
|
||||
|
||||
```go
|
||||
replace streamd => ../pkg
|
||||
replace drmdecryption => ../pkg
|
||||
```
|
||||
|
||||
## Packages
|
||||
|
|
@ -34,4 +34,4 @@ provider values live in that module's gitignored `module.yaml`.
|
|||
go -C apps/pkg test ./...
|
||||
```
|
||||
|
||||
No binary of its own — everything ships in `bin/streamd`, built from `apps/cli`.
|
||||
No binary of its own — everything ships in `bin/drm`, built from `apps/cli`.
|
||||
|
|
|
|||
|
|
@ -6,10 +6,10 @@ import (
|
|||
"sort"
|
||||
"sync"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/capture"
|
||||
"streamd/mpd"
|
||||
"streamd/session"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/session"
|
||||
)
|
||||
|
||||
// Channel is a named live target inside an app (e.g. rteone).
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
// Package bootstrap materialises a GitHub-like install tree next to streamd
|
||||
// Package bootstrap materialises a GitHub-like install tree next to drm.exe
|
||||
// so a single downloaded binary can create apps/, bin/, outputs/, etc. on first run.
|
||||
package bootstrap
|
||||
|
||||
|
|
@ -17,7 +17,7 @@ var embedded embed.FS
|
|||
const minProxyBytes = 100_000 // stub ELF is tiny; real proxy-android-arm64 is ~9MB
|
||||
|
||||
// InstallRoot is the directory that should contain apps/, bin/, outputs/.
|
||||
// If streamd lives in …/bin/, the parent is the root; otherwise the exe directory.
|
||||
// If drm.exe lives in …/bin/, the parent is the root; otherwise the exe directory.
|
||||
func InstallRoot() (string, error) {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
|
|
@ -91,30 +91,27 @@ func Ensure(root string) (created []string, err error) {
|
|||
return created, err
|
||||
}
|
||||
|
||||
// If streamd is not already under bin/, copy it there for 1:1 layout.
|
||||
if err := ensureBinHost(root); err != nil {
|
||||
// If drm is not already under bin/, copy/link a drm.exe there for 1:1 layout.
|
||||
if err := ensureBinDrm(root); err != nil {
|
||||
return created, err
|
||||
}
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func ensureBinHost(root string) error {
|
||||
func ensureBinDrm(root string) error {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
exe, _ = filepath.EvalSymlinks(exe)
|
||||
return copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe"))
|
||||
}
|
||||
|
||||
func copyExeIfMissing(src, dest string) error {
|
||||
if sameFile(src, dest) {
|
||||
dest := filepath.Join(root, "bin", "drm.exe")
|
||||
if sameFile(exe, dest) {
|
||||
return nil
|
||||
}
|
||||
if st, err := os.Stat(dest); err == nil && !st.IsDir() {
|
||||
return nil
|
||||
}
|
||||
data, err := os.ReadFile(src)
|
||||
data, err := os.ReadFile(exe)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -157,7 +154,7 @@ func EnsureAndLogFor(cmd string) error {
|
|||
}
|
||||
proxy := filepath.Join(root, "bin", "proxy-android-arm64")
|
||||
if st, err := os.Stat(proxy); err != nil || st.Size() < minProxyBytes {
|
||||
fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to streamd or use a release build that embeds it\n")
|
||||
fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to drm or use a release build that embeds it\n")
|
||||
}
|
||||
// Providers live under modules/; only warn when the command needs them.
|
||||
needsModules := cmd == "" || cmd == "modules" || cmd == "capture" || cmd == "catalog" || cmd == "agent" || cmd == "serve"
|
||||
|
|
|
|||
|
|
@ -1,14 +1,14 @@
|
|||
# Streamd
|
||||
# Null DRM
|
||||
|
||||
Host binary **`streamd`** + providers under **`modules/`**.
|
||||
Host binary **`drm`** + providers under **`modules/`**.
|
||||
|
||||
## Quick start
|
||||
|
||||
1. Download `streamd` (`v*` release) and module zips (`modules-v*` release).
|
||||
1. Download `drm` (`v*` release) and module zips (`modules-v*` release).
|
||||
2. Unzip providers into `modules/<name>/` and edit `module.yaml` (secrets only).
|
||||
3. `streamd proxy install-ca --reinject`
|
||||
4. `streamd capture --app bbc --channel bbcone --wait 120`
|
||||
5. `streamd proxy reset` when finished.
|
||||
3. `drm proxy install-ca --reinject`
|
||||
4. `drm capture --app bbc --channel bbcone --wait 120`
|
||||
5. `drm proxy reset` when finished.
|
||||
|
||||
```text
|
||||
drm modules
|
||||
|
|
@ -17,6 +17,6 @@ drm catalog --app NAME --channel ID [--keys] [--json]
|
|||
drm proxy install-ca --reinject | reset | transparent --package PKG
|
||||
```
|
||||
|
||||
`--modules-dir DIR` or `$STREAMD_MODULES_DIR` selects another modules folder.
|
||||
`--modules-dir DIR` or `$DRM_MODULES_DIR` selects another modules folder.
|
||||
|
||||
Full docs: https://git.nulldrm.com/nulldrm/Null-DRM-Official
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
module streamd
|
||||
module drmdecryption
|
||||
|
||||
go 1.25.0
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +0,0 @@
|
|||
# Dependencies for wvkey.py (the only Python in the project).
|
||||
# Install into a venv at the repo root:
|
||||
# python -m venv .venv
|
||||
# .venv/bin/pip install -r apps/wvkey/requirements.txt
|
||||
pywidevine==1.9.0
|
||||
requests==2.34.2
|
||||
|
|
@ -1,367 +0,0 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Thin Widevine CDM helper for the Go capture tooling.
|
||||
|
||||
Prints a single CONTENT key as KID:KEY on stdout (no banners) when --quiet.
|
||||
Exit code 0 on success.
|
||||
|
||||
Example:
|
||||
.venv/Scripts/python.exe wvkey.py \\
|
||||
--wvd path/to/device.wvd \\
|
||||
--pssh 'AAAA…' \\
|
||||
--license-url 'https://…' \\
|
||||
--auth 'Basic …' \\
|
||||
--pid 'xxxx' \\
|
||||
--quiet
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
from pywidevine.cdm import Cdm
|
||||
from pywidevine.device import Device
|
||||
from pywidevine.pssh import PSSH
|
||||
|
||||
|
||||
def fetch_content_keys_modulardrm(
|
||||
*,
|
||||
wvd: Path,
|
||||
pssh_b64: str,
|
||||
auth: str,
|
||||
release_pid: str,
|
||||
license_url: str,
|
||||
user_agent: str,
|
||||
) -> list[str]:
|
||||
"""RTE / thePlatform ModularDrm (JSON challenge wrapper)."""
|
||||
device = Device.load(str(wvd))
|
||||
cdm = Cdm.from_device(device)
|
||||
session_id = cdm.open()
|
||||
try:
|
||||
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
|
||||
challenge_b64 = base64.b64encode(challenge).decode("utf-8")
|
||||
payload = {
|
||||
"getWidevineLicense": {
|
||||
"releasePid": release_pid,
|
||||
"widevineChallenge": challenge_b64,
|
||||
}
|
||||
}
|
||||
headers = {
|
||||
"Accept-Encoding": "gzip",
|
||||
"Authorization": auth,
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
}
|
||||
if user_agent:
|
||||
headers["User-Agent"] = user_agent
|
||||
response = requests.post(license_url, json=payload, headers=headers, timeout=30)
|
||||
data = response.json()
|
||||
if data.get("isException"):
|
||||
raise RuntimeError(data.get("description") or "license server exception")
|
||||
license_b64 = (
|
||||
data.get("getWidevineLicenseResponse", {}).get("license")
|
||||
or data.get("license")
|
||||
)
|
||||
if not license_b64:
|
||||
raise RuntimeError("no license in response: " + json.dumps(data)[:1500])
|
||||
cdm.parse_license(session_id, base64.b64decode(license_b64))
|
||||
keys = [
|
||||
f"{key.kid.hex}:{key.key.hex()}"
|
||||
for key in cdm.get_keys(session_id)
|
||||
if key.type == "CONTENT"
|
||||
]
|
||||
finally:
|
||||
cdm.close(session_id)
|
||||
if not keys:
|
||||
raise RuntimeError("no CONTENT keys")
|
||||
return keys
|
||||
|
||||
|
||||
def fetch_content_keys_raw(
|
||||
*,
|
||||
wvd: Path,
|
||||
pssh_b64: str,
|
||||
license_url: str,
|
||||
user_agent: str,
|
||||
) -> list[str]:
|
||||
"""Brightcove / generic Widevine: POST raw challenge, parse raw license body."""
|
||||
device = Device.load(str(wvd))
|
||||
cdm = Cdm.from_device(device)
|
||||
session_id = cdm.open()
|
||||
try:
|
||||
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
|
||||
headers = {
|
||||
"Content-Type": "application/octet-stream",
|
||||
"Accept": "*/*",
|
||||
}
|
||||
if user_agent:
|
||||
headers["User-Agent"] = user_agent
|
||||
response = requests.post(
|
||||
license_url, data=challenge, headers=headers, timeout=30
|
||||
)
|
||||
if response.status_code >= 400:
|
||||
raise RuntimeError(
|
||||
f"license HTTP {response.status_code}: {response.text[:500]!r}"
|
||||
)
|
||||
body = response.content
|
||||
if not body:
|
||||
raise RuntimeError("empty license response body")
|
||||
# Some servers wrap base64 text; try raw first, then b64.
|
||||
try:
|
||||
cdm.parse_license(session_id, body)
|
||||
except Exception:
|
||||
try:
|
||||
cdm.parse_license(session_id, base64.b64decode(body))
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
f"parse_license failed ({len(body)} bytes): {exc}"
|
||||
) from exc
|
||||
keys = [
|
||||
f"{key.kid.hex}:{key.key.hex()}"
|
||||
for key in cdm.get_keys(session_id)
|
||||
if key.type == "CONTENT"
|
||||
]
|
||||
finally:
|
||||
cdm.close(session_id)
|
||||
if not keys:
|
||||
raise RuntimeError("no CONTENT keys")
|
||||
return keys
|
||||
|
||||
|
||||
_CHALLENGE_KEYS = (
|
||||
"request",
|
||||
"licenseRequest",
|
||||
"license_request",
|
||||
"widevineChallenge",
|
||||
"widevine_challenge",
|
||||
"challenge",
|
||||
"payload",
|
||||
"rawLicenseRequestBase64",
|
||||
"message",
|
||||
"drm_info",
|
||||
)
|
||||
|
||||
|
||||
def _replace_challenge(obj, challenge_b64: str, challenge_bytes: bytes) -> bool:
|
||||
"""Replace the Widevine challenge field inside a captured JSON license body."""
|
||||
if isinstance(obj, dict):
|
||||
for key in _CHALLENGE_KEYS:
|
||||
if key not in obj:
|
||||
continue
|
||||
val = obj[key]
|
||||
if key == "drm_info" and isinstance(val, list):
|
||||
obj[key] = list(challenge_bytes)
|
||||
return True
|
||||
if isinstance(val, str) and len(val) >= 8:
|
||||
obj[key] = challenge_b64
|
||||
return True
|
||||
if isinstance(val, dict) and _replace_challenge(val, challenge_b64, challenge_bytes):
|
||||
return True
|
||||
for val in obj.values():
|
||||
if _replace_challenge(val, challenge_b64, challenge_bytes):
|
||||
return True
|
||||
elif isinstance(obj, list):
|
||||
for item in obj:
|
||||
if _replace_challenge(item, challenge_b64, challenge_bytes):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _license_bytes_from_response(response: requests.Response) -> bytes:
|
||||
body = response.content
|
||||
if not body:
|
||||
raise RuntimeError("empty license response body")
|
||||
# Prefer JSON wrappers used by RedBee / ModularDrm-style proxies.
|
||||
try:
|
||||
data = response.json()
|
||||
except Exception:
|
||||
data = None
|
||||
if isinstance(data, dict):
|
||||
for path in (
|
||||
("license",),
|
||||
("licenseResponse",),
|
||||
("license_response",),
|
||||
("payload",),
|
||||
("message",),
|
||||
("getWidevineLicenseResponse", "license"),
|
||||
("status", "license"),
|
||||
):
|
||||
cur: object = data
|
||||
ok = True
|
||||
for key in path:
|
||||
if not isinstance(cur, dict) or key not in cur:
|
||||
ok = False
|
||||
break
|
||||
cur = cur[key]
|
||||
if ok and isinstance(cur, str) and cur:
|
||||
try:
|
||||
return base64.b64decode(cur)
|
||||
except Exception:
|
||||
return cur.encode("utf-8")
|
||||
# Some LSP responses nest the blob under status.success payload.
|
||||
if data.get("status", {}).get("success") is False:
|
||||
raise RuntimeError("license LSP error: " + json.dumps(data)[:500])
|
||||
return body
|
||||
|
||||
|
||||
def fetch_content_keys_wrap(
|
||||
*,
|
||||
wvd: Path,
|
||||
pssh_b64: str,
|
||||
license_url: str,
|
||||
wrap_json: str,
|
||||
user_agent: str,
|
||||
) -> list[str]:
|
||||
"""Re-POST a captured JSON license body with a fresh local CDM challenge.
|
||||
|
||||
Used by Channel 4 / RedBee (wvlicenceproxy-service) which reject raw
|
||||
octet-stream (HTTP 415) and need the phone's token fields intact.
|
||||
"""
|
||||
try:
|
||||
template = json.loads(wrap_json)
|
||||
except Exception as exc:
|
||||
raise RuntimeError(f"wrap-json is not valid JSON: {exc}") from exc
|
||||
|
||||
device = Device.load(str(wvd))
|
||||
cdm = Cdm.from_device(device)
|
||||
session_id = cdm.open()
|
||||
try:
|
||||
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
|
||||
challenge_b64 = base64.b64encode(challenge).decode("utf-8")
|
||||
if not _replace_challenge(template, challenge_b64, challenge):
|
||||
raise RuntimeError(
|
||||
"wrap-json has no recognisable challenge field "
|
||||
f"(tried {', '.join(_CHALLENGE_KEYS)})"
|
||||
)
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, */*",
|
||||
}
|
||||
if user_agent:
|
||||
headers["User-Agent"] = user_agent
|
||||
response = requests.post(
|
||||
license_url, json=template, headers=headers, timeout=30
|
||||
)
|
||||
if response.status_code >= 400:
|
||||
raise RuntimeError(
|
||||
f"license HTTP {response.status_code}: {response.text[:500]!r}"
|
||||
)
|
||||
license_bytes = _license_bytes_from_response(response)
|
||||
try:
|
||||
cdm.parse_license(session_id, license_bytes)
|
||||
except Exception:
|
||||
try:
|
||||
cdm.parse_license(session_id, base64.b64decode(license_bytes))
|
||||
except Exception as exc:
|
||||
raise RuntimeError(
|
||||
f"parse_license failed ({len(license_bytes)} bytes): {exc}"
|
||||
) from exc
|
||||
keys = [
|
||||
f"{key.kid.hex}:{key.key.hex()}"
|
||||
for key in cdm.get_keys(session_id)
|
||||
if key.type == "CONTENT"
|
||||
]
|
||||
finally:
|
||||
cdm.close(session_id)
|
||||
if not keys:
|
||||
raise RuntimeError("no CONTENT keys")
|
||||
return keys
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
p = argparse.ArgumentParser(description="Widevine CDM helper → KID:KEY")
|
||||
p.add_argument("--wvd", type=Path, required=True, help="Path to .wvd device file")
|
||||
p.add_argument("--pssh", required=True, help="Base64 PSSH box")
|
||||
p.add_argument(
|
||||
"--mode",
|
||||
choices=("modulardrm", "raw", "wrap"),
|
||||
default="modulardrm",
|
||||
help="modulardrm=RTE JSON; raw=octet-stream; wrap=captured JSON body",
|
||||
)
|
||||
p.add_argument("--auth", default="", help="Authorization header (modulardrm)")
|
||||
p.add_argument("--pid", default="", help="releasePid (modulardrm)")
|
||||
p.add_argument(
|
||||
"--wrap-json",
|
||||
default="",
|
||||
help="Captured phone license POST JSON (wrap mode)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--license-url",
|
||||
required=True,
|
||||
help="Widevine license server URL",
|
||||
)
|
||||
p.add_argument(
|
||||
"--user-agent",
|
||||
default="",
|
||||
help="Optional User-Agent for the license request",
|
||||
)
|
||||
p.add_argument(
|
||||
"--quiet",
|
||||
action="store_true",
|
||||
help="Print only KID:KEY lines (for Go tooling)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--all",
|
||||
action="store_true",
|
||||
help="Print every CONTENT key (default: first only)",
|
||||
)
|
||||
args = p.parse_args(argv)
|
||||
|
||||
if not args.wvd.is_file():
|
||||
print(f"[!] missing WVD: {args.wvd}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
try:
|
||||
if args.mode == "raw":
|
||||
keys = fetch_content_keys_raw(
|
||||
wvd=args.wvd,
|
||||
pssh_b64=args.pssh,
|
||||
license_url=args.license_url,
|
||||
user_agent=args.user_agent,
|
||||
)
|
||||
elif args.mode == "wrap":
|
||||
if not args.wrap_json.strip():
|
||||
print(
|
||||
"[!] --wrap-json required for wrap mode "
|
||||
"(phone must complete a license POST during capture)",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 2
|
||||
keys = fetch_content_keys_wrap(
|
||||
wvd=args.wvd,
|
||||
pssh_b64=args.pssh,
|
||||
license_url=args.license_url,
|
||||
wrap_json=args.wrap_json,
|
||||
user_agent=args.user_agent,
|
||||
)
|
||||
else:
|
||||
if not args.auth or not args.pid:
|
||||
print("[!] --auth and --pid required for modulardrm mode", file=sys.stderr)
|
||||
return 2
|
||||
keys = fetch_content_keys_modulardrm(
|
||||
wvd=args.wvd,
|
||||
pssh_b64=args.pssh,
|
||||
auth=args.auth,
|
||||
release_pid=args.pid,
|
||||
license_url=args.license_url,
|
||||
user_agent=args.user_agent,
|
||||
)
|
||||
except Exception as exc:
|
||||
print(f"[!] {exc}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
out = keys if args.all else keys[:1]
|
||||
if not args.quiet:
|
||||
print("[+] Keys:", file=sys.stderr)
|
||||
for pair in out:
|
||||
print(f"--key {pair}", file=sys.stderr)
|
||||
for pair in out:
|
||||
print(pair)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# External modules
|
||||
|
||||
Each subdirectory is a provider the `streamd` host discovers, builds, and runs.
|
||||
Each subdirectory is a provider the `drm` host discovers, builds, and runs.
|
||||
|
||||
```
|
||||
modules/
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
module streamd
|
||||
module drmdecryption
|
||||
|
||||
go 1.25.0
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"drmdecryption/adb"
|
||||
)
|
||||
|
||||
// Hints tell the waiter which fields / log tags mean a capture is complete.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
module streamd
|
||||
module drmdecryption
|
||||
|
||||
go 1.25.0
|
||||
|
||||
|
|
|
|||
|
|
@ -15,14 +15,13 @@ import (
|
|||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"streamd/modhost"
|
||||
"streamd/repo"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/repo"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// Dir returns the directory holding a module's values.
|
||||
// Prefers the active modules dir (see modhost / --modules-dir); then the
|
||||
// directory beside a panel/release binary (<mod>/.bin/<name>); then
|
||||
// Prefers the active modules dir (see modhost / --modules-dir); falls back to
|
||||
// apps/modules/<name>/ for older checkouts.
|
||||
func Dir(name string) string {
|
||||
preferred := filepath.Join(modhost.ModulesDir(""), name)
|
||||
|
|
@ -32,9 +31,6 @@ func Dir(name string) string {
|
|||
if modhost.ModulesDirOverride() != "" {
|
||||
return preferred
|
||||
}
|
||||
if beside := dirBesideExecutable(name); beside != "" {
|
||||
return beside
|
||||
}
|
||||
root := repo.Root()
|
||||
if _, err := os.Stat(filepath.Join(root, "modules")); err == nil {
|
||||
return filepath.Join(root, "modules", name)
|
||||
|
|
@ -42,43 +38,6 @@ func Dir(name string) string {
|
|||
return filepath.Join(root, "apps", "modules", name)
|
||||
}
|
||||
|
||||
// dirBesideExecutable finds module.yaml next to a panel/release binary layout:
|
||||
// <modDir>/.bin/<name>[.exe]
|
||||
// <modDir>/.bin/<goos>-<goarch>/<name>[.exe]
|
||||
func dirBesideExecutable(name string) string {
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
|
||||
exe = resolved
|
||||
}
|
||||
base := strings.TrimSuffix(filepath.Base(exe), ".exe")
|
||||
if !strings.EqualFold(base, name) {
|
||||
return ""
|
||||
}
|
||||
binDir := filepath.Dir(exe)
|
||||
candidates := []string{}
|
||||
if strings.EqualFold(filepath.Base(binDir), ".bin") {
|
||||
candidates = append(candidates, filepath.Dir(binDir))
|
||||
}
|
||||
parent := filepath.Dir(binDir)
|
||||
if strings.EqualFold(filepath.Base(parent), ".bin") {
|
||||
candidates = append(candidates, filepath.Dir(parent))
|
||||
}
|
||||
for _, dir := range candidates {
|
||||
if fileExists(filepath.Join(dir, "module.yaml")) || fileExists(filepath.Join(dir, "module-publish.yaml")) {
|
||||
return dir
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func fileExists(p string) bool {
|
||||
st, err := os.Stat(p)
|
||||
return err == nil && !st.IsDir()
|
||||
}
|
||||
|
||||
// Path returns the preferred values file path (module.yaml).
|
||||
func Path(name string) string {
|
||||
return filepath.Join(Dir(name), "module.yaml")
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ type Module struct {
|
|||
Dir string // absolute path to modules/<name>
|
||||
}
|
||||
|
||||
// ModulesDir returns the modules directory (honours --modules-dir / STREAMD_MODULES_DIR / DRM_MODULES_DIR).
|
||||
// ModulesDir returns the modules directory (honours --modules-dir / DRM_MODULES_DIR).
|
||||
func ModulesDir(root string) string {
|
||||
return EffectiveModulesDir(root)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,39 +9,9 @@ import (
|
|||
"strings"
|
||||
)
|
||||
|
||||
// prepareModuleCmd sets STREAMD_MODULES_DIR so child module binaries load
|
||||
// panel-store module.yaml. Module builds that call EffectiveModulesDir (or
|
||||
// ApplyEnvModulesDir) honour this; /api/apps also falls back to parsing the
|
||||
// panel module.yaml when describe returns no channels.
|
||||
func prepareModuleCmd(cmd *exec.Cmd) {
|
||||
ov := ModulesDirOverride()
|
||||
if ov == "" {
|
||||
return
|
||||
}
|
||||
cmd.Env = append(withoutEnvKeys(os.Environ(), "STREAMD_MODULES_DIR", "DRM_MODULES_DIR"),
|
||||
"STREAMD_MODULES_DIR="+ov)
|
||||
}
|
||||
|
||||
func withoutEnvKeys(env []string, keys ...string) []string {
|
||||
drop := map[string]struct{}{}
|
||||
for _, k := range keys {
|
||||
drop[strings.ToUpper(k)] = struct{}{}
|
||||
}
|
||||
out := make([]string, 0, len(env))
|
||||
for _, e := range env {
|
||||
key, _, _ := strings.Cut(e, "=")
|
||||
if _, skip := drop[strings.ToUpper(key)]; skip {
|
||||
continue
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Run executes the module binary with args, inheriting stdout/stderr.
|
||||
func Run(bin string, args ...string) error {
|
||||
cmd := exec.Command(bin, args...)
|
||||
prepareModuleCmd(cmd)
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
cmd.Stdin = os.Stdin
|
||||
|
|
@ -54,7 +24,6 @@ func Run(bin string, args ...string) error {
|
|||
// RunOutput executes the module binary and returns combined stdout.
|
||||
func RunOutput(bin string, args ...string) (string, error) {
|
||||
cmd := exec.Command(bin, args...)
|
||||
prepareModuleCmd(cmd)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
|
|
@ -105,9 +74,5 @@ func Load(root, name string) (Module, string, Describe, error) {
|
|||
if d.Name == "" {
|
||||
d.Name = m.Name
|
||||
}
|
||||
// Older panel binaries may not load module.yaml from STREAMD_MODULES_DIR /
|
||||
// exe-adjacent layout, leaving package empty (breaks transparent MITM —
|
||||
// iptables then treats the listen port as the package name).
|
||||
enrichDescribeFromYAML(&d, m.Dir)
|
||||
return m, bin, d, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,31 +0,0 @@
|
|||
package modhost
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPrepareModuleCmdSetsEnv(t *testing.T) {
|
||||
t.Cleanup(func() { _ = SetModulesDir("") })
|
||||
ov := filepath.Join(t.TempDir(), "modules")
|
||||
if err := os.MkdirAll(ov, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetModulesDir(ov); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := exec.Command("true")
|
||||
prepareModuleCmd(cmd)
|
||||
found := false
|
||||
for _, e := range cmd.Env {
|
||||
if e == "STREAMD_MODULES_DIR="+ov {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("STREAMD_MODULES_DIR missing in env: %v", cmd.Env)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,8 @@
|
|||
// Package modhost discovers, builds, and runs external provider modules that
|
||||
// live under modules/<name>/ (Go source + module.yaml), outside streamd.
|
||||
// live under modules/<name>/ (Go source + module.yaml), outside drm.exe.
|
||||
package modhost
|
||||
|
||||
import "streamd/capture"
|
||||
import "drmdecryption/capture"
|
||||
|
||||
// ProtocolVersion is bumped when describe/launch/autoplay CLI contract changes.
|
||||
const ProtocolVersion = 1
|
||||
|
|
|
|||
|
|
@ -6,11 +6,11 @@ import (
|
|||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/app"
|
||||
"streamd/capture"
|
||||
"streamd/mpd"
|
||||
"streamd/session"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/app"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/session"
|
||||
)
|
||||
|
||||
// RemoteApp implements app.App by calling an external module binary.
|
||||
|
|
|
|||
|
|
@ -3,10 +3,9 @@ package modhost
|
|||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"streamd/repo"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
var (
|
||||
|
|
@ -14,7 +13,7 @@ var (
|
|||
modulesDirOV string // absolute path override for the modules directory
|
||||
)
|
||||
|
||||
// SetModulesDir overrides where providers are discovered (streamd --modules-dir).
|
||||
// SetModulesDir overrides where providers are discovered (drm --modules-dir).
|
||||
// Empty clears the override. Relative paths are resolved against the process cwd.
|
||||
func SetModulesDir(dir string) error {
|
||||
rootMu.Lock()
|
||||
|
|
@ -38,45 +37,24 @@ func ModulesDirOverride() string {
|
|||
return modulesDirOV
|
||||
}
|
||||
|
||||
// envModulesDir returns STREAMD_MODULES_DIR (preferred) or DRM_MODULES_DIR.
|
||||
func envModulesDir() string {
|
||||
v := strings.TrimSpace(os.Getenv("STREAMD_MODULES_DIR"))
|
||||
if v == "" {
|
||||
v = strings.TrimSpace(os.Getenv("DRM_MODULES_DIR"))
|
||||
}
|
||||
if v == "" {
|
||||
return ""
|
||||
}
|
||||
if abs, err := filepath.Abs(v); err == nil {
|
||||
return abs
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// EffectiveModulesDir is the directory that Discover/Open scan.
|
||||
// Prefer --modules-dir, then STREAMD_MODULES_DIR / DRM_MODULES_DIR, else <root>/modules.
|
||||
// Module binaries read the env here directly so they honour the panel store even
|
||||
// when they never call ApplyEnvModulesDir.
|
||||
// Prefer --modules-dir / DRM_MODULES_DIR; else <root>/modules.
|
||||
func EffectiveModulesDir(root string) string {
|
||||
if ov := ModulesDirOverride(); ov != "" {
|
||||
return ov
|
||||
}
|
||||
if v := envModulesDir(); v != "" {
|
||||
return v
|
||||
}
|
||||
if root == "" {
|
||||
root = repo.Root()
|
||||
}
|
||||
return filepath.Join(root, "modules")
|
||||
}
|
||||
|
||||
// ApplyEnvModulesDir sets the override from STREAMD_MODULES_DIR (preferred) or
|
||||
// DRM_MODULES_DIR when no flag was set.
|
||||
// ApplyEnvModulesDir sets the override from DRM_MODULES_DIR when no flag was set.
|
||||
func ApplyEnvModulesDir() error {
|
||||
if ModulesDirOverride() != "" {
|
||||
return nil
|
||||
}
|
||||
v := envModulesDir()
|
||||
v := os.Getenv("DRM_MODULES_DIR")
|
||||
if v == "" {
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,39 +0,0 @@
|
|||
package modhost
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEffectiveModulesDirEnv(t *testing.T) {
|
||||
t.Cleanup(func() {
|
||||
_ = SetModulesDir("")
|
||||
_ = os.Unsetenv("STREAMD_MODULES_DIR")
|
||||
_ = os.Unsetenv("DRM_MODULES_DIR")
|
||||
})
|
||||
_ = SetModulesDir("")
|
||||
_ = os.Unsetenv("STREAMD_MODULES_DIR")
|
||||
_ = os.Unsetenv("DRM_MODULES_DIR")
|
||||
|
||||
dir := t.TempDir()
|
||||
t.Setenv("STREAMD_MODULES_DIR", dir)
|
||||
got := EffectiveModulesDir("")
|
||||
want, _ := filepath.Abs(dir)
|
||||
if got != want {
|
||||
t.Fatalf("env modules dir: got %q want %q", got, want)
|
||||
}
|
||||
|
||||
override := filepath.Join(t.TempDir(), "override")
|
||||
if err := os.MkdirAll(override, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := SetModulesDir(override); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = EffectiveModulesDir("")
|
||||
want, _ = filepath.Abs(override)
|
||||
if got != want {
|
||||
t.Fatalf("flag overrides env: got %q want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
package modhost
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// enrichDescribeFromYAML fills gaps left by older module binaries that do not
|
||||
// load panel/agent module.yaml (empty package breaks transparent MITM).
|
||||
func enrichDescribeFromYAML(d *Describe, modDir string) {
|
||||
if d == nil || strings.TrimSpace(modDir) == "" {
|
||||
return
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml"))
|
||||
if err != nil {
|
||||
raw, err = os.ReadFile(filepath.Join(modDir, "module-publish.yaml"))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
var doc struct {
|
||||
Package string `yaml:"package"`
|
||||
LicenseURL string `yaml:"license_url"`
|
||||
KeyMode string `yaml:"key_mode"`
|
||||
ProxyBin string `yaml:"proxy_bin"`
|
||||
CAHash string `yaml:"ca_hash"`
|
||||
TransparentMITM *bool `yaml:"transparent_mitm"`
|
||||
RequireWVD *bool `yaml:"require_wvd"`
|
||||
Rewriter string `yaml:"rewriter"`
|
||||
Channels map[string]struct {
|
||||
Label string `yaml:"label"`
|
||||
} `yaml:"channels"`
|
||||
}
|
||||
if err := yaml.Unmarshal(raw, &doc); err != nil {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(d.Package) == "" && strings.TrimSpace(doc.Package) != "" {
|
||||
d.Package = strings.TrimSpace(doc.Package)
|
||||
}
|
||||
if strings.TrimSpace(d.LicenseURL) == "" && strings.TrimSpace(doc.LicenseURL) != "" {
|
||||
d.LicenseURL = strings.TrimSpace(doc.LicenseURL)
|
||||
}
|
||||
if strings.TrimSpace(d.KeyMode) == "" && strings.TrimSpace(doc.KeyMode) != "" {
|
||||
d.KeyMode = strings.TrimSpace(doc.KeyMode)
|
||||
}
|
||||
if strings.TrimSpace(d.ProxyBin) == "" && strings.TrimSpace(doc.ProxyBin) != "" {
|
||||
d.ProxyBin = strings.TrimSpace(doc.ProxyBin)
|
||||
}
|
||||
if strings.TrimSpace(d.CAHash) == "" && strings.TrimSpace(doc.CAHash) != "" {
|
||||
d.CAHash = strings.TrimSpace(doc.CAHash)
|
||||
}
|
||||
if strings.TrimSpace(d.Rewriter) == "" && strings.TrimSpace(doc.Rewriter) != "" {
|
||||
d.Rewriter = strings.TrimSpace(doc.Rewriter)
|
||||
}
|
||||
if !d.TransparentMITM && doc.TransparentMITM != nil {
|
||||
d.TransparentMITM = *doc.TransparentMITM
|
||||
}
|
||||
if !d.RequireWVD && doc.RequireWVD != nil {
|
||||
d.RequireWVD = *doc.RequireWVD
|
||||
}
|
||||
if len(d.Channels) == 0 && len(doc.Channels) > 0 {
|
||||
for id, ch := range doc.Channels {
|
||||
label := strings.TrimSpace(ch.Label)
|
||||
if label == "" {
|
||||
label = id
|
||||
}
|
||||
d.Channels = append(d.Channels, Channel{ID: id, Label: label})
|
||||
}
|
||||
}
|
||||
if !d.ValuesLoaded {
|
||||
d.ValuesLoaded = true
|
||||
d.ValuesPath = filepath.Join(modDir, "module.yaml")
|
||||
}
|
||||
}
|
||||
|
|
@ -12,13 +12,13 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/app"
|
||||
"streamd/capture"
|
||||
"streamd/proxy"
|
||||
"streamd/repo"
|
||||
"streamd/session"
|
||||
"streamd/wvkey"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/app"
|
||||
"drmdecryption/capture"
|
||||
"drmdecryption/proxy"
|
||||
"drmdecryption/repo"
|
||||
"drmdecryption/session"
|
||||
"drmdecryption/wvkey"
|
||||
)
|
||||
|
||||
// DefaultCAHash is the subject hash of the bundled MITM CA, used when an app
|
||||
|
|
@ -206,21 +206,17 @@ func Run(opt Options) (res Result, err error) {
|
|||
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
|
||||
useTProxy = true
|
||||
}
|
||||
pkgName := strings.TrimSpace(a.Package())
|
||||
if useTProxy && pkgName == "" {
|
||||
return res, fmt.Errorf("module %q has empty package — fix module.yaml package: (or re-pull modules); transparent MITM cannot install iptables UID rules", a.Name())
|
||||
}
|
||||
|
||||
if useTProxy {
|
||||
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
|
||||
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
|
||||
proxy.ClearHTTPProxy(c)
|
||||
remoteDir := "/data/local/tmp/capture/" + pkgName
|
||||
remoteDir := "/data/local/tmp/capture/" + a.Package()
|
||||
var mitmHosts []string
|
||||
if mh, ok := a.(app.MitmHostList); ok {
|
||||
mitmHosts = mh.MitmHosts()
|
||||
}
|
||||
if err := proxy.StartTransparent(c, proxyBin, pkgName, "8080", remoteDir, false, mitmHosts...); err != nil {
|
||||
if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false, mitmHosts...); err != nil {
|
||||
return res, fmt.Errorf("transparent MITM start: %w", err)
|
||||
}
|
||||
defer proxy.StopTransparent(c)
|
||||
|
|
@ -242,6 +238,17 @@ func Run(opt Options) (res Result, err error) {
|
|||
proxy.ReinjectCA(c, caHash)
|
||||
}
|
||||
|
||||
if err := a.Launch(c); err != nil {
|
||||
return res, fmt.Errorf("launch: %w", err)
|
||||
}
|
||||
if !opt.NoAutoPlay {
|
||||
if err := a.AutoPlay(c, opt.Channel); err != nil {
|
||||
return res, fmt.Errorf("auto-play: %w", err)
|
||||
}
|
||||
} else {
|
||||
fmt.Println("[*] Open the channel on the phone and wait for playback…")
|
||||
}
|
||||
|
||||
_ = os.MkdirAll(filepath.Join(root, ".cache"), 0o755)
|
||||
serialTag := c.Serial
|
||||
if serialTag == "" {
|
||||
|
|
@ -249,86 +256,57 @@ func Run(opt Options) (res Result, err error) {
|
|||
}
|
||||
localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log")
|
||||
localCap := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+"_cap.json")
|
||||
// Fresh local mirrors each run so grab-all does not reuse a prior channel's MPD.
|
||||
_ = os.WriteFile(localLog, nil, 0o644)
|
||||
_ = os.Remove(localCap)
|
||||
stop := make(chan struct{})
|
||||
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
|
||||
defer close(stop)
|
||||
|
||||
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
|
||||
if keyMode == "" || keyMode == "auto" {
|
||||
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
|
||||
}
|
||||
needsKeys := keyMode != "none" && keyMode != "clear"
|
||||
|
||||
// DRM apps: wait up to 90s for Widevine traffic, then force-stop and retry
|
||||
// (max 3). Clear / MPD-only apps keep a single wait of opt.Wait.
|
||||
attempts := 1
|
||||
waitPer := opt.Wait
|
||||
if needsKeys {
|
||||
attempts = 3
|
||||
waitPer = 90 * time.Second
|
||||
if opt.Wait > 0 && opt.Wait < waitPer {
|
||||
waitPer = opt.Wait
|
||||
}
|
||||
}
|
||||
|
||||
need := hints.Require
|
||||
if len(need) == 0 {
|
||||
need = []string{"manifest"}
|
||||
}
|
||||
|
||||
var (
|
||||
capData capture.Data
|
||||
licenseURL string
|
||||
mpdURL string
|
||||
key string
|
||||
lastErr error
|
||||
)
|
||||
|
||||
for attempt := 1; attempt <= attempts; attempt++ {
|
||||
if attempt > 1 {
|
||||
fmt.Printf("[*] Widevine attempt %d/%d — closing app and retrying…\n", attempt, attempts)
|
||||
c.ForceStop(a.Package())
|
||||
time.Sleep(800 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Fresh local mirrors each attempt so we do not reuse a prior MPD/PSSH.
|
||||
_ = os.WriteFile(localLog, nil, 0o644)
|
||||
_ = os.Remove(localCap)
|
||||
|
||||
if err := a.Launch(c); err != nil {
|
||||
lastErr = fmt.Errorf("launch: %w", err)
|
||||
continue
|
||||
}
|
||||
if !opt.NoAutoPlay {
|
||||
if err := a.AutoPlay(c, opt.Channel); err != nil {
|
||||
lastErr = fmt.Errorf("auto-play: %w", err)
|
||||
c.ForceStop(a.Package())
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
fmt.Println("[*] Open the channel on the phone and wait for playback…")
|
||||
}
|
||||
|
||||
fmt.Printf("[*] Waiting for %s (attempt %d/%d, timeout %s)…\n",
|
||||
strings.Join(need, " + "), attempt, attempts, waitPer.Round(time.Second))
|
||||
fmt.Printf("[*] Waiting for %s…\n", strings.Join(need, " + "))
|
||||
fmt.Println(" watch:", localLog)
|
||||
cap, err := capture.Wait(c, hints, localLog, localCap, waitPer)
|
||||
capData, err := capture.Wait(c, hints, localLog, localCap, opt.Wait)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
fmt.Fprintf(os.Stderr, "[!] capture wait failed: %v\n", err)
|
||||
c.ForceStop(a.Package())
|
||||
continue
|
||||
return res, err
|
||||
}
|
||||
licenseURL := first(capData.Get("license_url"), a.LicenseURL())
|
||||
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
|
||||
if keyMode == "" || keyMode == "auto" {
|
||||
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
|
||||
}
|
||||
capData = cap
|
||||
licenseURL = first(capData.Get("license_url"), a.LicenseURL())
|
||||
|
||||
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
|
||||
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
|
||||
if needsKeys {
|
||||
enrichWidevinePSSH(capData)
|
||||
// Skip for clear/MPD-only apps (KeyMode none).
|
||||
if keyMode != "none" && keyMode != "clear" {
|
||||
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
|
||||
curPSSH := strings.TrimSpace(capData.Get("pssh"))
|
||||
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
|
||||
if needPSSH && mpdForPSSH != "" {
|
||||
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
|
||||
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
|
||||
if curPSSH != "" && curPSSH != pssh {
|
||||
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
|
||||
}
|
||||
capData["pssh"] = pssh
|
||||
} else if err != nil && curPSSH == "" {
|
||||
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
|
||||
}
|
||||
} else if curPSSH == "" {
|
||||
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
|
||||
capData["pssh"] = pssh
|
||||
} else if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mpdURL = strings.TrimSpace(capData.Get("mpd"))
|
||||
mpdURL := strings.TrimSpace(capData.Get("mpd"))
|
||||
// Console: always surface the MPD we will use (BBC clear streams only need this).
|
||||
fmt.Println()
|
||||
fmt.Println("========== MPD ==========")
|
||||
if mpdURL != "" {
|
||||
|
|
@ -358,52 +336,27 @@ func Run(opt Options) (res Result, err error) {
|
|||
fmt.Println(" ", label+":", trim(v, 120))
|
||||
}
|
||||
|
||||
if !needsKeys {
|
||||
key := ""
|
||||
if keyMode == "none" || keyMode == "clear" {
|
||||
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
|
||||
lastErr = nil
|
||||
break
|
||||
}
|
||||
|
||||
k, kerr := fetchKey(opt, root, capData, licenseURL)
|
||||
} else {
|
||||
var kerr error
|
||||
key, kerr = fetchKey(opt, root, capData, licenseURL)
|
||||
if kerr != nil {
|
||||
lastErr = kerr
|
||||
// Missing --wvd on a manual grab-all can soft-save MPD-only; agents
|
||||
// always pass WVD so this path is for interactive capture only.
|
||||
// Allow MPD-only sessions when no .wvd was passed (grab-all / first pass),
|
||||
// unless the app requires keys (e.g. c4).
|
||||
softOK := strings.Contains(kerr.Error(), "requires --wvd")
|
||||
if softOK {
|
||||
if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
|
||||
c.ForceStop(a.Package())
|
||||
continue
|
||||
return res, kerr
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
|
||||
key = ""
|
||||
lastErr = nil
|
||||
break
|
||||
} else {
|
||||
return res, kerr
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "[!] key fetch failed (attempt %d/%d): %v\n", attempt, attempts, kerr)
|
||||
c.ForceStop(a.Package())
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(k) == "" || !looksLikeKey(k) {
|
||||
lastErr = fmt.Errorf("wvkey returned no usable KID:KEY")
|
||||
fmt.Fprintf(os.Stderr, "[!] %v (attempt %d/%d)\n", lastErr, attempt, attempts)
|
||||
c.ForceStop(a.Package())
|
||||
continue
|
||||
}
|
||||
key = k
|
||||
} else {
|
||||
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
|
||||
lastErr = nil
|
||||
break
|
||||
}
|
||||
|
||||
if lastErr != nil {
|
||||
if needsKeys {
|
||||
return res, fmt.Errorf("widevine capture failed after %d attempt(s): %w", attempts, lastErr)
|
||||
}
|
||||
return res, lastErr
|
||||
}
|
||||
if needsKeys && (strings.TrimSpace(key) == "" || !looksLikeKey(key)) {
|
||||
return res, fmt.Errorf("refusing to save capture without Widevine keys (mpd alone is not enough)")
|
||||
}
|
||||
|
||||
sess := session.Session{
|
||||
|
|
@ -431,62 +384,6 @@ func Run(opt Options) (res Result, err error) {
|
|||
return res, nil
|
||||
}
|
||||
|
||||
func enrichWidevinePSSH(capData capture.Data) {
|
||||
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
|
||||
curPSSH := strings.TrimSpace(capData.Get("pssh"))
|
||||
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
|
||||
if !needPSSH || mpdForPSSH == "" {
|
||||
return
|
||||
}
|
||||
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
|
||||
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
|
||||
if curPSSH != "" && curPSSH != pssh {
|
||||
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
|
||||
}
|
||||
capData["pssh"] = pssh
|
||||
} else if err != nil && curPSSH == "" {
|
||||
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if curPSSH == "" {
|
||||
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
|
||||
capData["pssh"] = pssh
|
||||
} else if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func looksLikeKey(raw string) bool {
|
||||
raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
kid, k, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if len(hexDigits(kid)) == 32 && len(hexDigits(k)) == 32 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func hexDigits(s string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// ClearProxyLater clears http_proxy (exported for agent defer helpers).
|
||||
func ClearProxyLater(c *adb.Client) {
|
||||
proxy.ClearHTTPProxy(c)
|
||||
|
|
@ -517,18 +414,16 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
|
|||
if strings.TrimSpace(opt.WVD) == "" {
|
||||
return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)")
|
||||
}
|
||||
// Ensure apps/wvkey + .venv/pywidevine exist on Windows/Linux/macOS.
|
||||
rt, err := wvkey.EnsureRuntime(root)
|
||||
if err != nil {
|
||||
return "", err
|
||||
py := opt.Python
|
||||
if py == "" {
|
||||
py = filepath.Join(root, ".venv", "Scripts", "python.exe")
|
||||
if _, err := os.Stat(py); err != nil {
|
||||
py = filepath.Join(root, ".venv", "bin", "python")
|
||||
}
|
||||
py := rt.Python
|
||||
if p := strings.TrimSpace(opt.Python); p != "" && fileExistsPath(p) {
|
||||
py = p
|
||||
}
|
||||
wopt := wvkey.Options{
|
||||
Python: py,
|
||||
Script: rt.Script,
|
||||
Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"),
|
||||
WVD: opt.WVD,
|
||||
PSSH: cap.Get("pssh"),
|
||||
Auth: cap.Get("auth"),
|
||||
|
|
@ -570,11 +465,6 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
|
|||
}
|
||||
}
|
||||
|
||||
func fileExistsPath(path string) bool {
|
||||
st, err := os.Stat(path)
|
||||
return err == nil && !st.IsDir()
|
||||
}
|
||||
|
||||
func first(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if strings.TrimSpace(v) != "" {
|
||||
|
|
|
|||
|
|
@ -6,15 +6,15 @@ import (
|
|||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/repo"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
//go:embed embedded/tproxy_iptables.sh
|
||||
var embeddedTProxyScript []byte
|
||||
|
||||
// ensureTProxyScript pushes the iptables helper to the phone.
|
||||
// Prefers the source-tree copy; falls back to the copy embedded in streamd
|
||||
// Prefers the source-tree copy; falls back to the copy embedded in drm.exe
|
||||
// so a portable release zip does not need apps/proxy/device/.
|
||||
func ensureTProxyScript(c *adb.Client) error {
|
||||
candidates := []string{
|
||||
|
|
|
|||
|
|
@ -17,8 +17,8 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/repo"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -225,7 +225,7 @@ func PushAndStart(c *adb.Client, localBin string, extraArgs ...string) error {
|
|||
}
|
||||
|
||||
// FindLocalBin returns the on-device MITM binary.
|
||||
// Search order: next to this streamd binary (release zip layout), then under the repo.
|
||||
// Search order: next to this drm.exe (release zip layout), then under the repo.
|
||||
func FindLocalBin(root string) string {
|
||||
if root == "" {
|
||||
root = repo.Root()
|
||||
|
|
@ -322,11 +322,11 @@ func generateMITMCA(certPath, keyPath string) error {
|
|||
return err
|
||||
}
|
||||
// Unique CN so Android subject_hash_old differs per install (filename HASH.0).
|
||||
cn := fmt.Sprintf("Streamd Capture CA %x", serial.Bytes()[:8])
|
||||
cn := fmt.Sprintf("Null DRM Capture CA %x", serial.Bytes()[:8])
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{
|
||||
Organization: []string{"Streamd MITM CA"},
|
||||
Organization: []string{"Null DRM MITM CA"},
|
||||
CommonName: cn,
|
||||
},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
|
|
@ -481,14 +481,10 @@ const (
|
|||
// mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent
|
||||
// mode otherwise only MITMs open.live.bbc.co.uk.
|
||||
func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool, mitmHosts ...string) error {
|
||||
pkg = strings.TrimSpace(pkg)
|
||||
if pkg == "" {
|
||||
return fmt.Errorf("transparent MITM requires Android package name (module.yaml package: is empty — re-pull/rebuild the module)")
|
||||
}
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
if remoteDir == "" || strings.HasSuffix(remoteDir, "/capture/") || strings.HasSuffix(remoteDir, `\capture\`) {
|
||||
if remoteDir == "" {
|
||||
remoteDir = RemoteCaptureRoot + "/" + pkg
|
||||
}
|
||||
stopProxy(c)
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import (
|
|||
//
|
||||
// Search order:
|
||||
// 1. Walk up from the current working directory
|
||||
// 2. Walk up from streamd (if the exe lives in bin/, start at the parent)
|
||||
// 2. Walk up from drm.exe (if the exe lives in bin/, start at the parent)
|
||||
func Root() string {
|
||||
if root := findRoot(wd()); root != "" {
|
||||
return root
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"drmdecryption/adb"
|
||||
)
|
||||
|
||||
// Pick selects among several matching nodes.
|
||||
|
|
|
|||
|
|
@ -1,172 +0,0 @@
|
|||
package wvkey
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Runtime is a resolved Python + wvkey.py pair ready for Fetch*.
|
||||
type Runtime struct {
|
||||
Python string
|
||||
Script string
|
||||
}
|
||||
|
||||
// ScriptPath returns <root>/apps/wvkey/wvkey.py.
|
||||
func ScriptPath(root string) string {
|
||||
return filepath.Join(root, "apps", "wvkey", "wvkey.py")
|
||||
}
|
||||
|
||||
// VenvPython returns the platform venv interpreter under root, if present.
|
||||
func VenvPython(root string) string {
|
||||
candidates := []string{
|
||||
filepath.Join(root, ".venv", "Scripts", "python.exe"),
|
||||
filepath.Join(root, ".venv", "bin", "python"),
|
||||
filepath.Join(root, ".venv", "bin", "python3"),
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if fileExists(c) {
|
||||
return c
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// EnsureRuntime makes sure wvkey.py exists and a usable Python with
|
||||
// pywidevine is available under root (creating .venv when needed).
|
||||
// Works on Windows, Linux, and macOS.
|
||||
func EnsureRuntime(root string) (Runtime, error) {
|
||||
var zero Runtime
|
||||
if root == "" {
|
||||
return zero, fmt.Errorf("wvkey: install root required")
|
||||
}
|
||||
script := ScriptPath(root)
|
||||
if !fileExists(script) {
|
||||
return zero, fmt.Errorf("wvkey script missing at %s — re-run streamd so bootstrap can materialise apps/wvkey/", script)
|
||||
}
|
||||
req := filepath.Join(root, "apps", "wvkey", "requirements.txt")
|
||||
|
||||
if py := VenvPython(root); py != "" {
|
||||
if hasPywidevine(py) {
|
||||
return Runtime{Python: py, Script: script}, nil
|
||||
}
|
||||
if err := pipInstall(py, req); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
if !hasPywidevine(py) {
|
||||
return zero, fmt.Errorf("wvkey: installed requirements but pywidevine still missing in %s", py)
|
||||
}
|
||||
return Runtime{Python: py, Script: script}, nil
|
||||
}
|
||||
|
||||
base, err := findSystemPython()
|
||||
if err != nil {
|
||||
return zero, err
|
||||
}
|
||||
venvDir := filepath.Join(root, ".venv")
|
||||
fmt.Fprintf(os.Stderr, "agent: creating Widevine venv at %s …\n", venvDir)
|
||||
if err := createVenv(base, venvDir); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
py := VenvPython(root)
|
||||
if py == "" {
|
||||
return zero, fmt.Errorf("wvkey: venv created at %s but no python binary found", venvDir)
|
||||
}
|
||||
if err := pipInstall(py, req); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
if !hasPywidevine(py) {
|
||||
return zero, fmt.Errorf("wvkey: pywidevine missing after pip install (%s)", py)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "agent: Widevine helper ready (%s)\n", py)
|
||||
return Runtime{Python: py, Script: script}, nil
|
||||
}
|
||||
|
||||
// FindPython prefers an existing install-root venv, then PATH helpers.
|
||||
func FindPython(root string) string {
|
||||
if root != "" {
|
||||
if py := VenvPython(root); py != "" {
|
||||
return py
|
||||
}
|
||||
}
|
||||
return findPython()
|
||||
}
|
||||
|
||||
func fileExists(path string) bool {
|
||||
st, err := os.Stat(path)
|
||||
return err == nil && !st.IsDir()
|
||||
}
|
||||
|
||||
func hasPywidevine(py string) bool {
|
||||
cmd := exec.Command(py, "-c", "import pywidevine")
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
func pipInstall(py, requirements string) error {
|
||||
if !fileExists(requirements) {
|
||||
return fmt.Errorf("wvkey: requirements missing at %s", requirements)
|
||||
}
|
||||
fmt.Fprintf(os.Stderr, "agent: pip install -r %s …\n", requirements)
|
||||
cmd := exec.Command(py, "-m", "pip", "install", "-r", requirements)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("wvkey: pip install failed: %w\n%s", err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createVenv(basePython, venvDir string) error {
|
||||
cmd := exec.Command(basePython, "-m", "venv", venvDir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return fmt.Errorf("wvkey: python -m venv %s failed: %w\n%s", venvDir, err, strings.TrimSpace(string(out)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func findSystemPython() (string, error) {
|
||||
var names []string
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
// Prefer the py launcher (real install) over the Store stub named "python".
|
||||
names = []string{"py", "python3", "python"}
|
||||
default:
|
||||
names = []string{"python3", "python"}
|
||||
}
|
||||
for _, name := range names {
|
||||
if name == "py" {
|
||||
// `py -3` on Windows
|
||||
if p, err := exec.LookPath("py"); err == nil {
|
||||
cmd := exec.Command(p, "-3", "-c", "import sys; print(sys.executable)")
|
||||
out, err := cmd.Output()
|
||||
if err == nil {
|
||||
exe := strings.TrimSpace(string(out))
|
||||
if fileExists(exe) {
|
||||
return exe, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
if p, err := exec.LookPath(name); err == nil {
|
||||
// Skip the WindowsApps Store alias stub when it cannot run -m venv.
|
||||
if runtime.GOOS == "windows" && strings.Contains(strings.ToLower(p), `windowsapps`) {
|
||||
cmd := exec.Command(p, "-c", "import sys; print(sys.executable)")
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
exe := strings.TrimSpace(string(out))
|
||||
if !fileExists(exe) || strings.Contains(strings.ToLower(exe), `windowsapps`) {
|
||||
continue
|
||||
}
|
||||
return exe, nil
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
}
|
||||
return "", fmt.Errorf("wvkey: no system Python found — install Python 3.10+ (Windows/macOS/Linux) so the agent can create .venv for Widevine keys")
|
||||
}
|
||||
|
|
@ -58,21 +58,14 @@ func FetchWrapAll(opt Options) ([]string, error) {
|
|||
}
|
||||
|
||||
func run(opt Options, mode string, all bool) ([]string, error) {
|
||||
py := resolvePython(opt.Python)
|
||||
py := opt.Python
|
||||
if py == "" {
|
||||
py = findPython()
|
||||
}
|
||||
script := opt.Script
|
||||
if script == "" {
|
||||
return nil, fmt.Errorf("wvkey script path required")
|
||||
}
|
||||
if !fileExists(script) {
|
||||
return nil, fmt.Errorf("wvkey script not found: %s", script)
|
||||
}
|
||||
if !fileExists(py) {
|
||||
// Bare names like "python3" are OK via LookPath inside resolvePython;
|
||||
// absolute/relative paths must exist.
|
||||
if filepath.IsAbs(py) || strings.Contains(py, string(os.PathSeparator)) || strings.Contains(py, "/") {
|
||||
return nil, fmt.Errorf("wvkey python not found: %s (run agent once to auto-create .venv, or set python: in agent.yaml)", py)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(opt.WVD) == "" {
|
||||
return nil, fmt.Errorf("wvkey --wvd path required")
|
||||
}
|
||||
|
|
@ -127,30 +120,12 @@ func run(opt Options, mode string, all bool) ([]string, error) {
|
|||
return out, nil
|
||||
}
|
||||
|
||||
// resolvePython uses an explicit path only when the file exists; otherwise
|
||||
// discovers a usable interpreter. Passing a missing absolute path used to make
|
||||
// exec fail with a confusing "not found in %PATH%" on Windows.
|
||||
func resolvePython(explicit string) string {
|
||||
if strings.TrimSpace(explicit) != "" {
|
||||
if st, err := os.Stat(explicit); err == nil && !st.IsDir() {
|
||||
return explicit
|
||||
}
|
||||
if !strings.Contains(explicit, string(os.PathSeparator)) && !strings.Contains(explicit, "/") {
|
||||
if p, err := exec.LookPath(explicit); err == nil {
|
||||
return p
|
||||
}
|
||||
}
|
||||
}
|
||||
return findPython()
|
||||
}
|
||||
|
||||
func findPython() string {
|
||||
candidates := []string{
|
||||
filepath.Join(".venv", "Scripts", "python.exe"),
|
||||
filepath.Join(".venv", "bin", "python"),
|
||||
"python3",
|
||||
"python",
|
||||
"py",
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ license URLs, manifests and auth headers.
|
|||
|
||||
```text
|
||||
apps/proxy/
|
||||
proxyctlcmd/ host CLI, hosted by bin/streamd as `streamd proxy`
|
||||
proxyctlcmd/ host CLI, hosted by bin/drm as `drm proxy`
|
||||
device/ linux/arm64 MITM source (module: appproxy)
|
||||
rteproxy-ca.crt MITM CA (subject hash 6c3578b4)
|
||||
```
|
||||
|
|
@ -17,8 +17,8 @@ working.
|
|||
## Build
|
||||
|
||||
```bash
|
||||
go -C apps/cli build -o ../../bin/streamd . # host CLI
|
||||
./bin/streamd proxy build # cross-compile the device binary
|
||||
go -C apps/cli build -o ../../bin/drm . # host CLI
|
||||
./bin/drm proxy build # cross-compile the device binary
|
||||
```
|
||||
|
||||
`proxy build` compiles `device/` for linux/arm64 into
|
||||
|
|
@ -28,20 +28,20 @@ go -C apps/cli build -o ../../bin/streamd . # host CLI
|
|||
|
||||
```bash
|
||||
# trust the MITM CA (needs Magisk; mounts into the system store)
|
||||
./bin/streamd proxy install-ca --reinject
|
||||
./bin/streamd proxy reinject-ca # mount only, CA already pushed
|
||||
./bin/drm proxy install-ca --reinject
|
||||
./bin/drm proxy reinject-ca # mount only, CA already pushed
|
||||
|
||||
# structured capture proxy
|
||||
./bin/streamd proxy start --install-ca --reinject
|
||||
./bin/streamd proxy stop
|
||||
./bin/drm proxy start --install-ca --reinject
|
||||
./bin/drm proxy stop
|
||||
|
||||
# record everything while you explore an unknown app
|
||||
./bin/streamd proxy discover --install-ca --reinject
|
||||
./bin/streamd proxy discover --force-stop <package> # so it inherits the CA mount
|
||||
./bin/drm proxy discover --install-ca --reinject
|
||||
./bin/drm proxy discover --force-stop <package> # so it inherits the CA mount
|
||||
|
||||
# pull artifacts without re-running, and release the phone
|
||||
./bin/streamd proxy pull
|
||||
./bin/streamd proxy clear-proxy
|
||||
./bin/drm proxy pull
|
||||
./bin/drm proxy clear-proxy
|
||||
```
|
||||
|
||||
Always clear the proxy when done, or the phone keeps pointing at a dead listener.
|
||||
|
|
@ -53,7 +53,7 @@ phone can stay on NordVPN UK; nothing sets `http_proxy`.
|
|||
|
||||
```bash
|
||||
# leave UK VPN connected on the phone, then:
|
||||
./bin/streamd proxy transparent --package bbc.iplayer.android --reinject
|
||||
./bin/drm proxy transparent --package bbc.iplayer.android --reinject
|
||||
# open the app / play — Ctrl+C stops iptables and pulls files
|
||||
```
|
||||
|
||||
|
|
@ -75,7 +75,7 @@ Force-stop the target app once after CA reinject so it inherits the Magisk CA mo
|
|||
|
||||
The device binary cannot read an app module's values file, so a module's
|
||||
manifest-scoring hosts are passed to it as flags (`--match`, `--score-host`,
|
||||
`--score-deny`). `streamd capture` does this automatically.
|
||||
`--score-deny`). `drm capture` does this automatically.
|
||||
|
||||
## Artifacts
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
module streamd/apps/proxy
|
||||
module drmdecryption/apps/proxy
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require streamd v0.0.0
|
||||
require drmdecryption v0.0.0
|
||||
|
||||
replace streamd => ../pkg
|
||||
replace drmdecryption => ../pkg
|
||||
|
|
|
|||
|
|
@ -18,9 +18,9 @@ import (
|
|||
"syscall"
|
||||
"time"
|
||||
|
||||
"streamd/adb"
|
||||
"streamd/proxy"
|
||||
"streamd/repo"
|
||||
"drmdecryption/adb"
|
||||
"drmdecryption/proxy"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
// Run dispatches a proxy subcommand. args[0] is the subcommand name.
|
||||
|
|
@ -130,7 +130,7 @@ func buildCmd(args []string) {
|
|||
|
||||
if _, err := os.Stat(deviceDir); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "proxy build needs the full source tree (apps/proxy/device).\n")
|
||||
fmt.Fprintf(os.Stderr, "For a release zip, put proxy-android-arm64 next to streamd instead — no Go build required.\n")
|
||||
fmt.Fprintf(os.Stderr, "For a release zip, put proxy-android-arm64 next to drm.exe instead — no Go build required.\n")
|
||||
fmt.Fprintf(os.Stderr, "Missing: %s\n", deviceDir)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
# streamd
|
||||
|
||||
Control plane: REST API, SQLite, dashboard and media supervisor. Hosted by the
|
||||
single binary as `streamd serve`.
|
||||
single binary as `drm serve`.
|
||||
|
||||
```text
|
||||
apps/streamd/
|
||||
|
|
@ -17,9 +17,7 @@ apps/streamd/
|
|||
## Run
|
||||
|
||||
```bash
|
||||
./bin/streamd serve --bind 127.0.0.1:8083
|
||||
# --data is optional: reuses existing .cache/streamd (cwd or next to the binary)
|
||||
# or set STREAMD_DATA / pass --data explicitly
|
||||
./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd
|
||||
```
|
||||
|
||||
`--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any
|
||||
|
|
|
|||
|
|
@ -1,15 +1,14 @@
|
|||
module streamd/apps/streamd
|
||||
module drmdecryption/apps/streamd
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
drmdecryption v0.0.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
modernc.org/sqlite v1.34.5
|
||||
streamd v0.0.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
replace streamd => ../pkg
|
||||
replace drmdecryption => ../pkg
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
|
|
@ -18,7 +17,6 @@ require (
|
|||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
modernc.org/libc v1.55.3 // indirect
|
||||
modernc.org/mathutil v1.6.0 // indirect
|
||||
modernc.org/memory v1.8.0 // indirect
|
||||
|
|
|
|||
|
|
@ -19,9 +19,6 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
|||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
|
||||
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
|
||||
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
|
||||
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
|
||||
|
|
|
|||
|
|
@ -10,12 +10,10 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/apps/streamd/internal/deps"
|
||||
"streamd/apps/streamd/internal/egress"
|
||||
"streamd/apps/streamd/internal/httpx"
|
||||
"streamd/apps/streamd/internal/modstore"
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/apps/streamd/internal/deps"
|
||||
"drmdecryption/apps/streamd/internal/httpx"
|
||||
)
|
||||
|
||||
type Supervisor interface {
|
||||
|
|
@ -58,11 +56,6 @@ type Handler struct {
|
|||
Deps deps.Status
|
||||
WWWRoot string // data/www — used to report variant playlist health
|
||||
LogRoot string // data/logs — source for the log tail endpoints
|
||||
DataDir string // streamd --data root
|
||||
Modules *modstore.Store
|
||||
// ModulesNotify is set when the hub supports module change pushes.
|
||||
ModulesNotify ModulesNotifier
|
||||
Egress *egress.Manager
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
|
|
@ -72,7 +65,6 @@ func (h *Handler) Mount(mux *http.ServeMux) {
|
|||
mux.HandleFunc("/api/streams/", h.streamAction)
|
||||
mux.HandleFunc("/api/overview", h.overview)
|
||||
h.MountControl(mux)
|
||||
h.MountEgress(mux)
|
||||
mux.HandleFunc("/api/apps", h.apps)
|
||||
mux.HandleFunc("/api/modules", h.modules)
|
||||
mux.HandleFunc("/api/modules/", h.modules)
|
||||
|
|
@ -542,7 +534,6 @@ func changeNote(before, after db.Stream, in db.PatchStream) string {
|
|||
add("key", in.Key != nil && before.Key != after.Key)
|
||||
add("headers", in.HeadersJSON != nil && before.HeadersJSON != after.HeadersJSON)
|
||||
add("proxy", in.Proxy != nil && before.Proxy != after.Proxy)
|
||||
add("egress", in.Egress != nil && before.Egress != after.Egress)
|
||||
add("variants", before.VariantsJSON != after.VariantsJSON)
|
||||
add("outputs", before.OutputsJSON != after.OutputsJSON)
|
||||
add("settings", before.SettingsJSON != after.SettingsJSON)
|
||||
|
|
@ -574,9 +565,6 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
|
|||
if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) {
|
||||
return true
|
||||
}
|
||||
if in.Egress != nil && strings.TrimSpace(before.Egress) != strings.TrimSpace(after.Egress) {
|
||||
return true
|
||||
}
|
||||
if in.VariantsJSON != nil || len(in.Variants) > 0 {
|
||||
if strings.TrimSpace(before.VariantsJSON) != strings.TrimSpace(after.VariantsJSON) {
|
||||
return true
|
||||
|
|
|
|||
|
|
@ -2,15 +2,11 @@ package api
|
|||
|
||||
import (
|
||||
"net/http"
|
||||
"sort"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/modstore"
|
||||
"streamd/modhost"
|
||||
"streamd/mpd"
|
||||
"streamd/repo"
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/modhost"
|
||||
"drmdecryption/mpd"
|
||||
"drmdecryption/repo"
|
||||
)
|
||||
|
||||
// appInfo describes one modules/<name>/ provider to the dashboard, so the UI
|
||||
|
|
@ -20,7 +16,6 @@ type appInfo struct {
|
|||
Channels []channelInfo `json:"channels"`
|
||||
Rewriter string `json:"rewriter"`
|
||||
HasConfig bool `json:"has_config"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type channelInfo struct {
|
||||
|
|
@ -28,9 +23,7 @@ type channelInfo struct {
|
|||
Label string `json:"label"`
|
||||
}
|
||||
|
||||
// apps answers GET /api/apps: which providers exist under the panel modules store.
|
||||
// A single module that fails to describe is skipped with an error field rather
|
||||
// than failing the whole list (bad uploads must not blank the stream pickers).
|
||||
// apps answers GET /api/apps: which providers exist under modules/.
|
||||
func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
|
|
@ -40,43 +33,21 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
out := []appInfo{}
|
||||
mods, err := modhost.Discover(repo.Root())
|
||||
listed, err := modhost.ListAll(repo.Root())
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
for _, m := range mods {
|
||||
bin, err := modhost.EnsureBuilt(m)
|
||||
if err != nil {
|
||||
info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}
|
||||
h.fillChannelsFromStore(&info, m.Name)
|
||||
out = append(out, info)
|
||||
h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
|
||||
continue
|
||||
}
|
||||
d, err := modhost.RunDescribe(bin)
|
||||
if err != nil {
|
||||
info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}
|
||||
h.fillChannelsFromStore(&info, m.Name)
|
||||
out = append(out, info)
|
||||
h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
|
||||
continue
|
||||
}
|
||||
if d.Name == "" {
|
||||
d.Name = m.Name
|
||||
}
|
||||
for _, L := range listed {
|
||||
d := L.Desc
|
||||
info := appInfo{Name: d.Name, Channels: []channelInfo{}, Rewriter: "none"}
|
||||
for _, ch := range d.Channels {
|
||||
info.Channels = append(info.Channels, channelInfo{ID: ch.ID, Label: ch.Label})
|
||||
}
|
||||
info.HasConfig = len(info.Channels) > 0
|
||||
if d.Rewriter != "" {
|
||||
info.Rewriter = d.Rewriter
|
||||
}
|
||||
// Older module binaries may not see the panel store; fill from module.yaml.
|
||||
if len(info.Channels) == 0 {
|
||||
h.fillChannelsFromStore(&info, m.Name)
|
||||
}
|
||||
info.HasConfig = len(info.Channels) > 0
|
||||
out = append(out, info)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
|
|
@ -84,53 +55,3 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
|
|||
"rewriters": mpd.Names(),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) fillChannelsFromStore(info *appInfo, name string) {
|
||||
if h == nil || h.Modules == nil || info == nil {
|
||||
return
|
||||
}
|
||||
chans := channelsFromStoreYAML(h.Modules, name)
|
||||
if len(chans) == 0 {
|
||||
return
|
||||
}
|
||||
info.Channels = chans
|
||||
info.HasConfig = true
|
||||
if info.Error != "" {
|
||||
// Soft: yaml channels recovered even though describe failed.
|
||||
info.Error = ""
|
||||
}
|
||||
}
|
||||
|
||||
// channelsFromStoreYAML reads channels from the panel module.yaml when describe
|
||||
// returns none (common with uploaded binaries that resolve values via cwd).
|
||||
func channelsFromStoreYAML(store *modstore.Store, name string) []channelInfo {
|
||||
if store == nil {
|
||||
return nil
|
||||
}
|
||||
raw, err := store.ReadYAML(name)
|
||||
if err != nil || len(raw) == 0 {
|
||||
return nil
|
||||
}
|
||||
var doc struct {
|
||||
Channels map[string]struct {
|
||||
Label string `yaml:"label"`
|
||||
} `yaml:"channels"`
|
||||
}
|
||||
if err := yaml.Unmarshal(raw, &doc); err != nil || len(doc.Channels) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]string, 0, len(doc.Channels))
|
||||
for id := range doc.Channels {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
sort.Strings(ids)
|
||||
out := make([]channelInfo, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
label := doc.Channels[id].Label
|
||||
if label == "" {
|
||||
label = id
|
||||
}
|
||||
out = append(out, channelInfo{ID: id, Label: label})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,45 +0,0 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"streamd/apps/streamd/internal/modstore"
|
||||
)
|
||||
|
||||
func TestChannelsFromStoreYAML(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
store := modstore.New(root)
|
||||
modDir := filepath.Join(root, "rte")
|
||||
if err := os.MkdirAll(modDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
yaml := []byte(`package: air.RTE
|
||||
channels:
|
||||
rteone:
|
||||
label: RTE One
|
||||
rtetwo:
|
||||
label: RTE 2
|
||||
`)
|
||||
if err := os.WriteFile(filepath.Join(modDir, "module.yaml"), yaml, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chans := channelsFromStoreYAML(store, "rte")
|
||||
if len(chans) != 2 {
|
||||
t.Fatalf("got %d channels: %+v", len(chans), chans)
|
||||
}
|
||||
if chans[0].ID != "rteone" || chans[0].Label != "RTE One" {
|
||||
t.Fatalf("first channel: %+v", chans[0])
|
||||
}
|
||||
if chans[1].ID != "rtetwo" {
|
||||
t.Fatalf("second channel: %+v", chans[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestChannelsFromStoreYAMLMissing(t *testing.T) {
|
||||
store := modstore.New(t.TempDir())
|
||||
if chans := channelsFromStoreYAML(store, "nope"); chans != nil {
|
||||
t.Fatalf("expected nil, got %+v", chans)
|
||||
}
|
||||
}
|
||||
|
|
@ -11,9 +11,9 @@ import (
|
|||
"strings"
|
||||
"time"
|
||||
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
"streamd/mpd"
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
"drmdecryption/mpd"
|
||||
)
|
||||
|
||||
// MountControl adds the bulk, duplicate, probe, settings and schedule routes.
|
||||
|
|
@ -162,7 +162,6 @@ func (h *Handler) duplicate(w http.ResponseWriter, r *http.Request, id int64) {
|
|||
Key: src.Key,
|
||||
HeadersJSON: src.HeadersJSON,
|
||||
Proxy: src.Proxy,
|
||||
Egress: src.Egress,
|
||||
VideoSelect: src.VideoSelect,
|
||||
AudioSelect: src.AudioSelect,
|
||||
Rewriter: src.Rewriter,
|
||||
|
|
@ -272,19 +271,9 @@ func (h *Handler) doProbe(ctx context.Context, st db.Stream, target string) prob
|
|||
start := time.Now()
|
||||
|
||||
client := &http.Client{Timeout: 20 * time.Second}
|
||||
// Fetch through the stream's effective proxy (explicit or named egress),
|
||||
// so a geo-restricted origin is probed the same way the downloader would.
|
||||
proxy := strings.TrimSpace(st.Proxy)
|
||||
if h.Egress != nil {
|
||||
if p, err := h.Egress.ResolveProxy(st); err == nil {
|
||||
proxy = p
|
||||
} else if strings.TrimSpace(st.Egress) != "" && proxy == "" {
|
||||
res.Error = "egress: " + err.Error()
|
||||
res.Summary = "egress profile could not be brought up"
|
||||
return res
|
||||
}
|
||||
}
|
||||
if proxy != "" {
|
||||
// Fetch through the stream's own proxy, so a geo-restricted origin is
|
||||
// probed the same way the downloader would reach it.
|
||||
if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
|
||||
if c, err := httpClientWithProxy(proxy); err == nil {
|
||||
client = c
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -1,254 +0,0 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"streamd/apps/streamd/internal/auth"
|
||||
"streamd/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
// MountEgress registers /api/egress routes.
|
||||
func (h *Handler) MountEgress(mux *http.ServeMux) {
|
||||
mux.HandleFunc("/api/egress", h.egressRoot)
|
||||
mux.HandleFunc("/api/egress/", h.egressAction)
|
||||
}
|
||||
|
||||
func (h *Handler) egressRoot(w http.ResponseWriter, r *http.Request) {
|
||||
if h.Egress == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "egress manager not configured")
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
list, err := h.Store.ListEgressProfiles()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
for i := range list {
|
||||
h.Egress.Enrich(&list[i])
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"profiles": list})
|
||||
case http.MethodPost:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var in db.CreateEgressProfile
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
prof, err := h.Store.CreateEgressProfile(in)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.Egress.Enrich(&prof)
|
||||
h.audit(r, p, http.StatusOK, "create egress "+prof.Name)
|
||||
writeJSON(w, http.StatusOK, prof)
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) egressAction(w http.ResponseWriter, r *http.Request) {
|
||||
if h.Egress == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "egress manager not configured")
|
||||
return
|
||||
}
|
||||
path := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/egress/"), "/")
|
||||
if path == "" {
|
||||
h.egressRoot(w, r)
|
||||
return
|
||||
}
|
||||
parts := strings.Split(path, "/")
|
||||
name := db.Slug(parts[0])
|
||||
if name == "" {
|
||||
writeErr(w, http.StatusBadRequest, "invalid name")
|
||||
return
|
||||
}
|
||||
action := ""
|
||||
if len(parts) > 1 {
|
||||
action = strings.ToLower(parts[1])
|
||||
}
|
||||
|
||||
switch {
|
||||
case action == "" && r.Method == http.MethodGet:
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
prof, err := h.Egress.Status(name)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, prof)
|
||||
|
||||
case action == "" && r.Method == http.MethodPut:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h.putEgress(w, r, p, name)
|
||||
|
||||
case action == "" && r.Method == http.MethodDelete:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
prof, err := h.Store.GetEgressProfileByName(name)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
_ = h.Egress.Down(name)
|
||||
if err := h.Store.DeleteEgressProfile(prof.ID); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
_ = h.Egress.RemoveFiles(name)
|
||||
h.audit(r, p, http.StatusOK, "delete egress "+name)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
|
||||
case action == "up" && r.Method == http.MethodPost:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.Egress.EnsureUp(name); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
prof, _ := h.Egress.Status(name)
|
||||
h.audit(r, p, http.StatusOK, "egress up "+name)
|
||||
writeJSON(w, http.StatusOK, prof)
|
||||
|
||||
case action == "down" && r.Method == http.MethodPost:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := h.Egress.Down(name); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
prof, _ := h.Egress.Status(name)
|
||||
h.audit(r, p, http.StatusOK, "egress down "+name)
|
||||
writeJSON(w, http.StatusOK, prof)
|
||||
|
||||
case action == "test" && r.Method == http.MethodPost:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
out, err := h.Egress.TestDial(name)
|
||||
if err != nil {
|
||||
if out == nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "egress test "+name+" fail")
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
return
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "egress test "+name)
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
|
||||
case action == "conf" && r.Method == http.MethodPut:
|
||||
p, ok := auth.Guard(w, r, auth.RoleAdmin)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
_ = r.Body.Close()
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
contents := string(body)
|
||||
ct := r.Header.Get("Content-Type")
|
||||
if strings.Contains(ct, "json") || strings.HasPrefix(strings.TrimSpace(contents), "{") {
|
||||
var in struct {
|
||||
Conf string `json:"conf"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &in); err != nil || strings.TrimSpace(in.Conf) == "" {
|
||||
writeErr(w, http.StatusBadRequest, "conf required")
|
||||
return
|
||||
}
|
||||
contents = in.Conf
|
||||
}
|
||||
if strings.TrimSpace(contents) == "" {
|
||||
writeErr(w, http.StatusBadRequest, "empty conf")
|
||||
return
|
||||
}
|
||||
if _, err := h.Store.GetEgressProfileByName(name); err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
if err := h.Egress.WriteConf(name, contents); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
prof, _ := h.Egress.Status(name)
|
||||
h.audit(r, p, http.StatusOK, "egress conf "+name)
|
||||
writeJSON(w, http.StatusOK, prof)
|
||||
|
||||
default:
|
||||
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) putEgress(w http.ResponseWriter, r *http.Request, p *auth.Principal, name string) {
|
||||
prof, err := h.Store.GetEgressProfileByName(name)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "not found")
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
SocksURL *string `json:"socks_url"`
|
||||
Kind *string `json:"kind"`
|
||||
Conf *string `json:"conf"`
|
||||
}
|
||||
if err := readJSON(r, &in); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
upd, err := h.Store.UpdateEgressProfile(prof.ID, db.UpdateEgressProfile{
|
||||
Enabled: in.Enabled, SocksURL: in.SocksURL, Kind: in.Kind,
|
||||
})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if in.Conf != nil && strings.TrimSpace(*in.Conf) != "" {
|
||||
if err := h.Egress.WriteConf(name, *in.Conf); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
h.Egress.Enrich(&upd)
|
||||
if in.Enabled != nil && *in.Enabled {
|
||||
_ = h.Egress.EnsureUp(name)
|
||||
upd, _ = h.Egress.Status(name)
|
||||
}
|
||||
if in.Enabled != nil && !*in.Enabled {
|
||||
_ = h.Egress.Down(name)
|
||||
upd, _ = h.Egress.Status(name)
|
||||
}
|
||||
h.audit(r, p, http.StatusOK, "update egress "+name)
|
||||
writeJSON(w, http.StatusOK, upd)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue