package webread import ( "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "image/png" "io" "os" "path/filepath" "syscall" "unicode/utf8" "amadan.net/oficina/equipo/internal/attach" "golang.org/x/sys/unix" ) // ErrBundle refuses a bundle directory that is not exactly what the // fetcher writes. var ErrBundle = errors.New("webread: bundle refused") // textTypes are the media types a text file may carry. var textTypes = map[string]bool{"text/html": true, "text/plain": true, "text/css": true, "text/markdown": true, "application/json": true, "image/svg+xml": true} func sum(b []byte) string { s := sha256.Sum256(b) return hex.EncodeToString(s[:]) } // bundleWriter writes generated names only, each created new, never // through a symlink. type bundleWriter struct { dir string files []File } func (w *bundleWriter) add(source, kind, typ string, data []byte) (File, error) { ext := "txt" if kind == KindImage { ext = "png" } f := File{Name: fmt.Sprintf("s%03d.%s", len(w.files)+1, ext), Source: source, Kind: kind, Type: typ, Size: int64(len(data)), SHA256: sum(data)} if len(w.files) >= MaxRequests { return File{}, fmt.Errorf("%w: too many files", ErrBundle) } if err := writeNew(filepath.Join(w.dir, f.Name), data); err != nil { return File{}, err } w.files = append(w.files, f) return f, nil } func (w *bundleWriter) addImage(source string, data []byte, width, height int) (File, error) { f, err := w.add(source, KindImage, attach.PNG, data) if err != nil { return File{}, err } w.files[len(w.files)-1].Width, w.files[len(w.files)-1].Height = width, height f.Width, f.Height = width, height return f, nil } func (w *bundleWriter) finish(log []Entry, used Spent) (Manifest, error) { m := Manifest{Version: 1, Files: append([]File{}, w.files...), Log: append([]Entry{}, log...), Used: used} b, err := json.Marshal(m) if err != nil { return Manifest{}, err } if len(b) > MaxManifestBytes { return Manifest{}, fmt.Errorf("%w: manifest of %d bytes", ErrBundle, len(b)) } return m, writeNew(filepath.Join(w.dir, ManifestName), b) } func writeNew(path string, data []byte) error { f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0600) if err != nil { return err } if _, err = f.Write(data); err != nil { f.Close() return err } return f.Close() } // emptyDir requires dir to be an existing directory, not a symlink, with // nothing in it. func emptyDir(dir string) error { fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) if err != nil { return err } d := os.NewFile(uintptr(fd), dir) defer d.Close() names, err := d.Readdirnames(1) if err != nil && err != io.EOF { return err } if len(names) != 0 { return fmt.Errorf("%w: output directory is not empty", ErrBundle) } return nil } // BundleFile is one checked file and its bytes. type BundleFile struct { File Data []byte } // Bundle is a fetch phase's checked output. type Bundle struct { Files []BundleFile Log []Entry // Used is what the step's fetch phase has spent, as the fetcher said. Used Spent } // ReadBundle reads and checks what the fetcher wrote in dir: the // directory and every file opened without following a symlink, regular // files only, names exactly the generated ones and nothing else, each // file's size and SHA-256 as the manifest says, and every bound the // fetcher keeps. func ReadBundle(dir string) (Bundle, error) { refuse := func(format string, a ...any) (Bundle, error) { return Bundle{}, fmt.Errorf("%w: %s", ErrBundle, fmt.Sprintf(format, a...)) } fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) if err != nil { return refuse("open directory: %v", err) } d := os.NewFile(uintptr(fd), dir) defer d.Close() names, err := d.Readdirnames(MaxRequests + 2) if err != nil && err != io.EOF { return refuse("list: %v", err) } if more, _ := d.Readdirnames(1); len(more) != 0 { return refuse("too many entries") } raw, err := readAt(fd, ManifestName, MaxManifestBytes, false) if err != nil { return refuse("manifest: %v", err) } dec := json.NewDecoder(bytes.NewReader(raw)) dec.DisallowUnknownFields() var m Manifest if err = dec.Decode(&m); err != nil || dec.More() { return refuse("manifest: %v", err) } if m.Version != 1 || len(m.Files) > MaxRequests || len(m.Log) > MaxLogEntries { return refuse("manifest version or counts") } logged := map[string]string{} for _, e := range m.Log { if e.File != "" { logged[e.File] = e.Source } } listed := map[string]bool{} var text, images int64 for _, f := range m.Files { match := fileName.FindStringSubmatch(f.Name) if match == nil || listed[f.Name] || logged[f.Name] != f.Source || f.Source == "" || len(f.SHA256) != 64 || f.Size < 0 { return refuse("file %q", f.Name) } listed[f.Name] = true switch { case match[1] == "txt" && f.Kind == KindText && textTypes[f.Type] && f.Size <= MaxPageText: text += f.Size case match[1] == "png" && f.Kind == KindImage && f.Type == attach.PNG && f.Size <= MaxImageFile && f.Width > 0 && f.Height > 0 && f.Width <= MaxEdge && f.Height <= MaxEdge: images += f.Size default: return refuse("file %q kind %q type %q size %d", f.Name, f.Kind, f.Type, f.Size) } } if text > MaxTotalText || images > MaxImageTotal { return refuse("totals") } // A listed file that is missing fails to open below. for _, n := range names { if n != ManifestName && !listed[n] { return refuse("unexpected entry %q", n) } } b := Bundle{Log: m.Log, Used: m.Used} for _, f := range m.Files { data, err := readAt(fd, f.Name, f.Size, true) if err != nil { return refuse("%s: %v", f.Name, err) } if sum(data) != f.SHA256 { return refuse("%s: hash mismatch", f.Name) } if f.Kind == KindText && !utf8.Valid(data) { return refuse("%s: not UTF-8", f.Name) } if f.Kind == KindImage { c, err := png.DecodeConfig(bytes.NewReader(data)) if attach.Sniff(data) != attach.PNG || err != nil || c.Width != f.Width || c.Height != f.Height { return refuse("%s: not the PNG listed", f.Name) } } b.Files = append(b.Files, BundleFile{File: f, Data: data}) } return b, nil } // readAt reads name in the directory fd: no symlink, a regular file, at // most limit bytes (exactly limit when exact). func readAt(dirfd int, name string, limit int64, exact bool) ([]byte, error) { fd, err := unix.Openat(dirfd, name, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0) if err != nil { return nil, err } f := os.NewFile(uintptr(fd), name) defer f.Close() st, err := f.Stat() if err != nil { return nil, err } if !st.Mode().IsRegular() { return nil, errors.New("not a regular file") } if st.Size() > limit || (exact && st.Size() != limit) { return nil, errors.New("size") } data, err := io.ReadAll(io.LimitReader(f, limit+1)) if err != nil { return nil, err } if int64(len(data)) > limit || (exact && int64(len(data)) != limit) { return nil, errors.New("size") } return data, nil }