| 1 | package utils |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "net/url" |
| 6 | "strings" |
| 7 | |
| 8 | "github.com/gofiber/utils/v2/internal/unsafeconv" |
| 9 | ) |
| 10 | |
| 11 | // escapeMode selects between net/url's query-component and path-segment |
| 12 | // escaping dialects: only the query dialect maps '+' to space. |
| 13 | type escapeMode uint8 |
| 14 | |
| 15 | const ( |
| 16 | escapeQuery escapeMode = iota |
| 17 | escapePath |
| 18 | ) |
| 19 | |
| 20 | // upperHexDigits is the escape alphabet used by the Append*Escape helpers, |
| 21 | // matching net/url. |
| 22 | const upperHexDigits = "0123456789ABCDEF" |
| 23 | |
| 24 | // unhexTable maps an ASCII byte to its hexadecimal digit value, or 0xFF for |
| 25 | // bytes that are not hex digits. |
| 26 | var unhexTable = buildUnhexTable() |
| 27 | |
| 28 | func buildUnhexTable() [256]byte { |
| 29 | var t [256]byte |
| 30 | for i := range t { |
| 31 | t[i] = 0xFF |
| 32 | } |
| 33 | for c := byte('0'); c <= '9'; c++ { |
| 34 | t[c] = c - '0' |
| 35 | } |
| 36 | for c := byte('a'); c <= 'f'; c++ { |
| 37 | t[c] = c - 'a' + 10 |
| 38 | } |
| 39 | for c := byte('A'); c <= 'F'; c++ { |
| 40 | t[c] = c - 'A' + 10 |
| 41 | } |
| 42 | return t |
| 43 | } |
| 44 | |
| 45 | // queryNoEscapeTable and pathNoEscapeTable flag the bytes net/url leaves |
| 46 | // verbatim in query components and path segments respectively. They are |
| 47 | // derived from net/url's shouldEscape rules and pinned to them by |
| 48 | // exhaustive per-byte tests. Path segments additionally keep the sub-delims |
| 49 | // net/url's encodePathSegment mode does not escape. |
| 50 | var ( |
| 51 | queryNoEscapeTable = buildNoEscapeTable("") |
| 52 | pathNoEscapeTable = buildNoEscapeTable("$&+:=@") |
| 53 | ) |
| 54 | |
| 55 | // buildNoEscapeTable flags the RFC 3986 unreserved bytes plus alsoSafe as |
| 56 | // not needing escape. |
| 57 | func buildNoEscapeTable(alsoSafe string) [256]bool { |
| 58 | var t [256]bool |
| 59 | for i := range 256 { |
| 60 | c := byte(i) |
| 61 | t[i] = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || |
| 62 | c == '-' || c == '_' || c == '.' || c == '~' || |
| 63 | strings.IndexByte(alsoSafe, c) >= 0 |
| 64 | } |
| 65 | return t |
| 66 | } |
| 67 | |
| 68 | // AppendQueryEscape appends the percent-encoded form of s to dst and returns |
| 69 | // the extended slice. The output is byte-identical to net/url.QueryEscape: |
| 70 | // unreserved bytes pass through, space becomes '+', everything else becomes |
| 71 | // %XX with uppercase hex. dst must not alias s: escaping can grow the input, |
| 72 | // so in-place operation is impossible. |
| 73 | func AppendQueryEscape[S byteSeq](dst []byte, s S) []byte { |
| 74 | return appendEscape(dst, unsafeconv.Bytes(s), &queryNoEscapeTable, escapeQuery) |
| 75 | } |
| 76 | |
| 77 | // AppendPathEscape appends the percent-encoded path-segment form of s to dst |
| 78 | // and returns the extended slice. The output is byte-identical to |
| 79 | // net/url.PathEscape; the aliasing rule matches AppendQueryEscape. |
| 80 | func AppendPathEscape[S byteSeq](dst []byte, s S) []byte { |
| 81 | return appendEscape(dst, unsafeconv.Bytes(s), &pathNoEscapeTable, escapePath) |
| 82 | } |
| 83 | |
| 84 | // appendEscape copies runs of unescaped bytes wholesale and expands the rest, |
| 85 | // in one pass with no intermediate allocation — unlike net/url, which counts |
| 86 | // in a first pass and then rebuilds the string byte by byte. |
| 87 | func appendEscape(dst, s []byte, noEscape *[256]bool, mode escapeMode) []byte { |
| 88 | i, n := 0, len(s) |
| 89 | for i < n { |
| 90 | j := i |
| 91 | for j < n && noEscape[s[j]] { |
| 92 | j++ |
| 93 | } |
| 94 | dst = append(dst, s[i:j]...) |
| 95 | if j == n { |
| 96 | break |
| 97 | } |
| 98 | if c := s[j]; mode == escapeQuery && c == ' ' { |
| 99 | dst = append(dst, '+') |
| 100 | } else { |
| 101 | dst = append(dst, '%', upperHexDigits[c>>4], upperHexDigits[c&0x0F]) |
| 102 | } |
| 103 | i = j + 1 |
| 104 | } |
| 105 | return dst |
| 106 | } |
| 107 | |
| 108 | // AppendQueryUnescape appends the decoded form of the query component s to |
| 109 | // dst and returns the extended slice, converting '+' to space and %XX to the |
| 110 | // byte it encodes, exactly like net/url.QueryUnescape including its |
| 111 | // url.EscapeError values for malformed escapes. On error the returned slice |
| 112 | // is dst with its original length (its backing array may still have been |
| 113 | // reallocated by growth). Decoding never grows the input, so dst may be |
| 114 | // s[:0] on a common backing array to decode in place; any other overlap is |
| 115 | // invalid. Note that an in-place decode that fails has already overwritten |
| 116 | // the prefix of s before the malformed escape with decoded bytes — treat s |
| 117 | // as consumed once an in-place decode starts, error or not. |
| 118 | func AppendQueryUnescape[S byteSeq](dst []byte, s S) ([]byte, error) { |
| 119 | return appendUnescape(dst, unsafeconv.Bytes(s), escapeQuery) |
| 120 | } |
| 121 | |
| 122 | // AppendPathUnescape appends the decoded form of the path component s to dst |
| 123 | // and returns the extended slice, decoding %XX and leaving '+' verbatim, |
| 124 | // exactly like net/url.PathUnescape. Error and aliasing behavior match |
| 125 | // AppendQueryUnescape. |
| 126 | func AppendPathUnescape[S byteSeq](dst []byte, s S) ([]byte, error) { |
| 127 | return appendUnescape(dst, unsafeconv.Bytes(s), escapePath) |
| 128 | } |
| 129 | |
| 130 | // appendUnescape jumps between escape sites with vectorized scans — |
| 131 | // IndexAny2 (SWAR/AVX2) when '+' also needs rewriting, bytes.IndexByte |
| 132 | // otherwise — and copies the clean spans between them wholesale, so input |
| 133 | // without escapes costs one scan and one copy. |
| 134 | func appendUnescape(dst, s []byte, mode escapeMode) ([]byte, error) { |
| 135 | off := len(dst) |
| 136 | i, n := 0, len(s) |
| 137 | for i < n { |
| 138 | var j int |
| 139 | if mode == escapeQuery { |
| 140 | j = IndexAny2(s[i:], '%', '+') |
| 141 | } else { |
| 142 | j = bytes.IndexByte(s[i:], '%') |
| 143 | } |
| 144 | if j < 0 { |
| 145 | return append(dst, s[i:]...), nil |
| 146 | } |
| 147 | j += i |
| 148 | dst = append(dst, s[i:j]...) |
| 149 | if s[j] == '+' { |
| 150 | dst = append(dst, ' ') |
| 151 | i = j + 1 |
| 152 | continue |
| 153 | } |
| 154 | // s[j] == '%': the error substrings below match net/url's unescape. |
| 155 | if j+2 >= n { |
| 156 | return dst[:off], url.EscapeError(s[j:]) |
| 157 | } |
| 158 | hi := unhexTable[s[j+1]] |
| 159 | lo := unhexTable[s[j+2]] |
| 160 | if hi > 0x0F || lo > 0x0F { |
| 161 | return dst[:off], url.EscapeError(s[j : j+3]) |
| 162 | } |
| 163 | dst = append(dst, hi<<4|lo) |
| 164 | i = j + 3 |
| 165 | } |
| 166 | return dst, nil |
| 167 | } |