| 1 | package webread |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "image/png" |
| 11 | "io" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "syscall" |
| 15 | "unicode/utf8" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/attach" |
| 18 | "golang.org/x/sys/unix" |
| 19 | ) |
| 20 | |
| 21 | // ErrBundle refuses a bundle directory that is not exactly what the |
| 22 | // fetcher writes. |
| 23 | var ErrBundle = errors.New("webread: bundle refused") |
| 24 | |
| 25 | // textTypes are the media types a text file may carry. |
| 26 | var textTypes = map[string]bool{"text/html": true, "text/plain": true, "text/css": true, "text/markdown": true, "application/json": true, "image/svg+xml": true} |
| 27 | |
| 28 | func sum(b []byte) string { |
| 29 | s := sha256.Sum256(b) |
| 30 | return hex.EncodeToString(s[:]) |
| 31 | } |
| 32 | |
| 33 | // bundleWriter writes generated names only, each created new, never |
| 34 | // through a symlink. |
| 35 | type bundleWriter struct { |
| 36 | dir string |
| 37 | files []File |
| 38 | } |
| 39 | |
| 40 | func (w *bundleWriter) add(source, kind, typ string, data []byte) (File, error) { |
| 41 | ext := "txt" |
| 42 | if kind == KindImage { |
| 43 | ext = "png" |
| 44 | } |
| 45 | 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)} |
| 46 | if len(w.files) >= MaxRequests { |
| 47 | return File{}, fmt.Errorf("%w: too many files", ErrBundle) |
| 48 | } |
| 49 | if err := writeNew(filepath.Join(w.dir, f.Name), data); err != nil { |
| 50 | return File{}, err |
| 51 | } |
| 52 | w.files = append(w.files, f) |
| 53 | return f, nil |
| 54 | } |
| 55 | |
| 56 | func (w *bundleWriter) addImage(source string, data []byte, width, height int) (File, error) { |
| 57 | f, err := w.add(source, KindImage, attach.PNG, data) |
| 58 | if err != nil { |
| 59 | return File{}, err |
| 60 | } |
| 61 | w.files[len(w.files)-1].Width, w.files[len(w.files)-1].Height = width, height |
| 62 | f.Width, f.Height = width, height |
| 63 | return f, nil |
| 64 | } |
| 65 | |
| 66 | func (w *bundleWriter) finish(log []Entry, used Spent) (Manifest, error) { |
| 67 | m := Manifest{Version: 1, Files: append([]File{}, w.files...), Log: append([]Entry{}, log...), Used: used} |
| 68 | b, err := json.Marshal(m) |
| 69 | if err != nil { |
| 70 | return Manifest{}, err |
| 71 | } |
| 72 | if len(b) > MaxManifestBytes { |
| 73 | return Manifest{}, fmt.Errorf("%w: manifest of %d bytes", ErrBundle, len(b)) |
| 74 | } |
| 75 | return m, writeNew(filepath.Join(w.dir, ManifestName), b) |
| 76 | } |
| 77 | |
| 78 | func writeNew(path string, data []byte) error { |
| 79 | f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0600) |
| 80 | if err != nil { |
| 81 | return err |
| 82 | } |
| 83 | if _, err = f.Write(data); err != nil { |
| 84 | f.Close() |
| 85 | return err |
| 86 | } |
| 87 | return f.Close() |
| 88 | } |
| 89 | |
| 90 | // emptyDir requires dir to be an existing directory, not a symlink, with |
| 91 | // nothing in it. |
| 92 | func emptyDir(dir string) error { |
| 93 | fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| 94 | if err != nil { |
| 95 | return err |
| 96 | } |
| 97 | d := os.NewFile(uintptr(fd), dir) |
| 98 | defer d.Close() |
| 99 | names, err := d.Readdirnames(1) |
| 100 | if err != nil && err != io.EOF { |
| 101 | return err |
| 102 | } |
| 103 | if len(names) != 0 { |
| 104 | return fmt.Errorf("%w: output directory is not empty", ErrBundle) |
| 105 | } |
| 106 | return nil |
| 107 | } |
| 108 | |
| 109 | // BundleFile is one checked file and its bytes. |
| 110 | type BundleFile struct { |
| 111 | File |
| 112 | Data []byte |
| 113 | } |
| 114 | |
| 115 | // Bundle is a fetch phase's checked output. |
| 116 | type Bundle struct { |
| 117 | Files []BundleFile |
| 118 | Log []Entry |
| 119 | // Used is what the step's fetch phase has spent, as the fetcher said. |
| 120 | Used Spent |
| 121 | } |
| 122 | |
| 123 | // ReadBundle reads and checks what the fetcher wrote in dir: the |
| 124 | // directory and every file opened without following a symlink, regular |
| 125 | // files only, names exactly the generated ones and nothing else, each |
| 126 | // file's size and SHA-256 as the manifest says, and every bound the |
| 127 | // fetcher keeps. |
| 128 | func ReadBundle(dir string) (Bundle, error) { |
| 129 | refuse := func(format string, a ...any) (Bundle, error) { |
| 130 | return Bundle{}, fmt.Errorf("%w: %s", ErrBundle, fmt.Sprintf(format, a...)) |
| 131 | } |
| 132 | fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| 133 | if err != nil { |
| 134 | return refuse("open directory: %v", err) |
| 135 | } |
| 136 | d := os.NewFile(uintptr(fd), dir) |
| 137 | defer d.Close() |
| 138 | names, err := d.Readdirnames(MaxRequests + 2) |
| 139 | if err != nil && err != io.EOF { |
| 140 | return refuse("list: %v", err) |
| 141 | } |
| 142 | if more, _ := d.Readdirnames(1); len(more) != 0 { |
| 143 | return refuse("too many entries") |
| 144 | } |
| 145 | raw, err := readAt(fd, ManifestName, MaxManifestBytes, false) |
| 146 | if err != nil { |
| 147 | return refuse("manifest: %v", err) |
| 148 | } |
| 149 | dec := json.NewDecoder(bytes.NewReader(raw)) |
| 150 | dec.DisallowUnknownFields() |
| 151 | var m Manifest |
| 152 | if err = dec.Decode(&m); err != nil || dec.More() { |
| 153 | return refuse("manifest: %v", err) |
| 154 | } |
| 155 | if m.Version != 1 || len(m.Files) > MaxRequests || len(m.Log) > MaxLogEntries { |
| 156 | return refuse("manifest version or counts") |
| 157 | } |
| 158 | logged := map[string]string{} |
| 159 | for _, e := range m.Log { |
| 160 | if e.File != "" { |
| 161 | logged[e.File] = e.Source |
| 162 | } |
| 163 | } |
| 164 | listed := map[string]bool{} |
| 165 | var text, images int64 |
| 166 | for _, f := range m.Files { |
| 167 | match := fileName.FindStringSubmatch(f.Name) |
| 168 | if match == nil || listed[f.Name] || logged[f.Name] != f.Source || f.Source == "" || len(f.SHA256) != 64 || f.Size < 0 { |
| 169 | return refuse("file %q", f.Name) |
| 170 | } |
| 171 | listed[f.Name] = true |
| 172 | switch { |
| 173 | case match[1] == "txt" && f.Kind == KindText && textTypes[f.Type] && f.Size <= MaxPageText: |
| 174 | text += f.Size |
| 175 | case match[1] == "png" && f.Kind == KindImage && f.Type == attach.PNG && f.Size <= MaxImageFile && |
| 176 | f.Width > 0 && f.Height > 0 && f.Width <= MaxEdge && f.Height <= MaxEdge: |
| 177 | images += f.Size |
| 178 | default: |
| 179 | return refuse("file %q kind %q type %q size %d", f.Name, f.Kind, f.Type, f.Size) |
| 180 | } |
| 181 | } |
| 182 | if text > MaxTotalText || images > MaxImageTotal { |
| 183 | return refuse("totals") |
| 184 | } |
| 185 | // A listed file that is missing fails to open below. |
| 186 | for _, n := range names { |
| 187 | if n != ManifestName && !listed[n] { |
| 188 | return refuse("unexpected entry %q", n) |
| 189 | } |
| 190 | } |
| 191 | b := Bundle{Log: m.Log, Used: m.Used} |
| 192 | for _, f := range m.Files { |
| 193 | data, err := readAt(fd, f.Name, f.Size, true) |
| 194 | if err != nil { |
| 195 | return refuse("%s: %v", f.Name, err) |
| 196 | } |
| 197 | if sum(data) != f.SHA256 { |
| 198 | return refuse("%s: hash mismatch", f.Name) |
| 199 | } |
| 200 | if f.Kind == KindText && !utf8.Valid(data) { |
| 201 | return refuse("%s: not UTF-8", f.Name) |
| 202 | } |
| 203 | if f.Kind == KindImage { |
| 204 | c, err := png.DecodeConfig(bytes.NewReader(data)) |
| 205 | if attach.Sniff(data) != attach.PNG || err != nil || c.Width != f.Width || c.Height != f.Height { |
| 206 | return refuse("%s: not the PNG listed", f.Name) |
| 207 | } |
| 208 | } |
| 209 | b.Files = append(b.Files, BundleFile{File: f, Data: data}) |
| 210 | } |
| 211 | return b, nil |
| 212 | } |
| 213 | |
| 214 | // readAt reads name in the directory fd: no symlink, a regular file, at |
| 215 | // most limit bytes (exactly limit when exact). |
| 216 | func readAt(dirfd int, name string, limit int64, exact bool) ([]byte, error) { |
| 217 | fd, err := unix.Openat(dirfd, name, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0) |
| 218 | if err != nil { |
| 219 | return nil, err |
| 220 | } |
| 221 | f := os.NewFile(uintptr(fd), name) |
| 222 | defer f.Close() |
| 223 | st, err := f.Stat() |
| 224 | if err != nil { |
| 225 | return nil, err |
| 226 | } |
| 227 | if !st.Mode().IsRegular() { |
| 228 | return nil, errors.New("not a regular file") |
| 229 | } |
| 230 | if st.Size() > limit || (exact && st.Size() != limit) { |
| 231 | return nil, errors.New("size") |
| 232 | } |
| 233 | data, err := io.ReadAll(io.LimitReader(f, limit+1)) |
| 234 | if err != nil { |
| 235 | return nil, err |
| 236 | } |
| 237 | if int64(len(data)) > limit || (exact && int64(len(data)) != limit) { |
| 238 | return nil, errors.New("size") |
| 239 | } |
| 240 | return data, nil |
| 241 | } |
| 242 | |