// 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" "drmdecryption/apps/streamd/internal/api" "drmdecryption/apps/streamd/internal/auth" "drmdecryption/apps/streamd/internal/db" "drmdecryption/apps/streamd/internal/deps" "drmdecryption/apps/streamd/internal/hlsgate" "drmdecryption/apps/streamd/internal/httpx" "drmdecryption/apps/streamd/internal/scheduler" "drmdecryption/apps/streamd/internal/supervisor" "drmdecryption/apps/streamd/internal/tsfanout" "drmdecryption/apps/streamd/internal/ui" "drmdecryption/apps/streamd/internal/ws" ) // 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 [flags] serve flags: --bind listen address (default 127.0.0.1:8083) --data data dir for sqlite + www + work (default .cache/streamd) --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. `) } 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)") 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 /bin)") skipDeps := fs.Bool("skip-deps", false, "skip auto-download of missing media tools") logLevel := fs.String("log-level", "info", "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") trustedProxies := fs.String("trusted-proxies", "", "CIDRs allowed to set X-Forwarded-For") allowedOrigins := fs.String("allowed-origins", "", "extra CORS origins, comma separated") 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/.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) lg := newLogger(*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 if dataDir == "" { dataDir = filepath.Join(".", ".cache", "streamd") } tok := *token if tok == "" { tok = os.Getenv("STREAMD_TOKEN") } trust := httpx.Trust{} if nets, err := httpx.ParseCIDRs(*trustedProxies); err != nil { lg.Error("invalid --trusted-proxies", "err", err) os.Exit(2) } else { trust.Proxies = nets } origins := splitList(*allowedOrigins) for _, sub := range []string{"www", "work", "logs"} { 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, *cookieSecure) mw.SessionTTL = *sessionTTL authH := auth.NewHandler(authStore, mw, lg) bootstrapAdmin(lg, authStore, authH, *adminUser, *adminPass) depStatus, _ := deps.Ensure(deps.Options{ BinDir: *binDir, SkipDownload: *skipDeps, Log: depsLog, }, *nre, *ffmpeg, *mp4decrypt) fanout := tsfanout.NewSet(*tsBuffer) hub := ws.NewHub(store, lg, origins) sup := supervisor.NewMedia(supervisor.Options{ Store: store, DataDir: dataDir, NRE: depStatus.NRE, FFmpeg: depStatus.FFmpeg, MP4Decrypt: depStatus.MP4Decrypt, Log: lg, Fanout: fanout, Notifier: hub, }) 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: *ondemandWait, CaptureWait: *ondemandCaptureWait, }) // 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) 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"), Notifier: hub, Viewers: gate, Scheduler: sched, Log: lg, } mux := http.NewServeMux() 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) handler = httpx.CORS(origins, handler) handler = httpx.AccessLog(lg, trust, handler) srv := &http.Server{ Addr: *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, } lg.Info("streamd listening", "addr", *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(*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) } } stopBG := make(chan struct{}) go hub.RunExpireLoop(stopBG) go authStore.RunMaintenance(stopBG, *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 }