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
This commit is contained in:
parent
da8e1123ec
commit
8fc7e4c0b8
57 changed files with 4031 additions and 257 deletions
|
|
@ -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
4
.gitignore
vendored
|
|
@ -218,7 +218,7 @@ apps/proxy/proxy-android-arm64
|
|||
apps/proxy/rteproxy-android-arm64
|
||||
# local / VPS deploy + operator scripts (test stuff; keep out of git)
|
||||
deploy/
|
||||
# Ignore local scripts, but keep 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/**
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
`)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
31
apps/pkg/modhost/exec_test.go
Normal file
31
apps/pkg/modhost/exec_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
39
apps/pkg/modhost/root_test.go
Normal file
39
apps/pkg/modhost/root_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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=
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
45
apps/streamd/internal/api/apps_test.go
Normal file
45
apps/streamd/internal/api/apps_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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 {
|
||||
|
|
|
|||
254
apps/streamd/internal/api/egress.go
Normal file
254
apps/streamd/internal/api/egress.go
Normal 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)
|
||||
}
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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,10 @@ 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
|
||||
}
|
||||
return s.migrateEgress()
|
||||
}
|
||||
|
||||
func now() string {
|
||||
|
|
@ -264,10 +272,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 +329,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 +372,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 +569,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 +667,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 +746,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 {
|
||||
|
|
|
|||
226
apps/streamd/internal/db/egress.go
Normal file
226
apps/streamd/internal/db/egress.go
Normal 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
|
||||
}
|
||||
117
apps/streamd/internal/db/egress_test.go
Normal file
117
apps/streamd/internal/db/egress_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
80
apps/streamd/internal/egress/conf.go
Normal file
80
apps/streamd/internal/egress/conf.go
Normal 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()
|
||||
}
|
||||
401
apps/streamd/internal/egress/manager.go
Normal file
401
apps/streamd/internal/egress/manager.go
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
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{},
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
100
apps/streamd/internal/egress/manager_test.go
Normal file
100
apps/streamd/internal/egress/manager_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
262
apps/streamd/internal/egress/wg_linux.go
Normal file
262
apps/streamd/internal/egress/wg_linux.go
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
//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
|
||||
}
|
||||
}
|
||||
// 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"))
|
||||
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.
|
||||
cmd := exec.Command("ip", "netns", "exec", nsName,
|
||||
"curl", "-4", "-fsS", "--max-time", "5", "https://ifconfig.me/ip")
|
||||
out, err := cmd.Output()
|
||||
if err != nil {
|
||||
cmd = exec.Command("ip", "netns", "exec", nsName,
|
||||
"wget", "-qO-", "--timeout=5", "https://ifconfig.me/ip")
|
||||
out, err = cmd.Output()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(string(out))
|
||||
}
|
||||
19
apps/streamd/internal/egress/wg_stub.go
Normal file
19
apps/streamd/internal/egress/wg_stub.go
Normal 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
|
||||
}
|
||||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -37,12 +37,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)
|
||||
|
|
@ -82,15 +89,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 +111,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 +152,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 +219,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
|
||||
|
|
@ -246,7 +267,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)
|
||||
|
|
|
|||
|
|
@ -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),
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
|
|
@ -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();
|
||||
})();
|
||||
|
||||
|
|
|
|||
|
|
@ -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()) {
|
||||
|
|
|
|||
336
apps/streamd/servecmd/config.go
Normal file
336
apps/streamd/servecmd/config.go
Normal 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
|
||||
}
|
||||
101
apps/streamd/servecmd/config_test.go
Normal file
101
apps/streamd/servecmd/config_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
200
apps/streamd/servecmd/daemon.go
Normal file
200
apps/streamd/servecmd/daemon.go
Normal 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
|
||||
}
|
||||
37
apps/streamd/servecmd/daemon_unix.go
Normal file
37
apps/streamd/servecmd/daemon_unix.go
Normal 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)
|
||||
}
|
||||
46
apps/streamd/servecmd/daemon_windows.go
Normal file
46
apps/streamd/servecmd/daemon_windows.go
Normal 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)
|
||||
}
|
||||
71
apps/streamd/servecmd/data_dir_test.go
Normal file
71
apps/streamd/servecmd/data_dir_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
|
|
@ -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,35 @@ 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.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 +456,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 +487,7 @@ func serveCmd(args []string) {
|
|||
Notifier: hub,
|
||||
Viewers: gate,
|
||||
Scheduler: sched,
|
||||
Egress: eg,
|
||||
Log: lg,
|
||||
}
|
||||
|
||||
|
|
@ -239,15 +495,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 +506,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 +520,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)
|
||||
|
|
|
|||
243
apps/streamd/servecmd/update.go
Normal file
243
apps/streamd/servecmd/update.go
Normal 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))
|
||||
}
|
||||
}
|
||||
22
apps/streamd/servecmd/update_unix.go
Normal file
22
apps/streamd/servecmd/update_unix.go
Normal 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
|
||||
}
|
||||
123
apps/streamd/servecmd/update_windows.go
Normal file
123
apps/streamd/servecmd/update_windows.go
Normal 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
|
||||
}
|
||||
19
docs/examples/streamd.yaml
Normal file
19
docs/examples/streamd.yaml
Normal 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
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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,75 @@ 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.
|
||||
|
||||
### 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 +570,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 +578,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.
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
|
|
@ -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,17 @@ 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. See
|
||||
[streamd-server-setup.md](streamd-server-setup.md) §7.
|
||||
- **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
|
||||
|
|
@ -61,9 +65,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 |
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
)
|
||||
|
||||
|
|
|
|||
|
|
@ -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>"
|
||||
)
|
||||
|
|
|
|||
|
|
@ -84,7 +84,7 @@ Upload in the streamd Modules page, or unpack into <code>modules/<name>/</
|
|||
<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
69
scripts/streamd-bg.sh
Normal 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
12
scripts/streamd-update.sh
Normal 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 "$@"
|
||||
Loading…
Add table
Add a link
Reference in a new issue