Compare commits

...

4 commits
v0.2.0 ... main

Author SHA1 Message Date
404errordeveloper
5b6f38c9cf streamd v0.2.3: fix NRE Spectre crash under daemon (Linux PTY)
All checks were successful
release / build-and-upload (push) Successful in 6m56s
Wrap N_m3u8DL-RE with util-linux script so Spectre gets a real TTY; drop
subtitles; pin COLUMNS/LINES; kill process group on stop. Fixes immediate
'downloader exited before any media arrived' on serve start.
2026-10-10 19:54:41 +02:00
404errordeveloper
a091922efa streamd v0.2.2: session uptimes, egress DNS, Support, agent/Widevine
All checks were successful
release / build-and-upload (push) Successful in 7m2s
Dashboard Live uptimes + Recent runs from stream_sessions; overview.recent_sessions.
WireGuard netns resolv.conf + missing-deps WARN. Support donations card.
Agent start/stop/update, job_backoff default off, wvkey ensure/venv, phonecap retries,
modhost YAML enrich, DRM SetCredentials requires keys.
2026-10-10 19:26:39 +02:00
404errordeveloper
3ae1dd58b3 docs: add Streamd v0.2.1 release notes
All checks were successful
release / build-and-upload (push) Successful in 7m5s
Serve lifecycle, WireGuard/SOCKS egress, module panel fixes; streamd-* assets only.
2026-10-10 18:26:02 +02:00
404errordeveloper
8fc7e4c0b8 streamd: serve start/stop/update, streamd.yaml, egress, module panel fixes
- Add streamd serve start|stop|restart|status|update with auto-written streamd.yaml
- Panel modules: STREAMD_MODULES_DIR for describe, YAML channel fallback, textarea value fix
- Per-stream WireGuard/SOCKS egress profiles + Settings UI
- Drop drm-* from release builds; track streamd-bg.sh / streamd-update.sh wrappers
- Docs: streamd-server-setup lifecycle and update flow
2026-10-10 18:05:51 +02:00
88 changed files with 6678 additions and 421 deletions

View file

@ -1,4 +1,4 @@
# Build multi-platform streamd (+ drm compat) binaries + Android MITM and attach them to a Forgejo release.
# Build multi-platform streamd binaries + Android MITM and attach them to a Forgejo release.
#
# Triggers:
# Stable: git tag v1.2.3 && git push origin v1.2.3
@ -90,8 +90,6 @@ 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 |
@ -100,7 +98,6 @@ 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 |

4
.gitignore vendored
View file

@ -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 the release builders tracked for Forgejo Actions.
# Ignore local scripts, but keep release builders + server helpers tracked.
scripts/*
!scripts/build-release.sh
!scripts/build-release.ps1
@ -226,6 +226,8 @@ 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/**

View file

@ -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 (drm.exe also shipped as a compat copy)
streamd.exe # or ./streamd on Linux/macOS
bin/proxy-android-arm64 # optional; also embedded in the release binary
modules/ # or upload zips in the streamd Modules page
bbc/ # unzip bbc.zip here

View file

@ -28,14 +28,16 @@ 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 (operator API key from streamd Settings → API keys)
# terminal 2 — agent in the background (Linux / macOS / Windows)
export STREAMD_API_KEY=ndk_…
# or legacy: export STREAMD_TOKEN=…
./bin/streamd agent run --config apps/agent/agent.yaml
./bin/streamd agent start --config apps/agent/agent.yaml
./bin/streamd agent status --config apps/agent/agent.yaml
# foreground debug: ./bin/streamd agent run --config apps/agent/agent.yaml
# stop / restart: ./bin/streamd agent stop|restart --config …
# self-update: ./bin/streamd agent update [--beta] [--tag vX.Y.Z]
```
```bash
./bin/streamd agent status
./bin/streamd agent devices
./bin/streamd agent enqueue --stream tg4-ioi --reason manual
./bin/streamd agent cancel --job 3
@ -52,12 +54,18 @@ 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 `<data_dir>/modules`), `modules_sync_interval_sec`, `modules_prune`.
(default `<data_dir>/modules`), `modules_sync_interval_sec`, `modules_prune`,
`job_backoff` (default false — exponential delays only when several agents
share work), plus daemon fields `log_file`, `pid_file`, `channel`, `asset`,
`keep_old` for `agent start|stop|update`.
Create the key in the streamd dashboard (role **operator**). The legacy shared
`--token` / `STREAMD_TOKEN` still works but is meant for migration only.
`wvd` must be set or key fetches fail.
`wvd` must be set or key fetches fail. On first `agent start`/`run`, streamd
bootstraps `apps/wvkey/` and creates `<install>/.venv` with `pywidevine` using
the system Python (Windows, Linux, or macOS) so Widevine key fetch works without
a hand-made venv.
## Build

View file

@ -19,8 +19,18 @@ sync_modules: true
# modules_dir: # optional; default <data_dir>/modules
# modules_sync_interval_sec: 300
# modules_prune: false # delete local modules absent from the panel
# Required for key fetch. Relative paths resolve from the repo root
# (DRM-Decryption/), not from C:\Users\admin\Programming\.
wvd:
# Exponential retry delays (1m, 2m, 4m…). Default false — lone agents retry ASAP.
# Set true only when several agents share the same streams.
# job_backoff: false
# Background daemon (streamd agent start|stop|update):
# log_file: agent.log
# pid_file: agent.pid
# channel: stable # or beta — used by agent update
# asset: # optional streamd-* override
# keep_old: 10
# Required for key fetch. Relative paths resolve from the install/repo root.
# Agent auto-creates .venv + installs pywidevine on first run (Win/Linux/macOS).
# python: # optional override; default = <root>/.venv/…
wvd: data/device.wvd
# user_agent: "" # optional license-request User-Agent

View file

@ -9,6 +9,7 @@ import (
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"text/tabwriter"
@ -21,6 +22,8 @@ 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.
@ -36,6 +39,14 @@ func Run(args []string) error {
switch sub {
case "run":
runCmd(sub, rest)
case "start":
return startDaemonCmd(rest)
case "stop":
return stopDaemonCmd(rest)
case "restart":
return restartDaemonCmd(rest)
case "update":
return updateDaemonCmd(rest)
case "status":
statusCmd(sub, rest)
case "devices":
@ -58,8 +69,13 @@ func Usage() {
fmt.Fprintf(os.Stderr, `agent — always-on credentials refresher (queue + ADB)
Usage:
agent run [--config apps/agent/agent.yaml]
agent status [--config ...]
agent start [--config agent.yaml] # background (pid + log)
agent stop [--config ...]
agent restart [--config ...]
agent status [--config ...] # process + recent jobs
agent update [--config ...] [--beta] [--tag vX.Y.Z] [--no-restart]
agent run [--config ...] # foreground (debug)
agent devices [--config ...]
agent enqueue --stream NAME [--reason manual] [--config ...]
agent cancel --job ID [--config ...]
@ -68,6 +84,9 @@ Polls streamd for enabled streams that are down / missing credentials,
enqueues jobs, claims a free phone that already has the app, captures
via MITM, POSTs credentials, then force-stops the app.
Job retries default to immediate (job_backoff: false). Set job_backoff: true
in agent.yaml for exponential delays when several agents share work.
Does not install apps. Does not run NRE/ffmpeg.
`)
}
@ -117,6 +136,18 @@ func runCmd(sub string, args []string) {
"create an operator API key in the streamd dashboard", me.Role)
}
log.Printf("authenticated to streamd as %q (role %s)", me.Name, me.Role)
// Widevine keys need apps/wvkey + a local .venv (pywidevine). Create them
// once per install root so Windows / Linux / macOS agents all work.
if rt, err := wvkey.EnsureRuntime(repo.Root()); err != nil {
log.Fatalf("widevine helper: %v", err)
} else {
log.Printf("widevine helper ready python=%s script=%s", rt.Python, rt.Script)
if strings.TrimSpace(cfg.Python) == "" {
cfg.Python = rt.Python
}
}
q := openQueue(cfg)
defer q.Close()
@ -125,6 +156,16 @@ func runCmd(sub string, args []string) {
} else if n > 0 {
log.Printf("re-queued %d stuck running job(s) from previous run", n)
}
if n, err := q.ClearAllBackoffs(); err != nil {
log.Printf("clear backoffs: %v", err)
} else if n > 0 {
log.Printf("cleared backoff on %d queued job(s) — runnable now", n)
}
if cfg.JobBackoffEnabled() {
log.Printf("job_backoff=true (exponential delays after failures)")
} else {
log.Printf("job_backoff=false (retry failed captures immediately)")
}
pool := device.New("", cfg.Devices)
stop := make(chan struct{})
@ -205,6 +246,7 @@ func runCmd(sub string, args []string) {
Python: cfg.Python,
WVD: cfg.WVD,
UserAgent: cfg.UserAgent,
JobBackoff: cfg.JobBackoffEnabled(),
Log: log.Default(),
}
go w.Loop(stop)
@ -225,6 +267,7 @@ func runCmd(sub string, args []string) {
func statusCmd(sub string, args []string) {
cfg, _ := loadCfg(sub, args)
printDaemonStatus(cfg)
q := openQueue(cfg)
defer q.Close()
jobs, err := q.ListRecent(40)

View file

@ -0,0 +1,177 @@
package agentcmd
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"streamd/apps/agent/internal/config"
"streamd/repo"
)
func readPID(pidFile string) (int, error) {
b, err := os.ReadFile(pidFile)
if err != nil {
return 0, err
}
return strconv.Atoi(strings.TrimSpace(string(b)))
}
func writePID(pidFile string, pid int) error {
if err := os.MkdirAll(filepath.Dir(pidFile), 0o755); err != nil {
return err
}
return os.WriteFile(pidFile, []byte(strconv.Itoa(pid)+"\n"), 0o644)
}
func removePID(pidFile string) { _ = os.Remove(pidFile) }
func runningPID(cfg config.Config) (int, bool) {
pid, err := readPID(cfg.PIDFile)
if err != nil || pid <= 0 {
return 0, false
}
if !signalAlive(pid) {
removePID(cfg.PIDFile)
return pid, false
}
return pid, true
}
func printDaemonStatus(cfg config.Config) {
fmt.Printf("config: %s\n", cfgPathHint(cfg))
fmt.Printf("pid: %s\n", cfg.PIDFile)
fmt.Printf("log: %s\n", cfg.LogFile)
if pid, ok := runningPID(cfg); ok {
fmt.Printf("agent: running pid=%d\n", pid)
} else {
fmt.Println("agent: stopped")
}
}
func cfgPathHint(cfg config.Config) string {
// Best-effort: show data dir; exact yaml path was already resolved by Load.
return cfg.DataDir
}
func startDaemonCmd(args []string) error {
cfg, cfgFile := loadCfgWithPath("start", args)
if pid, ok := runningPID(cfg); ok {
fmt.Printf("agent already running (pid %d)\n", pid)
return nil
}
exe, err := os.Executable()
if err != nil {
return err
}
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
exe = resolved
}
runArgs := []string{"agent", "run"}
if cfgFile != "" {
runArgs = append(runArgs, "--config", cfgFile)
}
cmd := exec.Command(exe, runArgs...)
if err := os.MkdirAll(filepath.Dir(cfg.LogFile), 0o755); err != nil {
return err
}
logF, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
return err
}
cmd.Stdout = logF
cmd.Stderr = logF
cmd.Stdin = nil
detachProcess(cmd)
if err := cmd.Start(); err != nil {
_ = logF.Close()
return fmt.Errorf("start agent: %w", err)
}
pid := cmd.Process.Pid
_ = cmd.Process.Release()
_ = logF.Close()
if err := writePID(cfg.PIDFile, pid); err != nil {
return err
}
time.Sleep(400 * time.Millisecond)
if !signalAlive(pid) {
removePID(cfg.PIDFile)
return fmt.Errorf("agent exited immediately — see %s", cfg.LogFile)
}
fmt.Printf("agent started pid=%d\n", pid)
fmt.Printf("logs: %s\n", cfg.LogFile)
return nil
}
func stopDaemonCmd(args []string) error {
cfg, _ := loadCfgWithPath("stop", args)
pid, err := readPID(cfg.PIDFile)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("agent is not running")
return nil
}
return err
}
if !signalAlive(pid) {
removePID(cfg.PIDFile)
fmt.Println("agent is not running (stale pid file removed)")
return nil
}
if err := signalTerminate(pid); err != nil {
return fmt.Errorf("stop pid %d: %w", pid, err)
}
deadline := time.Now().Add(8 * time.Second)
for time.Now().Before(deadline) {
if !signalAlive(pid) {
removePID(cfg.PIDFile)
fmt.Printf("agent stopped (was pid %d)\n", pid)
return nil
}
time.Sleep(200 * time.Millisecond)
}
_ = signalKill(pid)
time.Sleep(200 * time.Millisecond)
removePID(cfg.PIDFile)
fmt.Printf("agent killed (pid %d)\n", pid)
return nil
}
func restartDaemonCmd(args []string) error {
_ = stopDaemonCmd(args)
return startDaemonCmd(args)
}
// loadCfgWithPath returns config and the resolved --config path (may be empty).
func loadCfgWithPath(sub string, args []string) (config.Config, string) {
fs := flag.NewFlagSet(sub, flag.ExitOnError)
cfgPath := fs.String("config", "", "path to agent.yaml")
_ = fs.Parse(args)
path := strings.TrimSpace(*cfgPath)
cfg, err := config.Load(path)
if err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
if path == "" {
// Mirror config.Load default discovery for daemon child argv.
path = defaultConfigPath()
} else if !filepath.IsAbs(path) {
abs, err := filepath.Abs(path)
if err == nil {
path = abs
}
}
return cfg, path
}
// defaultConfigPath matches config.Load("") discovery so the background child
// reopens the same yaml the parent resolved.
func defaultConfigPath() string {
return filepath.Join(repo.Root(), "apps", "agent", "agent.yaml")
}

View file

@ -0,0 +1,37 @@
//go:build unix
package agentcmd
import (
"os"
"os/exec"
"syscall"
)
func detachProcess(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
}
func signalAlive(pid int) bool {
p, err := os.FindProcess(pid)
if err != nil {
return false
}
return p.Signal(syscall.Signal(0)) == nil
}
func signalTerminate(pid int) error {
p, err := os.FindProcess(pid)
if err != nil {
return err
}
return p.Signal(syscall.SIGTERM)
}
func signalKill(pid int) error {
p, err := os.FindProcess(pid)
if err != nil {
return err
}
return p.Signal(syscall.SIGKILL)
}

View file

@ -0,0 +1,46 @@
//go:build windows
package agentcmd
import (
"os"
"os/exec"
"syscall"
"golang.org/x/sys/windows"
)
func detachProcess(cmd *exec.Cmd) {
// CREATE_NEW_PROCESS_GROUP so stop can target the child; keep stdio so
// stdout/stderr still reach the log file opened by the parent.
cmd.SysProcAttr = &syscall.SysProcAttr{
CreationFlags: windows.CREATE_NEW_PROCESS_GROUP,
}
}
func signalAlive(pid int) bool {
// On Windows, FindProcess always succeeds; use OpenProcess exit code instead.
h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, uint32(pid))
if err != nil {
return false
}
defer windows.CloseHandle(h)
var code uint32
if err := windows.GetExitCodeProcess(h, &code); err != nil {
return false
}
const stillActive = 259 // STILL_ACTIVE
return code == stillActive
}
func signalTerminate(pid int) error {
p, err := os.FindProcess(pid)
if err != nil {
return err
}
return p.Kill()
}
func signalKill(pid int) error {
return signalTerminate(pid)
}

View file

@ -0,0 +1,282 @@
package agentcmd
import (
"flag"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
"streamd/apps/agent/internal/config"
"streamd/repo"
)
const (
releaseBaseURL = "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download"
defaultChannel = "stable"
)
// errUpdateDeferred means the binary swap finishes after process exit (Windows self-update).
var errUpdateDeferred = fmt.Errorf("update deferred until process exit")
func defaultAssetName() string {
switch runtime.GOOS {
case "linux":
switch runtime.GOARCH {
case "amd64":
return "streamd-linux-amd64"
case "arm64":
return "streamd-linux-arm64"
}
case "darwin":
switch runtime.GOARCH {
case "amd64":
return "streamd-darwin-amd64"
case "arm64":
return "streamd-darwin-arm64"
}
case "windows":
switch runtime.GOARCH {
case "amd64":
return "streamd-windows-amd64.exe"
case "arm64":
return "streamd-windows-arm64.exe"
}
}
return ""
}
func updateURL(base, ref, asset string) string {
base = strings.TrimRight(base, "/")
return fmt.Sprintf("%s/%s/%s", base, ref, asset)
}
func updateDaemonCmd(args []string) error {
fs := flag.NewFlagSet("update", flag.ExitOnError)
cfgPath := fs.String("config", "", "path to agent.yaml")
beta := fs.Bool("beta", false, "use beta channel")
tag := fs.String("tag", "", "pin to release tag (e.g. v0.2.1)")
noRestart := fs.Bool("no-restart", false, "install only; do not start agent")
keep := fs.Int("keep", -1, "archived binaries to keep under old/ (-1 = config)")
_ = fs.Parse(args)
path := strings.TrimSpace(*cfgPath)
cfg, err := config.Load(path)
if err != nil {
return err
}
if path == "" {
path = defaultConfigPath()
} else if !filepath.IsAbs(path) {
if abs, err := filepath.Abs(path); err == nil {
path = abs
}
}
channel := cfg.Channel
if channel == "" {
channel = defaultChannel
}
if *beta {
channel = "beta"
}
ref := channel
if strings.TrimSpace(*tag) != "" {
ref = strings.TrimSpace(*tag)
}
asset := cfg.Asset
if asset == "" {
asset = defaultAssetName()
}
if asset == "" {
return fmt.Errorf("unsupported platform %s/%s — set asset: in agent.yaml", runtime.GOOS, runtime.GOARCH)
}
keepN := 10
if cfg.KeepOld != nil {
keepN = *cfg.KeepOld
}
if *keep >= 0 {
keepN = *keep
}
installRoot := repo.Root()
url := updateURL(releaseBaseURL, ref, asset)
fmt.Printf("agent update: downloading %s\n", url)
tmp, err := downloadToTemp(installRoot, url)
if err != nil {
return err
}
defer os.Remove(tmp)
if err := smokeTestBinary(tmp); err != nil {
return err
}
exe, err := os.Executable()
if err != nil {
return err
}
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
exe = resolved
}
target := exe
wantName := "streamd"
if runtime.GOOS == "windows" {
wantName = "streamd.exe"
}
// Prefer well-known names in the install / Downloads tree.
for _, candidate := range []string{
filepath.Join(installRoot, wantName),
filepath.Join(installRoot, "streamd-windows-amd64.exe"),
filepath.Join(installRoot, "streamd-linux-amd64"),
filepath.Join(installRoot, "bin", wantName),
} {
if st, err := os.Stat(candidate); err == nil && !st.IsDir() {
target = candidate
break
}
}
// If the running exe is already a streamd binary in this tree, prefer it.
if strings.Contains(strings.ToLower(filepath.Base(exe)), "streamd") {
if st, err := os.Stat(exe); err == nil && !st.IsDir() {
target = exe
}
}
if _, ok := runningPID(cfg); ok {
fmt.Println("agent update: stopping running agent…")
if err := stopDaemonCmd([]string{"--config", path}); err != nil {
return err
}
}
oldDir := filepath.Join(filepath.Dir(target), "old")
if err := os.MkdirAll(oldDir, 0o755); err != nil {
return err
}
stamp := time.Now().UTC().Format("20060102T150405Z")
archive := filepath.Join(oldDir, "streamd."+stamp)
if runtime.GOOS == "windows" {
archive += ".exe"
}
if _, err := os.Stat(archive); err == nil {
archive += "." + fmt.Sprint(os.Getpid())
}
if *noRestart {
_ = os.Setenv("STREAMD_UPDATE_RESTART", "0")
} else {
_ = os.Setenv("STREAMD_UPDATE_RESTART", "1")
_ = os.Setenv("STREAMD_UPDATE_AGENT_CONFIG", path)
}
if err := replaceBinary(target, tmp, archive); err != nil {
if err == errUpdateDeferred {
return nil // helper finishes after exit; treat as success for CLI
}
return err
}
fmt.Printf("agent update: archived previous → %s\n", archive)
fmt.Printf("agent update: installed %s (%s)\n", target, ref)
pruneOldBinaries(oldDir, keepN)
if *noRestart {
fmt.Println("agent update: done (--no-restart). Start with: streamd agent start")
return nil
}
fmt.Println("agent update: starting…")
return startDaemonCmd([]string{"--config", path})
}
func downloadToTemp(dir, url string) (string, error) {
if err := os.MkdirAll(dir, 0o755); err != nil {
return "", err
}
f, err := os.CreateTemp(dir, ".streamd-download-*")
if err != nil {
return "", err
}
path := f.Name()
resp, err := http.Get(url)
if err != nil {
_ = f.Close()
_ = os.Remove(path)
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
_ = f.Close()
_ = os.Remove(path)
return "", fmt.Errorf("download %s: HTTP %s", url, resp.Status)
}
n, err := io.Copy(f, resp.Body)
closeErr := f.Close()
if err != nil {
_ = os.Remove(path)
return "", err
}
if closeErr != nil {
_ = os.Remove(path)
return "", closeErr
}
if n < 1024 {
_ = os.Remove(path)
return "", fmt.Errorf("download too small (%d bytes) — check URL %s", n, url)
}
head, _ := os.ReadFile(path)
if len(head) > 32 {
h := strings.ToLower(string(head[:32]))
if strings.Contains(h, "<!doctype") || strings.Contains(h, "<html") {
_ = os.Remove(path)
return "", fmt.Errorf("download looks like HTML, not a binary: %s", url)
}
}
_ = os.Chmod(path, 0o755)
return path, nil
}
func smokeTestBinary(path string) error {
cmd := exec.Command(path, "help")
out, err := cmd.CombinedOutput()
text := string(out)
if err != nil {
if !strings.Contains(text, "serve") && !strings.Contains(text, "agent") && !strings.Contains(text, "streamd") {
return fmt.Errorf("new binary failed smoke test: %w\n%s", err, out)
}
}
return nil
}
func pruneOldBinaries(oldDir string, keep int) {
if keep <= 0 {
return
}
ents, err := os.ReadDir(oldDir)
if err != nil {
return
}
var names []string
for _, e := range ents {
if e.IsDir() {
continue
}
n := e.Name()
if strings.HasPrefix(n, "streamd.") {
names = append(names, n)
}
}
sort.Strings(names)
if len(names) <= keep {
return
}
for _, n := range names[:len(names)-keep] {
_ = os.Remove(filepath.Join(oldDir, n))
fmt.Printf("agent update: pruned %s\n", filepath.Join(oldDir, n))
}
}

View file

@ -0,0 +1,21 @@
//go:build unix
package agentcmd
import (
"fmt"
"os"
)
// replaceBinary moves the live binary to archive, then moves next into place.
func replaceBinary(target, next, archive string) error {
if err := os.Rename(target, archive); err != nil {
return fmt.Errorf("archive current binary: %w", err)
}
if err := os.Rename(next, target); err != nil {
_ = os.Rename(archive, target)
return fmt.Errorf("install new binary: %w", err)
}
_ = os.Chmod(target, 0o755)
return nil
}

View file

@ -0,0 +1,125 @@
//go:build windows
package agentcmd
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"time"
)
// replaceBinary on Windows cannot overwrite the running updater exe. Strategy:
// 1. Move target → archive when target is not our own running image.
// 2. If target is us, write next beside as *.new and spawn a helper cmd that
// waits for this PID to exit, then swaps and optionally starts the agent.
func replaceBinary(target, next, archive string) error {
self, _ := os.Executable()
if resolved, err := filepath.EvalSymlinks(self); err == nil {
self = resolved
}
same, _ := sameFile(self, target)
if !same {
if err := os.Rename(target, archive); err != nil {
if err2 := copyFile(target, archive); err2 != nil {
return fmt.Errorf("archive current binary: %v / %w", err, err2)
}
_ = os.Remove(target)
}
if err := os.Rename(next, target); err != nil {
if err2 := copyFile(next, target); err2 != nil {
_ = os.Rename(archive, target)
return fmt.Errorf("install new binary: %v / %w", err, err2)
}
_ = os.Remove(next)
}
return nil
}
newPath := target + ".new"
_ = os.Remove(newPath)
if err := os.Rename(next, newPath); err != nil {
if err2 := copyFile(next, newPath); err2 != nil {
return fmt.Errorf("stage new binary: %v / %w", err, err2)
}
_ = os.Remove(next)
}
helper := filepath.Join(filepath.Dir(target), "streamd-agent-update-finish.cmd")
pid := os.Getpid()
startLine := ""
if os.Getenv("STREAMD_UPDATE_RESTART") != "0" {
cfg := os.Getenv("STREAMD_UPDATE_AGENT_CONFIG")
if cfg != "" {
startLine = fmt.Sprintf("\"%s\" agent start --config \"%s\"\r\n", escapeCmd(target), escapeCmd(cfg))
} else {
startLine = fmt.Sprintf("\"%s\" agent start\r\n", escapeCmd(target))
}
}
script := fmt.Sprintf(""+
"@echo off\r\n"+
":wait\r\n"+
"timeout /t 1 /nobreak >nul\r\n"+
"tasklist /FI \"PID eq %d\" 2>nul | find \"%d\" >nul\r\n"+
"if not errorlevel 1 goto wait\r\n"+
"move /Y \"%s\" \"%s\"\r\n"+
"move /Y \"%s\" \"%s\"\r\n"+
"%s"+
"del \"%%~f0\"\r\n",
pid, pid,
escapeCmd(target), escapeCmd(archive),
escapeCmd(newPath), escapeCmd(target),
startLine,
)
if err := os.WriteFile(helper, []byte(script), 0o644); err != nil {
return err
}
cmd := exec.Command("cmd.exe", "/C", helper)
cmd.Stdout = nil
cmd.Stderr = nil
detachProcess(cmd)
if err := cmd.Start(); err != nil {
return fmt.Errorf("start update helper: %w", err)
}
_ = cmd.Process.Release()
fmt.Println("agent update: scheduled file swap after this process exits")
fmt.Println("agent update: agent will restart automatically in 1–2s")
time.Sleep(300 * time.Millisecond)
return errUpdateDeferred
}
func escapeCmd(p string) string {
return p
}
func sameFile(a, b string) (bool, error) {
absA, err := filepath.Abs(a)
if err != nil {
return false, err
}
absB, err := filepath.Abs(b)
if err != nil {
return false, err
}
return filepath.Clean(absA) == filepath.Clean(absB), nil
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)
if err != nil {
return err
}
_, copyErr := out.ReadFrom(in)
closeErr := out.Close()
if copyErr != nil {
return copyErr
}
return closeErr
}

View file

@ -36,6 +36,16 @@ 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.
@ -44,6 +54,12 @@ func (c Config) PushedCapturesArePriority() bool {
return c.OnDemandPriority == nil || *c.OnDemandPriority
}
// JobBackoffEnabled is the exponential multi-agent retry delay.
// Defaults to false so a lone agent retries immediately after a failure.
func (c Config) JobBackoffEnabled() bool {
return c.JobBackoff != nil && *c.JobBackoff
}
func (c Config) PollInterval() time.Duration {
if c.PollIntervalSec <= 0 {
return 30 * time.Second
@ -125,6 +141,9 @@ 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) {
@ -133,6 +152,25 @@ 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
}

View file

@ -232,17 +232,18 @@ func (s *Store) MarkOK(id int64) error {
return err
}
// MarkFailed increments attempts. Re-queues with backoff unless maxed out.
// MarkFailed increments attempts. Re-queues unless maxed out.
// waitingDevice=true keeps status queued without burning an attempt.
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool) error {
// backoff is how long to wait before the job is runnable again (0 = immediate).
func (s *Store) MarkFailed(id int64, msg string, waitingDevice bool, backoff time.Duration) error {
j, err := s.Get(id)
if err != nil {
return err
}
if waitingDevice {
_, err = s.DB.Exec(`
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='' WHERE id=?`,
msg, id)
UPDATE jobs SET status='queued', device_serial='', last_error=?, started_at='', not_before=? WHERE id=?`,
msg, now(), id)
return err
}
attempts := j.Attempts + 1
@ -252,9 +253,8 @@ UPDATE jobs SET status='failed', attempts=?, last_error=?, finished_at=? WHERE i
attempts, msg, now(), id)
return err
}
backoff := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
if backoff > 15*time.Minute {
backoff = 15 * time.Minute
if backoff < 0 {
backoff = 0
}
nb := time.Now().UTC().Add(backoff).Format(time.RFC3339)
_, err = s.DB.Exec(`
@ -263,6 +263,29 @@ UPDATE jobs SET status='queued', attempts=?, last_error=?, not_before=?, device_
return err
}
// ExponentialBackoff is the old multi-agent delay: 1m, 2m, 4m, 8m (cap 15m).
func ExponentialBackoff(attempts int) time.Duration {
if attempts < 1 {
attempts = 1
}
d := time.Duration(1<<uint(min(attempts, 4))) * time.Minute
if d > 15*time.Minute {
d = 15 * time.Minute
}
return d
}
// ClearAllBackoffs makes every queued job runnable now (e.g. agent restart
// after fixing modules, or when job_backoff is disabled).
func (s *Store) ClearAllBackoffs() (int, error) {
res, err := s.DB.Exec(`UPDATE jobs SET not_before=? WHERE status='queued'`, now())
if err != nil {
return 0, err
}
n, _ := res.RowsAffected()
return int(n), nil
}
func min(a, b int) int {
if a < b {
return a

View file

@ -27,7 +27,10 @@ type Worker struct {
Python string
WVD string
UserAgent string
Log *log.Logger
// JobBackoff enables exponential delays between failed capture attempts.
// When false (default), failed jobs are re-queued immediately.
JobBackoff bool
Log *log.Logger
lastDelayLog time.Time
}
@ -67,13 +70,18 @@ func (w *Worker) tick() {
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
// Config/environment issues — do not burn attempts or multi-minute backoff.
w.logf("job=%d waiting: %v", job.ID, err)
_ = w.Queue.MarkFailed(job.ID, err.Error(), true)
_ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
return
}
w.logf("job=%d failed: %v", job.ID, err)
w.event(job, client.EventCaptureFailed, err.Error(),
map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
_ = w.Queue.MarkFailed(job.ID, err.Error(), false)
backoff := time.Duration(0)
if w.JobBackoff {
backoff = queue.ExponentialBackoff(job.Attempts + 1)
w.logf("job=%d re-queue in %s (job_backoff=true)", job.ID, backoff)
}
_ = w.Queue.MarkFailed(job.ID, err.Error(), false, backoff)
return
}
_ = w.Queue.MarkOK(job.ID)
@ -119,8 +127,8 @@ func (w *Worker) runJob(job queue.Job) error {
_ = w.Queue.SetDevice(job.ID, serial)
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
// Short TTL; /ws/agent heartbeats renew while this process is alive.
if err := w.API.Claim(job.StreamID, w.AgentID, 90); err != nil {
// Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
return fmt.Errorf("streamd claim: %w", err)
}
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
@ -140,6 +148,19 @@ func (w *Worker) runJob(job queue.Job) error {
return err
}
needsKeys := true
if km := strings.ToLower(strings.TrimSpace(a.KeyMode())); km == "none" || km == "clear" {
needsKeys = false
}
hasKey := poller.ValidKeyPair(res.Key)
if needsKeys && !hasKey {
return fmt.Errorf("refusing to post credentials without valid Widevine key (got mpd=%q key_empty=%v)",
trimURL(res.MPD), strings.TrimSpace(res.Key) == "")
}
if strings.TrimSpace(res.MPD) == "" {
return fmt.Errorf("refusing to post credentials without mpd")
}
cred := client.Credentials{
MPD: res.MPD,
Key: res.Key,
@ -150,15 +171,25 @@ func (w *Worker) runJob(job queue.Job) error {
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
return fmt.Errorf("post credentials: %w", err)
}
w.logf("job=%d posted credentials to streamd has_key=%v key_valid=%v mpd=%s",
job.ID, strings.TrimSpace(res.Key) != "", hasKey, trimURL(res.MPD))
// Report what was captured, never the key itself.
w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
"device": serial,
"has_key": strings.TrimSpace(res.Key) != "",
"key_valid": poller.ValidKeyPair(res.Key),
"key_valid": hasKey,
})
return nil
}
func trimURL(s string) string {
s = strings.TrimSpace(s)
if len(s) <= 96 {
return s
}
return s[:96] + "…"
}
// event posts a stream event to streamd. A timeline entry is never worth
// failing a capture over, so errors are logged and dropped.
func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {

View file

@ -2,7 +2,6 @@
// catalog lookups, the always-on agent, the streamd control plane and the
// on-device MITM. Providers live under modules/<name>/ and are discovered,
// built, and executed by the host — they are not linked into this binary.
// A drm.exe copy of this binary is still shipped for one release as a compat alias.
package main
import (
@ -110,7 +109,8 @@ 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 [--bind …] [--data …] [--token …]
streamd serve start|stop|restart|status|update|run [flags]
streamd serve [--bind …] [--data …] # foreground (same as run)
streamd proxy build|push|install-ca|start|stop|reset|discover|pull|clear-proxy|transparent
Global flags:
@ -120,8 +120,6 @@ Providers live under modules/<name>/ (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.
`)
}

View file

@ -92,7 +92,6 @@ 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
}
@ -105,10 +104,7 @@ func ensureBinHost(root string) error {
return nil
}
exe, _ = filepath.EvalSymlinks(exe)
if err := copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe")); err != nil {
return err
}
return copyExeIfMissing(exe, filepath.Join(root, "bin", "drm.exe"))
return copyExeIfMissing(exe, filepath.Join(root, "bin", "streamd.exe"))
}
func copyExeIfMissing(src, dest string) error {

View file

@ -0,0 +1,6 @@
# Dependencies for wvkey.py (the only Python in the project).
# Install into a venv at the repo root:
# python -m venv .venv
# .venv/bin/pip install -r apps/wvkey/requirements.txt
pywidevine==1.9.0
requests==2.34.2

View file

@ -0,0 +1,367 @@
#!/usr/bin/env python3
"""Thin Widevine CDM helper for the Go capture tooling.
Prints a single CONTENT key as KID:KEY on stdout (no banners) when --quiet.
Exit code 0 on success.
Example:
.venv/Scripts/python.exe wvkey.py \\
--wvd path/to/device.wvd \\
--pssh 'AAAA…' \\
--license-url 'https://…' \\
--auth 'Basic …' \\
--pid 'xxxx' \\
--quiet
"""
from __future__ import annotations
import argparse
import base64
import json
import sys
from pathlib import Path
import requests
from pywidevine.cdm import Cdm
from pywidevine.device import Device
from pywidevine.pssh import PSSH
def fetch_content_keys_modulardrm(
*,
wvd: Path,
pssh_b64: str,
auth: str,
release_pid: str,
license_url: str,
user_agent: str,
) -> list[str]:
"""RTE / thePlatform ModularDrm (JSON challenge wrapper)."""
device = Device.load(str(wvd))
cdm = Cdm.from_device(device)
session_id = cdm.open()
try:
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
challenge_b64 = base64.b64encode(challenge).decode("utf-8")
payload = {
"getWidevineLicense": {
"releasePid": release_pid,
"widevineChallenge": challenge_b64,
}
}
headers = {
"Accept-Encoding": "gzip",
"Authorization": auth,
"Content-Type": "application/json; charset=utf-8",
}
if user_agent:
headers["User-Agent"] = user_agent
response = requests.post(license_url, json=payload, headers=headers, timeout=30)
data = response.json()
if data.get("isException"):
raise RuntimeError(data.get("description") or "license server exception")
license_b64 = (
data.get("getWidevineLicenseResponse", {}).get("license")
or data.get("license")
)
if not license_b64:
raise RuntimeError("no license in response: " + json.dumps(data)[:1500])
cdm.parse_license(session_id, base64.b64decode(license_b64))
keys = [
f"{key.kid.hex}:{key.key.hex()}"
for key in cdm.get_keys(session_id)
if key.type == "CONTENT"
]
finally:
cdm.close(session_id)
if not keys:
raise RuntimeError("no CONTENT keys")
return keys
def fetch_content_keys_raw(
*,
wvd: Path,
pssh_b64: str,
license_url: str,
user_agent: str,
) -> list[str]:
"""Brightcove / generic Widevine: POST raw challenge, parse raw license body."""
device = Device.load(str(wvd))
cdm = Cdm.from_device(device)
session_id = cdm.open()
try:
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
headers = {
"Content-Type": "application/octet-stream",
"Accept": "*/*",
}
if user_agent:
headers["User-Agent"] = user_agent
response = requests.post(
license_url, data=challenge, headers=headers, timeout=30
)
if response.status_code >= 400:
raise RuntimeError(
f"license HTTP {response.status_code}: {response.text[:500]!r}"
)
body = response.content
if not body:
raise RuntimeError("empty license response body")
# Some servers wrap base64 text; try raw first, then b64.
try:
cdm.parse_license(session_id, body)
except Exception:
try:
cdm.parse_license(session_id, base64.b64decode(body))
except Exception as exc:
raise RuntimeError(
f"parse_license failed ({len(body)} bytes): {exc}"
) from exc
keys = [
f"{key.kid.hex}:{key.key.hex()}"
for key in cdm.get_keys(session_id)
if key.type == "CONTENT"
]
finally:
cdm.close(session_id)
if not keys:
raise RuntimeError("no CONTENT keys")
return keys
_CHALLENGE_KEYS = (
"request",
"licenseRequest",
"license_request",
"widevineChallenge",
"widevine_challenge",
"challenge",
"payload",
"rawLicenseRequestBase64",
"message",
"drm_info",
)
def _replace_challenge(obj, challenge_b64: str, challenge_bytes: bytes) -> bool:
"""Replace the Widevine challenge field inside a captured JSON license body."""
if isinstance(obj, dict):
for key in _CHALLENGE_KEYS:
if key not in obj:
continue
val = obj[key]
if key == "drm_info" and isinstance(val, list):
obj[key] = list(challenge_bytes)
return True
if isinstance(val, str) and len(val) >= 8:
obj[key] = challenge_b64
return True
if isinstance(val, dict) and _replace_challenge(val, challenge_b64, challenge_bytes):
return True
for val in obj.values():
if _replace_challenge(val, challenge_b64, challenge_bytes):
return True
elif isinstance(obj, list):
for item in obj:
if _replace_challenge(item, challenge_b64, challenge_bytes):
return True
return False
def _license_bytes_from_response(response: requests.Response) -> bytes:
body = response.content
if not body:
raise RuntimeError("empty license response body")
# Prefer JSON wrappers used by RedBee / ModularDrm-style proxies.
try:
data = response.json()
except Exception:
data = None
if isinstance(data, dict):
for path in (
("license",),
("licenseResponse",),
("license_response",),
("payload",),
("message",),
("getWidevineLicenseResponse", "license"),
("status", "license"),
):
cur: object = data
ok = True
for key in path:
if not isinstance(cur, dict) or key not in cur:
ok = False
break
cur = cur[key]
if ok and isinstance(cur, str) and cur:
try:
return base64.b64decode(cur)
except Exception:
return cur.encode("utf-8")
# Some LSP responses nest the blob under status.success payload.
if data.get("status", {}).get("success") is False:
raise RuntimeError("license LSP error: " + json.dumps(data)[:500])
return body
def fetch_content_keys_wrap(
*,
wvd: Path,
pssh_b64: str,
license_url: str,
wrap_json: str,
user_agent: str,
) -> list[str]:
"""Re-POST a captured JSON license body with a fresh local CDM challenge.
Used by Channel 4 / RedBee (wvlicenceproxy-service) which reject raw
octet-stream (HTTP 415) and need the phone's token fields intact.
"""
try:
template = json.loads(wrap_json)
except Exception as exc:
raise RuntimeError(f"wrap-json is not valid JSON: {exc}") from exc
device = Device.load(str(wvd))
cdm = Cdm.from_device(device)
session_id = cdm.open()
try:
challenge = cdm.get_license_challenge(session_id, PSSH(pssh_b64))
challenge_b64 = base64.b64encode(challenge).decode("utf-8")
if not _replace_challenge(template, challenge_b64, challenge):
raise RuntimeError(
"wrap-json has no recognisable challenge field "
f"(tried {', '.join(_CHALLENGE_KEYS)})"
)
headers = {
"Content-Type": "application/json",
"Accept": "application/json, */*",
}
if user_agent:
headers["User-Agent"] = user_agent
response = requests.post(
license_url, json=template, headers=headers, timeout=30
)
if response.status_code >= 400:
raise RuntimeError(
f"license HTTP {response.status_code}: {response.text[:500]!r}"
)
license_bytes = _license_bytes_from_response(response)
try:
cdm.parse_license(session_id, license_bytes)
except Exception:
try:
cdm.parse_license(session_id, base64.b64decode(license_bytes))
except Exception as exc:
raise RuntimeError(
f"parse_license failed ({len(license_bytes)} bytes): {exc}"
) from exc
keys = [
f"{key.kid.hex}:{key.key.hex()}"
for key in cdm.get_keys(session_id)
if key.type == "CONTENT"
]
finally:
cdm.close(session_id)
if not keys:
raise RuntimeError("no CONTENT keys")
return keys
def main(argv: list[str] | None = None) -> int:
p = argparse.ArgumentParser(description="Widevine CDM helper → KID:KEY")
p.add_argument("--wvd", type=Path, required=True, help="Path to .wvd device file")
p.add_argument("--pssh", required=True, help="Base64 PSSH box")
p.add_argument(
"--mode",
choices=("modulardrm", "raw", "wrap"),
default="modulardrm",
help="modulardrm=RTE JSON; raw=octet-stream; wrap=captured JSON body",
)
p.add_argument("--auth", default="", help="Authorization header (modulardrm)")
p.add_argument("--pid", default="", help="releasePid (modulardrm)")
p.add_argument(
"--wrap-json",
default="",
help="Captured phone license POST JSON (wrap mode)",
)
p.add_argument(
"--license-url",
required=True,
help="Widevine license server URL",
)
p.add_argument(
"--user-agent",
default="",
help="Optional User-Agent for the license request",
)
p.add_argument(
"--quiet",
action="store_true",
help="Print only KID:KEY lines (for Go tooling)",
)
p.add_argument(
"--all",
action="store_true",
help="Print every CONTENT key (default: first only)",
)
args = p.parse_args(argv)
if not args.wvd.is_file():
print(f"[!] missing WVD: {args.wvd}", file=sys.stderr)
return 2
try:
if args.mode == "raw":
keys = fetch_content_keys_raw(
wvd=args.wvd,
pssh_b64=args.pssh,
license_url=args.license_url,
user_agent=args.user_agent,
)
elif args.mode == "wrap":
if not args.wrap_json.strip():
print(
"[!] --wrap-json required for wrap mode "
"(phone must complete a license POST during capture)",
file=sys.stderr,
)
return 2
keys = fetch_content_keys_wrap(
wvd=args.wvd,
pssh_b64=args.pssh,
license_url=args.license_url,
wrap_json=args.wrap_json,
user_agent=args.user_agent,
)
else:
if not args.auth or not args.pid:
print("[!] --auth and --pid required for modulardrm mode", file=sys.stderr)
return 2
keys = fetch_content_keys_modulardrm(
wvd=args.wvd,
pssh_b64=args.pssh,
auth=args.auth,
release_pid=args.pid,
license_url=args.license_url,
user_agent=args.user_agent,
)
except Exception as exc:
print(f"[!] {exc}", file=sys.stderr)
return 1
out = keys if args.all else keys[:1]
if not args.quiet:
print("[+] Keys:", file=sys.stderr)
for pair in out:
print(f"--key {pair}", file=sys.stderr)
for pair in out:
print(pair)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View file

@ -21,7 +21,8 @@ import (
)
// Dir returns the directory holding a module's values.
// Prefers the active modules dir (see modhost / --modules-dir); falls back to
// Prefers the active modules dir (see modhost / --modules-dir); then the
// directory beside a panel/release binary (<mod>/.bin/<name>); then
// apps/modules/<name>/ for older checkouts.
func Dir(name string) string {
preferred := filepath.Join(modhost.ModulesDir(""), name)
@ -31,6 +32,9 @@ func Dir(name string) string {
if modhost.ModulesDirOverride() != "" {
return preferred
}
if beside := dirBesideExecutable(name); beside != "" {
return beside
}
root := repo.Root()
if _, err := os.Stat(filepath.Join(root, "modules")); err == nil {
return filepath.Join(root, "modules", name)
@ -38,6 +42,43 @@ func Dir(name string) string {
return filepath.Join(root, "apps", "modules", name)
}
// dirBesideExecutable finds module.yaml next to a panel/release binary layout:
// <modDir>/.bin/<name>[.exe]
// <modDir>/.bin/<goos>-<goarch>/<name>[.exe]
func dirBesideExecutable(name string) string {
exe, err := os.Executable()
if err != nil {
return ""
}
if resolved, err := filepath.EvalSymlinks(exe); err == nil {
exe = resolved
}
base := strings.TrimSuffix(filepath.Base(exe), ".exe")
if !strings.EqualFold(base, name) {
return ""
}
binDir := filepath.Dir(exe)
candidates := []string{}
if strings.EqualFold(filepath.Base(binDir), ".bin") {
candidates = append(candidates, filepath.Dir(binDir))
}
parent := filepath.Dir(binDir)
if strings.EqualFold(filepath.Base(parent), ".bin") {
candidates = append(candidates, filepath.Dir(parent))
}
for _, dir := range candidates {
if fileExists(filepath.Join(dir, "module.yaml")) || fileExists(filepath.Join(dir, "module-publish.yaml")) {
return dir
}
}
return ""
}
func fileExists(p string) bool {
st, err := os.Stat(p)
return err == nil && !st.IsDir()
}
// Path returns the preferred values file path (module.yaml).
func Path(name string) string {
return filepath.Join(Dir(name), "module.yaml")

View file

@ -9,9 +9,39 @@ import (
"strings"
)
// prepareModuleCmd sets STREAMD_MODULES_DIR so child module binaries load
// panel-store module.yaml. Module builds that call EffectiveModulesDir (or
// ApplyEnvModulesDir) honour this; /api/apps also falls back to parsing the
// panel module.yaml when describe returns no channels.
func prepareModuleCmd(cmd *exec.Cmd) {
ov := ModulesDirOverride()
if ov == "" {
return
}
cmd.Env = append(withoutEnvKeys(os.Environ(), "STREAMD_MODULES_DIR", "DRM_MODULES_DIR"),
"STREAMD_MODULES_DIR="+ov)
}
func withoutEnvKeys(env []string, keys ...string) []string {
drop := map[string]struct{}{}
for _, k := range keys {
drop[strings.ToUpper(k)] = struct{}{}
}
out := make([]string, 0, len(env))
for _, e := range env {
key, _, _ := strings.Cut(e, "=")
if _, skip := drop[strings.ToUpper(key)]; skip {
continue
}
out = append(out, e)
}
return out
}
// Run executes the module binary with args, inheriting stdout/stderr.
func Run(bin string, args ...string) error {
cmd := exec.Command(bin, args...)
prepareModuleCmd(cmd)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
@ -24,6 +54,7 @@ func Run(bin string, args ...string) error {
// RunOutput executes the module binary and returns combined stdout.
func RunOutput(bin string, args ...string) (string, error) {
cmd := exec.Command(bin, args...)
prepareModuleCmd(cmd)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
@ -74,5 +105,9 @@ func Load(root, name string) (Module, string, Describe, error) {
if d.Name == "" {
d.Name = m.Name
}
// Older panel binaries may not load module.yaml from STREAMD_MODULES_DIR /
// exe-adjacent layout, leaving package empty (breaks transparent MITM —
// iptables then treats the listen port as the package name).
enrichDescribeFromYAML(&d, m.Dir)
return m, bin, d, nil
}

View file

@ -0,0 +1,31 @@
package modhost
import (
"os"
"os/exec"
"path/filepath"
"testing"
)
func TestPrepareModuleCmdSetsEnv(t *testing.T) {
t.Cleanup(func() { _ = SetModulesDir("") })
ov := filepath.Join(t.TempDir(), "modules")
if err := os.MkdirAll(ov, 0o755); err != nil {
t.Fatal(err)
}
if err := SetModulesDir(ov); err != nil {
t.Fatal(err)
}
cmd := exec.Command("true")
prepareModuleCmd(cmd)
found := false
for _, e := range cmd.Env {
if e == "STREAMD_MODULES_DIR="+ov {
found = true
break
}
}
if !found {
t.Fatalf("STREAMD_MODULES_DIR missing in env: %v", cmd.Env)
}
}

View file

@ -3,6 +3,7 @@ package modhost
import (
"os"
"path/filepath"
"strings"
"sync"
"streamd/repo"
@ -37,12 +38,32 @@ 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 / STREAMD_MODULES_DIR / DRM_MODULES_DIR; else <root>/modules.
// Prefer --modules-dir, then STREAMD_MODULES_DIR / DRM_MODULES_DIR, else <root>/modules.
// Module binaries read the env here directly so they honour the panel store even
// when they never call ApplyEnvModulesDir.
func EffectiveModulesDir(root string) string {
if ov := ModulesDirOverride(); ov != "" {
return ov
}
if v := envModulesDir(); v != "" {
return v
}
if root == "" {
root = repo.Root()
}
@ -55,10 +76,7 @@ func ApplyEnvModulesDir() error {
if ModulesDirOverride() != "" {
return nil
}
v := os.Getenv("STREAMD_MODULES_DIR")
if v == "" {
v = os.Getenv("DRM_MODULES_DIR")
}
v := envModulesDir()
if v == "" {
return nil
}

View file

@ -0,0 +1,39 @@
package modhost
import (
"os"
"path/filepath"
"testing"
)
func TestEffectiveModulesDirEnv(t *testing.T) {
t.Cleanup(func() {
_ = SetModulesDir("")
_ = os.Unsetenv("STREAMD_MODULES_DIR")
_ = os.Unsetenv("DRM_MODULES_DIR")
})
_ = SetModulesDir("")
_ = os.Unsetenv("STREAMD_MODULES_DIR")
_ = os.Unsetenv("DRM_MODULES_DIR")
dir := t.TempDir()
t.Setenv("STREAMD_MODULES_DIR", dir)
got := EffectiveModulesDir("")
want, _ := filepath.Abs(dir)
if got != want {
t.Fatalf("env modules dir: got %q want %q", got, want)
}
override := filepath.Join(t.TempDir(), "override")
if err := os.MkdirAll(override, 0o755); err != nil {
t.Fatal(err)
}
if err := SetModulesDir(override); err != nil {
t.Fatal(err)
}
got = EffectiveModulesDir("")
want, _ = filepath.Abs(override)
if got != want {
t.Fatalf("flag overrides env: got %q want %q", got, want)
}
}

View file

@ -0,0 +1,77 @@
package modhost
import (
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
)
// enrichDescribeFromYAML fills gaps left by older module binaries that do not
// load panel/agent module.yaml (empty package breaks transparent MITM).
func enrichDescribeFromYAML(d *Describe, modDir string) {
if d == nil || strings.TrimSpace(modDir) == "" {
return
}
raw, err := os.ReadFile(filepath.Join(modDir, "module.yaml"))
if err != nil {
raw, err = os.ReadFile(filepath.Join(modDir, "module-publish.yaml"))
if err != nil {
return
}
}
var doc struct {
Package string `yaml:"package"`
LicenseURL string `yaml:"license_url"`
KeyMode string `yaml:"key_mode"`
ProxyBin string `yaml:"proxy_bin"`
CAHash string `yaml:"ca_hash"`
TransparentMITM *bool `yaml:"transparent_mitm"`
RequireWVD *bool `yaml:"require_wvd"`
Rewriter string `yaml:"rewriter"`
Channels map[string]struct {
Label string `yaml:"label"`
} `yaml:"channels"`
}
if err := yaml.Unmarshal(raw, &doc); err != nil {
return
}
if strings.TrimSpace(d.Package) == "" && strings.TrimSpace(doc.Package) != "" {
d.Package = strings.TrimSpace(doc.Package)
}
if strings.TrimSpace(d.LicenseURL) == "" && strings.TrimSpace(doc.LicenseURL) != "" {
d.LicenseURL = strings.TrimSpace(doc.LicenseURL)
}
if strings.TrimSpace(d.KeyMode) == "" && strings.TrimSpace(doc.KeyMode) != "" {
d.KeyMode = strings.TrimSpace(doc.KeyMode)
}
if strings.TrimSpace(d.ProxyBin) == "" && strings.TrimSpace(doc.ProxyBin) != "" {
d.ProxyBin = strings.TrimSpace(doc.ProxyBin)
}
if strings.TrimSpace(d.CAHash) == "" && strings.TrimSpace(doc.CAHash) != "" {
d.CAHash = strings.TrimSpace(doc.CAHash)
}
if strings.TrimSpace(d.Rewriter) == "" && strings.TrimSpace(doc.Rewriter) != "" {
d.Rewriter = strings.TrimSpace(doc.Rewriter)
}
if !d.TransparentMITM && doc.TransparentMITM != nil {
d.TransparentMITM = *doc.TransparentMITM
}
if !d.RequireWVD && doc.RequireWVD != nil {
d.RequireWVD = *doc.RequireWVD
}
if len(d.Channels) == 0 && len(doc.Channels) > 0 {
for id, ch := range doc.Channels {
label := strings.TrimSpace(ch.Label)
if label == "" {
label = id
}
d.Channels = append(d.Channels, Channel{ID: id, Label: label})
}
}
if !d.ValuesLoaded {
d.ValuesLoaded = true
d.ValuesPath = filepath.Join(modDir, "module.yaml")
}
}

View file

@ -206,17 +206,21 @@ func Run(opt Options) (res Result, err error) {
if tm, ok := a.(app.TransparentMITM); ok && tm.UseTransparentMITM() {
useTProxy = true
}
pkgName := strings.TrimSpace(a.Package())
if useTProxy && pkgName == "" {
return res, fmt.Errorf("module %q has empty package — fix module.yaml package: (or re-pull modules); transparent MITM cannot install iptables UID rules", a.Name())
}
if useTProxy {
// Transparent REDIRECT — keeps phone VPN (BBC UK geo) working.
// StartTransparent creates a per-install CA under data/ if needed and pushes cert+key.
proxy.ClearHTTPProxy(c)
remoteDir := "/data/local/tmp/capture/" + a.Package()
remoteDir := "/data/local/tmp/capture/" + pkgName
var mitmHosts []string
if mh, ok := a.(app.MitmHostList); ok {
mitmHosts = mh.MitmHosts()
}
if err := proxy.StartTransparent(c, proxyBin, a.Package(), "8080", remoteDir, false, mitmHosts...); err != nil {
if err := proxy.StartTransparent(c, proxyBin, pkgName, "8080", remoteDir, false, mitmHosts...); err != nil {
return res, fmt.Errorf("transparent MITM start: %w", err)
}
defer proxy.StopTransparent(c)
@ -238,17 +242,6 @@ func Run(opt Options) (res Result, err error) {
proxy.ReinjectCA(c, caHash)
}
if err := a.Launch(c); err != nil {
return res, fmt.Errorf("launch: %w", err)
}
if !opt.NoAutoPlay {
if err := a.AutoPlay(c, opt.Channel); err != nil {
return res, fmt.Errorf("auto-play: %w", err)
}
} else {
fmt.Println("[*] Open the channel on the phone and wait for playback…")
}
_ = os.MkdirAll(filepath.Join(root, ".cache"), 0o755)
serialTag := c.Serial
if serialTag == "" {
@ -256,107 +249,161 @@ func Run(opt Options) (res Result, err error) {
}
localLog := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+".log")
localCap := filepath.Join(root, ".cache", "appproxy-"+sanitize(serialTag)+"_cap.json")
// Fresh local mirrors each run so grab-all does not reuse a prior channel's MPD.
_ = os.WriteFile(localLog, nil, 0o644)
_ = os.Remove(localCap)
stop := make(chan struct{})
go capture.MirrorLogLoop(c, hints.RemoteLog, localLog, stop)
defer close(stop)
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
if keyMode == "" || keyMode == "auto" {
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
}
needsKeys := keyMode != "none" && keyMode != "clear"
// DRM apps: wait up to 90s for Widevine traffic, then force-stop and retry
// (max 3). Clear / MPD-only apps keep a single wait of opt.Wait.
attempts := 1
waitPer := opt.Wait
if needsKeys {
attempts = 3
waitPer = 90 * time.Second
if opt.Wait > 0 && opt.Wait < waitPer {
waitPer = opt.Wait
}
}
need := hints.Require
if len(need) == 0 {
need = []string{"manifest"}
}
fmt.Printf("[*] Waiting for %s…\n", strings.Join(need, " + "))
fmt.Println(" watch:", localLog)
capData, err := capture.Wait(c, hints, localLog, localCap, opt.Wait)
if err != nil {
return res, err
}
licenseURL := first(capData.Get("license_url"), a.LicenseURL())
keyMode := strings.ToLower(strings.TrimSpace(opt.KeyMode))
if keyMode == "" || keyMode == "auto" {
keyMode = strings.ToLower(strings.TrimSpace(a.KeyMode()))
}
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
// Skip for clear/MPD-only apps (KeyMode none).
if keyMode != "none" && keyMode != "clear" {
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
curPSSH := strings.TrimSpace(capData.Get("pssh"))
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
if needPSSH && mpdForPSSH != "" {
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
if curPSSH != "" && curPSSH != pssh {
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
}
capData["pssh"] = pssh
} else if err != nil && curPSSH == "" {
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
}
} else if curPSSH == "" {
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
capData["pssh"] = pssh
} else if err != nil {
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
}
}
}
}
mpdURL := strings.TrimSpace(capData.Get("mpd"))
// Console: always surface the MPD we will use (BBC clear streams only need this).
fmt.Println()
fmt.Println("========== MPD ==========")
if mpdURL != "" {
fmt.Println(mpdURL)
} else {
fmt.Println("(none)")
}
fmt.Println("=========================")
fmt.Println()
fmt.Println("[+] Capture:")
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
v := capData.Get(k)
if k == "license_url" {
v = first(v, licenseURL)
var (
capData capture.Data
licenseURL string
mpdURL string
key string
lastErr error
)
for attempt := 1; attempt <= attempts; attempt++ {
if attempt > 1 {
fmt.Printf("[*] Widevine attempt %d/%d — closing app and retrying…\n", attempt, attempts)
c.ForceStop(a.Package())
time.Sleep(800 * time.Millisecond)
}
if v == "" {
// Fresh local mirrors each attempt so we do not reuse a prior MPD/PSSH.
_ = os.WriteFile(localLog, nil, 0o644)
_ = os.Remove(localCap)
if err := a.Launch(c); err != nil {
lastErr = fmt.Errorf("launch: %w", err)
continue
}
label := k
switch k {
case "license_url":
label = "license"
case "license_body":
label = "license_body"
v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
if !opt.NoAutoPlay {
if err := a.AutoPlay(c, opt.Channel); err != nil {
lastErr = fmt.Errorf("auto-play: %w", err)
c.ForceStop(a.Package())
continue
}
} else {
fmt.Println("[*] Open the channel on the phone and wait for playback…")
}
fmt.Println(" ", label+":", trim(v, 120))
}
key := ""
if keyMode == "none" || keyMode == "clear" {
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
} else {
var kerr error
key, kerr = fetchKey(opt, root, capData, licenseURL)
fmt.Printf("[*] Waiting for %s (attempt %d/%d, timeout %s)…\n",
strings.Join(need, " + "), attempt, attempts, waitPer.Round(time.Second))
fmt.Println(" watch:", localLog)
cap, err := capture.Wait(c, hints, localLog, localCap, waitPer)
if err != nil {
lastErr = err
fmt.Fprintf(os.Stderr, "[!] capture wait failed: %v\n", err)
c.ForceStop(a.Package())
continue
}
capData = cap
licenseURL = first(capData.Get("license_url"), a.LicenseURL())
// Brightcove/HLS: proxy often captures license + master URL but not PSSH.
// C4 MPDs list PlayReady before Widevine — replace a PlayReady blob.
if needsKeys {
enrichWidevinePSSH(capData)
}
mpdURL = strings.TrimSpace(capData.Get("mpd"))
fmt.Println()
fmt.Println("========== MPD ==========")
if mpdURL != "" {
fmt.Println(mpdURL)
} else {
fmt.Println("(none)")
}
fmt.Println("=========================")
fmt.Println()
fmt.Println("[+] Capture:")
for _, k := range []string{"pid", "mpd", "license_url", "auth", "pssh", "license_body"} {
v := capData.Get(k)
if k == "license_url" {
v = first(v, licenseURL)
}
if v == "" {
continue
}
label := k
switch k {
case "license_url":
label = "license"
case "license_body":
label = "license_body"
v = trim(v, 80) + fmt.Sprintf(" (%d bytes)", len(capData.Get("license_body")))
}
fmt.Println(" ", label+":", trim(v, 120))
}
if !needsKeys {
fmt.Println("[*] Key mode none — skipping wvkey (clear / MPD-only capture)")
lastErr = nil
break
}
k, kerr := fetchKey(opt, root, capData, licenseURL)
if kerr != nil {
// Allow MPD-only sessions when no .wvd was passed (grab-all / first pass),
// unless the app requires keys (e.g. c4).
lastErr = kerr
// Missing --wvd on a manual grab-all can soft-save MPD-only; agents
// always pass WVD so this path is for interactive capture only.
softOK := strings.Contains(kerr.Error(), "requires --wvd")
if softOK {
if rw, ok := a.(app.RequireWVD); ok && rw.RequireWVD() {
return res, kerr
c.ForceStop(a.Package())
continue
}
fmt.Fprintf(os.Stderr, "[!] %v — saving MPD-only session\n", kerr)
} else {
return res, kerr
key = ""
lastErr = nil
break
}
} else {
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
fmt.Fprintf(os.Stderr, "[!] key fetch failed (attempt %d/%d): %v\n", attempt, attempts, kerr)
c.ForceStop(a.Package())
continue
}
if strings.TrimSpace(k) == "" || !looksLikeKey(k) {
lastErr = fmt.Errorf("wvkey returned no usable KID:KEY")
fmt.Fprintf(os.Stderr, "[!] %v (attempt %d/%d)\n", lastErr, attempt, attempts)
c.ForceStop(a.Package())
continue
}
key = k
fmt.Println("[+] key:", strings.ReplaceAll(key, "\n", " | "))
lastErr = nil
break
}
if lastErr != nil {
if needsKeys {
return res, fmt.Errorf("widevine capture failed after %d attempt(s): %w", attempts, lastErr)
}
return res, lastErr
}
if needsKeys && (strings.TrimSpace(key) == "" || !looksLikeKey(key)) {
return res, fmt.Errorf("refusing to save capture without Widevine keys (mpd alone is not enough)")
}
sess := session.Session{
@ -384,6 +431,62 @@ func Run(opt Options) (res Result, err error) {
return res, nil
}
func enrichWidevinePSSH(capData capture.Data) {
mpdForPSSH := strings.TrimSpace(capData.Get("mpd"))
curPSSH := strings.TrimSpace(capData.Get("pssh"))
needPSSH := curPSSH == "" || isPlayReadyPSSH(curPSSH)
if !needPSSH || mpdForPSSH == "" {
return
}
if strings.Contains(strings.ToLower(mpdForPSSH), ".mpd") {
if pssh, err := extractWidevinePSSHFromMPD(mpdForPSSH); err == nil && pssh != "" {
if curPSSH != "" && curPSSH != pssh {
fmt.Println("[*] Replaced PlayReady/non-Widevine PSSH with Widevine from MPD")
}
capData["pssh"] = pssh
} else if err != nil && curPSSH == "" {
fmt.Fprintf(os.Stderr, "[!] MPD Widevine PSSH extract: %v\n", err)
}
return
}
if curPSSH == "" {
if pssh, err := extractHLSPSSH(mpdForPSSH); err == nil && pssh != "" {
capData["pssh"] = pssh
} else if err != nil {
fmt.Fprintf(os.Stderr, "[!] HLS PSSH extract: %v\n", err)
}
}
}
func looksLikeKey(raw string) bool {
raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
for _, line := range strings.Split(raw, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
kid, k, ok := strings.Cut(line, ":")
if !ok {
continue
}
if len(hexDigits(kid)) == 32 && len(hexDigits(k)) == 32 {
return true
}
}
return false
}
func hexDigits(s string) string {
var b strings.Builder
for _, r := range s {
switch {
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
b.WriteRune(r)
}
}
return b.String()
}
// ClearProxyLater clears http_proxy (exported for agent defer helpers).
func ClearProxyLater(c *adb.Client) {
proxy.ClearHTTPProxy(c)
@ -414,16 +517,18 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
if strings.TrimSpace(opt.WVD) == "" {
return "", fmt.Errorf("wvkey requires --wvd (path to .wvd device file)")
}
py := opt.Python
if py == "" {
py = filepath.Join(root, ".venv", "Scripts", "python.exe")
if _, err := os.Stat(py); err != nil {
py = filepath.Join(root, ".venv", "bin", "python")
}
// Ensure apps/wvkey + .venv/pywidevine exist on Windows/Linux/macOS.
rt, err := wvkey.EnsureRuntime(root)
if err != nil {
return "", err
}
py := rt.Python
if p := strings.TrimSpace(opt.Python); p != "" && fileExistsPath(p) {
py = p
}
wopt := wvkey.Options{
Python: py,
Script: filepath.Join(root, "apps", "wvkey", "wvkey.py"),
Script: rt.Script,
WVD: opt.WVD,
PSSH: cap.Get("pssh"),
Auth: cap.Get("auth"),
@ -465,6 +570,11 @@ func fetchKey(opt Options, root string, cap capture.Data, licenseURL string) (st
}
}
func fileExistsPath(path string) bool {
st, err := os.Stat(path)
return err == nil && !st.IsDir()
}
func first(vals ...string) string {
for _, v := range vals {
if strings.TrimSpace(v) != "" {

View file

@ -481,10 +481,14 @@ const (
// mitmHosts are passed as repeatable -mitm-host flags (suffix match); transparent
// mode otherwise only MITMs open.live.bbc.co.uk.
func StartTransparent(c *adb.Client, localBin, pkg, port, remoteDir string, reinject bool, mitmHosts ...string) error {
pkg = strings.TrimSpace(pkg)
if pkg == "" {
return fmt.Errorf("transparent MITM requires Android package name (module.yaml package: is empty — re-pull/rebuild the module)")
}
if port == "" {
port = "8080"
}
if remoteDir == "" {
if remoteDir == "" || strings.HasSuffix(remoteDir, "/capture/") || strings.HasSuffix(remoteDir, `\capture\`) {
remoteDir = RemoteCaptureRoot + "/" + pkg
}
stopProxy(c)

172
apps/pkg/wvkey/ensure.go Normal file
View file

@ -0,0 +1,172 @@
package wvkey
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
)
// Runtime is a resolved Python + wvkey.py pair ready for Fetch*.
type Runtime struct {
Python string
Script string
}
// ScriptPath returns <root>/apps/wvkey/wvkey.py.
func ScriptPath(root string) string {
return filepath.Join(root, "apps", "wvkey", "wvkey.py")
}
// VenvPython returns the platform venv interpreter under root, if present.
func VenvPython(root string) string {
candidates := []string{
filepath.Join(root, ".venv", "Scripts", "python.exe"),
filepath.Join(root, ".venv", "bin", "python"),
filepath.Join(root, ".venv", "bin", "python3"),
}
for _, c := range candidates {
if fileExists(c) {
return c
}
}
return ""
}
// EnsureRuntime makes sure wvkey.py exists and a usable Python with
// pywidevine is available under root (creating .venv when needed).
// Works on Windows, Linux, and macOS.
func EnsureRuntime(root string) (Runtime, error) {
var zero Runtime
if root == "" {
return zero, fmt.Errorf("wvkey: install root required")
}
script := ScriptPath(root)
if !fileExists(script) {
return zero, fmt.Errorf("wvkey script missing at %s — re-run streamd so bootstrap can materialise apps/wvkey/", script)
}
req := filepath.Join(root, "apps", "wvkey", "requirements.txt")
if py := VenvPython(root); py != "" {
if hasPywidevine(py) {
return Runtime{Python: py, Script: script}, nil
}
if err := pipInstall(py, req); err != nil {
return zero, err
}
if !hasPywidevine(py) {
return zero, fmt.Errorf("wvkey: installed requirements but pywidevine still missing in %s", py)
}
return Runtime{Python: py, Script: script}, nil
}
base, err := findSystemPython()
if err != nil {
return zero, err
}
venvDir := filepath.Join(root, ".venv")
fmt.Fprintf(os.Stderr, "agent: creating Widevine venv at %s …\n", venvDir)
if err := createVenv(base, venvDir); err != nil {
return zero, err
}
py := VenvPython(root)
if py == "" {
return zero, fmt.Errorf("wvkey: venv created at %s but no python binary found", venvDir)
}
if err := pipInstall(py, req); err != nil {
return zero, err
}
if !hasPywidevine(py) {
return zero, fmt.Errorf("wvkey: pywidevine missing after pip install (%s)", py)
}
fmt.Fprintf(os.Stderr, "agent: Widevine helper ready (%s)\n", py)
return Runtime{Python: py, Script: script}, nil
}
// FindPython prefers an existing install-root venv, then PATH helpers.
func FindPython(root string) string {
if root != "" {
if py := VenvPython(root); py != "" {
return py
}
}
return findPython()
}
func fileExists(path string) bool {
st, err := os.Stat(path)
return err == nil && !st.IsDir()
}
func hasPywidevine(py string) bool {
cmd := exec.Command(py, "-c", "import pywidevine")
return cmd.Run() == nil
}
func pipInstall(py, requirements string) error {
if !fileExists(requirements) {
return fmt.Errorf("wvkey: requirements missing at %s", requirements)
}
fmt.Fprintf(os.Stderr, "agent: pip install -r %s …\n", requirements)
cmd := exec.Command(py, "-m", "pip", "install", "-r", requirements)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("wvkey: pip install failed: %w\n%s", err, strings.TrimSpace(string(out)))
}
return nil
}
func createVenv(basePython, venvDir string) error {
cmd := exec.Command(basePython, "-m", "venv", venvDir)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("wvkey: python -m venv %s failed: %w\n%s", venvDir, err, strings.TrimSpace(string(out)))
}
return nil
}
func findSystemPython() (string, error) {
var names []string
switch runtime.GOOS {
case "windows":
// Prefer the py launcher (real install) over the Store stub named "python".
names = []string{"py", "python3", "python"}
default:
names = []string{"python3", "python"}
}
for _, name := range names {
if name == "py" {
// `py -3` on Windows
if p, err := exec.LookPath("py"); err == nil {
cmd := exec.Command(p, "-3", "-c", "import sys; print(sys.executable)")
out, err := cmd.Output()
if err == nil {
exe := strings.TrimSpace(string(out))
if fileExists(exe) {
return exe, nil
}
}
}
continue
}
if p, err := exec.LookPath(name); err == nil {
// Skip the WindowsApps Store alias stub when it cannot run -m venv.
if runtime.GOOS == "windows" && strings.Contains(strings.ToLower(p), `windowsapps`) {
cmd := exec.Command(p, "-c", "import sys; print(sys.executable)")
out, err := cmd.Output()
if err != nil {
continue
}
exe := strings.TrimSpace(string(out))
if !fileExists(exe) || strings.Contains(strings.ToLower(exe), `windowsapps`) {
continue
}
return exe, nil
}
return p, nil
}
}
return "", fmt.Errorf("wvkey: no system Python found — install Python 3.10+ (Windows/macOS/Linux) so the agent can create .venv for Widevine keys")
}

View file

@ -58,14 +58,21 @@ func FetchWrapAll(opt Options) ([]string, error) {
}
func run(opt Options, mode string, all bool) ([]string, error) {
py := opt.Python
if py == "" {
py = findPython()
}
py := resolvePython(opt.Python)
script := opt.Script
if script == "" {
return nil, fmt.Errorf("wvkey script path required")
}
if !fileExists(script) {
return nil, fmt.Errorf("wvkey script not found: %s", script)
}
if !fileExists(py) {
// Bare names like "python3" are OK via LookPath inside resolvePython;
// absolute/relative paths must exist.
if filepath.IsAbs(py) || strings.Contains(py, string(os.PathSeparator)) || strings.Contains(py, "/") {
return nil, fmt.Errorf("wvkey python not found: %s (run agent once to auto-create .venv, or set python: in agent.yaml)", py)
}
}
if strings.TrimSpace(opt.WVD) == "" {
return nil, fmt.Errorf("wvkey --wvd path required")
}
@ -120,12 +127,30 @@ func run(opt Options, mode string, all bool) ([]string, error) {
return out, nil
}
// resolvePython uses an explicit path only when the file exists; otherwise
// discovers a usable interpreter. Passing a missing absolute path used to make
// exec fail with a confusing "not found in %PATH%" on Windows.
func resolvePython(explicit string) string {
if strings.TrimSpace(explicit) != "" {
if st, err := os.Stat(explicit); err == nil && !st.IsDir() {
return explicit
}
if !strings.Contains(explicit, string(os.PathSeparator)) && !strings.Contains(explicit, "/") {
if p, err := exec.LookPath(explicit); err == nil {
return p
}
}
}
return findPython()
}
func findPython() string {
candidates := []string{
filepath.Join(".venv", "Scripts", "python.exe"),
filepath.Join(".venv", "bin", "python"),
"python3",
"python",
"py",
}
for _, c := range candidates {
if filepath.IsAbs(c) || strings.Contains(c, string(os.PathSeparator)) {

View file

@ -17,7 +17,9 @@ apps/streamd/
## Run
```bash
./bin/streamd serve --bind 127.0.0.1:8083 --data .cache/streamd
./bin/streamd serve --bind 127.0.0.1:8083
# --data is optional: reuses existing .cache/streamd (cwd or next to the binary)
# or set STREAMD_DATA / pass --data explicitly
```
`--bind` defaults to **`127.0.0.1:8083`** (loopback). Binding `0.0.0.0` (or any

View file

@ -6,6 +6,7 @@ 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
@ -17,6 +18,7 @@ require (
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.42.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
modernc.org/libc v1.55.3 // indirect
modernc.org/mathutil v1.6.0 // indirect
modernc.org/memory v1.8.0 // indirect

View file

@ -19,6 +19,9 @@ golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=

View file

@ -13,6 +13,7 @@ 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"
)
@ -61,6 +62,7 @@ type Handler struct {
Modules *modstore.Store
// ModulesNotify is set when the hub supports module change pushes.
ModulesNotify ModulesNotifier
Egress *egress.Manager
Log *slog.Logger
}
@ -70,6 +72,7 @@ func (h *Handler) Mount(mux *http.ServeMux) {
mux.HandleFunc("/api/streams/", h.streamAction)
mux.HandleFunc("/api/overview", h.overview)
h.MountControl(mux)
h.MountEgress(mux)
mux.HandleFunc("/api/apps", h.apps)
mux.HandleFunc("/api/modules", h.modules)
mux.HandleFunc("/api/modules/", h.modules)
@ -539,6 +542,7 @@ func changeNote(before, after db.Stream, in db.PatchStream) string {
add("key", in.Key != nil && before.Key != after.Key)
add("headers", in.HeadersJSON != nil && before.HeadersJSON != after.HeadersJSON)
add("proxy", in.Proxy != nil && before.Proxy != after.Proxy)
add("egress", in.Egress != nil && before.Egress != after.Egress)
add("variants", before.VariantsJSON != after.VariantsJSON)
add("outputs", before.OutputsJSON != after.OutputsJSON)
add("settings", before.SettingsJSON != after.SettingsJSON)
@ -570,6 +574,9 @@ func credentialsChanged(before, after db.Stream, in db.PatchStream) bool {
if in.Proxy != nil && strings.TrimSpace(before.Proxy) != strings.TrimSpace(after.Proxy) {
return true
}
if in.Egress != nil && strings.TrimSpace(before.Egress) != strings.TrimSpace(after.Egress) {
return true
}
if in.VariantsJSON != nil || len(in.Variants) > 0 {
if strings.TrimSpace(before.VariantsJSON) != strings.TrimSpace(after.VariantsJSON) {
return true

View file

@ -2,8 +2,12 @@ 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"
@ -44,13 +48,17 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
for _, m := range mods {
bin, err := modhost.EnsureBuilt(m)
if err != nil {
out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()})
info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}
h.fillChannelsFromStore(&info, m.Name)
out = append(out, info)
h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
continue
}
d, err := modhost.RunDescribe(bin)
if err != nil {
out = append(out, appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()})
info := appInfo{Name: m.Name, Channels: []channelInfo{}, Rewriter: "none", Error: err.Error()}
h.fillChannelsFromStore(&info, m.Name)
out = append(out, info)
h.logger().Warn("module describe skipped", "module", m.Name, "err", err)
continue
}
@ -61,10 +69,14 @@ 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{
@ -72,3 +84,53 @@ func (h *Handler) apps(w http.ResponseWriter, r *http.Request) {
"rewriters": mpd.Names(),
})
}
func (h *Handler) fillChannelsFromStore(info *appInfo, name string) {
if h == nil || h.Modules == nil || info == nil {
return
}
chans := channelsFromStoreYAML(h.Modules, name)
if len(chans) == 0 {
return
}
info.Channels = chans
info.HasConfig = true
if info.Error != "" {
// Soft: yaml channels recovered even though describe failed.
info.Error = ""
}
}
// channelsFromStoreYAML reads channels from the panel module.yaml when describe
// returns none (common with uploaded binaries that resolve values via cwd).
func channelsFromStoreYAML(store *modstore.Store, name string) []channelInfo {
if store == nil {
return nil
}
raw, err := store.ReadYAML(name)
if err != nil || len(raw) == 0 {
return nil
}
var doc struct {
Channels map[string]struct {
Label string `yaml:"label"`
} `yaml:"channels"`
}
if err := yaml.Unmarshal(raw, &doc); err != nil || len(doc.Channels) == 0 {
return nil
}
ids := make([]string, 0, len(doc.Channels))
for id := range doc.Channels {
ids = append(ids, id)
}
sort.Strings(ids)
out := make([]channelInfo, 0, len(ids))
for _, id := range ids {
label := doc.Channels[id].Label
if label == "" {
label = id
}
out = append(out, channelInfo{ID: id, Label: label})
}
return out
}

View file

@ -0,0 +1,45 @@
package api
import (
"os"
"path/filepath"
"testing"
"streamd/apps/streamd/internal/modstore"
)
func TestChannelsFromStoreYAML(t *testing.T) {
root := t.TempDir()
store := modstore.New(root)
modDir := filepath.Join(root, "rte")
if err := os.MkdirAll(modDir, 0o755); err != nil {
t.Fatal(err)
}
yaml := []byte(`package: air.RTE
channels:
rteone:
label: RTE One
rtetwo:
label: RTE 2
`)
if err := os.WriteFile(filepath.Join(modDir, "module.yaml"), yaml, 0o644); err != nil {
t.Fatal(err)
}
chans := channelsFromStoreYAML(store, "rte")
if len(chans) != 2 {
t.Fatalf("got %d channels: %+v", len(chans), chans)
}
if chans[0].ID != "rteone" || chans[0].Label != "RTE One" {
t.Fatalf("first channel: %+v", chans[0])
}
if chans[1].ID != "rtetwo" {
t.Fatalf("second channel: %+v", chans[1])
}
}
func TestChannelsFromStoreYAMLMissing(t *testing.T) {
store := modstore.New(t.TempDir())
if chans := channelsFromStoreYAML(store, "nope"); chans != nil {
t.Fatalf("expected nil, got %+v", chans)
}
}

View file

@ -162,6 +162,7 @@ func (h *Handler) duplicate(w http.ResponseWriter, r *http.Request, id int64) {
Key: src.Key,
HeadersJSON: src.HeadersJSON,
Proxy: src.Proxy,
Egress: src.Egress,
VideoSelect: src.VideoSelect,
AudioSelect: src.AudioSelect,
Rewriter: src.Rewriter,
@ -271,9 +272,19 @@ func (h *Handler) doProbe(ctx context.Context, st db.Stream, target string) prob
start := time.Now()
client := &http.Client{Timeout: 20 * time.Second}
// Fetch through the stream's own proxy, so a geo-restricted origin is
// probed the same way the downloader would reach it.
if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
// Fetch through the stream's effective proxy (explicit or named egress),
// so a geo-restricted origin is probed the same way the downloader would.
proxy := strings.TrimSpace(st.Proxy)
if h.Egress != nil {
if p, err := h.Egress.ResolveProxy(st); err == nil {
proxy = p
} else if strings.TrimSpace(st.Egress) != "" && proxy == "" {
res.Error = "egress: " + err.Error()
res.Summary = "egress profile could not be brought up"
return res
}
}
if proxy != "" {
if c, err := httpClientWithProxy(proxy); err == nil {
client = c
} else {

View file

@ -0,0 +1,254 @@
package api
import (
"database/sql"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"streamd/apps/streamd/internal/auth"
"streamd/apps/streamd/internal/db"
)
// MountEgress registers /api/egress routes.
func (h *Handler) MountEgress(mux *http.ServeMux) {
mux.HandleFunc("/api/egress", h.egressRoot)
mux.HandleFunc("/api/egress/", h.egressAction)
}
func (h *Handler) egressRoot(w http.ResponseWriter, r *http.Request) {
if h.Egress == nil {
writeErr(w, http.StatusServiceUnavailable, "egress manager not configured")
return
}
switch r.Method {
case http.MethodGet:
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
return
}
list, err := h.Store.ListEgressProfiles()
if err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
for i := range list {
h.Egress.Enrich(&list[i])
}
writeJSON(w, http.StatusOK, map[string]any{"profiles": list})
case http.MethodPost:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
var in db.CreateEgressProfile
if err := readJSON(r, &in); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
prof, err := h.Store.CreateEgressProfile(in)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.Egress.Enrich(&prof)
h.audit(r, p, http.StatusOK, "create egress "+prof.Name)
writeJSON(w, http.StatusOK, prof)
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
func (h *Handler) egressAction(w http.ResponseWriter, r *http.Request) {
if h.Egress == nil {
writeErr(w, http.StatusServiceUnavailable, "egress manager not configured")
return
}
path := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/egress/"), "/")
if path == "" {
h.egressRoot(w, r)
return
}
parts := strings.Split(path, "/")
name := db.Slug(parts[0])
if name == "" {
writeErr(w, http.StatusBadRequest, "invalid name")
return
}
action := ""
if len(parts) > 1 {
action = strings.ToLower(parts[1])
}
switch {
case action == "" && r.Method == http.MethodGet:
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
return
}
prof, err := h.Egress.Status(name)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
writeErr(w, http.StatusNotFound, "not found")
return
}
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
writeJSON(w, http.StatusOK, prof)
case action == "" && r.Method == http.MethodPut:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
h.putEgress(w, r, p, name)
case action == "" && r.Method == http.MethodDelete:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
prof, err := h.Store.GetEgressProfileByName(name)
if err != nil {
writeErr(w, http.StatusNotFound, "not found")
return
}
_ = h.Egress.Down(name)
if err := h.Store.DeleteEgressProfile(prof.ID); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
_ = h.Egress.RemoveFiles(name)
h.audit(r, p, http.StatusOK, "delete egress "+name)
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
case action == "up" && r.Method == http.MethodPost:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
if err := h.Egress.EnsureUp(name); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
prof, _ := h.Egress.Status(name)
h.audit(r, p, http.StatusOK, "egress up "+name)
writeJSON(w, http.StatusOK, prof)
case action == "down" && r.Method == http.MethodPost:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
if err := h.Egress.Down(name); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
prof, _ := h.Egress.Status(name)
h.audit(r, p, http.StatusOK, "egress down "+name)
writeJSON(w, http.StatusOK, prof)
case action == "test" && r.Method == http.MethodPost:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
out, err := h.Egress.TestDial(name)
if err != nil {
if out == nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
h.audit(r, p, http.StatusOK, "egress test "+name+" fail")
writeJSON(w, http.StatusOK, out)
return
}
h.audit(r, p, http.StatusOK, "egress test "+name)
writeJSON(w, http.StatusOK, out)
case action == "conf" && r.Method == http.MethodPut:
p, ok := auth.Guard(w, r, auth.RoleAdmin)
if !ok {
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
_ = r.Body.Close()
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
contents := string(body)
ct := r.Header.Get("Content-Type")
if strings.Contains(ct, "json") || strings.HasPrefix(strings.TrimSpace(contents), "{") {
var in struct {
Conf string `json:"conf"`
}
if err := json.Unmarshal(body, &in); err != nil || strings.TrimSpace(in.Conf) == "" {
writeErr(w, http.StatusBadRequest, "conf required")
return
}
contents = in.Conf
}
if strings.TrimSpace(contents) == "" {
writeErr(w, http.StatusBadRequest, "empty conf")
return
}
if _, err := h.Store.GetEgressProfileByName(name); err != nil {
writeErr(w, http.StatusNotFound, "not found")
return
}
if err := h.Egress.WriteConf(name, contents); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
prof, _ := h.Egress.Status(name)
h.audit(r, p, http.StatusOK, "egress conf "+name)
writeJSON(w, http.StatusOK, prof)
default:
writeErr(w, http.StatusMethodNotAllowed, "method not allowed")
}
}
func (h *Handler) putEgress(w http.ResponseWriter, r *http.Request, p *auth.Principal, name string) {
prof, err := h.Store.GetEgressProfileByName(name)
if err != nil {
writeErr(w, http.StatusNotFound, "not found")
return
}
var in struct {
Enabled *bool `json:"enabled"`
SocksURL *string `json:"socks_url"`
Kind *string `json:"kind"`
Conf *string `json:"conf"`
}
if err := readJSON(r, &in); err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
upd, err := h.Store.UpdateEgressProfile(prof.ID, db.UpdateEgressProfile{
Enabled: in.Enabled, SocksURL: in.SocksURL, Kind: in.Kind,
})
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if in.Conf != nil && strings.TrimSpace(*in.Conf) != "" {
if err := h.Egress.WriteConf(name, *in.Conf); err != nil {
writeErr(w, http.StatusInternalServerError, err.Error())
return
}
}
h.Egress.Enrich(&upd)
if in.Enabled != nil && *in.Enabled {
_ = h.Egress.EnsureUp(name)
upd, _ = h.Egress.Status(name)
}
if in.Enabled != nil && !*in.Enabled {
_ = h.Egress.Down(name)
upd, _ = h.Egress.Status(name)
}
h.audit(r, p, http.StatusOK, "update egress "+name)
writeJSON(w, http.StatusOK, upd)
}

View file

@ -363,6 +363,10 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
}
_ = h.Store.FlushHistory()
recent, _ := h.Store.RecentEvents(25)
sessions, _ := h.Store.ListRecentSessions(50)
if sessions == nil {
sessions = []db.StreamSession{}
}
out := map[string]any{
"totals": map[string]any{
"streams": len(list),
@ -374,7 +378,8 @@ func (h *Handler) overview(w http.ResponseWriter, r *http.Request) {
"viewers": viewers,
"needs_capture": needCapture,
},
"recent_events": recent,
"recent_events": recent,
"recent_sessions": sessions,
}
if h.Scheduler != nil {
out["upcoming"] = h.Scheduler.Upcoming(10)

View file

@ -222,6 +222,14 @@ 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

View file

@ -41,7 +41,8 @@ type Stream struct {
MPD string `json:"mpd"`
Key string `json:"key"`
HeadersJSON string `json:"headers_json"`
Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE)
Proxy string `json:"proxy"` // socks5:// or http:// for origin fetch (NRE)
Egress string `json:"egress"` // named egress profile (wireguard/socks); used when Proxy empty
VideoSelect string `json:"video_select"`
AudioSelect string `json:"audio_select"`
Enabled bool `json:"enabled"`
@ -81,6 +82,7 @@ type Stream struct {
HasKey bool `json:"has_key"`
HasHeaders bool `json:"has_headers"`
HasProxy bool `json:"has_proxy"`
HasEgress bool `json:"has_egress"`
KeyValid bool `json:"key_valid"`
// DRMRequired is DRMMode resolved: whether this stream needs keys at all.
DRMRequired bool `json:"drm_required"`
@ -103,6 +105,7 @@ type CreateStream struct {
Key string `json:"key"`
HeadersJSON string `json:"headers_json"`
Proxy string `json:"proxy"`
Egress string `json:"egress"`
VideoSelect string `json:"video_select"`
AudioSelect string `json:"audio_select"`
Rewriter string `json:"rewriter"`
@ -128,6 +131,7 @@ type PatchStream struct {
Key *string `json:"key"`
HeadersJSON *string `json:"headers_json"`
Proxy *string `json:"proxy"`
Egress *string `json:"egress"`
VideoSelect *string `json:"video_select"`
AudioSelect *string `json:"audio_select"`
Rewriter *string `json:"rewriter"`
@ -230,6 +234,7 @@ CREATE TABLE IF NOT EXISTS agent_claims (
`ALTER TABLE streams ADD COLUMN on_demand INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE streams ADD COLUMN idle_timeout_s INTEGER NOT NULL DEFAULT 300`,
`ALTER TABLE streams ADD COLUMN public INTEGER NOT NULL DEFAULT 1`,
`ALTER TABLE streams ADD COLUMN egress TEXT NOT NULL DEFAULT ''`,
} {
_, _ = s.DB.Exec(stmt)
}
@ -239,7 +244,13 @@ CREATE TABLE IF NOT EXISTS agent_claims (
if err := s.migrateSettings(); err != nil {
return err
}
return s.migrateSchedules()
if err := s.migrateSchedules(); err != nil {
return err
}
if err := s.migrateEgress(); err != nil {
return err
}
return s.migrateSessions()
}
func now() string {
@ -264,10 +275,13 @@ func slug(name string) string {
return out
}
// Slug normalises a name the same way stream and egress profile names are stored.
func Slug(name string) string { return slug(name) }
const streamSelect = `
SELECT s.id, s.name, s.title, COALESCE(s.description,''), COALESCE(s.tags,''),
s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
COALESCE(s.proxy,''), s.video_select, s.audio_select, s.enabled, s.rewriter,
COALESCE(s.proxy,''), COALESCE(s.egress,''), s.video_select, s.audio_select, s.enabled, s.rewriter,
COALESCE(s.variants_json,''), COALESCE(s.outputs_json,''), COALESCE(s.settings_json,''),
COALESCE(s.drm_mode,'auto'), COALESCE(s.on_demand,0),
COALESCE(s.idle_timeout_s,300), COALESCE(s.public,1),
@ -318,7 +332,7 @@ func scanStream(row rowScanner) (Stream, error) {
err := row.Scan(
&st.ID, &st.Name, &st.Title, &st.Description, &st.Tags,
&st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
&st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter,
&st.Proxy, &st.Egress, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter,
&st.VariantsJSON, &st.OutputsJSON, &st.SettingsJSON,
&st.DRMMode, &onDemand, &st.IdleTimeoutS, &public,
&st.CreatedAt, &st.UpdatedAt,
@ -361,6 +375,7 @@ func (st *Stream) fillDerived() {
hdr := strings.TrimSpace(st.HeadersJSON)
st.HasHeaders = hdr != "" && hdr != "{}" && hdr != "null"
st.HasProxy = strings.TrimSpace(st.Proxy) != ""
st.HasEgress = strings.TrimSpace(st.Egress) != ""
switch strings.ToLower(strings.TrimSpace(st.DRMMode)) {
case DRMYes:
st.DRMRequired = true
@ -557,12 +572,13 @@ func (s *Store) CreateStream(in CreateStream) (Stream, error) {
}
ts := now()
res, err := s.DB.Exec(`
INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,
INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,egress,
video_select,audio_select,enabled,rewriter,variants_json,outputs_json,
settings_json,drm_mode,on_demand,idle_timeout_s,public,created_at,updated_at)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
name, in.Title, strings.TrimSpace(in.Description), normalizeTags(in.Tags),
in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy),
slug(strings.TrimSpace(in.Egress)),
in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, outputsJSON,
settingsJSON, normalizeDRMMode(in.DRMMode), onDemand, idle, public, ts, ts)
if err != nil {
@ -654,6 +670,9 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
if in.Proxy != nil {
cur.Proxy = strings.TrimSpace(*in.Proxy)
}
if in.Egress != nil {
cur.Egress = slug(strings.TrimSpace(*in.Egress))
}
if in.VideoSelect != nil {
cur.VideoSelect = *in.VideoSelect
}
@ -730,11 +749,11 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
ts := now()
_, err = s.DB.Exec(`
UPDATE streams SET title=?, description=?, tags=?, app=?, channel=?, mpd=?, key_kid_key=?,
headers_json=?, proxy=?, video_select=?, audio_select=?, enabled=?, rewriter=?,
headers_json=?, proxy=?, egress=?, video_select=?, audio_select=?, enabled=?, rewriter=?,
variants_json=?, outputs_json=?, settings_json=?, drm_mode=?, on_demand=?,
idle_timeout_s=?, public=?, updated_at=? WHERE id=?`,
cur.Title, cur.Description, cur.Tags, cur.App, cur.Channel, cur.MPD, cur.Key,
cur.HeadersJSON, cur.Proxy, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter,
cur.HeadersJSON, cur.Proxy, cur.Egress, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter,
cur.VariantsJSON, cur.OutputsJSON, cur.SettingsJSON, cur.DRMMode, onDemand,
cur.IdleTimeoutS, public, ts, id)
if err != nil {
@ -775,7 +794,16 @@ func (s *Store) SetCredentials(id int64, cred Credentials) (Stream, error) {
if mpd == "" {
return Stream{}, fmt.Errorf("mpd required")
}
_, err := s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
st, err := s.GetStream(id)
if err != nil {
return Stream{}, err
}
// Encrypted streams must receive usable KID:KEY lines — MPD alone leaves
// the packager rainbow-decrypting forever.
if st.DRMRequired && !ValidKeyPairs(key) {
return Stream{}, fmt.Errorf("key required for DRM stream %q (got mpd but no valid KID:KEY)", st.Name)
}
_, err = s.DB.Exec(`UPDATE streams SET mpd=?, key_kid_key=?, updated_at=? WHERE id=?`,
mpd, key, now(), id)
if err != nil {
return Stream{}, err

View file

@ -0,0 +1,226 @@
package db
import (
"database/sql"
"fmt"
"strings"
)
const (
EgressKindWireGuard = "wireguard"
EgressKindSocks = "socks"
EgressStopped = "stopped"
EgressStarting = "starting"
EgressUp = "up"
EgressDown = "down"
EgressError = "error"
)
// EgressProfile is a named origin-egress path (WireGuard netns or plain SOCKS).
// Conf blobs live on disk under data/egress/<name>/; 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
}

View file

@ -0,0 +1,117 @@
package db
import (
"path/filepath"
"testing"
)
func TestSlugValidation(t *testing.T) {
for _, c := range []struct {
in, want string
}{
{"London", "london"},
{"dublin-1", "dublin-1"},
{" RTE IE ", "rte-ie"},
{"!!!", ""},
{"Wire_Guard", "wire-guard"},
{"a--b", "a-b"},
} {
if got := Slug(c.in); got != c.want {
t.Errorf("Slug(%q) = %q want %q", c.in, got, c.want)
}
}
}
func TestEgressCRUD(t *testing.T) {
dir := t.TempDir()
store, err := Open(filepath.Join(dir, "data"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
_, err = store.CreateEgressProfile(CreateEgressProfile{Name: "!!!"})
if err == nil {
t.Fatal("expected empty slug to fail")
}
on := true
p, err := store.CreateEgressProfile(CreateEgressProfile{
Name: "London", Kind: "wireguard", Enabled: &on,
})
if err != nil {
t.Fatal(err)
}
if p.Name != "london" || p.Kind != EgressKindWireGuard || !p.Enabled {
t.Fatalf("create: %+v", p)
}
if p.Status != EgressStopped {
t.Fatalf("status = %q", p.Status)
}
got, err := store.GetEgressProfileByName("LONDON")
if err != nil || got.ID != p.ID {
t.Fatalf("GetByName: %+v %v", got, err)
}
off := false
url := "socks5://127.0.0.1:1080"
kind := EgressKindSocks
upd, err := store.UpdateEgressProfile(p.ID, UpdateEgressProfile{
Enabled: &off, SocksURL: &url, Kind: &kind,
})
if err != nil {
t.Fatal(err)
}
if upd.Enabled || upd.SocksURL != url || upd.Kind != EgressKindSocks {
t.Fatalf("update: %+v", upd)
}
if err := store.SetEgressRuntime(p.ID, EgressUp, "", "1.2.3.4", 18080); err != nil {
t.Fatal(err)
}
got, _ = store.GetEgressProfile(p.ID)
if got.Status != EgressUp || got.EgressIP != "1.2.3.4" || got.ListenPort != 18080 {
t.Fatalf("runtime: %+v", got)
}
list, err := store.ListEgressProfiles()
if err != nil || len(list) != 1 {
t.Fatalf("list: %v %#v", err, list)
}
if err := store.DeleteEgressProfile(p.ID); err != nil {
t.Fatal(err)
}
if _, err := store.GetEgressProfile(p.ID); err == nil {
t.Fatal("expected missing after delete")
}
}
func TestStreamEgressField(t *testing.T) {
dir := t.TempDir()
store, err := Open(filepath.Join(dir, "data"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
st, err := store.CreateStream(CreateStream{Name: "rte1", MPD: "https://x/a.mpd", Egress: "Dublin"})
if err != nil {
t.Fatal(err)
}
if st.Egress != "dublin" || !st.HasEgress || st.HasProxy {
t.Fatalf("create egress: %+v has_egress=%v has_proxy=%v", st.Egress, st.HasEgress, st.HasProxy)
}
empty := ""
london := "london"
st, err = store.PatchStream(st.ID, PatchStream{Egress: &london})
if err != nil || st.Egress != "london" {
t.Fatalf("patch: %+v %v", st, err)
}
st, err = store.PatchStream(st.ID, PatchStream{Egress: &empty})
if err != nil || st.HasEgress {
t.Fatalf("clear egress: %+v %v", st, err)
}
}

View file

@ -408,6 +408,13 @@ GROUP BY stream_id, substr(at, 1, 17)`, rollupBucketS, rawCutoff); err != nil {
_ = tx.Rollback()
return err
}
sessionCutoff := time.Now().UTC().Add(-SessionRetention).Format(time.RFC3339)
if _, err := tx.Exec(`
DELETE FROM stream_sessions
WHERE ended_at <> '' AND ended_at < ?`, sessionCutoff); err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}

View file

@ -0,0 +1,211 @@
package db
import (
"database/sql"
"fmt"
"time"
)
// Session end reasons recorded when a run closes.
const (
SessionStopped = "stopped"
SessionNREExit = "nre_exit"
SessionOrphaned = "orphaned"
SessionTimeout = "timeout"
)
// SessionRetention is how long closed run history is kept.
const SessionRetention = 90 * 24 * time.Hour
// StreamSession is one media worker run: start → stop/crash with a duration.
type StreamSession struct {
ID int64 `json:"id"`
StreamID int64 `json:"stream_id"`
StreamName string `json:"stream_name,omitempty"`
StreamTitle string `json:"stream_title,omitempty"`
StartedAt string `json:"started_at"`
EndedAt string `json:"ended_at,omitempty"`
DurationS float64 `json:"duration_s"`
EndReason string `json:"end_reason,omitempty"`
HealthAtEnd string `json:"health_at_end,omitempty"`
}
func (s *Store) migrateSessions() error {
_, err := s.DB.Exec(`
CREATE TABLE IF NOT EXISTS stream_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
started_at TEXT NOT NULL,
ended_at TEXT NOT NULL DEFAULT '',
duration_s REAL NOT NULL DEFAULT 0,
end_reason TEXT NOT NULL DEFAULT '',
health_at_end TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_sessions_stream_started ON stream_sessions(stream_id, started_at DESC);
CREATE INDEX IF NOT EXISTS idx_sessions_ended ON stream_sessions(ended_at DESC);
CREATE INDEX IF NOT EXISTS idx_sessions_open ON stream_sessions(stream_id, ended_at);
`)
return err
}
// OpenSession records a new run for streamID. Any previously open row for the
// same stream is closed as orphaned (e.g. process crash without a clean stop).
func (s *Store) OpenSession(streamID int64) (int64, error) {
if streamID == 0 {
return 0, fmt.Errorf("stream id required")
}
_ = s.CloseOpenSessions(streamID, SessionOrphaned, "stopped")
started := now()
res, err := s.DB.Exec(`
INSERT INTO stream_sessions(stream_id, started_at)
VALUES(?, ?)`, streamID, started)
if err != nil {
return 0, err
}
return res.LastInsertId()
}
// CloseSession ends one open session by id. Already-closed rows are a no-op.
func (s *Store) CloseSession(id int64, reason, healthAtEnd string) error {
if id == 0 {
return nil
}
var started string
var ended string
err := s.DB.QueryRow(`SELECT started_at, ended_at FROM stream_sessions WHERE id=?`, id).
Scan(&started, &ended)
if err == sql.ErrNoRows {
return nil
}
if err != nil {
return err
}
if ended != "" {
return nil
}
endedAt := now()
dur := durationSeconds(started, endedAt)
if reason == "" {
reason = SessionStopped
}
_, err = s.DB.Exec(`
UPDATE stream_sessions
SET ended_at=?, duration_s=?, end_reason=?, health_at_end=?
WHERE id=? AND ended_at=''`,
endedAt, dur, reason, healthAtEnd, id)
return err
}
// CloseOpenSessions ends every open session for a stream.
func (s *Store) CloseOpenSessions(streamID int64, reason, healthAtEnd string) error {
if streamID == 0 {
return nil
}
rows, err := s.DB.Query(`
SELECT id FROM stream_sessions WHERE stream_id=? AND ended_at=''`, streamID)
if err != nil {
return err
}
defer rows.Close()
var ids []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return err
}
ids = append(ids, id)
}
for _, id := range ids {
if err := s.CloseSession(id, reason, healthAtEnd); err != nil {
return err
}
}
return nil
}
// ListRecentSessions returns the newest closed runs across all streams.
func (s *Store) ListRecentSessions(limit int) ([]StreamSession, error) {
if limit <= 0 {
limit = 50
}
if limit > 200 {
limit = 200
}
rows, err := s.DB.Query(`
SELECT ss.id, ss.stream_id, COALESCE(st.name,''), COALESCE(st.title,''),
ss.started_at, ss.ended_at, ss.duration_s, ss.end_reason, ss.health_at_end
FROM stream_sessions ss
LEFT JOIN streams st ON st.id = ss.stream_id
WHERE ss.ended_at <> ''
ORDER BY ss.ended_at DESC, ss.id DESC
LIMIT ?`, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []StreamSession
for rows.Next() {
var ss StreamSession
if err := rows.Scan(
&ss.ID, &ss.StreamID, &ss.StreamName, &ss.StreamTitle,
&ss.StartedAt, &ss.EndedAt, &ss.DurationS, &ss.EndReason, &ss.HealthAtEnd,
); err != nil {
return nil, err
}
out = append(out, ss)
}
return out, rows.Err()
}
// ListStreamSessions returns recent closed runs for one stream.
func (s *Store) ListStreamSessions(streamID int64, limit int) ([]StreamSession, error) {
if limit <= 0 {
limit = 50
}
rows, err := s.DB.Query(`
SELECT ss.id, ss.stream_id, COALESCE(st.name,''), COALESCE(st.title,''),
ss.started_at, ss.ended_at, ss.duration_s, ss.end_reason, ss.health_at_end
FROM stream_sessions ss
LEFT JOIN streams st ON st.id = ss.stream_id
WHERE ss.stream_id=? AND ss.ended_at <> ''
ORDER BY ss.ended_at DESC, ss.id DESC
LIMIT ?`, streamID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []StreamSession
for rows.Next() {
var ss StreamSession
if err := rows.Scan(
&ss.ID, &ss.StreamID, &ss.StreamName, &ss.StreamTitle,
&ss.StartedAt, &ss.EndedAt, &ss.DurationS, &ss.EndReason, &ss.HealthAtEnd,
); err != nil {
return nil, err
}
out = append(out, ss)
}
return out, rows.Err()
}
// PruneSessions drops closed sessions older than SessionRetention.
func (s *Store) PruneSessions() error {
cutoff := time.Now().UTC().Add(-SessionRetention).Format(time.RFC3339)
_, err := s.DB.Exec(`
DELETE FROM stream_sessions
WHERE ended_at <> '' AND ended_at < ?`, cutoff)
return err
}
func durationSeconds(startedAt, endedAt string) float64 {
start, err1 := time.Parse(time.RFC3339, startedAt)
end, err2 := time.Parse(time.RFC3339, endedAt)
if err1 != nil || err2 != nil {
return 0
}
d := end.Sub(start).Seconds()
if d < 0 {
return 0
}
return d
}

View file

@ -0,0 +1,114 @@
package db
import (
"path/filepath"
"testing"
"time"
)
func TestStreamSessionsOpenCloseList(t *testing.T) {
store, err := Open(filepath.Join(t.TempDir(), "data"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
st, err := store.CreateStream(CreateStream{
Name: "bbc1", Title: "BBC One", MPD: "https://example.test/a.mpd",
})
if err != nil {
t.Fatal(err)
}
id1, err := store.OpenSession(st.ID)
if err != nil || id1 == 0 {
t.Fatalf("OpenSession: id=%d err=%v", id1, err)
}
time.Sleep(20 * time.Millisecond)
if err := store.CloseSession(id1, SessionStopped, "stopped"); err != nil {
t.Fatal(err)
}
// Second open should orphan-close nothing (already closed) and create a new row.
id2, err := store.OpenSession(st.ID)
if err != nil || id2 == 0 || id2 == id1 {
t.Fatalf("second OpenSession: id=%d (first=%d) err=%v", id2, id1, err)
}
if err := store.CloseSession(id2, SessionNREExit, "down"); err != nil {
t.Fatal(err)
}
// Idempotent close.
if err := store.CloseSession(id2, SessionStopped, "stopped"); err != nil {
t.Fatal(err)
}
recent, err := store.ListRecentSessions(10)
if err != nil {
t.Fatal(err)
}
if len(recent) != 2 {
t.Fatalf("recent len=%d want 2", len(recent))
}
// Newest ended first.
if recent[0].ID != id2 || recent[0].EndReason != SessionNREExit {
t.Fatalf("newest = %+v", recent[0])
}
if recent[1].ID != id1 || recent[1].EndReason != SessionStopped {
t.Fatalf("older = %+v", recent[1])
}
if recent[0].StreamName != "bbc1" || recent[0].DurationS < 0 {
t.Fatalf("row fields: %+v", recent[0])
}
per, err := store.ListStreamSessions(st.ID, 5)
if err != nil || len(per) != 2 {
t.Fatalf("ListStreamSessions: len=%d err=%v", len(per), err)
}
}
func TestOpenSessionClosesOrphan(t *testing.T) {
store, err := Open(filepath.Join(t.TempDir(), "data"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
st, err := store.CreateStream(CreateStream{
Name: "rte1", MPD: "https://example.test/b.mpd",
})
if err != nil {
t.Fatal(err)
}
orphan, err := store.OpenSession(st.ID)
if err != nil {
t.Fatal(err)
}
next, err := store.OpenSession(st.ID)
if err != nil {
t.Fatal(err)
}
if next == orphan {
t.Fatal("expected a new session id")
}
var ended, reason string
if err := store.DB.QueryRow(
`SELECT ended_at, end_reason FROM stream_sessions WHERE id=?`, orphan,
).Scan(&ended, &reason); err != nil {
t.Fatal(err)
}
if ended == "" || reason != SessionOrphaned {
t.Fatalf("orphan close: ended=%q reason=%q", ended, reason)
}
_ = store.CloseSession(next, SessionStopped, "stopped")
recent, err := store.ListRecentSessions(10)
if err != nil {
t.Fatal(err)
}
if len(recent) != 2 {
t.Fatalf("want 2 closed sessions, got %d", len(recent))
}
}

View file

@ -0,0 +1,80 @@
package egress
import (
"bufio"
"strings"
)
// wgInterfaceAddrs extracts Address= values from the [Interface] section of a
// wg-quick style conf. Private keys are never returned or logged.
func wgInterfaceAddrs(conf string) []string {
var addrs []string
section := ""
sc := bufio.NewScanner(strings.NewReader(conf))
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
continue
}
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
section = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1]))
continue
}
if section != "interface" {
continue
}
key, val, ok := strings.Cut(line, "=")
if !ok {
continue
}
if strings.EqualFold(strings.TrimSpace(key), "Address") {
for _, part := range strings.Split(val, ",") {
if a := strings.TrimSpace(part); a != "" {
addrs = append(addrs, a)
}
}
}
}
return addrs
}
// wgSetconfBody strips wg-quick-only keys so the result is valid for `wg setconf`.
func wgSetconfBody(conf string) string {
var b strings.Builder
section := ""
sc := bufio.NewScanner(strings.NewReader(conf))
for sc.Scan() {
raw := sc.Text()
line := strings.TrimSpace(raw)
if line == "" || strings.HasPrefix(line, "#") || strings.HasPrefix(line, ";") {
continue
}
if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") {
section = strings.ToLower(strings.TrimSpace(line[1 : len(line)-1]))
b.WriteString(line)
b.WriteByte('\n')
continue
}
key, _, ok := strings.Cut(line, "=")
if !ok {
continue
}
k := strings.ToLower(strings.TrimSpace(key))
if section == "interface" {
switch k {
case "privatekey", "listenport", "fwmark":
b.WriteString(line)
b.WriteByte('\n')
}
continue
}
if section == "peer" {
switch k {
case "publickey", "presharedkey", "allowedips", "endpoint", "persistentkeepalive":
b.WriteString(line)
b.WriteByte('\n')
}
}
}
return b.String()
}

View file

@ -0,0 +1,418 @@
package egress
import (
"fmt"
"io"
"log/slog"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"streamd/apps/streamd/internal/db"
)
const (
baseListenPort = 18080
socksPortInNS = 1080
)
// Manager brings named egress profiles up and resolves a stream's origin proxy.
type Manager struct {
DataDir string
Store *db.Store
Log *slog.Logger
SocksBin string // microsocks or gost; looked up if empty
mu sync.Mutex
running map[string]*runState // by profile name
}
type runState struct {
name string
listenPort int
nsIP string // veth IP inside netns, e.g. 10.255.N.2
socksCmd *exec.Cmd
forwardLn net.Listener
stopFwd chan struct{}
}
// New builds a Manager. SocksBin may be empty (auto LookPath).
func New(dataDir string, store *db.Store, log *slog.Logger, socksBin string) *Manager {
if log == nil {
log = slog.Default()
}
return &Manager{
DataDir: dataDir,
Store: store,
Log: log,
SocksBin: socksBin,
running: map[string]*runState{},
}
}
// WarnMissingDeps logs once when WireGuard host tools are absent. Safe to call
// on every platform; non-Linux hosts skip the check.
func (m *Manager) WarnMissingDeps() {
if runtime.GOOS != "linux" {
return
}
for _, bin := range []string{"ip", "wg"} {
if _, err := exec.LookPath(bin); err != nil {
m.logger().Warn("egress: tool missing from PATH (WireGuard profiles need it)",
"bin", bin)
}
}
if _, err := m.findSocksBin(); err != nil {
m.logger().Warn("egress: microsocks or gost missing from PATH (WireGuard profiles need a SOCKS forwarder in the netns)")
}
}
func (m *Manager) logger() *slog.Logger {
if m.Log != nil {
return m.Log
}
return slog.Default()
}
func (m *Manager) profileDir(name string) string {
return filepath.Join(m.DataDir, "egress", db.Slug(name))
}
func (m *Manager) confPath(name string) string {
return filepath.Join(m.profileDir(name), "wg.conf")
}
// HasConf reports whether a WireGuard conf file exists for name.
func (m *Manager) HasConf(name string) bool {
st, err := os.Stat(m.confPath(name))
return err == nil && st.Size() > 0
}
// WriteConf stores a WireGuard conf on disk (0600). Does not log contents.
func (m *Manager) WriteConf(name, contents string) error {
name = db.Slug(name)
if name == "" {
return fmt.Errorf("name required")
}
dir := m.profileDir(name)
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
path := m.confPath(name)
tmp := path + ".tmp"
if err := os.WriteFile(tmp, []byte(contents), 0o600); err != nil {
return err
}
return os.Rename(tmp, path)
}
// ReadConf returns the raw conf for admin use. Callers must not log it.
func (m *Manager) ReadConf(name string) (string, error) {
b, err := os.ReadFile(m.confPath(name))
if err != nil {
return "", err
}
return string(b), nil
}
// RemoveFiles deletes on-disk conf for a profile (after DB delete).
func (m *Manager) RemoveFiles(name string) error {
name = db.Slug(name)
if name == "" {
return nil
}
return os.RemoveAll(m.profileDir(name))
}
// Enrich fills HasConf on profiles (conf is never stored in the DB).
func (m *Manager) Enrich(p *db.EgressProfile) {
if p == nil {
return
}
if p.Kind == db.EgressKindWireGuard {
p.HasConf = m.HasConf(p.Name)
}
}
// ResolveProxy returns the SOCKS/HTTP proxy URL a stream should use for origin
// fetch. Order: explicit stream.Proxy, then named egress profile, else empty.
func (m *Manager) ResolveProxy(st db.Stream) (string, error) {
if p := strings.TrimSpace(st.Proxy); p != "" {
return p, nil
}
name := strings.TrimSpace(st.Egress)
if name == "" {
return "", nil
}
if err := m.EnsureUp(name); err != nil {
return "", err
}
p, err := m.Store.GetEgressProfileByName(name)
if err != nil {
return "", err
}
switch p.Kind {
case db.EgressKindSocks:
u := strings.TrimSpace(p.SocksURL)
if u == "" {
return "", fmt.Errorf("egress %q has no socks_url", p.Name)
}
return u, nil
default:
if p.ListenPort <= 0 {
return "", fmt.Errorf("egress %q is up but has no listen port", p.Name)
}
return fmt.Sprintf("socks5://127.0.0.1:%d", p.ListenPort), nil
}
}
// StartEnabled brings up every profile marked enabled.
func (m *Manager) StartEnabled() {
list, err := m.Store.ListEgressProfiles()
if err != nil {
m.logger().Error("list egress profiles", "err", err)
return
}
for _, p := range list {
if !p.Enabled {
continue
}
if err := m.EnsureUp(p.Name); err != nil {
m.logger().Warn("egress start", "name", p.Name, "err", err)
}
}
}
// StopAll tears down every running profile.
func (m *Manager) StopAll() {
m.mu.Lock()
names := make([]string, 0, len(m.running))
for n := range m.running {
names = append(names, n)
}
m.mu.Unlock()
for _, n := range names {
_ = m.Down(n)
}
}
// Status returns the DB row for a profile (with HasConf filled).
func (m *Manager) Status(name string) (db.EgressProfile, error) {
p, err := m.Store.GetEgressProfileByName(name)
if err != nil {
return p, err
}
m.Enrich(&p)
return p, nil
}
// EnsureUp brings a profile to a usable SOCKS endpoint.
func (m *Manager) EnsureUp(name string) error {
name = db.Slug(name)
if name == "" {
return fmt.Errorf("egress name required")
}
p, err := m.Store.GetEgressProfileByName(name)
if err != nil {
return fmt.Errorf("egress profile %q: %w", name, err)
}
m.mu.Lock()
if rs, ok := m.running[name]; ok && rs != nil {
m.mu.Unlock()
return nil
}
m.mu.Unlock()
_ = m.Store.SetEgressRuntime(p.ID, db.EgressStarting, "", p.EgressIP, p.ListenPort)
switch p.Kind {
case db.EgressKindSocks:
u := strings.TrimSpace(p.SocksURL)
if u == "" {
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, "socks_url required", "", 0)
return fmt.Errorf("egress %q: socks_url required", name)
}
m.mu.Lock()
m.running[name] = &runState{name: name}
m.mu.Unlock()
_ = m.Store.SetEgressRuntime(p.ID, db.EgressUp, "", "", 0)
return nil
case db.EgressKindWireGuard:
if runtime.GOOS != "linux" {
msg := "wireguard egress requires Linux"
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
return fmt.Errorf("%s", msg)
}
return m.ensureWireGuardUp(p)
default:
msg := fmt.Sprintf("unknown egress kind %q", p.Kind)
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
return fmt.Errorf("%s", msg)
}
}
// Down stops a profile's local SOCKS / netns.
func (m *Manager) Down(name string) error {
name = db.Slug(name)
p, err := m.Store.GetEgressProfileByName(name)
if err != nil {
return err
}
m.mu.Lock()
rs := m.running[name]
delete(m.running, name)
m.mu.Unlock()
if rs != nil {
m.stopRun(rs)
}
if p.Kind == db.EgressKindWireGuard && runtime.GOOS == "linux" {
if err := m.teardownWireGuard(name, p.ID); err != nil {
m.logger().Warn("egress teardown", "name", name, "err", err)
}
}
_ = m.Store.SetEgressRuntime(p.ID, db.EgressStopped, "", "", 0)
return nil
}
func (m *Manager) stopRun(rs *runState) {
if rs.stopFwd != nil {
close(rs.stopFwd)
rs.stopFwd = nil
}
if rs.forwardLn != nil {
_ = rs.forwardLn.Close()
rs.forwardLn = nil
}
if rs.socksCmd != nil && rs.socksCmd.Process != nil {
_ = rs.socksCmd.Process.Kill()
_, _ = rs.socksCmd.Process.Wait()
rs.socksCmd = nil
}
}
func (m *Manager) findSocksBin() (string, error) {
if m.SocksBin != "" {
return m.SocksBin, nil
}
for _, n := range []string{"microsocks", "gost"} {
if p, err := exec.LookPath(n); err == nil {
m.SocksBin = p
return p, nil
}
}
return "", fmt.Errorf("microsocks (or gost) not found on PATH")
}
func (m *Manager) allocListenPort(id int64) int {
return baseListenPort + int(id%1000)
}
func (m *Manager) vethAddrs(id int64) (hostIP, nsIP, subnet string) {
// Unique /30-ish /24 host pair per profile id (1..254).
n := int(id % 200)
if n <= 0 {
n = 1
}
hostIP = fmt.Sprintf("10.255.%d.1", n)
nsIP = fmt.Sprintf("10.255.%d.2", n)
subnet = fmt.Sprintf("10.255.%d.0/24", n)
return hostIP, nsIP, subnet
}
func (m *Manager) startLocalForward(listenPort int, destHost string, destPort int) (net.Listener, chan struct{}, error) {
ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", listenPort))
if err != nil {
return nil, nil, err
}
stop := make(chan struct{})
go func() {
for {
c, err := ln.Accept()
if err != nil {
select {
case <-stop:
return
default:
return
}
}
go proxyTCP(c, fmt.Sprintf("%s:%d", destHost, destPort))
}
}()
return ln, stop, nil
}
func proxyTCP(client net.Conn, addr string) {
defer client.Close()
_ = client.SetDeadline(time.Now().Add(60 * time.Second))
upstream, err := net.DialTimeout("tcp", addr, 15*time.Second)
if err != nil {
return
}
defer upstream.Close()
_ = client.SetDeadline(time.Time{})
_ = upstream.SetDeadline(time.Time{})
done := make(chan struct{}, 2)
go func() { _, _ = io.Copy(upstream, client); done <- struct{}{} }()
go func() { _, _ = io.Copy(client, upstream); done <- struct{}{} }()
<-done
}
// TestDial tries a short TCP connect through the resolved SOCKS endpoint of a
// profile (after EnsureUp). Used by POST /api/egress/:name/test.
func (m *Manager) TestDial(name string) (map[string]any, error) {
if err := m.EnsureUp(name); err != nil {
return nil, err
}
p, err := m.Store.GetEgressProfileByName(name)
if err != nil {
return nil, err
}
var proxyURL string
switch p.Kind {
case db.EgressKindSocks:
proxyURL = strings.TrimSpace(p.SocksURL)
default:
if p.ListenPort <= 0 {
return nil, fmt.Errorf("no listen port")
}
proxyURL = fmt.Sprintf("socks5://127.0.0.1:%d", p.ListenPort)
}
out := map[string]any{
"ok": true,
"name": p.Name,
"kind": p.Kind,
"proxy_url": proxyURL,
"status": p.Status,
"egress_ip": p.EgressIP,
}
// Dial the local SOCKS port to confirm it accepts TCP.
hostPort := ""
if p.Kind == db.EgressKindWireGuard && p.ListenPort > 0 {
hostPort = fmt.Sprintf("127.0.0.1:%d", p.ListenPort)
} else if u := strings.TrimPrefix(strings.TrimPrefix(proxyURL, "socks5://"), "socks5h://"); u != proxyURL {
if i := strings.LastIndex(u, "@"); i >= 0 {
u = u[i+1:]
}
hostPort = u
}
if hostPort != "" {
c, err := net.DialTimeout("tcp", hostPort, 5*time.Second)
if err != nil {
out["ok"] = false
out["error"] = err.Error()
return out, fmt.Errorf("socks dial: %w", err)
}
_ = c.Close()
out["socks_reachable"] = true
}
return out, nil
}

View file

@ -0,0 +1,100 @@
package egress
import (
"path/filepath"
"strings"
"testing"
"streamd/apps/streamd/internal/db"
)
func TestResolveProxyOrder(t *testing.T) {
dir := t.TempDir()
store, err := db.Open(filepath.Join(dir, "data"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
m := New(filepath.Join(dir, "data"), store, nil, "")
// Neither proxy nor egress.
got, err := m.ResolveProxy(db.Stream{Name: "a"})
if err != nil || got != "" {
t.Fatalf("empty: got %q err %v", got, err)
}
// Explicit proxy wins over egress.
got, err = m.ResolveProxy(db.Stream{
Proxy: "socks5://127.0.0.1:9999",
Egress: "london",
})
if err != nil || got != "socks5://127.0.0.1:9999" {
t.Fatalf("proxy wins: got %q err %v", got, err)
}
on := true
_, err = store.CreateEgressProfile(db.CreateEgressProfile{
Name: "dublin",
Kind: db.EgressKindSocks,
Enabled: &on,
SocksURL: "socks5://10.0.0.5:1080",
})
if err != nil {
t.Fatal(err)
}
got, err = m.ResolveProxy(db.Stream{Egress: "dublin"})
if err != nil || got != "socks5://10.0.0.5:1080" {
t.Fatalf("egress socks: got %q err %v", got, err)
}
// Missing profile.
_, err = m.ResolveProxy(db.Stream{Egress: "missing"})
if err == nil {
t.Fatal("expected error for missing profile")
}
// WireGuard on non-Linux must fail EnsureUp (covered when GOOS != linux).
_, err = store.CreateEgressProfile(db.CreateEgressProfile{
Name: "london", Kind: db.EgressKindWireGuard, Enabled: &on,
})
if err != nil {
t.Fatal(err)
}
_, err = m.ResolveProxy(db.Stream{Egress: "london"})
// On Linux without conf/tools this also errors; on Windows always errors.
if err == nil {
t.Fatal("expected wireguard EnsureUp to fail without a working tunnel")
}
}
func TestWgConfParse(t *testing.T) {
conf := `[Interface]
PrivateKey = AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEE=
Address = 10.64.0.2/32
Address = fd00::2/128
DNS = 1.1.1.1
[Peer]
PublicKey = BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBEE=
AllowedIPs = 0.0.0.0/0, ::/0
Endpoint = 203.0.113.1:51820
`
addrs := wgInterfaceAddrs(conf)
if len(addrs) != 2 || addrs[0] != "10.64.0.2/32" || addrs[1] != "fd00::2/128" {
t.Fatalf("addrs: %#v", addrs)
}
body := wgSetconfBody(conf)
lower := strings.ToLower(body)
if strings.Contains(lower, "address") || strings.Contains(lower, "dns") {
t.Fatalf("setconf body still has wg-quick keys:\n%s", body)
}
if !strings.Contains(body, "PrivateKey") || !strings.Contains(body, "PublicKey") {
t.Fatalf("setconf missing keys:\n%s", body)
}
addrs = wgInterfaceAddrs("[Interface]\nAddress = 10.1.0.2/32, 10.1.0.3/32\n")
if len(addrs) != 2 {
t.Fatalf("combined: %#v", addrs)
}
}

View file

@ -0,0 +1,302 @@
//go:build linux
package egress
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"streamd/apps/streamd/internal/db"
)
func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
name := p.Name
confPath := m.confPath(name)
raw, err := os.ReadFile(confPath)
if err != nil {
msg := "wg.conf missing; upload a WireGuard conf first"
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
return fmt.Errorf("egress %q: %s", name, msg)
}
addrs := wgInterfaceAddrs(string(raw))
if len(addrs) == 0 {
msg := "wg.conf has no Interface Address="
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
return fmt.Errorf("egress %q: %s", name, msg)
}
socksBin, err := m.findSocksBin()
if err != nil {
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
return err
}
if _, err := exec.LookPath("ip"); err != nil {
msg := "ip (iproute2) not found on PATH"
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
return fmt.Errorf("%s", msg)
}
if _, err := exec.LookPath("wg"); err != nil {
msg := "wg (wireguard-tools) not found on PATH"
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
return fmt.Errorf("%s", msg)
}
listenPort := p.ListenPort
if listenPort <= 0 {
listenPort = m.allocListenPort(p.ID)
}
hostIP, nsIP, _ := m.vethAddrs(p.ID)
nsName := netnsName(name)
wgDev := wgDevName(name)
hostVeth := hostVethName(name)
nsVeth := "hv0"
// Tear down any leftover state before bringing up.
_ = m.teardownWireGuard(name, p.ID)
run := func(args ...string) error {
cmd := exec.Command(args[0], args[1:]...)
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%s: %w (%s)", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
}
return nil
}
nsExec := func(args ...string) error {
full := append([]string{"ip", "netns", "exec", nsName}, args...)
return run(full...)
}
if err := run("ip", "netns", "add", nsName); err != nil {
// Already exists is fine after a partial teardown.
if !strings.Contains(err.Error(), "File exists") {
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, err.Error(), "", 0)
return err
}
}
// DNS inside the netns: host /etc/resolv.conf often points at
// 127.0.0.53 (systemd-resolved), which is unreachable from the ns.
// ip netns exec bind-mounts /etc/netns/<name>/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 ""
}

View file

@ -0,0 +1,19 @@
//go:build !linux
package egress
import (
"fmt"
"streamd/apps/streamd/internal/db"
)
func (m *Manager) ensureWireGuardUp(p db.EgressProfile) error {
msg := "wireguard egress requires Linux"
_ = m.Store.SetEgressRuntime(p.ID, db.EgressError, msg, "", 0)
return fmt.Errorf("%s", msg)
}
func (m *Manager) teardownWireGuard(name string, id int64) error {
return nil
}

View file

@ -64,6 +64,34 @@ func OpenWithBanner(path string, maxBytes int64, generations int, what string) (
return w, nil
}
// OpenCmdLog prepares a rotating append log and returns the live *os.File for
// exec.Cmd Stdout/Stderr. Go only inherits a real FD for *os.File; any other
// io.Writer becomes a pipe, and N_m3u8DL-RE's Spectre progress UI crashes on
// pipe-backed consoles (ArgumentException in LiveRenderable.RemoveRange).
//
// The caller owns the file and must Close it. Mid-run size rotation is skipped
// (rotation still happens at open when the prior file is already over the cap).
func OpenCmdLog(path string, maxBytes int64, generations int, what string) (*os.File, error) {
w, err := OpenWithBanner(path, maxBytes, generations, what)
if err != nil {
return nil, err
}
return w.DetachFile()
}
// DetachFile transfers ownership of the underlying *os.File to the caller.
// The Writer becomes inert; do not Write or Close it afterward.
func (w *Writer) DetachFile() (*os.File, error) {
w.mu.Lock()
defer w.mu.Unlock()
if w.f == nil {
return nil, os.ErrClosed
}
f := w.f
w.f = nil
return f, nil
}
func (w *Writer) reopen() error {
f, err := os.OpenFile(w.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {

View file

@ -28,6 +28,9 @@ const (
var NameRe = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$`)
// archDirRe matches .bin/<goos>-<goarch>/ 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"`
@ -387,23 +390,7 @@ func inspectZipReader(zr *zip.Reader, nameHint string) (string, []zipEntry, erro
}
if hint == "" {
// Try to infer from .bin/<arch>/<name> or .bin/<name>.
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
}
}
hint = inferNameFromBinEntries(zr, prefix)
}
if hint == "" {
return "", nil, fmt.Errorf("cannot infer module name from zip; pass name=")
@ -476,6 +463,47 @@ func extractZipEntries(zipBytes []byte, entries []zipEntry, destDir string) erro
return nil
}
// inferNameFromBinEntries picks the module binary basename from
// .bin/<arch>/<name>[.exe] or .bin/<name>[.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/<arch>/<name>
if len(parts) >= 2 && archDirRe.MatchString(parts[0]) {
return base
}
// .bin/<name>
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)

View file

@ -29,6 +29,27 @@ 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)

View file

@ -8,7 +8,6 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
@ -37,12 +36,19 @@ type Media struct {
// ViewersFn reports the live client count for a stream, for the metrics
// series. Optional.
ViewersFn func(streamName string) int
// ProxyResolver resolves stream.Proxy / stream.Egress to a SOCKS/HTTP URL.
ProxyResolver ProxyResolver
mu sync.Mutex
procs map[int64]*streamProc
stopMon chan struct{}
}
// ProxyResolver turns a stream row into an origin-fetch proxy URL.
type ProxyResolver interface {
ResolveProxy(st db.Stream) (string, error)
}
// Notifier is the subset of the websocket hub the supervisor needs.
type Notifier interface {
NotifyRuntime(name, health string)
@ -55,11 +61,13 @@ type streamProc struct {
nre *exec.Cmd
ffmpeg *exec.Cmd
started time.Time
sessionID int64 // stream_sessions row opened when NRE starts
workDir string
wwwDir string
tsPath string
hlsIndex string
nreLog *logfile.Writer
nreLogFile *os.File // per-stream NRE log (banner + append)
nrePTY io.Closer // Linux PTY master; nil on Windows / fallback
ffOutLog *logfile.Writer
ffErrLog *logfile.Writer
stopping bool
@ -82,15 +90,16 @@ type streamProc struct {
// Options for constructing the media supervisor.
type Options struct {
Store *db.Store
DataDir string
NRE string
FFmpeg string
MP4Decrypt string
Log *slog.Logger
Fanout *tsfanout.Set
Notifier Notifier
ViewersFn func(streamName string) int
Store *db.Store
DataDir string
NRE string
FFmpeg string
MP4Decrypt string
Log *slog.Logger
Fanout *tsfanout.Set
Notifier Notifier
ViewersFn func(streamName string) int
ProxyResolver ProxyResolver
}
func NewMedia(opt Options) *Media {
@ -103,17 +112,18 @@ func NewMedia(opt Options) *Media {
fan = tsfanout.NewSet(tsfanout.DefaultBufferBytes)
}
m := &Media{
Store: opt.Store,
DataDir: opt.DataDir,
NRE: opt.NRE,
FFmpeg: opt.FFmpeg,
MP4Decrypt: opt.MP4Decrypt,
Log: lg,
Fanout: fan,
Notifier: opt.Notifier,
ViewersFn: opt.ViewersFn,
procs: map[int64]*streamProc{},
stopMon: make(chan struct{}),
Store: opt.Store,
DataDir: opt.DataDir,
NRE: opt.NRE,
FFmpeg: opt.FFmpeg,
MP4Decrypt: opt.MP4Decrypt,
Log: lg,
Fanout: fan,
Notifier: opt.Notifier,
ViewersFn: opt.ViewersFn,
ProxyResolver: opt.ProxyResolver,
procs: map[int64]*streamProc{},
stopMon: make(chan struct{}),
}
go m.monitorLoop()
return m
@ -143,6 +153,13 @@ func (m *Media) Running(id int64) bool {
func (m *Media) logsDir() string { return filepath.Join(m.DataDir, "logs") }
func (m *Media) effectiveProxy(st db.Stream) (string, error) {
if m.ProxyResolver != nil {
return m.ProxyResolver.ResolveProxy(st)
}
return strings.TrimSpace(st.Proxy), nil
}
func (m *Media) Start(id int64) error {
st, err := m.Store.GetStream(id)
if err != nil {
@ -203,12 +220,17 @@ func (m *Media) Start(id int64) error {
saveName := st.Name
headers := headerMap(st.HeadersJSON)
cfg := settingsFor(st, m.Store.GlobalPackagerSettings())
originProxy, err := m.effectiveProxy(st)
if err != nil {
m.fail(id, st.Name, "egress: "+err.Error())
return err
}
manifestURL := st.MPD
var mpdProxy *mpd.LocalServer
// The rewriter is named by the stream row or its app module and looked up in
// the mpd registry, so streamd needs no knowledge of any provider.
if rw, needed := mpd.Lookup(cfg.Rewriter); needed && strings.TrimSpace(st.MPD) != "" && !cfg.IsHLS {
srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, st.Proxy)
srv, err := mpd.StartLocal(st.MPD, st.Key, headers, rw, originProxy)
if err != nil {
m.fail(id, st.Name, "mpd rewrite server: "+err.Error())
return err
@ -236,7 +258,10 @@ func (m *Media) Start(id int64) error {
"--tmp-dir", nreTmp,
"--no-ansi-color",
"--log-level", "ERROR",
"-ss", "0",
// Drop every subtitle track. Live pipe-mux to TS does not need them, and
// an extra Spectre progress row makes redirected-console crashes more
// likely (NRE forces ANSI UI when stdout is a log file).
"-ds", "for=all",
}
if hasKeys {
// Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so
@ -246,7 +271,7 @@ func (m *Media) Start(id int64) error {
"--mp4-real-time-decryption",
)
}
if proxy := strings.TrimSpace(st.Proxy); proxy != "" {
if proxy := strings.TrimSpace(originProxy); proxy != "" {
// NRE prefers --custom-proxy over the system proxy when both are set.
// The proxy may carry credentials, so it is not logged.
nreArgs = append(nreArgs, "--custom-proxy", proxy)
@ -273,23 +298,24 @@ func (m *Media) Start(id int64) error {
}
}
// A rotating log opened with a start banner, rather than truncated. The
// previous run's output is exactly what you need when working out why
// this run is happening.
nreLog, err := logfile.OpenWithBanner(
// Banner + rotate-on-open keep prior runs readable. On Linux, NRE runs under
// a PTY (see startNRELogged): plain file/pipe redirects force Spectre live UI
// with WindowWidth 0 and crash ProgressRefreshThread.
nreLogFile, err := logfile.OpenCmdLog(
filepath.Join(m.logsDir(), st.Name+"-nre.log"),
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "nre")
if err != nil {
return err
}
nreCmd := exec.Command(m.NRE, nreArgs...)
nreCmd.Stdout = nreLog
nreCmd.Stderr = nreLog
hideWindow(nreCmd)
// NRE (v0.6) resolves mp4decrypt via PATH / sibling of its .exe, and often
// ignores --decryption-binary-path for MP4DECRYPT. Match legacy: prepend
// dirs and best-effort copy beside NRE.
nreEnv := os.Environ()
nreEnv = setEnvDefault(nreEnv, "COLUMNS", "120")
nreEnv = setEnvDefault(nreEnv, "LINES", "40")
nreEnv = setEnvDefault(nreEnv, "TERM", "xterm")
pathPrepend := []string{}
if m.MP4Decrypt != "" {
pathPrepend = append(pathPrepend, filepath.Dir(m.MP4Decrypt))
@ -306,27 +332,37 @@ func (m *Media) Start(id int64) error {
nreEnv = prependPathEnv(nreEnv, strings.Join(pathPrepend, sep))
}
nreCmd.Env = nreEnv
if err := nreCmd.Start(); err != nil {
_ = nreLog.Close()
nrePTY, keepLogFD, err := startNRELogged(nreCmd, nreLogFile)
if err != nil {
if keepLogFD {
_ = nreLogFile.Close()
}
if mpdProxy != nil {
mpdProxy.Close()
}
m.fail(id, st.Name, err.Error())
return err
}
ownedLog := nreLogFile
if !keepLogFD {
ownedLog = nil
}
m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid)
sessionID, _ := m.Store.OpenSession(id)
sp := &streamProc{
id: id,
name: st.Name,
nre: nreCmd,
started: time.Now(),
workDir: workDir,
wwwDir: wwwDir,
tsPath: tsPath,
hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
nreLog: nreLog,
mpdProxy: mpdProxy,
id: id,
name: st.Name,
nre: nreCmd,
started: time.Now(),
sessionID: sessionID,
workDir: workDir,
wwwDir: wwwDir,
tsPath: tsPath,
hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
nreLogFile: ownedLog,
nrePTY: nrePTY,
mpdProxy: mpdProxy,
variantSpecs: variantSpecs,
outputSpecs: outputSpecs,
@ -411,12 +447,13 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
_ = m.Store.SetRuntime(sp.id, db.RuntimePatch{
Health: "down",
PlayPath: "/hls/" + sp.name + "/index.m3u8",
LastError: "NRE exited before TS was ready — see logs/" + sp.name + "-nre.log",
LastError: "NRE exited before TS was ready — see data/logs/" + sp.name + "-nre.log",
})
m.Store.AddEvent(db.StreamEvent{
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
Message: "downloader exited before any media arrived — see logs/" + sp.name + "-nre.log",
Message: "downloader exited before any media arrived — see data/logs/" + sp.name + "-nre.log",
})
m.closeSession(sp, db.SessionNREExit, "down")
m.cleanupProc(sp.id)
return
}
@ -568,9 +605,11 @@ func (m *Media) Stop(id int64) error {
if st.Name != "" {
name = st.Name
}
_ = m.Store.CloseOpenSessions(id, db.SessionStopped, "stopped")
_ = m.Store.SetRuntime(id, db.RuntimePatch{Health: "stopped", PlayPath: "/hls/" + name + "/index.m3u8"})
return nil
}
m.closeSession(sp, db.SessionStopped, "stopped")
m.stopAllVariants(sp)
nrePID, ffPID := 0, 0
if sp.ffmpeg != nil && sp.ffmpeg.Process != nil {
@ -603,6 +642,15 @@ func (m *Media) Stop(id int64) error {
return nil
}
// closeSession ends the open stream_sessions row for this process, if any.
func (m *Media) closeSession(sp *streamProc, reason, health string) {
if sp == nil || sp.sessionID == 0 {
return
}
_ = m.Store.CloseSession(sp.sessionID, reason, health)
sp.sessionID = 0
}
func (m *Media) Restart(id int64) error {
m.Log.Info("hard restart", "stream_id", id)
_ = m.Stop(id)
@ -622,7 +670,15 @@ func (m *Media) cleanupProc(id int64) {
if !ok {
return
}
for _, w := range []*logfile.Writer{sp.nreLog, sp.ffOutLog, sp.ffErrLog} {
if sp.nrePTY != nil {
_ = sp.nrePTY.Close()
sp.nrePTY = nil
}
if sp.nreLogFile != nil {
_ = sp.nreLogFile.Close()
sp.nreLogFile = nil
}
for _, w := range []*logfile.Writer{sp.ffOutLog, sp.ffErrLog} {
if w != nil {
_ = w.Close()
}
@ -674,13 +730,14 @@ func (m *Media) refreshHealth(id int64) {
if nreDead {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down", PID: 0, PlayPath: playPath, UptimeS: uptime,
LastError: "NRE process exited — see logs/" + sp.name + "-nre.log",
LastError: "NRE process exited — see data/logs/" + sp.name + "-nre.log",
})
m.Store.AddEvent(db.StreamEvent{
StreamID: id, Kind: db.EventCrashed, Severity: db.SevError,
Message: fmt.Sprintf("downloader exited after %.0fs — see logs/%s-nre.log", uptime, sp.name),
Message: fmt.Sprintf("downloader exited after %.0fs — see data/logs/%s-nre.log", uptime, sp.name),
})
m.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime))
m.closeSession(sp, db.SessionNREExit, "down")
m.report(sp, "down")
m.cleanupProc(id)
return
@ -887,11 +944,7 @@ func killProcess(cmd *exec.Cmd) error {
if cmd == nil || cmd.Process == nil {
return nil
}
pid := cmd.Process.Pid
if runtime.GOOS == "windows" {
return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
}
return cmd.Process.Kill()
return killProcessTree(cmd)
}
func prependPathEnv(env []string, prefix string) []string {
@ -914,6 +967,20 @@ func prependPathEnv(env []string, prefix string) []string {
return out
}
// setEnvDefault sets KEY=value when KEY is missing or empty in env.
func setEnvDefault(env []string, key, value string) []string {
prefix := key + "="
for i, e := range env {
if strings.HasPrefix(e, prefix) {
if strings.TrimSpace(e[len(prefix):]) == "" {
env[i] = prefix + value
}
return env
}
}
return append(env, prefix+value)
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {

View file

@ -3,13 +3,27 @@
package supervisor
import (
"io"
"os"
"os/exec"
"strings"
"syscall"
)
func hideWindow(cmd *exec.Cmd) {}
func killProcessTree(cmd *exec.Cmd) error {
if cmd == nil || cmd.Process == nil {
return nil
}
pid := cmd.Process.Pid
// Negative PID signals the process group (script PTY wrapper + NRE).
if err := syscall.Kill(-pid, syscall.SIGKILL); err == nil {
return nil
}
return cmd.Process.Kill()
}
func processDead(pid int) bool {
p, err := os.FindProcess(pid)
if err != nil {
@ -18,3 +32,63 @@ func processDead(pid int) bool {
err = p.Signal(syscall.Signal(0))
return err != nil
}
// startNRELogged starts NRE under a PTY so Spectre.Console sees a real terminal.
// Plain file/pipe redirects make N_m3u8DL-RE force ANSI UI with WindowWidth 0,
// which crashes ProgressRefreshThread (ArgumentException/RemoveRange).
//
// Uses util-linux `script` when available (PTY + typescript log). Falls back to
// attaching logFile as Stdout/Stderr. keepLogFD is false when script took over
// the log path (caller must not Close logFile again).
func startNRELogged(cmd *exec.Cmd, logFile *os.File) (pty io.Closer, keepLogFD bool, err error) {
scriptPath, err := exec.LookPath("script")
if err != nil {
cmd.Stdout = logFile
cmd.Stderr = logFile
if err := cmd.Start(); err != nil {
return nil, true, err
}
return nopCloser{}, true, nil
}
logPath := logFile.Name()
_ = logFile.Sync()
_ = logFile.Close()
inner := shellJoin(append([]string{cmd.Path}, cmd.Args[1:]...)...)
// -q quiet header, -a append (keep prior runs), -f flush so log tails live.
wrapped := exec.Command(scriptPath, "-q", "-a", "-f", "-c", inner, logPath)
wrapped.Env = cmd.Env
wrapped.Dir = cmd.Dir
if cmd.SysProcAttr != nil {
wrapped.SysProcAttr = cmd.SysProcAttr
} else {
wrapped.SysProcAttr = &syscall.SysProcAttr{}
}
// Own process group so Stop can signal the whole tree (script + NRE).
wrapped.SysProcAttr.Setpgid = true
*cmd = *wrapped
if err := cmd.Start(); err != nil {
return nil, false, err
}
return nopCloser{}, false, nil
}
func shellJoin(argv ...string) string {
parts := make([]string, len(argv))
for i, a := range argv {
parts[i] = shellQuote(a)
}
return strings.Join(parts, " ")
}
func shellQuote(s string) string {
if s == "" {
return "''"
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
type nopCloser struct{}
func (nopCloser) Close() error { return nil }

View file

@ -3,8 +3,10 @@
package supervisor
import (
"io"
"os"
"os/exec"
"strconv"
"syscall"
)
@ -15,6 +17,29 @@ func hideWindow(cmd *exec.Cmd) {
}
}
func killProcessTree(cmd *exec.Cmd) error {
if cmd == nil || cmd.Process == nil {
return nil
}
pid := cmd.Process.Pid
return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
}
// startNRELogged attaches logFile as Stdout/Stderr. Windows CREATE_NO_WINDOW
// avoids the Spectre pipe-width crash that hits Linux daemons.
func startNRELogged(cmd *exec.Cmd, logFile *os.File) (io.Closer, bool, error) {
cmd.Stdout = logFile
cmd.Stderr = logFile
if err := cmd.Start(); err != nil {
return nil, true, err
}
return nopCloser{}, true, nil
}
type nopCloser struct{}
func (nopCloser) Close() error { return nil }
func processDead(pid int) bool {
p, err := os.FindProcess(pid)
if err != nil {

View file

@ -117,6 +117,20 @@ 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),

View file

@ -15,6 +15,7 @@ export const state = {
agents: [],
deps: null,
uptimeS: 0,
refreshedAt: 0,
connected: false,
lastError: "",
};
@ -57,6 +58,7 @@ 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);

View file

@ -36,6 +36,11 @@ 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
// <textarea>, and checked must be a property too.
else if (k === "value") node.value = v;
else if (k === "checked") node.checked = !!v;
else if (k === "selected") node.selected = !!v;
else if (v === true) node.setAttribute(k, "");
else node.setAttribute(k, v);
}

View file

@ -192,12 +192,186 @@ export function settingsView(root) {
),
),
);
wrap.append(await egressCard());
}
load();
return () => {};
}
async function egressCard() {
const box = el("div.card",
el("div.card-head",
el("h2", { text: "Egress tunnels" }),
el("span.spacer"),
el("button.sm", { type: "button", text: "+ Add profile", onclick: () => openEgressDialog(reload) }),
),
el("p.hint", {
text: "Named WireGuard (Linux netns + local SOCKS) or SOCKS URL profiles. " +
"Assign a profile per stream so only that stream’s origin fetch exits via the tunnel. " +
"Full-tunnel WG stays inside a network namespace — SSH and the dashboard keep the host route.",
}),
);
const list = el("div");
box.append(list);
async function reload() {
clear(list);
let data;
try {
data = await api.egress();
} catch (err) {
list.append(el("p.msg.err", { text: err.message }));
return;
}
const profiles = data.profiles || [];
if (!profiles.length) {
list.append(el("p.hint", { text: "No profiles yet. Add london (or dublin, …) from a WireGuard client .conf." }));
return;
}
for (const p of profiles) {
const status = p.status || "stopped";
const meta = [
p.kind,
status,
p.listen_port ? `:${p.listen_port}` : null,
p.egress_ip || null,
p.has_conf ? "conf" : null,
p.enabled ? "autostart" : null,
].filter(Boolean).join(" · ");
const row = el("div.row", {
style: { alignItems: "center", gap: "8px", flexWrap: "wrap", padding: "8px 0", borderBottom: "1px solid var(--border)" },
},
el("div", { style: { flex: "1 1 160px" } },
el("div.mono", { text: p.name }),
el("small.muted", { text: meta }),
p.last_error ? el("div.msg.err", { text: p.last_error, style: { marginTop: "4px" } }) : null,
),
el("button.ghost.sm", {
type: "button", text: "Up",
onclick: async () => {
try { await api.egressUp(p.name); toast(`${p.name} up`); reload(); }
catch (err) { toast(err.message, true); }
},
}),
el("button.ghost.sm", {
type: "button", text: "Down",
onclick: async () => {
try { await api.egressDown(p.name); toast(`${p.name} down`); reload(); }
catch (err) { toast(err.message, true); }
},
}),
el("button.ghost.sm", {
type: "button", text: "Test IP",
onclick: async () => {
try {
const r = await api.egressTest(p.name);
toast(`${p.name} egress IP: ${r.egress_ip || r.ip || JSON.stringify(r)}`);
reload();
} catch (err) { toast(err.message, true); }
},
}),
el("button.ghost.sm", {
type: "button", text: "Edit",
onclick: () => openEgressDialog(reload, p),
}),
el("button.ghost.sm.danger", {
type: "button", text: "Delete",
onclick: async () => {
if (!confirm(`Delete egress profile ${p.name}?`)) return;
try { await api.deleteEgress(p.name); toast("Deleted"); reload(); }
catch (err) { toast(err.message, true); }
},
}),
);
list.append(row);
}
}
await reload();
return box;
}
function openEgressDialog(onDone, existing) {
const isEdit = !!existing;
const name = el("input", {
required: true, placeholder: "london",
value: existing?.name || "",
disabled: isEdit,
});
const kind = el("select",
el("option", { value: "wireguard", text: "WireGuard (Linux netns)", selected: !existing || existing.kind === "wireguard" }),
el("option", { value: "socks", text: "SOCKS/HTTP URL only", selected: existing?.kind === "socks" }),
);
const enabled = el("input", { type: "checkbox", checked: existing ? !!existing.enabled : true });
const socksURL = el("input", {
placeholder: "socks5://127.0.0.1:1081",
value: existing?.socks_url || "",
});
const conf = el("textarea", {
rows: "12",
placeholder: "[Interface]\nPrivateKey = …\nAddress = …\n\n[Peer]\nPublicKey = …\nEndpoint = …\nAllowedIPs = 0.0.0.0/0, ::/0\n",
spellcheck: "false",
});
const msg = el("p.msg");
function syncKind() {
socksURL.closest("label").hidden = kind.value !== "socks";
conf.closest("label").hidden = kind.value !== "wireguard";
}
kind.addEventListener("change", syncKind);
const form = el("form",
el("div.grid",
el("label", el("span.lbl", { text: "Name (slug)" }), name),
el("label", el("span.lbl", { text: "Kind" }), kind),
el("label.inline-check", enabled, el("span", { text: "Auto-start with streamd serve" })),
el("label.span2", el("span.lbl", { text: "SOCKS/HTTP URL" }), socksURL),
el("label.span2", el("span.lbl", { text: "WireGuard client config" }), conf,
el("small.hint", { text: isEdit ? "Leave blank to keep the stored conf. Pasting replaces it." : "Paste a client .conf (e.g. vps-london.conf). Private keys stay on the server." })),
),
msg,
el("div.row.end", { style: { marginTop: "12px" } },
el("button.ghost", { type: "button", text: "Cancel", onclick: () => close() }),
el("button", { type: "submit", text: isEdit ? "Save" : "Create" }),
),
);
syncKind();
form.addEventListener("submit", async (ev) => {
ev.preventDefault();
msg.textContent = "";
msg.classList.remove("err");
const slug = name.value.trim();
try {
if (isEdit) {
const body = { kind: kind.value, enabled: enabled.checked };
if (kind.value === "socks") body.socks_url = socksURL.value.trim();
if (kind.value === "wireguard" && conf.value.trim()) body.conf = conf.value;
await api.saveEgress(existing.name, body);
} else {
const body = { name: slug, kind: kind.value, enabled: enabled.checked };
if (kind.value === "socks") body.socks_url = socksURL.value.trim();
await api.createEgress(body);
if (kind.value === "wireguard" && conf.value.trim()) {
await api.saveEgress(slug, { conf: conf.value });
}
}
toast(isEdit ? "Saved" : "Created");
close();
onDone();
} catch (err) {
msg.textContent = err.message;
msg.classList.add("err");
}
});
const close = openModal(
el("h2", { text: isEdit ? `Edit egress · ${existing.name}` : "Add egress profile" }),
form,
);
}
// ---------- people and API keys ----------
export function peopleView(root) {

View file

@ -1,15 +1,26 @@
// Dashboard: the headline numbers, what is scheduled next, and recent events.
import { el, pill, fmtRelative, fmtDateTime, setText, reconcile } from "../util.js";
import {
el, pill, fmtRelative, fmtDateTime, fmtSeconds, setText, reconcile, copyText,
} from "../util.js";
import { state, subscribe, refresh } from "../store.js";
import { timeline } from "../components.js";
const DONATIONS = [
{ coin: "ETH", addr: "0xa6314ce4deaa8329abba301802e3f511b3fa80a6" },
{ coin: "LTC", addr: "ltc1qpm26uccjgn4gx5pqxwzvs89mdp9hcshx9xj5a6" },
{ coin: "BTC", addr: "bc1qzr70ur76jhm5gjsuqelzqaskumpkhkk2ewjgha" },
];
export function dashboard(root) {
const alarmTiles = el("div.tiles");
const trafficTiles = el("div.tiles");
const upcomingBody = el("tbody");
const feed = el("div");
const attention = el("div.stack");
const uptimeBody = el("tbody");
const sessionsBody = el("tbody");
const supportBody = el("div.stack");
root.append(el("div.stack",
el("div.tile-band",
@ -24,6 +35,38 @@ export function dashboard(root) {
el("div.card-head", el("h2", { text: "Needs attention" })),
attention,
),
el("div.card",
el("div.card-head",
el("h2", { text: "Live uptimes" }),
el("span.spacer"),
el("a", { href: "#/streams", text: "All streams" }),
),
el("div.table-wrap",
el("table",
el("thead", el("tr",
el("th", { text: "Stream" }),
el("th", { text: "Health" }),
el("th", { text: "Uptime" }),
)),
uptimeBody,
),
),
),
el("div.card",
el("div.card-head", el("h2", { text: "Recent runs" })),
el("div.table-wrap",
el("table",
el("thead", el("tr",
el("th", { text: "Stream" }),
el("th", { text: "Started" }),
el("th", { text: "Ended" }),
el("th", { text: "Duration" }),
el("th", { text: "Reason" }),
)),
sessionsBody,
),
),
),
el("div.card",
el("div.card-head",
el("h2", { text: "Coming up" }),
@ -46,8 +89,36 @@ export function dashboard(root) {
el("div.card-head", el("h2", { text: "Recent activity" })),
feed,
),
el("div.card",
el("div.card-head", el("h2", { text: "Support the project" })),
el("p.sub", {
text: "If Streamd saves you time, donations keep development going.",
}),
supportBody,
),
));
supportBody.replaceChildren(...DONATIONS.map((d) =>
el("div.row",
el("span.pill", { text: d.coin }),
el("code.mono", { text: d.addr }),
el("span.spacer"),
el("button.tiny.ghost", {
type: "button",
text: "Copy",
onclick: (ev) => copyText(d.addr, d.coin + " address", ev.currentTarget),
}),
),
));
function liveUptimeSeconds(s) {
const health = s.health || "";
if (health !== "ok" && health !== "starting") return null;
const base = Number(s.uptime_s) || 0;
const fetched = state.refreshedAt || Date.now();
return base + Math.max(0, (Date.now() - fetched) / 1000);
}
function paint() {
const t = (state.overview && state.overview.totals) || {};
const streams = state.streams || [];
@ -126,6 +197,75 @@ export function dashboard(root) {
);
}
// Live uptimes: prefer enabled streams; fall back to all if none enabled.
const uptimeRows = (() => {
const enabled = streams.filter((s) => s.enabled);
return (enabled.length ? enabled : streams).slice().sort((a, b) =>
String(a.title || a.name).localeCompare(String(b.title || b.name)));
})();
if (!uptimeRows.length) {
reconcile(uptimeBody, [{ id: "none" }], (x) => x.id,
() => el("tr", el("td.empty", { colspan: "3", text: "No streams yet." })), () => {});
} else {
reconcile(uptimeBody, uptimeRows, (s) => s.id,
() => el("tr",
el("td.who"),
el("td.health"),
el("td.uptime.mono"),
),
(tr, s) => {
const who = tr.querySelector(".who");
who.replaceChildren(el("a", {
href: `#/stream/${s.id}`, text: s.title || s.name,
}));
tr.querySelector(".health").replaceChildren(pill(s.health || "stopped"));
const live = liveUptimeSeconds(s);
setText(tr.querySelector(".uptime"),
live == null ? "—" : fmtSeconds(live));
},
);
}
const sessions = (state.overview && state.overview.recent_sessions) || [];
if (!sessions.length) {
reconcile(sessionsBody, [{ id: "none" }], (x) => x.id,
() => el("tr", el("td.empty", {
colspan: "5",
text: "No completed runs yet — start a stream to begin history.",
})), () => {});
} else {
reconcile(sessionsBody, sessions, (s) => s.id,
() => el("tr",
el("td.who"),
el("td.started"),
el("td.ended"),
el("td.dur.mono"),
el("td.reason"),
),
(tr, s) => {
const who = tr.querySelector(".who");
who.replaceChildren(el("a", {
href: `#/stream/${s.stream_id}`,
text: s.stream_title || s.stream_name || `#${s.stream_id}`,
}));
const started = tr.querySelector(".started");
started.replaceChildren(
el("div", { text: fmtRelative(s.started_at) }),
el("div.sub", { text: fmtDateTime(s.started_at) }),
);
const ended = tr.querySelector(".ended");
ended.replaceChildren(
el("div", { text: fmtRelative(s.ended_at) }),
el("div.sub", { text: fmtDateTime(s.ended_at) }),
);
setText(tr.querySelector(".dur"), fmtSeconds(s.duration_s));
tr.querySelector(".reason").replaceChildren(
pill(s.end_reason || s.health_at_end || "—"),
);
},
);
}
const upcoming = (state.overview && state.overview.upcoming) || [];
if (!upcoming.length) {
reconcile(upcomingBody, [{ id: "none" }], (x) => x.id,
@ -160,8 +300,8 @@ export function dashboard(root) {
const off = subscribe(paint);
paint();
refresh("dashboard");
// Keep the relative times honest without a full refetch.
const tick = setInterval(paint, 30000);
// Keep relative times and live uptimes honest without a full refetch.
const tick = setInterval(paint, 1000);
return () => {
off();
clearInterval(tick);

View file

@ -215,8 +215,12 @@ async function uploadFile(file, reload) {
}
toast(`Uploading ${file.name}…`);
try {
const res = await api.uploadModuleZip(file);
const name = (res.module && res.module.name) || file.name;
// Pass stem of rte.zip → "rte" so flat release zips never become "darwin-arm64".
let hint = "";
const base = (file.name || "").replace(/\.zip$/i, "").trim();
if (/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(base)) hint = base;
const res = await api.uploadModuleZip(file, hint || undefined);
const name = (res.module && res.module.name) || hint || file.name;
toast(`Uploaded ${name}`);
reload();
} catch (err) {

View file

@ -33,7 +33,8 @@ export function streamCreate(root) {
const mpd = el("input", { placeholder: "https://…/manifest.mpd" });
const key = el("textarea", { rows: "3", placeholder: "KID:KEY per line — leave empty for clear streams", spellcheck: "false" });
const proxy = el("input", { placeholder: "socks5://127.0.0.1:1080 (optional)" });
const egress = el("select", el("option", { value: "", text: "Direct (no tunnel)" }));
const proxy = el("input", { placeholder: "socks5://… overrides egress if set" });
const headers = el("input", { value: "{}" });
const idle = el("input", { type: "number", value: "300", min: "30", max: "86400" });
const drm = el("select",
@ -98,6 +99,7 @@ export function streamCreate(root) {
channel: chanSel.value,
mpd: mpd.value.trim(),
key: key.value.trim(),
egress: egress.value.trim(),
proxy: proxy.value.trim(),
headers_json: headers.value.trim() || "{}",
tags: tags.value,
@ -171,7 +173,10 @@ export function streamCreate(root) {
panel.append(el("div.grid",
el("label.span2", el("span.lbl", { text: "Manifest URL" }), mpd),
el("label.span2", el("span.lbl", { text: "Keys" }), key),
el("label", el("span.lbl", { text: "Origin proxy" }), proxy),
el("label", el("span.lbl", { text: "Egress tunnel" }), egress,
el("small.hint", { text: "Named WireGuard / SOCKS profile (Settings → Egress). Direct = normal server route." })),
el("label", el("span.lbl", { text: "Origin proxy URL" }), proxy,
el("small.hint", { text: "Optional raw socks5:// or http://. If set, it overrides the egress dropdown." })),
el("label", el("span.lbl", { text: "Headers JSON" }), headers),
el("label", el("span.lbl", { text: "Encryption" }), drm),
el("label", el("span.lbl", { text: "Rewriter" }), rewriter),
@ -190,6 +195,8 @@ export function streamCreate(root) {
row("Title", b.title || "—"),
row("Module", b.app ? `${b.app} / ${b.channel || "—"}` : "—"),
row("Manifest", b.mpd || "(from module / capture)"),
row("Egress", b.egress || "Direct"),
row("Origin proxy", b.proxy || "—"),
row("Encryption", b.drm_mode),
row("On-demand", b.on_demand ? "yes" : "no"),
row("Public", b.public ? "yes" : "no"),
@ -256,6 +263,19 @@ export function streamCreate(root) {
} catch {
// Module list is optional.
}
try {
const eg = await api.egress();
clear(egress);
egress.append(el("option", { value: "", text: "Direct (no tunnel)" }));
for (const p of eg.profiles || []) {
const label = p.status && p.status !== "stopped"
? `${p.name} (${p.kind}, ${p.status})`
: `${p.name} (${p.kind})`;
egress.append(el("option", { value: p.name, text: label }));
}
} catch {
// Egress API optional on older servers.
}
paint();
})();

View file

@ -402,6 +402,7 @@ export function streamView(root, id, tab = "live") {
const tags = el("input", { value: s.tags || "" });
const mpd = el("input", { value: s.mpd || "" });
const key = el("textarea", { rows: "3", placeholder: s.has_key ? "unchanged — type to replace" : "none", spellcheck: "false" });
const egress = el("select", el("option", { value: "", text: "Direct (no tunnel)", selected: !s.egress }));
const proxy = el("input", { placeholder: s.has_proxy ? "unchanged — type to replace" : "none" });
const headers = el("input", { placeholder: s.has_headers ? "unchanged — type to replace" : "{}" });
const drm = el("select",
@ -482,6 +483,23 @@ export function streamView(root, id, tab = "live") {
if (s.rewriter && !rewriters.includes(s.rewriter)) {
rewriter.append(el("option", { value: s.rewriter, text: `${s.rewriter} (stored)`, selected: true }));
}
try {
const eg = await api.egress();
clear(egress);
egress.append(el("option", { value: "", text: "Direct (no tunnel)", selected: !s.egress }));
for (const p of eg.profiles || []) {
egress.append(el("option", {
value: p.name,
text: `${p.name} (${p.kind}${p.status ? ", " + p.status : ""})`,
selected: s.egress === p.name,
}));
}
if (s.egress && !(eg.profiles || []).some((p) => p.name === s.egress)) {
egress.append(el("option", { value: s.egress, text: `${s.egress} (stored)`, selected: true }));
}
} catch {
// Older servers without /api/egress.
}
})();
const revealBtn = el("button.ghost.sm", {
@ -514,7 +532,8 @@ export function streamView(root, id, tab = "live") {
el("label", el("span.lbl", { text: "Audio select" }), audioSel),
el("label.span2", el("span.lbl", { text: "Manifest URL" }), mpd),
el("label.span2", el("span.lbl", { text: "Keys" }), key),
el("label", el("span.lbl", { text: "Origin proxy" }), proxy),
el("label", el("span.lbl", { text: "Egress tunnel" }), egress),
el("label", el("span.lbl", { text: "Origin proxy URL" }), proxy),
el("label", el("span.lbl", { text: "Headers JSON" }), headers),
el("label", el("span.lbl", { text: "Idle timeout (s)" }), idle),
el("label", el("span.lbl", { text: "Segment seconds" }), hlsTime),
@ -560,6 +579,7 @@ export function streamView(root, id, tab = "live") {
};
// Only send a credential when it was actually typed, so saving the form
// does not wipe a key the browser was never given.
body.egress = egress.value.trim();
if (key.value.trim()) body.key = key.value.trim();
if (proxy.value.trim()) body.proxy = proxy.value.trim();
if (headers.value.trim()) {

View file

@ -0,0 +1,336 @@
package servecmd
import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
"gopkg.in/yaml.v3"
"streamd/bootstrap"
)
const (
defaultBind = "127.0.0.1:8083"
defaultLogLevel = "info"
defaultLogFile = "streamd.log"
defaultPIDFile = "streamd.pid"
defaultChannel = "stable"
defaultKeepOld = 10
configFileName = "streamd.yaml"
releaseBaseURL = "https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download"
)
// FileConfig is the on-disk streamd.yaml next to the binary.
type FileConfig struct {
Bind string `yaml:"bind,omitempty"`
Data string `yaml:"data,omitempty"`
LogLevel string `yaml:"log_level,omitempty"`
LogFile string `yaml:"log_file,omitempty"`
PIDFile string `yaml:"pid_file,omitempty"`
Channel string `yaml:"channel,omitempty"` // stable | beta
Asset string `yaml:"asset,omitempty"`
KeepOld *int `yaml:"keep_old,omitempty"`
TrustedProxies string `yaml:"trusted_proxies,omitempty"`
AllowedOrigins string `yaml:"allowed_origins,omitempty"`
CookieSecure *bool `yaml:"cookie_secure,omitempty"`
SkipDeps *bool `yaml:"skip_deps,omitempty"`
BinDir string `yaml:"bin_dir,omitempty"`
NRE string `yaml:"nre,omitempty"`
FFmpeg string `yaml:"ffmpeg,omitempty"`
MP4Decrypt string `yaml:"mp4decrypt,omitempty"`
Token string `yaml:"token,omitempty"` // legacy; prefer dashboard keys
SessionTTL string `yaml:"session_ttl,omitempty"`
AuditRetain string `yaml:"audit_retain,omitempty"`
OnDemandWait string `yaml:"ondemand_wait,omitempty"`
CaptureWait string `yaml:"ondemand_capture_wait,omitempty"`
SchedulePreroll string `yaml:"schedule_preroll,omitempty"`
TSFanoutBuffer *int `yaml:"ts_fanout_buffer,omitempty"`
}
// ServeOptions is the fully resolved runtime config for serve run/start/update.
type ServeOptions struct {
InstallRoot string
ConfigPath string // path used or written; may be empty if --config pointed elsewhere missing
Bind string
Data string // absolute after resolve
LogLevel string
LogFile string // absolute
PIDFile string // absolute
Channel string
Asset string
KeepOld int
TrustedProxies string
AllowedOrigins string
CookieSecure bool
SkipDeps bool
BinDir string
NRE string
FFmpeg string
MP4Decrypt string
Token string
AdminUser string
AdminPass string
SessionTTL time.Duration
AuditRetain time.Duration
OnDemandWait time.Duration
CaptureWait time.Duration
SchedulePreroll time.Duration
TSFanoutBuffer int
// FlagSet / write tracking
WroteConfig bool
}
func defaultFileConfig() FileConfig {
keep := defaultKeepOld
cookie := false
skip := false
return FileConfig{
Bind: defaultBind,
Data: filepath.Join(".cache", "streamd"),
LogLevel: defaultLogLevel,
LogFile: defaultLogFile,
PIDFile: defaultPIDFile,
Channel: defaultChannel,
KeepOld: &keep,
CookieSecure: &cookie,
SkipDeps: &skip,
}
}
func installRoot() string {
root, err := bootstrap.InstallRoot()
if err != nil || root == "" {
wd, _ := os.Getwd()
return wd
}
return root
}
// findConfigPath returns the config path to use and whether the file exists.
func findConfigPath(explicit string) (path string, exists bool) {
if strings.TrimSpace(explicit) != "" {
abs, err := filepath.Abs(explicit)
if err != nil {
abs = explicit
}
_, err = os.Stat(abs)
return abs, err == nil
}
if env := strings.TrimSpace(os.Getenv("STREAMD_CONFIG")); env != "" {
abs, err := filepath.Abs(env)
if err != nil {
abs = env
}
_, err = os.Stat(abs)
return abs, err == nil
}
cwd := filepath.Join(".", configFileName)
if st, err := os.Stat(cwd); err == nil && !st.IsDir() {
abs, _ := filepath.Abs(cwd)
return abs, true
}
root := installRoot()
p := filepath.Join(root, configFileName)
if st, err := os.Stat(p); err == nil && !st.IsDir() {
return p, true
}
// Default write target: next to the binary.
return p, false
}
func loadFileConfig(path string) (FileConfig, error) {
b, err := os.ReadFile(path)
if err != nil {
return FileConfig{}, err
}
var fc FileConfig
if err := yaml.Unmarshal(b, &fc); err != nil {
return FileConfig{}, fmt.Errorf("%s: %w", path, err)
}
return fc, nil
}
func writeFileConfig(path string, fc FileConfig) error {
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
b, err := yaml.Marshal(&fc)
if err != nil {
return err
}
header := []byte("# streamd.yaml — server settings (auto-written on first serve).\n" +
"# Edit bind/data/channel here; streamd serve start|update reuse this file.\n")
return os.WriteFile(path, append(header, b...), 0o644)
}
func absUnderRoot(root, p string) string {
p = strings.TrimSpace(p)
if p == "" {
return ""
}
if filepath.IsAbs(p) {
return p
}
return filepath.Join(root, p)
}
func parseDuration(s string, fallback time.Duration) time.Duration {
s = strings.TrimSpace(s)
if s == "" {
return fallback
}
d, err := time.ParseDuration(s)
if err != nil {
return fallback
}
return d
}
func mergeFileIntoOptions(opt *ServeOptions, fc FileConfig) {
if fc.Bind != "" {
opt.Bind = fc.Bind
}
if fc.Data != "" {
opt.Data = absUnderRoot(opt.InstallRoot, fc.Data)
}
if fc.LogLevel != "" {
opt.LogLevel = fc.LogLevel
}
if fc.LogFile != "" {
opt.LogFile = absUnderRoot(opt.InstallRoot, fc.LogFile)
}
if fc.PIDFile != "" {
opt.PIDFile = absUnderRoot(opt.InstallRoot, fc.PIDFile)
}
if fc.Channel != "" {
opt.Channel = fc.Channel
}
if fc.Asset != "" {
opt.Asset = fc.Asset
}
if fc.KeepOld != nil {
opt.KeepOld = *fc.KeepOld
}
if fc.TrustedProxies != "" {
opt.TrustedProxies = fc.TrustedProxies
}
if fc.AllowedOrigins != "" {
opt.AllowedOrigins = fc.AllowedOrigins
}
if fc.CookieSecure != nil {
opt.CookieSecure = *fc.CookieSecure
}
if fc.SkipDeps != nil {
opt.SkipDeps = *fc.SkipDeps
}
if fc.BinDir != "" {
opt.BinDir = absUnderRoot(opt.InstallRoot, fc.BinDir)
}
if fc.NRE != "" {
opt.NRE = fc.NRE
}
if fc.FFmpeg != "" {
opt.FFmpeg = fc.FFmpeg
}
if fc.MP4Decrypt != "" {
opt.MP4Decrypt = fc.MP4Decrypt
}
if fc.Token != "" {
opt.Token = fc.Token
}
opt.SessionTTL = parseDuration(fc.SessionTTL, opt.SessionTTL)
opt.AuditRetain = parseDuration(fc.AuditRetain, opt.AuditRetain)
opt.OnDemandWait = parseDuration(fc.OnDemandWait, opt.OnDemandWait)
opt.CaptureWait = parseDuration(fc.CaptureWait, opt.CaptureWait)
opt.SchedulePreroll = parseDuration(fc.SchedulePreroll, opt.SchedulePreroll)
if fc.TSFanoutBuffer != nil {
opt.TSFanoutBuffer = *fc.TSFanoutBuffer
}
}
func relOrAbs(root, p string) string {
if p == "" {
return ""
}
if rel, err := filepath.Rel(root, p); err == nil && !strings.HasPrefix(rel, "..") {
return filepath.ToSlash(rel)
}
return p
}
func optionsToFileConfig(opt ServeOptions) FileConfig {
keep := opt.KeepOld
cookie := opt.CookieSecure
skip := opt.SkipDeps
data := relOrAbs(opt.InstallRoot, opt.Data)
if data == "" {
data = filepath.ToSlash(filepath.Join(".cache", "streamd"))
}
logFile := relOrAbs(opt.InstallRoot, opt.LogFile)
if logFile == "" {
logFile = defaultLogFile
}
pidFile := relOrAbs(opt.InstallRoot, opt.PIDFile)
if pidFile == "" {
pidFile = defaultPIDFile
}
fc := FileConfig{
Bind: opt.Bind,
Data: data,
LogLevel: opt.LogLevel,
LogFile: logFile,
PIDFile: pidFile,
Channel: opt.Channel,
Asset: opt.Asset,
KeepOld: &keep,
TrustedProxies: opt.TrustedProxies,
AllowedOrigins: opt.AllowedOrigins,
CookieSecure: &cookie,
SkipDeps: &skip,
}
if opt.BinDir != "" {
fc.BinDir = relOrAbs(opt.InstallRoot, opt.BinDir)
}
return fc
}
// ensureConfigLoaded applies discovered yaml (if any) and optionally writes a
// default file when missing. explicitConfig is the --config value (may be empty).
func ensureConfigLoaded(opt *ServeOptions, explicitConfig string, writeIfMissing bool) error {
opt.InstallRoot = installRoot()
path, exists := findConfigPath(explicitConfig)
opt.ConfigPath = path
if exists {
fc, err := loadFileConfig(path)
if err != nil {
return err
}
mergeFileIntoOptions(opt, fc)
return nil
}
if !writeIfMissing {
return nil
}
// Don't write when user passed --config to a missing path outside install root
// unless it's the default install-root path.
if strings.TrimSpace(explicitConfig) != "" {
abs, _ := filepath.Abs(explicitConfig)
def := filepath.Join(opt.InstallRoot, configFileName)
if abs != def {
return fmt.Errorf("config file not found: %s", abs)
}
path = abs
opt.ConfigPath = path
}
fc := optionsToFileConfig(*opt)
if err := writeFileConfig(path, fc); err != nil {
return err
}
opt.WroteConfig = true
return nil
}

View file

@ -0,0 +1,101 @@
package servecmd
import (
"os"
"path/filepath"
"testing"
)
func TestWriteAndLoadFileConfig(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "streamd.yaml")
keep := 5
cookie := true
fc := FileConfig{
Bind: "0.0.0.0:8083",
Data: ".cache/streamd",
LogLevel: "debug",
LogFile: "streamd.log",
PIDFile: "streamd.pid",
Channel: "beta",
KeepOld: &keep,
CookieSecure: &cookie,
}
if err := writeFileConfig(path, fc); err != nil {
t.Fatal(err)
}
got, err := loadFileConfig(path)
if err != nil {
t.Fatal(err)
}
if got.Bind != "0.0.0.0:8083" || got.Channel != "beta" || got.LogLevel != "debug" {
t.Fatalf("got %+v", got)
}
if got.KeepOld == nil || *got.KeepOld != 5 {
t.Fatalf("keep_old=%v", got.KeepOld)
}
}
func TestMergeRelativePaths(t *testing.T) {
root := t.TempDir()
opt := ServeOptions{InstallRoot: root, Bind: defaultBind, KeepOld: 10}
fc := FileConfig{Data: ".cache/streamd", LogFile: "streamd.log", PIDFile: "streamd.pid", Bind: "0.0.0.0:9"}
mergeFileIntoOptions(&opt, fc)
if opt.Bind != "0.0.0.0:9" {
t.Fatalf("bind=%s", opt.Bind)
}
wantData := filepath.Join(root, ".cache", "streamd")
if opt.Data != wantData {
t.Fatalf("data=%s want %s", opt.Data, wantData)
}
}
func TestEnsureConfigWritesOnce(t *testing.T) {
root := t.TempDir()
// Point InstallRoot via a fake by writing to root/streamd.yaml through ensure
opt := ServeOptions{
InstallRoot: root,
Bind: "0.0.0.0:8083",
Data: filepath.Join(root, ".cache", "streamd"),
LogLevel: "info",
LogFile: filepath.Join(root, "streamd.log"),
PIDFile: filepath.Join(root, "streamd.pid"),
Channel: "stable",
KeepOld: 10,
}
path := filepath.Join(root, configFileName)
if err := writeFileConfig(path, optionsToFileConfig(opt)); err != nil {
t.Fatal(err)
}
// Second ensure should not set WroteConfig when loading existing.
opt2 := baseServeOptions()
opt2.InstallRoot = root
// findConfigPath uses real installRoot(); test loadFileConfig merge instead.
fc, err := loadFileConfig(path)
if err != nil {
t.Fatal(err)
}
mergeFileIntoOptions(&opt2, fc)
if opt2.Bind != "0.0.0.0:8083" {
t.Fatalf("bind=%s", opt2.Bind)
}
// Existing file must not be clobbered by a second write of defaults.
before, _ := os.ReadFile(path)
_ = writeFileConfig(path, optionsToFileConfig(opt2))
after, _ := os.ReadFile(path)
if len(before) == 0 || len(after) == 0 {
t.Fatal("empty config")
}
}
func TestUpdateURL(t *testing.T) {
u := updateURL(releaseBaseURL, "stable", "streamd-linux-amd64")
want := releaseBaseURL + "/stable/streamd-linux-amd64"
if u != want {
t.Fatalf("%s != %s", u, want)
}
u = updateURL(releaseBaseURL, "v0.2.0", "streamd-linux-arm64")
if u != releaseBaseURL+"/v0.2.0/streamd-linux-arm64" {
t.Fatal(u)
}
}

View file

@ -0,0 +1,200 @@
package servecmd
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)
func readPID(pidFile string) (int, error) {
b, err := os.ReadFile(pidFile)
if err != nil {
return 0, err
}
s := strings.TrimSpace(string(b))
if s == "" {
return 0, fmt.Errorf("empty pid file")
}
return strconv.Atoi(s)
}
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 processAlive(pid int) bool {
if pid <= 0 {
return false
}
return signalAlive(pid)
}
func runningPID(opt ServeOptions) (pid int, ok bool) {
pid, err := readPID(opt.PIDFile)
if err != nil {
return 0, false
}
if !processAlive(pid) {
removePID(opt.PIDFile)
return pid, false
}
return pid, true
}
func statusCmd(opt ServeOptions) error {
fmt.Printf("config: %s\n", opt.ConfigPath)
fmt.Printf("bind: %s\n", opt.Bind)
fmt.Printf("data: %s\n", opt.Data)
fmt.Printf("log: %s\n", opt.LogFile)
fmt.Printf("pid: %s\n", opt.PIDFile)
if pid, ok := runningPID(opt); ok {
fmt.Printf("streamd: running pid=%d\n", pid)
return nil
}
fmt.Println("streamd: stopped")
return nil
}
func stopCmd(opt ServeOptions) error {
pid, err := readPID(opt.PIDFile)
if err != nil {
if os.IsNotExist(err) {
fmt.Println("streamd is not running")
return nil
}
return err
}
if !processAlive(pid) {
removePID(opt.PIDFile)
fmt.Println("streamd 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(5 * time.Second)
for time.Now().Before(deadline) {
if !processAlive(pid) {
removePID(opt.PIDFile)
fmt.Printf("streamd stopped (was pid %d)\n", pid)
return nil
}
time.Sleep(200 * time.Millisecond)
}
_ = signalKill(pid)
time.Sleep(200 * time.Millisecond)
removePID(opt.PIDFile)
fmt.Printf("streamd killed (pid %d)\n", pid)
return nil
}
func startCmd(opt ServeOptions) error {
if pid, ok := runningPID(opt); ok {
fmt.Printf("streamd 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
}
args := buildDaemonArgs(opt)
cmd := exec.Command(exe, args...)
if err := os.MkdirAll(filepath.Dir(opt.LogFile), 0o755); err != nil {
return err
}
logF, err := os.OpenFile(opt.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 daemon: %w", err)
}
pid := cmd.Process.Pid
// Release so the child is not tied to this process on Unix.
_ = cmd.Process.Release()
_ = logF.Close()
if err := writePID(opt.PIDFile, pid); err != nil {
return err
}
time.Sleep(400 * time.Millisecond)
if !processAlive(pid) {
removePID(opt.PIDFile)
return fmt.Errorf("daemon exited immediately — see %s", opt.LogFile)
}
fmt.Printf("streamd started pid=%d bind=%s data=%s\n", pid, opt.Bind, opt.Data)
fmt.Printf("logs: %s\n", opt.LogFile)
if opt.WroteConfig {
fmt.Printf("wrote config %s\n", opt.ConfigPath)
}
return nil
}
func restartCmd(opt ServeOptions) error {
_ = stopCmd(opt)
return startCmd(opt)
}
func buildDaemonArgs(opt ServeOptions) []string {
args := []string{"serve", "run", "--daemon-child"}
if opt.ConfigPath != "" {
args = append(args, "--config", opt.ConfigPath)
}
args = append(args,
"--bind", opt.Bind,
"--data", opt.Data,
"--log-level", opt.LogLevel,
)
if opt.BinDir != "" {
args = append(args, "--bin-dir", opt.BinDir)
}
if opt.NRE != "" {
args = append(args, "--nre", opt.NRE)
}
if opt.FFmpeg != "" {
args = append(args, "--ffmpeg", opt.FFmpeg)
}
if opt.MP4Decrypt != "" {
args = append(args, "--mp4decrypt", opt.MP4Decrypt)
}
if opt.SkipDeps {
args = append(args, "--skip-deps")
}
if opt.TrustedProxies != "" {
args = append(args, "--trusted-proxies", opt.TrustedProxies)
}
if opt.AllowedOrigins != "" {
args = append(args, "--allowed-origins", opt.AllowedOrigins)
}
if opt.CookieSecure {
args = append(args, "--cookie-secure")
}
if opt.Token != "" {
args = append(args, "--token", opt.Token)
}
if opt.AdminUser != "" {
args = append(args, "--admin-user", opt.AdminUser)
}
if opt.AdminPass != "" {
args = append(args, "--admin-pass", opt.AdminPass)
}
return args
}

View file

@ -0,0 +1,37 @@
//go:build unix
package servecmd
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)
}

View file

@ -0,0 +1,46 @@
//go:build windows
package servecmd
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)
}

View file

@ -0,0 +1,71 @@
package servecmd
import (
"os"
"path/filepath"
"testing"
)
func TestResolveDataDirFlagWins(t *testing.T) {
t.Setenv("STREAMD_DATA", "")
dir, src := resolveDataDir("/explicit/data")
if dir != "/explicit/data" || src != "flag" {
t.Fatalf("got dir=%q src=%q", dir, src)
}
}
func TestResolveDataDirEnv(t *testing.T) {
t.Setenv("STREAMD_DATA", "/from/env")
dir, src := resolveDataDir("")
if dir != "/from/env" || src != "env" {
t.Fatalf("got dir=%q src=%q", dir, src)
}
}
func TestResolveDataDirExistingCwd(t *testing.T) {
t.Setenv("STREAMD_DATA", "")
tmp := t.TempDir()
old, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(old)
if err := os.Chdir(tmp); err != nil {
t.Fatal(err)
}
want := filepath.Join(".", ".cache", "streamd")
if err := os.MkdirAll(want, 0o755); err != nil {
t.Fatal(err)
}
dir, src := resolveDataDir("")
if src != "cwd" {
t.Fatalf("src=%q want cwd", src)
}
absGot, _ := filepath.Abs(dir)
absWant, _ := filepath.Abs(want)
if absGot != absWant {
t.Fatalf("dir=%q want %q", absGot, absWant)
}
}
func TestResolveDataDirDefaultWhenMissing(t *testing.T) {
t.Setenv("STREAMD_DATA", "")
tmp := t.TempDir()
old, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
defer os.Chdir(old)
if err := os.Chdir(tmp); err != nil {
t.Fatal(err)
}
dir, src := resolveDataDir("")
if src != "default" && src != "install" {
// install may win if the test binary's InstallRoot already has a cache;
// either way we must not invent a random path.
t.Fatalf("src=%q want default or install", src)
}
if filepath.Base(dir) != "streamd" {
t.Fatalf("dir=%q", dir)
}
}

View file

@ -19,6 +19,7 @@ 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/hlsgate"
"streamd/apps/streamd/internal/httpx"
"streamd/apps/streamd/internal/modstore"
@ -27,6 +28,7 @@ import (
"streamd/apps/streamd/internal/tsfanout"
"streamd/apps/streamd/internal/ui"
"streamd/apps/streamd/internal/ws"
"streamd/bootstrap"
"streamd/modhost"
)
@ -56,11 +58,30 @@ func Usage() {
fmt.Fprintf(os.Stderr, `streamd — Go control plane for DRM restreams
Usage:
streamd serve [flags]
streamd serve start|stop|restart|status|update|run [flags]
streamd serve [flags] # foreground (same as run)
Lifecycle (uses streamd.yaml next to the binary; written on first run):
streamd serve start # background WebUI
streamd serve stop
streamd serve restart
streamd serve status
streamd serve update # download stable, archive old → ./old/, restart
streamd serve update --beta
streamd serve update --tag v0.2.0
streamd serve update --no-restart
streamd serve run # foreground (debug)
Config:
--config PATH streamd.yaml (default: $STREAMD_CONFIG, ./streamd.yaml,
or <install>/streamd.yaml next to the binary)
serve flags:
--bind listen address (default 127.0.0.1:8083)
--data data dir for sqlite + www + work (default .cache/streamd)
--data data dir for sqlite + www + work
(omit to reuse an existing .cache/streamd under cwd or
next to the binary; else create ./.cache/streamd.
STREAMD_DATA env is an alternate default.)
--nre path to N_m3u8DL-RE (else NRE_PATH, bin/, PATH, auto-download)
--ffmpeg path to ffmpeg (else FFMPEG_PATH, bin/, PATH, auto-download)
--mp4decrypt path to mp4decrypt (else MP4DECRYPT_PATH, bin/, PATH, auto-download)
@ -90,61 +111,293 @@ set --trusted-proxies to that proxy. Use --bind 0.0.0.0:8083 only deliberately.
`)
}
// resolveDataDir picks the streamd data directory.
//
// Order when --data is empty:
// 1. $STREAMD_DATA if set
// 2. ./.cache/streamd if that directory already exists
// 3. <install-root>/.cache/streamd if that directory already exists
// (install root = directory of the binary, or its parent when the binary
// lives in bin/)
// 4. otherwise ./.cache/streamd (created on startup)
//
// Returns the path and a short source label for logs (flag|env|cwd|install|default).
func resolveDataDir(flagValue string) (dir, source string) {
if strings.TrimSpace(flagValue) != "" {
return flagValue, "flag"
}
if env := strings.TrimSpace(os.Getenv("STREAMD_DATA")); env != "" {
return env, "env"
}
cwdCandidate := filepath.Join(".", ".cache", "streamd")
if dirExists(cwdCandidate) {
return cwdCandidate, "cwd"
}
if root, err := bootstrap.InstallRoot(); err == nil {
installCandidate := filepath.Join(root, ".cache", "streamd")
if dirExists(installCandidate) {
return installCandidate, "install"
}
}
return cwdCandidate, "default"
}
func dirExists(path string) bool {
st, err := os.Stat(path)
return err == nil && st.IsDir()
}
func serveCmd(args []string) {
fs := flag.NewFlagSet("serve", flag.ExitOnError)
// Loopback by default. This used to be 0.0.0.0, which published the API —
// and before redaction, the Widevine keys — to the whole network.
bind := fs.String("bind", "127.0.0.1:8083", "listen address")
data := fs.String("data", "", "data directory (sqlite, www, work, logs)")
token := fs.String("token", "", "legacy admin API token (default: STREAMD_TOKEN env)")
verb := ""
rest := args
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
switch args[0] {
case "start", "stop", "restart", "status", "update", "run", "help", "-h", "--help":
verb, rest = args[0], args[1:]
}
}
if verb == "help" || verb == "-h" || verb == "--help" {
Usage()
return
}
opt, uf, err := parseServeArgs(verb, rest)
if err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(2)
}
switch verb {
case "start":
if err := startCmd(opt); err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
case "stop":
if err := stopCmd(opt); err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
case "restart":
if err := restartCmd(opt); err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
case "status":
if err := statusCmd(opt); err != nil {
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
case "update":
if err := updateCmd(opt, uf); err != nil {
if err == errUpdateDeferred {
fmt.Println(err.Error())
os.Exit(0)
}
fmt.Fprintln(os.Stderr, "[!]", err)
os.Exit(1)
}
default: // "", "run" — foreground
runServe(opt)
}
}
func baseServeOptions() ServeOptions {
root := installRoot()
return ServeOptions{
InstallRoot: root,
Bind: defaultBind,
LogLevel: defaultLogLevel,
LogFile: absUnderRoot(root, defaultLogFile),
PIDFile: absUnderRoot(root, defaultPIDFile),
Channel: defaultChannel,
KeepOld: defaultKeepOld,
SessionTTL: auth.DefaultSessionTTL,
AuditRetain: 90 * 24 * time.Hour,
OnDemandWait: hlsgate.DefaultWait,
CaptureWait: hlsgate.DefaultCaptureWait,
SchedulePreroll: scheduler.DefaultPreroll,
TSFanoutBuffer: tsfanout.DefaultBufferBytes,
}
}
func parseServeArgs(verb string, args []string) (ServeOptions, updateFlags, error) {
opt := baseServeOptions()
uf := updateFlags{Keep: -1}
fs := flag.NewFlagSet("serve", flag.ContinueOnError)
fs.SetOutput(os.Stderr)
configPath := fs.String("config", "", "path to streamd.yaml")
daemonChild := fs.Bool("daemon-child", false, "internal: spawned by serve start")
bind := fs.String("bind", "", "listen address")
data := fs.String("data", "", "data directory")
token := fs.String("token", "", "legacy admin API token")
nre := fs.String("nre", "", "N_m3u8DL-RE binary")
ffmpeg := fs.String("ffmpeg", "", "ffmpeg binary")
mp4decrypt := fs.String("mp4decrypt", "", "mp4decrypt binary")
binDir := fs.String("bin-dir", "", "directory for media tool binaries (default <repo>/bin)")
binDir := fs.String("bin-dir", "", "directory for media tool binaries")
skipDeps := fs.Bool("skip-deps", false, "skip auto-download of missing media tools")
logLevel := fs.String("log-level", "info", "debug | info | warn | error")
logLevel := fs.String("log-level", "", "debug | info | warn | error")
adminUser := fs.String("admin-user", "", "create this admin account on first run")
adminPass := fs.String("admin-pass", "", "password for --admin-user (or STREAMD_ADMIN_PASS)")
sessionTTL := fs.Duration("session-ttl", auth.DefaultSessionTTL, "login lifetime without activity")
adminPass := fs.String("admin-pass", "", "password for --admin-user")
sessionTTL := fs.Duration("session-ttl", 0, "login lifetime without activity")
trustedProxies := fs.String("trusted-proxies", "", "CIDRs allowed to set X-Forwarded-For")
allowedOrigins := fs.String("allowed-origins", "", "extra CORS origins, comma separated")
allowedOrigins := fs.String("allowed-origins", "", "extra CORS origins")
cookieSecure := fs.Bool("cookie-secure", false, "always mark cookies Secure")
auditRetain := fs.Duration("audit-retain", 90*24*time.Hour, "how long to keep audit rows")
tsBuffer := fs.Int("ts-fanout-buffer", tsfanout.DefaultBufferBytes,
"bytes of live MPEG-TS buffered per stream for /live/<name>.ts")
ondemandWait := fs.Duration("ondemand-wait", hlsgate.DefaultWait,
"how long to hold a viewer request while an on-demand stream starts")
ondemandCaptureWait := fs.Duration("ondemand-capture-wait", hlsgate.DefaultCaptureWait,
"as --ondemand-wait, but when credentials must be captured first")
preroll := fs.Duration("schedule-preroll", scheduler.DefaultPreroll,
"how far ahead of a scheduled start to refresh credentials")
_ = fs.Parse(args)
auditRetain := fs.Duration("audit-retain", 0, "how long to keep audit rows")
tsBuffer := fs.Int("ts-fanout-buffer", 0, "live MPEG-TS buffer bytes")
ondemandWait := fs.Duration("ondemand-wait", 0, "on-demand start wait")
ondemandCaptureWait := fs.Duration("ondemand-capture-wait", 0, "on-demand capture wait")
preroll := fs.Duration("schedule-preroll", 0, "schedule credential preroll")
lg := newLogger(*logLevel)
// update-only flags (harmless on other verbs)
beta := fs.Bool("beta", false, "update: use beta channel")
stable := fs.Bool("stable", false, "update: use stable channel")
tag := fs.String("tag", "", "update: pin release tag")
noRestart := fs.Bool("no-restart", false, "update: do not start after replace")
keep := fs.Int("keep", -1, "update: max binaries to keep in old/")
if err := fs.Parse(args); err != nil {
return opt, uf, err
}
visited := map[string]bool{}
fs.Visit(func(f *flag.Flag) { visited[f.Name] = true })
writeMissing := !*daemonChild && (verb == "" || verb == "run" || verb == "start" || verb == "update" || verb == "restart")
if err := ensureConfigLoaded(&opt, *configPath, writeMissing); err != nil {
return opt, uf, err
}
if *bind != "" {
opt.Bind = *bind
}
if *data != "" {
opt.Data = *data
if !filepath.IsAbs(opt.Data) {
opt.Data = absUnderRoot(opt.InstallRoot, opt.Data)
}
} else if opt.Data == "" {
dir, _ := resolveDataDir("")
opt.Data = dir
if !filepath.IsAbs(opt.Data) {
abs, err := filepath.Abs(opt.Data)
if err == nil {
opt.Data = abs
}
}
}
if *logLevel != "" {
opt.LogLevel = *logLevel
}
if *token != "" {
opt.Token = *token
}
if *nre != "" {
opt.NRE = *nre
}
if *ffmpeg != "" {
opt.FFmpeg = *ffmpeg
}
if *mp4decrypt != "" {
opt.MP4Decrypt = *mp4decrypt
}
if *binDir != "" {
opt.BinDir = *binDir
}
if visited["skip-deps"] {
opt.SkipDeps = *skipDeps
}
if *adminUser != "" {
opt.AdminUser = *adminUser
}
if *adminPass != "" {
opt.AdminPass = *adminPass
}
if visited["session-ttl"] {
opt.SessionTTL = *sessionTTL
}
if *trustedProxies != "" {
opt.TrustedProxies = *trustedProxies
}
if *allowedOrigins != "" {
opt.AllowedOrigins = *allowedOrigins
}
if visited["cookie-secure"] {
opt.CookieSecure = *cookieSecure
}
if visited["audit-retain"] {
opt.AuditRetain = *auditRetain
}
if visited["ts-fanout-buffer"] {
opt.TSFanoutBuffer = *tsBuffer
}
if visited["ondemand-wait"] {
opt.OnDemandWait = *ondemandWait
}
if visited["ondemand-capture-wait"] {
opt.CaptureWait = *ondemandCaptureWait
}
if visited["schedule-preroll"] {
opt.SchedulePreroll = *preroll
}
// Persist effective settings when we created the file, or when start/restart
// was given explicit bind/data so the next restart remembers them.
persist := opt.WroteConfig
if (verb == "start" || verb == "restart") && (visited["bind"] || visited["data"] || visited["log-level"]) {
persist = true
}
if persist && opt.ConfigPath != "" {
if err := writeFileConfig(opt.ConfigPath, optionsToFileConfig(opt)); err == nil && !opt.WroteConfig {
opt.WroteConfig = true
}
}
if *beta {
uf.Channel = "beta"
}
if *stable {
uf.Channel = "stable"
}
uf.Tag = strings.TrimSpace(*tag)
uf.NoRestart = *noRestart
uf.Keep = *keep
_ = daemonChild
return opt, uf, nil
}
func runServe(opt ServeOptions) {
lg := newLogger(opt.LogLevel)
slog.SetDefault(lg)
// deps still wants a *log.Logger; bridge it onto the same handler so one
// stream of output stays coherent.
depsLog := slog.NewLogLogger(lg.Handler(), slog.LevelInfo)
dataDir := *data
dataDir := opt.Data
if dataDir == "" {
dataDir = filepath.Join(".", ".cache", "streamd")
var src string
dataDir, src = resolveDataDir("")
if src != "flag" {
lg.Info("using data directory", "data", dataDir, "source", src)
}
}
tok := *token
if opt.WroteConfig {
lg.Info("wrote config", "path", opt.ConfigPath)
}
tok := opt.Token
if tok == "" {
tok = os.Getenv("STREAMD_TOKEN")
}
trust := httpx.Trust{}
if nets, err := httpx.ParseCIDRs(*trustedProxies); err != nil {
if nets, err := httpx.ParseCIDRs(opt.TrustedProxies); err != nil {
lg.Error("invalid --trusted-proxies", "err", err)
os.Exit(2)
} else {
trust.Proxies = nets
}
origins := splitList(*allowedOrigins)
origins := splitList(opt.AllowedOrigins)
for _, sub := range []string{"www", "work", "logs", "modules"} {
for _, sub := range []string{"www", "work", "logs", "modules", "egress"} {
if err := os.MkdirAll(filepath.Join(dataDir, sub), 0o755); err != nil {
lg.Error("create data dir", "err", err)
os.Exit(1)
@ -163,30 +416,36 @@ func serveCmd(args []string) {
lg.Error("init auth tables", "err", err)
os.Exit(1)
}
mw := auth.NewMiddleware(authStore, trust, *cookieSecure)
mw.SessionTTL = *sessionTTL
mw := auth.NewMiddleware(authStore, trust, opt.CookieSecure)
mw.SessionTTL = opt.SessionTTL
authH := auth.NewHandler(authStore, mw, lg)
bootstrapAdmin(lg, authStore, authH, *adminUser, *adminPass)
bootstrapAdmin(lg, authStore, authH, opt.AdminUser, opt.AdminPass)
depStatus, _ := deps.Ensure(deps.Options{
BinDir: *binDir,
SkipDownload: *skipDeps,
BinDir: opt.BinDir,
SkipDownload: opt.SkipDeps,
Log: depsLog,
}, *nre, *ffmpeg, *mp4decrypt)
}, opt.NRE, opt.FFmpeg, opt.MP4Decrypt)
fanout := tsfanout.NewSet(*tsBuffer)
fanout := tsfanout.NewSet(opt.TSFanoutBuffer)
hub := ws.NewHub(store, lg, origins)
eg := egress.New(dataDir, store, lg, "")
eg.WarnMissingDeps()
eg.StartEnabled()
defer eg.StopAll()
sup := supervisor.NewMedia(supervisor.Options{
Store: store,
DataDir: dataDir,
NRE: depStatus.NRE,
FFmpeg: depStatus.FFmpeg,
MP4Decrypt: depStatus.MP4Decrypt,
Log: lg,
Fanout: fanout,
Notifier: hub,
Store: store,
DataDir: dataDir,
NRE: depStatus.NRE,
FFmpeg: depStatus.FFmpeg,
MP4Decrypt: depStatus.MP4Decrypt,
Log: lg,
Fanout: fanout,
Notifier: hub,
ProxyResolver: eg,
})
defer sup.Close()
@ -198,18 +457,15 @@ func serveCmd(args []string) {
Capture: hub,
Trust: trust,
Log: lg,
Wait: *ondemandWait,
CaptureWait: *ondemandCaptureWait,
Wait: opt.OnDemandWait,
CaptureWait: opt.CaptureWait,
})
// The supervisor records viewer counts in its metrics series, and the
// gate is what knows them.
sup.ViewersFn = gate.ViewersFor
sched := scheduler.New(store, sup, hub, lg, *preroll)
sched := scheduler.New(store, sup, hub, lg, opt.SchedulePreroll)
modulesRoot := filepath.Join(dataDir, "modules")
modStore := modstore.New(modulesRoot)
// Panel-owned modules are the source of truth for /api/apps and describe.
if err := modhost.SetModulesDir(modulesRoot); err != nil {
lg.Error("set modules dir", "err", err)
os.Exit(1)
@ -232,6 +488,7 @@ func serveCmd(args []string) {
Notifier: hub,
Viewers: gate,
Scheduler: sched,
Egress: eg,
Log: lg,
}
@ -239,15 +496,10 @@ func serveCmd(args []string) {
apiH.Mount(mux)
authH.Mount(mux)
hub.Mount(mux)
// The media paths are served by the gate, not a bare FileServer: it wakes
// on-demand streams, counts viewers, sets cache headers per file kind and
// refuses directory listings.
gate.Mount(mux)
mux.Handle("/", ui.Handler())
mux.Handle("/static/", http.StripPrefix("/static/", ui.Static()))
// Order matters: the access log wraps everything so it sees final statuses,
// then CORS and security headers, then principal resolution, then the mux.
var handler http.Handler = mux
handler = mw.Attach(handler)
handler = httpx.SecurityHeaders(trust, handler)
@ -255,15 +507,13 @@ func serveCmd(args []string) {
handler = httpx.AccessLog(lg, trust, handler)
srv := &http.Server{
Addr: *bind,
Addr: opt.Bind,
Handler: handler,
ReadHeaderTimeout: 10 * time.Second,
// No WriteTimeout: HLS responses, SSE log tails and websockets are all
// long-lived and a write deadline would cut them off.
IdleTimeout: 120 * time.Second,
IdleTimeout: 120 * time.Second,
}
lg.Info("streamd listening", "addr", *bind, "data", dataDir)
lg.Info("streamd listening", "addr", opt.Bind, "data", dataDir)
lg.Info("media tools", "nre", depStatus.NRE, "ffmpeg", depStatus.FFmpeg, "mp4decrypt", depStatus.MP4Decrypt)
if len(trust.Proxies) == 0 {
lg.Info("no --trusted-proxies set: forwarded headers are ignored and client IPs come from the peer address")
@ -271,19 +521,18 @@ func serveCmd(args []string) {
if tok != "" {
lg.Warn("--token / STREAMD_TOKEN is in use as an admin API key; create per-agent keys in the dashboard and drop it")
}
if host, _, err := net.SplitHostPort(*bind); err == nil {
if host, _, err := net.SplitHostPort(opt.Bind); err == nil {
switch strings.ToLower(host) {
case "127.0.0.1", "localhost", "::1":
// Loopback is the safe default.
default:
lg.Warn("listening on a non-loopback address — the dashboard and API are reachable on the network; put a TLS reverse proxy in front, or bind 127.0.0.1",
"bind", *bind)
"bind", opt.Bind)
}
}
stopBG := make(chan struct{})
go hub.RunExpireLoop(stopBG)
go authStore.RunMaintenance(stopBG, *auditRetain)
go authStore.RunMaintenance(stopBG, opt.AuditRetain)
go store.RunHistoryMaintenance(stopBG)
go gate.RunIdleLoop(stopBG)
go sched.Run(stopBG)

View file

@ -0,0 +1,243 @@
package servecmd
import (
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
)
type updateFlags struct {
Channel string // stable|beta or empty → config
Tag string
NoRestart bool
Keep int // -1 = use config
}
// 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 updateCmd(opt ServeOptions, uf updateFlags) error {
channel := opt.Channel
if channel == "" {
channel = defaultChannel
}
if uf.Channel != "" {
channel = uf.Channel
}
ref := channel
if uf.Tag != "" {
ref = uf.Tag
}
asset := opt.Asset
if asset == "" {
asset = defaultAssetName()
}
if asset == "" {
return fmt.Errorf("unsupported platform %s/%s — set asset: in streamd.yaml", runtime.GOOS, runtime.GOARCH)
}
keep := opt.KeepOld
if uf.Keep >= 0 {
keep = uf.Keep
}
url := updateURL(releaseBaseURL, ref, asset)
fmt.Printf("streamd update: downloading %s\n", url)
tmp, err := downloadToTemp(opt.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
}
// Prefer replacing the install-root binary named streamd[.exe] when that is
// where operators keep the release asset.
target := exe
wantName := "streamd"
if runtime.GOOS == "windows" {
wantName = "streamd.exe"
}
installBin := filepath.Join(opt.InstallRoot, wantName)
if st, err := os.Stat(installBin); err == nil && !st.IsDir() {
target = installBin
}
if _, ok := runningPID(opt); ok {
fmt.Println("streamd update: stopping running serve…")
if err := stopCmd(opt); err != nil {
return err
}
}
oldDir := filepath.Join(opt.InstallRoot, "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 uf.NoRestart {
_ = os.Setenv("STREAMD_UPDATE_RESTART", "0")
} else {
_ = os.Setenv("STREAMD_UPDATE_RESTART", "1")
}
if err := replaceBinary(target, tmp, archive); err != nil {
if err == errUpdateDeferred {
return err
}
return err
}
fmt.Printf("streamd update: archived previous → %s\n", archive)
fmt.Printf("streamd update: installed %s (%s)\n", target, ref)
pruneOldBinaries(oldDir, keep)
if uf.NoRestart {
fmt.Println("streamd update: done (--no-restart). Start with: streamd serve start")
return nil
}
fmt.Println("streamd update: starting…")
return startCmd(opt)
}
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)
}
// Reject HTML error pages.
head, _ := os.ReadFile(path)
if len(head) > 32 {
h := strings.ToLower(string(head[:32]))
if strings.Contains(h, "<!doctype") || strings.Contains(h, "<html") {
_ = os.Remove(path)
return "", fmt.Errorf("download looks like HTML, not a binary: %s", url)
}
}
_ = os.Chmod(path, 0o755)
return path, nil
}
func smokeTestBinary(path string) error {
cmd := exec.Command(path, "help")
out, err := cmd.CombinedOutput()
if err != nil {
// help may exit 0; some builds exit 2 — accept if output mentions serve.
if !strings.Contains(string(out), "serve") && !strings.Contains(string(out), "streamd") {
return fmt.Errorf("new binary failed smoke test: %w\n%s", err, out)
}
}
return nil
}
func pruneOldBinaries(oldDir string, keep int) {
if keep <= 0 {
return
}
ents, err := os.ReadDir(oldDir)
if err != nil {
return
}
var names []string
for _, e := range ents {
if e.IsDir() {
continue
}
n := e.Name()
if strings.HasPrefix(n, "streamd.") {
names = append(names, n)
}
}
sort.Strings(names)
if len(names) <= keep {
return
}
for _, n := range names[:len(names)-keep] {
_ = os.Remove(filepath.Join(oldDir, n))
fmt.Printf("streamd update: pruned %s\n", filepath.Join(oldDir, n))
}
}

View file

@ -0,0 +1,22 @@
//go:build unix
package servecmd
import (
"fmt"
"os"
)
// replaceBinary moves the live binary to archive, then moves next into place.
func replaceBinary(target, next, archive string) error {
if err := os.Rename(target, archive); err != nil {
return fmt.Errorf("archive current binary: %w", err)
}
if err := os.Rename(next, target); err != nil {
// Best-effort rollback.
_ = os.Rename(archive, target)
return fmt.Errorf("install new binary: %w", err)
}
_ = os.Chmod(target, 0o755)
return nil
}

View file

@ -0,0 +1,123 @@
//go:build windows
package servecmd
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"time"
)
// replaceBinary on Windows cannot overwrite the running updater exe. Strategy:
// 1. Move target → archive when target is not our own running image.
// 2. If target is us, write next beside as streamd.exe.new and spawn a helper
// cmd that waits for this PID to exit, then swaps and optionally starts.
func replaceBinary(target, next, archive string) error {
self, _ := os.Executable()
if resolved, err := filepath.EvalSymlinks(self); err == nil {
self = resolved
}
same, _ := sameFile(self, target)
if !same {
if err := os.Rename(target, archive); err != nil {
// Fall through to copy-based replace if rename fails (file locked).
if err2 := copyFile(target, archive); err2 != nil {
return fmt.Errorf("archive current binary: %v / %w", err, err2)
}
_ = os.Remove(target)
}
if err := os.Rename(next, target); err != nil {
if err2 := copyFile(next, target); err2 != nil {
_ = os.Rename(archive, target)
return fmt.Errorf("install new binary: %v / %w", err, err2)
}
_ = os.Remove(next)
}
return nil
}
// Self-replace: leave next as target+".new", archive current after exit via helper.
newPath := target + ".new"
_ = os.Remove(newPath)
if err := os.Rename(next, newPath); err != nil {
if err2 := copyFile(next, newPath); err2 != nil {
return fmt.Errorf("stage new binary: %v / %w", err, err2)
}
_ = os.Remove(next)
}
helper := filepath.Join(filepath.Dir(target), "streamd-update-finish.cmd")
pid := os.Getpid()
startLine := ""
if os.Getenv("STREAMD_UPDATE_RESTART") != "0" {
startLine = fmt.Sprintf("\"%s\" serve start\r\n", escapeCmd(target))
}
script := fmt.Sprintf(""+
"@echo off\r\n"+
":wait\r\n"+
"timeout /t 1 /nobreak >nul\r\n"+
"tasklist /FI \"PID eq %d\" 2>nul | find \"%d\" >nul\r\n"+
"if not errorlevel 1 goto wait\r\n"+
"move /Y \"%s\" \"%s\"\r\n"+
"move /Y \"%s\" \"%s\"\r\n"+
"%s"+
"del \"%%~f0\"\r\n",
pid, pid,
escapeCmd(target), escapeCmd(archive),
escapeCmd(newPath), escapeCmd(target),
startLine,
)
if err := os.WriteFile(helper, []byte(script), 0o644); err != nil {
return err
}
cmd := exec.Command("cmd.exe", "/C", helper)
cmd.Stdout = nil
cmd.Stderr = nil
detachProcess(cmd)
if err := cmd.Start(); err != nil {
return fmt.Errorf("start update helper: %w", err)
}
_ = cmd.Process.Release()
fmt.Println("streamd update: scheduled file swap after this process exits")
fmt.Println("streamd update: run `streamd serve start` once the swap finishes (1–2s)")
// Give the helper a moment to spawn, then return so the caller can exit.
time.Sleep(300 * time.Millisecond)
return errUpdateDeferred
}
func escapeCmd(p string) string {
return p // paths used in quotes; avoid extra escaping of %
}
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
}

View file

@ -0,0 +1,19 @@
# Example streamd.yaml — place next to the streamd binary (e.g. ~/null-drm/).
# On first `streamd serve` / `streamd serve start`, a file like this is written
# automatically with the effective bind/data from that run.
bind: 0.0.0.0:8083
data: .cache/streamd
log_level: info
log_file: streamd.log
pid_file: streamd.pid
# Rolling release channel for `streamd serve update`
channel: stable
# asset: streamd-linux-amd64 # optional override
keep_old: 10
# trusted_proxies: "127.0.0.1/32"
# cookie_secure: true
# skip_deps: false
# bin_dir: bin

View file

@ -40,7 +40,7 @@ first command it creates scaffold folders next to itself (`apps/pkg`, `bin/`,
```text
./
streamd.exe # drm.exe also shipped as a one-release compat copy
streamd.exe
README.md
apps/pkg/go.mod
apps/proxy/device/tproxy_iptables.sh

View file

@ -1,7 +1,8 @@
# Streamd v0.2.0
First release under the **Streamd** product name. Host binary is `streamd`
(`drm` is still shipped as an identical compatibility copy for this release).
First release under the **Streamd** product name. Host binary is `streamd`.
This tag also shipped identical `drm-*` compatibility copies; later releases
drop those and publish `streamd-*` only.
## Highlights

43
docs/releases/v0.2.1.md Normal file
View file

@ -0,0 +1,43 @@
# Streamd v0.2.1
Host release after v0.2.0. Ships **`streamd-*` only** (no `drm-*` compat
copies). Retargets the rolling **`stable`** channel.
## Highlights
### Serve lifecycle
- `streamd serve start|stop|restart|status|update` (plus foreground `serve` / `serve run`)
- First run writes `streamd.yaml` next to the binary (bind / data / log / pid / channel)
- `serve update` downloads stable/beta/`--tag`, archives under `./old/`, and restarts
- Thin wrappers: `scripts/streamd-bg.sh`, `scripts/streamd-update.sh`
### WireGuard / SOCKS egress
- Per-stream egress profiles (Settings → Egress)
- WireGuard profiles use Linux netns + local SOCKS forwarder; `kind=socks` is URL-only
- Resolve order: explicit stream `proxy` → egress SOCKS → direct
### Module panel fixes
- Describe injects `STREAMD_MODULES_DIR` so uploaded modules read panel YAML
- `/api/apps` falls back to panel `module.yaml` channels when describe returns none
- YAML editor fills via textarea `value` property
## Assets
| Asset | Platform |
|---|---|
| `streamd-windows-amd64.exe` | Windows x86_64 |
| `streamd-windows-arm64.exe` | Windows ARM64 |
| `streamd-linux-amd64` | Linux x86_64 |
| `streamd-linux-arm64` | Linux ARM64 |
| `streamd-darwin-amd64` | macOS Intel |
| `streamd-darwin-arm64` | macOS Apple Silicon |
| `proxy-android-arm64` | On-device MITM |
| `SHA256SUMS.txt` | Checksums |
Built with `CGO_ENABLED=0`. Provider zips remain on separate **`modules-v*`** releases.
```bash
curl -fL -o streamd \
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-amd64"
chmod +x streamd
```

50
docs/releases/v0.2.2.md Normal file
View file

@ -0,0 +1,50 @@
# Streamd v0.2.2
Host release after v0.2.1. Retargets the rolling **`stable`** channel.
## Highlights
### Dashboard: live uptimes + run history
- **Live uptimes** card below Needs attention — per-stream health and ticking uptime
- **Recent runs** — durable `stream_sessions` rows (start → stop/crash) with duration and end reason
- `GET /api/overview` includes `recent_sessions` (newest closed runs first)
### Support / donations
- Dashboard **Support the project** card with copyable ETH / LTC / BTC addresses (same as README)
### WireGuard egress DNS
- On Linux Up, write `/etc/netns/streamd-<name>/resolv.conf` with public resolvers so SOCKS hostname lookups work when the host uses systemd-resolved (`127.0.0.53`)
- Startup WARN if `ip`, `wg`, or `microsocks`/`gost` are missing from `PATH`
- Docs updated in `docs/streamd-server-setup.md` §7 and `docs/streamd.md`
### Agent / Widevine / modules (included from prior work)
- Agent lifecycle: `streamd agent start|stop|restart|status|update`
- `job_backoff` defaults off (immediate retries)
- Widevine auto-venv + embedded `apps/wvkey`; phonecap 90s×3 license retries
- Module panel YAML enrich / empty-package guards; DRM credential posts require keys
## Known limits
- **BBC Live from datacenter IPs** can still get CDN **403** after SOCKS/DNS is healthy. Needs UK residential egress — out of scope for this release.
## Assets
| Asset | Platform |
|---|---|
| `streamd-windows-amd64.exe` | Windows x86_64 |
| `streamd-windows-arm64.exe` | Windows ARM64 |
| `streamd-linux-amd64` | Linux x86_64 |
| `streamd-linux-arm64` | Linux ARM64 |
| `streamd-darwin-amd64` | macOS Intel |
| `streamd-darwin-arm64` | macOS Apple Silicon |
| `proxy-android-arm64` | On-device MITM |
| `SHA256SUMS.txt` | Checksums |
Built with `CGO_ENABLED=0`. Provider zips remain on separate **`modules-v*`** releases.
```bash
curl -fL -o streamd \
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-amd64"
chmod +x streamd
./streamd serve update # or: stop → replace → start
```

46
docs/releases/v0.2.3.md Normal file
View file

@ -0,0 +1,46 @@
# Streamd v0.2.3
Host patch after v0.2.2. Retargets the rolling **`stable`** channel.
## Highlights
### NRE Spectre crash under daemon (Linux)
- **Symptom:** `downloader exited before any media arrived` within ~1s; log showed
`System.ArgumentException` / `Spectre.Console.LiveRenderable.RemoveRange`
- **Cause:** N_m3u8DL-RE forces Spectre live UI when stdout is redirected. Under
`streamd serve` (no TTY) console width is 0 and the progress thread crashes
- **Fix:** On Linux, wrap NRE with util-linux `script -q -a -f` so it gets a real
PTY; drop subtitle tracks (`-ds for=all`); pin `COLUMNS`/`LINES`/`TERM`; kill
the process group on stop
- Log path in errors clarified as `data/logs/<name>-nre.log`
### Verified
- vm-2085: `rte` + `rte-jr` stayed **ok** after deploy (40s+ uptime)
## Known limits
- **BBC Live from datacenter IPs** can still get CDN **403**. Needs UK residential egress.
- Requires `script` (util-linux) on the host PATH for the PTY path; falls back to
plain file redirect if missing (may still hit Spectre on some hosts)
## Assets
| Asset | Platform |
|---|---|
| `streamd-windows-amd64.exe` | Windows x86_64 |
| `streamd-windows-arm64.exe` | Windows ARM64 |
| `streamd-linux-amd64` | Linux x86_64 |
| `streamd-linux-arm64` | Linux ARM64 |
| `streamd-darwin-amd64` | macOS Intel |
| `streamd-darwin-arm64` | macOS Apple Silicon |
| `proxy-android-arm64` | On-device MITM |
| `SHA256SUMS.txt` | Checksums |
Built with `CGO_ENABLED=0`. Provider zips remain on separate **`modules-v*`** releases.
```bash
curl -fL -o streamd \
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-amd64"
chmod +x streamd
./streamd serve update # or: stop → replace → start
```

View file

@ -81,50 +81,75 @@ chmod +x streamd
You should see a list of commands including `serve` and `agent`.
Optional layout after first run:
```text
~/null-drm/
streamd # the binary
.cache/streamd/ # created by serve (database, HLS, logs)
.cache/agent/ # created by agent
agent.yaml # you create this for the agent
data/ # optional .wvd for key fetch
modules/ # optional provider zips (agent / capture)
bin/ # auto-downloaded ffmpeg, N_m3u8DL-RE, mp4decrypt
```
---
## 2. Start streamd (first time)
Pick a password. Create the first admin account on the command line so you are
not stuck hunting a setup token in the logs:
### Recommended — background with `streamd.yaml`
```bash
cd ~/null-drm
./streamd serve \
./streamd serve start \
--bind 0.0.0.0:8083 \
--data .cache/streamd \
--admin-user admin \
--admin-pass 'CHANGE_ME_NOW'
```
What those flags mean:
What happens:
| Flag | Meaning |
1. streamd writes **`streamd.yaml`** next to the binary (bind, data, log/pid paths,
update channel) so the next start remembers your settings
2. Starts the WebUI **in the background** (pid file + log file)
3. On first boot, downloads ffmpeg / N_m3u8DL-RE / mp4decrypt into `bin/`
Check it:
```bash
./streamd serve status
./streamd serve stop
./streamd serve start # uses streamd.yaml — no flags needed next time
```
Edit `streamd.yaml` any time (then `./streamd serve restart`):
```yaml
bind: 0.0.0.0:8083
data: .cache/streamd
log_level: info
log_file: streamd.log
pid_file: streamd.pid
channel: stable # used by: streamd serve update
keep_old: 10
```
Example file in the repo: [`docs/examples/streamd.yaml`](examples/streamd.yaml).
### Foreground (debug)
```bash
./streamd serve --bind 0.0.0.0:8083 --admin-user admin --admin-pass 'CHANGE_ME_NOW'
# or: ./streamd serve run --bind …
```
Also writes `streamd.yaml` on first run if missing. Ctrl+C stops it.
`--data` is optional. If you omit it, streamd:
1. uses `$STREAMD_DATA` when that env var is set, else
2. reuses `./.cache/streamd` when that folder already exists, else
3. reuses `<install>/.cache/streamd` next to the binary when that folder exists, else
4. creates `./.cache/streamd`
| Flag / yaml key | Meaning |
|---|---|
| `--bind 0.0.0.0:8083` | Listen on all interfaces so you can open it from your PC |
| `--data .cache/streamd` | Where the DB, HLS files, and logs live |
| `--admin-user` / `--admin-pass` | First admin account (only used when the DB is empty) |
| `--bind` / `bind` | Listen address (`0.0.0.0:8083` on a server) |
| `--data` / `data` | DB / HLS / logs dir |
| `--admin-user` / `--admin-pass` | First admin account (only when the DB is empty) |
You will see a startup warning about binding non-loopback. That is expected on a
server. Prefer putting a reverse proxy (Caddy / nginx) with TLS in front later.
On first start, streamd downloads ffmpeg, N_m3u8DL-RE, and mp4decrypt into
`bin/`. Wait until the log says it is listening.
Open in your browser (use the server IP):
```text
@ -141,6 +166,22 @@ sudo ufw allow 8083/tcp
sudo ufw reload
```
Layout after first start:
```text
~/null-drm/
streamd # the binary
streamd.yaml # auto-written on first serve / serve start
streamd.log
streamd.pid
old/ # previous binaries after `serve update`
.cache/streamd/ # database, HLS, logs, modules
.cache/agent/ # created by agent
agent.yaml # you create this for the agent
data/ # optional .wvd for key fetch
bin/ # auto-downloaded ffmpeg, N_m3u8DL-RE, mp4decrypt
```
---
## 3. Create an API key for the agent (and for curl)
@ -294,9 +335,41 @@ In the dashboard, **Refresh keys** on a stream asks connected agents to capture
## 6. Keep it running when you close the terminal
If you close SSH while `streamd serve` is in the foreground, it dies. Pick one method.
If you close SSH while `streamd serve` / `serve run` is in the **foreground**, it
dies. Use **`streamd serve start`** (Method A) so it survives logout.
### Method A — `screen` (simplest)
### Method A — `streamd serve start` (recommended)
Built into the binary. Reads `streamd.yaml`, writes pid + log, safe to close SSH:
```bash
cd ~/null-drm
./streamd serve start
./streamd serve status
./streamd serve stop
./streamd serve restart
tail -f streamd.log # Ctrl+C leaves streamd running
```
Upgrade later with `./streamd serve update` (see [§10](#10-stopping--upgrading)).
Optional thin wrappers (same commands) if you already curl’d them:
```bash
curl -fL -o streamd-bg.sh \
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/raw/branch/main/scripts/streamd-bg.sh"
chmod +x streamd-bg.sh
./streamd-bg.sh start # → streamd serve start
```
Agent (still separate; needs `agent.yaml`):
```bash
nohup ./streamd agent run --config agent.yaml >agent.log 2>&1 &
# or: ./streamd-bg.sh start-agent
```
### Method B — `screen`
```bash
sudo apt-get update && sudo apt-get install -y screen # Debian/Ubuntu
@ -308,7 +381,7 @@ Start streamd inside a named screen:
```bash
cd ~/null-drm
screen -S streamd
./streamd serve --bind 0.0.0.0:8083 --data .cache/streamd
./streamd serve --bind 0.0.0.0:8083
```
Detach without killing it: press **`Ctrl+A`**, then **`D`**.
@ -330,36 +403,17 @@ cd ~/null-drm
List sessions: `screen -ls`
### Method B — `tmux` (same idea)
### Method C — `tmux` (same idea)
```bash
sudo apt-get install -y tmux
cd ~/null-drm
tmux new -s streamd
./streamd serve --bind 0.0.0.0:8083 --data .cache/streamd
./streamd serve --bind 0.0.0.0:8083
# Detach: Ctrl+B then D
# Reattach: tmux attach -t streamd
```
### Method C — `nohup` (one-liner, no session to reattach)
```bash
cd ~/null-drm
nohup ./streamd serve --bind 0.0.0.0:8083 --data .cache/streamd > streamd.log 2>&1 &
echo $! > streamd.pid
# optional agent
nohup ./streamd agent run --config agent.yaml > agent.log 2>&1 &
echo $! > agent.pid
```
Stop later:
```bash
kill "$(cat streamd.pid)"
kill "$(cat agent.pid)"
```
### Method D — systemd (survives reboot — recommended for a real server)
Create a user unit (no root binary needed). Paths assume install in `/home/ubuntu/null-drm`
@ -376,7 +430,8 @@ Wants=network-online.target
Type=simple
User=ubuntu
WorkingDirectory=/home/ubuntu/null-drm
ExecStart=/home/ubuntu/null-drm/streamd serve --bind 0.0.0.0:8083 --data /home/ubuntu/null-drm/.cache/streamd
# Foreground under systemd (do not use `serve start` here — systemd is the supervisor).
ExecStart=/home/ubuntu/null-drm/streamd serve run --config /home/ubuntu/null-drm/streamd.yaml
Restart=on-failure
RestartSec=5
# Optional first-boot admin (ignored once users exist):
@ -424,7 +479,84 @@ Same pattern with `streamd-agent` for the agent unit.
---
## 7. Quick “am I done?” checklist
## 7. Per-stream WireGuard egress (optional)
Use this when **some** streams must exit via another country (e.g. London) while
SSH and the dashboard stay on the server’s normal IP.
### Host packages
```bash
# Debian/Ubuntu
sudo apt-get install -y wireguard wireguard-tools iproute2 microsocks
# Fedora: sudo dnf install wireguard-tools iproute microsocks
```
`streamd serve` must be allowed to create network namespaces (`CAP_NET_ADMIN` /
`CAP_SYS_ADMIN`, or run as root). A full-tunnel client conf (`AllowedIPs = 0.0.0.0/0`)
is fine — traffic is isolated inside `streamd-<name>` netns.
On **Up**, streamd also writes `/etc/netns/streamd-<name>/resolv.conf` with public
resolvers (`1.1.1.1`, `1.0.0.1`, `8.8.8.8`). Without that, SOCKS hostname lookups
fail when the host uses systemd-resolved’s `127.0.0.53` stub (unreachable inside
the netns). Writing under `/etc/netns/` needs the same privileges as `ip netns`.
Teardown removes that directory with the namespace.
If `ip`, `wg`, or `microsocks`/`gost` are missing from `PATH`, `streamd serve`
logs a WARN at startup so WireGuard profiles fail clearly instead of silently.
### Dashboard
1. **Settings → Egress tunnels → Add profile**
2. Name `london`, kind **WireGuard**, paste your client `.conf` (e.g. `vps-london.conf`)
3. **Up**, then **Test IP** (should show the London egress address)
4. On each stream (**Config**): **Egress tunnel** = `london` (leave others on Direct)
Raw **Origin proxy URL** still overrides the dropdown when set.
### curl equivalent
```bash
export STREAMD_API_KEY='YOUR_API_KEY'
curl -sS -X POST "http://127.0.0.1:8083/api/egress" \
-H "Authorization: Bearer $STREAMD_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"london","kind":"wireguard","enabled":true}'
# Upload conf (JSON). Do not commit real keys to git.
python3 - <<'PY'
import json, pathlib, urllib.request, os
conf = pathlib.Path("vps-london.conf").read_text()
req = urllib.request.Request(
"http://127.0.0.1:8083/api/egress/london",
data=json.dumps({"conf": conf}).encode(),
headers={
"Authorization": "Bearer " + os.environ["STREAMD_API_KEY"],
"Content-Type": "application/json",
},
method="PUT",
)
print(urllib.request.urlopen(req).read().decode())
PY
curl -sS -X POST "http://127.0.0.1:8083/api/egress/london/up" \
-H "Authorization: Bearer $STREAMD_API_KEY"
curl -sS -X POST "http://127.0.0.1:8083/api/egress/london/test" \
-H "Authorization: Bearer $STREAMD_API_KEY"
curl -sS -X PATCH "http://127.0.0.1:8083/api/streams/1" \
-H "Authorization: Bearer $STREAMD_API_KEY" \
-H "Content-Type: application/json" \
-d '{"egress":"london"}'
```
Conf on disk: `.cache/streamd/egress/london/wg.conf` (mode `0600`). Add `dublin`
the same way as a second profile.
---
## 8. Quick “am I done?” checklist
```bash
cd ~/null-drm
@ -447,7 +579,7 @@ Play the m3u8 in VLC / ffplay / any HLS player using the server IP URL.
---
## 8. Common problems
## 9. Common problems
| Symptom | Fix |
|---|---|
@ -455,30 +587,89 @@ Play the m3u8 in VLC / ffplay / any HLS player using the server IP URL.
| Browser cannot open the page | Use `--bind 0.0.0.0:8083`, open firewall port 8083, check `curl` from the server itself |
| Stream will not start | MPD must be `http://` or `https://`. Encrypted streams need `KID:KEY` lines |
| Agent does nothing | Operator API key wrong; stream **Enabled**; phone in `adb devices` as `device`; app installed |
| Dies when SSH closes | Use screen/tmux/nohup/systemd from §6 |
| Dies when SSH closes | Use `./streamd serve start` (or screen/tmux/systemd) from §6 |
| `text file busy` / cannot replace `streamd` | Use `./streamd serve update` (stops first) or `serve stop` then replace — see §10 |
| Deps download fails | Server needs outbound HTTPS; or place ffmpeg / N_m3u8DL-RE / mp4decrypt on `PATH` / in `bin/` and use `--skip-deps` only if you already have them |
| Want loopback only + proxy | Bind `127.0.0.1:8083` and put Caddy/nginx in front with TLS |
---
## 9. Stopping / upgrading
## 10. Stopping / upgrading
Stop a foreground or screen session with `Ctrl+C` inside that session.
Upgrade:
Built into the binary — one command stops, downloads, archives the old binary
under `./old/`, and restarts:
```bash
cd ~/null-drm
# stop streamd first (systemctl stop streamd / kill / Ctrl+C)
curl -fL -o streamd.new \
"https://git.nulldrm.com/nulldrm/Null-DRM-Official/releases/download/stable/streamd-linux-amd64"
chmod +x streamd.new
mv streamd streamd.bak
mv streamd.new streamd
# start again
./streamd serve update # stable channel (from streamd.yaml `channel:`)
./streamd serve update --beta
./streamd serve update --tag v0.2.0
./streamd serve update --no-restart # replace only; then: ./streamd serve start
./streamd serve status
```
Back up `.cache/streamd/streamd.db` before big upgrades.
What `serve update` does:
1. Stops a background serve if it is running (pid file)
2. Downloads `streamd-linux-amd64` or `streamd-linux-arm64` (or the yaml `asset:`)
from the `stable` / `beta` / `--tag` release
3. Smoke-tests the new file (`streamd help`)
4. Moves `./streamd` → `./old/streamd.YYYYMMDDTHHMMSSZ`
5. Installs the new binary and starts it again (unless `--no-restart`)
`streamd.yaml` / `.cache/streamd` are left alone.
Layout after a few upgrades:
```text
~/null-drm/
streamd
streamd.yaml
old/
streamd.20261010T153012Z
streamd.20261012T091500Z
.cache/streamd/
```
Roll back:
```bash
cd ~/null-drm
./streamd serve stop
mv streamd "old/streamd.failed.$(date -u +%Y%m%dT%H%M%SZ)"
cp old/streamd.20261010T153012Z streamd
chmod +x streamd
./streamd serve start
```
### screen / tmux
```bash
screen -r streamd # or: tmux attach -t streamd
# Ctrl+C — detach is not enough; the process must exit
./streamd serve update --no-restart
# then start again in screen, or:
./streamd serve start
```
### systemd
```bash
sudo systemctl stop streamd
./streamd serve update --no-restart
sudo systemctl start streamd
sudo systemctl status streamd
```
### Optional shell wrappers
```bash
./streamd-update.sh --beta # → streamd serve update --beta
./streamd-bg.sh stop # → streamd serve stop
```
Back up `.cache/streamd/streamd.db` before big upgrades if you want an extra
safety copy. The updater never touches the data directory.
---

View file

@ -16,7 +16,7 @@ streams, screen/systemd so it survives closing the terminal).
| Flag | Default | Purpose |
|---|---|---|
| `--bind` | `127.0.0.1:8083` | listen address (loopback). Non-loopback logs a warning |
| `--data` | `.cache/streamd` | SQLite, work dirs, HLS output, logs |
| `--data` | auto (see below) | SQLite, work dirs, HLS output, logs. If omitted: `$STREAMD_DATA`, else existing `./.cache/streamd`, else existing `<install>/.cache/streamd`, else create `./.cache/streamd` |
| `--token` | `$STREAMD_TOKEN` | legacy admin API key (prefer dashboard API keys) |
| `--admin-user` / `--admin-pass` | — | create first admin on empty install |
| `--nre` | `$NRE_PATH`, `bin/`, `PATH`, auto-download | N_m3u8DL-RE |
@ -36,13 +36,23 @@ anonymous for liveness; stream list and mutations need a principal. Legacy
`--token` / `STREAMD_TOKEN` still works as an admin key and prints a migration
warning.
### Keys and proxy
### Keys, proxy, and egress
- **MPD** is required to start. **Keys are optional** (clear streams such as BBC).
- Per-stream **`proxy`** (`socks5://127.0.0.1:1080` or `http://…`) is passed to
N_m3u8DL-RE as `--custom-proxy` so origin fetches can egress via a UK SOCKS
sidecar while the host itself stays elsewhere. The local MPD rewrite fetch
uses the same proxy. Outbound HLS you serve is unaffected.
N_m3u8DL-RE as `--custom-proxy`. The local MPD rewrite fetch uses the same
proxy. Outbound HLS you serve is unaffected.
- Per-stream **`egress`** names a profile from **Settings → Egress** (WireGuard
netns + local SOCKS on Linux, or a plain SOCKS URL profile). Resolve order:
explicit `proxy` → named egress SOCKS → direct. Full-tunnel WG stays inside
`streamd-<name>` netns so SSH/UI keep the host route. On Linux Up, streamd
writes `/etc/netns/streamd-<name>/resolv.conf` (public DNS) so SOCKS hostname
lookups work when the host uses `127.0.0.53`. See
[streamd-server-setup.md](streamd-server-setup.md) §7.
- The dashboard **Live uptimes** and **Recent runs** cards use
`stream_runtime.uptime_s` plus durable `stream_sessions` rows (opened when
NRE starts, closed on stop / NRE exit). `GET /api/overview` includes
`recent_sessions`.
- **Variants** (FHD / HD / SD): FHD is the source copy at `/hls/<name>/index.m3u8`.
Enabling HD/SD starts live ffmpeg ladders at `/hls/<name>-hd/` and
`/hls/<name>-sd/`. The dashboard Copy button copies the absolute m3u8 URL
@ -53,6 +63,7 @@ warning.
| Route | Purpose |
|---|---|
| `GET /api/health` | liveness + uptime + `deps` paths |
| `GET /api/overview` | dashboard totals, upcoming, recent events + sessions |
| `GET /api/apps` | modules under the panel store (`--data/modules`), channels, rewriters |
| `GET /api/modules` | list panel modules with yaml/package hashes + arches |
| `GET /api/modules/:name` | metadata; `?include=yaml` returns YAML (operator+) |
@ -61,9 +72,16 @@ warning.
| `PUT /api/modules/:name` | save `module.yaml` (operator; JSON `{"yaml":…}` or raw YAML) |
| `POST /api/modules/upload` | multipart zip upload (`file` + optional `name`) |
| `DELETE /api/modules/:name` | remove a module from the panel store |
| `GET /api/egress` | list egress profiles (viewer+) |
| `POST /api/egress` | create profile (admin) |
| `GET /api/egress/:name` | profile status |
| `PUT /api/egress/:name` | update enabled/kind/socks_url/conf (admin) |
| `PUT /api/egress/:name/conf` | upload WireGuard conf (admin) |
| `POST /api/egress/:name/up\|down\|test` | bring tunnel up/down / probe egress IP |
| `DELETE /api/egress/:name` | remove profile (admin) |
| `GET /api/streams` | all streams with runtime state |
| `POST /api/streams` | create |
| `PATCH /api/streams/:id` | update |
| `PATCH /api/streams/:id` | update (incl. `egress`) |
| `DELETE /api/streams/:id` | remove |
| `POST /api/streams/:id/start\|stop\|restart` | desired state |
| `POST /api/streams/:id/capture` | ask connected agents to refresh credentials now |

View file

@ -1,5 +1,4 @@
# Cross-compile host streamd (+ drm compat copy) and on-device proxy-android-arm64
# into dist/release/.
# Cross-compile host streamd and on-device proxy-android-arm64 into dist/release/.
# Usage:
# .\scripts\build-release.ps1
# .\scripts\build-release.ps1 -Version v1.2.3
@ -43,8 +42,7 @@ Get-ChildItem $Out -ErrorAction SilentlyContinue | Where-Object { $_.Name -match
function Build-Host([string]$Goos, [string]$Goarch, [string]$Ext = "") {
$name = "streamd-$Goos-$Goarch$Ext"
$compat = "drm-$Goos-$Goarch$Ext"
Write-Host " - $name (+ $compat)"
Write-Host " - $name"
$env:GOOS = $Goos
$env:GOARCH = $Goarch
$env:CGO_ENABLED = "0"
@ -52,7 +50,6 @@ function Build-Host([string]$Goos, [string]$Goarch, [string]$Ext = "") {
try {
& $GoExe -C apps/cli build -trimpath -ldflags="-s -w" -o (Join-Path $Out $name) .
if ($LASTEXITCODE -ne 0) { throw "go build failed for $name" }
Copy-Item (Join-Path $Out $name) (Join-Path $Out $compat) -Force
} finally {
Pop-Location
Remove-Item Env:GOOS -ErrorAction SilentlyContinue
@ -95,9 +92,8 @@ Copy-Item (Join-Path $Out "proxy-android-arm64") (Join-Path $Root "bin\proxy-and
Copy-Item (Join-Path $Out "proxy-android-arm64") (Join-Path $Root "apps\proxy\proxy-android-arm64") -Force
try {
Copy-Item (Join-Path $Out "streamd-windows-amd64.exe") (Join-Path $Root "bin\streamd.exe") -Force
Copy-Item (Join-Path $Out "streamd-windows-amd64.exe") (Join-Path $Root "bin\drm.exe") -Force
} catch {
Write-Host "WARN: could not refresh bin\streamd.exe / bin\drm.exe (file in use): $($_.Exception.Message)"
Write-Host "WARN: could not refresh bin\streamd.exe (file in use): $($_.Exception.Message)"
}
# Restore tiny embed stub so the 9MB MITM binary is not left in the source tree.
$stub = Join-Path $Root "apps\pkg\bootstrap\embedded\bin\proxy-android-arm64"
@ -107,7 +103,7 @@ Write-Host "==> checksums"
$sumsPath = Join-Path $Out "SHA256SUMS.txt"
$tmpSums = Join-Path $Out "SHA256SUMS.txt.tmp"
$lines = Get-ChildItem $Out -File |
Where-Object { $_.Name -match '^(streamd-|drm-|proxy-android)' } |
Where-Object { $_.Name -match '^(streamd-|proxy-android)' } |
Get-FileHash -Algorithm SHA256 |
ForEach-Object { "{0} {1}" -f $_.Hash.ToLower(), (Split-Path $_.Path -Leaf) }
[System.IO.File]::WriteAllLines($tmpSums, @($lines))
@ -123,10 +119,8 @@ New-Item -ItemType Directory -Force -Path @(
(Join-Path $win "outputs")
) | Out-Null
Copy-Item (Join-Path $Out "streamd-windows-amd64.exe") (Join-Path $win "bin\streamd.exe") -Force
Copy-Item (Join-Path $Out "streamd-windows-amd64.exe") (Join-Path $win "bin\drm.exe") -Force
Copy-Item (Join-Path $Out "proxy-android-arm64") (Join-Path $win "bin\proxy-android-arm64") -Force
Copy-Item (Join-Path $Out "streamd-windows-amd64.exe") (Join-Path $win "streamd.exe") -Force
Copy-Item (Join-Path $Out "streamd-windows-amd64.exe") (Join-Path $win "drm.exe") -Force
Copy-Item (Join-Path $Out "proxy-android-arm64") (Join-Path $win "proxy-android-arm64") -Force
Copy-Item (Join-Path $Root "apps\proxy\device\tproxy_iptables.sh") (Join-Path $win "apps\proxy\device\") -Force
Copy-Item (Join-Path $Root "apps\pkg\go.mod") (Join-Path $win "apps\pkg\") -Force
@ -136,7 +130,6 @@ Streamd — Windows portable
Scaffold (streamd.exe also creates this on first run if you only download the exe):
bin\streamd.exe
bin\drm.exe (identical compatibility copy)
bin\proxy-android-arm64
apps\proxy\device\tproxy_iptables.sh

View file

@ -1,6 +1,5 @@
#!/usr/bin/env bash
# Cross-compile host `streamd` (+ `drm` compat copy) and on-device
# `proxy-android-arm64` into dist/release/.
# Cross-compile host `streamd` and on-device `proxy-android-arm64` into dist/release/.
# Usage:
# ./scripts/build-release.sh # VERSION=git describe
# ./scripts/build-release.sh v1.2.3
@ -48,14 +47,12 @@ echo "==> building host streamd ($VERSION) into $OUT"
build_host() {
local goos="$1" goarch="$2" ext="${3:-}"
local name="streamd-${goos}-${goarch}${ext}"
local compat="drm-${goos}-${goarch}${ext}"
echo " - $name (+ $compat)"
echo " - $name"
(
cd "$ROOT"
GOOS="$goos" GOARCH="$goarch" CGO_ENABLED=0 \
"$GO" -C apps/cli build -trimpath -ldflags="-s -w" -o "$OUT/$name" .
)
cp -f "$OUT/$name" "$OUT/$compat"
}
build_host windows amd64 .exe
@ -80,27 +77,15 @@ case "$(uname -s)" in
Linux)
arch="$(uname -m)"
case "$arch" in
x86_64)
cp -f "$OUT/streamd-linux-amd64" "$ROOT/bin/streamd"
cp -f "$OUT/streamd-linux-amd64" "$ROOT/bin/drm"
;;
aarch64)
cp -f "$OUT/streamd-linux-arm64" "$ROOT/bin/streamd"
cp -f "$OUT/streamd-linux-arm64" "$ROOT/bin/drm"
;;
x86_64) cp -f "$OUT/streamd-linux-amd64" "$ROOT/bin/streamd" ;;
aarch64) cp -f "$OUT/streamd-linux-arm64" "$ROOT/bin/streamd" ;;
esac
;;
Darwin)
arch="$(uname -m)"
case "$arch" in
x86_64)
cp -f "$OUT/streamd-darwin-amd64" "$ROOT/bin/streamd"
cp -f "$OUT/streamd-darwin-amd64" "$ROOT/bin/drm"
;;
arm64)
cp -f "$OUT/streamd-darwin-arm64" "$ROOT/bin/streamd"
cp -f "$OUT/streamd-darwin-arm64" "$ROOT/bin/drm"
;;
x86_64) cp -f "$OUT/streamd-darwin-amd64" "$ROOT/bin/streamd" ;;
arm64) cp -f "$OUT/streamd-darwin-arm64" "$ROOT/bin/streamd" ;;
esac
;;
esac
@ -108,9 +93,9 @@ esac
(
cd "$OUT"
if command -v sha256sum >/dev/null 2>&1; then
sha256sum streamd-* drm-* proxy-android-arm64 > SHA256SUMS.txt
sha256sum streamd-* proxy-android-arm64 > SHA256SUMS.txt
else
shasum -a 256 streamd-* drm-* proxy-android-arm64 > SHA256SUMS.txt
shasum -a 256 streamd-* proxy-android-arm64 > SHA256SUMS.txt
fi
)

View file

@ -85,7 +85,7 @@ function New-TelegramBody {
}
return (
"<b>$Title</b>" + $nl +
"Host CLI ($( & $code 'streamd' ); $( & $code 'drm' ) compat copy) + on-device MITM ($( & $code 'proxy-android-arm64' ))." +
"Host CLI ($( & $code 'streamd' )) + on-device MITM ($( & $code 'proxy-android-arm64' ))." +
$channelLine + $nl + $nl +
"<a href=`"$ReleaseUrl`">Download $Tag</a>"
)

View file

@ -84,7 +84,7 @@ Upload in the streamd Modules page, or unpack into <code>modules/&lt;name&gt;/</
<a href=\"${URL}\">Download ${TAG}</a>"
else
BODY="<b>${TITLE}</b>
Host CLI (<code>streamd</code>; <code>drm</code> compat copy) + on-device MITM (<code>proxy-android-arm64</code>).
Host CLI (<code>streamd</code>) + on-device MITM (<code>proxy-android-arm64</code>).
${CHANNEL_LINE}
<a href=\"${URL}\">Download ${TAG}</a>"

69
scripts/streamd-bg.sh Normal file
View file

@ -0,0 +1,69 @@
#!/usr/bin/env bash
# Thin wrapper around `streamd serve` lifecycle commands.
# Prefer calling the binary directly:
# ./streamd serve start|stop|restart|status
#
# Kept so older docs/curl installs that fetch streamd-bg.sh still work.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"
BIN="${STREAMD_BIN:-$ROOT/streamd}"
[[ -x "$BIN" ]] || { echo "streamd-bg: missing executable $BIN" >&2; exit 1; }
cmd="${1:-}"
shift || true
case "$cmd" in
start|stop|restart|status)
exec "$BIN" serve "$cmd" "$@"
;;
log)
# Resolve log file from streamd.yaml when possible; else streamd.log
log="$ROOT/streamd.log"
if [[ -f "$ROOT/streamd.yaml" ]]; then
# shellcheck disable=SC2016
ylog="$(grep -E '^log_file:' "$ROOT/streamd.yaml" | head -1 | sed 's/^log_file:[[:space:]]*//;s/[[:space:]]*$//;s/^["'\'']//;s/["'\'']$//')" || true
if [[ -n "${ylog:-}" ]]; then
if [[ "$ylog" = /* ]]; then log="$ylog"; else log="$ROOT/$ylog"; fi
fi
fi
exec tail -n 100 -f "$log"
;;
start-agent)
cfg="${AGENT_CONFIG:-$ROOT/agent.yaml}"
[[ -f "$cfg" ]] || { echo "streamd-bg: missing $cfg" >&2; exit 1; }
nohup "$BIN" agent run --config "$cfg" >"$ROOT/agent.log" 2>&1 &
echo $! >"$ROOT/agent.pid"
echo "agent started pid=$(cat "$ROOT/agent.pid")"
;;
stop-agent)
if [[ -f "$ROOT/agent.pid" ]]; then
kill "$(cat "$ROOT/agent.pid")" 2>/dev/null || true
rm -f "$ROOT/agent.pid"
echo "agent stopped"
else
echo "agent is not running"
fi
;;
log-agent)
exec tail -n 100 -f "$ROOT/agent.log"
;;
-h|--help|help|"")
cat <<EOF
Usage: $(basename "$0") <command>
Preferred (same machine): ./streamd serve start|stop|restart|status|update
This wrapper still accepts:
start | stop | restart | status | log
start-agent | stop-agent | log-agent
EOF
[[ -n "$cmd" ]] || exit 2
;;
*)
echo "streamd-bg: unknown command: $cmd (try --help)" >&2
exit 1
;;
esac

12
scripts/streamd-update.sh Normal file
View file

@ -0,0 +1,12 @@
#!/usr/bin/env bash
# Thin wrapper around `streamd serve update`.
# Prefer: ./streamd serve update [--beta] [--tag vX.Y.Z] [--no-restart]
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"
BIN="${STREAMD_BIN:-$ROOT/streamd}"
[[ -x "$BIN" ]] || { echo "streamd-update: missing executable $BIN" >&2; exit 1; }
exec "$BIN" serve update "$@"