diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index e9181c7..fc1d1ba 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -1,7 +1,16 @@ -# Build multi-platform drm binaries + Android MITM and attach them to a Forgejo release. +# Build multi-platform streamd binaries + Android MITM and attach them to a Forgejo release. # -# Trigger: push a version tag -# git tag v1.2.3 && git push origin v1.2.3 +# 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-
→ prerelease + update `beta` (always-latest beta URL)
+#
+# Download without pinning a version:
+# .../releases/download/stable/streamd-linux-amd64
+# .../releases/download/beta/streamd-linux-amd64
#
# Requires a Forgejo Actions runner registered against this instance
# (label must match runs-on below — default act_runner often uses "docker").
@@ -23,6 +32,35 @@ 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:
@@ -37,44 +75,91 @@ jobs:
./scripts/build-release.sh "${{ github.ref_name }}"
ls -la dist/release
- - name: Upload to Forgejo 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 <\`
+ - Beta: \`…/releases/download/beta/\`
+
+ 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 <
@@ -64,15 +64,55 @@ Server setup guide: [docs/streamd-server-setup.md](docs/streamd-server-setup.md)
### 1️⃣ Download
-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`).
+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`.
```text
-Null-DRM/
- drm.exe # or ./drm on Linux/macOS
- bin/proxy-android-arm64 # optional; also embedded in release drm
- modules/
+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
bbc/ # unzip bbc.zip here
rte/
tg4/
@@ -81,7 +121,7 @@ Null-DRM/
outputs/ # created on first run
```
-On first run, `drm` creates the install scaffold next to the exe.
+On first run, `streamd` creates the install scaffold next to the exe.
### 2️⃣ Prerequisites
@@ -99,14 +139,14 @@ Unzip into `modules//`. Edit **`module.yaml`** — fill sensitive fields o
almost nothing extra.
```bash
-drm modules
-# or: drm --modules-dir D:\mods modules
+streamd modules
+# or: streamd --modules-dir D:\mods modules
```
### 4️⃣ Phone CA (once per device / CA)
```bash
-drm proxy install-ca --reinject
+streamd proxy install-ca --reinject
adb shell am force-stop bbc.iplayer.android # or the app you will capture
```
@@ -114,25 +154,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)
-drm capture --app bbc --channel bbcone --wait 120
-drm capture --app bbc --channel s4c --wait 120
+streamd capture --app bbc --channel bbcone --wait 120
+streamd capture --app bbc --channel s4c --wait 120
# ITVX (UK VPN; Live tab autoplay)
-drm capture --app itv --channel itv1 --wait 90
+streamd capture --app itv --channel itv1 --wait 90
# Channel 4 — one channel, or every Live channel
-drm capture --app c4 --channel channel4 --wait 90
-drm capture --app c4 --all --wait 90
+streamd capture --app c4 --channel channel4 --wait 90
+streamd capture --app c4 --all --wait 90
# Grab every channel for any module
-drm capture --app itv --all --wait 90
+streamd capture --app itv --all --wait 90
# RTE / TG4 (keys via --wvd when needed)
-drm capture --app rte --channel rteone --wvd data/device.wvd
-drm capture --app tg4 --channel ioi --wvd data/device.wvd
+streamd capture --app rte --channel rteone --wvd data/device.wvd
+streamd capture --app tg4 --channel ioi --wvd data/device.wvd
# Catalog only (no phone) — TG4
-drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
+streamd catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
```
📁 Results land in `outputs///` (and `latest/`).
@@ -140,7 +180,7 @@ drm catalog --app tg4 --channel ioi --keys --wvd data/device.wvd --json
### 6️⃣ Clean the phone after a run
```bash
-drm proxy reset
+streamd proxy reset
```
Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fresh.
@@ -150,19 +190,19 @@ Stops MITM/iptables and deletes pushed CA/binaries so the next capture starts fr
## 🧾 Command cheat sheet
```text
-drm [--modules-dir DIR] …
+streamd [--modules-dir DIR] …
-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]
+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]
| transparent --package PKG [--mitm-host HOST]
| start | stop | push | discover | pull
-drm serve [--bind …] [--data …] [--token …]
-drm agent run|status|devices|enqueue|cancel [--config …]
+streamd serve [--bind …] [--data …] [--token …]
+streamd agent run|status|devices|enqueue|cancel [--config …]
```
-🌍 Global: `--modules-dir DIR` or `$DRM_MODULES_DIR` (default: `./modules`).
+🌍 Global: `--modules-dir DIR` or `$STREAMD_MODULES_DIR` (default: `./modules`).
🎯 `--channel` implies interactive auto-play (provider-specific Live UI flow).
@@ -185,7 +225,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/drm.exe . # Windows
+go -C apps/cli build -o ../../bin/streamd.exe . # Windows
# Host release: .\scripts\build-release.ps1 -Version v0.1.1
# Modules: .\scripts\build-modules-release.ps1 -Version modules-v0.1.1
```
@@ -196,7 +236,7 @@ More detail: [docs/quickstart.md](docs/quickstart.md) · [docs/architecture.md](
## 💚 Support the project
-If Null DRM saves you time, donations keep development going:
+If Streamd saves you time, donations keep development going:
| Coin | Address |
|------|---------|
diff --git a/apps/agent/README.md b/apps/agent/README.md
index 44fe6ae..a27d6de 100644
--- a/apps/agent/README.md
+++ b/apps/agent/README.md
@@ -1,6 +1,6 @@
# agent
-Always-on credentials refresher, hosted by the single binary as `drm agent`.
+Always-on credentials refresher, hosted by the single binary as `streamd agent`.
```text
apps/agent/
@@ -26,43 +26,54 @@ expire by themselves if the agent dies.
```bash
# terminal 1 — control plane
-./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd
+./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
-# terminal 2 — agent (operator API key from streamd Settings → API keys)
+# terminal 2 — agent in the background (Linux / macOS / Windows)
export STREAMD_API_KEY=ndk_…
-# or legacy: export STREAMD_TOKEN=…
-./bin/drm agent run --config apps/agent/agent.yaml
+./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]
```
```bash
-./bin/drm agent status
-./bin/drm agent devices
-./bin/drm agent enqueue --stream tg4-ioi --reason manual
-./bin/drm agent cancel --job 3
+./bin/streamd agent devices
+./bin/streamd agent enqueue --stream tg4-ioi --reason manual
+./bin/streamd agent cancel --job 3
```
-App modules are discovered under `modules/`. The agent drives whichever module a
-stream names and contains no provider logic.
+With `sync_modules: true` (default in the sample config), the agent **pulls**
+provider modules from the streamd Modules page into `/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.
## 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`.
+`wvd`, `user_agent`, `agent_id`, `data_dir`, `sync_modules`, `modules_dir`
+(default `/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`.
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.
+`wvd` must be set or key fetches fail. On first `agent start`/`run`, streamd
+bootstraps `apps/wvkey/` and creates `/.venv` with `pywidevine` using
+the system Python (Windows, Linux, or macOS) so Widevine key fetch works without
+a hand-made venv.
## Build
```bash
-go -C apps/cli build -o ../../bin/drm .
+go -C apps/cli build -o ../../bin/streamd .
# cross-compile
-GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/drm .
+GOOS=darwin GOARCH=arm64 go -C apps/cli build -o ../../bin/streamd .
```
**Full guide: [docs/streamd.md](../../docs/streamd.md)**
diff --git a/apps/agent/agent.yaml b/apps/agent/agent.yaml
index 0bf5550..4b7b511 100644
--- a/apps/agent/agent.yaml
+++ b/apps/agent/agent.yaml
@@ -14,12 +14,23 @@ workers: 1 # concurrent ADB jobs
max_attempts: 5
capture_wait_sec: 180
devices: [] # empty = all adb "device" serials; never installs apps
-# Push local modules//module.yaml to streamd when missing or SHA differs.
+# Pull modules from the streamd panel into the local cache (package.zip + yaml).
sync_modules: true
-# modules_dir: modules # optional override (default: repo modules/)
+# modules_dir: # optional; default /modules
# modules_sync_interval_sec: 300
-# Required for key fetch. Relative paths resolve from the repo root
-# (DRM-Decryption/), not from C:\Users\admin\Programming\.
-wvd:
+# 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 = /.venv/…
+wvd: data/device.wvd
# user_agent: "" # optional license-request User-Agent
diff --git a/apps/agent/agentcmd/agentcmd.go b/apps/agent/agentcmd/agentcmd.go
index a104e32..9329025 100644
--- a/apps/agent/agentcmd/agentcmd.go
+++ b/apps/agent/agentcmd/agentcmd.go
@@ -9,17 +9,21 @@ import (
"os"
"os/signal"
"strconv"
+ "strings"
"syscall"
"text/tabwriter"
- "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"
+ "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"
)
// Run dispatches an agent subcommand. args[0] is the subcommand name.
@@ -35,6 +39,14 @@ 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":
@@ -57,8 +69,13 @@ func Usage() {
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
Usage:
- agent run [--config apps/agent/agent.yaml]
- agent status [--config ...]
+ 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 devices [--config ...]
agent enqueue --stream NAME [--reason manual] [--config ...]
agent cancel --job ID [--config ...]
@@ -67,6 +84,9 @@ 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.
`)
}
@@ -116,6 +136,18 @@ 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()
@@ -124,6 +156,16 @@ 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{})
@@ -137,15 +179,25 @@ 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 sync enabled interval=%s", cfg.ModulesSyncInterval())
+ log.Printf("modules pull sync enabled interval=%s dir=%s", cfg.ModulesSyncInterval(), cfg.ModulesDir)
}
ws := wsclient.New(cfg.StreamdURL, cfg.Token, cfg.AgentID, log.Default())
@@ -171,6 +223,16 @@ 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++ {
@@ -184,6 +246,7 @@ 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)
@@ -204,6 +267,7 @@ 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)
diff --git a/apps/agent/agentcmd/daemon.go b/apps/agent/agentcmd/daemon.go
new file mode 100644
index 0000000..b258c71
--- /dev/null
+++ b/apps/agent/agentcmd/daemon.go
@@ -0,0 +1,177 @@
+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")
+}
diff --git a/apps/agent/agentcmd/daemon_unix.go b/apps/agent/agentcmd/daemon_unix.go
new file mode 100644
index 0000000..14eb237
--- /dev/null
+++ b/apps/agent/agentcmd/daemon_unix.go
@@ -0,0 +1,37 @@
+//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)
+}
diff --git a/apps/agent/agentcmd/daemon_windows.go b/apps/agent/agentcmd/daemon_windows.go
new file mode 100644
index 0000000..ce8e088
--- /dev/null
+++ b/apps/agent/agentcmd/daemon_windows.go
@@ -0,0 +1,46 @@
+//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)
+}
diff --git a/apps/agent/agentcmd/update.go b/apps/agent/agentcmd/update.go
new file mode 100644
index 0000000..6b0e04d
--- /dev/null
+++ b/apps/agent/agentcmd/update.go
@@ -0,0 +1,282 @@
+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, "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
+}
diff --git a/apps/agent/go.mod b/apps/agent/go.mod
index c3aa50f..c912a7b 100644
--- a/apps/agent/go.mod
+++ b/apps/agent/go.mod
@@ -1,12 +1,12 @@
-module drmdecryption/apps/agent
+module streamd/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,11 +15,10 @@ 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 drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/agent/go.sum b/apps/agent/go.sum
index 5ef9a1c..58f3755 100644
--- a/apps/agent/go.sum
+++ b/apps/agent/go.sum
@@ -1,7 +1,5 @@
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=
@@ -14,8 +12,6 @@ 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=
@@ -23,8 +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=
-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=
diff --git a/apps/agent/internal/client/client.go b/apps/agent/internal/client/client.go
index 0ddaa5c..ba96c65 100644
--- a/apps/agent/internal/client/client.go
+++ b/apps/agent/internal/client/client.go
@@ -7,6 +7,7 @@ import (
"fmt"
"io"
"net/http"
+ "os"
"strings"
"time"
)
@@ -180,9 +181,13 @@ func (c *Client) PostEvent(streamID int64, kind, message string, detail map[stri
// ModuleInfo is one modules// entry from GET /api/modules.
type ModuleInfo struct {
- Name string `json:"name"`
- HasYAML bool `json:"has_yaml"`
- YAMLSHA256 string `json:"yaml_sha256,omitempty"`
+ 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) {
@@ -199,30 +204,64 @@ func (c *Client) ListModules() ([]ModuleInfo, error) {
return wrap.Modules, 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))
+// 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)
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()
- body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode >= 300 {
- return c.statusError(http.MethodPut, "/api/modules/"+name, resp, body)
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ return c.statusError(http.MethodGet, "/api/modules/"+name+"/package", resp, body)
}
- return nil
+ 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)
}
func (c *Client) setHeaders(req *http.Request) {
ua := c.UserAgent
if ua == "" {
- ua = "drm-agent/" + Version
+ ua = "streamd-agent/" + Version
}
req.Header.Set("User-Agent", ua)
if c.Token != "" {
diff --git a/apps/agent/internal/config/config.go b/apps/agent/internal/config/config.go
index 2239f5a..0391f2b 100644
--- a/apps/agent/internal/config/config.go
+++ b/apps/agent/internal/config/config.go
@@ -7,7 +7,7 @@ import (
"gopkg.in/yaml.v3"
- "drmdecryption/repo"
+ "streamd/repo"
)
type Config struct {
@@ -27,14 +27,25 @@ 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 pushes local modules//module.yaml to streamd when missing/stale.
+ // SyncModules pulls modules from streamd into the local cache when missing/stale.
SyncModules bool `yaml:"sync_modules"`
- ModulesDir string `yaml:"modules_dir"` // empty = repo modules/
+ ModulesDir string `yaml:"modules_dir"` // empty = /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.
@@ -43,6 +54,12 @@ 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
@@ -124,12 +141,36 @@ func applyDefaults(cfg Config, root string) Config {
if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) {
cfg.WVD = filepath.Join(root, cfg.WVD)
}
- if cfg.ModulesDir != "" && !filepath.IsAbs(cfg.ModulesDir) {
+ 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) {
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
}
diff --git a/apps/agent/internal/device/pool.go b/apps/agent/internal/device/pool.go
index a9800b4..5d5eab1 100644
--- a/apps/agent/internal/device/pool.go
+++ b/apps/agent/internal/device/pool.go
@@ -4,7 +4,7 @@ import (
"fmt"
"sync"
- "drmdecryption/adb"
+ "streamd/adb"
)
// Pool tracks free/busy ADB devices. Never installs apps.
diff --git a/apps/agent/internal/modsync/sync.go b/apps/agent/internal/modsync/sync.go
index 5563db0..5fa3c0d 100644
--- a/apps/agent/internal/modsync/sync.go
+++ b/apps/agent/internal/modsync/sync.go
@@ -1,26 +1,32 @@
-// Package modsync pushes local modules//module.yaml to streamd
-// when the remote copy is missing or the SHA-256 differs.
+// 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
import (
+ "archive/zip"
"crypto/sha256"
"encoding/hex"
+ "fmt"
+ "io"
"log"
"os"
"path/filepath"
+ "runtime"
"strings"
"time"
- "drmdecryption/apps/agent/internal/client"
- "drmdecryption/modhost"
- "drmdecryption/repo"
+ "streamd/apps/agent/internal/client"
+ "streamd/modhost"
+ "streamd/repo"
)
-// Syncer compares local module.yaml files to streamd and PUTs updates.
+// Syncer keeps the local modules cache aligned with streamd.
type Syncer struct {
API *client.Client
- ModulesDir string // empty = modhost.ModulesDir(repo.Root())
+ ModulesDir string // empty = /modules resolved by caller, or modhost default
Interval time.Duration
+ Prune bool // remove local modules absent from the panel
Log *log.Logger
}
@@ -31,15 +37,10 @@ func (s *Syncer) modulesDir() string {
return modhost.ModulesDir(repo.Root())
}
-// Once uploads every local module.yaml that is missing or stale on streamd.
+// Once pulls every remote module that is missing or stale locally.
func (s *Syncer) Once() error {
dir := s.modulesDir()
- ents, err := os.ReadDir(dir)
- if err != nil {
- if os.IsNotExist(err) {
- s.logf("modules sync: no local dir %s", dir)
- return nil
- }
+ if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
@@ -47,42 +48,139 @@ func (s *Syncer) Once() error {
if err != nil {
return err
}
- byName := make(map[string]client.ModuleInfo, len(remote))
+ seen := map[string]struct{}{}
for _, m := range remote {
- byName[m.Name] = m
+ 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[:])
}
+ 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
}
- name := e.Name()
- yamlPath := filepath.Join(dir, name, "module.yaml")
- raw, err := os.ReadFile(yamlPath)
- if err != nil {
- if os.IsNotExist(err) {
- continue
- }
- s.logf("modules sync: read %s: %v", yamlPath, err)
+ if _, ok := keep[e.Name()]; ok {
continue
}
- sum := sha256.Sum256(raw)
- localSHA := hex.EncodeToString(sum[:])
- rm, ok := byName[name]
- if ok && rm.HasYAML && strings.EqualFold(rm.YAMLSHA256, localSHA) {
+ path := filepath.Join(dir, e.Name())
+ if err := os.RemoveAll(path); err != nil {
+ s.logf("modules sync: prune %s: %v", e.Name(), err)
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)
- }
+ s.logf("modules sync: pruned %s", e.Name())
}
- return nil
}
// Loop runs Once immediately, then on Interval until stop closes.
@@ -119,3 +217,161 @@ 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
+}
diff --git a/apps/agent/internal/modsync/sync_test.go b/apps/agent/internal/modsync/sync_test.go
new file mode 100644
index 0000000..0e5c3bd
--- /dev/null
+++ b/apps/agent/internal/modsync/sync_test.go
@@ -0,0 +1,154 @@
+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)
+ }
+}
diff --git a/apps/agent/internal/poller/poller.go b/apps/agent/internal/poller/poller.go
index 2014717..5195e87 100644
--- a/apps/agent/internal/poller/poller.go
+++ b/apps/agent/internal/poller/poller.go
@@ -6,8 +6,8 @@ import (
"strings"
"time"
- "drmdecryption/apps/agent/internal/client"
- "drmdecryption/apps/agent/internal/queue"
+ "streamd/apps/agent/internal/client"
+ "streamd/apps/agent/internal/queue"
)
type Poller struct {
diff --git a/apps/agent/internal/queue/queue.go b/apps/agent/internal/queue/queue.go
index 40411bb..04a44b0 100644
--- a/apps/agent/internal/queue/queue.go
+++ b/apps/agent/internal/queue/queue.go
@@ -232,17 +232,18 @@ func (s *Store) MarkOK(id int64) error {
return err
}
-// MarkFailed increments attempts. Re-queues with backoff unless maxed out.
+// MarkFailed increments attempts. Re-queues unless maxed out.
// waitingDevice=true keeps status queued without burning an attempt.
-func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error {
+// 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 {
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='' WHERE id=?`,
- msg, id)
+UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`,
+ msg, now(), id)
return err
}
attempts := j.Attempts + 1
@@ -252,9 +253,8 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i
attempts, msg, now(), id)
return err
}
- backoff := time.Duration(1< 15*time.Minute {
- backoff = 15 * time.Minute
+ if backoff < 0 {
+ backoff = 0
}
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
_, err = s.DB.Exec(`
@@ -263,6 +263,29 @@ 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< 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
diff --git a/apps/agent/internal/worker/worker.go b/apps/agent/internal/worker/worker.go
index ea009f4..c399bd6 100644
--- a/apps/agent/internal/worker/worker.go
+++ b/apps/agent/internal/worker/worker.go
@@ -7,14 +7,14 @@ import (
"strings"
"time"
- "drmdecryption/modhost"
- "drmdecryption/phonecap"
- "drmdecryption/repo"
+ "streamd/modhost"
+ "streamd/phonecap"
+ "streamd/repo"
- "drmdecryption/apps/agent/internal/client"
- "drmdecryption/apps/agent/internal/device"
- "drmdecryption/apps/agent/internal/poller"
- "drmdecryption/apps/agent/internal/queue"
+ "streamd/apps/agent/internal/client"
+ "streamd/apps/agent/internal/device"
+ "streamd/apps/agent/internal/poller"
+ "streamd/apps/agent/internal/queue"
)
type Worker struct {
@@ -27,7 +27,10 @@ type Worker struct {
Python string
WVD string
UserAgent string
- Log *log.Logger
+ // 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
}
@@ -67,13 +70,18 @@ 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)
+ _ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
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})
- _ = w.Queue.MarkFailed(job.ID, err.Error(), false)
+ 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)
return
}
_ = w.Queue.MarkOK(job.ID)
@@ -119,8 +127,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())
- // Short TTL; /ws/agent heartbeats renew while this process is alive.
- if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil {
+ // Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
+ if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
return fmt.Errorf("streamd claim: %w", err)
}
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
@@ -140,6 +148,19 @@ 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,
@@ -150,15 +171,25 @@ 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": poller.ValidKeyPair(res.Key),
+ "key_valid": hasKey,
})
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) {
diff --git a/apps/agent/internal/wsclient/wsclient.go b/apps/agent/internal/wsclient/wsclient.go
index 05400c7..b37ac6c 100644
--- a/apps/agent/internal/wsclient/wsclient.go
+++ b/apps/agent/internal/wsclient/wsclient.go
@@ -11,7 +11,7 @@ import (
"github.com/gorilla/websocket"
- "drmdecryption/apps/agent/internal/client"
+ "streamd/apps/agent/internal/client"
)
// Message is one push from streamd.
@@ -42,6 +42,9 @@ 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{}
}
@@ -111,7 +114,7 @@ func (c *Client) session() error {
if c.AgentID != "" {
hdr.Set("X-Agent-ID", c.AgentID)
}
- hdr.Set("User-Agent", "drm-agent/"+client.Version)
+ hdr.Set("User-Agent", "streamd-agent/"+client.Version)
dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
conn, resp, err := dialer.Dial(u.String(), hdr)
if err != nil {
@@ -190,6 +193,11 @@ 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)
+ }
}
}
diff --git a/apps/capture/README.md b/apps/capture/README.md
index 4274d50..f34b0f7 100644
--- a/apps/capture/README.md
+++ b/apps/capture/README.md
@@ -1,6 +1,6 @@
# capture
-One-shot phone MITM capture, hosted by the single binary as `drm capture`.
+One-shot phone MITM capture, hosted by the single binary as `streamd capture`.
```text
apps/capture/
@@ -8,17 +8,17 @@ apps/capture/
```
```bash
-./bin/drm capture # passive: play anything
-./bin/drm capture --app rte # launch, navigate by hand
-./bin/drm capture --app rte --channel rteone --auto-play \
+./bin/streamd capture # passive: play anything
+./bin/streamd capture --app rte # launch, navigate by hand
+./bin/streamd capture --app rte --channel rteone --auto-play \
--wvd data/device.wvd # fully automated
```
Writes `outputs///` plus `latest/`. App modules are compiled in, so
-there is no modules directory to point at; `drm modules` lists what is available.
+there is no modules directory to point at; `streamd 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 `drm catalog` (`apps/cli/catalogcmd`).
+provider-agnostic `streamd catalog` (`apps/cli/catalogcmd`).
diff --git a/apps/capture/capturecmd/capturecmd.go b/apps/capture/capturecmd/capturecmd.go
index 8c93c66..c76e01d 100644
--- a/apps/capture/capturecmd/capturecmd.go
+++ b/apps/capture/capturecmd/capturecmd.go
@@ -12,16 +12,16 @@ import (
"time"
"unicode"
- "drmdecryption/adb"
- "drmdecryption/app"
- "drmdecryption/modcfg"
- "drmdecryption/modhost"
- "drmdecryption/phonecap"
- "drmdecryption/repo"
+ "streamd/adb"
+ "streamd/app"
+ "streamd/modcfg"
+ "streamd/modhost"
+ "streamd/phonecap"
+ "streamd/repo"
)
// Run performs one capture. Providers live under modules// and are built
-// and executed by modhost — they are not linked into drm.exe.
+// and executed by modhost — they are not linked into streamd.
func Run(args []string) error {
args = normalizeArgs(args)
diff --git a/apps/capture/go.mod b/apps/capture/go.mod
index af6edc7..e575d3d 100644
--- a/apps/capture/go.mod
+++ b/apps/capture/go.mod
@@ -1,13 +1,9 @@
-module drmdecryption/apps/capture
+module streamd/apps/capture
go 1.25.0
-require drmdecryption v0.0.0
+require streamd v0.0.0
-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
-)
+require gopkg.in/yaml.v3 v3.0.1 // indirect
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/capture/go.sum b/apps/capture/go.sum
index 908fb03..a62c313 100644
--- a/apps/capture/go.sum
+++ b/apps/capture/go.sum
@@ -1,11 +1,3 @@
-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=
diff --git a/apps/cli/capture_args_test.go b/apps/cli/capture_args_test.go
index ef8a084..c533f80 100644
--- a/apps/cli/capture_args_test.go
+++ b/apps/cli/capture_args_test.go
@@ -4,7 +4,7 @@ import (
"strings"
"testing"
- "drmdecryption/apps/capture/capturecmd"
+ "streamd/apps/capture/capturecmd"
)
func TestCaptureRejectsChannelAsApp(t *testing.T) {
diff --git a/apps/cli/catalogcmd/catalogcmd.go b/apps/cli/catalogcmd/catalogcmd.go
index b45ba90..4f5a782 100644
--- a/apps/cli/catalogcmd/catalogcmd.go
+++ b/apps/cli/catalogcmd/catalogcmd.go
@@ -11,9 +11,9 @@ import (
"sort"
"strings"
- "drmdecryption/modhost"
- "drmdecryption/repo"
- "drmdecryption/session"
+ "streamd/modhost"
+ "streamd/repo"
+ "streamd/session"
)
// Run performs a catalog lookup for one channel.
diff --git a/apps/cli/go.mod b/apps/cli/go.mod
index 441ed1e..a3df87f 100644
--- a/apps/cli/go.mod
+++ b/apps/cli/go.mod
@@ -1,13 +1,13 @@
-module drmdecryption/apps/cli
+module streamd/apps/cli
go 1.25.0
require (
- 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
+ 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
)
require (
@@ -26,9 +26,9 @@ require (
)
replace (
- drmdecryption => ../pkg
- drmdecryption/apps/agent => ../agent
- drmdecryption/apps/capture => ../capture
- drmdecryption/apps/proxy => ../proxy
- drmdecryption/apps/streamd => ../streamd
+ streamd => ../pkg
+ streamd/apps/agent => ../agent
+ streamd/apps/capture => ../capture
+ streamd/apps/proxy => ../proxy
+ streamd/apps/streamd => ../streamd
)
diff --git a/apps/cli/main.go b/apps/cli/main.go
index 3db10b7..802c7fb 100644
--- a/apps/cli/main.go
+++ b/apps/cli/main.go
@@ -1,4 +1,4 @@
-// Command drm is the single entry point for the toolchain: phone capture,
+// Command streamd 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// and are discovered,
// built, and executed by the host — they are not linked into this binary.
@@ -13,14 +13,14 @@ import (
"os"
"strings"
- "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"
+ "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"
)
func main() {
@@ -39,12 +39,12 @@ func main() {
os.Exit(1)
}
} else if err := modhost.ApplyEnvModulesDir(); err != nil {
- fmt.Fprintln(os.Stderr, "[!] DRM_MODULES_DIR:", err)
+ fmt.Fprintln(os.Stderr, "[!] STREAMD_MODULES_DIR / DRM_MODULES_DIR:", err)
os.Exit(1)
}
// Materialise apps/, bin/, modules/, outputs/, … next to this exe when
- // missing so a lone downloaded drm.exe becomes a GitHub-like install tree.
+ // missing so a lone downloaded streamd.exe becomes a usable install tree.
if cmd != "help" && cmd != "-h" && cmd != "--help" {
if err := bootstrap.EnsureAndLogFor(cmd); err != nil {
fmt.Fprintln(os.Stderr, "[!] bootstrap:", err)
@@ -102,18 +102,19 @@ func peelGlobalFlags(args []string) (modulesDir string, rest []string) {
}
func usage() {
- fmt.Fprint(os.Stderr, `drm — DRM capture / restream toolchain
+ fmt.Fprint(os.Stderr, `streamd — capture / restream toolchain
Usage:
- 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
+ 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
Global flags:
- --modules-dir DIR provider folder (default: /modules, or $DRM_MODULES_DIR)
+ --modules-dir DIR provider folder (default: /modules, or $STREAMD_MODULES_DIR)
Providers live under modules// (Go source + module-publish.yaml).
Local module.yaml holds secrets and is never published; release zips ship
diff --git a/apps/cli/modulescmd/modulescmd.go b/apps/cli/modulescmd/modulescmd.go
index 4f7ee55..5cf2a23 100644
--- a/apps/cli/modulescmd/modulescmd.go
+++ b/apps/cli/modulescmd/modulescmd.go
@@ -9,8 +9,8 @@ import (
"sort"
"text/tabwriter"
- "drmdecryption/modhost"
- "drmdecryption/repo"
+ "streamd/modhost"
+ "streamd/repo"
)
// Run prints external modules under modules/.
diff --git a/apps/modules/README.md b/apps/modules/README.md
index e518fd5..87532fc 100644
--- a/apps/modules/README.md
+++ b/apps/modules/README.md
@@ -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: drmdecryption/modules
- go.mod replace drmdecryption => ../pkg
+apps/modules/ Go module: streamd/modules
+ go.mod replace streamd => ../pkg
all/all.go blank-imports every module — the link point
provider/ shared base: values loading, channel aliases, durations
/*.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/drm catalog --app tg4 --channel ioi --tg4.policy-key BCpkAD...
+./bin/streamd 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`: `_ "drmdecryption/modules/myapp"`
+3. Add one line to `all/all.go`: `_ "streamd/modules/myapp"`
4. Create `apps/modules/myapp/module.yaml` with your values
-5. `go -C apps/cli build -o ../../bin/drm .` then `./bin/drm modules`
+5. `go -C apps/cli build -o ../../bin/streamd .` then `./bin/streamd 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/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
+./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
```
diff --git a/apps/modules/all/all.go b/apps/modules/all/all.go
index 33b94a3..9771be3 100644
--- a/apps/modules/all/all.go
+++ b/apps/modules/all/all.go
@@ -4,7 +4,7 @@
package all
import (
- _ "drmdecryption/modules/bbc"
- _ "drmdecryption/modules/rte"
- _ "drmdecryption/modules/tg4"
+ _ "streamd/modules/bbc"
+ _ "streamd/modules/rte"
+ _ "streamd/modules/tg4"
)
diff --git a/apps/modules/all/all_test.go b/apps/modules/all/all_test.go
index 9639faa..f7d2031 100644
--- a/apps/modules/all/all_test.go
+++ b/apps/modules/all/all_test.go
@@ -4,7 +4,7 @@ import (
"flag"
"testing"
- appreg "drmdecryption/app"
+ appreg "streamd/app"
)
// Every module must be constructible with no module.yaml present — a fresh clone
diff --git a/apps/modules/bbc/bbc.go b/apps/modules/bbc/bbc.go
index b20424c..50941de 100644
--- a/apps/modules/bbc/bbc.go
+++ b/apps/modules/bbc/bbc.go
@@ -9,12 +9,12 @@ import (
"os"
"time"
- "drmdecryption/adb"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
)
func init() {
diff --git a/apps/modules/bbc/bbc_test.go b/apps/modules/bbc/bbc_test.go
index 1ea2bca..fff5490 100644
--- a/apps/modules/bbc/bbc_test.go
+++ b/apps/modules/bbc/bbc_test.go
@@ -3,11 +3,11 @@ package bbc
import (
"testing"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modcfg"
+ "streamd/modules/provider"
+ "streamd/mpd"
)
var (
diff --git a/apps/modules/bbc/config.go b/apps/modules/bbc/config.go
index 969ad7d..321ad85 100644
--- a/apps/modules/bbc/config.go
+++ b/apps/modules/bbc/config.go
@@ -4,8 +4,8 @@ import (
"regexp"
"time"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
+ "streamd/modcfg"
+ "streamd/modules/provider"
)
// Name is the module id (--app bbc).
diff --git a/apps/modules/bbc/steps.go b/apps/modules/bbc/steps.go
index b0bdb15..df0e1ee 100644
--- a/apps/modules/bbc/steps.go
+++ b/apps/modules/bbc/steps.go
@@ -6,8 +6,8 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ "streamd/uiflow"
)
// openExplorePage taps the Explore bottom-nav tab and waits for the channel rail.
diff --git a/apps/modules/c4/c4.go b/apps/modules/c4/c4.go
index 4757ef6..f6cea1b 100644
--- a/apps/modules/c4/c4.go
+++ b/apps/modules/c4/c4.go
@@ -9,12 +9,12 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
)
func init() {
diff --git a/apps/modules/c4/config.go b/apps/modules/c4/config.go
index fd8d192..8fc767b 100644
--- a/apps/modules/c4/config.go
+++ b/apps/modules/c4/config.go
@@ -3,8 +3,8 @@ package c4
import (
"time"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
+ "streamd/modcfg"
+ "streamd/modules/provider"
)
// Name is the module id (--app c4).
diff --git a/apps/modules/c4/steps.go b/apps/modules/c4/steps.go
index fd60461..698016c 100644
--- a/apps/modules/c4/steps.go
+++ b/apps/modules/c4/steps.go
@@ -6,8 +6,8 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ "streamd/uiflow"
)
func (a *App) openLiveTab(c *adb.Client) error {
diff --git a/apps/modules/go.mod b/apps/modules/go.mod
index 6635e2a..1036caa 100644
--- a/apps/modules/go.mod
+++ b/apps/modules/go.mod
@@ -1,9 +1,9 @@
-module drmdecryption/modules
+module streamd/modules
go 1.25.0
-require drmdecryption v0.0.0
+require streamd v0.0.0
require gopkg.in/yaml.v3 v3.0.1 // indirect
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/modules/itv/config.go b/apps/modules/itv/config.go
index dde2df8..e2f7d96 100644
--- a/apps/modules/itv/config.go
+++ b/apps/modules/itv/config.go
@@ -3,8 +3,8 @@ package itv
import (
"time"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
+ "streamd/modcfg"
+ "streamd/modules/provider"
)
// Name is the module id (--app itv).
diff --git a/apps/modules/itv/itv.go b/apps/modules/itv/itv.go
index 5a34212..bc89ffd 100644
--- a/apps/modules/itv/itv.go
+++ b/apps/modules/itv/itv.go
@@ -10,12 +10,12 @@ import (
"os"
"time"
- "drmdecryption/adb"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
)
func init() {
diff --git a/apps/modules/itv/steps.go b/apps/modules/itv/steps.go
index 10cde09..4ac6ac6 100644
--- a/apps/modules/itv/steps.go
+++ b/apps/modules/itv/steps.go
@@ -6,8 +6,8 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ "streamd/uiflow"
)
// openLiveTab taps bottom-nav Live. Accessibility desc is obfuscated as "Lyve";
diff --git a/apps/modules/my5/config.go b/apps/modules/my5/config.go
index 9b7e6e8..8720d4f 100644
--- a/apps/modules/my5/config.go
+++ b/apps/modules/my5/config.go
@@ -3,8 +3,8 @@ package my5
import (
"time"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
+ "streamd/modcfg"
+ "streamd/modules/provider"
)
// Name is the module id (--app my5).
diff --git a/apps/modules/my5/my5.go b/apps/modules/my5/my5.go
index 94c46de..ebd103b 100644
--- a/apps/modules/my5/my5.go
+++ b/apps/modules/my5/my5.go
@@ -9,12 +9,12 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
)
func init() {
diff --git a/apps/modules/my5/steps.go b/apps/modules/my5/steps.go
index 9c6c996..f9fd4f7 100644
--- a/apps/modules/my5/steps.go
+++ b/apps/modules/my5/steps.go
@@ -6,8 +6,8 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ "streamd/uiflow"
)
func (a *App) appFocused(c *adb.Client) bool {
diff --git a/apps/modules/provider/provider.go b/apps/modules/provider/provider.go
index b6e96e2..1b0f919 100644
--- a/apps/modules/provider/provider.go
+++ b/apps/modules/provider/provider.go
@@ -10,10 +10,10 @@ import (
"sort"
"strings"
- "drmdecryption/capture"
- "drmdecryption/modcfg"
- "drmdecryption/phonecap"
- "drmdecryption/repo"
+ "streamd/capture"
+ "streamd/modcfg"
+ "streamd/phonecap"
+ "streamd/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 drm.exe, then repo bin/).
+// proxy.FindLocalBin — next to streamd, then repo bin/).
func (b *Base) ProxyBin() string {
if b.common.ProxyBin != "" {
return modcfg.Resolve(b.common.ProxyBin)
diff --git a/apps/modules/rte/config.go b/apps/modules/rte/config.go
index 6eb03ce..f01d3db 100644
--- a/apps/modules/rte/config.go
+++ b/apps/modules/rte/config.go
@@ -3,9 +3,9 @@ package rte
import (
"time"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
+ "streamd/modcfg"
+ "streamd/modules/provider"
+ "streamd/mpd"
)
// Name is the module id (--app rte).
diff --git a/apps/modules/rte/live_test.go b/apps/modules/rte/live_test.go
index b89e50a..329a1b1 100644
--- a/apps/modules/rte/live_test.go
+++ b/apps/modules/rte/live_test.go
@@ -12,7 +12,7 @@ import (
"strings"
"testing"
- "drmdecryption/mpd"
+ "streamd/mpd"
)
// The rewriter must publish a usable manifest from the KID alone — this is the
diff --git a/apps/modules/rte/mpd.go b/apps/modules/rte/mpd.go
index 2d5a31b..6c91a05 100644
--- a/apps/modules/rte/mpd.go
+++ b/apps/modules/rte/mpd.go
@@ -6,7 +6,7 @@ import (
"strings"
"sync"
- "drmdecryption/mpd"
+ "streamd/mpd"
)
func init() {
diff --git a/apps/modules/rte/rte.go b/apps/modules/rte/rte.go
index 2f279ff..ec8ec12 100644
--- a/apps/modules/rte/rte.go
+++ b/apps/modules/rte/rte.go
@@ -9,12 +9,12 @@ import (
"fmt"
"time"
- "drmdecryption/adb"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
)
func init() {
diff --git a/apps/modules/rte/rte_test.go b/apps/modules/rte/rte_test.go
index eb08cc1..faf3cfd 100644
--- a/apps/modules/rte/rte_test.go
+++ b/apps/modules/rte/rte_test.go
@@ -4,8 +4,8 @@ import (
"strings"
"testing"
- appreg "drmdecryption/app"
- "drmdecryption/mpd"
+ appreg "streamd/app"
+ "streamd/mpd"
)
// Compile-time proof the plugin satisfies every interface the host expects.
diff --git a/apps/modules/rte/steps.go b/apps/modules/rte/steps.go
index 32e1360..584e2d1 100644
--- a/apps/modules/rte/steps.go
+++ b/apps/modules/rte/steps.go
@@ -5,8 +5,8 @@ import (
"regexp"
"time"
- "drmdecryption/adb"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ "streamd/uiflow"
)
// openLiveTab taps the bottom-nav Live tab and waits for channel chips.
diff --git a/apps/modules/tg4/catalog.go b/apps/modules/tg4/catalog.go
index a80501d..5afaada 100644
--- a/apps/modules/tg4/catalog.go
+++ b/apps/modules/tg4/catalog.go
@@ -6,9 +6,9 @@ import (
"net/http"
"strings"
- appreg "drmdecryption/app"
- "drmdecryption/brightcove"
- "drmdecryption/session"
+ appreg "streamd/app"
+ "streamd/brightcove"
+ "streamd/session"
)
// playbackConfig is the app's remote config blob. It is decoded generically: the
diff --git a/apps/modules/tg4/config.go b/apps/modules/tg4/config.go
index 2162ed7..3fef619 100644
--- a/apps/modules/tg4/config.go
+++ b/apps/modules/tg4/config.go
@@ -3,9 +3,9 @@ package tg4
import (
"time"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
- "drmdecryption/uiflow"
+ "streamd/modcfg"
+ "streamd/modules/provider"
+ "streamd/uiflow"
)
// Name is the module id (--app tg4).
diff --git a/apps/modules/tg4/keys.go b/apps/modules/tg4/keys.go
index a14db24..5ec6cd1 100644
--- a/apps/modules/tg4/keys.go
+++ b/apps/modules/tg4/keys.go
@@ -5,10 +5,10 @@ import (
"path/filepath"
"strings"
- "drmdecryption/brightcove"
- "drmdecryption/repo"
- "drmdecryption/session"
- "drmdecryption/wvkey"
+ "streamd/brightcove"
+ "streamd/repo"
+ "streamd/session"
+ "streamd/wvkey"
)
// EnrichWithKeys fetches the HLS master, extracts the Widevine PSSH and resolves
diff --git a/apps/modules/tg4/steps.go b/apps/modules/tg4/steps.go
index 3b5040b..b915877 100644
--- a/apps/modules/tg4/steps.go
+++ b/apps/modules/tg4/steps.go
@@ -5,8 +5,8 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ "streamd/uiflow"
)
// openLivePage navigates to the Live page: if a menu entry is visible tap it,
diff --git a/apps/modules/tg4/tg4.go b/apps/modules/tg4/tg4.go
index 8e20653..d1f1a62 100644
--- a/apps/modules/tg4/tg4.go
+++ b/apps/modules/tg4/tg4.go
@@ -10,12 +10,12 @@ import (
"fmt"
"time"
- "drmdecryption/adb"
- appreg "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/modules/provider"
- "drmdecryption/mpd"
- "drmdecryption/uiflow"
+ "streamd/adb"
+ appreg "streamd/app"
+ "streamd/capture"
+ "streamd/modules/provider"
+ "streamd/mpd"
+ "streamd/uiflow"
)
func init() {
diff --git a/apps/modules/tg4/tg4_test.go b/apps/modules/tg4/tg4_test.go
index cc16fc6..1e16891 100644
--- a/apps/modules/tg4/tg4_test.go
+++ b/apps/modules/tg4/tg4_test.go
@@ -3,9 +3,9 @@ package tg4
import (
"testing"
- appreg "drmdecryption/app"
- "drmdecryption/modcfg"
- "drmdecryption/modules/provider"
+ appreg "streamd/app"
+ "streamd/modcfg"
+ "streamd/modules/provider"
)
// Compile-time proof the plugin satisfies every interface the host expects.
diff --git a/apps/pkg/README.md b/apps/pkg/README.md
index 05a5413..6d17d2b 100644
--- a/apps/pkg/README.md
+++ b/apps/pkg/README.md
@@ -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 `drmdecryption` via:
+and `apps/modules` as module `streamd` via:
```go
-replace drmdecryption => ../pkg
+replace streamd => ../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/drm`, built from `apps/cli`.
+No binary of its own — everything ships in `bin/streamd`, built from `apps/cli`.
diff --git a/apps/pkg/app/app.go b/apps/pkg/app/app.go
index 3a180b7..a78b688 100644
--- a/apps/pkg/app/app.go
+++ b/apps/pkg/app/app.go
@@ -6,10 +6,10 @@ import (
"sort"
"sync"
- "drmdecryption/adb"
- "drmdecryption/capture"
- "drmdecryption/mpd"
- "drmdecryption/session"
+ "streamd/adb"
+ "streamd/capture"
+ "streamd/mpd"
+ "streamd/session"
)
// Channel is a named live target inside an app (e.g. rteone).
diff --git a/apps/pkg/bootstrap/bootstrap.go b/apps/pkg/bootstrap/bootstrap.go
index 1ec264c..52ff36b 100644
--- a/apps/pkg/bootstrap/bootstrap.go
+++ b/apps/pkg/bootstrap/bootstrap.go
@@ -1,4 +1,4 @@
-// Package bootstrap materialises a GitHub-like install tree next to drm.exe
+// Package bootstrap materialises a GitHub-like install tree next to streamd
// 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 drm.exe lives in …/bin/, the parent is the root; otherwise the exe directory.
+// If streamd lives in …/bin/, the parent is the root; otherwise the exe directory.
func InstallRoot() (string, error) {
exe, err := os.Executable()
if err != nil {
@@ -91,27 +91,30 @@ func Ensure(root string) (created []string, err error) {
return created, err
}
- // If drm is not already under bin/, copy/link a drm.exe there for 1:1 layout.
- if err := ensureBinDrm(root); err != nil {
+ // If streamd is not already under bin/, copy it there for 1:1 layout.
+ if err := ensureBinHost(root); err != nil {
return created, err
}
return created, nil
}
-func ensureBinDrm(root string) error {
+func ensureBinHost(root string) error {
exe, err := os.Executable()
if err != nil {
return nil
}
exe, _ = filepath.EvalSymlinks(exe)
- dest := filepath.Join(root, "bin", "drm.exe")
- if sameFile(exe, dest) {
+ return copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe"))
+}
+
+func copyExeIfMissing(src, dest string) error {
+ if sameFile(src, dest) {
return nil
}
if st, err := os.Stat(dest); err == nil && !st.IsDir() {
return nil
}
- data, err := os.ReadFile(exe)
+ data, err := os.ReadFile(src)
if err != nil {
return err
}
@@ -154,7 +157,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 drm or use a release build that embeds it\n")
+ fmt.Fprintf(os.Stderr, "[!] missing bin/proxy-android-arm64 — place it next to streamd 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"
diff --git a/apps/pkg/bootstrap/embedded/README.md b/apps/pkg/bootstrap/embedded/README.md
index 6773ac9..e4e6cc8 100644
--- a/apps/pkg/bootstrap/embedded/README.md
+++ b/apps/pkg/bootstrap/embedded/README.md
@@ -1,14 +1,14 @@
-# Null DRM
+# Streamd
-Host binary **`drm`** + providers under **`modules/`**.
+Host binary **`streamd`** + providers under **`modules/`**.
## Quick start
-1. Download `drm` (`v*` release) and module zips (`modules-v*` release).
+1. Download `streamd` (`v*` release) and module zips (`modules-v*` release).
2. Unzip providers into `modules//` and edit `module.yaml` (secrets only).
-3. `drm proxy install-ca --reinject`
-4. `drm capture --app bbc --channel bbcone --wait 120`
-5. `drm proxy reset` when finished.
+3. `streamd proxy install-ca --reinject`
+4. `streamd capture --app bbc --channel bbcone --wait 120`
+5. `streamd 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 `$DRM_MODULES_DIR` selects another modules folder.
+`--modules-dir DIR` or `$STREAMD_MODULES_DIR` selects another modules folder.
Full docs: https://git.nulldrm.com/nulldrm/Null-DRM-Official
diff --git a/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod b/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod
index c23f9f3..1b7a669 100644
--- a/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod
+++ b/apps/pkg/bootstrap/embedded/apps/pkg/pkg.gomod
@@ -1,4 +1,4 @@
-module drmdecryption
+module streamd
go 1.25.0
diff --git a/apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt b/apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt
new file mode 100644
index 0000000..9c8759c
--- /dev/null
+++ b/apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt
@@ -0,0 +1,6 @@
+# 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
diff --git a/apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py b/apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py
new file mode 100644
index 0000000..87c9e43
--- /dev/null
+++ b/apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py
@@ -0,0 +1,367 @@
+#!/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())
diff --git a/apps/pkg/bootstrap/embedded/modules/README.md b/apps/pkg/bootstrap/embedded/modules/README.md
index edc20ac..8493f8b 100644
--- a/apps/pkg/bootstrap/embedded/modules/README.md
+++ b/apps/pkg/bootstrap/embedded/modules/README.md
@@ -1,6 +1,6 @@
# External modules
-Each subdirectory is a provider the `drm` host discovers, builds, and runs.
+Each subdirectory is a provider the `streamd` host discovers, builds, and runs.
```
modules/
diff --git a/apps/pkg/bootstrap/embedded/root-go-mod.txt b/apps/pkg/bootstrap/embedded/root-go-mod.txt
index c23f9f3..1b7a669 100644
--- a/apps/pkg/bootstrap/embedded/root-go-mod.txt
+++ b/apps/pkg/bootstrap/embedded/root-go-mod.txt
@@ -1,4 +1,4 @@
-module drmdecryption
+module streamd
go 1.25.0
diff --git a/apps/pkg/capture/capture.go b/apps/pkg/capture/capture.go
index f4e30e4..ef73a54 100644
--- a/apps/pkg/capture/capture.go
+++ b/apps/pkg/capture/capture.go
@@ -9,7 +9,7 @@ import (
"strings"
"time"
- "drmdecryption/adb"
+ "streamd/adb"
)
// Hints tell the waiter which fields / log tags mean a capture is complete.
diff --git a/apps/pkg/go.mod b/apps/pkg/go.mod
index c23f9f3..1b7a669 100644
--- a/apps/pkg/go.mod
+++ b/apps/pkg/go.mod
@@ -1,4 +1,4 @@
-module drmdecryption
+module streamd
go 1.25.0
diff --git a/apps/pkg/modcfg/modcfg.go b/apps/pkg/modcfg/modcfg.go
index 30b3fa5..5868a55 100644
--- a/apps/pkg/modcfg/modcfg.go
+++ b/apps/pkg/modcfg/modcfg.go
@@ -15,13 +15,14 @@ import (
"path/filepath"
"strings"
- "drmdecryption/modhost"
- "drmdecryption/repo"
+ "streamd/modhost"
+ "streamd/repo"
"gopkg.in/yaml.v3"
)
// Dir returns the directory holding a module's values.
-// Prefers the active modules dir (see modhost / --modules-dir); falls back to
+// Prefers the active modules dir (see modhost / --modules-dir); then the
+// directory beside a panel/release binary (/.bin/); then
// apps/modules// for older checkouts.
func Dir(name string) string {
preferred := filepath.Join(modhost.ModulesDir(""), name)
@@ -31,6 +32,9 @@ 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)
@@ -38,6 +42,43 @@ func Dir(name string) string {
return filepath.Join(root, "apps", "modules", name)
}
+// dirBesideExecutable finds module.yaml next to a panel/release binary layout:
+// /.bin/[.exe]
+// /.bin/-/[.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")
diff --git a/apps/pkg/modhost/discover.go b/apps/pkg/modhost/discover.go
index 93a90de..efecb85 100644
--- a/apps/pkg/modhost/discover.go
+++ b/apps/pkg/modhost/discover.go
@@ -13,7 +13,7 @@ type Module struct {
Dir string // absolute path to modules/
}
-// ModulesDir returns the modules directory (honours --modules-dir / DRM_MODULES_DIR).
+// ModulesDir returns the modules directory (honours --modules-dir / STREAMD_MODULES_DIR / DRM_MODULES_DIR).
func ModulesDir(root string) string {
return EffectiveModulesDir(root)
}
diff --git a/apps/pkg/modhost/exec.go b/apps/pkg/modhost/exec.go
index 57d1beb..173e9c5 100644
--- a/apps/pkg/modhost/exec.go
+++ b/apps/pkg/modhost/exec.go
@@ -9,9 +9,39 @@ 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
@@ -24,6 +54,7 @@ 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
@@ -74,5 +105,9 @@ 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
}
diff --git a/apps/pkg/modhost/exec_test.go b/apps/pkg/modhost/exec_test.go
new file mode 100644
index 0000000..ae7c842
--- /dev/null
+++ b/apps/pkg/modhost/exec_test.go
@@ -0,0 +1,31 @@
+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)
+ }
+}
diff --git a/apps/pkg/modhost/protocol.go b/apps/pkg/modhost/protocol.go
index 4fbade8..3ac5acc 100644
--- a/apps/pkg/modhost/protocol.go
+++ b/apps/pkg/modhost/protocol.go
@@ -1,8 +1,8 @@
// Package modhost discovers, builds, and runs external provider modules that
-// live under modules// (Go source + module.yaml), outside drm.exe.
+// live under modules// (Go source + module.yaml), outside streamd.
package modhost
-import "drmdecryption/capture"
+import "streamd/capture"
// ProtocolVersion is bumped when describe/launch/autoplay CLI contract changes.
const ProtocolVersion = 1
diff --git a/apps/pkg/modhost/remote_app.go b/apps/pkg/modhost/remote_app.go
index 6932567..ac113d5 100644
--- a/apps/pkg/modhost/remote_app.go
+++ b/apps/pkg/modhost/remote_app.go
@@ -6,11 +6,11 @@ import (
"path/filepath"
"strings"
- "drmdecryption/adb"
- "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/mpd"
- "drmdecryption/session"
+ "streamd/adb"
+ "streamd/app"
+ "streamd/capture"
+ "streamd/mpd"
+ "streamd/session"
)
// RemoteApp implements app.App by calling an external module binary.
diff --git a/apps/pkg/modhost/root.go b/apps/pkg/modhost/root.go
index 9133e24..9da5fd3 100644
--- a/apps/pkg/modhost/root.go
+++ b/apps/pkg/modhost/root.go
@@ -3,9 +3,10 @@ package modhost
import (
"os"
"path/filepath"
+ "strings"
"sync"
- "drmdecryption/repo"
+ "streamd/repo"
)
var (
@@ -13,7 +14,7 @@ var (
modulesDirOV string // absolute path override for the modules directory
)
-// SetModulesDir overrides where providers are discovered (drm --modules-dir).
+// SetModulesDir overrides where providers are discovered (streamd --modules-dir).
// Empty clears the override. Relative paths are resolved against the process cwd.
func SetModulesDir(dir string) error {
rootMu.Lock()
@@ -37,24 +38,45 @@ 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 / DRM_MODULES_DIR; else /modules.
+// Prefer --modules-dir, then STREAMD_MODULES_DIR / DRM_MODULES_DIR, else /modules.
+// Module binaries read the env here directly so they honour the panel store even
+// when they never call ApplyEnvModulesDir.
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 DRM_MODULES_DIR when no flag was set.
+// ApplyEnvModulesDir sets the override from STREAMD_MODULES_DIR (preferred) or
+// DRM_MODULES_DIR when no flag was set.
func ApplyEnvModulesDir() error {
if ModulesDirOverride() != "" {
return nil
}
- v := os.Getenv("DRM_MODULES_DIR")
+ v := envModulesDir()
if v == "" {
return nil
}
diff --git a/apps/pkg/modhost/root_test.go b/apps/pkg/modhost/root_test.go
new file mode 100644
index 0000000..d653914
--- /dev/null
+++ b/apps/pkg/modhost/root_test.go
@@ -0,0 +1,39 @@
+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)
+ }
+}
diff --git a/apps/pkg/modhost/yaml_enrich.go b/apps/pkg/modhost/yaml_enrich.go
new file mode 100644
index 0000000..abb108b
--- /dev/null
+++ b/apps/pkg/modhost/yaml_enrich.go
@@ -0,0 +1,77 @@
+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")
+ }
+}
diff --git a/apps/pkg/phonecap/phonecap.go b/apps/pkg/phonecap/phonecap.go
index 776335c..b90bc6d 100644
--- a/apps/pkg/phonecap/phonecap.go
+++ b/apps/pkg/phonecap/phonecap.go
@@ -12,13 +12,13 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/app"
- "drmdecryption/capture"
- "drmdecryption/proxy"
- "drmdecryption/repo"
- "drmdecryption/session"
- "drmdecryption/wvkey"
+ "streamd/adb"
+ "streamd/app"
+ "streamd/capture"
+ "streamd/proxy"
+ "streamd/repo"
+ "streamd/session"
+ "streamd/wvkey"
)
// DefaultCAHash is the subject hash of the bundled MITM CA, used when an app
@@ -206,17 +206,21 @@ 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/" + a.Package()
+ remoteDir := "/data/local/tmp/capture/" + pkgName
var mitmHosts []string
if mh, ok := a.(app.MitmHostList); ok {
mitmHosts = mh.MitmHosts()
}
- if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false, mitmHosts...); err != nil {
+ if err := proxy.StartTransparent(c, proxyBin, pkgName, "8080", remoteDir, false, mitmHosts...); err != nil {
return res, fmt.Errorf("transparent MITM start: %w", err)
}
defer proxy.StopTransparent(c)
@@ -238,17 +242,6 @@ 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 == "" {
@@ -256,107 +249,161 @@ 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"}
}
- fmt.Printf("[*] Waiting for %s…\n", strings.Join(need, " + "))
- fmt.Println(" watch:", localLog)
- capData, err := capture.Wait(c, hints, localLog, localCap, opt.Wait)
- if err != nil {
- 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()))
- }
- // Brightcove/HLS: proxy often captures license + master URL but not PSSH.
- // C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
- // 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"))
- // Console: always surface the MPD we will use (BBC clear streams only need this).
- fmt.Println()
- fmt.Println("========== MPD ==========")
- if mpdURL != "" {
- fmt.Println(mpdURL)
- } else {
- fmt.Println("(none)")
- }
- fmt.Println("=========================")
- fmt.Println()
- fmt.Println("[+] Capture:")
- for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
- v := capData.Get(k)
- if k == "license_url" {
- v = first(v, licenseURL)
+ 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)
}
- if v == "" {
+
+ // 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
}
- label := k
- switch k {
- case "license_url":
- label = "license"
- case "license_body":
- label = "license_body"
- v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
+ 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.Println(" ", label+":", trim(v, 120))
- }
- key := ""
- if keyMode == "none" || keyMode == "clear" {
- fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
- } else {
- var kerr error
- key, kerr = fetchKey(opt, root, capData, licenseURL)
+ fmt.Printf("[*] Waiting for %s (attempt %d/%d, timeout %s)…\n",
+ strings.Join(need, " + "), attempt, attempts, waitPer.Round(time.Second))
+ fmt.Println(" watch:", localLog)
+ cap, err := capture.Wait(c, hints, localLog, localCap, waitPer)
+ if err != nil {
+ lastErr = err
+ fmt.Fprintf(os.Stderr, "[!] capture wait failed: %v\n", err)
+ c.ForceStop(a.Package())
+ continue
+ }
+ 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)
+ }
+
+ mpdURL = strings.TrimSpace(capData.Get("mpd"))
+ fmt.Println()
+ fmt.Println("========== MPD ==========")
+ if mpdURL != "" {
+ fmt.Println(mpdURL)
+ } else {
+ fmt.Println("(none)")
+ }
+ fmt.Println("=========================")
+ fmt.Println()
+ fmt.Println("[+] Capture:")
+ for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
+ v := capData.Get(k)
+ if k == "license_url" {
+ v = first(v, licenseURL)
+ }
+ if v == "" {
+ continue
+ }
+ label := k
+ switch k {
+ case "license_url":
+ label = "license"
+ case "license_body":
+ label = "license_body"
+ v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
+ }
+ fmt.Println(" ", label+":", trim(v, 120))
+ }
+
+ if !needsKeys {
+ fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
+ lastErr = nil
+ break
+ }
+
+ k, kerr := fetchKey(opt, root, capData, licenseURL)
if kerr != nil {
- // Allow MPD-only sessions when no .wvd was passed (grab-all / first pass),
- // unless the app requires keys (e.g. c4).
+ 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.
softOK := strings.Contains(kerr.Error(), "requires --wvd")
if softOK {
if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
- return res, kerr
+ c.ForceStop(a.Package())
+ continue
}
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
- } else {
- return res, kerr
+ key = ""
+ lastErr = nil
+ break
}
- } else {
- fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
+ 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
+ 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{
@@ -384,6 +431,62 @@ 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)
@@ -414,16 +517,18 @@ 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)")
}
- 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")
- }
+ // Ensure apps/wvkey + .venv/pywidevine exist on Windows/Linux/macOS.
+ rt, err := wvkey.EnsureRuntime(root)
+ if err != nil {
+ return "", err
+ }
+ py := rt.Python
+ if p := strings.TrimSpace(opt.Python); p != "" && fileExistsPath(p) {
+ py = p
}
wopt := wvkey.Options{
Python: py,
- Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"),
+ Script: rt.Script,
WVD: opt.WVD,
PSSH: cap.Get("pssh"),
Auth: cap.Get("auth"),
@@ -465,6 +570,11 @@ 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) != "" {
diff --git a/apps/pkg/proxy/embed.go b/apps/pkg/proxy/embed.go
index 1c985c4..79d0e20 100644
--- a/apps/pkg/proxy/embed.go
+++ b/apps/pkg/proxy/embed.go
@@ -6,15 +6,15 @@ import (
"os"
"path/filepath"
- "drmdecryption/adb"
- "drmdecryption/repo"
+ "streamd/adb"
+ "streamd/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 drm.exe
+// Prefers the source-tree copy; falls back to the copy embedded in streamd
// so a portable release zip does not need apps/proxy/device/.
func ensureTProxyScript(c *adb.Client) error {
candidates := []string{
diff --git a/apps/pkg/proxy/proxy.go b/apps/pkg/proxy/proxy.go
index d6be1e2..02286d6 100644
--- a/apps/pkg/proxy/proxy.go
+++ b/apps/pkg/proxy/proxy.go
@@ -17,8 +17,8 @@ import (
"strings"
"time"
- "drmdecryption/adb"
- "drmdecryption/repo"
+ "streamd/adb"
+ "streamd/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 drm.exe (release zip layout), then under the repo.
+// Search order: next to this streamd binary (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("Null DRM Capture CA %x", serial.Bytes()[:8])
+ cn := fmt.Sprintf("Streamd Capture CA %x", serial.Bytes()[:8])
tmpl := &x509.Certificate{
SerialNumber: serial,
Subject: pkix.Name{
- Organization: []string{"Null DRM MITM CA"},
+ Organization: []string{"Streamd MITM CA"},
CommonName: cn,
},
NotBefore: time.Now().Add(-time.Hour),
@@ -481,10 +481,14 @@ 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 == "" {
+ if remoteDir == "" || strings.HasSuffix(remoteDir, "/capture/") || strings.HasSuffix(remoteDir, `\capture\`) {
remoteDir = RemoteCaptureRoot + "/" + pkg
}
stopProxy(c)
diff --git a/apps/pkg/repo/root.go b/apps/pkg/repo/root.go
index a03ac8a..c218f43 100644
--- a/apps/pkg/repo/root.go
+++ b/apps/pkg/repo/root.go
@@ -11,7 +11,7 @@ import (
//
// Search order:
// 1. Walk up from the current working directory
-// 2. Walk up from drm.exe (if the exe lives in bin/, start at the parent)
+// 2. Walk up from streamd (if the exe lives in bin/, start at the parent)
func Root() string {
if root := findRoot(wd()); root != "" {
return root
diff --git a/apps/pkg/uiflow/uiflow.go b/apps/pkg/uiflow/uiflow.go
index de8da07..afde843 100644
--- a/apps/pkg/uiflow/uiflow.go
+++ b/apps/pkg/uiflow/uiflow.go
@@ -10,7 +10,7 @@ import (
"strings"
"time"
- "drmdecryption/adb"
+ "streamd/adb"
)
// Pick selects among several matching nodes.
diff --git a/apps/pkg/wvkey/ensure.go b/apps/pkg/wvkey/ensure.go
new file mode 100644
index 0000000..6c7eac6
--- /dev/null
+++ b/apps/pkg/wvkey/ensure.go
@@ -0,0 +1,172 @@
+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 /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")
+}
diff --git a/apps/pkg/wvkey/wvkey.go b/apps/pkg/wvkey/wvkey.go
index 48ec924..b5d9a30 100644
--- a/apps/pkg/wvkey/wvkey.go
+++ b/apps/pkg/wvkey/wvkey.go
@@ -58,14 +58,21 @@ func FetchWrapAll(opt Options) ([]string, error) {
}
func run(opt Options, mode string, all bool) ([]string, error) {
- py := opt.Python
- if py == "" {
- py = findPython()
- }
+ py := resolvePython(opt.Python)
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")
}
@@ -120,12 +127,30 @@ 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)) {
diff --git a/apps/proxy/README.md b/apps/proxy/README.md
index 38f5e83..1641534 100644
--- a/apps/proxy/README.md
+++ b/apps/proxy/README.md
@@ -5,7 +5,7 @@ license URLs, manifests and auth headers.
```text
apps/proxy/
- proxyctlcmd/ host CLI, hosted by bin/drm as `drm proxy`
+ proxyctlcmd/ host CLI, hosted by bin/streamd as `streamd 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/drm . # host CLI
-./bin/drm proxy build # cross-compile the device binary
+go -C apps/cli build -o ../../bin/streamd . # host CLI
+./bin/streamd 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/drm . # host CLI
```bash
# trust the MITM CA (needs Magisk; mounts into the system store)
-./bin/drm proxy install-ca --reinject
-./bin/drm proxy reinject-ca # mount only, CA already pushed
+./bin/streamd proxy install-ca --reinject
+./bin/streamd proxy reinject-ca # mount only, CA already pushed
# structured capture proxy
-./bin/drm proxy start --install-ca --reinject
-./bin/drm proxy stop
+./bin/streamd proxy start --install-ca --reinject
+./bin/streamd proxy stop
# record everything while you explore an unknown app
-./bin/drm proxy discover --install-ca --reinject
-./bin/drm proxy discover --force-stop # so it inherits the CA mount
+./bin/streamd proxy discover --install-ca --reinject
+./bin/streamd proxy discover --force-stop # so it inherits the CA mount
# pull artifacts without re-running, and release the phone
-./bin/drm proxy pull
-./bin/drm proxy clear-proxy
+./bin/streamd proxy pull
+./bin/streamd 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/drm proxy transparent --package bbc.iplayer.android --reinject
+./bin/streamd 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`). `drm capture` does this automatically.
+`--score-deny`). `streamd capture` does this automatically.
## Artifacts
diff --git a/apps/proxy/go.mod b/apps/proxy/go.mod
index 859bedf..0bea3da 100644
--- a/apps/proxy/go.mod
+++ b/apps/proxy/go.mod
@@ -1,7 +1,7 @@
-module drmdecryption/apps/proxy
+module streamd/apps/proxy
go 1.25.0
-require drmdecryption v0.0.0
+require streamd v0.0.0
-replace drmdecryption => ../pkg
+replace streamd => ../pkg
diff --git a/apps/proxy/proxyctlcmd/proxyctlcmd.go b/apps/proxy/proxyctlcmd/proxyctlcmd.go
index d1864bf..a39ae31 100644
--- a/apps/proxy/proxyctlcmd/proxyctlcmd.go
+++ b/apps/proxy/proxyctlcmd/proxyctlcmd.go
@@ -18,9 +18,9 @@ import (
"syscall"
"time"
- "drmdecryption/adb"
- "drmdecryption/proxy"
- "drmdecryption/repo"
+ "streamd/adb"
+ "streamd/proxy"
+ "streamd/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 drm.exe instead — no Go build required.\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, "Missing: %s\n", deviceDir)
os.Exit(1)
}
diff --git a/apps/streamd/README.md b/apps/streamd/README.md
index 7efabc8..79994a8 100644
--- a/apps/streamd/README.md
+++ b/apps/streamd/README.md
@@ -1,7 +1,7 @@
# streamd
Control plane: REST API, SQLite, dashboard and media supervisor. Hosted by the
-single binary as `drm serve`.
+single binary as `streamd serve`.
```text
apps/streamd/
@@ -17,7 +17,9 @@ apps/streamd/
## Run
```bash
-./bin/drm serve --bind 127.0.0.1:8083 --data .cache/streamd
+./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
```
`--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any
diff --git a/apps/streamd/go.mod b/apps/streamd/go.mod
index 4064060..d3a639e 100644
--- a/apps/streamd/go.mod
+++ b/apps/streamd/go.mod
@@ -1,14 +1,15 @@
-module drmdecryption/apps/streamd
+module streamd/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 drmdecryption => ../pkg
+replace streamd => ../pkg
require (
github.com/dustin/go-humanize v1.0.1 // indirect
@@ -17,6 +18,7 @@ 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
diff --git a/apps/streamd/go.sum b/apps/streamd/go.sum
index 3dff215..077f977 100644
--- a/apps/streamd/go.sum
+++ b/apps/streamd/go.sum
@@ -19,6 +19,9 @@ 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=
diff --git a/apps/streamd/internal/api/api.go b/apps/streamd/internal/api/api.go
index 0ae4089..bf83790 100644
--- a/apps/streamd/internal/api/api.go
+++ b/apps/streamd/internal/api/api.go
@@ -10,10 +10,12 @@ import (
"strings"
"time"
- "drmdecryption/apps/streamd/internal/auth"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/apps/streamd/internal/deps"
- "drmdecryption/apps/streamd/internal/httpx"
+ "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"
)
type Supervisor interface {
@@ -56,7 +58,12 @@ 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
- Log *slog.Logger
+ 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
}
func (h *Handler) Mount(mux *http.ServeMux) {
@@ -65,6 +72,7 @@ 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)
@@ -534,6 +542,7 @@ 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)
@@ -565,6 +574,9 @@ 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
diff --git a/apps/streamd/internal/api/apps.go b/apps/streamd/internal/api/apps.go
index 179290a..53b146d 100644
--- a/apps/streamd/internal/api/apps.go
+++ b/apps/streamd/internal/api/apps.go
@@ -2,11 +2,15 @@ package api
import (
"net/http"
+ "sort"
- "drmdecryption/apps/streamd/internal/auth"
- "drmdecryption/modhost"
- "drmdecryption/mpd"
- "drmdecryption/repo"
+ "gopkg.in/yaml.v3"
+
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/modstore"
+ "streamd/modhost"
+ "streamd/mpd"
+ "streamd/repo"
)
// appInfo describes one modules// provider to the dashboard, so the UI
@@ -16,6 +20,7 @@ type appInfo struct {
Channels []channelInfo `json:"channels"`
Rewriter string `json:"rewriter"`
HasConfig bool `json:"has_config"`
+ Error string `json:"error,omitempty"`
}
type channelInfo struct {
@@ -23,7 +28,9 @@ type channelInfo struct {
Label string `json:"label"`
}
-// apps answers GET /api/apps: which providers exist under modules/.
+// 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).
func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
@@ -33,21 +40,43 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
return
}
out := []appInfo{}
- listed, err := modhost.ListAll(repo.Root())
+ mods, err := modhost.Discover(repo.Root())
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
- for _, L := range listed {
- d := L.Desc
+ 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
+ }
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{
@@ -55,3 +84,53 @@ 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
+}
diff --git a/apps/streamd/internal/api/apps_test.go b/apps/streamd/internal/api/apps_test.go
new file mode 100644
index 0000000..2ade1ad
--- /dev/null
+++ b/apps/streamd/internal/api/apps_test.go
@@ -0,0 +1,45 @@
+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)
+ }
+}
diff --git a/apps/streamd/internal/api/control.go b/apps/streamd/internal/api/control.go
index 7cb3723..f89db47 100644
--- a/apps/streamd/internal/api/control.go
+++ b/apps/streamd/internal/api/control.go
@@ -11,9 +11,9 @@ import (
"strings"
"time"
- "drmdecryption/apps/streamd/internal/auth"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/mpd"
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/db"
+ "streamd/mpd"
)
// MountControl adds the bulk, duplicate, probe, settings and schedule routes.
@@ -162,6 +162,7 @@ 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,
@@ -271,9 +272,19 @@ 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 own proxy, so a geo-restricted origin is
- // probed the same way the downloader would reach it.
- if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
+ // 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 != "" {
if c, err := httpClientWithProxy(proxy); err == nil {
client = c
} else {
diff --git a/apps/streamd/internal/api/egress.go b/apps/streamd/internal/api/egress.go
new file mode 100644
index 0000000..bfda8b9
--- /dev/null
+++ b/apps/streamd/internal/api/egress.go
@@ -0,0 +1,254 @@
+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)
+}
diff --git a/apps/streamd/internal/api/events.go b/apps/streamd/internal/api/events.go
index 8943dbf..1817a19 100644
--- a/apps/streamd/internal/api/events.go
+++ b/apps/streamd/internal/api/events.go
@@ -10,9 +10,9 @@ import (
"strings"
"time"
- "drmdecryption/apps/streamd/internal/auth"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/apps/streamd/internal/logfile"
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/logfile"
)
// logSources maps a caller-supplied source name to the log file suffix the
@@ -363,6 +363,10 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
}
_ = h.Store.FlushHistory()
recent, _ := h.Store.RecentEvents(25)
+ sessions, _ := h.Store.ListRecentSessions(50)
+ if sessions == nil {
+ sessions = []db.StreamSession{}
+ }
out := map[string]any{
"totals": map[string]any{
"streams": len(list),
@@ -374,7 +378,8 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
"viewers": viewers,
"needs_capture": needCapture,
},
- "recent_events": recent,
+ "recent_events": recent,
+ "recent_sessions": sessions,
}
if h.Scheduler != nil {
out["upcoming"] = h.Scheduler.Upcoming(10)
diff --git a/apps/streamd/internal/api/modules.go b/apps/streamd/internal/api/modules.go
index b04a480..e5a9de0 100644
--- a/apps/streamd/internal/api/modules.go
+++ b/apps/streamd/internal/api/modules.go
@@ -1,93 +1,160 @@
package api
import (
- "crypto/sha256"
- "encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
- "os"
"path/filepath"
- "regexp"
"strings"
+ "time"
- "drmdecryption/apps/streamd/internal/auth"
- "drmdecryption/modhost"
- "drmdecryption/repo"
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/modstore"
)
-// moduleInfo is one modules// entry for agent sync.
-type moduleInfo struct {
- Name string `json:"name"`
- HasYAML bool `json:"has_yaml"`
- YAMLSHA256 string `json:"yaml_sha256,omitempty"`
+// ModulesNotifier pushes module change events to agents and the dashboard.
+type ModulesNotifier interface {
+ NotifyModulesChanged(name, reason string)
}
-var moduleNameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`)
+func (h *Handler) modStore() *modstore.Store {
+ if h.Modules != nil {
+ return h.Modules
+ }
+ root := filepath.Join(h.DataDir, "modules")
+ return modstore.New(root)
+}
+
+func (h *Handler) notifyModules(name, reason string) {
+ if h.ModulesNotify != nil {
+ h.ModulesNotify.NotifyModulesChanged(name, reason)
+ return
+ }
+ // Hub also implements Notifier; prefer the dedicated method when available.
+ if n, ok := h.Notifier.(ModulesNotifier); ok {
+ n.NotifyModulesChanged(name, reason)
+ }
+}
func (h *Handler) modules(w http.ResponseWriter, r *http.Request) {
path := strings.TrimPrefix(r.URL.Path, "/api/modules")
path = strings.Trim(path, "/")
- // Module metadata describes the provider plugins installed on this host,
- // so even reading it needs a principal.
- if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
- return
- }
-
switch {
case path == "" && r.Method == http.MethodGet:
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
h.listModules(w, r)
+ case path == "upload" && r.Method == http.MethodPost:
+ h.uploadModule(w, r)
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodGet:
+ if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
+ return
+ }
h.getModule(w, r, path)
case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodPut:
h.putModule(w, r, path)
+ case path != "" && !strings.Contains(path, "/") && r.Method == http.MethodDelete:
+ h.deleteModule(w, r, path)
+ case strings.HasSuffix(path, "/yaml") && r.Method == http.MethodGet:
+ name := strings.TrimSuffix(path, "/yaml")
+ name = strings.Trim(name, "/")
+ h.getModuleYAML(w, r, name)
+ case strings.HasSuffix(path, "/package") && r.Method == http.MethodGet:
+ name := strings.TrimSuffix(path, "/package")
+ name = strings.Trim(name, "/")
+ h.getModulePackage(w, r, name)
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
func (h *Handler) listModules(w http.ResponseWriter, r *http.Request) {
- root := repo.Root()
- dir := modhost.ModulesDir(root)
- ents, err := os.ReadDir(dir)
+ list, err := h.modStore().List()
if err != nil {
- if os.IsNotExist(err) {
- writeJSON(w, http.StatusOK, map[string]any{"modules": []moduleInfo{}})
- return
- }
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
- out := []moduleInfo{}
- for _, e := range ents {
- if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
- continue
- }
- info := moduleYAMLInfo(filepath.Join(dir, e.Name()), e.Name())
- out = append(out, info)
- }
- writeJSON(w, http.StatusOK, map[string]any{"modules": out})
+ writeJSON(w, http.StatusOK, map[string]any{"modules": list})
}
func (h *Handler) getModule(w http.ResponseWriter, r *http.Request, name string) {
- if !moduleNameRe.MatchString(name) {
+ if !modstore.NameRe.MatchString(name) {
writeErr(w, http.StatusBadRequest, "invalid module name")
return
}
- info := moduleYAMLInfo(filepath.Join(modhost.ModulesDir(repo.Root()), name), name)
- writeJSON(w, http.StatusOK, info)
+ info := h.modStore().Info(name)
+ if !info.HasYAML && !info.HasPackage {
+ writeErr(w, http.StatusNotFound, "module not found")
+ return
+ }
+ out := map[string]any{"module": info}
+ if r.URL.Query().Get("include") == "yaml" {
+ // YAML may hold secrets — operator+.
+ if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
+ return
+ }
+ raw, err := h.modStore().ReadYAML(name)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, err.Error())
+ return
+ }
+ out["yaml"] = string(raw)
+ }
+ writeJSON(w, http.StatusOK, out)
+}
+
+func (h *Handler) getModuleYAML(w http.ResponseWriter, r *http.Request, name string) {
+ if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
+ return
+ }
+ if !modstore.NameRe.MatchString(name) {
+ writeErr(w, http.StatusBadRequest, "invalid module name")
+ return
+ }
+ raw, err := h.modStore().ReadYAML(name)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, err.Error())
+ return
+ }
+ w.Header().Set("Content-Type", "text/yaml; charset=utf-8")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(raw)
+}
+
+func (h *Handler) getModulePackage(w http.ResponseWriter, r *http.Request, name string) {
+ if _, ok := auth.Guard(w, r, auth.RoleOperator); !ok {
+ return
+ }
+ if !modstore.NameRe.MatchString(name) {
+ writeErr(w, http.StatusBadRequest, "invalid module name")
+ return
+ }
+ f, _, err := h.modStore().OpenPackage(name)
+ if err != nil {
+ writeErr(w, http.StatusNotFound, err.Error())
+ return
+ }
+ defer f.Close()
+ modTime := time.Time{}
+ if st, err := f.Stat(); err == nil {
+ modTime = st.ModTime()
+ }
+ w.Header().Set("Content-Type", "application/zip")
+ w.Header().Set("Content-Disposition", `attachment; filename="`+name+`.zip"`)
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ http.ServeContent(w, r, name+".zip", modTime, f)
}
func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string) {
- // Writing a module.yaml changes how streams are captured on this host:
- // operator, and recorded.
p, ok := auth.Guard(w, r, auth.RoleOperator)
if !ok {
return
}
- if !moduleNameRe.MatchString(name) {
+ if !modstore.NameRe.MatchString(name) {
writeErr(w, http.StatusBadRequest, "invalid module name")
return
}
@@ -104,47 +171,92 @@ func (h *Handler) putModule(w http.ResponseWriter, r *http.Request, name string)
writeErr(w, http.StatusBadRequest, err.Error())
return
}
- if len(strings.TrimSpace(string(yamlBytes))) == 0 {
- writeErr(w, http.StatusBadRequest, "empty module.yaml")
+
+ info, err := h.modStore().WriteYAML(name, yamlBytes)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
return
}
- modDir := filepath.Join(modhost.ModulesDir(repo.Root()), name)
- if err := os.MkdirAll(modDir, 0o755); err != nil {
- writeErr(w, http.StatusInternalServerError, err.Error())
- return
- }
- dest := filepath.Join(modDir, "module.yaml")
- tmp := dest + ".tmp"
- if err := os.WriteFile(tmp, yamlBytes, 0o644); err != nil {
- writeErr(w, http.StatusInternalServerError, err.Error())
- return
- }
- if err := os.Rename(tmp, dest); err != nil {
- _ = os.Remove(tmp)
- writeErr(w, http.StatusInternalServerError, err.Error())
- return
- }
-
- info := moduleYAMLInfo(modDir, name)
- h.audit(r, p, http.StatusOK, "uploaded module.yaml for "+name)
+ h.audit(r, p, http.StatusOK, "updated module.yaml for "+name)
h.logger().Info("module.yaml updated", "module", name, "by", p.Actor(), "sha256", info.YAMLSHA256)
+ h.notifyModules(name, "yaml_updated")
writeJSON(w, http.StatusOK, map[string]any{
"ok": true,
"module": info,
})
}
-func moduleYAMLInfo(modDir, name string) moduleInfo {
- info := moduleInfo{Name: name}
- b, err := os.ReadFile(filepath.Join(modDir, "module.yaml"))
- if err != nil {
- return info
+func (h *Handler) deleteModule(w http.ResponseWriter, r *http.Request, name string) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
}
- sum := sha256.Sum256(b)
- info.HasYAML = true
- info.YAMLSHA256 = hex.EncodeToString(sum[:])
- return info
+ if !modstore.NameRe.MatchString(name) {
+ writeErr(w, http.StatusBadRequest, "invalid module name")
+ return
+ }
+ if err := h.modStore().Delete(name); err != nil {
+ writeErr(w, http.StatusNotFound, err.Error())
+ return
+ }
+ h.audit(r, p, http.StatusOK, "deleted module "+name)
+ h.logger().Info("module deleted", "module", name, "by", p.Actor())
+ h.notifyModules(name, "deleted")
+ writeJSON(w, http.StatusOK, map[string]any{"ok": true})
+}
+
+func (h *Handler) uploadModule(w http.ResponseWriter, r *http.Request) {
+ p, ok := auth.Guard(w, r, auth.RoleOperator)
+ if !ok {
+ return
+ }
+ if err := r.ParseMultipartForm(modstore.MaxPackageBytes + (1 << 20)); err != nil {
+ writeErr(w, http.StatusBadRequest, "multipart: "+err.Error())
+ return
+ }
+ name := strings.TrimSpace(r.FormValue("name"))
+ file, hdr, err := r.FormFile("file")
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, "missing file field")
+ return
+ }
+ defer file.Close()
+ if name == "" && hdr != nil {
+ // rte.zip → rte (helps flat release zips before binary inference).
+ base := strings.TrimSuffix(filepath.Base(hdr.Filename), filepath.Ext(hdr.Filename))
+ base = strings.ToLower(strings.TrimSpace(base))
+ if modstore.NameRe.MatchString(base) {
+ name = base
+ }
+ }
+ if hdr.Size > modstore.MaxPackageBytes {
+ writeErr(w, http.StatusBadRequest, "zip too large")
+ return
+ }
+ raw, err := io.ReadAll(io.LimitReader(file, modstore.MaxPackageBytes+1))
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ if int64(len(raw)) > modstore.MaxPackageBytes {
+ writeErr(w, http.StatusBadRequest, "zip too large")
+ return
+ }
+ info, err := h.modStore().InstallZip(raw, name)
+ if err != nil {
+ writeErr(w, http.StatusBadRequest, err.Error())
+ return
+ }
+ h.audit(r, p, http.StatusOK, "uploaded module package "+info.Name)
+ h.logger().Info("module package uploaded",
+ "module", info.Name, "by", p.Actor(),
+ "package_sha256", info.PackageSHA256, "arches", info.Arches)
+ h.notifyModules(info.Name, "uploaded")
+ writeJSON(w, http.StatusOK, map[string]any{
+ "ok": true,
+ "module": info,
+ })
}
// extractModuleYAML accepts raw YAML or JSON {"yaml":"..."}.
@@ -163,7 +275,6 @@ func extractModuleYAML(contentType string, body []byte) ([]byte, error) {
}
return []byte(wrap.YAML), nil
default:
- // text/yaml, application/x-yaml, or bare body
return body, nil
}
}
diff --git a/apps/streamd/internal/api/variants.go b/apps/streamd/internal/api/variants.go
index 69da377..c29db91 100644
--- a/apps/streamd/internal/api/variants.go
+++ b/apps/streamd/internal/api/variants.go
@@ -6,7 +6,7 @@ import (
"strings"
"time"
- "drmdecryption/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/db"
)
// stalePlaylistS is how old a playlist may get before the output counts as
diff --git a/apps/streamd/internal/auth/auth_test.go b/apps/streamd/internal/auth/auth_test.go
index b4a7df4..cbe85b3 100644
--- a/apps/streamd/internal/auth/auth_test.go
+++ b/apps/streamd/internal/auth/auth_test.go
@@ -8,7 +8,7 @@ import (
"testing"
"time"
- "drmdecryption/apps/streamd/internal/httpx"
+ "streamd/apps/streamd/internal/httpx"
_ "modernc.org/sqlite"
)
diff --git a/apps/streamd/internal/auth/handlers.go b/apps/streamd/internal/auth/handlers.go
index 40290d0..a86d412 100644
--- a/apps/streamd/internal/auth/handlers.go
+++ b/apps/streamd/internal/auth/handlers.go
@@ -11,7 +11,7 @@ import (
"sync"
"time"
- "drmdecryption/apps/streamd/internal/httpx"
+ "streamd/apps/streamd/internal/httpx"
)
// Handler serves the auth routes: login/logout/me, user administration, API
diff --git a/apps/streamd/internal/auth/middleware.go b/apps/streamd/internal/auth/middleware.go
index db2e5a1..8d84625 100644
--- a/apps/streamd/internal/auth/middleware.go
+++ b/apps/streamd/internal/auth/middleware.go
@@ -8,7 +8,7 @@ import (
"strings"
"time"
- "drmdecryption/apps/streamd/internal/httpx"
+ "streamd/apps/streamd/internal/httpx"
)
const (
diff --git a/apps/streamd/internal/db/db.go b/apps/streamd/internal/db/db.go
index 522e009..aa6b3f7 100644
--- a/apps/streamd/internal/db/db.go
+++ b/apps/streamd/internal/db/db.go
@@ -41,7 +41,8 @@ type Stream struct {
MPD string `json:"mpd"`
Key string `json:"key"`
HeadersJSON string `json:"headers_json"`
- Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE)
+ Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE)
+ Egress string `json:"egress"` // named egress profile (wireguard/socks); used when Proxy empty
VideoSelect string `json:"video_select"`
AudioSelect string `json:"audio_select"`
Enabled bool `json:"enabled"`
@@ -81,6 +82,7 @@ type Stream struct {
HasKey bool `json:"has_key"`
HasHeaders bool `json:"has_headers"`
HasProxy bool `json:"has_proxy"`
+ HasEgress bool `json:"has_egress"`
KeyValid bool `json:"key_valid"`
// DRMRequired is DRMMode resolved: whether this stream needs keys at all.
DRMRequired bool `json:"drm_required"`
@@ -103,6 +105,7 @@ type CreateStream struct {
Key string `json:"key"`
HeadersJSON string `json:"headers_json"`
Proxy string `json:"proxy"`
+ Egress string `json:"egress"`
VideoSelect string `json:"video_select"`
AudioSelect string `json:"audio_select"`
Rewriter string `json:"rewriter"`
@@ -128,6 +131,7 @@ type PatchStream struct {
Key *string `json:"key"`
HeadersJSON *string `json:"headers_json"`
Proxy *string `json:"proxy"`
+ Egress *string `json:"egress"`
VideoSelect *string `json:"video_select"`
AudioSelect *string `json:"audio_select"`
Rewriter *string `json:"rewriter"`
@@ -230,6 +234,7 @@ CREATE TABLE IF NOT EXISTS agent_claims (
`ALTER TABLE streams ADD COLUMN on_demand INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE streams ADD COLUMN idle_timeout_s INTEGER NOT NULL DEFAULT 300`,
`ALTER TABLE streams ADD COLUMN public INTEGER NOT NULL DEFAULT 1`,
+ `ALTER TABLE streams ADD COLUMN egress TEXT NOT NULL DEFAULT ''`,
} {
_, _ = s.DB.Exec(stmt)
}
@@ -239,7 +244,13 @@ CREATE TABLE IF NOT EXISTS agent_claims (
if err := s.migrateSettings(); err != nil {
return err
}
- return s.migrateSchedules()
+ if err := s.migrateSchedules(); err != nil {
+ return err
+ }
+ if err := s.migrateEgress(); err != nil {
+ return err
+ }
+ return s.migrateSessions()
}
func now() string {
@@ -264,10 +275,13 @@ func slug(name string) string {
return out
}
+// Slug normalises a name the same way stream and egress profile names are stored.
+func Slug(name string) string { return slug(name) }
+
const streamSelect = `
SELECT s.id, s.name, s.title, COALESCE(s.description,''), COALESCE(s.tags,''),
s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
- COALESCE(s.proxy,''), s.video_select, s.audio_select, s.enabled, s.rewriter,
+ COALESCE(s.proxy,''), COALESCE(s.egress,''), s.video_select, s.audio_select, s.enabled, s.rewriter,
COALESCE(s.variants_json,''), COALESCE(s.outputs_json,''), COALESCE(s.settings_json,''),
COALESCE(s.drm_mode,'auto'), COALESCE(s.on_demand,0),
COALESCE(s.idle_timeout_s,300), COALESCE(s.public,1),
@@ -318,7 +332,7 @@ func scanStream(row rowScanner) (Stream, error) {
err := row.Scan(
&st.ID, &st.Name, &st.Title, &st.Description, &st.Tags,
&st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
- &st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter,
+ &st.Proxy, &st.Egress, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter,
&st.VariantsJSON, &st.OutputsJSON, &st.SettingsJSON,
&st.DRMMode, &onDemand, &st.IdleTimeoutS, &public,
&st.CreatedAt, &st.UpdatedAt,
@@ -361,6 +375,7 @@ func (st *Stream) fillDerived() {
hdr := strings.TrimSpace(st.HeadersJSON)
st.HasHeaders = hdr != "" && hdr != "{}" && hdr != "null"
st.HasProxy = strings.TrimSpace(st.Proxy) != ""
+ st.HasEgress = strings.TrimSpace(st.Egress) != ""
switch strings.ToLower(strings.TrimSpace(st.DRMMode)) {
case DRMYes:
st.DRMRequired = true
@@ -557,12 +572,13 @@ func (s *Store) CreateStream(in CreateStream) (Stream, error) {
}
ts := now()
res, err := s.DB.Exec(`
-INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,
+INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,egress,
video_select,audio_select,enabled,rewriter,variants_json,outputs_json,
settings_json,drm_mode,on_demand,idle_timeout_s,public,created_at,updated_at)
-VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
+VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
name, in.Title, strings.TrimSpace(in.Description), normalizeTags(in.Tags),
in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy),
+ slug(strings.TrimSpace(in.Egress)),
in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, outputsJSON,
settingsJSON, normalizeDRMMode(in.DRMMode), onDemand, idle, public, ts, ts)
if err != nil {
@@ -654,6 +670,9 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
if in.Proxy != nil {
cur.Proxy = strings.TrimSpace(*in.Proxy)
}
+ if in.Egress != nil {
+ cur.Egress = slug(strings.TrimSpace(*in.Egress))
+ }
if in.VideoSelect != nil {
cur.VideoSelect = *in.VideoSelect
}
@@ -730,11 +749,11 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
ts := now()
_, err = s.DB.Exec(`
UPDATE streams SET title=?, description=?, tags=?, app=?, channel=?, mpd=?, key_kid_key=?,
- headers_json=?, proxy=?, video_select=?, audio_select=?, enabled=?, rewriter=?,
+ headers_json=?, proxy=?, egress=?, video_select=?, audio_select=?, enabled=?, rewriter=?,
variants_json=?, outputs_json=?, settings_json=?, drm_mode=?, on_demand=?,
idle_timeout_s=?, public=?, updated_at=? WHERE id=?`,
cur.Title, cur.Description, cur.Tags, cur.App, cur.Channel, cur.MPD, cur.Key,
- cur.HeadersJSON, cur.Proxy, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter,
+ cur.HeadersJSON, cur.Proxy, cur.Egress, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter,
cur.VariantsJSON, cur.OutputsJSON, cur.SettingsJSON, cur.DRMMode, onDemand,
cur.IdleTimeoutS, public, ts, id)
if err != nil {
@@ -775,7 +794,16 @@ func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) {
if mpd == "" {
return Stream{}, fmt.Errorf("mpd required")
}
- _, err := s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
+ st, err := s.GetStream(id)
+ if err != nil {
+ return Stream{}, err
+ }
+ // Encrypted streams must receive usable KID:KEY lines — MPD alone leaves
+ // the packager rainbow-decrypting forever.
+ if st.DRMRequired && !ValidKeyPairs(key) {
+ return Stream{}, fmt.Errorf("key required for DRM stream %q (got mpd but no valid KID:KEY)", st.Name)
+ }
+ _, err = s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
mpd, key, now(), id)
if err != nil {
return Stream{}, err
diff --git a/apps/streamd/internal/db/egress.go b/apps/streamd/internal/db/egress.go
new file mode 100644
index 0000000..6371c83
--- /dev/null
+++ b/apps/streamd/internal/db/egress.go
@@ -0,0 +1,226 @@
+package db
+
+import (
+ "database/sql"
+ "fmt"
+ "strings"
+)
+
+const (
+ EgressKindWireGuard = "wireguard"
+ EgressKindSocks = "socks"
+
+ EgressStopped = "stopped"
+ EgressStarting = "starting"
+ EgressUp = "up"
+ EgressDown = "down"
+ EgressError = "error"
+)
+
+// EgressProfile is a named origin-egress path (WireGuard netns or plain SOCKS).
+// Conf blobs live on disk under data/egress//; never in this table.
+type EgressProfile struct {
+ ID int64 `json:"id"`
+ Name string `json:"name"`
+ Kind string `json:"kind"`
+ Enabled bool `json:"enabled"`
+ ListenPort int `json:"listen_port"`
+ SocksURL string `json:"socks_url,omitempty"`
+ Status string `json:"status"`
+ LastError string `json:"last_error,omitempty"`
+ EgressIP string `json:"egress_ip,omitempty"`
+ HasConf bool `json:"has_conf"`
+ CreatedAt string `json:"created_at"`
+ UpdatedAt string `json:"updated_at"`
+}
+
+func (s *Store) migrateEgress() error {
+ _, err := s.DB.Exec(`
+CREATE TABLE IF NOT EXISTS egress_profiles (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ name TEXT NOT NULL UNIQUE,
+ kind TEXT NOT NULL DEFAULT 'wireguard',
+ enabled INTEGER NOT NULL DEFAULT 0,
+ listen_port INTEGER NOT NULL DEFAULT 0,
+ socks_url TEXT NOT NULL DEFAULT '',
+ status TEXT NOT NULL DEFAULT 'stopped',
+ last_error TEXT NOT NULL DEFAULT '',
+ egress_ip TEXT NOT NULL DEFAULT '',
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+);
+`)
+ return err
+}
+
+type CreateEgressProfile struct {
+ Name string `json:"name"`
+ Kind string `json:"kind"`
+ Enabled *bool `json:"enabled"`
+ SocksURL string `json:"socks_url"`
+}
+
+type UpdateEgressProfile struct {
+ Enabled *bool `json:"enabled"`
+ SocksURL *string `json:"socks_url"`
+ Kind *string `json:"kind"`
+}
+
+func normalizeEgressKind(k string) (string, error) {
+ switch strings.ToLower(strings.TrimSpace(k)) {
+ case "", EgressKindWireGuard:
+ return EgressKindWireGuard, nil
+ case EgressKindSocks:
+ return EgressKindSocks, nil
+ default:
+ return "", fmt.Errorf("kind must be %q or %q", EgressKindWireGuard, EgressKindSocks)
+ }
+}
+
+func (s *Store) ListEgressProfiles() ([]EgressProfile, error) {
+ rows, err := s.DB.Query(`
+SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at
+FROM egress_profiles ORDER BY name`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []EgressProfile
+ for rows.Next() {
+ p, err := scanEgress(rows)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, p)
+ }
+ if out == nil {
+ out = []EgressProfile{}
+ }
+ return out, rows.Err()
+}
+
+func (s *Store) GetEgressProfile(id int64) (EgressProfile, error) {
+ row := s.DB.QueryRow(`
+SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at
+FROM egress_profiles WHERE id=?`, id)
+ return scanEgress(row)
+}
+
+func (s *Store) GetEgressProfileByName(name string) (EgressProfile, error) {
+ name = slug(name)
+ if name == "" {
+ return EgressProfile{}, fmt.Errorf("name required")
+ }
+ row := s.DB.QueryRow(`
+SELECT id, name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at
+FROM egress_profiles WHERE name=?`, name)
+ return scanEgress(row)
+}
+
+func scanEgress(row rowScanner) (EgressProfile, error) {
+ var p EgressProfile
+ var enabled int
+ err := row.Scan(
+ &p.ID, &p.Name, &p.Kind, &enabled, &p.ListenPort, &p.SocksURL,
+ &p.Status, &p.LastError, &p.EgressIP, &p.CreatedAt, &p.UpdatedAt,
+ )
+ if err != nil {
+ return p, err
+ }
+ p.Enabled = enabled != 0
+ if p.Status == "" {
+ p.Status = EgressStopped
+ }
+ return p, nil
+}
+
+func (s *Store) CreateEgressProfile(in CreateEgressProfile) (EgressProfile, error) {
+ name := slug(in.Name)
+ if name == "" {
+ return EgressProfile{}, fmt.Errorf("name required (slug of letters, digits, hyphens)")
+ }
+ kind, err := normalizeEgressKind(in.Kind)
+ if err != nil {
+ return EgressProfile{}, err
+ }
+ socks := strings.TrimSpace(in.SocksURL)
+ if kind == EgressKindSocks && socks == "" {
+ return EgressProfile{}, fmt.Errorf("socks_url required for kind=socks")
+ }
+ enabled := 0
+ if in.Enabled != nil && *in.Enabled {
+ enabled = 1
+ }
+ ts := now()
+ res, err := s.DB.Exec(`
+INSERT INTO egress_profiles(name, kind, enabled, listen_port, socks_url, status, last_error, egress_ip, created_at, updated_at)
+VALUES(?,?,?,0,?,?, '','',?,?)`,
+ name, kind, enabled, socks, EgressStopped, ts, ts)
+ if err != nil {
+ if strings.Contains(strings.ToLower(err.Error()), "unique") {
+ return EgressProfile{}, fmt.Errorf("egress profile %q already exists", name)
+ }
+ return EgressProfile{}, err
+ }
+ id, _ := res.LastInsertId()
+ return s.GetEgressProfile(id)
+}
+
+func (s *Store) UpdateEgressProfile(id int64, in UpdateEgressProfile) (EgressProfile, error) {
+ cur, err := s.GetEgressProfile(id)
+ if err != nil {
+ return EgressProfile{}, err
+ }
+ if in.Enabled != nil {
+ cur.Enabled = *in.Enabled
+ }
+ if in.SocksURL != nil {
+ cur.SocksURL = strings.TrimSpace(*in.SocksURL)
+ }
+ if in.Kind != nil {
+ kind, err := normalizeEgressKind(*in.Kind)
+ if err != nil {
+ return EgressProfile{}, err
+ }
+ cur.Kind = kind
+ }
+ if cur.Kind == EgressKindSocks && cur.SocksURL == "" {
+ return EgressProfile{}, fmt.Errorf("socks_url required for kind=socks")
+ }
+ enabled := 0
+ if cur.Enabled {
+ enabled = 1
+ }
+ ts := now()
+ _, err = s.DB.Exec(`
+UPDATE egress_profiles SET kind=?, enabled=?, socks_url=?, updated_at=? WHERE id=?`,
+ cur.Kind, enabled, cur.SocksURL, ts, id)
+ if err != nil {
+ return EgressProfile{}, err
+ }
+ return s.GetEgressProfile(id)
+}
+
+func (s *Store) DeleteEgressProfile(id int64) error {
+ res, err := s.DB.Exec(`DELETE FROM egress_profiles WHERE id=?`, id)
+ if err != nil {
+ return err
+ }
+ n, _ := res.RowsAffected()
+ if n == 0 {
+ return sql.ErrNoRows
+ }
+ return nil
+}
+
+// SetEgressRuntime updates live status fields without touching config.
+func (s *Store) SetEgressRuntime(id int64, status, lastErr, egressIP string, listenPort int) error {
+ status = strings.TrimSpace(status)
+ if status == "" {
+ status = EgressStopped
+ }
+ _, err := s.DB.Exec(`
+UPDATE egress_profiles SET status=?, last_error=?, egress_ip=?, listen_port=?, updated_at=? WHERE id=?`,
+ status, strings.TrimSpace(lastErr), strings.TrimSpace(egressIP), listenPort, now(), id)
+ return err
+}
diff --git a/apps/streamd/internal/db/egress_test.go b/apps/streamd/internal/db/egress_test.go
new file mode 100644
index 0000000..3b6c9c1
--- /dev/null
+++ b/apps/streamd/internal/db/egress_test.go
@@ -0,0 +1,117 @@
+package db
+
+import (
+ "path/filepath"
+ "testing"
+)
+
+func TestSlugValidation(t *testing.T) {
+ for _, c := range []struct {
+ in, want string
+ }{
+ {"London", "london"},
+ {"dublin-1", "dublin-1"},
+ {" RTE IE ", "rte-ie"},
+ {"!!!", ""},
+ {"Wire_Guard", "wire-guard"},
+ {"a--b", "a-b"},
+ } {
+ if got := Slug(c.in); got != c.want {
+ t.Errorf("Slug(%q) = %q want %q", c.in, got, c.want)
+ }
+ }
+}
+
+func TestEgressCRUD(t *testing.T) {
+ dir := t.TempDir()
+ store, err := Open(filepath.Join(dir, "data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+
+ _, err = store.CreateEgressProfile(CreateEgressProfile{Name: "!!!"})
+ if err == nil {
+ t.Fatal("expected empty slug to fail")
+ }
+
+ on := true
+ p, err := store.CreateEgressProfile(CreateEgressProfile{
+ Name: "London", Kind: "wireguard", Enabled: &on,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if p.Name != "london" || p.Kind != EgressKindWireGuard || !p.Enabled {
+ t.Fatalf("create: %+v", p)
+ }
+ if p.Status != EgressStopped {
+ t.Fatalf("status = %q", p.Status)
+ }
+
+ got, err := store.GetEgressProfileByName("LONDON")
+ if err != nil || got.ID != p.ID {
+ t.Fatalf("GetByName: %+v %v", got, err)
+ }
+
+ off := false
+ url := "socks5://127.0.0.1:1080"
+ kind := EgressKindSocks
+ upd, err := store.UpdateEgressProfile(p.ID, UpdateEgressProfile{
+ Enabled: &off, SocksURL: &url, Kind: &kind,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if upd.Enabled || upd.SocksURL != url || upd.Kind != EgressKindSocks {
+ t.Fatalf("update: %+v", upd)
+ }
+
+ if err := store.SetEgressRuntime(p.ID, EgressUp, "", "1.2.3.4", 18080); err != nil {
+ t.Fatal(err)
+ }
+ got, _ = store.GetEgressProfile(p.ID)
+ if got.Status != EgressUp || got.EgressIP != "1.2.3.4" || got.ListenPort != 18080 {
+ t.Fatalf("runtime: %+v", got)
+ }
+
+ list, err := store.ListEgressProfiles()
+ if err != nil || len(list) != 1 {
+ t.Fatalf("list: %v %#v", err, list)
+ }
+
+ if err := store.DeleteEgressProfile(p.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.GetEgressProfile(p.ID); err == nil {
+ t.Fatal("expected missing after delete")
+ }
+}
+
+func TestStreamEgressField(t *testing.T) {
+ dir := t.TempDir()
+ store, err := Open(filepath.Join(dir, "data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+
+ st, err := store.CreateStream(CreateStream{Name: "rte1", MPD: "https://x/a.mpd", Egress: "Dublin"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if st.Egress != "dublin" || !st.HasEgress || st.HasProxy {
+ t.Fatalf("create egress: %+v has_egress=%v has_proxy=%v", st.Egress, st.HasEgress, st.HasProxy)
+ }
+
+ empty := ""
+ london := "london"
+ st, err = store.PatchStream(st.ID, PatchStream{Egress: &london})
+ if err != nil || st.Egress != "london" {
+ t.Fatalf("patch: %+v %v", st, err)
+ }
+ st, err = store.PatchStream(st.ID, PatchStream{Egress: &empty})
+ if err != nil || st.HasEgress {
+ t.Fatalf("clear egress: %+v %v", st, err)
+ }
+}
diff --git a/apps/streamd/internal/db/events.go b/apps/streamd/internal/db/events.go
index 426285d..07bb1e5 100644
--- a/apps/streamd/internal/db/events.go
+++ b/apps/streamd/internal/db/events.go
@@ -408,6 +408,13 @@ GROUP BY stream_id, substr(at, 1, 17)`, rollupBucketS, rawCutoff); err != nil {
_ = tx.Rollback()
return err
}
+ sessionCutoff := time.Now().UTC().Add(-SessionRetention).Format(time.RFC3339)
+ if _, err := tx.Exec(`
+DELETE FROM stream_sessions
+WHERE ended_at <> '' AND ended_at < ?`, sessionCutoff); err != nil {
+ _ = tx.Rollback()
+ return err
+ }
return tx.Commit()
}
diff --git a/apps/streamd/internal/db/sessions.go b/apps/streamd/internal/db/sessions.go
new file mode 100644
index 0000000..12a3a96
--- /dev/null
+++ b/apps/streamd/internal/db/sessions.go
@@ -0,0 +1,211 @@
+package db
+
+import (
+ "database/sql"
+ "fmt"
+ "time"
+)
+
+// Session end reasons recorded when a run closes.
+const (
+ SessionStopped = "stopped"
+ SessionNREExit = "nre_exit"
+ SessionOrphaned = "orphaned"
+ SessionTimeout = "timeout"
+)
+
+// SessionRetention is how long closed run history is kept.
+const SessionRetention = 90 * 24 * time.Hour
+
+// StreamSession is one media worker run: start → stop/crash with a duration.
+type StreamSession struct {
+ ID int64 `json:"id"`
+ StreamID int64 `json:"stream_id"`
+ StreamName string `json:"stream_name,omitempty"`
+ StreamTitle string `json:"stream_title,omitempty"`
+ StartedAt string `json:"started_at"`
+ EndedAt string `json:"ended_at,omitempty"`
+ DurationS float64 `json:"duration_s"`
+ EndReason string `json:"end_reason,omitempty"`
+ HealthAtEnd string `json:"health_at_end,omitempty"`
+}
+
+func (s *Store) migrateSessions() error {
+ _, err := s.DB.Exec(`
+CREATE TABLE IF NOT EXISTS stream_sessions (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
+ started_at TEXT NOT NULL,
+ ended_at TEXT NOT NULL DEFAULT '',
+ duration_s REAL NOT NULL DEFAULT 0,
+ end_reason TEXT NOT NULL DEFAULT '',
+ health_at_end TEXT NOT NULL DEFAULT ''
+);
+CREATE INDEX IF NOT EXISTS idx_sessions_stream_started ON stream_sessions(stream_id, started_at DESC);
+CREATE INDEX IF NOT EXISTS idx_sessions_ended ON stream_sessions(ended_at DESC);
+CREATE INDEX IF NOT EXISTS idx_sessions_open ON stream_sessions(stream_id, ended_at);
+`)
+ return err
+}
+
+// OpenSession records a new run for streamID. Any previously open row for the
+// same stream is closed as orphaned (e.g. process crash without a clean stop).
+func (s *Store) OpenSession(streamID int64) (int64, error) {
+ if streamID == 0 {
+ return 0, fmt.Errorf("stream id required")
+ }
+ _ = s.CloseOpenSessions(streamID, SessionOrphaned, "stopped")
+ started := now()
+ res, err := s.DB.Exec(`
+INSERT INTO stream_sessions(stream_id, started_at)
+VALUES(?, ?)`, streamID, started)
+ if err != nil {
+ return 0, err
+ }
+ return res.LastInsertId()
+}
+
+// CloseSession ends one open session by id. Already-closed rows are a no-op.
+func (s *Store) CloseSession(id int64, reason, healthAtEnd string) error {
+ if id == 0 {
+ return nil
+ }
+ var started string
+ var ended string
+ err := s.DB.QueryRow(`SELECT started_at, ended_at FROM stream_sessions WHERE id=?`, id).
+ Scan(&started, &ended)
+ if err == sql.ErrNoRows {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if ended != "" {
+ return nil
+ }
+ endedAt := now()
+ dur := durationSeconds(started, endedAt)
+ if reason == "" {
+ reason = SessionStopped
+ }
+ _, err = s.DB.Exec(`
+UPDATE stream_sessions
+SET ended_at=?, duration_s=?, end_reason=?, health_at_end=?
+WHERE id=? AND ended_at=''`,
+ endedAt, dur, reason, healthAtEnd, id)
+ return err
+}
+
+// CloseOpenSessions ends every open session for a stream.
+func (s *Store) CloseOpenSessions(streamID int64, reason, healthAtEnd string) error {
+ if streamID == 0 {
+ return nil
+ }
+ rows, err := s.DB.Query(`
+SELECT id FROM stream_sessions WHERE stream_id=? AND ended_at=''`, streamID)
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ var ids []int64
+ for rows.Next() {
+ var id int64
+ if err := rows.Scan(&id); err != nil {
+ return err
+ }
+ ids = append(ids, id)
+ }
+ for _, id := range ids {
+ if err := s.CloseSession(id, reason, healthAtEnd); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// ListRecentSessions returns the newest closed runs across all streams.
+func (s *Store) ListRecentSessions(limit int) ([]StreamSession, error) {
+ if limit <= 0 {
+ limit = 50
+ }
+ if limit > 200 {
+ limit = 200
+ }
+ rows, err := s.DB.Query(`
+SELECT ss.id, ss.stream_id, COALESCE(st.name,''), COALESCE(st.title,''),
+ ss.started_at, ss.ended_at, ss.duration_s, ss.end_reason, ss.health_at_end
+FROM stream_sessions ss
+LEFT JOIN streams st ON st.id = ss.stream_id
+WHERE ss.ended_at <> ''
+ORDER BY ss.ended_at DESC, ss.id DESC
+LIMIT ?`, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []StreamSession
+ for rows.Next() {
+ var ss StreamSession
+ if err := rows.Scan(
+ &ss.ID, &ss.StreamID, &ss.StreamName, &ss.StreamTitle,
+ &ss.StartedAt, &ss.EndedAt, &ss.DurationS, &ss.EndReason, &ss.HealthAtEnd,
+ ); err != nil {
+ return nil, err
+ }
+ out = append(out, ss)
+ }
+ return out, rows.Err()
+}
+
+// ListStreamSessions returns recent closed runs for one stream.
+func (s *Store) ListStreamSessions(streamID int64, limit int) ([]StreamSession, error) {
+ if limit <= 0 {
+ limit = 50
+ }
+ rows, err := s.DB.Query(`
+SELECT ss.id, ss.stream_id, COALESCE(st.name,''), COALESCE(st.title,''),
+ ss.started_at, ss.ended_at, ss.duration_s, ss.end_reason, ss.health_at_end
+FROM stream_sessions ss
+LEFT JOIN streams st ON st.id = ss.stream_id
+WHERE ss.stream_id=? AND ss.ended_at <> ''
+ORDER BY ss.ended_at DESC, ss.id DESC
+LIMIT ?`, streamID, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []StreamSession
+ for rows.Next() {
+ var ss StreamSession
+ if err := rows.Scan(
+ &ss.ID, &ss.StreamID, &ss.StreamName, &ss.StreamTitle,
+ &ss.StartedAt, &ss.EndedAt, &ss.DurationS, &ss.EndReason, &ss.HealthAtEnd,
+ ); err != nil {
+ return nil, err
+ }
+ out = append(out, ss)
+ }
+ return out, rows.Err()
+}
+
+// PruneSessions drops closed sessions older than SessionRetention.
+func (s *Store) PruneSessions() error {
+ cutoff := time.Now().UTC().Add(-SessionRetention).Format(time.RFC3339)
+ _, err := s.DB.Exec(`
+DELETE FROM stream_sessions
+WHERE ended_at <> '' AND ended_at < ?`, cutoff)
+ return err
+}
+
+func durationSeconds(startedAt, endedAt string) float64 {
+ start, err1 := time.Parse(time.RFC3339, startedAt)
+ end, err2 := time.Parse(time.RFC3339, endedAt)
+ if err1 != nil || err2 != nil {
+ return 0
+ }
+ d := end.Sub(start).Seconds()
+ if d < 0 {
+ return 0
+ }
+ return d
+}
diff --git a/apps/streamd/internal/db/sessions_test.go b/apps/streamd/internal/db/sessions_test.go
new file mode 100644
index 0000000..f6f26b6
--- /dev/null
+++ b/apps/streamd/internal/db/sessions_test.go
@@ -0,0 +1,114 @@
+package db
+
+import (
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func TestStreamSessionsOpenCloseList(t *testing.T) {
+ store, err := Open(filepath.Join(t.TempDir(), "data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+
+ st, err := store.CreateStream(CreateStream{
+ Name: "bbc1", Title: "BBC One", MPD: "https://example.test/a.mpd",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ id1, err := store.OpenSession(st.ID)
+ if err != nil || id1 == 0 {
+ t.Fatalf("OpenSession: id=%d err=%v", id1, err)
+ }
+ time.Sleep(20 * time.Millisecond)
+ if err := store.CloseSession(id1, SessionStopped, "stopped"); err != nil {
+ t.Fatal(err)
+ }
+
+ // Second open should orphan-close nothing (already closed) and create a new row.
+ id2, err := store.OpenSession(st.ID)
+ if err != nil || id2 == 0 || id2 == id1 {
+ t.Fatalf("second OpenSession: id=%d (first=%d) err=%v", id2, id1, err)
+ }
+ if err := store.CloseSession(id2, SessionNREExit, "down"); err != nil {
+ t.Fatal(err)
+ }
+
+ // Idempotent close.
+ if err := store.CloseSession(id2, SessionStopped, "stopped"); err != nil {
+ t.Fatal(err)
+ }
+
+ recent, err := store.ListRecentSessions(10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(recent) != 2 {
+ t.Fatalf("recent len=%d want 2", len(recent))
+ }
+ // Newest ended first.
+ if recent[0].ID != id2 || recent[0].EndReason != SessionNREExit {
+ t.Fatalf("newest = %+v", recent[0])
+ }
+ if recent[1].ID != id1 || recent[1].EndReason != SessionStopped {
+ t.Fatalf("older = %+v", recent[1])
+ }
+ if recent[0].StreamName != "bbc1" || recent[0].DurationS < 0 {
+ t.Fatalf("row fields: %+v", recent[0])
+ }
+
+ per, err := store.ListStreamSessions(st.ID, 5)
+ if err != nil || len(per) != 2 {
+ t.Fatalf("ListStreamSessions: len=%d err=%v", len(per), err)
+ }
+}
+
+func TestOpenSessionClosesOrphan(t *testing.T) {
+ store, err := Open(filepath.Join(t.TempDir(), "data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+
+ st, err := store.CreateStream(CreateStream{
+ Name: "rte1", MPD: "https://example.test/b.mpd",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ orphan, err := store.OpenSession(st.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ next, err := store.OpenSession(st.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if next == orphan {
+ t.Fatal("expected a new session id")
+ }
+
+ var ended, reason string
+ if err := store.DB.QueryRow(
+ `SELECT ended_at, end_reason FROM stream_sessions WHERE id=?`, orphan,
+ ).Scan(&ended, &reason); err != nil {
+ t.Fatal(err)
+ }
+ if ended == "" || reason != SessionOrphaned {
+ t.Fatalf("orphan close: ended=%q reason=%q", ended, reason)
+ }
+
+ _ = store.CloseSession(next, SessionStopped, "stopped")
+ recent, err := store.ListRecentSessions(10)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(recent) != 2 {
+ t.Fatalf("want 2 closed sessions, got %d", len(recent))
+ }
+}
diff --git a/apps/streamd/internal/deps/deps.go b/apps/streamd/internal/deps/deps.go
index 7ee72b9..9b449c5 100644
--- a/apps/streamd/internal/deps/deps.go
+++ b/apps/streamd/internal/deps/deps.go
@@ -14,7 +14,7 @@ import (
"strings"
"time"
- "drmdecryption/repo"
+ "streamd/repo"
)
// Status is the resolved path for each tool after Ensure.
@@ -202,7 +202,7 @@ func httpGet(url string) (*http.Response, error) {
if err != nil {
return nil, err
}
- req.Header.Set("User-Agent", "null-drm-streamd/1.0")
+ req.Header.Set("User-Agent", "streamd/1.0")
return client.Do(req)
}
diff --git a/apps/streamd/internal/egress/conf.go b/apps/streamd/internal/egress/conf.go
new file mode 100644
index 0000000..7e4356b
--- /dev/null
+++ b/apps/streamd/internal/egress/conf.go
@@ -0,0 +1,80 @@
+package egress
+
+import (
+ "bufio"
+ "strings"
+)
+
+// wgInterfaceAddrs extracts Address= values from the [Interface] section of a
+// wg-quick style conf. Private keys are never returned or logged.
+func wgInterfaceAddrs(conf string) []string {
+ var addrs []string
+ section := ""
+ sc := bufio.NewScanner(strings.NewReader(conf))
+ for sc.Scan() {
+ line := strings.TrimSpace(sc.Text())
+ if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
+ continue
+ }
+ if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
+ section = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1]))
+ continue
+ }
+ if section != "interface" {
+ continue
+ }
+ key, val, ok := strings.Cut(line, "=")
+ if !ok {
+ continue
+ }
+ if strings.EqualFold(strings.TrimSpace(key), "Address") {
+ for _, part := range strings.Split(val, ",") {
+ if a := strings.TrimSpace(part); a != "" {
+ addrs = append(addrs, a)
+ }
+ }
+ }
+ }
+ return addrs
+}
+
+// wgSetconfBody strips wg-quick-only keys so the result is valid for `wg setconf`.
+func wgSetconfBody(conf string) string {
+ var b strings.Builder
+ section := ""
+ sc := bufio.NewScanner(strings.NewReader(conf))
+ for sc.Scan() {
+ raw := sc.Text()
+ line := strings.TrimSpace(raw)
+ if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
+ continue
+ }
+ if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
+ section = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1]))
+ b.WriteString(line)
+ b.WriteByte('\n')
+ continue
+ }
+ key, _, ok := strings.Cut(line, "=")
+ if !ok {
+ continue
+ }
+ k := strings.ToLower(strings.TrimSpace(key))
+ if section == "interface" {
+ switch k {
+ case "privatekey", "listenport", "fwmark":
+ b.WriteString(line)
+ b.WriteByte('\n')
+ }
+ continue
+ }
+ if section == "peer" {
+ switch k {
+ case "publickey", "presharedkey", "allowedips", "endpoint", "persistentkeepalive":
+ b.WriteString(line)
+ b.WriteByte('\n')
+ }
+ }
+ }
+ return b.String()
+}
diff --git a/apps/streamd/internal/egress/manager.go b/apps/streamd/internal/egress/manager.go
new file mode 100644
index 0000000..d7a8967
--- /dev/null
+++ b/apps/streamd/internal/egress/manager.go
@@ -0,0 +1,418 @@
+package egress
+
+import (
+ "fmt"
+ "io"
+ "log/slog"
+ "net"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+ "time"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+const (
+ baseListenPort = 18080
+ socksPortInNS = 1080
+)
+
+// Manager brings named egress profiles up and resolves a stream's origin proxy.
+type Manager struct {
+ DataDir string
+ Store *db.Store
+ Log *slog.Logger
+ SocksBin string // microsocks or gost; looked up if empty
+
+ mu sync.Mutex
+ running map[string]*runState // by profile name
+}
+
+type runState struct {
+ name string
+ listenPort int
+ nsIP string // veth IP inside netns, e.g. 10.255.N.2
+ socksCmd *exec.Cmd
+ forwardLn net.Listener
+ stopFwd chan struct{}
+}
+
+// New builds a Manager. SocksBin may be empty (auto LookPath).
+func New(dataDir string, store *db.Store, log *slog.Logger, socksBin string) *Manager {
+ if log == nil {
+ log = slog.Default()
+ }
+ return &Manager{
+ DataDir: dataDir,
+ Store: store,
+ Log: log,
+ SocksBin: socksBin,
+ running: map[string]*runState{},
+ }
+}
+
+// WarnMissingDeps logs once when WireGuard host tools are absent. Safe to call
+// on every platform; non-Linux hosts skip the check.
+func (m *Manager) WarnMissingDeps() {
+ if runtime.GOOS != "linux" {
+ return
+ }
+ for _, bin := range []string{"ip", "wg"} {
+ if _, err := exec.LookPath(bin); err != nil {
+ m.logger().Warn("egress: tool missing from PATH (WireGuard profiles need it)",
+ "bin", bin)
+ }
+ }
+ if _, err := m.findSocksBin(); err != nil {
+ m.logger().Warn("egress: microsocks or gost missing from PATH (WireGuard profiles need a SOCKS forwarder in the netns)")
+ }
+}
+
+func (m *Manager) logger() *slog.Logger {
+ if m.Log != nil {
+ return m.Log
+ }
+ return slog.Default()
+}
+
+func (m *Manager) profileDir(name string) string {
+ return filepath.Join(m.DataDir, "egress", db.Slug(name))
+}
+
+func (m *Manager) confPath(name string) string {
+ return filepath.Join(m.profileDir(name), "wg.conf")
+}
+
+// HasConf reports whether a WireGuard conf file exists for name.
+func (m *Manager) HasConf(name string) bool {
+ st, err := os.Stat(m.confPath(name))
+ return err == nil && st.Size() > 0
+}
+
+// WriteConf stores a WireGuard conf on disk (0600). Does not log contents.
+func (m *Manager) WriteConf(name, contents string) error {
+ name = db.Slug(name)
+ if name == "" {
+ return fmt.Errorf("name required")
+ }
+ dir := m.profileDir(name)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return err
+ }
+ path := m.confPath(name)
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, []byte(contents), 0o600); err != nil {
+ return err
+ }
+ return os.Rename(tmp, path)
+}
+
+// ReadConf returns the raw conf for admin use. Callers must not log it.
+func (m *Manager) ReadConf(name string) (string, error) {
+ b, err := os.ReadFile(m.confPath(name))
+ if err != nil {
+ return "", err
+ }
+ return string(b), nil
+}
+
+// RemoveFiles deletes on-disk conf for a profile (after DB delete).
+func (m *Manager) RemoveFiles(name string) error {
+ name = db.Slug(name)
+ if name == "" {
+ return nil
+ }
+ return os.RemoveAll(m.profileDir(name))
+}
+
+// Enrich fills HasConf on profiles (conf is never stored in the DB).
+func (m *Manager) Enrich(p *db.EgressProfile) {
+ if p == nil {
+ return
+ }
+ if p.Kind == db.EgressKindWireGuard {
+ p.HasConf = m.HasConf(p.Name)
+ }
+}
+
+// ResolveProxy returns the SOCKS/HTTP proxy URL a stream should use for origin
+// fetch. Order: explicit stream.Proxy, then named egress profile, else empty.
+func (m *Manager) ResolveProxy(st db.Stream) (string, error) {
+ if p := strings.TrimSpace(st.Proxy); p != "" {
+ return p, nil
+ }
+ name := strings.TrimSpace(st.Egress)
+ if name == "" {
+ return "", nil
+ }
+ if err := m.EnsureUp(name); err != nil {
+ return "", err
+ }
+ p, err := m.Store.GetEgressProfileByName(name)
+ if err != nil {
+ return "", err
+ }
+ switch p.Kind {
+ case db.EgressKindSocks:
+ u := strings.TrimSpace(p.SocksURL)
+ if u == "" {
+ return "", fmt.Errorf("egress %q has no socks_url", p.Name)
+ }
+ return u, nil
+ default:
+ if p.ListenPort <= 0 {
+ return "", fmt.Errorf("egress %q is up but has no listen port", p.Name)
+ }
+ return fmt.Sprintf("socks5://127.0.0.1:%d", p.ListenPort), nil
+ }
+}
+
+// StartEnabled brings up every profile marked enabled.
+func (m *Manager) StartEnabled() {
+ list, err := m.Store.ListEgressProfiles()
+ if err != nil {
+ m.logger().Error("list egress profiles", "err", err)
+ return
+ }
+ for _, p := range list {
+ if !p.Enabled {
+ continue
+ }
+ if err := m.EnsureUp(p.Name); err != nil {
+ m.logger().Warn("egress start", "name", p.Name, "err", err)
+ }
+ }
+}
+
+// StopAll tears down every running profile.
+func (m *Manager) StopAll() {
+ m.mu.Lock()
+ names := make([]string, 0, len(m.running))
+ for n := range m.running {
+ names = append(names, n)
+ }
+ m.mu.Unlock()
+ for _, n := range names {
+ _ = m.Down(n)
+ }
+}
+
+// Status returns the DB row for a profile (with HasConf filled).
+func (m *Manager) Status(name string) (db.EgressProfile, error) {
+ p, err := m.Store.GetEgressProfileByName(name)
+ if err != nil {
+ return p, err
+ }
+ m.Enrich(&p)
+ return p, nil
+}
+
+// EnsureUp brings a profile to a usable SOCKS endpoint.
+func (m *Manager) EnsureUp(name string) error {
+ name = db.Slug(name)
+ if name == "" {
+ return fmt.Errorf("egress name required")
+ }
+ p, err := m.Store.GetEgressProfileByName(name)
+ if err != nil {
+ return fmt.Errorf("egress profile %q: %w", name, err)
+ }
+
+ m.mu.Lock()
+ if rs, ok := m.running[name]; ok && rs != nil {
+ m.mu.Unlock()
+ return nil
+ }
+ m.mu.Unlock()
+
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressStarting, "", p.EgressIP, p.ListenPort)
+
+ switch p.Kind {
+ case db.EgressKindSocks:
+ u := strings.TrimSpace(p.SocksURL)
+ if u == "" {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, "socks_url required", "", 0)
+ return fmt.Errorf("egress %q: socks_url required", name)
+ }
+ m.mu.Lock()
+ m.running[name] = &runState{name: name}
+ m.mu.Unlock()
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressUp, "", "", 0)
+ return nil
+ case db.EgressKindWireGuard:
+ if runtime.GOOS != "linux" {
+ msg := "wireguard egress requires Linux"
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("%s", msg)
+ }
+ return m.ensureWireGuardUp(p)
+ default:
+ msg := fmt.Sprintf("unknown egress kind %q", p.Kind)
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("%s", msg)
+ }
+}
+
+// Down stops a profile's local SOCKS / netns.
+func (m *Manager) Down(name string) error {
+ name = db.Slug(name)
+ p, err := m.Store.GetEgressProfileByName(name)
+ if err != nil {
+ return err
+ }
+
+ m.mu.Lock()
+ rs := m.running[name]
+ delete(m.running, name)
+ m.mu.Unlock()
+
+ if rs != nil {
+ m.stopRun(rs)
+ }
+ if p.Kind == db.EgressKindWireGuard && runtime.GOOS == "linux" {
+ if err := m.teardownWireGuard(name, p.ID); err != nil {
+ m.logger().Warn("egress teardown", "name", name, "err", err)
+ }
+ }
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressStopped, "", "", 0)
+ return nil
+}
+
+func (m *Manager) stopRun(rs *runState) {
+ if rs.stopFwd != nil {
+ close(rs.stopFwd)
+ rs.stopFwd = nil
+ }
+ if rs.forwardLn != nil {
+ _ = rs.forwardLn.Close()
+ rs.forwardLn = nil
+ }
+ if rs.socksCmd != nil && rs.socksCmd.Process != nil {
+ _ = rs.socksCmd.Process.Kill()
+ _, _ = rs.socksCmd.Process.Wait()
+ rs.socksCmd = nil
+ }
+}
+
+func (m *Manager) findSocksBin() (string, error) {
+ if m.SocksBin != "" {
+ return m.SocksBin, nil
+ }
+ for _, n := range []string{"microsocks", "gost"} {
+ if p, err := exec.LookPath(n); err == nil {
+ m.SocksBin = p
+ return p, nil
+ }
+ }
+ return "", fmt.Errorf("microsocks (or gost) not found on PATH")
+}
+
+func (m *Manager) allocListenPort(id int64) int {
+ return baseListenPort + int(id%1000)
+}
+
+func (m *Manager) vethAddrs(id int64) (hostIP, nsIP, subnet string) {
+ // Unique /30-ish /24 host pair per profile id (1..254).
+ n := int(id % 200)
+ if n <= 0 {
+ n = 1
+ }
+ hostIP = fmt.Sprintf("10.255.%d.1", n)
+ nsIP = fmt.Sprintf("10.255.%d.2", n)
+ subnet = fmt.Sprintf("10.255.%d.0/24", n)
+ return hostIP, nsIP, subnet
+}
+
+func (m *Manager) startLocalForward(listenPort int, destHost string, destPort int) (net.Listener, chan struct{}, error) {
+ ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", listenPort))
+ if err != nil {
+ return nil, nil, err
+ }
+ stop := make(chan struct{})
+ go func() {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ select {
+ case <-stop:
+ return
+ default:
+ return
+ }
+ }
+ go proxyTCP(c, fmt.Sprintf("%s:%d", destHost, destPort))
+ }
+ }()
+ return ln, stop, nil
+}
+
+func proxyTCP(client net.Conn, addr string) {
+ defer client.Close()
+ _ = client.SetDeadline(time.Now().Add(60 * time.Second))
+ upstream, err := net.DialTimeout("tcp", addr, 15*time.Second)
+ if err != nil {
+ return
+ }
+ defer upstream.Close()
+ _ = client.SetDeadline(time.Time{})
+ _ = upstream.SetDeadline(time.Time{})
+ done := make(chan struct{}, 2)
+ go func() { _, _ = io.Copy(upstream, client); done <- struct{}{} }()
+ go func() { _, _ = io.Copy(client, upstream); done <- struct{}{} }()
+ <-done
+}
+
+// TestDial tries a short TCP connect through the resolved SOCKS endpoint of a
+// profile (after EnsureUp). Used by POST /api/egress/:name/test.
+func (m *Manager) TestDial(name string) (map[string]any, error) {
+ if err := m.EnsureUp(name); err != nil {
+ return nil, err
+ }
+ p, err := m.Store.GetEgressProfileByName(name)
+ if err != nil {
+ return nil, err
+ }
+ var proxyURL string
+ switch p.Kind {
+ case db.EgressKindSocks:
+ proxyURL = strings.TrimSpace(p.SocksURL)
+ default:
+ if p.ListenPort <= 0 {
+ return nil, fmt.Errorf("no listen port")
+ }
+ proxyURL = fmt.Sprintf("socks5://127.0.0.1:%d", p.ListenPort)
+ }
+ out := map[string]any{
+ "ok": true,
+ "name": p.Name,
+ "kind": p.Kind,
+ "proxy_url": proxyURL,
+ "status": p.Status,
+ "egress_ip": p.EgressIP,
+ }
+ // Dial the local SOCKS port to confirm it accepts TCP.
+ hostPort := ""
+ if p.Kind == db.EgressKindWireGuard && p.ListenPort > 0 {
+ hostPort = fmt.Sprintf("127.0.0.1:%d", p.ListenPort)
+ } else if u := strings.TrimPrefix(strings.TrimPrefix(proxyURL, "socks5://"), "socks5h://"); u != proxyURL {
+ if i := strings.LastIndex(u, "@"); i >= 0 {
+ u = u[i+1:]
+ }
+ hostPort = u
+ }
+ if hostPort != "" {
+ c, err := net.DialTimeout("tcp", hostPort, 5*time.Second)
+ if err != nil {
+ out["ok"] = false
+ out["error"] = err.Error()
+ return out, fmt.Errorf("socks dial: %w", err)
+ }
+ _ = c.Close()
+ out["socks_reachable"] = true
+ }
+ return out, nil
+}
diff --git a/apps/streamd/internal/egress/manager_test.go b/apps/streamd/internal/egress/manager_test.go
new file mode 100644
index 0000000..b355237
--- /dev/null
+++ b/apps/streamd/internal/egress/manager_test.go
@@ -0,0 +1,100 @@
+package egress
+
+import (
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+func TestResolveProxyOrder(t *testing.T) {
+ dir := t.TempDir()
+ store, err := db.Open(filepath.Join(dir, "data"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer store.Close()
+
+ m := New(filepath.Join(dir, "data"), store, nil, "")
+
+ // Neither proxy nor egress.
+ got, err := m.ResolveProxy(db.Stream{Name: "a"})
+ if err != nil || got != "" {
+ t.Fatalf("empty: got %q err %v", got, err)
+ }
+
+ // Explicit proxy wins over egress.
+ got, err = m.ResolveProxy(db.Stream{
+ Proxy: "socks5://127.0.0.1:9999",
+ Egress: "london",
+ })
+ if err != nil || got != "socks5://127.0.0.1:9999" {
+ t.Fatalf("proxy wins: got %q err %v", got, err)
+ }
+
+ on := true
+ _, err = store.CreateEgressProfile(db.CreateEgressProfile{
+ Name: "dublin",
+ Kind: db.EgressKindSocks,
+ Enabled: &on,
+ SocksURL: "socks5://10.0.0.5:1080",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ got, err = m.ResolveProxy(db.Stream{Egress: "dublin"})
+ if err != nil || got != "socks5://10.0.0.5:1080" {
+ t.Fatalf("egress socks: got %q err %v", got, err)
+ }
+
+ // Missing profile.
+ _, err = m.ResolveProxy(db.Stream{Egress: "missing"})
+ if err == nil {
+ t.Fatal("expected error for missing profile")
+ }
+
+ // WireGuard on non-Linux must fail EnsureUp (covered when GOOS != linux).
+ _, err = store.CreateEgressProfile(db.CreateEgressProfile{
+ Name: "london", Kind: db.EgressKindWireGuard, Enabled: &on,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = m.ResolveProxy(db.Stream{Egress: "london"})
+ // On Linux without conf/tools this also errors; on Windows always errors.
+ if err == nil {
+ t.Fatal("expected wireguard EnsureUp to fail without a working tunnel")
+ }
+}
+
+func TestWgConfParse(t *testing.T) {
+ conf := `[Interface]
+PrivateKey = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEE=
+Address = 10.64.0.2/32
+Address = fd00::2/128
+DNS = 1.1.1.1
+
+[Peer]
+PublicKey = BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBEE=
+AllowedIPs = 0.0.0.0/0, ::/0
+Endpoint = 203.0.113.1:51820
+`
+ addrs := wgInterfaceAddrs(conf)
+ if len(addrs) != 2 || addrs[0] != "10.64.0.2/32" || addrs[1] != "fd00::2/128" {
+ t.Fatalf("addrs: %#v", addrs)
+ }
+ body := wgSetconfBody(conf)
+ lower := strings.ToLower(body)
+ if strings.Contains(lower, "address") || strings.Contains(lower, "dns") {
+ t.Fatalf("setconf body still has wg-quick keys:\n%s", body)
+ }
+ if !strings.Contains(body, "PrivateKey") || !strings.Contains(body, "PublicKey") {
+ t.Fatalf("setconf missing keys:\n%s", body)
+ }
+ addrs = wgInterfaceAddrs("[Interface]\nAddress = 10.1.0.2/32, 10.1.0.3/32\n")
+ if len(addrs) != 2 {
+ t.Fatalf("combined: %#v", addrs)
+ }
+}
diff --git a/apps/streamd/internal/egress/wg_linux.go b/apps/streamd/internal/egress/wg_linux.go
new file mode 100644
index 0000000..a26c3a3
--- /dev/null
+++ b/apps/streamd/internal/egress/wg_linux.go
@@ -0,0 +1,302 @@
+//go:build linux
+
+package egress
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
+ name := p.Name
+ confPath := m.confPath(name)
+ raw, err := os.ReadFile(confPath)
+ if err != nil {
+ msg := "wg.conf missing; upload a WireGuard conf first"
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("egress %q: %s", name, msg)
+ }
+ addrs := wgInterfaceAddrs(string(raw))
+ if len(addrs) == 0 {
+ msg := "wg.conf has no Interface Address="
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("egress %q: %s", name, msg)
+ }
+ socksBin, err := m.findSocksBin()
+ if err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ return err
+ }
+ if _, err := exec.LookPath("ip"); err != nil {
+ msg := "ip (iproute2) not found on PATH"
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("%s", msg)
+ }
+ if _, err := exec.LookPath("wg"); err != nil {
+ msg := "wg (wireguard-tools) not found on PATH"
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("%s", msg)
+ }
+
+ listenPort := p.ListenPort
+ if listenPort <= 0 {
+ listenPort = m.allocListenPort(p.ID)
+ }
+ hostIP, nsIP, _ := m.vethAddrs(p.ID)
+ nsName := netnsName(name)
+ wgDev := wgDevName(name)
+ hostVeth := hostVethName(name)
+ nsVeth := "hv0"
+
+ // Tear down any leftover state before bringing up.
+ _ = m.teardownWireGuard(name, p.ID)
+
+ run := func(args ...string) error {
+ cmd := exec.Command(args[0], args[1:]...)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s: %w (%s)", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
+ }
+ return nil
+ }
+ nsExec := func(args ...string) error {
+ full := append([]string{"ip", "netns", "exec", nsName}, args...)
+ return run(full...)
+ }
+
+ if err := run("ip", "netns", "add", nsName); err != nil {
+ // Already exists is fine after a partial teardown.
+ if !strings.Contains(err.Error(), "File exists") {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ return err
+ }
+ }
+ // DNS inside the netns: host /etc/resolv.conf often points at
+ // 127.0.0.53 (systemd-resolved), which is unreachable from the ns.
+ // ip netns exec bind-mounts /etc/netns//resolv.conf over /etc/resolv.conf.
+ if err := writeNetnsResolv(nsName); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ return err
+ }
+ // Loopback inside ns.
+ _ = nsExec("ip", "link", "set", "lo", "up")
+
+ if err := run("ip", "link", "add", wgDev, "type", "wireguard"); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ return err
+ }
+ if err := run("ip", "link", "set", wgDev, "netns", nsName); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = run("ip", "link", "del", wgDev)
+ return err
+ }
+
+ setconfPath := filepath.Join(m.profileDir(name), "wg.setconf")
+ body := wgSetconfBody(string(raw))
+ if err := os.WriteFile(setconfPath, []byte(body), 0o600); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ return err
+ }
+ if err := nsExec("wg", "setconf", wgDev, setconfPath); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ for _, a := range addrs {
+ if err := nsExec("ip", "address", "add", a, "dev", wgDev); err != nil {
+ // "File exists" after restart is fine.
+ if !strings.Contains(err.Error(), "File exists") {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ }
+ }
+ if err := nsExec("ip", "link", "set", wgDev, "up"); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ // Default route only inside the netns — never the host table.
+ _ = nsExec("ip", "route", "replace", "default", "dev", wgDev)
+
+ if err := run("ip", "link", "add", hostVeth, "type", "veth", "peer", "name", nsVeth); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ if err := run("ip", "link", "set", nsVeth, "netns", nsName); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ if err := run("ip", "addr", "add", hostIP+"/24", "dev", hostVeth); err != nil && !strings.Contains(err.Error(), "File exists") {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ if err := run("ip", "link", "set", hostVeth, "up"); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ if err := nsExec("ip", "addr", "add", nsIP+"/24", "dev", nsVeth); err != nil && !strings.Contains(err.Error(), "File exists") {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+ if err := nsExec("ip", "link", "set", nsVeth, "up"); err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+
+ socksCmd, err := m.startSocksInNS(nsName, socksBin, nsIP)
+ if err != nil {
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+
+ ln, stopFwd, err := m.startLocalForward(listenPort, nsIP, socksPortInNS)
+ if err != nil {
+ _ = socksCmd.Process.Kill()
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
+ _ = m.teardownWireGuard(name, p.ID)
+ return err
+ }
+
+ rs := &runState{
+ name: name,
+ listenPort: listenPort,
+ nsIP: nsIP,
+ socksCmd: socksCmd,
+ forwardLn: ln,
+ stopFwd: stopFwd,
+ }
+ m.mu.Lock()
+ m.running[name] = rs
+ m.mu.Unlock()
+
+ egressIP := probeEgressIP(nsName)
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressUp, "", egressIP, listenPort)
+ m.logger().Info("egress up", "name", name, "listen", listenPort, "ns", nsName, "egress_ip", egressIP)
+ return nil
+}
+
+func (m *Manager) startSocksInNS(nsName, socksBin, bindIP string) (*exec.Cmd, error) {
+ base := filepath.Base(socksBin)
+ var cmd *exec.Cmd
+ switch {
+ case strings.Contains(base, "gost"):
+ cmd = exec.Command("ip", "netns", "exec", nsName, socksBin,
+ "-L", fmt.Sprintf("socks5://%s:%d", bindIP, socksPortInNS))
+ default:
+ // microsocks
+ cmd = exec.Command("ip", "netns", "exec", nsName, socksBin,
+ "-i", bindIP, "-p", fmt.Sprintf("%d", socksPortInNS))
+ }
+ cmd.Stdout = nil
+ cmd.Stderr = nil
+ if err := cmd.Start(); err != nil {
+ return nil, fmt.Errorf("start socks in netns: %w", err)
+ }
+ // Brief wait so a crash-on-start is visible.
+ time.Sleep(200 * time.Millisecond)
+ if cmd.ProcessState != nil && cmd.ProcessState.Exited() {
+ return nil, fmt.Errorf("socks exited immediately")
+ }
+ return cmd, nil
+}
+
+func (m *Manager) teardownWireGuard(name string, _ int64) error {
+ nsName := netnsName(name)
+ wgDev := wgDevName(name)
+ hostVeth := hostVethName(name)
+
+ runQuiet := func(args ...string) {
+ _ = exec.Command(args[0], args[1:]...).Run()
+ }
+ runQuiet("ip", "netns", "exec", nsName, "ip", "link", "del", wgDev)
+ runQuiet("ip", "link", "del", hostVeth)
+ runQuiet("ip", "link", "del", wgDev) // if still in init ns
+ runQuiet("ip", "netns", "del", nsName)
+ _ = os.Remove(filepath.Join(m.profileDir(name), "wg.setconf"))
+ _ = os.RemoveAll(filepath.Join("/etc/netns", nsName))
+ return nil
+}
+
+// writeNetnsResolv installs public resolvers for processes inside the netns
+// (microsocks, curl probe). Without this, SOCKS5 hostname connects fail with
+// error 0x01 when the host uses systemd-resolved's 127.0.0.53 stub.
+func writeNetnsResolv(nsName string) error {
+ dir := filepath.Join("/etc/netns", nsName)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return fmt.Errorf("netns resolv dir: %w", err)
+ }
+ body := "# streamd egress — public DNS (host 127.0.0.53 is unreachable in netns)\n" +
+ "nameserver 1.1.1.1\n" +
+ "nameserver 1.0.0.1\n" +
+ "nameserver 8.8.8.8\n"
+ path := filepath.Join(dir, "resolv.conf")
+ if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
+ return fmt.Errorf("netns resolv.conf: %w", err)
+ }
+ return nil
+}
+
+func netnsName(name string) string {
+ return "streamd-" + name
+}
+
+func wgDevName(name string) string {
+ // IFNAMSIZ is 15.
+ s := "wg-" + name
+ if len(s) > 15 {
+ s = s[:15]
+ }
+ return s
+}
+
+func hostVethName(name string) string {
+ s := "sv-" + name
+ if len(s) > 15 {
+ s = s[:15]
+ }
+ return s
+}
+
+func probeEgressIP(nsName string) string {
+ // Best-effort: ask a public echo over the ns default route.
+ for _, url := range []string{
+ "https://api.ipify.org",
+ "https://ifconfig.me/ip",
+ "https://1.1.1.1/cdn-cgi/trace", // fallback parse below if needed
+ } {
+ cmd := exec.Command("ip", "netns", "exec", nsName,
+ "curl", "-4", "-fsS", "--max-time", "5", url)
+ out, err := cmd.Output()
+ if err != nil {
+ continue
+ }
+ s := strings.TrimSpace(string(out))
+ if strings.Contains(url, "cdn-cgi/trace") {
+ for _, line := range strings.Split(s, "\n") {
+ if strings.HasPrefix(line, "ip=") {
+ return strings.TrimPrefix(line, "ip=")
+ }
+ }
+ continue
+ }
+ if s != "" && !strings.Contains(s, " ") {
+ return s
+ }
+ }
+ return ""
+}
diff --git a/apps/streamd/internal/egress/wg_stub.go b/apps/streamd/internal/egress/wg_stub.go
new file mode 100644
index 0000000..065d686
--- /dev/null
+++ b/apps/streamd/internal/egress/wg_stub.go
@@ -0,0 +1,19 @@
+//go:build !linux
+
+package egress
+
+import (
+ "fmt"
+
+ "streamd/apps/streamd/internal/db"
+)
+
+func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
+ msg := "wireguard egress requires Linux"
+ _ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
+ return fmt.Errorf("%s", msg)
+}
+
+func (m *Manager) teardownWireGuard(name string, id int64) error {
+ return nil
+}
diff --git a/apps/streamd/internal/hlsgate/hlsgate.go b/apps/streamd/internal/hlsgate/hlsgate.go
index 0005dbd..264ece4 100644
--- a/apps/streamd/internal/hlsgate/hlsgate.go
+++ b/apps/streamd/internal/hlsgate/hlsgate.go
@@ -17,10 +17,10 @@ import (
"sync"
"time"
- "drmdecryption/apps/streamd/internal/auth"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/apps/streamd/internal/httpx"
- "drmdecryption/apps/streamd/internal/tsfanout"
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/httpx"
+ "streamd/apps/streamd/internal/tsfanout"
)
// Supervisor is the subset of the media supervisor the gate needs.
diff --git a/apps/streamd/internal/hlsgate/hlsgate_test.go b/apps/streamd/internal/hlsgate/hlsgate_test.go
index 01c318b..8fe07ad 100644
--- a/apps/streamd/internal/hlsgate/hlsgate_test.go
+++ b/apps/streamd/internal/hlsgate/hlsgate_test.go
@@ -11,9 +11,9 @@ import (
"testing"
"time"
- "drmdecryption/apps/streamd/internal/auth"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/apps/streamd/internal/tsfanout"
+ "streamd/apps/streamd/internal/auth"
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/tsfanout"
)
// fakeSup records what the gate asked for, and can pretend a stream comes up.
diff --git a/apps/streamd/internal/logfile/logfile.go b/apps/streamd/internal/logfile/logfile.go
index a4598f8..b9bd4e4 100644
--- a/apps/streamd/internal/logfile/logfile.go
+++ b/apps/streamd/internal/logfile/logfile.go
@@ -64,6 +64,34 @@ func OpenWithBanner(path string, maxBytes int64, generations int, what string) (
return w, nil
}
+// OpenCmdLog prepares a rotating append log and returns the live *os.File for
+// exec.Cmd Stdout/Stderr. Go only inherits a real FD for *os.File; any other
+// io.Writer becomes a pipe, and N_m3u8DL-RE's Spectre progress UI crashes on
+// pipe-backed consoles (ArgumentException in LiveRenderable.RemoveRange).
+//
+// The caller owns the file and must Close it. Mid-run size rotation is skipped
+// (rotation still happens at open when the prior file is already over the cap).
+func OpenCmdLog(path string, maxBytes int64, generations int, what string) (*os.File, error) {
+ w, err := OpenWithBanner(path, maxBytes, generations, what)
+ if err != nil {
+ return nil, err
+ }
+ return w.DetachFile()
+}
+
+// DetachFile transfers ownership of the underlying *os.File to the caller.
+// The Writer becomes inert; do not Write or Close it afterward.
+func (w *Writer) DetachFile() (*os.File, error) {
+ w.mu.Lock()
+ defer w.mu.Unlock()
+ if w.f == nil {
+ return nil, os.ErrClosed
+ }
+ f := w.f
+ w.f = nil
+ return f, nil
+}
+
func (w *Writer) reopen() error {
f, err := os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
diff --git a/apps/streamd/internal/modstore/modstore.go b/apps/streamd/internal/modstore/modstore.go
new file mode 100644
index 0000000..b6acdff
--- /dev/null
+++ b/apps/streamd/internal/modstore/modstore.go
@@ -0,0 +1,650 @@
+// Package modstore keeps provider modules under the streamd data directory.
+// Operators upload release-style zips; agents pull package.zip + module.yaml.
+package modstore
+
+import (
+ "archive/zip"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "sort"
+ "strings"
+ "time"
+)
+
+const (
+ MaxPackageBytes = 100 << 20 // 100 MiB
+ manifestName = "manifest.json"
+ packageName = "package.zip"
+ yamlName = "module.yaml"
+)
+
+var NameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`)
+
+// archDirRe matches .bin/-/ folder names (never a module name).
+var archDirRe = regexp.MustCompile(`^[a-z0-9]+-(amd64|arm64|386|arm)$`)
+
+// Info is one module's metadata for the API and agent sync.
+type Info 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"`
+ UploadedAt string `json:"uploaded_at,omitempty"`
+ YAMLUpdatedAt string `json:"yaml_updated_at,omitempty"`
+}
+
+type Manifest struct {
+ Name string `json:"name"`
+ YAMLSHA256 string `json:"yaml_sha256,omitempty"`
+ PackageSHA256 string `json:"package_sha256,omitempty"`
+ Arches []string `json:"arches,omitempty"`
+ SizeBytes int64 `json:"size_bytes,omitempty"`
+ UploadedAt string `json:"uploaded_at,omitempty"`
+ YAMLUpdatedAt string `json:"yaml_updated_at,omitempty"`
+}
+
+// Store is the on-disk module library under /modules.
+type Store struct {
+ Root string
+}
+
+func New(root string) *Store {
+ return &Store{Root: root}
+}
+
+func (s *Store) modulesDir() string {
+ return s.Root
+}
+
+func (s *Store) modDir(name string) string {
+ return filepath.Join(s.Root, name)
+}
+
+func (s *Store) Ensure() error {
+ return os.MkdirAll(s.Root, 0o755)
+}
+
+// List returns every module directory under the store.
+func (s *Store) List() ([]Info, error) {
+ ents, err := os.ReadDir(s.Root)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return []Info{}, nil
+ }
+ return nil, err
+ }
+ out := make([]Info, 0, len(ents))
+ for _, e := range ents {
+ if !e.IsDir() || strings.HasPrefix(e.Name(), ".") {
+ continue
+ }
+ if !NameRe.MatchString(e.Name()) {
+ continue
+ }
+ out = append(out, s.Info(e.Name()))
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
+ return out, nil
+}
+
+// Info loads manifest + checks for yaml/package files.
+func (s *Store) Info(name string) Info {
+ info := Info{Name: name}
+ if !NameRe.MatchString(name) {
+ return info
+ }
+ dir := s.modDir(name)
+ m, err := s.readManifest(dir)
+ if err == nil {
+ info.YAMLSHA256 = m.YAMLSHA256
+ info.PackageSHA256 = m.PackageSHA256
+ info.Arches = append([]string(nil), m.Arches...)
+ info.SizeBytes = m.SizeBytes
+ info.UploadedAt = m.UploadedAt
+ info.YAMLUpdatedAt = m.YAMLUpdatedAt
+ info.HasYAML = m.YAMLSHA256 != ""
+ info.HasPackage = m.PackageSHA256 != ""
+ }
+ // Prefer live file hashes when present so a hand-edited yaml still shows.
+ if b, err := os.ReadFile(filepath.Join(dir, yamlName)); err == nil {
+ info.HasYAML = true
+ sum := sha256.Sum256(b)
+ info.YAMLSHA256 = hex.EncodeToString(sum[:])
+ }
+ if st, err := os.Stat(filepath.Join(dir, packageName)); err == nil && !st.IsDir() {
+ info.HasPackage = true
+ if info.PackageSHA256 == "" {
+ if sum, err := fileSHA256(filepath.Join(dir, packageName)); err == nil {
+ info.PackageSHA256 = sum
+ }
+ }
+ if info.SizeBytes == 0 {
+ info.SizeBytes = st.Size()
+ }
+ }
+ return info
+}
+
+// ReadYAML returns module.yaml bytes.
+func (s *Store) ReadYAML(name string) ([]byte, error) {
+ if !NameRe.MatchString(name) {
+ return nil, fmt.Errorf("invalid module name")
+ }
+ b, err := os.ReadFile(filepath.Join(s.modDir(name), yamlName))
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, fmt.Errorf("module %s: no module.yaml", name)
+ }
+ return nil, err
+ }
+ return b, nil
+}
+
+// WriteYAML atomically replaces module.yaml and updates the manifest.
+func (s *Store) WriteYAML(name string, yamlBytes []byte) (Info, error) {
+ if !NameRe.MatchString(name) {
+ return Info{}, fmt.Errorf("invalid module name")
+ }
+ if len(strings.TrimSpace(string(yamlBytes))) == 0 {
+ return Info{}, fmt.Errorf("empty module.yaml")
+ }
+ dir := s.modDir(name)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ return Info{}, err
+ }
+ dest := filepath.Join(dir, yamlName)
+ if err := atomicWrite(dest, yamlBytes, 0o644); err != nil {
+ return Info{}, err
+ }
+ sum := sha256.Sum256(yamlBytes)
+ now := time.Now().UTC().Format(time.RFC3339)
+ m, _ := s.readManifest(dir)
+ m.Name = name
+ m.YAMLSHA256 = hex.EncodeToString(sum[:])
+ m.YAMLUpdatedAt = now
+ if m.UploadedAt == "" {
+ m.UploadedAt = now
+ }
+ if err := s.writeManifest(dir, m); err != nil {
+ return Info{}, err
+ }
+ return s.Info(name), nil
+}
+
+// OpenPackage returns a ReadCloser for package.zip plus size.
+func (s *Store) OpenPackage(name string) (*os.File, int64, error) {
+ if !NameRe.MatchString(name) {
+ return nil, 0, fmt.Errorf("invalid module name")
+ }
+ path := filepath.Join(s.modDir(name), packageName)
+ f, err := os.Open(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, 0, fmt.Errorf("module %s: no package.zip", name)
+ }
+ return nil, 0, err
+ }
+ st, err := f.Stat()
+ if err != nil {
+ _ = f.Close()
+ return nil, 0, err
+ }
+ return f, st.Size(), nil
+}
+
+// Delete removes the module directory.
+func (s *Store) Delete(name string) error {
+ if !NameRe.MatchString(name) {
+ return fmt.Errorf("invalid module name")
+ }
+ dir := s.modDir(name)
+ if _, err := os.Stat(dir); err != nil {
+ if os.IsNotExist(err) {
+ return fmt.Errorf("module %s not found", name)
+ }
+ return err
+ }
+ return os.RemoveAll(dir)
+}
+
+// InstallZip stores zipBytes as package.zip, extracts into the module dir,
+// promotes the host-arch binary, and writes the manifest.
+// nameHint may be empty; the zip layout is used to infer the name.
+func (s *Store) InstallZip(zipBytes []byte, nameHint string) (Info, error) {
+ if len(zipBytes) == 0 {
+ return Info{}, fmt.Errorf("empty zip")
+ }
+ if int64(len(zipBytes)) > MaxPackageBytes {
+ return Info{}, fmt.Errorf("zip exceeds %d byte limit", MaxPackageBytes)
+ }
+
+ name, entries, err := inspectZip(zipBytes, nameHint)
+ if err != nil {
+ return Info{}, err
+ }
+ if !NameRe.MatchString(name) {
+ return Info{}, fmt.Errorf("invalid module name %q", name)
+ }
+
+ if err := s.Ensure(); err != nil {
+ return Info{}, err
+ }
+ dir := s.modDir(name)
+ tmpDir, err := os.MkdirTemp(s.Root, "."+name+".tmp-*")
+ if err != nil {
+ return Info{}, err
+ }
+ defer os.RemoveAll(tmpDir)
+
+ if err := extractZipEntries(zipBytes, entries, tmpDir); err != nil {
+ return Info{}, err
+ }
+ if err := promoteHostBinary(tmpDir, name); err != nil {
+ return Info{}, err
+ }
+ yamlPath := filepath.Join(tmpDir, yamlName)
+ if _, err := os.Stat(yamlPath); err != nil {
+ return Info{}, fmt.Errorf("zip missing module.yaml")
+ }
+ arches := detectArches(tmpDir, name)
+ pkgSum := sha256.Sum256(zipBytes)
+ yamlRaw, err := os.ReadFile(yamlPath)
+ if err != nil {
+ return Info{}, err
+ }
+ yamlSum := sha256.Sum256(yamlRaw)
+ now := time.Now().UTC().Format(time.RFC3339)
+ m := Manifest{
+ Name: name,
+ YAMLSHA256: hex.EncodeToString(yamlSum[:]),
+ PackageSHA256: hex.EncodeToString(pkgSum[:]),
+ Arches: arches,
+ SizeBytes: int64(len(zipBytes)),
+ UploadedAt: now,
+ YAMLUpdatedAt: now,
+ }
+ if err := s.writeManifest(tmpDir, m); err != nil {
+ return Info{}, err
+ }
+ if err := atomicWrite(filepath.Join(tmpDir, packageName), zipBytes, 0o644); err != nil {
+ return Info{}, err
+ }
+
+ // Replace the live module dir.
+ backup := dir + ".bak"
+ _ = os.RemoveAll(backup)
+ if _, err := os.Stat(dir); err == nil {
+ if err := os.Rename(dir, backup); err != nil {
+ return Info{}, err
+ }
+ }
+ if err := os.Rename(tmpDir, dir); err != nil {
+ _ = os.Rename(backup, dir)
+ return Info{}, err
+ }
+ _ = os.RemoveAll(backup)
+ return s.Info(name), nil
+}
+
+type zipEntry struct {
+ // Rel is the path relative to the module root inside the zip (forward slashes).
+ Rel string
+ File *zip.File
+}
+
+func inspectZip(zipBytes []byte, nameHint string) (name string, entries []zipEntry, err error) {
+ zr, err := zip.NewReader(newBytesReaderAt(zipBytes), int64(len(zipBytes)))
+ if err != nil {
+ return "", nil, fmt.Errorf("open zip: %w", err)
+ }
+ return inspectZipReader(zr, nameHint)
+}
+
+type bytesReaderAt struct{ b []byte }
+
+func newBytesReaderAt(b []byte) *bytesReaderAt { return &bytesReaderAt{b: b} }
+
+func (r *bytesReaderAt) ReadAt(p []byte, off int64) (int, error) {
+ if off < 0 {
+ return 0, errors.New("negative offset")
+ }
+ if off >= int64(len(r.b)) {
+ return 0, io.EOF
+ }
+ n := copy(p, r.b[off:])
+ if n < len(p) {
+ return n, io.EOF
+ }
+ return n, nil
+}
+
+func inspectZipReader(zr *zip.Reader, nameHint string) (string, []zipEntry, error) {
+ hint := strings.TrimSpace(nameHint)
+ if hint != "" && !NameRe.MatchString(hint) {
+ return "", nil, fmt.Errorf("invalid module name %q", hint)
+ }
+
+ prefix := ""
+ topDirs := map[string]struct{}{}
+ hasRootFile := false
+
+ for _, f := range zr.File {
+ name := strings.ReplaceAll(f.Name, "\\", "/")
+ name = strings.TrimPrefix(name, "./")
+ if name == "" || strings.HasPrefix(name, "__MACOSX/") || strings.HasSuffix(name, ".DS_Store") {
+ continue
+ }
+ parts := strings.Split(name, "/")
+ if len(parts) > 0 && parts[0] != "" {
+ if f.FileInfo().IsDir() || len(parts) > 1 {
+ topDirs[parts[0]] = struct{}{}
+ }
+ if len(parts) == 1 && !f.FileInfo().IsDir() {
+ hasRootFile = true
+ }
+ }
+ }
+
+ switch {
+ case hint != "":
+ prefix = ""
+ // If every entry is under hint/, strip it.
+ allUnder := true
+ for _, f := range zr.File {
+ n := strings.ReplaceAll(f.Name, "\\", "/")
+ n = strings.TrimPrefix(n, "./")
+ if n == "" || strings.HasPrefix(n, "__MACOSX/") {
+ continue
+ }
+ if n != hint && !strings.HasPrefix(n, hint+"/") {
+ allUnder = false
+ break
+ }
+ }
+ if allUnder {
+ prefix = hint + "/"
+ }
+ case hasRootFile:
+ // Flat zip: module.yaml at root. Name must be provided or inferred from binary.
+ prefix = ""
+ case len(topDirs) == 1:
+ for d := range topDirs {
+ prefix = d + "/"
+ if hint == "" {
+ hint = d
+ }
+ }
+ default:
+ return "", nil, fmt.Errorf("cannot infer module name from zip; pass name= or use a single top-level folder")
+ }
+
+ if hint == "" {
+ hint = inferNameFromBinEntries(zr, prefix)
+ }
+ if hint == "" {
+ return "", nil, fmt.Errorf("cannot infer module name from zip; pass name=")
+ }
+ if !NameRe.MatchString(hint) {
+ return "", nil, fmt.Errorf("invalid module name %q", hint)
+ }
+
+ var entries []zipEntry
+ for _, f := range zr.File {
+ n := strings.ReplaceAll(f.Name, "\\", "/")
+ n = strings.TrimPrefix(n, "./")
+ if n == "" || strings.HasPrefix(n, "__MACOSX/") || strings.HasSuffix(n, ".DS_Store") {
+ continue
+ }
+ rel := n
+ if prefix != "" {
+ if !strings.HasPrefix(n, prefix) {
+ continue
+ }
+ rel = strings.TrimPrefix(n, prefix)
+ }
+ if rel == "" {
+ continue
+ }
+ if strings.Contains(rel, "..") {
+ return "", nil, fmt.Errorf("zip slip: %s", f.Name)
+ }
+ entries = append(entries, zipEntry{Rel: rel, File: f})
+ }
+ if len(entries) == 0 {
+ return "", nil, fmt.Errorf("zip has no files for module %s", hint)
+ }
+ return hint, entries, nil
+}
+
+func extractZipEntries(zipBytes []byte, entries []zipEntry, destDir string) error {
+ _ = zipBytes // entries already hold openable *zip.File from the same buffer
+ for _, e := range entries {
+ target := filepath.Join(destDir, filepath.FromSlash(e.Rel))
+ // Zip-slip: ensure target stays under destDir.
+ if !isUnder(destDir, target) {
+ return fmt.Errorf("zip slip: %s", e.Rel)
+ }
+ if e.File.FileInfo().IsDir() || strings.HasSuffix(e.Rel, "/") {
+ 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 := e.File.Open()
+ if err != nil {
+ return err
+ }
+ mode := e.File.Mode()
+ if mode&0o111 != 0 {
+ mode = 0o755
+ } else {
+ mode = 0o644
+ }
+ err = copyToFile(target, rc, mode)
+ _ = rc.Close()
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// inferNameFromBinEntries picks the module binary basename from
+// .bin//[.exe] or .bin/[.exe]. Directory entries and
+// arch folder names (linux-amd64, darwin-arm64, …) are skipped — those used
+// to be mistaken for the module name on flat release zips.
+func inferNameFromBinEntries(zr *zip.Reader, prefix string) string {
+ var fallback string
+ for _, f := range zr.File {
+ if f.FileInfo().IsDir() {
+ continue
+ }
+ n := strings.ReplaceAll(f.Name, "\\", "/")
+ n = strings.TrimPrefix(n, "./")
+ if prefix != "" {
+ if !strings.HasPrefix(n, prefix) {
+ continue
+ }
+ n = strings.TrimPrefix(n, prefix)
+ }
+ n = strings.TrimSuffix(n, "/")
+ if !strings.HasPrefix(n, ".bin/") {
+ continue
+ }
+ rel := strings.TrimPrefix(n, ".bin/")
+ parts := strings.Split(rel, "/")
+ base := parts[len(parts)-1]
+ base = strings.TrimSuffix(base, ".exe")
+ if !NameRe.MatchString(base) || archDirRe.MatchString(base) {
+ continue
+ }
+ // Prefer .bin//
+ if len(parts) >= 2 && archDirRe.MatchString(parts[0]) {
+ return base
+ }
+ // .bin/
+ if len(parts) == 1 && fallback == "" {
+ fallback = base
+ }
+ }
+ return fallback
+}
+
+func isUnder(root, path string) bool {
+ absRoot, err1 := filepath.Abs(root)
+ absPath, err2 := filepath.Abs(path)
+ if err1 != nil || err2 != nil {
+ return false
+ }
+ rel, err := filepath.Rel(absRoot, absPath)
+ if err != nil {
+ return false
+ }
+ return rel == "." || (!strings.HasPrefix(rel, "..") && !filepath.IsAbs(rel))
+}
+
+func copyToFile(dest string, r io.Reader, mode os.FileMode) error {
+ tmp := dest + ".partial"
+ f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode)
+ if err != nil {
+ return err
+ }
+ _, copyErr := io.Copy(f, r)
+ closeErr := f.Close()
+ if copyErr != nil {
+ _ = os.Remove(tmp)
+ return copyErr
+ }
+ if closeErr != nil {
+ _ = os.Remove(tmp)
+ return closeErr
+ }
+ _ = os.Remove(dest)
+ return os.Rename(tmp, dest)
+}
+
+func promoteHostBinary(modDir, name string) error {
+ want := name
+ if runtime.GOOS == "windows" {
+ want += ".exe"
+ }
+ dest := filepath.Join(modDir, ".bin", want)
+ if fileExists(dest) {
+ return nil
+ }
+ archDir := filepath.Join(modDir, ".bin", runtime.GOOS+"-"+runtime.GOARCH)
+ src := filepath.Join(archDir, want)
+ if !fileExists(src) {
+ // Soft: describe may fail later; zip install still succeeds.
+ return nil
+ }
+ if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {
+ return err
+ }
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer in.Close()
+ return copyToFile(dest, in, 0o755)
+}
+
+func detectArches(modDir, name string) []string {
+ binRoot := filepath.Join(modDir, ".bin")
+ ents, err := os.ReadDir(binRoot)
+ if err != nil {
+ return nil
+ }
+ seen := map[string]struct{}{}
+ var arches []string
+ add := func(a string) {
+ if _, ok := seen[a]; ok {
+ return
+ }
+ seen[a] = struct{}{}
+ arches = append(arches, a)
+ }
+ for _, e := range ents {
+ if e.IsDir() {
+ sub := e.Name() // e.g. windows-amd64
+ if strings.Contains(sub, "-") {
+ add(sub)
+ }
+ continue
+ }
+ base := strings.TrimSuffix(e.Name(), ".exe")
+ if base == name {
+ add(runtime.GOOS + "-" + runtime.GOARCH)
+ }
+ }
+ sort.Strings(arches)
+ return arches
+}
+
+func (s *Store) readManifest(dir string) (Manifest, error) {
+ var m Manifest
+ b, err := os.ReadFile(filepath.Join(dir, manifestName))
+ if err != nil {
+ return m, err
+ }
+ if err := json.Unmarshal(b, &m); err != nil {
+ return m, err
+ }
+ return m, nil
+}
+
+func (s *Store) writeManifest(dir string, m Manifest) error {
+ b, err := json.MarshalIndent(m, "", " ")
+ if err != nil {
+ return err
+ }
+ b = append(b, '\n')
+ return atomicWrite(filepath.Join(dir, manifestName), b, 0o644)
+}
+
+func atomicWrite(path string, data []byte, mode os.FileMode) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ 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 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 fileExists(p string) bool {
+ st, err := os.Stat(p)
+ return err == nil && !st.IsDir()
+}
diff --git a/apps/streamd/internal/modstore/modstore_test.go b/apps/streamd/internal/modstore/modstore_test.go
new file mode 100644
index 0000000..bcd841c
--- /dev/null
+++ b/apps/streamd/internal/modstore/modstore_test.go
@@ -0,0 +1,170 @@
+package modstore
+
+import (
+ "archive/zip"
+ "bytes"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+func makeZip(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 TestInstallZipInfersNameNotArchDir(t *testing.T) {
+ // Flat release zips list .bin/darwin-arm64/ before the binary; that arch
+ // folder must not become the module name.
+ root := t.TempDir()
+ s := New(root)
+ zipBytes := makeZip(t, map[string][]byte{
+ "module.yaml": []byte("package: air.RTE\nchannels:\n rteone: {label: One}\n"),
+ ".bin/": nil, // directory markers via path only
+ ".bin/darwin-arm64/rte": []byte("mac-bin"),
+ ".bin/linux-amd64/rte": []byte("linux-bin"),
+ ".bin/windows-amd64/rte.exe": []byte("win-bin"),
+ })
+ info, err := s.InstallZip(zipBytes, "")
+ if err != nil {
+ t.Fatalf("InstallZip: %v", err)
+ }
+ if info.Name != "rte" {
+ t.Fatalf("inferred name=%q want rte", info.Name)
+ }
+}
+
+func TestInstallZipFlatAndYAMLOnly(t *testing.T) {
+ root := t.TempDir()
+ s := New(root)
+
+ arch := runtime.GOOS + "-" + runtime.GOARCH
+ binName := "demo"
+ if runtime.GOOS == "windows" {
+ binName += ".exe"
+ }
+ zipBytes := makeZip(t, map[string][]byte{
+ "module.yaml": []byte("package: com.example\nchannels: {}\n"),
+ ".bin/" + arch + "/" + binName: []byte("fake-binary"),
+ ".bin/linux-amd64/demo": []byte("linux-bin"),
+ })
+
+ info, err := s.InstallZip(zipBytes, "demo")
+ if err != nil {
+ t.Fatalf("InstallZip: %v", err)
+ }
+ if info.Name != "demo" || !info.HasYAML || !info.HasPackage {
+ t.Fatalf("info = %+v", info)
+ }
+ if info.PackageSHA256 == "" || info.YAMLSHA256 == "" {
+ t.Fatalf("missing hashes: %+v", info)
+ }
+ pkgHash := info.PackageSHA256
+ yamlHash := info.YAMLSHA256
+
+ // Host binary should be promoted.
+ promoted := filepath.Join(root, "demo", ".bin", binName)
+ if !fileExists(promoted) {
+ t.Fatalf("expected promoted binary at %s", promoted)
+ }
+
+ // YAML-only update must not change package hash.
+ info2, err := s.WriteYAML("demo", []byte("package: com.example\nchannels:\n one: {label: One}\n"))
+ if err != nil {
+ t.Fatalf("WriteYAML: %v", err)
+ }
+ if info2.PackageSHA256 != pkgHash {
+ t.Fatalf("package hash changed on yaml edit: %s -> %s", pkgHash, info2.PackageSHA256)
+ }
+ if info2.YAMLSHA256 == yamlHash {
+ t.Fatal("yaml hash should change after edit")
+ }
+
+ raw, err := s.ReadYAML("demo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(raw), "one:") {
+ t.Fatalf("yaml not updated: %s", raw)
+ }
+
+ f, size, err := s.OpenPackage("demo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ if size != int64(len(zipBytes)) {
+ t.Fatalf("package size %d want %d", size, len(zipBytes))
+ }
+}
+
+func TestInstallZipTopLevelFolder(t *testing.T) {
+ root := t.TempDir()
+ s := New(root)
+ zipBytes := makeZip(t, map[string][]byte{
+ "bbc/module.yaml": []byte("package: bbc.iplayer.android\n"),
+ "bbc/.bin/linux-amd64/bbc": []byte("bin"),
+ "bbc/.bin/windows-amd64/bbc.exe": []byte("winbin"),
+ })
+ info, err := s.InstallZip(zipBytes, "")
+ if err != nil {
+ t.Fatalf("InstallZip: %v", err)
+ }
+ if info.Name != "bbc" {
+ t.Fatalf("name=%q", info.Name)
+ }
+ list, err := s.List()
+ if err != nil || len(list) != 1 || list[0].Name != "bbc" {
+ t.Fatalf("list=%v err=%v", list, err)
+ }
+}
+
+func TestZipSlipRejected(t *testing.T) {
+ root := t.TempDir()
+ s := New(root)
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ w, err := zw.Create("../evil.yaml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _ = w.Write([]byte("x"))
+ _ = zw.Close()
+ _, err = s.InstallZip(buf.Bytes(), "demo")
+ if err == nil {
+ t.Fatal("expected zip-slip error")
+ }
+}
+
+func TestDelete(t *testing.T) {
+ root := t.TempDir()
+ s := New(root)
+ zipBytes := makeZip(t, map[string][]byte{
+ "module.yaml": []byte("package: x\n"),
+ })
+ if _, err := s.InstallZip(zipBytes, "xmod"); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.Delete("xmod"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(filepath.Join(root, "xmod")); !os.IsNotExist(err) {
+ t.Fatalf("dir still present: %v", err)
+ }
+}
diff --git a/apps/streamd/internal/scheduler/scheduler.go b/apps/streamd/internal/scheduler/scheduler.go
index c8c40cf..fa0b2e2 100644
--- a/apps/streamd/internal/scheduler/scheduler.go
+++ b/apps/streamd/internal/scheduler/scheduler.go
@@ -6,7 +6,7 @@ import (
"log/slog"
"time"
- "drmdecryption/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/db"
)
// Supervisor is the subset of the media supervisor the scheduler needs.
diff --git a/apps/streamd/internal/supervisor/appdefaults.go b/apps/streamd/internal/supervisor/appdefaults.go
index 24725bd..dd0440a 100644
--- a/apps/streamd/internal/supervisor/appdefaults.go
+++ b/apps/streamd/internal/supervisor/appdefaults.go
@@ -3,10 +3,10 @@ package supervisor
import (
"strings"
- "drmdecryption/app"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/modhost"
- "drmdecryption/repo"
+ "streamd/app"
+ "streamd/apps/streamd/internal/db"
+ "streamd/modhost"
+ "streamd/repo"
)
// streamSettings are the downloader and packager knobs for one stream. They
diff --git a/apps/streamd/internal/supervisor/appdefaults_test.go b/apps/streamd/internal/supervisor/appdefaults_test.go
index f41eb39..ee1feca 100644
--- a/apps/streamd/internal/supervisor/appdefaults_test.go
+++ b/apps/streamd/internal/supervisor/appdefaults_test.go
@@ -3,11 +3,11 @@ package supervisor
import (
"testing"
- "drmdecryption/adb"
- "drmdecryption/app"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/capture"
- "drmdecryption/mpd"
+ "streamd/adb"
+ "streamd/app"
+ "streamd/apps/streamd/internal/db"
+ "streamd/capture"
+ "streamd/mpd"
)
// fakeApp stands in for a compiled-in app module: the supervisor must take its
diff --git a/apps/streamd/internal/supervisor/ffmpeg_integration_test.go b/apps/streamd/internal/supervisor/ffmpeg_integration_test.go
index dcbcf8b..c333c44 100644
--- a/apps/streamd/internal/supervisor/ffmpeg_integration_test.go
+++ b/apps/streamd/internal/supervisor/ffmpeg_integration_test.go
@@ -10,7 +10,7 @@ import (
"testing"
"time"
- "drmdecryption/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/db"
)
// These tests run the real ffmpeg against the real generated command line.
diff --git a/apps/streamd/internal/supervisor/media.go b/apps/streamd/internal/supervisor/media.go
index cc14d53..8f7e8e8 100644
--- a/apps/streamd/internal/supervisor/media.go
+++ b/apps/streamd/internal/supervisor/media.go
@@ -8,16 +8,15 @@ import (
"os"
"os/exec"
"path/filepath"
- "runtime"
"strconv"
"strings"
"sync"
"time"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/apps/streamd/internal/logfile"
- "drmdecryption/apps/streamd/internal/tsfanout"
- "drmdecryption/mpd"
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/logfile"
+ "streamd/apps/streamd/internal/tsfanout"
+ "streamd/mpd"
)
// Media runs N_m3u8DL-RE plus one ffmpeg packager per variant, publishing into
@@ -37,12 +36,19 @@ type Media struct {
// ViewersFn reports the live client count for a stream, for the metrics
// series. Optional.
ViewersFn func(streamName string) int
+ // ProxyResolver resolves stream.Proxy / stream.Egress to a SOCKS/HTTP URL.
+ ProxyResolver ProxyResolver
mu sync.Mutex
procs map[int64]*streamProc
stopMon chan struct{}
}
+// ProxyResolver turns a stream row into an origin-fetch proxy URL.
+type ProxyResolver interface {
+ ResolveProxy(st db.Stream) (string, error)
+}
+
// Notifier is the subset of the websocket hub the supervisor needs.
type Notifier interface {
NotifyRuntime(name, health string)
@@ -55,11 +61,13 @@ type streamProc struct {
nre *exec.Cmd
ffmpeg *exec.Cmd
started time.Time
+ sessionID int64 // stream_sessions row opened when NRE starts
workDir string
wwwDir string
tsPath string
hlsIndex string
- nreLog *logfile.Writer
+ nreLogFile *os.File // per-stream NRE log (banner + append)
+ nrePTY io.Closer // Linux PTY master; nil on Windows / fallback
ffOutLog *logfile.Writer
ffErrLog *logfile.Writer
stopping bool
@@ -82,15 +90,16 @@ type streamProc struct {
// Options for constructing the media supervisor.
type Options struct {
- Store *db.Store
- DataDir string
- NRE string
- FFmpeg string
- MP4Decrypt string
- Log *slog.Logger
- Fanout *tsfanout.Set
- Notifier Notifier
- ViewersFn func(streamName string) int
+ Store *db.Store
+ DataDir string
+ NRE string
+ FFmpeg string
+ MP4Decrypt string
+ Log *slog.Logger
+ Fanout *tsfanout.Set
+ Notifier Notifier
+ ViewersFn func(streamName string) int
+ ProxyResolver ProxyResolver
}
func NewMedia(opt Options) *Media {
@@ -103,17 +112,18 @@ func NewMedia(opt Options) *Media {
fan = tsfanout.NewSet(tsfanout.DefaultBufferBytes)
}
m := &Media{
- Store: opt.Store,
- DataDir: opt.DataDir,
- NRE: opt.NRE,
- FFmpeg: opt.FFmpeg,
- MP4Decrypt: opt.MP4Decrypt,
- Log: lg,
- Fanout: fan,
- Notifier: opt.Notifier,
- ViewersFn: opt.ViewersFn,
- procs: map[int64]*streamProc{},
- stopMon: make(chan struct{}),
+ Store: opt.Store,
+ DataDir: opt.DataDir,
+ NRE: opt.NRE,
+ FFmpeg: opt.FFmpeg,
+ MP4Decrypt: opt.MP4Decrypt,
+ Log: lg,
+ Fanout: fan,
+ Notifier: opt.Notifier,
+ ViewersFn: opt.ViewersFn,
+ ProxyResolver: opt.ProxyResolver,
+ procs: map[int64]*streamProc{},
+ stopMon: make(chan struct{}),
}
go m.monitorLoop()
return m
@@ -143,6 +153,13 @@ func (m *Media) Running(id int64) bool {
func (m *Media) logsDir() string { return filepath.Join(m.DataDir, "logs") }
+func (m *Media) effectiveProxy(st db.Stream) (string, error) {
+ if m.ProxyResolver != nil {
+ return m.ProxyResolver.ResolveProxy(st)
+ }
+ return strings.TrimSpace(st.Proxy), nil
+}
+
func (m *Media) Start(id int64) error {
st, err := m.Store.GetStream(id)
if err != nil {
@@ -203,12 +220,17 @@ func (m *Media) Start(id int64) error {
saveName := st.Name
headers := headerMap(st.HeadersJSON)
cfg := settingsFor(st, m.Store.GlobalPackagerSettings())
+ originProxy, err := m.effectiveProxy(st)
+ if err != nil {
+ m.fail(id, st.Name, "egress: "+err.Error())
+ return err
+ }
manifestURL := st.MPD
var mpdProxy *mpd.LocalServer
// The rewriter is named by the stream row or its app module and looked up in
// the mpd registry, so streamd needs no knowledge of any provider.
if rw, needed := mpd.Lookup(cfg.Rewriter); needed && strings.TrimSpace(st.MPD) != "" && !cfg.IsHLS {
- srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, st.Proxy)
+ srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, originProxy)
if err != nil {
m.fail(id, st.Name, "mpd rewrite server: "+err.Error())
return err
@@ -236,7 +258,10 @@ func (m *Media) Start(id int64) error {
"--tmp-dir", nreTmp,
"--no-ansi-color",
"--log-level", "ERROR",
- "-ss", "0",
+ // Drop every subtitle track. Live pipe-mux to TS does not need them, and
+ // an extra Spectre progress row makes redirected-console crashes more
+ // likely (NRE forces ANSI UI when stdout is a log file).
+ "-ds", "for=all",
}
if hasKeys {
// Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so
@@ -246,7 +271,7 @@ func (m *Media) Start(id int64) error {
"--mp4-real-time-decryption",
)
}
- if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
+ if proxy := strings.TrimSpace(originProxy); proxy != "" {
// NRE prefers --custom-proxy over the system proxy when both are set.
// The proxy may carry credentials, so it is not logged.
nreArgs = append(nreArgs, "--custom-proxy", proxy)
@@ -273,23 +298,24 @@ func (m *Media) Start(id int64) error {
}
}
- // A rotating log opened with a start banner, rather than truncated. The
- // previous run's output is exactly what you need when working out why
- // this run is happening.
- nreLog, err := logfile.OpenWithBanner(
+ // Banner + rotate-on-open keep prior runs readable. On Linux, NRE runs under
+ // a PTY (see startNRELogged): plain file/pipe redirects force Spectre live UI
+ // with WindowWidth 0 and crash ProgressRefreshThread.
+ nreLogFile, err := logfile.OpenCmdLog(
filepath.Join(m.logsDir(), st.Name+"-nre.log"),
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "nre")
if err != nil {
return err
}
nreCmd := exec.Command(m.NRE, nreArgs...)
- nreCmd.Stdout = nreLog
- nreCmd.Stderr = nreLog
hideWindow(nreCmd)
// NRE (v0.6) resolves mp4decrypt via PATH / sibling of its .exe, and often
// ignores --decryption-binary-path for MP4DECRYPT. Match legacy: prepend
// dirs and best-effort copy beside NRE.
nreEnv := os.Environ()
+ nreEnv = setEnvDefault(nreEnv, "COLUMNS", "120")
+ nreEnv = setEnvDefault(nreEnv, "LINES", "40")
+ nreEnv = setEnvDefault(nreEnv, "TERM", "xterm")
pathPrepend := []string{}
if m.MP4Decrypt != "" {
pathPrepend = append(pathPrepend, filepath.Dir(m.MP4Decrypt))
@@ -306,27 +332,37 @@ func (m *Media) Start(id int64) error {
nreEnv = prependPathEnv(nreEnv, strings.Join(pathPrepend, sep))
}
nreCmd.Env = nreEnv
- if err := nreCmd.Start(); err != nil {
- _ = nreLog.Close()
+ nrePTY, keepLogFD, err := startNRELogged(nreCmd, nreLogFile)
+ if err != nil {
+ if keepLogFD {
+ _ = nreLogFile.Close()
+ }
if mpdProxy != nil {
mpdProxy.Close()
}
m.fail(id, st.Name, err.Error())
return err
}
+ ownedLog := nreLogFile
+ if !keepLogFD {
+ ownedLog = nil
+ }
m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid)
+ sessionID, _ := m.Store.OpenSession(id)
sp := &streamProc{
- id: id,
- name: st.Name,
- nre: nreCmd,
- started: time.Now(),
- workDir: workDir,
- wwwDir: wwwDir,
- tsPath: tsPath,
- hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
- nreLog: nreLog,
- mpdProxy: mpdProxy,
+ id: id,
+ name: st.Name,
+ nre: nreCmd,
+ started: time.Now(),
+ sessionID: sessionID,
+ workDir: workDir,
+ wwwDir: wwwDir,
+ tsPath: tsPath,
+ hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
+ nreLogFile: ownedLog,
+ nrePTY: nrePTY,
+ mpdProxy: mpdProxy,
variantSpecs: variantSpecs,
outputSpecs: outputSpecs,
@@ -411,12 +447,13 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
_ = m.Store.SetRuntime(sp.id, db.RuntimePatch{
Health: "down",
PlayPath: "/hls/" + sp.name + "/index.m3u8",
- LastError: "NRE exited before TS was ready — see logs/" + sp.name + "-nre.log",
+ LastError: "NRE exited before TS was ready — see data/logs/" + sp.name + "-nre.log",
})
m.Store.AddEvent(db.StreamEvent{
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
- Message: "downloader exited before any media arrived — see logs/" + sp.name + "-nre.log",
+ Message: "downloader exited before any media arrived — see data/logs/" + sp.name + "-nre.log",
})
+ m.closeSession(sp, db.SessionNREExit, "down")
m.cleanupProc(sp.id)
return
}
@@ -568,9 +605,11 @@ func (m *Media) Stop(id int64) error {
if st.Name != "" {
name = st.Name
}
+ _ = m.Store.CloseOpenSessions(id, db.SessionStopped, "stopped")
_ = m.Store.SetRuntime(id, db.RuntimePatch{Health: "stopped", PlayPath: "/hls/" + name + "/index.m3u8"})
return nil
}
+ m.closeSession(sp, db.SessionStopped, "stopped")
m.stopAllVariants(sp)
nrePID, ffPID := 0, 0
if sp.ffmpeg != nil && sp.ffmpeg.Process != nil {
@@ -603,6 +642,15 @@ func (m *Media) Stop(id int64) error {
return nil
}
+// closeSession ends the open stream_sessions row for this process, if any.
+func (m *Media) closeSession(sp *streamProc, reason, health string) {
+ if sp == nil || sp.sessionID == 0 {
+ return
+ }
+ _ = m.Store.CloseSession(sp.sessionID, reason, health)
+ sp.sessionID = 0
+}
+
func (m *Media) Restart(id int64) error {
m.Log.Info("hard restart", "stream_id", id)
_ = m.Stop(id)
@@ -622,7 +670,15 @@ func (m *Media) cleanupProc(id int64) {
if !ok {
return
}
- for _, w := range []*logfile.Writer{sp.nreLog, sp.ffOutLog, sp.ffErrLog} {
+ if sp.nrePTY != nil {
+ _ = sp.nrePTY.Close()
+ sp.nrePTY = nil
+ }
+ if sp.nreLogFile != nil {
+ _ = sp.nreLogFile.Close()
+ sp.nreLogFile = nil
+ }
+ for _, w := range []*logfile.Writer{sp.ffOutLog, sp.ffErrLog} {
if w != nil {
_ = w.Close()
}
@@ -674,13 +730,14 @@ func (m *Media) refreshHealth(id int64) {
if nreDead {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down", PID: 0, PlayPath: playPath, UptimeS: uptime,
- LastError: "NRE process exited — see logs/" + sp.name + "-nre.log",
+ LastError: "NRE process exited — see data/logs/" + sp.name + "-nre.log",
})
m.Store.AddEvent(db.StreamEvent{
StreamID: id, Kind: db.EventCrashed, Severity: db.SevError,
- Message: fmt.Sprintf("downloader exited after %.0fs — see logs/%s-nre.log", uptime, sp.name),
+ Message: fmt.Sprintf("downloader exited after %.0fs — see data/logs/%s-nre.log", uptime, sp.name),
})
m.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime))
+ m.closeSession(sp, db.SessionNREExit, "down")
m.report(sp, "down")
m.cleanupProc(id)
return
@@ -887,11 +944,7 @@ func killProcess(cmd *exec.Cmd) error {
if cmd == nil || cmd.Process == nil {
return nil
}
- pid := cmd.Process.Pid
- if runtime.GOOS == "windows" {
- return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
- }
- return cmd.Process.Kill()
+ return killProcessTree(cmd)
}
func prependPathEnv(env []string, prefix string) []string {
@@ -914,6 +967,20 @@ func prependPathEnv(env []string, prefix string) []string {
return out
}
+// setEnvDefault sets KEY=value when KEY is missing or empty in env.
+func setEnvDefault(env []string, key, value string) []string {
+ prefix := key + "="
+ for i, e := range env {
+ if strings.HasPrefix(e, prefix) {
+ if strings.TrimSpace(e[len(prefix):]) == "" {
+ env[i] = prefix + value
+ }
+ return env
+ }
+ }
+ return append(env, prefix+value)
+}
+
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
diff --git a/apps/streamd/internal/supervisor/outputs.go b/apps/streamd/internal/supervisor/outputs.go
index 12d443f..0a2457e 100644
--- a/apps/streamd/internal/supervisor/outputs.go
+++ b/apps/streamd/internal/supervisor/outputs.go
@@ -6,7 +6,7 @@ import (
"strconv"
"strings"
- "drmdecryption/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/db"
)
// Packager defaults. These were literals in the ffmpeg command line before
diff --git a/apps/streamd/internal/supervisor/outputs_test.go b/apps/streamd/internal/supervisor/outputs_test.go
index 76c4000..c4e6a92 100644
--- a/apps/streamd/internal/supervisor/outputs_test.go
+++ b/apps/streamd/internal/supervisor/outputs_test.go
@@ -4,7 +4,7 @@ import (
"strings"
"testing"
- "drmdecryption/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/db"
)
// quote and backslash as values, so the test source stays readable where it
diff --git a/apps/streamd/internal/supervisor/proc_unix.go b/apps/streamd/internal/supervisor/proc_unix.go
index 266175f..832f76d 100644
--- a/apps/streamd/internal/supervisor/proc_unix.go
+++ b/apps/streamd/internal/supervisor/proc_unix.go
@@ -3,13 +3,27 @@
package supervisor
import (
+ "io"
"os"
"os/exec"
+ "strings"
"syscall"
)
func hideWindow(cmd *exec.Cmd) {}
+func killProcessTree(cmd *exec.Cmd) error {
+ if cmd == nil || cmd.Process == nil {
+ return nil
+ }
+ pid := cmd.Process.Pid
+ // Negative PID signals the process group (script PTY wrapper + NRE).
+ if err := syscall.Kill(-pid, syscall.SIGKILL); err == nil {
+ return nil
+ }
+ return cmd.Process.Kill()
+}
+
func processDead(pid int) bool {
p, err := os.FindProcess(pid)
if err != nil {
@@ -18,3 +32,63 @@ func processDead(pid int) bool {
err = p.Signal(syscall.Signal(0))
return err != nil
}
+
+// startNRELogged starts NRE under a PTY so Spectre.Console sees a real terminal.
+// Plain file/pipe redirects make N_m3u8DL-RE force ANSI UI with WindowWidth 0,
+// which crashes ProgressRefreshThread (ArgumentException/RemoveRange).
+//
+// Uses util-linux `script` when available (PTY + typescript log). Falls back to
+// attaching logFile as Stdout/Stderr. keepLogFD is false when script took over
+// the log path (caller must not Close logFile again).
+func startNRELogged(cmd *exec.Cmd, logFile *os.File) (pty io.Closer, keepLogFD bool, err error) {
+ scriptPath, err := exec.LookPath("script")
+ if err != nil {
+ cmd.Stdout = logFile
+ cmd.Stderr = logFile
+ if err := cmd.Start(); err != nil {
+ return nil, true, err
+ }
+ return nopCloser{}, true, nil
+ }
+
+ logPath := logFile.Name()
+ _ = logFile.Sync()
+ _ = logFile.Close()
+
+ inner := shellJoin(append([]string{cmd.Path}, cmd.Args[1:]...)...)
+ // -q quiet header, -a append (keep prior runs), -f flush so log tails live.
+ wrapped := exec.Command(scriptPath, "-q", "-a", "-f", "-c", inner, logPath)
+ wrapped.Env = cmd.Env
+ wrapped.Dir = cmd.Dir
+ if cmd.SysProcAttr != nil {
+ wrapped.SysProcAttr = cmd.SysProcAttr
+ } else {
+ wrapped.SysProcAttr = &syscall.SysProcAttr{}
+ }
+ // Own process group so Stop can signal the whole tree (script + NRE).
+ wrapped.SysProcAttr.Setpgid = true
+ *cmd = *wrapped
+ if err := cmd.Start(); err != nil {
+ return nil, false, err
+ }
+ return nopCloser{}, false, nil
+}
+
+func shellJoin(argv ...string) string {
+ parts := make([]string, len(argv))
+ for i, a := range argv {
+ parts[i] = shellQuote(a)
+ }
+ return strings.Join(parts, " ")
+}
+
+func shellQuote(s string) string {
+ if s == "" {
+ return "''"
+ }
+ return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
+}
+
+type nopCloser struct{}
+
+func (nopCloser) Close() error { return nil }
diff --git a/apps/streamd/internal/supervisor/proc_windows.go b/apps/streamd/internal/supervisor/proc_windows.go
index 4de3aff..bc95f5a 100644
--- a/apps/streamd/internal/supervisor/proc_windows.go
+++ b/apps/streamd/internal/supervisor/proc_windows.go
@@ -3,8 +3,10 @@
package supervisor
import (
+ "io"
"os"
"os/exec"
+ "strconv"
"syscall"
)
@@ -15,6 +17,29 @@ func hideWindow(cmd *exec.Cmd) {
}
}
+func killProcessTree(cmd *exec.Cmd) error {
+ if cmd == nil || cmd.Process == nil {
+ return nil
+ }
+ pid := cmd.Process.Pid
+ return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
+}
+
+// startNRELogged attaches logFile as Stdout/Stderr. Windows CREATE_NO_WINDOW
+// avoids the Spectre pipe-width crash that hits Linux daemons.
+func startNRELogged(cmd *exec.Cmd, logFile *os.File) (io.Closer, bool, error) {
+ cmd.Stdout = logFile
+ cmd.Stderr = logFile
+ if err := cmd.Start(); err != nil {
+ return nil, true, err
+ }
+ return nopCloser{}, true, nil
+}
+
+type nopCloser struct{}
+
+func (nopCloser) Close() error { return nil }
+
func processDead(pid int) bool {
p, err := os.FindProcess(pid)
if err != nil {
diff --git a/apps/streamd/internal/supervisor/stub.go b/apps/streamd/internal/supervisor/stub.go
index 58eef69..609c0ee 100644
--- a/apps/streamd/internal/supervisor/stub.go
+++ b/apps/streamd/internal/supervisor/stub.go
@@ -5,7 +5,7 @@ import (
"sync"
"time"
- "drmdecryption/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/db"
)
// Stub marks streams as starting/stopped without spawning media workers.
diff --git a/apps/streamd/internal/supervisor/variants.go b/apps/streamd/internal/supervisor/variants.go
index 324786d..ebf925d 100644
--- a/apps/streamd/internal/supervisor/variants.go
+++ b/apps/streamd/internal/supervisor/variants.go
@@ -9,8 +9,8 @@ import (
"sort"
"strings"
- "drmdecryption/apps/streamd/internal/db"
- "drmdecryption/apps/streamd/internal/logfile"
+ "streamd/apps/streamd/internal/db"
+ "streamd/apps/streamd/internal/logfile"
)
type variantProc struct {
diff --git a/apps/streamd/internal/ui/index.html b/apps/streamd/internal/ui/index.html
index 4121147..c425196 100644
--- a/apps/streamd/internal/ui/index.html
+++ b/apps/streamd/internal/ui/index.html
@@ -26,6 +26,10 @@
Streams
+
+
+ Modules
+
Schedule
@@ -81,7 +85,7 @@