streamd v0.2.3: fix NRE Spectre crash under daemon (Linux PTY)
All checks were successful
release / build-and-upload (push) Successful in 6m56s

Wrap N_m3u8DL-RE with util-linux script so Spectre gets a real TTY; drop
subtitles; pin COLUMNS/LINES; kill process group on stop. Fixes immediate
'downloader exited before any media arrived' on serve start.
This commit is contained in:
404errordeveloper 2026-10-10 19:54:41 +02:00
parent a091922efa
commit 5b6f38c9cf
5 changed files with 235 additions and 32 deletions

View file

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

View file

@ -8,7 +8,6 @@ import (
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
@ -67,7 +66,8 @@ type streamProc struct {
wwwDir string
tsPath string
hlsIndex string
nreLog *logfile.Writer
nreLogFile *os.File // per-stream NRE log (banner + append)
nrePTY io.Closer // Linux PTY master; nil on Windows / fallback
ffOutLog *logfile.Writer
ffErrLog *logfile.Writer
stopping bool
@ -258,7 +258,10 @@ func (m *Media) Start(id int64) error {
"--tmp-dir", nreTmp,
"--no-ansi-color",
"--log-level", "ERROR",
"-ss", "0",
// Drop every subtitle track. Live pipe-mux to TS does not need them, and
// an extra Spectre progress row makes redirected-console crashes more
// likely (NRE forces ANSI UI when stdout is a log file).
"-ds", "for=all",
}
if hasKeys {
// Multi-KID SAMPLE-AES streams rainbow-decrypt with a single --key, so
@ -295,23 +298,24 @@ func (m *Media) Start(id int64) error {
}
}
// A rotating log opened with a start banner, rather than truncated. The
// previous run's output is exactly what you need when working out why
// this run is happening.
nreLog, err := logfile.OpenWithBanner(
// Banner + rotate-on-open keep prior runs readable. On Linux, NRE runs under
// a PTY (see startNRELogged): plain file/pipe redirects force Spectre live UI
// with WindowWidth 0 and crash ProgressRefreshThread.
nreLogFile, err := logfile.OpenCmdLog(
filepath.Join(m.logsDir(), st.Name+"-nre.log"),
logfile.DefaultMaxBytes, logfile.DefaultGenerations, "nre")
if err != nil {
return err
}
nreCmd := exec.Command(m.NRE, nreArgs...)
nreCmd.Stdout = nreLog
nreCmd.Stderr = nreLog
hideWindow(nreCmd)
// NRE (v0.6) resolves mp4decrypt via PATH / sibling of its .exe, and often
// ignores --decryption-binary-path for MP4DECRYPT. Match legacy: prepend
// dirs and best-effort copy beside NRE.
nreEnv := os.Environ()
nreEnv = setEnvDefault(nreEnv, "COLUMNS", "120")
nreEnv = setEnvDefault(nreEnv, "LINES", "40")
nreEnv = setEnvDefault(nreEnv, "TERM", "xterm")
pathPrepend := []string{}
if m.MP4Decrypt != "" {
pathPrepend = append(pathPrepend, filepath.Dir(m.MP4Decrypt))
@ -328,14 +332,21 @@ func (m *Media) Start(id int64) error {
nreEnv = prependPathEnv(nreEnv, strings.Join(pathPrepend, sep))
}
nreCmd.Env = nreEnv
if err := nreCmd.Start(); err != nil {
_ = nreLog.Close()
nrePTY, keepLogFD, err := startNRELogged(nreCmd, nreLogFile)
if err != nil {
if keepLogFD {
_ = nreLogFile.Close()
}
if mpdProxy != nil {
mpdProxy.Close()
}
m.fail(id, st.Name, err.Error())
return err
}
ownedLog := nreLogFile
if !keepLogFD {
ownedLog = nil
}
m.Log.Info("downloader started", "stream", st.Name, "pid", nreCmd.Process.Pid)
sessionID, _ := m.Store.OpenSession(id)
@ -349,7 +360,8 @@ func (m *Media) Start(id int64) error {
wwwDir: wwwDir,
tsPath: tsPath,
hlsIndex: filepath.Join(wwwDir, "index.m3u8"),
nreLog: nreLog,
nreLogFile: ownedLog,
nrePTY: nrePTY,
mpdProxy: mpdProxy,
variantSpecs: variantSpecs,
@ -435,11 +447,11 @@ func (m *Media) bootstrapHLS(sp *streamProc) {
_ = m.Store.SetRuntime(sp.id, db.RuntimePatch{
Health: "down",
PlayPath: "/hls/" + sp.name + "/index.m3u8",
LastError: "NRE exited before TS was ready — see logs/" + sp.name + "-nre.log",
LastError: "NRE exited before TS was ready — see data/logs/" + sp.name + "-nre.log",
})
m.Store.AddEvent(db.StreamEvent{
StreamID: sp.id, Kind: db.EventCrashed, Severity: db.SevError,
Message: "downloader exited before any media arrived — see logs/" + sp.name + "-nre.log",
Message: "downloader exited before any media arrived — see data/logs/" + sp.name + "-nre.log",
})
m.closeSession(sp, db.SessionNREExit, "down")
m.cleanupProc(sp.id)
@ -658,7 +670,15 @@ func (m *Media) cleanupProc(id int64) {
if !ok {
return
}
for _, w := range []*logfile.Writer{sp.nreLog, sp.ffOutLog, sp.ffErrLog} {
if sp.nrePTY != nil {
_ = sp.nrePTY.Close()
sp.nrePTY = nil
}
if sp.nreLogFile != nil {
_ = sp.nreLogFile.Close()
sp.nreLogFile = nil
}
for _, w := range []*logfile.Writer{sp.ffOutLog, sp.ffErrLog} {
if w != nil {
_ = w.Close()
}
@ -710,11 +730,11 @@ func (m *Media) refreshHealth(id int64) {
if nreDead {
_ = m.Store.SetRuntime(id, db.RuntimePatch{
Health: "down", PID: 0, PlayPath: playPath, UptimeS: uptime,
LastError: "NRE process exited — see logs/" + sp.name + "-nre.log",
LastError: "NRE process exited — see data/logs/" + sp.name + "-nre.log",
})
m.Store.AddEvent(db.StreamEvent{
StreamID: id, Kind: db.EventCrashed, Severity: db.SevError,
Message: fmt.Sprintf("downloader exited after %.0fs — see logs/%s-nre.log", uptime, sp.name),
Message: fmt.Sprintf("downloader exited after %.0fs — see data/logs/%s-nre.log", uptime, sp.name),
})
m.Log.Error("downloader exited", "stream", sp.name, "uptime_s", int(uptime))
m.closeSession(sp, db.SessionNREExit, "down")
@ -924,11 +944,7 @@ func killProcess(cmd *exec.Cmd) error {
if cmd == nil || cmd.Process == nil {
return nil
}
pid := cmd.Process.Pid
if runtime.GOOS == "windows" {
return exec.Command("taskkill", "/T", "/F", "/PID", strconv.Itoa(pid)).Run()
}
return cmd.Process.Kill()
return killProcessTree(cmd)
}
func prependPathEnv(env []string, prefix string) []string {
@ -951,6 +967,20 @@ func prependPathEnv(env []string, prefix string) []string {
return out
}
// setEnvDefault sets KEY=value when KEY is missing or empty in env.
func setEnvDefault(env []string, key, value string) []string {
prefix := key + "="
for i, e := range env {
if strings.HasPrefix(e, prefix) {
if strings.TrimSpace(e[len(prefix):]) == "" {
env[i] = prefix + value
}
return env
}
}
return append(env, prefix+value)
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {

View file

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

View file

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

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

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