-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisposition.go
More file actions
432 lines (361 loc) · 10.5 KB
/
Copy pathdisposition.go
File metadata and controls
432 lines (361 loc) · 10.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
// Package dispo provides helpers to build RFC-compliant Content-Disposition
// header values (RFC 6266) with support for internationalized filenames
// using RFC 5987 encoding.
//
// The implementation focuses on:
// - security (removal of control characters, CRLF injection prevention)
// - interoperability (ASCII fallback + filename*)
// - performance (minimal allocations)
// - strict adherence to RFC 6266 and RFC 5987 where applicable
package dispo
import (
"net/textproto"
"strings"
"unicode"
"unicode/utf8"
)
const (
inline = "inline"
attachment = "attachment"
filenamePrefix = `; filename="`
filenameStarPrefix = `; filename*=UTF-8''`
filenameSuffix = `"`
httpTokenSeparators = `()<>@,;:\"/[]?={} `
hexUpper = "0123456789ABCDEF"
asciiScratchSize = 256
encodedScratchSize = 512
)
var rfc5987AttrCharTable = buildRFC5987AttrCharTable()
var httpTokenCharTable = buildHTTPTokenCharTable()
var asciiSpaceTable = [256]uint8{'\t': 1, '\n': 1, '\v': 1, '\f': 1, '\r': 1, ' ': 1}
var quotedPairEscapeTable = [256]uint8{'"': 1, '\\': 1}
// ContentDisposition builds a Content-Disposition header value using the
// provided disposition type and filename.
//
// The dispositionType is normalized as follows:
// - surrounding HTTP whitespace is trimmed
// - "inline" and "attachment" (case-insensitive) are normalized to lowercase
// - any other valid HTTP token is returned in lowercase
// - invalid or empty values fall back to "attachment"
//
// The filename is sanitized and encoded according to RFC 6266 and RFC 5987.
//
// Behavior details:
// - Control characters are removed.
// - Leading and trailing whitespace is trimmed.
// - Internal ASCII and Unicode whitespace is normalized to ASCII spaces.
// - Invalid UTF-8 byte sequences become '_' in filename and U+FFFD in filename*.
// - If the resulting filename is empty, only the disposition-type is returned.
//
// ASCII handling (filename parameter):
// - Always emitted when filename is non-empty.
// - Encoded as quoted-string.
// - The fallback avoids `\`, `/`, and `%HH` sequences per RFC 6266 guidance.
// - `"` is escaped with backslash in the quoted-string form.
// - Other printable ASCII characters are preserved as-is.
//
// Non-ASCII handling:
// - Non-ASCII runes are replaced with '_' in the ASCII filename.
// - The sanitized filename is emitted via filename* using RFC 5987 ext-value
// syntax with UTF-8, an empty language tag, and percent-encoded UTF-8 bytes.
// - Path separators are rewritten to '_' in both filename and filename*.
//
// Notes:
// - filename* is included when the ASCII fallback cannot represent the
// sanitized filename faithfully.
// - Spaces in filename* are encoded as %20.
// - The function does not enforce filename length limits.
func ContentDisposition(dispositionType, name string) string {
return contentDisposition(NormalizeDispositionType(dispositionType), name)
}
// Attachment is a shorthand for ContentDisposition("attachment", name).
//
// See ContentDisposition for full behavior description.
func Attachment(name string) string {
return contentDisposition(attachment, name)
}
// Inline is a shorthand for ContentDisposition("inline", name).
//
// See ContentDisposition for full behavior description.
func Inline(name string) string {
return contentDisposition(inline, name)
}
func contentDisposition(dispoType, name string) string {
if name == "" {
return dispoType
}
if out, ok := trySimpleASCIIContentDisposition(dispoType, name); ok {
return out
}
var (
out strings.Builder
// Tuned scratch capacities keep the common slow path on stack-backed slices
// and avoid extra heap work for short and medium filenames.
asciiScratch [asciiScratchSize]byte
encodedScratch [encodedScratchSize]byte
)
out.Grow(len(dispoType) + len(filenamePrefix) + len(name) + len(filenameSuffix) + len(filenameStarPrefix))
out.WriteString(dispoType)
asciiBuf := asciiScratch[:0]
if len(name)*2 > cap(asciiBuf) {
asciiBuf = make([]byte, 0, len(name)*2)
}
encodedBuf := encodedScratch[:0]
hasFilenameStar := false
hasContent := false
pendingSpaces := 0
for i := 0; i < len(name); {
if b := name[i]; b < utf8.RuneSelf {
idx := i
i++
if isASCIIControl(b) {
continue
}
if asciiSpaceTable[b] != 0 {
if hasContent {
pendingSpaces++
}
continue
}
if hasFilenameStar {
asciiBuf, encodedBuf = appendPendingSpacesToBoth(asciiBuf, encodedBuf, pendingSpaces)
} else {
asciiBuf = appendPendingASCIISpaces(asciiBuf, pendingSpaces)
}
pendingSpaces = 0
hasContent = true
if isASCIIFallbackUnsafeByte(name, idx, b) {
if !hasFilenameStar {
out.Grow(len(filenameStarPrefix) + len(name)*3)
if len(name)*3 > cap(encodedBuf) {
encodedBuf = make([]byte, 0, len(name)*3)
}
encodedBuf = appendRFC5987EncodedASCII(encodedBuf, name[:idx])
hasFilenameStar = true
}
asciiBuf = append(asciiBuf, '_')
if b == '/' || b == '\\' {
encodedBuf = append(encodedBuf, '_')
continue
}
encodedBuf = appendRFC5987EncodedByte(encodedBuf, b)
continue
}
asciiBuf = appendQuotedStringByte(asciiBuf, b)
if hasFilenameStar {
encodedBuf = appendRFC5987EncodedByte(encodedBuf, b)
}
continue
}
r, size := utf8.DecodeRuneInString(name[i:])
i += size
if unicode.IsControl(r) {
continue
}
if unicode.IsSpace(r) {
if hasContent {
pendingSpaces++
}
continue
}
if !hasFilenameStar {
out.Grow(len(filenameStarPrefix) + len(name)*3)
if len(name)*3 > cap(encodedBuf) {
encodedBuf = make([]byte, 0, len(name)*3)
}
encodedBuf = appendRFC5987EncodedASCII(encodedBuf, name[:i-size])
for range pendingSpaces {
encodedBuf = appendRFC5987EncodedByte(encodedBuf, ' ')
}
asciiBuf = appendPendingASCIISpaces(asciiBuf, pendingSpaces)
hasFilenameStar = true
} else {
asciiBuf, encodedBuf = appendPendingSpacesToBoth(asciiBuf, encodedBuf, pendingSpaces)
}
pendingSpaces = 0
hasContent = true
asciiBuf = append(asciiBuf, '_')
encodedBuf = appendRFC5987EncodedRune(encodedBuf, r)
}
if !hasContent {
return dispoType
}
if !hasFilenameStar && rewriteRFC6266PercentHazards(asciiBuf) {
out.Grow(len(filenameStarPrefix) + len(name)*3)
if len(name)*3 > cap(encodedBuf) {
encodedBuf = make([]byte, 0, len(name)*3)
}
encodedBuf = appendRFC5987EncodedASCII(encodedBuf, name)
hasFilenameStar = true
}
out.WriteString(filenamePrefix)
out.Write(asciiBuf)
out.WriteString(filenameSuffix)
if hasFilenameStar {
out.WriteString(filenameStarPrefix)
out.Write(encodedBuf)
}
return out.String()
}
func trySimpleASCIIContentDisposition(dispoType, name string) (string, bool) {
if name == "" {
return dispoType, true
}
for i := 0; i < len(name); i++ {
b := name[i]
if b == ' ' {
if i == 0 || i == len(name)-1 {
return "", false
}
continue
}
switch {
case b >= utf8.RuneSelf:
return "", false
case isASCIIControl(b):
return "", false
case b == '"' || b == '\\' || b == '/':
return "", false
case b == '%' && i+2 < len(name) && isHex(name[i+1]) && isHex(name[i+2]):
return "", false
}
}
return dispoType + filenamePrefix + name + filenameSuffix, true
}
// NormalizeDispositionType normalizes a Content-Disposition disposition type.
//
// Surrounding HTTP whitespace is trimmed, "inline" and "attachment" are
// canonicalized to lowercase, valid extension tokens are lowercased, and empty
// or invalid values fall back to "attachment".
func NormalizeDispositionType(v string) string {
v = textproto.TrimString(v)
if !isHTTPToken(v) {
return attachment
}
switch {
case strings.EqualFold(v, inline):
return inline
case strings.EqualFold(v, attachment):
return attachment
default:
return strings.ToLower(v)
}
}
func isASCIIControl(b byte) bool {
return b < 0x20 || b == 0x7f
}
func isHex(b byte) bool {
return (b >= '0' && b <= '9') || (b >= 'A' && b <= 'F') || (b >= 'a' && b <= 'f')
}
func isHTTPToken(s string) bool {
if s == "" {
return false
}
for i := 0; i < len(s); i++ {
if !httpTokenCharTable[s[i]] {
return false
}
}
return true
}
func appendPendingASCIISpaces(asciiBuf []byte, pendingSpaces int) []byte {
for range pendingSpaces {
asciiBuf = append(asciiBuf, ' ')
}
return asciiBuf
}
func appendPendingSpacesToBoth(asciiBuf, encodedBuf []byte, pendingSpaces int) ([]byte, []byte) {
for range pendingSpaces {
asciiBuf = append(asciiBuf, ' ')
encodedBuf = appendRFC5987EncodedByte(encodedBuf, ' ')
}
return asciiBuf, encodedBuf
}
func appendQuotedStringByte(asciiBuf []byte, b byte) []byte {
if quotedPairEscapeTable[b] != 0 {
return append(asciiBuf, '\\', b)
}
return append(asciiBuf, b)
}
func isASCIIFallbackUnsafeByte(name string, i int, b byte) bool {
if b == '/' || b == '\\' {
return true
}
return b == '%' && i+2 < len(name) && isHex(name[i+1]) && isHex(name[i+2])
}
func rewriteRFC6266PercentHazards(asciiBuf []byte) bool {
replaced := false
for i := 0; i+2 < len(asciiBuf); i++ {
if asciiBuf[i] == '%' && isHex(asciiBuf[i+1]) && isHex(asciiBuf[i+2]) {
asciiBuf[i] = '_'
replaced = true
}
}
return replaced
}
func appendRFC5987EncodedASCII(buf []byte, s string) []byte {
written := false
pendingSpaces := 0
for i := 0; i < len(s); i++ {
b := s[i]
if isASCIIControl(b) {
continue
}
if asciiSpaceTable[b] != 0 {
if written {
pendingSpaces++
}
continue
}
for range pendingSpaces {
buf = appendRFC5987EncodedByte(buf, ' ')
}
pendingSpaces = 0
written = true
if b == '/' || b == '\\' {
b = '_'
}
buf = appendRFC5987EncodedByte(buf, b)
}
return buf
}
func appendRFC5987EncodedRune(encodedBuf []byte, r rune) []byte {
var runeBuf [utf8.UTFMax]byte
n := utf8.EncodeRune(runeBuf[:], r)
for i := 0; i < n; i++ {
encodedBuf = appendRFC5987EncodedByte(encodedBuf, runeBuf[i])
}
return encodedBuf
}
func appendRFC5987EncodedByte(buf []byte, b byte) []byte {
if rfc5987AttrCharTable[b] {
return append(buf, b)
}
return append(buf, '%', hexUpper[b>>4], hexUpper[b&0x0f])
}
func buildRFC5987AttrCharTable() [256]bool {
var table [256]bool
for b := byte('a'); b <= byte('z'); b++ {
table[b] = true
}
for b := byte('A'); b <= byte('Z'); b++ {
table[b] = true
}
for b := byte('0'); b <= byte('9'); b++ {
table[b] = true
}
for i := 0; i < len("!#$&+-.^_`|~"); i++ {
table["!#$&+-.^_`|~"[i]] = true
}
return table
}
func buildHTTPTokenCharTable() [256]bool {
var table [256]bool
for b := byte(0x21); b < 0x7f; b++ {
table[b] = true
}
for i := 0; i < len(httpTokenSeparators); i++ {
table[httpTokenSeparators[i]] = false
}
return table
}