Debian Codegraph @

url.go

raw
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 // A multi-segment path keeps '/', which separates its segments rather than
54 // belonging to one of them.
55 pathSegmentsNoEscapeTable = buildNoEscapeTable("$&+:=@/")
56 )
57
58 // buildNoEscapeTable flags the RFC 3986 unreserved bytes plus alsoSafe as
59 // not needing escape.
60 func buildNoEscapeTable(alsoSafe string) [256]bool {
61 var t [256]bool
62 for i := range 256 {
63 c := byte(i)
64 t[i] = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' ||
65 c == '-' || c == '_' || c == '.' || c == '~' ||
66 strings.IndexByte(alsoSafe, c) >= 0
67 }
68 return t
69 }
70
71 // AppendQueryEscape appends the percent-encoded form of s to dst and returns
72 // the extended slice. The output is byte-identical to net/url.QueryEscape:
73 // unreserved bytes pass through, space becomes '+', everything else becomes
74 // %XX with uppercase hex. dst must not alias s: escaping can grow the input,
75 // so in-place operation is impossible.
76 func AppendQueryEscape[S byteSeq](dst []byte, s S) []byte {
77 return appendEscape(dst, unsafeconv.Bytes(s), &queryNoEscapeTable, escapeQuery)
78 }
79
80 // AppendPathEscape appends the percent-encoded path-segment form of s to dst
81 // and returns the extended slice. The output is byte-identical to
82 // net/url.PathEscape; the aliasing rule matches AppendQueryEscape.
83 func AppendPathEscape[S byteSeq](dst []byte, s S) []byte {
84 return appendEscape(dst, unsafeconv.Bytes(s), &pathNoEscapeTable, escapePath)
85 }
86
87 // AppendPathSegmentsEscape appends the percent-encoded form of the multi-segment
88 // path s to dst and returns the extended slice. It escapes every segment as
89 // AppendPathEscape does but leaves the '/' between them, so the output matches
90 // escaping each segment separately and joining the results with '/'. Use it for
91 // a value whose slashes are separators; use AppendPathEscape for one segment,
92 // where a slash is data and has to be encoded. Empty and dot segments pass
93 // through unchanged, so clean or reject an untrusted value before appending it
94 // under a fixed prefix. The aliasing rule matches AppendQueryEscape.
95 func AppendPathSegmentsEscape[S byteSeq](dst []byte, s S) []byte {
96 return appendEscape(dst, unsafeconv.Bytes(s), &pathSegmentsNoEscapeTable, escapePath)
97 }
98
99 // appendEscape copies runs of unescaped bytes wholesale and expands the rest,
100 // in one pass with no intermediate allocation — unlike net/url, which counts
101 // in a first pass and then rebuilds the string byte by byte.
102 func appendEscape(dst, s []byte, noEscape *[256]bool, mode escapeMode) []byte {
103 i, n := 0, len(s)
104 for i < n {
105 j := i
106 for j < n && noEscape[s[j]] {
107 j++
108 }
109 dst = append(dst, s[i:j]...)
110 if j == n {
111 break
112 }
113 if c := s[j]; mode == escapeQuery && c == ' ' {
114 dst = append(dst, '+')
115 } else {
116 dst = append(dst, '%', upperHexDigits[c>>4], upperHexDigits[c&0x0F])
117 }
118 i = j + 1
119 }
120 return dst
121 }
122
123 // AppendQueryUnescape appends the decoded form of the query component s to
124 // dst and returns the extended slice, converting '+' to space and %XX to the
125 // byte it encodes, exactly like net/url.QueryUnescape including its
126 // url.EscapeError values for malformed escapes. On error the returned slice
127 // is dst with its original length (its backing array may still have been
128 // reallocated by growth). Decoding never grows the input, so dst may be
129 // s[:0] on a common backing array to decode in place; any other overlap is
130 // invalid. Note that an in-place decode that fails has already overwritten
131 // the prefix of s before the malformed escape with decoded bytes — treat s
132 // as consumed once an in-place decode starts, error or not.
133 func AppendQueryUnescape[S byteSeq](dst []byte, s S) ([]byte, error) {
134 return appendUnescape(dst, unsafeconv.Bytes(s), escapeQuery)
135 }
136
137 // AppendPathUnescape appends the decoded form of the path component s to dst
138 // and returns the extended slice, decoding %XX and leaving '+' verbatim,
139 // exactly like net/url.PathUnescape. Error and aliasing behavior match
140 // AppendQueryUnescape.
141 func AppendPathUnescape[S byteSeq](dst []byte, s S) ([]byte, error) {
142 return appendUnescape(dst, unsafeconv.Bytes(s), escapePath)
143 }
144
145 // appendUnescape jumps between escape sites with vectorized scans —
146 // IndexAny2 (SWAR/AVX2) when '+' also needs rewriting, bytes.IndexByte
147 // otherwise — and copies the clean spans between them wholesale, so input
148 // without escapes costs one scan and one copy.
149 func appendUnescape(dst, s []byte, mode escapeMode) ([]byte, error) {
150 off := len(dst)
151 i, n := 0, len(s)
152 for i < n {
153 var j int
154 if mode == escapeQuery {
155 j = IndexAny2(s[i:], '%', '+')
156 } else {
157 j = bytes.IndexByte(s[i:], '%')
158 }
159 if j < 0 {
160 return append(dst, s[i:]...), nil
161 }
162 j += i
163 dst = append(dst, s[i:j]...)
164 if s[j] == '+' {
165 dst = append(dst, ' ')
166 i = j + 1
167 continue
168 }
169 // s[j] == '%': the error substrings below match net/url's unescape.
170 if j+2 >= n {
171 return dst[:off], url.EscapeError(s[j:])
172 }
173 hi := unhexTable[s[j+1]]
174 lo := unhexTable[s[j+2]]
175 if hi > 0x0F || lo > 0x0F {
176 return dst[:off], url.EscapeError(s[j : j+3])
177 }
178 dst = append(dst, hi<<4|lo)
179 i = j + 3
180 }
181 return dst, nil
182 }