diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml index fc1d1ba..d534396 100644 --- a/.forgejo/workflows/release.yml +++ b/.forgejo/workflows/release.yml @@ -1,4 +1,4 @@ -# Build multi-platform streamd binaries + Android MITM and attach them to a Forgejo release. +# Build multi-platform streamd (+ drm compat) binaries + Android MITM and attach them to a Forgejo release. # # Triggers: # Stable: git tag v1.2.3 && git push origin v1.2.3 @@ -90,6 +90,8 @@ jobs: Channel: **${CHANNEL}** (rolling download tag \`${CHANNEL}\` also updated). + Prefer \`streamd-*\`. Matching \`drm-*\` files are identical compatibility copies for this release. + | Asset | Platform | |---|---| | \`streamd-windows-amd64.exe\` | Windows x86_64 | @@ -98,6 +100,7 @@ jobs: | \`streamd-linux-arm64\` | Linux ARM64 | | \`streamd-darwin-amd64\` | macOS Intel | | \`streamd-darwin-arm64\` | macOS Apple Silicon | + | \`drm-*\` | Same bytes as the matching \`streamd-*\` (compat) | | \`proxy-android-arm64\` | On-device MITM (push with \`streamd proxy\`) | | \`SHA256SUMS.txt\` | Checksums | diff --git a/.gitignore b/.gitignore index c8832a5..b91b24c 100644 --- a/.gitignore +++ b/.gitignore @@ -218,7 +218,7 @@ apps/proxy/proxy-android-arm64 apps/proxy/rteproxy-android-arm64 # local / VPS deploy + operator scripts (test stuff; keep out of git) deploy/ -# Ignore local scripts, but keep release builders + server helpers tracked. +# Ignore local scripts, but keep the release builders tracked for Forgejo Actions. scripts/* !scripts/build-release.sh !scripts/build-release.ps1 @@ -226,8 +226,6 @@ scripts/* !scripts/build-modules-release.ps1 !scripts/notify-telegram.sh !scripts/notify-telegram.ps1 -!scripts/streamd-bg.sh -!scripts/streamd-update.sh # Shared library packages under apps/modules/ (imported by external module CLIs). # module.yaml stays local; module-publish.yaml is the tracked universal template. apps/modules/** diff --git a/README.md b/README.md index 7867424..c12d14d 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,7 @@ Pinned install: swap `stable` / `beta` for a concrete tag such as `v0.1.5` or `v ```text Streamd/ - streamd.exe # or ./streamd on Linux/macOS + streamd.exe # or ./streamd on Linux/macOS (drm.exe also shipped as a compat copy) 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 diff --git a/apps/agent/README.md b/apps/agent/README.md index a27d6de..2f70fe0 100644 --- a/apps/agent/README.md +++ b/apps/agent/README.md @@ -28,16 +28,14 @@ expire by themselves if the agent dies. # terminal 1 — control plane ./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd -# terminal 2 — agent in the background (Linux / macOS / Windows) +# terminal 2 — agent (operator API key from streamd Settings → API keys) export STREAMD_API_KEY=ndk_… -./bin/streamd agent start --config apps/agent/agent.yaml -./bin/streamd agent status --config apps/agent/agent.yaml -# foreground debug: ./bin/streamd agent run --config apps/agent/agent.yaml -# stop / restart: ./bin/streamd agent stop|restart --config … -# self-update: ./bin/streamd agent update [--beta] [--tag vX.Y.Z] +# or legacy: export STREAMD_TOKEN=… +./bin/streamd agent run --config apps/agent/agent.yaml ``` ```bash +./bin/streamd agent status ./bin/streamd agent devices ./bin/streamd agent enqueue --stream tg4-ioi --reason manual ./bin/streamd agent cancel --job 3 @@ -54,18 +52,12 @@ whichever module a stream names and contains no provider logic. env `STREAMD_API_KEY` / `STREAMD_TOKEN`. Also: `poll_interval_sec`, `workers`, `max_attempts`, `capture_wait_sec`, `devices` (empty = any authorised device), `wvd`, `user_agent`, `agent_id`, `data_dir`, `sync_modules`, `modules_dir` -(default `/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`. +(default `/modules`), `modules_sync_interval_sec`, `modules_prune`. Create the key in the streamd dashboard (role **operator**). The legacy shared `--token` / `STREAMD_TOKEN` still works but is meant for migration only. -`wvd` must be set or key fetches fail. On first `agent start`/`run`, streamd -bootstraps `apps/wvkey/` and creates `/.venv` with `pywidevine` using -the system Python (Windows, Linux, or macOS) so Widevine key fetch works without -a hand-made venv. +`wvd` must be set or key fetches fail. ## Build diff --git a/apps/agent/agent.yaml b/apps/agent/agent.yaml index 4b7b511..0155cb7 100644 --- a/apps/agent/agent.yaml +++ b/apps/agent/agent.yaml @@ -19,18 +19,8 @@ sync_modules: true # modules_dir: # optional; default /modules # modules_sync_interval_sec: 300 # modules_prune: false # delete local modules absent from the panel -# Exponential retry delays (1m, 2m, 4m…). Default false — lone agents retry ASAP. -# Set true only when several agents share the same streams. -# job_backoff: false -# Background daemon (streamd agent start|stop|update): -# log_file: agent.log -# pid_file: agent.pid -# channel: stable # or beta — used by agent update -# asset: # optional streamd-* override -# keep_old: 10 -# Required for key fetch. Relative paths resolve from the install/repo root. -# Agent auto-creates .venv + installs pywidevine on first run (Win/Linux/macOS). -# python: # optional override; default = /.venv/… -wvd: data/device.wvd +# Required for key fetch. Relative paths resolve from the repo root +# (DRM-Decryption/), not from C:\Users\admin\Programming\. +wvd: # user_agent: "" # optional license-request User-Agent diff --git a/apps/agent/agentcmd/agentcmd.go b/apps/agent/agentcmd/agentcmd.go index 9329025..60ef0ba 100644 --- a/apps/agent/agentcmd/agentcmd.go +++ b/apps/agent/agentcmd/agentcmd.go @@ -9,7 +9,6 @@ import ( "os" "os/signal" "strconv" - "strings" "syscall" "text/tabwriter" @@ -22,8 +21,6 @@ import ( "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. @@ -39,14 +36,6 @@ func Run(args []string) error { switch sub { case "run": runCmd(sub, rest) - case "start": - return startDaemonCmd(rest) - case "stop": - return stopDaemonCmd(rest) - case "restart": - return restartDaemonCmd(rest) - case "update": - return updateDaemonCmd(rest) case "status": statusCmd(sub, rest) case "devices": @@ -69,13 +58,8 @@ func Usage() { fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB) Usage: - agent start [--config agent.yaml] # background (pid + log) - agent stop [--config ...] - agent restart [--config ...] - agent status [--config ...] # process + recent jobs - agent update [--config ...] [--beta] [--tag vX.Y.Z] [--no-restart] - agent run [--config ...] # foreground (debug) - + agent run [--config apps/agent/agent.yaml] + agent status [--config ...] agent devices [--config ...] agent enqueue --stream NAME [--reason manual] [--config ...] agent cancel --job ID [--config ...] @@ -84,9 +68,6 @@ Polls streamd for enabled streams that are down / missing credentials, enqueues jobs, claims a free phone that already has the app, captures via MITM, POSTs credentials, then force-stops the app. -Job retries default to immediate (job_backoff: false). Set job_backoff: true -in agent.yaml for exponential delays when several agents share work. - Does not install apps. Does not run NRE/ffmpeg. `) } @@ -136,18 +117,6 @@ func runCmd(sub string, args []string) { "create an operator API key in the streamd dashboard", me.Role) } log.Printf("authenticated to streamd as %q (role %s)", me.Name, me.Role) - - // Widevine keys need apps/wvkey + a local .venv (pywidevine). Create them - // once per install root so Windows / Linux / macOS agents all work. - if rt, err := wvkey.EnsureRuntime(repo.Root()); err != nil { - log.Fatalf("widevine helper: %v", err) - } else { - log.Printf("widevine helper ready python=%s script=%s", rt.Python, rt.Script) - if strings.TrimSpace(cfg.Python) == "" { - cfg.Python = rt.Python - } - } - q := openQueue(cfg) defer q.Close() @@ -156,16 +125,6 @@ func runCmd(sub string, args []string) { } else if n > 0 { log.Printf("re-queued %d stuck running job(s) from previous run", n) } - if n, err := q.ClearAllBackoffs(); err != nil { - log.Printf("clear backoffs: %v", err) - } else if n > 0 { - log.Printf("cleared backoff on %d queued job(s) — runnable now", n) - } - if cfg.JobBackoffEnabled() { - log.Printf("job_backoff=true (exponential delays after failures)") - } else { - log.Printf("job_backoff=false (retry failed captures immediately)") - } pool := device.New("", cfg.Devices) stop := make(chan struct{}) @@ -246,7 +205,6 @@ func runCmd(sub string, args []string) { Python: cfg.Python, WVD: cfg.WVD, UserAgent: cfg.UserAgent, - JobBackoff: cfg.JobBackoffEnabled(), Log: log.Default(), } go w.Loop(stop) @@ -267,7 +225,6 @@ func runCmd(sub string, args []string) { func statusCmd(sub string, args []string) { cfg, _ := loadCfg(sub, args) - printDaemonStatus(cfg) q := openQueue(cfg) defer q.Close() jobs, err := q.ListRecent(40) diff --git a/apps/agent/agentcmd/daemon.go b/apps/agent/agentcmd/daemon.go deleted file mode 100644 index b258c71..0000000 --- a/apps/agent/agentcmd/daemon.go +++ /dev/null @@ -1,177 +0,0 @@ -package agentcmd - -import ( - "flag" - "fmt" - "os" - "os/exec" - "path/filepath" - "strconv" - "strings" - "time" - - "streamd/apps/agent/internal/config" - "streamd/repo" -) - -func readPID(pidFile string) (int, error) { - b, err := os.ReadFile(pidFile) - if err != nil { - return 0, err - } - return strconv.Atoi(strings.TrimSpace(string(b))) -} - -func writePID(pidFile string, pid int) error { - if err := os.MkdirAll(filepath.Dir(pidFile), 0o755); err != nil { - return err - } - return os.WriteFile(pidFile, []byte(strconv.Itoa(pid)+"\n"), 0o644) -} - -func removePID(pidFile string) { _ = os.Remove(pidFile) } - -func runningPID(cfg config.Config) (int, bool) { - pid, err := readPID(cfg.PIDFile) - if err != nil || pid <= 0 { - return 0, false - } - if !signalAlive(pid) { - removePID(cfg.PIDFile) - return pid, false - } - return pid, true -} - -func printDaemonStatus(cfg config.Config) { - fmt.Printf("config: %s\n", cfgPathHint(cfg)) - fmt.Printf("pid: %s\n", cfg.PIDFile) - fmt.Printf("log: %s\n", cfg.LogFile) - if pid, ok := runningPID(cfg); ok { - fmt.Printf("agent: running pid=%d\n", pid) - } else { - fmt.Println("agent: stopped") - } -} - -func cfgPathHint(cfg config.Config) string { - // Best-effort: show data dir; exact yaml path was already resolved by Load. - return cfg.DataDir -} - -func startDaemonCmd(args []string) error { - cfg, cfgFile := loadCfgWithPath("start", args) - if pid, ok := runningPID(cfg); ok { - fmt.Printf("agent already running (pid %d)\n", pid) - return nil - } - exe, err := os.Executable() - if err != nil { - return err - } - if resolved, err := filepath.EvalSymlinks(exe); err == nil { - exe = resolved - } - runArgs := []string{"agent", "run"} - if cfgFile != "" { - runArgs = append(runArgs, "--config", cfgFile) - } - cmd := exec.Command(exe, runArgs...) - if err := os.MkdirAll(filepath.Dir(cfg.LogFile), 0o755); err != nil { - return err - } - logF, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) - if err != nil { - return err - } - cmd.Stdout = logF - cmd.Stderr = logF - cmd.Stdin = nil - detachProcess(cmd) - if err := cmd.Start(); err != nil { - _ = logF.Close() - return fmt.Errorf("start agent: %w", err) - } - pid := cmd.Process.Pid - _ = cmd.Process.Release() - _ = logF.Close() - if err := writePID(cfg.PIDFile, pid); err != nil { - return err - } - time.Sleep(400 * time.Millisecond) - if !signalAlive(pid) { - removePID(cfg.PIDFile) - return fmt.Errorf("agent exited immediately — see %s", cfg.LogFile) - } - fmt.Printf("agent started pid=%d\n", pid) - fmt.Printf("logs: %s\n", cfg.LogFile) - return nil -} - -func stopDaemonCmd(args []string) error { - cfg, _ := loadCfgWithPath("stop", args) - pid, err := readPID(cfg.PIDFile) - if err != nil { - if os.IsNotExist(err) { - fmt.Println("agent is not running") - return nil - } - return err - } - if !signalAlive(pid) { - removePID(cfg.PIDFile) - fmt.Println("agent is not running (stale pid file removed)") - return nil - } - if err := signalTerminate(pid); err != nil { - return fmt.Errorf("stop pid %d: %w", pid, err) - } - deadline := time.Now().Add(8 * time.Second) - for time.Now().Before(deadline) { - if !signalAlive(pid) { - removePID(cfg.PIDFile) - fmt.Printf("agent stopped (was pid %d)\n", pid) - return nil - } - time.Sleep(200 * time.Millisecond) - } - _ = signalKill(pid) - time.Sleep(200 * time.Millisecond) - removePID(cfg.PIDFile) - fmt.Printf("agent killed (pid %d)\n", pid) - return nil -} - -func restartDaemonCmd(args []string) error { - _ = stopDaemonCmd(args) - return startDaemonCmd(args) -} - -// loadCfgWithPath returns config and the resolved --config path (may be empty). -func loadCfgWithPath(sub string, args []string) (config.Config, string) { - fs := flag.NewFlagSet(sub, flag.ExitOnError) - cfgPath := fs.String("config", "", "path to agent.yaml") - _ = fs.Parse(args) - path := strings.TrimSpace(*cfgPath) - cfg, err := config.Load(path) - if err != nil { - fmt.Fprintln(os.Stderr, "[!]", err) - os.Exit(1) - } - if path == "" { - // Mirror config.Load default discovery for daemon child argv. - path = defaultConfigPath() - } else if !filepath.IsAbs(path) { - abs, err := filepath.Abs(path) - if err == nil { - path = abs - } - } - return cfg, path -} - -// defaultConfigPath matches config.Load("") discovery so the background child -// reopens the same yaml the parent resolved. -func defaultConfigPath() string { - return filepath.Join(repo.Root(), "apps", "agent", "agent.yaml") -} diff --git a/apps/agent/agentcmd/daemon_unix.go b/apps/agent/agentcmd/daemon_unix.go deleted file mode 100644 index 14eb237..0000000 --- a/apps/agent/agentcmd/daemon_unix.go +++ /dev/null @@ -1,37 +0,0 @@ -//go:build unix - -package agentcmd - -import ( - "os" - "os/exec" - "syscall" -) - -func detachProcess(cmd *exec.Cmd) { - cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} -} - -func signalAlive(pid int) bool { - p, err := os.FindProcess(pid) - if err != nil { - return false - } - return p.Signal(syscall.Signal(0)) == nil -} - -func signalTerminate(pid int) error { - p, err := os.FindProcess(pid) - if err != nil { - return err - } - return p.Signal(syscall.SIGTERM) -} - -func signalKill(pid int) error { - p, err := os.FindProcess(pid) - if err != nil { - return err - } - return p.Signal(syscall.SIGKILL) -} diff --git a/apps/agent/agentcmd/daemon_windows.go b/apps/agent/agentcmd/daemon_windows.go deleted file mode 100644 index ce8e088..0000000 --- a/apps/agent/agentcmd/daemon_windows.go +++ /dev/null @@ -1,46 +0,0 @@ -//go:build windows - -package agentcmd - -import ( - "os" - "os/exec" - "syscall" - - "golang.org/x/sys/windows" -) - -func detachProcess(cmd *exec.Cmd) { - // CREATE_NEW_PROCESS_GROUP so stop can target the child; keep stdio so - // stdout/stderr still reach the log file opened by the parent. - cmd.SysProcAttr = &syscall.SysProcAttr{ - CreationFlags: windows.CREATE_NEW_PROCESS_GROUP, - } -} - -func signalAlive(pid int) bool { - // On Windows, FindProcess always succeeds; use OpenProcess exit code instead. - h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid)) - if err != nil { - return false - } - defer windows.CloseHandle(h) - var code uint32 - if err := windows.GetExitCodeProcess(h, &code); err != nil { - return false - } - const stillActive = 259 // STILL_ACTIVE - return code == stillActive -} - -func signalTerminate(pid int) error { - p, err := os.FindProcess(pid) - if err != nil { - return err - } - return p.Kill() -} - -func signalKill(pid int) error { - return signalTerminate(pid) -} diff --git a/apps/agent/agentcmd/update.go b/apps/agent/agentcmd/update.go deleted file mode 100644 index 6b0e04d..0000000 --- a/apps/agent/agentcmd/update.go +++ /dev/null @@ -1,282 +0,0 @@ -package agentcmd - -import ( - "flag" - "fmt" - "io" - "net/http" - "os" - "os/exec" - "path/filepath" - "runtime" - "sort" - "strings" - "time" - - "streamd/apps/agent/internal/config" - "streamd/repo" -) - -const ( - releaseBaseURL = "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download" - defaultChannel = "stable" -) - -// errUpdateDeferred means the binary swap finishes after process exit (Windows self-update). -var errUpdateDeferred = fmt.Errorf("update deferred until process exit") - -func defaultAssetName() string { - switch runtime.GOOS { - case "linux": - switch runtime.GOARCH { - case "amd64": - return "streamd-linux-amd64" - case "arm64": - return "streamd-linux-arm64" - } - case "darwin": - switch runtime.GOARCH { - case "amd64": - return "streamd-darwin-amd64" - case "arm64": - return "streamd-darwin-arm64" - } - case "windows": - switch runtime.GOARCH { - case "amd64": - return "streamd-windows-amd64.exe" - case "arm64": - return "streamd-windows-arm64.exe" - } - } - return "" -} - -func updateURL(base, ref, asset string) string { - base = strings.TrimRight(base, "/") - return fmt.Sprintf("%s/%s/%s", base, ref, asset) -} - -func updateDaemonCmd(args []string) error { - fs := flag.NewFlagSet("update", flag.ExitOnError) - cfgPath := fs.String("config", "", "path to agent.yaml") - beta := fs.Bool("beta", false, "use beta channel") - tag := fs.String("tag", "", "pin to release tag (e.g. v0.2.1)") - noRestart := fs.Bool("no-restart", false, "install only; do not start agent") - keep := fs.Int("keep", -1, "archived binaries to keep under old/ (-1 = config)") - _ = fs.Parse(args) - - path := strings.TrimSpace(*cfgPath) - cfg, err := config.Load(path) - if err != nil { - return err - } - if path == "" { - path = defaultConfigPath() - } else if !filepath.IsAbs(path) { - if abs, err := filepath.Abs(path); err == nil { - path = abs - } - } - - channel := cfg.Channel - if channel == "" { - channel = defaultChannel - } - if *beta { - channel = "beta" - } - ref := channel - if strings.TrimSpace(*tag) != "" { - ref = strings.TrimSpace(*tag) - } - asset := cfg.Asset - if asset == "" { - asset = defaultAssetName() - } - if asset == "" { - return fmt.Errorf("unsupported platform %s/%s — set asset: in agent.yaml", runtime.GOOS, runtime.GOARCH) - } - keepN := 10 - if cfg.KeepOld != nil { - keepN = *cfg.KeepOld - } - if *keep >= 0 { - keepN = *keep - } - - installRoot := repo.Root() - url := updateURL(releaseBaseURL, ref, asset) - fmt.Printf("agent update: downloading %s\n", url) - - tmp, err := downloadToTemp(installRoot, url) - if err != nil { - return err - } - defer os.Remove(tmp) - - if err := smokeTestBinary(tmp); err != nil { - return err - } - - exe, err := os.Executable() - if err != nil { - return err - } - if resolved, err := filepath.EvalSymlinks(exe); err == nil { - exe = resolved - } - target := exe - wantName := "streamd" - if runtime.GOOS == "windows" { - wantName = "streamd.exe" - } - // Prefer well-known names in the install / Downloads tree. - for _, candidate := range []string{ - filepath.Join(installRoot, wantName), - filepath.Join(installRoot, "streamd-windows-amd64.exe"), - filepath.Join(installRoot, "streamd-linux-amd64"), - filepath.Join(installRoot, "bin", wantName), - } { - if st, err := os.Stat(candidate); err == nil && !st.IsDir() { - target = candidate - break - } - } - // If the running exe is already a streamd binary in this tree, prefer it. - if strings.Contains(strings.ToLower(filepath.Base(exe)), "streamd") { - if st, err := os.Stat(exe); err == nil && !st.IsDir() { - target = exe - } - } - - if _, ok := runningPID(cfg); ok { - fmt.Println("agent update: stopping running agent…") - if err := stopDaemonCmd([]string{"--config", path}); err != nil { - return err - } - } - - oldDir := filepath.Join(filepath.Dir(target), "old") - if err := os.MkdirAll(oldDir, 0o755); err != nil { - return err - } - stamp := time.Now().UTC().Format("20060102T150405Z") - archive := filepath.Join(oldDir, "streamd."+stamp) - if runtime.GOOS == "windows" { - archive += ".exe" - } - if _, err := os.Stat(archive); err == nil { - archive += "." + fmt.Sprint(os.Getpid()) - } - - if *noRestart { - _ = os.Setenv("STREAMD_UPDATE_RESTART", "0") - } else { - _ = os.Setenv("STREAMD_UPDATE_RESTART", "1") - _ = os.Setenv("STREAMD_UPDATE_AGENT_CONFIG", path) - } - if err := replaceBinary(target, tmp, archive); err != nil { - if err == errUpdateDeferred { - return nil // helper finishes after exit; treat as success for CLI - } - return err - } - fmt.Printf("agent update: archived previous → %s\n", archive) - fmt.Printf("agent update: installed %s (%s)\n", target, ref) - pruneOldBinaries(oldDir, keepN) - - if *noRestart { - fmt.Println("agent update: done (--no-restart). Start with: streamd agent start") - return nil - } - fmt.Println("agent update: starting…") - return startDaemonCmd([]string{"--config", path}) -} - -func downloadToTemp(dir, url string) (string, error) { - if err := os.MkdirAll(dir, 0o755); err != nil { - return "", err - } - f, err := os.CreateTemp(dir, ".streamd-download-*") - if err != nil { - return "", err - } - path := f.Name() - resp, err := http.Get(url) - if err != nil { - _ = f.Close() - _ = os.Remove(path) - return "", err - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - _ = f.Close() - _ = os.Remove(path) - return "", fmt.Errorf("download %s: HTTP %s", url, resp.Status) - } - n, err := io.Copy(f, resp.Body) - closeErr := f.Close() - if err != nil { - _ = os.Remove(path) - return "", err - } - if closeErr != nil { - _ = os.Remove(path) - return "", closeErr - } - if n < 1024 { - _ = os.Remove(path) - return "", fmt.Errorf("download too small (%d bytes) — check URL %s", n, url) - } - head, _ := os.ReadFile(path) - if len(head) > 32 { - h := strings.ToLower(string(head[:32])) - if strings.Contains(h, "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/internal/config/config.go b/apps/agent/internal/config/config.go index 0391f2b..65e6c41 100644 --- a/apps/agent/internal/config/config.go +++ b/apps/agent/internal/config/config.go @@ -36,16 +36,6 @@ type Config struct { // an on-demand stream, or a scheduled event about to start — jump ahead // of routine refreshes in the queue. OnDemandPriority *bool `yaml:"ondemand_priority"` - // JobBackoff enables exponential retry delays after a failed capture - // (1m, 2m, 4m, 8m…). Default off — a single agent should retry ASAP. - // Set job_backoff: true when several agents share the same streams. - JobBackoff *bool `yaml:"job_backoff"` - // Daemon / update (streamd agent start|stop|update) - LogFile string `yaml:"log_file"` // default agent.log next to config / install root - PIDFile string `yaml:"pid_file"` // default agent.pid - Channel string `yaml:"channel"` // stable|beta for agent update - Asset string `yaml:"asset"` // optional streamd-* asset override - KeepOld *int `yaml:"keep_old"` // archived binaries under old/ (default 10) } // PushedCapturesArePriority reports whether pushed captures jump the queue. @@ -54,12 +44,6 @@ func (c Config) PushedCapturesArePriority() bool { return c.OnDemandPriority == nil || *c.OnDemandPriority } -// JobBackoffEnabled is the exponential multi-agent retry delay. -// Defaults to false so a lone agent retries immediately after a failure. -func (c Config) JobBackoffEnabled() bool { - return c.JobBackoff != nil && *c.JobBackoff -} - func (c Config) PollInterval() time.Duration { if c.PollIntervalSec <= 0 { return 30 * time.Second @@ -141,9 +125,6 @@ func applyDefaults(cfg Config, root string) Config { if cfg.WVD != "" && !filepath.IsAbs(cfg.WVD) { cfg.WVD = filepath.Join(root, cfg.WVD) } - if cfg.Python != "" && !filepath.IsAbs(cfg.Python) { - cfg.Python = filepath.Join(root, cfg.Python) - } if cfg.ModulesDir == "" { cfg.ModulesDir = filepath.Join(cfg.DataDir, "modules") } else if !filepath.IsAbs(cfg.ModulesDir) { @@ -152,25 +133,6 @@ func applyDefaults(cfg Config, root string) Config { 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/queue/queue.go b/apps/agent/internal/queue/queue.go index 04a44b0..40411bb 100644 --- a/apps/agent/internal/queue/queue.go +++ b/apps/agent/internal/queue/queue.go @@ -232,18 +232,17 @@ func (s *Store) MarkOK(id int64) error { return err } -// MarkFailed increments attempts. Re-queues unless maxed out. +// MarkFailed increments attempts. Re-queues with backoff unless maxed out. // waitingDevice=true keeps status queued without burning an attempt. -// backoff is how long to wait before the job is runnable again (0 = immediate). -func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool, backoff time.Duration) error { +func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error { j, err := s.Get(id) if err != nil { return err } if waitingDevice { _, err = s.DB.Exec(` -UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`, - msg, now(), id) +UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='' WHERE id=?`, + msg, id) return err } attempts := j.Attempts + 1 @@ -253,8 +252,9 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i attempts, msg, now(), id) return err } - if backoff < 0 { - backoff = 0 + backoff := time.Duration(1< 15*time.Minute { + backoff = 15 * time.Minute } nb := time.Now().UTC().Add(backoff).Format(time.RFC3339) _, err = s.DB.Exec(` @@ -263,29 +263,6 @@ UPDATE jobs SET status='queued', attempts=?, last_error=?, not_before=?, device_ return err } -// ExponentialBackoff is the old multi-agent delay: 1m, 2m, 4m, 8m (cap 15m). -func ExponentialBackoff(attempts int) time.Duration { - if attempts < 1 { - attempts = 1 - } - d := time.Duration(1< 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 c399bd6..517ffb7 100644 --- a/apps/agent/internal/worker/worker.go +++ b/apps/agent/internal/worker/worker.go @@ -27,10 +27,7 @@ type Worker struct { Python string WVD string UserAgent string - // JobBackoff enables exponential delays between failed capture attempts. - // When false (default), failed jobs are re-queued immediately. - JobBackoff bool - Log *log.Logger + Log *log.Logger lastDelayLog time.Time } @@ -70,18 +67,13 @@ func (w *Worker) tick() { if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) { // Config/environment issues — do not burn attempts or multi-minute backoff. w.logf("job=%d waiting: %v", job.ID, err) - _ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0) + _ = w.Queue.MarkFailed(job.ID, err.Error(), true) return } w.logf("job=%d failed: %v", job.ID, err) w.event(job, client.EventCaptureFailed, err.Error(), map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts}) - backoff := time.Duration(0) - if w.JobBackoff { - backoff = queue.ExponentialBackoff(job.Attempts + 1) - w.logf("job=%d re-queue in %s (job_backoff=true)", job.ID, backoff) - } - _ = w.Queue.MarkFailed(job.ID, err.Error(), false, backoff) + _ = w.Queue.MarkFailed(job.ID, err.Error(), false) return } _ = w.Queue.MarkOK(job.ID) @@ -127,8 +119,8 @@ func (w *Worker) runJob(job queue.Job) error { _ = w.Queue.SetDevice(job.ID, serial) w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package()) - // Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew. - if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil { + // Short TTL; /ws/agent heartbeats renew while this process is alive. + if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil { return fmt.Errorf("streamd claim: %w", err) } defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }() @@ -148,19 +140,6 @@ func (w *Worker) runJob(job queue.Job) error { return err } - needsKeys := true - if km := strings.ToLower(strings.TrimSpace(a.KeyMode())); km == "none" || km == "clear" { - needsKeys = false - } - hasKey := poller.ValidKeyPair(res.Key) - if needsKeys && !hasKey { - return fmt.Errorf("refusing to post credentials without valid Widevine key (got mpd=%q key_empty=%v)", - trimURL(res.MPD), strings.TrimSpace(res.Key) == "") - } - if strings.TrimSpace(res.MPD) == "" { - return fmt.Errorf("refusing to post credentials without mpd") - } - cred := client.Credentials{ MPD: res.MPD, Key: res.Key, @@ -171,25 +150,15 @@ func (w *Worker) runJob(job queue.Job) error { if err := w.API.PostCredentials(job.StreamID, cred); err != nil { return fmt.Errorf("post credentials: %w", err) } - w.logf("job=%d posted credentials to streamd has_key=%v key_valid=%v mpd=%s", - job.ID, strings.TrimSpace(res.Key) != "", hasKey, trimURL(res.MPD)) // Report what was captured, never the key itself. w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{ "device": serial, "has_key": strings.TrimSpace(res.Key) != "", - "key_valid": hasKey, + "key_valid": poller.ValidKeyPair(res.Key), }) return nil } -func trimURL(s string) string { - s = strings.TrimSpace(s) - if len(s) <= 96 { - return s - } - return s[:96] + "…" -} - // event posts a stream event to streamd. A timeline entry is never worth // failing a capture over, so errors are logged and dropped. func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) { diff --git a/apps/cli/main.go b/apps/cli/main.go index 802c7fb..37d6475 100644 --- a/apps/cli/main.go +++ b/apps/cli/main.go @@ -2,6 +2,7 @@ // 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. +// A drm.exe copy of this binary is still shipped for one release as a compat alias. package main import ( @@ -109,8 +110,7 @@ Usage: 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 serve [--bind …] [--data …] [--token …] streamd proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent Global flags: @@ -120,6 +120,8 @@ Providers live under modules// (Go source + module-publish.yaml). Local module.yaml holds secrets and is never published; release zips ship module-publish.yaml renamed to module.yaml. The host builds modules on demand. +A drm binary may still be shipped as an identical compatibility copy. + Run any subcommand with --help for its own flags. `) } diff --git a/apps/pkg/bootstrap/bootstrap.go b/apps/pkg/bootstrap/bootstrap.go index 52ff36b..86f4d5d 100644 --- a/apps/pkg/bootstrap/bootstrap.go +++ b/apps/pkg/bootstrap/bootstrap.go @@ -92,6 +92,7 @@ func Ensure(root string) (created []string, err error) { } // If streamd is not already under bin/, copy it there for 1:1 layout. + // Also keep a drm.exe compat copy for one release when missing. if err := ensureBinHost(root); err != nil { return created, err } @@ -104,7 +105,10 @@ func ensureBinHost(root string) error { return nil } exe, _ = filepath.EvalSymlinks(exe) - return copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe")) + if err := copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe")); err != nil { + return err + } + return copyExeIfMissing(exe, filepath.Join(root, "bin", "drm.exe")) } func copyExeIfMissing(src, dest string) error { diff --git a/apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt b/apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt deleted file mode 100644 index 9c8759c..0000000 --- a/apps/pkg/bootstrap/embedded/apps/wvkey/requirements.txt +++ /dev/null @@ -1,6 +0,0 @@ -# Dependencies for wvkey.py (the only Python in the project). -# Install into a venv at the repo root: -# python -m venv .venv -# .venv/bin/pip install -r apps/wvkey/requirements.txt -pywidevine==1.9.0 -requests==2.34.2 diff --git a/apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py b/apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py deleted file mode 100644 index 87c9e43..0000000 --- a/apps/pkg/bootstrap/embedded/apps/wvkey/wvkey.py +++ /dev/null @@ -1,367 +0,0 @@ -#!/usr/bin/env python3 -"""Thin Widevine CDM helper for the Go capture tooling. - -Prints a single CONTENT key as KID:KEY on stdout (no banners) when --quiet. -Exit code 0 on success. - -Example: - .venv/Scripts/python.exe wvkey.py \\ - --wvd path/to/device.wvd \\ - --pssh 'AAAA…' \\ - --license-url 'https://…' \\ - --auth 'Basic …' \\ - --pid 'xxxx' \\ - --quiet -""" - -from __future__ import annotations - -import argparse -import base64 -import json -import sys -from pathlib import Path - -import requests -from pywidevine.cdm import Cdm -from pywidevine.device import Device -from pywidevine.pssh import PSSH - - -def fetch_content_keys_modulardrm( - *, - wvd: Path, - pssh_b64: str, - auth: str, - release_pid: str, - license_url: str, - user_agent: str, -) -> list[str]: - """RTE / thePlatform ModularDrm (JSON challenge wrapper).""" - device = Device.load(str(wvd)) - cdm = Cdm.from_device(device) - session_id = cdm.open() - try: - challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64)) - challenge_b64 = base64.b64encode(challenge).decode("utf-8") - payload = { - "getWidevineLicense": { - "releasePid": release_pid, - "widevineChallenge": challenge_b64, - } - } - headers = { - "Accept-Encoding": "gzip", - "Authorization": auth, - "Content-Type": "application/json; charset=utf-8", - } - if user_agent: - headers["User-Agent"] = user_agent - response = requests.post(license_url, json=payload, headers=headers, timeout=30) - data = response.json() - if data.get("isException"): - raise RuntimeError(data.get("description") or "license server exception") - license_b64 = ( - data.get("getWidevineLicenseResponse", {}).get("license") - or data.get("license") - ) - if not license_b64: - raise RuntimeError("no license in response: " + json.dumps(data)[:1500]) - cdm.parse_license(session_id, base64.b64decode(license_b64)) - keys = [ - f"{key.kid.hex}:{key.key.hex()}" - for key in cdm.get_keys(session_id) - if key.type == "CONTENT" - ] - finally: - cdm.close(session_id) - if not keys: - raise RuntimeError("no CONTENT keys") - return keys - - -def fetch_content_keys_raw( - *, - wvd: Path, - pssh_b64: str, - license_url: str, - user_agent: str, -) -> list[str]: - """Brightcove / generic Widevine: POST raw challenge, parse raw license body.""" - device = Device.load(str(wvd)) - cdm = Cdm.from_device(device) - session_id = cdm.open() - try: - challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64)) - headers = { - "Content-Type": "application/octet-stream", - "Accept": "*/*", - } - if user_agent: - headers["User-Agent"] = user_agent - response = requests.post( - license_url, data=challenge, headers=headers, timeout=30 - ) - if response.status_code >= 400: - raise RuntimeError( - f"license HTTP {response.status_code}: {response.text[:500]!r}" - ) - body = response.content - if not body: - raise RuntimeError("empty license response body") - # Some servers wrap base64 text; try raw first, then b64. - try: - cdm.parse_license(session_id, body) - except Exception: - try: - cdm.parse_license(session_id, base64.b64decode(body)) - except Exception as exc: - raise RuntimeError( - f"parse_license failed ({len(body)} bytes): {exc}" - ) from exc - keys = [ - f"{key.kid.hex}:{key.key.hex()}" - for key in cdm.get_keys(session_id) - if key.type == "CONTENT" - ] - finally: - cdm.close(session_id) - if not keys: - raise RuntimeError("no CONTENT keys") - return keys - - -_CHALLENGE_KEYS = ( - "request", - "licenseRequest", - "license_request", - "widevineChallenge", - "widevine_challenge", - "challenge", - "payload", - "rawLicenseRequestBase64", - "message", - "drm_info", -) - - -def _replace_challenge(obj, challenge_b64: str, challenge_bytes: bytes) -> bool: - """Replace the Widevine challenge field inside a captured JSON license body.""" - if isinstance(obj, dict): - for key in _CHALLENGE_KEYS: - if key not in obj: - continue - val = obj[key] - if key == "drm_info" and isinstance(val, list): - obj[key] = list(challenge_bytes) - return True - if isinstance(val, str) and len(val) >= 8: - obj[key] = challenge_b64 - return True - if isinstance(val, dict) and _replace_challenge(val, challenge_b64, challenge_bytes): - return True - for val in obj.values(): - if _replace_challenge(val, challenge_b64, challenge_bytes): - return True - elif isinstance(obj, list): - for item in obj: - if _replace_challenge(item, challenge_b64, challenge_bytes): - return True - return False - - -def _license_bytes_from_response(response: requests.Response) -> bytes: - body = response.content - if not body: - raise RuntimeError("empty license response body") - # Prefer JSON wrappers used by RedBee / ModularDrm-style proxies. - try: - data = response.json() - except Exception: - data = None - if isinstance(data, dict): - for path in ( - ("license",), - ("licenseResponse",), - ("license_response",), - ("payload",), - ("message",), - ("getWidevineLicenseResponse", "license"), - ("status", "license"), - ): - cur: object = data - ok = True - for key in path: - if not isinstance(cur, dict) or key not in cur: - ok = False - break - cur = cur[key] - if ok and isinstance(cur, str) and cur: - try: - return base64.b64decode(cur) - except Exception: - return cur.encode("utf-8") - # Some LSP responses nest the blob under status.success payload. - if data.get("status", {}).get("success") is False: - raise RuntimeError("license LSP error: " + json.dumps(data)[:500]) - return body - - -def fetch_content_keys_wrap( - *, - wvd: Path, - pssh_b64: str, - license_url: str, - wrap_json: str, - user_agent: str, -) -> list[str]: - """Re-POST a captured JSON license body with a fresh local CDM challenge. - - Used by Channel 4 / RedBee (wvlicenceproxy-service) which reject raw - octet-stream (HTTP 415) and need the phone's token fields intact. - """ - try: - template = json.loads(wrap_json) - except Exception as exc: - raise RuntimeError(f"wrap-json is not valid JSON: {exc}") from exc - - device = Device.load(str(wvd)) - cdm = Cdm.from_device(device) - session_id = cdm.open() - try: - challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64)) - challenge_b64 = base64.b64encode(challenge).decode("utf-8") - if not _replace_challenge(template, challenge_b64, challenge): - raise RuntimeError( - "wrap-json has no recognisable challenge field " - f"(tried {', '.join(_CHALLENGE_KEYS)})" - ) - headers = { - "Content-Type": "application/json", - "Accept": "application/json, */*", - } - if user_agent: - headers["User-Agent"] = user_agent - response = requests.post( - license_url, json=template, headers=headers, timeout=30 - ) - if response.status_code >= 400: - raise RuntimeError( - f"license HTTP {response.status_code}: {response.text[:500]!r}" - ) - license_bytes = _license_bytes_from_response(response) - try: - cdm.parse_license(session_id, license_bytes) - except Exception: - try: - cdm.parse_license(session_id, base64.b64decode(license_bytes)) - except Exception as exc: - raise RuntimeError( - f"parse_license failed ({len(license_bytes)} bytes): {exc}" - ) from exc - keys = [ - f"{key.kid.hex}:{key.key.hex()}" - for key in cdm.get_keys(session_id) - if key.type == "CONTENT" - ] - finally: - cdm.close(session_id) - if not keys: - raise RuntimeError("no CONTENT keys") - return keys - - -def main(argv: list[str] | None = None) -> int: - p = argparse.ArgumentParser(description="Widevine CDM helper → KID:KEY") - p.add_argument("--wvd", type=Path, required=True, help="Path to .wvd device file") - p.add_argument("--pssh", required=True, help="Base64 PSSH box") - p.add_argument( - "--mode", - choices=("modulardrm", "raw", "wrap"), - default="modulardrm", - help="modulardrm=RTE JSON; raw=octet-stream; wrap=captured JSON body", - ) - p.add_argument("--auth", default="", help="Authorization header (modulardrm)") - p.add_argument("--pid", default="", help="releasePid (modulardrm)") - p.add_argument( - "--wrap-json", - default="", - help="Captured phone license POST JSON (wrap mode)", - ) - p.add_argument( - "--license-url", - required=True, - help="Widevine license server URL", - ) - p.add_argument( - "--user-agent", - default="", - help="Optional User-Agent for the license request", - ) - p.add_argument( - "--quiet", - action="store_true", - help="Print only KID:KEY lines (for Go tooling)", - ) - p.add_argument( - "--all", - action="store_true", - help="Print every CONTENT key (default: first only)", - ) - args = p.parse_args(argv) - - if not args.wvd.is_file(): - print(f"[!] missing WVD: {args.wvd}", file=sys.stderr) - return 2 - - try: - if args.mode == "raw": - keys = fetch_content_keys_raw( - wvd=args.wvd, - pssh_b64=args.pssh, - license_url=args.license_url, - user_agent=args.user_agent, - ) - elif args.mode == "wrap": - if not args.wrap_json.strip(): - print( - "[!] --wrap-json required for wrap mode " - "(phone must complete a license POST during capture)", - file=sys.stderr, - ) - return 2 - keys = fetch_content_keys_wrap( - wvd=args.wvd, - pssh_b64=args.pssh, - license_url=args.license_url, - wrap_json=args.wrap_json, - user_agent=args.user_agent, - ) - else: - if not args.auth or not args.pid: - print("[!] --auth and --pid required for modulardrm mode", file=sys.stderr) - return 2 - keys = fetch_content_keys_modulardrm( - wvd=args.wvd, - pssh_b64=args.pssh, - auth=args.auth, - release_pid=args.pid, - license_url=args.license_url, - user_agent=args.user_agent, - ) - except Exception as exc: - print(f"[!] {exc}", file=sys.stderr) - return 1 - - out = keys if args.all else keys[:1] - if not args.quiet: - print("[+] Keys:", file=sys.stderr) - for pair in out: - print(f"--key {pair}", file=sys.stderr) - for pair in out: - print(pair) - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/apps/pkg/modcfg/modcfg.go b/apps/pkg/modcfg/modcfg.go index 5868a55..371e621 100644 --- a/apps/pkg/modcfg/modcfg.go +++ b/apps/pkg/modcfg/modcfg.go @@ -21,8 +21,7 @@ import ( ) // Dir returns the directory holding a module's values. -// Prefers the active modules dir (see modhost / --modules-dir); then the -// directory beside a panel/release binary (/.bin/); then +// Prefers the active modules dir (see modhost / --modules-dir); falls back to // apps/modules// for older checkouts. func Dir(name string) string { preferred := filepath.Join(modhost.ModulesDir(""), name) @@ -32,9 +31,6 @@ func Dir(name string) string { if modhost.ModulesDirOverride() != "" { return preferred } - if beside := dirBesideExecutable(name); beside != "" { - return beside - } root := repo.Root() if _, err := os.Stat(filepath.Join(root, "modules")); err == nil { return filepath.Join(root, "modules", name) @@ -42,43 +38,6 @@ func Dir(name string) string { return filepath.Join(root, "apps", "modules", name) } -// dirBesideExecutable finds module.yaml next to a panel/release binary layout: -// /.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/exec.go b/apps/pkg/modhost/exec.go index 173e9c5..57d1beb 100644 --- a/apps/pkg/modhost/exec.go +++ b/apps/pkg/modhost/exec.go @@ -9,39 +9,9 @@ import ( "strings" ) -// prepareModuleCmd sets STREAMD_MODULES_DIR so child module binaries load -// panel-store module.yaml. Module builds that call EffectiveModulesDir (or -// ApplyEnvModulesDir) honour this; /api/apps also falls back to parsing the -// panel module.yaml when describe returns no channels. -func prepareModuleCmd(cmd *exec.Cmd) { - ov := ModulesDirOverride() - if ov == "" { - return - } - cmd.Env = append(withoutEnvKeys(os.Environ(), "STREAMD_MODULES_DIR", "DRM_MODULES_DIR"), - "STREAMD_MODULES_DIR="+ov) -} - -func withoutEnvKeys(env []string, keys ...string) []string { - drop := map[string]struct{}{} - for _, k := range keys { - drop[strings.ToUpper(k)] = struct{}{} - } - out := make([]string, 0, len(env)) - for _, e := range env { - key, _, _ := strings.Cut(e, "=") - if _, skip := drop[strings.ToUpper(key)]; skip { - continue - } - out = append(out, e) - } - return out -} - // Run executes the module binary with args, inheriting stdout/stderr. func Run(bin string, args ...string) error { cmd := exec.Command(bin, args...) - prepareModuleCmd(cmd) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin @@ -54,7 +24,6 @@ func Run(bin string, args ...string) error { // RunOutput executes the module binary and returns combined stdout. func RunOutput(bin string, args ...string) (string, error) { cmd := exec.Command(bin, args...) - prepareModuleCmd(cmd) var stdout, stderr bytes.Buffer cmd.Stdout = &stdout cmd.Stderr = &stderr @@ -105,9 +74,5 @@ func Load(root, name string) (Module, string, Describe, error) { if d.Name == "" { d.Name = m.Name } - // Older panel binaries may not load module.yaml from STREAMD_MODULES_DIR / - // exe-adjacent layout, leaving package empty (breaks transparent MITM — - // iptables then treats the listen port as the package name). - enrichDescribeFromYAML(&d, m.Dir) return m, bin, d, nil } diff --git a/apps/pkg/modhost/exec_test.go b/apps/pkg/modhost/exec_test.go deleted file mode 100644 index ae7c842..0000000 --- a/apps/pkg/modhost/exec_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package modhost - -import ( - "os" - "os/exec" - "path/filepath" - "testing" -) - -func TestPrepareModuleCmdSetsEnv(t *testing.T) { - t.Cleanup(func() { _ = SetModulesDir("") }) - ov := filepath.Join(t.TempDir(), "modules") - if err := os.MkdirAll(ov, 0o755); err != nil { - t.Fatal(err) - } - if err := SetModulesDir(ov); err != nil { - t.Fatal(err) - } - cmd := exec.Command("true") - prepareModuleCmd(cmd) - found := false - for _, e := range cmd.Env { - if e == "STREAMD_MODULES_DIR="+ov { - found = true - break - } - } - if !found { - t.Fatalf("STREAMD_MODULES_DIR missing in env: %v", cmd.Env) - } -} diff --git a/apps/pkg/modhost/root.go b/apps/pkg/modhost/root.go index 9da5fd3..f796db6 100644 --- a/apps/pkg/modhost/root.go +++ b/apps/pkg/modhost/root.go @@ -3,7 +3,6 @@ package modhost import ( "os" "path/filepath" - "strings" "sync" "streamd/repo" @@ -38,32 +37,12 @@ func ModulesDirOverride() string { return modulesDirOV } -// envModulesDir returns STREAMD_MODULES_DIR (preferred) or DRM_MODULES_DIR. -func envModulesDir() string { - v := strings.TrimSpace(os.Getenv("STREAMD_MODULES_DIR")) - if v == "" { - v = strings.TrimSpace(os.Getenv("DRM_MODULES_DIR")) - } - if v == "" { - return "" - } - if abs, err := filepath.Abs(v); err == nil { - return abs - } - return v -} - // EffectiveModulesDir is the directory that Discover/Open scan. -// Prefer --modules-dir, then STREAMD_MODULES_DIR / DRM_MODULES_DIR, else /modules. -// Module binaries read the env here directly so they honour the panel store even -// when they never call ApplyEnvModulesDir. +// Prefer --modules-dir / STREAMD_MODULES_DIR / DRM_MODULES_DIR; else /modules. func EffectiveModulesDir(root string) string { if ov := ModulesDirOverride(); ov != "" { return ov } - if v := envModulesDir(); v != "" { - return v - } if root == "" { root = repo.Root() } @@ -76,7 +55,10 @@ func ApplyEnvModulesDir() error { if ModulesDirOverride() != "" { return nil } - v := envModulesDir() + v := os.Getenv("STREAMD_MODULES_DIR") + if v == "" { + v = os.Getenv("DRM_MODULES_DIR") + } if v == "" { return nil } diff --git a/apps/pkg/modhost/root_test.go b/apps/pkg/modhost/root_test.go deleted file mode 100644 index d653914..0000000 --- a/apps/pkg/modhost/root_test.go +++ /dev/null @@ -1,39 +0,0 @@ -package modhost - -import ( - "os" - "path/filepath" - "testing" -) - -func TestEffectiveModulesDirEnv(t *testing.T) { - t.Cleanup(func() { - _ = SetModulesDir("") - _ = os.Unsetenv("STREAMD_MODULES_DIR") - _ = os.Unsetenv("DRM_MODULES_DIR") - }) - _ = SetModulesDir("") - _ = os.Unsetenv("STREAMD_MODULES_DIR") - _ = os.Unsetenv("DRM_MODULES_DIR") - - dir := t.TempDir() - t.Setenv("STREAMD_MODULES_DIR", dir) - got := EffectiveModulesDir("") - want, _ := filepath.Abs(dir) - if got != want { - t.Fatalf("env modules dir: got %q want %q", got, want) - } - - override := filepath.Join(t.TempDir(), "override") - if err := os.MkdirAll(override, 0o755); err != nil { - t.Fatal(err) - } - if err := SetModulesDir(override); err != nil { - t.Fatal(err) - } - got = EffectiveModulesDir("") - want, _ = filepath.Abs(override) - if got != want { - t.Fatalf("flag overrides env: got %q want %q", got, want) - } -} diff --git a/apps/pkg/modhost/yaml_enrich.go b/apps/pkg/modhost/yaml_enrich.go deleted file mode 100644 index abb108b..0000000 --- a/apps/pkg/modhost/yaml_enrich.go +++ /dev/null @@ -1,77 +0,0 @@ -package modhost - -import ( - "os" - "path/filepath" - "strings" - - "gopkg.in/yaml.v3" -) - -// enrichDescribeFromYAML fills gaps left by older module binaries that do not -// load panel/agent module.yaml (empty package breaks transparent MITM). -func enrichDescribeFromYAML(d *Describe, modDir string) { - if d == nil || strings.TrimSpace(modDir) == "" { - return - } - raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml")) - if err != nil { - raw, err = os.ReadFile(filepath.Join(modDir, "module-publish.yaml")) - if err != nil { - return - } - } - var doc struct { - Package string `yaml:"package"` - LicenseURL string `yaml:"license_url"` - KeyMode string `yaml:"key_mode"` - ProxyBin string `yaml:"proxy_bin"` - CAHash string `yaml:"ca_hash"` - TransparentMITM *bool `yaml:"transparent_mitm"` - RequireWVD *bool `yaml:"require_wvd"` - Rewriter string `yaml:"rewriter"` - Channels map[string]struct { - Label string `yaml:"label"` - } `yaml:"channels"` - } - if err := yaml.Unmarshal(raw, &doc); err != nil { - return - } - if strings.TrimSpace(d.Package) == "" && strings.TrimSpace(doc.Package) != "" { - d.Package = strings.TrimSpace(doc.Package) - } - if strings.TrimSpace(d.LicenseURL) == "" && strings.TrimSpace(doc.LicenseURL) != "" { - d.LicenseURL = strings.TrimSpace(doc.LicenseURL) - } - if strings.TrimSpace(d.KeyMode) == "" && strings.TrimSpace(doc.KeyMode) != "" { - d.KeyMode = strings.TrimSpace(doc.KeyMode) - } - if strings.TrimSpace(d.ProxyBin) == "" && strings.TrimSpace(doc.ProxyBin) != "" { - d.ProxyBin = strings.TrimSpace(doc.ProxyBin) - } - if strings.TrimSpace(d.CAHash) == "" && strings.TrimSpace(doc.CAHash) != "" { - d.CAHash = strings.TrimSpace(doc.CAHash) - } - if strings.TrimSpace(d.Rewriter) == "" && strings.TrimSpace(doc.Rewriter) != "" { - d.Rewriter = strings.TrimSpace(doc.Rewriter) - } - if !d.TransparentMITM && doc.TransparentMITM != nil { - d.TransparentMITM = *doc.TransparentMITM - } - if !d.RequireWVD && doc.RequireWVD != nil { - d.RequireWVD = *doc.RequireWVD - } - if len(d.Channels) == 0 && len(doc.Channels) > 0 { - for id, ch := range doc.Channels { - label := strings.TrimSpace(ch.Label) - if label == "" { - label = id - } - d.Channels = append(d.Channels, Channel{ID: id, Label: label}) - } - } - if !d.ValuesLoaded { - d.ValuesLoaded = true - d.ValuesPath = filepath.Join(modDir, "module.yaml") - } -} diff --git a/apps/pkg/phonecap/phonecap.go b/apps/pkg/phonecap/phonecap.go index b90bc6d..2f27ffd 100644 --- a/apps/pkg/phonecap/phonecap.go +++ b/apps/pkg/phonecap/phonecap.go @@ -206,21 +206,17 @@ func Run(opt Options) (res Result, err error) { if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() { useTProxy = true } - pkgName := strings.TrimSpace(a.Package()) - if useTProxy && pkgName == "" { - return res, fmt.Errorf("module %q has empty package — fix module.yaml package: (or re-pull modules); transparent MITM cannot install iptables UID rules", a.Name()) - } if useTProxy { // Transparent REDIRECT — keeps phone VPN (BBC UK geo) working. // StartTransparent creates a per-install CA under data/ if needed and pushes cert+key. proxy.ClearHTTPProxy(c) - remoteDir := "/data/local/tmp/capture/" + pkgName + remoteDir := "/data/local/tmp/capture/" + a.Package() var mitmHosts []string if mh, ok := a.(app.MitmHostList); ok { mitmHosts = mh.MitmHosts() } - if err := proxy.StartTransparent(c, proxyBin, pkgName, "8080", remoteDir, false, mitmHosts...); err != nil { + if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false, mitmHosts...); err != nil { return res, fmt.Errorf("transparent MITM start: %w", err) } defer proxy.StopTransparent(c) @@ -242,6 +238,17 @@ func Run(opt Options) (res Result, err error) { proxy.ReinjectCA(c, caHash) } + if err := a.Launch(c); err != nil { + return res, fmt.Errorf("launch: %w", err) + } + if !opt.NoAutoPlay { + if err := a.AutoPlay(c, opt.Channel); err != nil { + return res, fmt.Errorf("auto-play: %w", err) + } + } else { + fmt.Println("[*] Open the channel on the phone and wait for playback…") + } + _ = os.MkdirAll(filepath.Join(root, ".cache"), 0o755) serialTag := c.Serial if serialTag == "" { @@ -249,161 +256,107 @@ func Run(opt Options) (res Result, err error) { } localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log") localCap := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+"_cap.json") + // Fresh local mirrors each run so grab-all does not reuse a prior channel's MPD. + _ = os.WriteFile(localLog, nil, 0o644) + _ = os.Remove(localCap) stop := make(chan struct{}) go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop) defer close(stop) - keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode)) - if keyMode == "" || keyMode == "auto" { - keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode())) - } - needsKeys := keyMode != "none" && keyMode != "clear" - - // DRM apps: wait up to 90s for Widevine traffic, then force-stop and retry - // (max 3). Clear / MPD-only apps keep a single wait of opt.Wait. - attempts := 1 - waitPer := opt.Wait - if needsKeys { - attempts = 3 - waitPer = 90 * time.Second - if opt.Wait > 0 && opt.Wait < waitPer { - waitPer = opt.Wait - } - } - need := hints.Require if len(need) == 0 { need = []string{"manifest"} } - - var ( - capData capture.Data - licenseURL string - mpdURL string - key string - lastErr error - ) - - for attempt := 1; attempt <= attempts; attempt++ { - if attempt > 1 { - fmt.Printf("[*] Widevine attempt %d/%d — closing app and retrying…\n", attempt, attempts) - c.ForceStop(a.Package()) - time.Sleep(800 * time.Millisecond) + 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) + } + } } + } - // 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) + 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) + } + if v == "" { continue } - if !opt.NoAutoPlay { - if err := a.AutoPlay(c, opt.Channel); err != nil { - lastErr = fmt.Errorf("auto-play: %w", err) - c.ForceStop(a.Package()) - continue - } - } else { - fmt.Println("[*] Open the channel on the phone and wait for playback…") + 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)) + } - 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) + 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) if kerr != nil { - lastErr = kerr - // Missing --wvd on a manual grab-all can soft-save MPD-only; agents - // always pass WVD so this path is for interactive capture only. + // Allow MPD-only sessions when no .wvd was passed (grab-all / first pass), + // unless the app requires keys (e.g. c4). softOK := strings.Contains(kerr.Error(), "requires --wvd") if softOK { if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() { - c.ForceStop(a.Package()) - continue + return res, kerr } fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr) - key = "" - lastErr = nil - break + } else { + return res, kerr } - fmt.Fprintf(os.Stderr, "[!] key fetch failed (attempt %d/%d): %v\n", attempt, attempts, kerr) - c.ForceStop(a.Package()) - continue + } else { + fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | ")) } - 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{ @@ -431,62 +384,6 @@ func Run(opt Options) (res Result, err error) { return res, nil } -func enrichWidevinePSSH(capData capture.Data) { - mpdForPSSH := strings.TrimSpace(capData.Get("mpd")) - curPSSH := strings.TrimSpace(capData.Get("pssh")) - needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH) - if !needPSSH || mpdForPSSH == "" { - return - } - if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") { - if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" { - if curPSSH != "" && curPSSH != pssh { - fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD") - } - capData["pssh"] = pssh - } else if err != nil && curPSSH == "" { - fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err) - } - return - } - if curPSSH == "" { - if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" { - capData["pssh"] = pssh - } else if err != nil { - fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err) - } - } -} - -func looksLikeKey(raw string) bool { - raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw) - for _, line := range strings.Split(raw, "\n") { - line = strings.TrimSpace(line) - if line == "" { - continue - } - kid, k, ok := strings.Cut(line, ":") - if !ok { - continue - } - if len(hexDigits(kid)) == 32 && len(hexDigits(k)) == 32 { - return true - } - } - return false -} - -func hexDigits(s string) string { - var b strings.Builder - for _, r := range s { - switch { - case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F': - b.WriteRune(r) - } - } - return b.String() -} - // ClearProxyLater clears http_proxy (exported for agent defer helpers). func ClearProxyLater(c *adb.Client) { proxy.ClearHTTPProxy(c) @@ -517,18 +414,16 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st if strings.TrimSpace(opt.WVD) == "" { return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)") } - // Ensure apps/wvkey + .venv/pywidevine exist on Windows/Linux/macOS. - rt, err := wvkey.EnsureRuntime(root) - if err != nil { - return "", err - } - py := rt.Python - if p := strings.TrimSpace(opt.Python); p != "" && fileExistsPath(p) { - py = p + 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") + } } wopt := wvkey.Options{ Python: py, - Script: rt.Script, + Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"), WVD: opt.WVD, PSSH: cap.Get("pssh"), Auth: cap.Get("auth"), @@ -570,11 +465,6 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st } } -func fileExistsPath(path string) bool { - st, err := os.Stat(path) - return err == nil && !st.IsDir() -} - func first(vals ...string) string { for _, v := range vals { if strings.TrimSpace(v) != "" { diff --git a/apps/pkg/proxy/proxy.go b/apps/pkg/proxy/proxy.go index 02286d6..90d7647 100644 --- a/apps/pkg/proxy/proxy.go +++ b/apps/pkg/proxy/proxy.go @@ -481,14 +481,10 @@ const ( // mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent // mode otherwise only MITMs open.live.bbc.co.uk. func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool, mitmHosts ...string) error { - pkg = strings.TrimSpace(pkg) - if pkg == "" { - return fmt.Errorf("transparent MITM requires Android package name (module.yaml package: is empty — re-pull/rebuild the module)") - } if port == "" { port = "8080" } - if remoteDir == "" || strings.HasSuffix(remoteDir, "/capture/") || strings.HasSuffix(remoteDir, `\capture\`) { + if remoteDir == "" { remoteDir = RemoteCaptureRoot + "/" + pkg } stopProxy(c) diff --git a/apps/pkg/wvkey/ensure.go b/apps/pkg/wvkey/ensure.go deleted file mode 100644 index 6c7eac6..0000000 --- a/apps/pkg/wvkey/ensure.go +++ /dev/null @@ -1,172 +0,0 @@ -package wvkey - -import ( - "fmt" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" -) - -// Runtime is a resolved Python + wvkey.py pair ready for Fetch*. -type Runtime struct { - Python string - Script string -} - -// ScriptPath returns /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 b5d9a30..48ec924 100644 --- a/apps/pkg/wvkey/wvkey.go +++ b/apps/pkg/wvkey/wvkey.go @@ -58,21 +58,14 @@ func FetchWrapAll(opt Options) ([]string, error) { } func run(opt Options, mode string, all bool) ([]string, error) { - py := resolvePython(opt.Python) + py := opt.Python + if py == "" { + py = findPython() + } script := opt.Script if script == "" { return nil, fmt.Errorf("wvkey script path required") } - if !fileExists(script) { - return nil, fmt.Errorf("wvkey script not found: %s", script) - } - if !fileExists(py) { - // Bare names like "python3" are OK via LookPath inside resolvePython; - // absolute/relative paths must exist. - if filepath.IsAbs(py) || strings.Contains(py, string(os.PathSeparator)) || strings.Contains(py, "/") { - return nil, fmt.Errorf("wvkey python not found: %s (run agent once to auto-create .venv, or set python: in agent.yaml)", py) - } - } if strings.TrimSpace(opt.WVD) == "" { return nil, fmt.Errorf("wvkey --wvd path required") } @@ -127,30 +120,12 @@ func run(opt Options, mode string, all bool) ([]string, error) { return out, nil } -// resolvePython uses an explicit path only when the file exists; otherwise -// discovers a usable interpreter. Passing a missing absolute path used to make -// exec fail with a confusing "not found in %PATH%" on Windows. -func resolvePython(explicit string) string { - if strings.TrimSpace(explicit) != "" { - if st, err := os.Stat(explicit); err == nil && !st.IsDir() { - return explicit - } - if !strings.Contains(explicit, string(os.PathSeparator)) && !strings.Contains(explicit, "/") { - if p, err := exec.LookPath(explicit); err == nil { - return p - } - } - } - return findPython() -} - func findPython() string { candidates := []string{ filepath.Join(".venv", "Scripts", "python.exe"), filepath.Join(".venv", "bin", "python"), "python3", "python", - "py", } for _, c := range candidates { if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) { diff --git a/apps/streamd/README.md b/apps/streamd/README.md index 79994a8..20dfe6a 100644 --- a/apps/streamd/README.md +++ b/apps/streamd/README.md @@ -17,9 +17,7 @@ apps/streamd/ ## Run ```bash -./bin/streamd serve --bind 127.0.0.1:8083 -# --data is optional: reuses existing .cache/streamd (cwd or next to the binary) -# or set STREAMD_DATA / pass --data explicitly +./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd ``` `--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any diff --git a/apps/streamd/go.mod b/apps/streamd/go.mod index d3a639e..ec97f71 100644 --- a/apps/streamd/go.mod +++ b/apps/streamd/go.mod @@ -6,7 +6,6 @@ require ( github.com/gorilla/websocket v1.5.3 modernc.org/sqlite v1.34.5 streamd v0.0.0 - gopkg.in/yaml.v3 v3.0.1 ) replace streamd => ../pkg @@ -18,7 +17,6 @@ require ( github.com/ncruces/go-strftime v0.1.9 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect golang.org/x/sys v0.42.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect modernc.org/libc v1.55.3 // indirect modernc.org/mathutil v1.6.0 // indirect modernc.org/memory v1.8.0 // indirect diff --git a/apps/streamd/go.sum b/apps/streamd/go.sum index 077f977..3dff215 100644 --- a/apps/streamd/go.sum +++ b/apps/streamd/go.sum @@ -19,9 +19,6 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo= golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw= golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= -gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= diff --git a/apps/streamd/internal/api/api.go b/apps/streamd/internal/api/api.go index bf83790..4408794 100644 --- a/apps/streamd/internal/api/api.go +++ b/apps/streamd/internal/api/api.go @@ -13,7 +13,6 @@ import ( "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" ) @@ -62,7 +61,6 @@ type Handler struct { Modules *modstore.Store // ModulesNotify is set when the hub supports module change pushes. ModulesNotify ModulesNotifier - Egress *egress.Manager Log *slog.Logger } @@ -72,7 +70,6 @@ func (h *Handler) Mount(mux *http.ServeMux) { mux.HandleFunc("/api/streams/", h.streamAction) mux.HandleFunc("/api/overview", h.overview) h.MountControl(mux) - h.MountEgress(mux) mux.HandleFunc("/api/apps", h.apps) mux.HandleFunc("/api/modules", h.modules) mux.HandleFunc("/api/modules/", h.modules) @@ -542,7 +539,6 @@ func changeNote(before, after db.Stream, in db.PatchStream) string { add("key", in.Key != nil && before.Key != after.Key) add("headers", in.HeadersJSON != nil && before.HeadersJSON != after.HeadersJSON) add("proxy", in.Proxy != nil && before.Proxy != after.Proxy) - add("egress", in.Egress != nil && before.Egress != after.Egress) add("variants", before.VariantsJSON != after.VariantsJSON) add("outputs", before.OutputsJSON != after.OutputsJSON) add("settings", before.SettingsJSON != after.SettingsJSON) @@ -574,9 +570,6 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool { if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) { return true } - if in.Egress != nil && strings.TrimSpace(before.Egress) != strings.TrimSpace(after.Egress) { - return true - } if in.VariantsJSON != nil || len(in.Variants) > 0 { if strings.TrimSpace(before.VariantsJSON) != strings.TrimSpace(after.VariantsJSON) { return true diff --git a/apps/streamd/internal/api/apps.go b/apps/streamd/internal/api/apps.go index 53b146d..5b61afc 100644 --- a/apps/streamd/internal/api/apps.go +++ b/apps/streamd/internal/api/apps.go @@ -2,12 +2,8 @@ package api import ( "net/http" - "sort" - - "gopkg.in/yaml.v3" "streamd/apps/streamd/internal/auth" - "streamd/apps/streamd/internal/modstore" "streamd/modhost" "streamd/mpd" "streamd/repo" @@ -48,17 +44,13 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) { 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) + out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}) 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) + out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}) h.logger().Warn("module describe skipped", "module", m.Name, "err", err) continue } @@ -69,14 +61,10 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) { for _, ch := range d.Channels { info.Channels = append(info.Channels, channelInfo{ID: ch.ID, Label: ch.Label}) } + info.HasConfig = len(info.Channels) > 0 if d.Rewriter != "" { info.Rewriter = d.Rewriter } - // Older module binaries may not see the panel store; fill from module.yaml. - if len(info.Channels) == 0 { - h.fillChannelsFromStore(&info, m.Name) - } - info.HasConfig = len(info.Channels) > 0 out = append(out, info) } writeJSON(w, http.StatusOK, map[string]any{ @@ -84,53 +72,3 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) { "rewriters": mpd.Names(), }) } - -func (h *Handler) fillChannelsFromStore(info *appInfo, name string) { - if h == nil || h.Modules == nil || info == nil { - return - } - chans := channelsFromStoreYAML(h.Modules, name) - if len(chans) == 0 { - return - } - info.Channels = chans - info.HasConfig = true - if info.Error != "" { - // Soft: yaml channels recovered even though describe failed. - info.Error = "" - } -} - -// channelsFromStoreYAML reads channels from the panel module.yaml when describe -// returns none (common with uploaded binaries that resolve values via cwd). -func channelsFromStoreYAML(store *modstore.Store, name string) []channelInfo { - if store == nil { - return nil - } - raw, err := store.ReadYAML(name) - if err != nil || len(raw) == 0 { - return nil - } - var doc struct { - Channels map[string]struct { - Label string `yaml:"label"` - } `yaml:"channels"` - } - if err := yaml.Unmarshal(raw, &doc); err != nil || len(doc.Channels) == 0 { - return nil - } - ids := make([]string, 0, len(doc.Channels)) - for id := range doc.Channels { - ids = append(ids, id) - } - sort.Strings(ids) - out := make([]channelInfo, 0, len(ids)) - for _, id := range ids { - label := doc.Channels[id].Label - if label == "" { - label = id - } - out = append(out, channelInfo{ID: id, Label: label}) - } - return out -} diff --git a/apps/streamd/internal/api/apps_test.go b/apps/streamd/internal/api/apps_test.go deleted file mode 100644 index 2ade1ad..0000000 --- a/apps/streamd/internal/api/apps_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package api - -import ( - "os" - "path/filepath" - "testing" - - "streamd/apps/streamd/internal/modstore" -) - -func TestChannelsFromStoreYAML(t *testing.T) { - root := t.TempDir() - store := modstore.New(root) - modDir := filepath.Join(root, "rte") - if err := os.MkdirAll(modDir, 0o755); err != nil { - t.Fatal(err) - } - yaml := []byte(`package: air.RTE -channels: - rteone: - label: RTE One - rtetwo: - label: RTE 2 -`) - if err := os.WriteFile(filepath.Join(modDir, "module.yaml"), yaml, 0o644); err != nil { - t.Fatal(err) - } - chans := channelsFromStoreYAML(store, "rte") - if len(chans) != 2 { - t.Fatalf("got %d channels: %+v", len(chans), chans) - } - if chans[0].ID != "rteone" || chans[0].Label != "RTE One" { - t.Fatalf("first channel: %+v", chans[0]) - } - if chans[1].ID != "rtetwo" { - t.Fatalf("second channel: %+v", chans[1]) - } -} - -func TestChannelsFromStoreYAMLMissing(t *testing.T) { - store := modstore.New(t.TempDir()) - if chans := channelsFromStoreYAML(store, "nope"); chans != nil { - t.Fatalf("expected nil, got %+v", chans) - } -} diff --git a/apps/streamd/internal/api/control.go b/apps/streamd/internal/api/control.go index f89db47..44fd939 100644 --- a/apps/streamd/internal/api/control.go +++ b/apps/streamd/internal/api/control.go @@ -162,7 +162,6 @@ func (h *Handler) duplicate(w http.ResponseWriter, r *http.Request, id int64) { Key: src.Key, HeadersJSON: src.HeadersJSON, Proxy: src.Proxy, - Egress: src.Egress, VideoSelect: src.VideoSelect, AudioSelect: src.AudioSelect, Rewriter: src.Rewriter, @@ -272,19 +271,9 @@ func (h *Handler) doProbe(ctx context.Context, st db.Stream, target string) prob start := time.Now() client := &http.Client{Timeout: 20 * time.Second} - // Fetch through the stream's effective proxy (explicit or named egress), - // so a geo-restricted origin is probed the same way the downloader would. - proxy := strings.TrimSpace(st.Proxy) - if h.Egress != nil { - if p, err := h.Egress.ResolveProxy(st); err == nil { - proxy = p - } else if strings.TrimSpace(st.Egress) != "" && proxy == "" { - res.Error = "egress: " + err.Error() - res.Summary = "egress profile could not be brought up" - return res - } - } - if proxy != "" { + // Fetch through the stream's own proxy, so a geo-restricted origin is + // probed the same way the downloader would reach it. + if proxy := strings.TrimSpace(st.Proxy); proxy != "" { if c, err := httpClientWithProxy(proxy); err == nil { client = c } else { diff --git a/apps/streamd/internal/api/egress.go b/apps/streamd/internal/api/egress.go deleted file mode 100644 index bfda8b9..0000000 --- a/apps/streamd/internal/api/egress.go +++ /dev/null @@ -1,254 +0,0 @@ -package api - -import ( - "database/sql" - "encoding/json" - "errors" - "io" - "net/http" - "strings" - - "streamd/apps/streamd/internal/auth" - "streamd/apps/streamd/internal/db" -) - -// MountEgress registers /api/egress routes. -func (h *Handler) MountEgress(mux *http.ServeMux) { - mux.HandleFunc("/api/egress", h.egressRoot) - mux.HandleFunc("/api/egress/", h.egressAction) -} - -func (h *Handler) egressRoot(w http.ResponseWriter, r *http.Request) { - if h.Egress == nil { - writeErr(w, http.StatusServiceUnavailable, "egress manager not configured") - return - } - switch r.Method { - case http.MethodGet: - if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { - return - } - list, err := h.Store.ListEgressProfiles() - if err != nil { - writeErr(w, http.StatusInternalServerError, err.Error()) - return - } - for i := range list { - h.Egress.Enrich(&list[i]) - } - writeJSON(w, http.StatusOK, map[string]any{"profiles": list}) - case http.MethodPost: - p, ok := auth.Guard(w, r, auth.RoleAdmin) - if !ok { - return - } - var in db.CreateEgressProfile - if err := readJSON(r, &in); err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - prof, err := h.Store.CreateEgressProfile(in) - if err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - h.Egress.Enrich(&prof) - h.audit(r, p, http.StatusOK, "create egress "+prof.Name) - writeJSON(w, http.StatusOK, prof) - default: - writeErr(w, http.StatusMethodNotAllowed, "method not allowed") - } -} - -func (h *Handler) egressAction(w http.ResponseWriter, r *http.Request) { - if h.Egress == nil { - writeErr(w, http.StatusServiceUnavailable, "egress manager not configured") - return - } - path := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/egress/"), "/") - if path == "" { - h.egressRoot(w, r) - return - } - parts := strings.Split(path, "/") - name := db.Slug(parts[0]) - if name == "" { - writeErr(w, http.StatusBadRequest, "invalid name") - return - } - action := "" - if len(parts) > 1 { - action = strings.ToLower(parts[1]) - } - - switch { - case action == "" && r.Method == http.MethodGet: - if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok { - return - } - prof, err := h.Egress.Status(name) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - writeErr(w, http.StatusNotFound, "not found") - return - } - writeErr(w, http.StatusInternalServerError, err.Error()) - return - } - writeJSON(w, http.StatusOK, prof) - - case action == "" && r.Method == http.MethodPut: - p, ok := auth.Guard(w, r, auth.RoleAdmin) - if !ok { - return - } - h.putEgress(w, r, p, name) - - case action == "" && r.Method == http.MethodDelete: - p, ok := auth.Guard(w, r, auth.RoleAdmin) - if !ok { - return - } - prof, err := h.Store.GetEgressProfileByName(name) - if err != nil { - writeErr(w, http.StatusNotFound, "not found") - return - } - _ = h.Egress.Down(name) - if err := h.Store.DeleteEgressProfile(prof.ID); err != nil { - writeErr(w, http.StatusInternalServerError, err.Error()) - return - } - _ = h.Egress.RemoveFiles(name) - h.audit(r, p, http.StatusOK, "delete egress "+name) - writeJSON(w, http.StatusOK, map[string]any{"ok": true}) - - case action == "up" && r.Method == http.MethodPost: - p, ok := auth.Guard(w, r, auth.RoleAdmin) - if !ok { - return - } - if err := h.Egress.EnsureUp(name); err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - prof, _ := h.Egress.Status(name) - h.audit(r, p, http.StatusOK, "egress up "+name) - writeJSON(w, http.StatusOK, prof) - - case action == "down" && r.Method == http.MethodPost: - p, ok := auth.Guard(w, r, auth.RoleAdmin) - if !ok { - return - } - if err := h.Egress.Down(name); err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - prof, _ := h.Egress.Status(name) - h.audit(r, p, http.StatusOK, "egress down "+name) - writeJSON(w, http.StatusOK, prof) - - case action == "test" && r.Method == http.MethodPost: - p, ok := auth.Guard(w, r, auth.RoleAdmin) - if !ok { - return - } - out, err := h.Egress.TestDial(name) - if err != nil { - if out == nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - h.audit(r, p, http.StatusOK, "egress test "+name+" fail") - writeJSON(w, http.StatusOK, out) - return - } - h.audit(r, p, http.StatusOK, "egress test "+name) - writeJSON(w, http.StatusOK, out) - - case action == "conf" && r.Method == http.MethodPut: - p, ok := auth.Guard(w, r, auth.RoleAdmin) - if !ok { - return - } - body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) - _ = r.Body.Close() - if err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - contents := string(body) - ct := r.Header.Get("Content-Type") - if strings.Contains(ct, "json") || strings.HasPrefix(strings.TrimSpace(contents), "{") { - var in struct { - Conf string `json:"conf"` - } - if err := json.Unmarshal(body, &in); err != nil || strings.TrimSpace(in.Conf) == "" { - writeErr(w, http.StatusBadRequest, "conf required") - return - } - contents = in.Conf - } - if strings.TrimSpace(contents) == "" { - writeErr(w, http.StatusBadRequest, "empty conf") - return - } - if _, err := h.Store.GetEgressProfileByName(name); err != nil { - writeErr(w, http.StatusNotFound, "not found") - return - } - if err := h.Egress.WriteConf(name, contents); err != nil { - writeErr(w, http.StatusInternalServerError, err.Error()) - return - } - prof, _ := h.Egress.Status(name) - h.audit(r, p, http.StatusOK, "egress conf "+name) - writeJSON(w, http.StatusOK, prof) - - default: - writeErr(w, http.StatusMethodNotAllowed, "method not allowed") - } -} - -func (h *Handler) putEgress(w http.ResponseWriter, r *http.Request, p *auth.Principal, name string) { - prof, err := h.Store.GetEgressProfileByName(name) - if err != nil { - writeErr(w, http.StatusNotFound, "not found") - return - } - var in struct { - Enabled *bool `json:"enabled"` - SocksURL *string `json:"socks_url"` - Kind *string `json:"kind"` - Conf *string `json:"conf"` - } - if err := readJSON(r, &in); err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - upd, err := h.Store.UpdateEgressProfile(prof.ID, db.UpdateEgressProfile{ - Enabled: in.Enabled, SocksURL: in.SocksURL, Kind: in.Kind, - }) - if err != nil { - writeErr(w, http.StatusBadRequest, err.Error()) - return - } - if in.Conf != nil && strings.TrimSpace(*in.Conf) != "" { - if err := h.Egress.WriteConf(name, *in.Conf); err != nil { - writeErr(w, http.StatusInternalServerError, err.Error()) - return - } - } - h.Egress.Enrich(&upd) - if in.Enabled != nil && *in.Enabled { - _ = h.Egress.EnsureUp(name) - upd, _ = h.Egress.Status(name) - } - if in.Enabled != nil && !*in.Enabled { - _ = h.Egress.Down(name) - upd, _ = h.Egress.Status(name) - } - h.audit(r, p, http.StatusOK, "update egress "+name) - writeJSON(w, http.StatusOK, upd) -} diff --git a/apps/streamd/internal/api/events.go b/apps/streamd/internal/api/events.go index 1817a19..873c006 100644 --- a/apps/streamd/internal/api/events.go +++ b/apps/streamd/internal/api/events.go @@ -363,10 +363,6 @@ 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), @@ -378,8 +374,7 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) { "viewers": viewers, "needs_capture": needCapture, }, - "recent_events": recent, - "recent_sessions": sessions, + "recent_events": recent, } 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 e5a9de0..f99efa5 100644 --- a/apps/streamd/internal/api/modules.go +++ b/apps/streamd/internal/api/modules.go @@ -222,14 +222,6 @@ func (h *Handler) uploadModule(w http.ResponseWriter, r *http.Request) { 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 diff --git a/apps/streamd/internal/db/db.go b/apps/streamd/internal/db/db.go index aa6b3f7..522e009 100644 --- a/apps/streamd/internal/db/db.go +++ b/apps/streamd/internal/db/db.go @@ -41,8 +41,7 @@ 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) - Egress string `json:"egress"` // named egress profile (wireguard/socks); used when Proxy empty + Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE) VideoSelect string `json:"video_select"` AudioSelect string `json:"audio_select"` Enabled bool `json:"enabled"` @@ -82,7 +81,6 @@ 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"` @@ -105,7 +103,6 @@ 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"` @@ -131,7 +128,6 @@ 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"` @@ -234,7 +230,6 @@ 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) } @@ -244,13 +239,7 @@ CREATE TABLE IF NOT EXISTS agent_claims ( if err := s.migrateSettings(); err != nil { return err } - if err := s.migrateSchedules(); err != nil { - return err - } - if err := s.migrateEgress(); err != nil { - return err - } - return s.migrateSessions() + return s.migrateSchedules() } func now() string { @@ -275,13 +264,10 @@ 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,''), COALESCE(s.egress,''), s.video_select, s.audio_select, s.enabled, s.rewriter, + COALESCE(s.proxy,''), 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), @@ -332,7 +318,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.Egress, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, + &st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, &st.VariantsJSON, &st.OutputsJSON, &st.SettingsJSON, &st.DRMMode, &onDemand, &st.IdleTimeoutS, &public, &st.CreatedAt, &st.UpdatedAt, @@ -375,7 +361,6 @@ 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 @@ -572,13 +557,12 @@ 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,egress, +INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy, 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 { @@ -670,9 +654,6 @@ 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 } @@ -749,11 +730,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=?, egress=?, video_select=?, audio_select=?, enabled=?, rewriter=?, + headers_json=?, proxy=?, 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.Egress, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, + cur.HeadersJSON, cur.Proxy, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, cur.VariantsJSON, cur.OutputsJSON, cur.SettingsJSON, cur.DRMMode, onDemand, cur.IdleTimeoutS, public, ts, id) if err != nil { @@ -794,16 +775,7 @@ func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) { if mpd == "" { return Stream{}, fmt.Errorf("mpd required") } - 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=?`, + _, 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 deleted file mode 100644 index 6371c83..0000000 --- a/apps/streamd/internal/db/egress.go +++ /dev/null @@ -1,226 +0,0 @@ -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 deleted file mode 100644 index 3b6c9c1..0000000 --- a/apps/streamd/internal/db/egress_test.go +++ /dev/null @@ -1,117 +0,0 @@ -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 07bb1e5..426285d 100644 --- a/apps/streamd/internal/db/events.go +++ b/apps/streamd/internal/db/events.go @@ -408,13 +408,6 @@ 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 deleted file mode 100644 index 12a3a96..0000000 --- a/apps/streamd/internal/db/sessions.go +++ /dev/null @@ -1,211 +0,0 @@ -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 deleted file mode 100644 index f6f26b6..0000000 --- a/apps/streamd/internal/db/sessions_test.go +++ /dev/null @@ -1,114 +0,0 @@ -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/egress/conf.go b/apps/streamd/internal/egress/conf.go deleted file mode 100644 index 7e4356b..0000000 --- a/apps/streamd/internal/egress/conf.go +++ /dev/null @@ -1,80 +0,0 @@ -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 deleted file mode 100644 index d7a8967..0000000 --- a/apps/streamd/internal/egress/manager.go +++ /dev/null @@ -1,418 +0,0 @@ -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 deleted file mode 100644 index b355237..0000000 --- a/apps/streamd/internal/egress/manager_test.go +++ /dev/null @@ -1,100 +0,0 @@ -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 deleted file mode 100644 index a26c3a3..0000000 --- a/apps/streamd/internal/egress/wg_linux.go +++ /dev/null @@ -1,302 +0,0 @@ -//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 deleted file mode 100644 index 065d686..0000000 --- a/apps/streamd/internal/egress/wg_stub.go +++ /dev/null @@ -1,19 +0,0 @@ -//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/logfile/logfile.go b/apps/streamd/internal/logfile/logfile.go index b9bd4e4..a4598f8 100644 --- a/apps/streamd/internal/logfile/logfile.go +++ b/apps/streamd/internal/logfile/logfile.go @@ -64,34 +64,6 @@ 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 index b6acdff..f527d58 100644 --- a/apps/streamd/internal/modstore/modstore.go +++ b/apps/streamd/internal/modstore/modstore.go @@ -28,9 +28,6 @@ const ( 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"` @@ -390,7 +387,23 @@ func inspectZipReader(zr *zip.Reader, nameHint string) (string, []zipEntry, erro } if hint == "" { - hint = inferNameFromBinEntries(zr, prefix) + // Try to infer from .bin// or .bin/. + for _, f := range zr.File { + n := strings.ReplaceAll(f.Name, "\\", "/") + n = strings.TrimPrefix(n, "./") + if prefix != "" { + if !strings.HasPrefix(n, prefix) { + continue + } + n = strings.TrimPrefix(n, prefix) + } + base := filepath.Base(n) + base = strings.TrimSuffix(base, ".exe") + if strings.HasPrefix(n, ".bin/") && NameRe.MatchString(base) && base != ".bin" { + hint = base + break + } + } } if hint == "" { return "", nil, fmt.Errorf("cannot infer module name from zip; pass name=") @@ -463,47 +476,6 @@ func extractZipEntries(zipBytes []byte, entries []zipEntry, destDir string) erro 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) diff --git a/apps/streamd/internal/modstore/modstore_test.go b/apps/streamd/internal/modstore/modstore_test.go index bcd841c..edb3096 100644 --- a/apps/streamd/internal/modstore/modstore_test.go +++ b/apps/streamd/internal/modstore/modstore_test.go @@ -29,27 +29,6 @@ func makeZip(t *testing.T, files map[string][]byte) []byte { 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) diff --git a/apps/streamd/internal/supervisor/media.go b/apps/streamd/internal/supervisor/media.go index 8f7e8e8..91aa7c0 100644 --- a/apps/streamd/internal/supervisor/media.go +++ b/apps/streamd/internal/supervisor/media.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "path/filepath" + "runtime" "strconv" "strings" "sync" @@ -36,19 +37,12 @@ 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) @@ -61,13 +55,11 @@ 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 - nreLogFile *os.File // per-stream NRE log (banner + append) - nrePTY io.Closer // Linux PTY master; nil on Windows / fallback + nreLog *logfile.Writer ffOutLog *logfile.Writer ffErrLog *logfile.Writer stopping bool @@ -90,16 +82,15 @@ 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 - ProxyResolver ProxyResolver + Store *db.Store + DataDir string + NRE string + FFmpeg string + MP4Decrypt string + Log *slog.Logger + Fanout *tsfanout.Set + Notifier Notifier + ViewersFn func(streamName string) int } func NewMedia(opt Options) *Media { @@ -112,18 +103,17 @@ 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, - ProxyResolver: opt.ProxyResolver, - 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, + procs: map[int64]*streamProc{}, + stopMon: make(chan struct{}), } go m.monitorLoop() return m @@ -153,13 +143,6 @@ 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 { @@ -220,17 +203,12 @@ 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, originProxy) + srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, st.Proxy) if err != nil { m.fail(id, st.Name, "mpd rewrite server: "+err.Error()) return err @@ -258,10 +236,7 @@ func (m *Media) Start(id int64) error { "--tmp-dir", nreTmp, "--no-ansi-color", "--log-level", "ERROR", - // 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", + "-ss", "0", } if hasKeys { // Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so @@ -271,7 +246,7 @@ func (m *Media) Start(id int64) error { "--mp4-real-time-decryption", ) } - if proxy := strings.TrimSpace(originProxy); proxy != "" { + if proxy := strings.TrimSpace(st.Proxy); 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) @@ -298,24 +273,23 @@ func (m *Media) Start(id int64) error { } } - // 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( + // 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( 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)) @@ -332,37 +306,27 @@ func (m *Media) Start(id int64) error { nreEnv = prependPathEnv(nreEnv, strings.Join(pathPrepend, sep)) } nreCmd.Env = nreEnv - nrePTY, keepLogFD, err := startNRELogged(nreCmd, nreLogFile) - if err != nil { - if keepLogFD { - _ = nreLogFile.Close() - } + if err := nreCmd.Start(); err != nil { + _ = nreLog.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(), - sessionID: sessionID, - workDir: workDir, - wwwDir: wwwDir, - tsPath: tsPath, - hlsIndex: filepath.Join(wwwDir, "index.m3u8"), - nreLogFile: ownedLog, - nrePTY: nrePTY, - mpdProxy: mpdProxy, + 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, variantSpecs: variantSpecs, outputSpecs: outputSpecs, @@ -447,13 +411,12 @@ 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 data/logs/" + sp.name + "-nre.log", + LastError: "NRE exited before TS was ready — see 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 data/logs/" + sp.name + "-nre.log", + Message: "downloader exited before any media arrived — see logs/" + sp.name + "-nre.log", }) - m.closeSession(sp, db.SessionNREExit, "down") m.cleanupProc(sp.id) return } @@ -605,11 +568,9 @@ 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 { @@ -642,15 +603,6 @@ 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) @@ -670,15 +622,7 @@ func (m *Media) cleanupProc(id int64) { if !ok { return } - 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} { + for _, w := range []*logfile.Writer{sp.nreLog, sp.ffOutLog, sp.ffErrLog} { if w != nil { _ = w.Close() } @@ -730,14 +674,13 @@ 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 data/logs/" + sp.name + "-nre.log", + LastError: "NRE process exited — see 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 data/logs/%s-nre.log", uptime, sp.name), + Message: fmt.Sprintf("downloader exited after %.0fs — see 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 @@ -944,7 +887,11 @@ func killProcess(cmd *exec.Cmd) error { if cmd == nil || cmd.Process == nil { return nil } - return killProcessTree(cmd) + pid := cmd.Process.Pid + if runtime.GOOS == "windows" { + return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run() + } + return cmd.Process.Kill() } func prependPathEnv(env []string, prefix string) []string { @@ -967,20 +914,6 @@ 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/proc_unix.go b/apps/streamd/internal/supervisor/proc_unix.go index 832f76d..266175f 100644 --- a/apps/streamd/internal/supervisor/proc_unix.go +++ b/apps/streamd/internal/supervisor/proc_unix.go @@ -3,27 +3,13 @@ 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 { @@ -32,63 +18,3 @@ 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 bc95f5a..4de3aff 100644 --- a/apps/streamd/internal/supervisor/proc_windows.go +++ b/apps/streamd/internal/supervisor/proc_windows.go @@ -3,10 +3,8 @@ package supervisor import ( - "io" "os" "os/exec" - "strconv" "syscall" ) @@ -17,29 +15,6 @@ 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/ui/static/js/api.js b/apps/streamd/internal/ui/static/js/api.js index 1329da1..0c4816d 100644 --- a/apps/streamd/internal/ui/static/js/api.js +++ b/apps/streamd/internal/ui/static/js/api.js @@ -117,20 +117,6 @@ export const api = { patchSchedule: (sid, body) => api.patch(`/api/schedules/${sid}`, body), deleteSchedule: (sid) => api.del(`/api/schedules/${sid}`), - // --- egress tunnels --- - egress: () => api.get("/api/egress"), - egressProfiles: () => api.get("/api/egress"), - egressProfile: (name) => api.get(`/api/egress/${encodeURIComponent(name)}`), - createEgress: (body) => api.post("/api/egress", body), - saveEgress: (name, body) => api.put(`/api/egress/${encodeURIComponent(name)}`, body), - updateEgress: (name, body) => api.put(`/api/egress/${encodeURIComponent(name)}`, body), - deleteEgress: (name) => api.del(`/api/egress/${encodeURIComponent(name)}`), - egressUp: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/up`), - egressDown: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/down`), - egressTest: (name) => api.post(`/api/egress/${encodeURIComponent(name)}/test`), - egressConf: (name, conf) => - api.put(`/api/egress/${encodeURIComponent(name)}/conf`, { conf }), - // --- admin --- settings: () => api.get("/api/settings"), saveSettings: (body) => api.put("/api/settings", body), diff --git a/apps/streamd/internal/ui/static/js/store.js b/apps/streamd/internal/ui/static/js/store.js index b85bb65..1662ac7 100644 --- a/apps/streamd/internal/ui/static/js/store.js +++ b/apps/streamd/internal/ui/static/js/store.js @@ -15,7 +15,6 @@ export const state = { agents: [], deps: null, uptimeS: 0, - refreshedAt: 0, connected: false, lastError: "", }; @@ -58,7 +57,6 @@ export async function refresh(reason = "poll") { state.uptimeS = health.uptime_s || 0; if (health.deps) state.deps = health.deps; } - state.refreshedAt = Date.now(); state.lastError = ""; } catch (err) { state.lastError = err.message || String(err); diff --git a/apps/streamd/internal/ui/static/js/util.js b/apps/streamd/internal/ui/static/js/util.js index 3b2da13..ccceae2 100644 --- a/apps/streamd/internal/ui/static/js/util.js +++ b/apps/streamd/internal/ui/static/js/util.js @@ -36,11 +36,6 @@ export function el(spec, attrs, ...children) { else if (k === "dataset") Object.assign(node.dataset, v); else if (k === "style" && typeof v === "object") Object.assign(node.style, v); else if (k.startsWith("on") && typeof v === "function") node.addEventListener(k.slice(2), v); - // Form controls: set the live property. setAttribute("value") does not fill - //