// 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" } }