package validate import ( "fmt" "strings" "unicode" "unicode/utf8" ) const ( FilenameMinLen = 1 FilenameMaxLen = 255 AttachmentIDsMax = 10 ) // Filename проверяет отображаемое имя. Оно нигде не используется как путь, но попадает в заголовки // и к другим клиентам, поэтому разделители и невидимые управляющие символы запрещены. func Filename(s string) error { if !utf8.ValidString(s) { return newError("filename", "must be valid UTF-8") } if !notOnlyWhitespace(s) { return newError("filename", "must not be empty or whitespace only") } if !codePointsBetween(s, FilenameMinLen, FilenameMaxLen) { return newError("filename", fmt.Sprintf("length must be in [%d, %d] code points", FilenameMinLen, FilenameMaxLen)) } if s == "." || s == ".." { return newError("filename", "must not be a path component") } if strings.ContainsFunc(s, unsafeFilenameRune) { return newError("filename", "must not contain path separators or control characters") } return nil } func unsafeFilenameRune(r rune) bool { switch { case r == '/', r == '\\', unicode.IsControl(r): return true case r == '
', r == '
': return true case r >= '‪' && r <= '‮', r >= '⁦' && r <= '⁩': // Символы смены направления текста позволяют выдать evil.exe за безобидное имя. return true } return false } // AttachmentIDs приводит ID к каноничному виду с сохранением порядка. func AttachmentIDs(ids []string) ([]string, error) { if len(ids) > AttachmentIDsMax { return nil, newError("attachment_ids", fmt.Sprintf("count must be at most %d", AttachmentIDsMax)) } out := make([]string, 0, len(ids)) seen := make(map[string]struct{}, len(ids)) for i, raw := range ids { id, err := CanonicalUUID(fmt.Sprintf("attachment_ids[%d]", i), raw) if err != nil { return nil, err } if _, dup := seen[id]; dup { return nil, newError("attachment_ids", "must not contain duplicates") } seen[id] = struct{}{} out = append(out, id) } return out, nil }