// Package servecmd is the streamd control plane, exposed as a library so the // single drm binary can host it as a subcommand. package servecmd import ( "flag" "fmt" "log/slog" "net" "net/http" "os" "os/signal" "path/filepath" "strings" "syscall" "time" "streamd/apps/streamd/internal/api" "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" "streamd/apps/streamd/internal/scheduler" "streamd/apps/streamd/internal/supervisor" "streamd/apps/streamd/internal/tsfanout" "streamd/apps/streamd/internal/ui" "streamd/apps/streamd/internal/ws" "streamd/bootstrap" "streamd/modhost" ) // Run dispatches a streamd subcommand. args[0] is the subcommand name. func Run(args []string) error { if len(args) < 1 { Usage() return fmt.Errorf("streamd: subcommand required") } sub, rest := args[0], args[1:] switch sub { case "serve": serveCmd(rest) case "worker": return fmt.Errorf("worker: media is supervised in-process by `serve` now") case "help", "-h", "--help": Usage() default: Usage() return fmt.Errorf("streamd: unknown subcommand %q", sub) } return nil } // Usage prints the streamd subcommand help. func Usage() { fmt.Fprintf(os.Stderr, `streamd — Go control plane for DRM restreams Usage: 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 /streamd.yaml next to the binary) serve flags: --bind listen address (default 127.0.0.1:8083) --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) --bin-dir where to install/look for media tools (default /bin) --skip-deps do not auto-download missing ffmpeg / N_m3u8DL-RE / mp4decrypt --log-level debug | info | warn | error (default info) access control: --admin-user create this admin account on first run (with --admin-pass) --admin-pass password for --admin-user (prefer STREAMD_ADMIN_PASS) --token legacy shared bearer token, treated as an admin API key (or STREAMD_TOKEN). Prefer per-agent keys in the dashboard. --session-ttl how long a login lasts without activity (default 12h) --trusted-proxies CIDRs allowed to set X-Forwarded-For/-Proto (e.g. 127.0.0.1/32) --allowed-origins extra CORS origins, comma separated (default same-origin only) --cookie-secure always mark cookies Secure (set this behind a TLS proxy) --audit-retain how long to keep audit rows (default 2160h / 90d) on-demand and scheduling: --ondemand-wait hold a viewer request this long while a stream starts --ondemand-capture-wait as above, when credentials must be captured first --schedule-preroll refresh credentials this far before a scheduled start --ts-fanout-buffer live MPEG-TS bytes buffered per stream for /live/ Bind defaults to 127.0.0.1 — put a TLS-terminating reverse proxy in front and 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. /.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) { 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") skipDeps := fs.Bool("skip-deps", false, "skip auto-download of missing media tools") 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") 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") cookieSecure := fs.Bool("cookie-secure", false, "always mark cookies Secure") 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") // 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) depsLog := slog.NewLogLogger(lg.Handler(), slog.LevelInfo) dataDir := opt.Data if dataDir == "" { var src string dataDir, src = resolveDataDir("") if src != "flag" { lg.Info("using data directory", "data", dataDir, "source", src) } } 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(opt.TrustedProxies); err != nil { lg.Error("invalid --trusted-proxies", "err", err) os.Exit(2) } else { trust.Proxies = nets } origins := splitList(opt.AllowedOrigins) 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) } } store, err := db.Open(dataDir) if err != nil { lg.Error("open database", "err", err) os.Exit(1) } defer store.Close() authStore, err := auth.New(store.DB, tok) if err != nil { lg.Error("init auth tables", "err", err) os.Exit(1) } mw := auth.NewMiddleware(authStore, trust, opt.CookieSecure) mw.SessionTTL = opt.SessionTTL authH := auth.NewHandler(authStore, mw, lg) bootstrapAdmin(lg, authStore, authH, opt.AdminUser, opt.AdminPass) depStatus, _ := deps.Ensure(deps.Options{ BinDir: opt.BinDir, SkipDownload: opt.SkipDeps, Log: depsLog, }, opt.NRE, opt.FFmpeg, opt.MP4Decrypt) 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, ProxyResolver: eg, }) defer sup.Close() gate := hlsgate.New(hlsgate.Config{ Store: store, WWWRoot: filepath.Join(dataDir, "www"), Sup: sup, Fanout: fanout, Capture: hub, Trust: trust, Log: lg, Wait: opt.OnDemandWait, CaptureWait: opt.CaptureWait, }) sup.ViewersFn = gate.ViewersFor sched := scheduler.New(store, sup, hub, lg, opt.SchedulePreroll) modulesRoot := filepath.Join(dataDir, "modules") modStore := modstore.New(modulesRoot) if err := modhost.SetModulesDir(modulesRoot); err != nil { lg.Error("set modules dir", "err", err) os.Exit(1) } lg.Info("modules store", "dir", modulesRoot) apiH := &api.Handler{ Store: store, Auth: authStore, Trust: trust, Supervisor: sup, Capture: hub, StartedAt: time.Now(), Deps: depStatus, WWWRoot: filepath.Join(dataDir, "www"), LogRoot: filepath.Join(dataDir, "logs"), DataDir: dataDir, Modules: modStore, ModulesNotify: hub, Notifier: hub, Viewers: gate, Scheduler: sched, Egress: eg, Log: lg, } mux := http.NewServeMux() apiH.Mount(mux) authH.Mount(mux) hub.Mount(mux) gate.Mount(mux) mux.Handle("/", ui.Handler()) mux.Handle("/static/", http.StripPrefix("/static/", ui.Static())) var handler http.Handler = mux handler = mw.Attach(handler) handler = httpx.SecurityHeaders(trust, handler) handler = httpx.CORS(origins, handler) handler = httpx.AccessLog(lg, trust, handler) srv := &http.Server{ Addr: opt.Bind, Handler: handler, ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 120 * time.Second, } 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") } 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(opt.Bind); err == nil { switch strings.ToLower(host) { case "127.0.0.1", "localhost", "::1": 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", opt.Bind) } } stopBG := make(chan struct{}) go hub.RunExpireLoop(stopBG) go authStore.RunMaintenance(stopBG, opt.AuditRetain) go store.RunHistoryMaintenance(stopBG) go gate.RunIdleLoop(stopBG) go sched.Run(stopBG) go resumeEnabledStreams(lg, store, sup) go func() { ch := make(chan os.Signal, 1) signal.Notify(ch, os.Interrupt, syscall.SIGTERM) <-ch lg.Info("shutting down") close(stopBG) sup.Close() _ = authStore.FlushAudit() _ = srv.Close() }() if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { lg.Error("listen", "err", err) os.Exit(1) } } func newLogger(level string) *slog.Logger { var lv slog.Level switch strings.ToLower(strings.TrimSpace(level)) { case "debug": lv = slog.LevelDebug case "warn", "warning": lv = slog.LevelWarn case "error": lv = slog.LevelError default: lv = slog.LevelInfo } // A text handler keeps the console output as readable as the old // log.Printf lines while giving every record structured attributes. return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: lv})) } // bootstrapAdmin creates the first account from flags when asked, or prints a // one-time setup token so the dashboard can create it. func bootstrapAdmin(lg *slog.Logger, store *auth.Store, h *auth.Handler, user, pass string) { n, err := store.CountUsers() if err != nil { lg.Error("count users", "err", err) return } if n > 0 { h.SetSetupToken("") return } if pass == "" { pass = os.Getenv("STREAMD_ADMIN_PASS") } if user != "" && pass != "" { if _, err := store.CreateUser(user, pass, auth.RoleAdmin); err != nil { lg.Error("create admin account", "err", err) } else { lg.Info("created initial admin account", "user", strings.ToLower(strings.TrimSpace(user))) h.SetSetupToken("") return } } tok := auth.NewSetupToken() h.SetSetupToken(tok) lg.Warn("no accounts exist yet — open the dashboard and use this one-time setup token to create the first admin", "setup_token", tok) } // resumeEnabledStreams restarts streams that were running before a restart. // On-demand streams are deliberately left stopped: a viewer's first request // starts them, which is the whole point. func resumeEnabledStreams(lg *slog.Logger, store *db.Store, sup *supervisor.Media) { time.Sleep(500 * time.Millisecond) list, err := store.ListStreams() if err != nil { return } for _, st := range list { if !st.Enabled || strings.TrimSpace(st.MPD) == "" { continue } if st.OnDemand { lg.Info("auto-start skipped: on-demand stream waits for a viewer", "stream", st.Name) continue } mpd := strings.ToLower(strings.TrimSpace(st.MPD)) if !strings.HasPrefix(mpd, "http://") && !strings.HasPrefix(mpd, "https://") { lg.Warn("auto-start skipped: mpd is not an http(s) URL", "stream", st.Name) continue } lg.Info("auto-starting enabled stream", "stream", st.Name) func(id int64, name string) { defer func() { if r := recover(); r != nil { lg.Error("auto-start panicked", "stream", name, "panic", r) } }() if err := sup.Start(id); err != nil { lg.Error("auto-start failed", "stream", name, "err", err) } }(st.ID, st.Name) time.Sleep(1500 * time.Millisecond) } } func splitList(s string) []string { var out []string for _, p := range strings.Split(s, ",") { if p = strings.TrimSpace(p); p != "" { out = append(out, p) } } return out }