// Package attach decides what a person may attach to a message and makes // it safe to keep: the type is sniffed from the bytes (never taken from // the client), the size and count are bounded, the name is reduced to a // plain base name, and an image's location is stripped. It also scales // images down for previews and for a model's image input. Pure: no I/O. // The instance and the runner share it. package attach import ( "bytes" "encoding/json" "errors" "path" "strings" "unicode" "unicode/utf8" ) // Limits. const ( // MaxBytes bounds one attachment. MaxBytes = 10 << 20 // MaxPerMessage bounds one message's attachments. MaxPerMessage = 5 // ChunkBytes is one relay frame's share of a file: base64 in JSON stays // well under the stream's 256 KiB frame bound. ChunkBytes = 128 << 10 // MaxChunks is a 10 MB file's chunk count. MaxChunks = (MaxBytes + ChunkBytes - 1) / ChunkBytes // MaxName bounds a stored name, in bytes. MaxName = 120 // MaxSide and MaxPixels bound an image's size, read from its header // before anything decodes it: a small file can claim a huge canvas. MaxSide = 12000 MaxPixels = 40_000_000 ) // Kinds. const ( KindImage = "image" KindFile = "file" ) // Media types Equipo keeps. const ( PNG = "image/png" JPEG = "image/jpeg" WebP = "image/webp" GIF = "image/gif" PDF = "application/pdf" Text = "text/plain" Markdown = "text/markdown" CSV = "text/csv" JSON = "application/json" ) // Refusals. Each has words in the instance's copy. var ( ErrEmpty = errors.New("attach: empty") ErrTooLarge = errors.New("attach: too large") ErrType = errors.New("attach: type not allowed") ErrHEIC = errors.New("attach: heic") ErrPixels = errors.New("attach: too many pixels") ) // TooBig reports image dimensions over MaxSide or MaxPixels. func TooBig(w, h int) bool { return w > MaxSide || h > MaxSide || int64(w)*int64(h) > MaxPixels } // Info is what Inspect found. type Info struct { Kind, MediaType, Name string // Width and Height are an image's pixel size, 0 when unknown. Width, Height int } // IsImage reports a media type Equipo shows as an image. func IsImage(mediaType string) bool { switch mediaType { case PNG, JPEG, WebP, GIF: return true } return false } // Allowed reports a media type Equipo keeps. func Allowed(mediaType string) bool { switch mediaType { case PNG, JPEG, WebP, GIF, PDF, Text, Markdown, CSV, JSON: return true } return false } var imageExt = map[string]string{".png": PNG, ".jpg": JPEG, ".jpeg": JPEG, ".webp": WebP, ".gif": GIF} var heicExt = map[string]bool{".heic": true, ".heif": true, ".hif": true} // Inspect checks one upload and returns what it is and the bytes to keep // (an image with its location stripped). declared is the client's // Content-Type, a hint only: an image or PDF type that disagrees with the // bytes is refused. func Inspect(name, declared string, data []byte) (Info, []byte, error) { if len(data) == 0 { return Info{}, nil, ErrEmpty } if len(data) > MaxBytes { return Info{}, nil, ErrTooLarge } name = SafeName(name) ext := strings.ToLower(path.Ext(name)) declared = strings.ToLower(strings.TrimSpace(strings.SplitN(declared, ";", 2)[0])) sniffed := Sniff(data) if sniffed == "image/heic" || (sniffed == "" && heicExt[ext]) || declared == "image/heic" || declared == "image/heif" { return Info{}, nil, ErrHEIC } switch { case IsImage(sniffed): if want, ok := imageExt[ext]; (ext != "" && !ok) || (ok && !sameImage(want, sniffed)) { return Info{}, nil, ErrType } if (strings.HasPrefix(declared, "image/") || declared == PDF) && !sameImage(declared, sniffed) { return Info{}, nil, ErrType } clean, err := StripLocation(sniffed, data) if err != nil { return Info{}, nil, ErrType } w, h := Dimensions(sniffed, clean) if w == 0 || h == 0 { return Info{}, nil, ErrType } if TooBig(w, h) { return Info{}, nil, ErrPixels } return Info{Kind: KindImage, MediaType: sniffed, Name: withExt(name, sniffed), Width: w, Height: h}, clean, nil case sniffed == PDF: if (ext != "" && ext != ".pdf") || (declared != "" && declared != PDF && declared != "application/octet-stream" && (strings.HasPrefix(declared, "image/") || strings.HasPrefix(declared, "text/"))) { return Info{}, nil, ErrType } return Info{Kind: KindFile, MediaType: PDF, Name: withExt(name, PDF)}, data, nil case sniffed == "": if !isText(data) || imageExt[ext] != "" || ext == ".pdf" || strings.HasPrefix(declared, "image/") || declared == PDF { return Info{}, nil, ErrType } media := Text switch ext { case ".md", ".markdown": media = Markdown case ".csv": media = CSV case ".json": if json.Valid(data) { media = JSON } } if name == "" { name = "file.txt" } return Info{Kind: KindFile, MediaType: media, Name: name}, data, nil } return Info{}, nil, ErrType } func sameImage(a, b string) bool { norm := func(s string) string { if s == "image/jpg" || s == "image/pjpeg" { return JPEG } return s } return norm(a) == norm(b) } // withExt gives a nameless or extensionless image or PDF a fitting name. func withExt(name, media string) string { ext := map[string]string{PNG: ".png", JPEG: ".jpg", WebP: ".webp", GIF: ".gif", PDF: ".pdf"}[media] if name == "" { kind := "image" if media == PDF { kind = "document" } return kind + ext } if path.Ext(name) == "" { return name + ext } return name } // Sniff names an image, HEIC or PDF by its magic number; "" for anything // else (text is checked separately). func Sniff(b []byte) string { switch { case bytes.HasPrefix(b, []byte("\x89PNG\r\n\x1a\n")): return PNG case bytes.HasPrefix(b, []byte{0xff, 0xd8, 0xff}): return JPEG case bytes.HasPrefix(b, []byte("GIF87a")), bytes.HasPrefix(b, []byte("GIF89a")): return GIF case len(b) >= 12 && string(b[:4]) == "RIFF" && string(b[8:12]) == "WEBP": return WebP case bytes.HasPrefix(b, []byte("%PDF-")): return PDF case len(b) >= 12 && string(b[4:8]) == "ftyp": switch string(b[8:12]) { case "heic", "heix", "hevc", "hevx", "heim", "heis", "mif1", "msf1", "heif": return "image/heic" } } return "" } // isText is valid UTF-8 with no NUL and no other control characters // beyond tab, newline, carriage return and form feed. func isText(b []byte) bool { if !utf8.Valid(b) { return false } for _, r := range string(b) { if r == 0 || (r < 0x20 && r != '\t' && r != '\n' && r != '\r' && r != '\f') || r == 0x7f { return false } } return true } // SafeName is the base name only, with no path, control or quote // characters, at most MaxName bytes (the extension kept); "" when nothing // is left. func SafeName(name string) string { name = strings.ReplaceAll(name, "\\", "/") if i := strings.LastIndex(name, "/"); i >= 0 { name = name[i+1:] } var b strings.Builder for _, r := range name { switch { case r == utf8.RuneError, unicode.IsControl(r), r == '"', r == '\'', r == '`', r == '<', r == '>', r == ':', r == '*', r == '?', r == '|': continue case unicode.IsSpace(r): b.WriteRune(' ') default: b.WriteRune(r) } } name = strings.Trim(strings.Join(strings.Fields(b.String()), " "), ". ") if len(name) > MaxName { ext := path.Ext(name) if len(ext) > 12 { ext = "" } stem := name[:MaxName-len(ext)] for !utf8.ValidString(stem) { stem = stem[:len(stem)-1] } name = strings.TrimRight(stem, ". ") + ext } return name } // Chunks is the number of relay frames for size bytes. func Chunks(size int64) int { return int((size + ChunkBytes - 1) / ChunkBytes) }