sonda/internal/streaming/streaming.go
tgiachi 46463846b3 feat(library): named media libraries managed through the API
- feat(storage): libraries table (name, path); audio_files points at a library
  by id instead of repeating the root path; migration 0005 for both drivers
  turns every existing root into a library and keeps file ids, tracks and the
  missing flag
- feat(library): Libraries service validates names and paths: absolute, an
  existing directory, never the filesystem root, never inside or around
  another library (checked on real paths, so symlinks cannot hide an overlap)
- feat(api): admin-only GET/POST /libraries, PATCH/DELETE /libraries/{id} and
  POST /libraries/{id}/scan; deleting a library drops its index entries and
  keeps tracks and listening history
- feat(library): the scanner and the scan manager work on libraries; scanning
  with no libraries answers 409 no_libraries
- feat(streaming): the library directory comes from the database instead of
  a configured list of roots
- breaking(config): library.roots is removed; an old config fails with a hint
  to use POST /api/v1/libraries
- test: CRUD and duplicates on both databases, path change keeps files,
  upgrade of a database written before libraries existed
2026-11-11 13:30:25 +01:00

147 lines
4.4 KiB
Go

// Package streaming opens audio files for playback.
//
// The only job here is to turn a track id into an open, verified file. The
// relative path is treated as untrusted and the file is opened through os.Root,
// so that nothing, not even a symlink swapped in at the last moment, can lead
// outside the library directory. The library directory itself comes from the
// libraries table, which only admins can change.
package streaming
import (
"context"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"time"
)
// Errors returned by Open. Handlers map them to HTTP statuses.
var (
ErrNotFound = errors.New("no playable file for this track")
ErrFileMissing = errors.New("audio file is missing on disk")
ErrUnsafePath = errors.New("audio path is outside the library")
)
// File is where a track's audio lives: the directory of its library plus a
// path relative to it, exactly as the scanner stored it.
type File struct {
Root string // absolute library directory
RelPath string // slash-separated
}
// Source finds the file to play for a track.
type Source interface {
// PlayableFile returns ErrNotFound when the track does not exist or every
// file of it is flagged missing.
PlayableFile(ctx context.Context, trackID int64) (File, error)
}
// Stream is an open audio file ready to be served. The caller must Close it.
type Stream struct {
File *os.File
Name string
ModTime time.Time
ContentType string
}
// Close releases the file.
func (s *Stream) Close() error { return s.File.Close() }
// Service opens tracks for playback.
type Service struct {
source Source
}
// NewService builds a Service that plays files found by source.
func NewService(source Source) *Service {
return &Service{source: source}
}
// Open returns the audio file of a track, after verifying that it is a regular
// file inside its library directory.
//
// The file is opened through an os.Root, which refuses to leave the root at
// open time: a symlink swapped in after any earlier check cannot escape, and
// there is no gap between "check the path" and "open the file".
func (s *Service) Open(ctx context.Context, trackID int64) (*Stream, error) {
f, err := s.source.PlayableFile(ctx, trackID)
if err != nil {
return nil, err
}
rel, err := s.validate(f)
if err != nil {
return nil, err
}
root, err := os.OpenRoot(filepath.Clean(f.Root))
if errors.Is(err, fs.ErrNotExist) {
return nil, ErrFileMissing // volume not mounted
}
if err != nil {
return nil, fmt.Errorf("open library root: %w", err)
}
defer root.Close() // files already opened stay valid
// O_NONBLOCK so that a FIFO cannot hang the request: opening one would
// otherwise block until a writer appears.
file, err := root.OpenFile(rel, os.O_RDONLY|nonBlock, 0)
switch {
case errors.Is(err, fs.ErrNotExist):
return nil, ErrFileMissing
case err != nil && strings.Contains(err.Error(), "path escapes from parent"):
// os.Root has no exported error for this case.
return nil, fmt.Errorf("%w: symlink leaves the library", ErrUnsafePath)
case err != nil:
return nil, fmt.Errorf("open audio file: %w", err)
}
// Check what was actually opened, not what the path looked like earlier.
info, err := file.Stat()
if err != nil {
_ = file.Close()
return nil, fmt.Errorf("stat audio file: %w", err)
}
if !info.Mode().IsRegular() {
_ = file.Close()
return nil, fmt.Errorf("%w: not a regular file", ErrUnsafePath)
}
return &Stream{
File: file,
Name: filepath.Base(rel),
ModTime: info.ModTime(),
ContentType: contentType(rel),
}, nil
}
// validate checks the library directory and the relative path and returns the
// cleaned relative path to open under the directory.
func (s *Service) validate(f File) (string, error) {
if !filepath.IsAbs(filepath.Clean(f.Root)) {
return "", fmt.Errorf("%w: library directory is not absolute", ErrUnsafePath)
}
rel := filepath.FromSlash(f.RelPath)
if rel == "" || filepath.IsAbs(rel) {
return "", fmt.Errorf("%w: bad relative path", ErrUnsafePath)
}
rel = filepath.Clean(rel)
if rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
return "", fmt.Errorf("%w: path escapes the root", ErrUnsafePath)
}
return rel, nil
}
func contentType(path string) string {
switch strings.ToLower(filepath.Ext(path)) {
case ".mp3":
return "audio/mpeg"
case ".flac":
return "audio/flac"
default:
return "application/octet-stream"
}
}