-
Notifications
You must be signed in to change notification settings - Fork 10.1k
/
Copy pathcontent_disposition.js
219 lines (208 loc) · 7.69 KB
/
content_disposition.js
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
/* Copyright 2017 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { stringToBytes } from "../shared/util.js";
// This getFilenameFromContentDispositionHeader function is adapted from
// https://github.com/Rob--W/open-in-browser/blob/7e2e35a38b8b4e981b11da7b2f01df0149049e92/extension/content-disposition.js
// with the following changes:
// - Modified to conform to PDF.js's coding style.
// - Move return to the end of the function to prevent Babel from dropping the
// function declarations.
/**
* Extract file name from the Content-Disposition HTTP response header.
*
* @param {string} contentDisposition
* @returns {string} Filename, if found in the Content-Disposition header.
*/
function getFilenameFromContentDispositionHeader(contentDisposition) {
let needsEncodingFixup = true;
// filename*=ext-value ("ext-value" from RFC 5987, referenced by RFC 6266).
let tmp = toParamRegExp("filename\\*", "i").exec(contentDisposition);
if (tmp) {
tmp = tmp[1];
let filename = rfc2616unquote(tmp);
filename = unescape(filename);
filename = rfc5987decode(filename);
filename = rfc2047decode(filename);
return fixupEncoding(filename);
}
// Continuations (RFC 2231 section 3, referenced by RFC 5987 section 3.1).
// filename*n*=part
// filename*n=part
tmp = rfc2231getparam(contentDisposition);
if (tmp) {
// RFC 2047, section
const filename = rfc2047decode(tmp);
return fixupEncoding(filename);
}
// filename=value (RFC 5987, section 4.1).
tmp = toParamRegExp("filename", "i").exec(contentDisposition);
if (tmp) {
tmp = tmp[1];
let filename = rfc2616unquote(tmp);
filename = rfc2047decode(filename);
return fixupEncoding(filename);
}
// After this line there are only function declarations. We cannot put
// "return" here for readability because babel would then drop the function
// declarations...
function toParamRegExp(attributePattern, flags) {
return new RegExp(
"(?:^|;)\\s*" +
attributePattern +
"\\s*=\\s*" +
// Captures: value = token | quoted-string
// (RFC 2616, section 3.6 and referenced by RFC 6266 4.1)
"(" +
'[^";\\s][^;\\s]*' +
"|" +
'"(?:[^"\\\\]|\\\\"?)+"?' +
")",
flags
);
}
function textdecode(encoding, value) {
if (encoding) {
if (!/^[\x00-\xFF]+$/.test(value)) {
return value;
}
try {
const decoder = new TextDecoder(encoding, { fatal: true });
const buffer = stringToBytes(value);
value = decoder.decode(buffer);
needsEncodingFixup = false;
} catch {
// TextDecoder constructor threw - unrecognized encoding.
}
}
return value;
}
function fixupEncoding(value) {
if (needsEncodingFixup && /[\x80-\xff]/.test(value)) {
// Maybe multi-byte UTF-8.
value = textdecode("utf-8", value);
if (needsEncodingFixup) {
// Try iso-8859-1 encoding.
value = textdecode("iso-8859-1", value);
}
}
return value;
}
function rfc2231getparam(contentDispositionStr) {
const matches = [];
let match;
// Iterate over all filename*n= and filename*n*= with n being an integer
// of at least zero. Any non-zero number must not start with '0'.
const iter = toParamRegExp("filename\\*((?!0\\d)\\d+)(\\*?)", "ig");
while ((match = iter.exec(contentDispositionStr)) !== null) {
let [, n, quot, part] = match; // eslint-disable-line prefer-const
n = parseInt(n, 10);
if (n in matches) {
// Ignore anything after the invalid second filename*0.
if (n === 0) {
break;
}
continue;
}
matches[n] = [quot, part];
}
const parts = [];
for (let n = 0; n < matches.length; ++n) {
if (!(n in matches)) {
// Numbers must be consecutive. Truncate when there is a hole.
break;
}
let [quot, part] = matches[n]; // eslint-disable-line prefer-const
part = rfc2616unquote(part);
if (quot) {
part = unescape(part);
if (n === 0) {
part = rfc5987decode(part);
}
}
parts.push(part);
}
return parts.join("");
}
function rfc2616unquote(value) {
if (value.startsWith('"')) {
const parts = value.slice(1).split('\\"');
// Find the first unescaped " and terminate there.
for (let i = 0; i < parts.length; ++i) {
const quotindex = parts[i].indexOf('"');
if (quotindex !== -1) {
parts[i] = parts[i].slice(0, quotindex);
parts.length = i + 1; // Truncates and stop the iteration.
}
parts[i] = parts[i].replaceAll(/\\(.)/g, "$1");
}
value = parts.join('"');
}
return value;
}
function rfc5987decode(extvalue) {
// Decodes "ext-value" from RFC 5987.
const encodingend = extvalue.indexOf("'");
if (encodingend === -1) {
// Some servers send "filename*=" without encoding 'language' prefix,
// e.g. in https://github.com/Rob--W/open-in-browser/issues/26
// Let's accept the value like Firefox (57) (Chrome 62 rejects it).
return extvalue;
}
const encoding = extvalue.slice(0, encodingend);
const langvalue = extvalue.slice(encodingend + 1);
// Ignore language (RFC 5987 section 3.2.1, and RFC 6266 section 4.1 ).
const value = langvalue.replace(/^[^']*'/, "");
return textdecode(encoding, value);
}
function rfc2047decode(value) {
// RFC 2047-decode the result. Firefox tried to drop support for it, but
// backed out because some servers use it - https://bugzil.la/875615
// Firefox's condition for decoding is here: https://searchfox.org/mozilla-central/rev/4a590a5a15e35d88a3b23dd6ac3c471cf85b04a8/netwerk/mime/nsMIMEHeaderParamImpl.cpp#742-748
// We are more strict and only recognize RFC 2047-encoding if the value
// starts with "=?", since then it is likely that the full value is
// RFC 2047-encoded.
// Firefox also decodes words even where RFC 2047 section 5 states:
// "An 'encoded-word' MUST NOT appear within a 'quoted-string'."
if (!value.startsWith("=?") || /[\x00-\x19\x80-\xff]/.test(value)) {
return value;
}
// RFC 2047, section 2.4
// encoded-word = "=?" charset "?" encoding "?" encoded-text "?="
// charset = token (but let's restrict to characters that denote a
// possibly valid encoding).
// encoding = q or b
// encoded-text = any printable ASCII character other than ? or space.
// ... but Firefox permits ? and space.
return value.replaceAll(
/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,
function (matches, charset, encoding, text) {
if (encoding === "q" || encoding === "Q") {
// RFC 2047 section 4.2.
text = text.replaceAll("_", " ");
text = text.replaceAll(/=([0-9a-fA-F]{2})/g, function (match, hex) {
return String.fromCharCode(parseInt(hex, 16));
});
return textdecode(charset, text);
} // else encoding is b or B - base64 (RFC 2047 section 4.1)
try {
text = atob(text);
} catch {}
return textdecode(charset, text);
}
);
}
return "";
}
export { getFilenameFromContentDispositionHeader };