1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.protocol.data;
16
17 import static java.nio.charset.StandardCharsets.US_ASCII;
18 import static org.htmlunit.protocol.data.DataURLConnection.DATA_PREFIX;
19
20 import java.io.UnsupportedEncodingException;
21 import java.net.URL;
22 import java.nio.charset.Charset;
23 import java.nio.charset.IllegalCharsetNameException;
24 import java.nio.charset.UnsupportedCharsetException;
25 import java.util.Base64;
26 import java.util.HashSet;
27 import java.util.Locale;
28 import java.util.Set;
29
30 import org.htmlunit.util.MimeType;
31 import org.htmlunit.util.StringUtils;
32 import org.htmlunit.util.UrlUtils;
33
34
35
36
37
38
39
40
41 public class DataUrlDecoder {
42 private static final Charset DEFAULT_CHARSET = US_ASCII;
43 private static final String DEFAULT_MEDIA_TYPE = MimeType.TEXT_PLAIN;
44
45 private static final String DEFAULT_CONTENT_TYPE = "text/plain;charset=US-ASCII";
46
47 private final String mediaType_;
48 private final Charset charset_;
49 private final byte[] content_;
50 private String contentType_;
51 private String beforeData_;
52
53
54
55
56
57
58
59 protected DataUrlDecoder(final byte[] data, final String mediaType, final Charset charset) {
60 content_ = data;
61 mediaType_ = mediaType;
62 charset_ = charset;
63 }
64
65
66
67
68
69
70
71 public static DataUrlDecoder decode(final URL url) throws UnsupportedEncodingException {
72 return decodeDataURL(url.toExternalForm());
73 }
74
75
76
77
78
79
80
81
82 public static DataUrlDecoder decodeDataURL(final String url) throws UnsupportedEncodingException {
83 if (!url.startsWith(DATA_PREFIX)) {
84 throw new UnsupportedEncodingException("Invalid data url: '" + url + "' (wrong prefix)");
85 }
86 final int comma = url.indexOf(',');
87 if (comma < 0) {
88 throw new UnsupportedEncodingException("Invalid data url: '" + url + "' (no data)");
89 }
90
91 String beforeData = url.substring(DATA_PREFIX.length(), comma);
92
93 final int lastSemicolon = beforeData.lastIndexOf(';');
94 final boolean base64 = lastSemicolon > -1
95 && "base64".equalsIgnoreCase(beforeData.substring(lastSemicolon + 1).strip());
96 if (base64) {
97 beforeData = beforeData.substring(0, lastSemicolon);
98 }
99 final String mediaType = extractMediaType(beforeData);
100 final Charset charset = extractCharset(beforeData);
101
102 try {
103 byte[] data = url.substring(comma + 1).getBytes(charset);
104 data = UrlUtils.decodeDataUrl(data, base64);
105 if (base64) {
106 data = Base64.getDecoder().decode(data);
107 }
108 final DataUrlDecoder decoder = new DataUrlDecoder(data, mediaType, charset);
109 decoder.beforeData_ = url.substring(DATA_PREFIX.length(), comma);
110 decoder.contentType_ = toContentType(decoder.beforeData_, false);
111 return decoder;
112 }
113 catch (final IllegalArgumentException e) {
114 final UnsupportedEncodingException ex =
115 new UnsupportedEncodingException("Invalid data url: '" + url + "' (data decoding failed)");
116 ex.initCause(e);
117 throw ex;
118 }
119 }
120
121
122
123
124
125
126
127
128
129
130
131 static String toContentType(final String beforeData, final boolean standardSerialization) {
132 String mimeType = beforeData.strip();
133
134
135 final int semicolon = mimeType.lastIndexOf(';');
136 if (semicolon > -1 && "base64".equalsIgnoreCase(mimeType.substring(semicolon + 1).stripLeading())) {
137 mimeType = mimeType.substring(0, semicolon);
138
139
140 if (standardSerialization) {
141 final StringBuilder withoutWhitespace = new StringBuilder(mimeType.length());
142 for (int i = 0; i < mimeType.length(); i++) {
143 final char c = mimeType.charAt(i);
144 if (!isHttpWhitespace(c)) {
145 withoutWhitespace.append(c);
146 }
147 }
148 mimeType = withoutWhitespace.toString();
149 }
150 }
151
152 if (mimeType.startsWith(";")) {
153 mimeType = MimeType.TEXT_PLAIN + mimeType;
154 }
155
156 final String serialized = parseAndSerializeMimeType(mimeType, standardSerialization);
157 if (serialized == null) {
158 return DEFAULT_CONTENT_TYPE;
159 }
160 return serialized;
161 }
162
163
164
165
166
167
168
169
170 static String parseAndSerializeMimeType(final String input) {
171 return parseAndSerializeMimeType(input, false);
172 }
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192 static String parseAndSerializeMimeType(final String input, final boolean standardSerialization) {
193 final String mimeType = stripHttpWhitespace(input);
194
195 final int slash = mimeType.indexOf('/');
196 if (slash < 1) {
197 return null;
198 }
199 final String type = mimeType.substring(0, slash);
200 if (!isToken(type)) {
201 return null;
202 }
203
204 int position = mimeType.indexOf(';', slash + 1);
205 if (position < 0) {
206 position = mimeType.length();
207 }
208 final String subtype = stripHttpWhitespace(mimeType.substring(slash + 1, position));
209 if (subtype.isEmpty() || !isToken(subtype)) {
210 return null;
211 }
212
213 final StringBuilder result = new StringBuilder()
214 .append(type.toLowerCase(Locale.ROOT))
215 .append('/')
216 .append(subtype.toLowerCase(Locale.ROOT));
217
218 if (!standardSerialization) {
219 appendParametersLikeChrome(result, mimeType.substring(position));
220 return result.toString();
221 }
222
223 final Set<String> names = new HashSet<>();
224 final int length = mimeType.length();
225 while (position < length) {
226
227 position++;
228 while (position < length && isHttpWhitespace(mimeType.charAt(position))) {
229 position++;
230 }
231
232
233 final int nameStart = position;
234 while (position < length && mimeType.charAt(position) != ';' && mimeType.charAt(position) != '=') {
235 position++;
236 }
237 final String name = mimeType.substring(nameStart, position).toLowerCase(Locale.ROOT);
238 if (position >= length) {
239 break;
240 }
241 if (mimeType.charAt(position) == ';') {
242 continue;
243 }
244
245 position++;
246
247
248 final String value;
249 if (position < length && mimeType.charAt(position) == '"') {
250 final StringBuilder quoted = new StringBuilder();
251 position++;
252 while (position < length && mimeType.charAt(position) != '"') {
253 char c = mimeType.charAt(position);
254 if (c == '\\' && position + 1 < length) {
255 position++;
256 c = mimeType.charAt(position);
257 }
258 quoted.append(c);
259 position++;
260 }
261 value = quoted.toString();
262
263 while (position < length && mimeType.charAt(position) != ';') {
264 position++;
265 }
266 }
267 else {
268 final int valueStart = position;
269 while (position < length && mimeType.charAt(position) != ';') {
270 position++;
271 }
272 value = stripHttpWhitespace(mimeType.substring(valueStart, position));
273 if (value.isEmpty()) {
274 continue;
275 }
276 }
277
278 if (!name.isEmpty() && isToken(name) && isQuotedStringContent(value)) {
279 if (names.add(name)) {
280 result.append(';').append(name).append('=').append(serializeParameterValue(value));
281 }
282 }
283 }
284 return result.toString();
285 }
286
287
288
289
290
291
292
293
294
295
296 private static void appendParametersLikeChrome(final StringBuilder result, final String parameters) {
297 String charset = null;
298 for (final String part : parameters.split(";", -1)) {
299 final String parameter = stripHttpWhitespace(part);
300 final int equals = parameter.indexOf('=');
301 if (equals < 1) {
302 continue;
303 }
304 final String name = parameter.substring(0, equals);
305
306 if (isHttpWhitespace(name.charAt(name.length() - 1))
307 || equals + 1 < parameter.length() && isHttpWhitespace(parameter.charAt(equals + 1))) {
308 continue;
309 }
310 String value = parameter.substring(equals + 1);
311 if (!isQuotedStringContent(value)) {
312 continue;
313 }
314 String unquoted = value;
315 if (value.startsWith("\"")) {
316 final StringBuilder content = new StringBuilder();
317 int i = 1;
318 while (i < value.length() && value.charAt(i) != '"') {
319 if (value.charAt(i) == '\\' && i + 1 < value.length()) {
320 i++;
321 }
322 content.append(value.charAt(i));
323 i++;
324 }
325 unquoted = content.toString();
326
327 value = i < value.length() ? value.substring(0, i + 1) : value + '"';
328 }
329
330 if ("charset".equalsIgnoreCase(name)) {
331 if (charset == null && !unquoted.isEmpty()) {
332 charset = unquoted;
333 }
334 continue;
335 }
336 result.append(';').append(name).append('=').append(value);
337 }
338
339 if (charset != null) {
340 result.append(";charset=").append(charset);
341 }
342 }
343
344 private static String serializeParameterValue(final String value) {
345 if (!value.isEmpty() && isToken(value)) {
346 return value;
347 }
348 return '"' + value.replace("\\", "\\\\").replace("\"", "\\\"") + '"';
349 }
350
351 private static boolean isHttpWhitespace(final char c) {
352 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
353 }
354
355 private static String stripHttpWhitespace(final String value) {
356 int start = 0;
357 int end = value.length();
358 while (start < end && isHttpWhitespace(value.charAt(start))) {
359 start++;
360 }
361 while (end > start && isHttpWhitespace(value.charAt(end - 1))) {
362 end--;
363 }
364 return value.substring(start, end);
365 }
366
367 private static boolean isToken(final String value) {
368 if (value.isEmpty()) {
369 return false;
370 }
371 for (int i = 0; i < value.length(); i++) {
372 final char c = value.charAt(i);
373 if (!(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9'
374 || "!#$%&'*+-.^_`|~".indexOf(c) > -1)) {
375 return false;
376 }
377 }
378 return true;
379 }
380
381 private static boolean isQuotedStringContent(final String value) {
382 for (int i = 0; i < value.length(); i++) {
383 final char c = value.charAt(i);
384 if (c != '\t' && (c < 0x20 || c == 0x7F || c > 0xFF)) {
385 return false;
386 }
387 }
388 return true;
389 }
390
391 private static Charset extractCharset(final String beforeData) {
392 if (beforeData.contains(";")) {
393 String charsetName = StringUtils.substringAfter(beforeData, ";");
394 charsetName = charsetName.trim();
395 if (charsetName.startsWith("charset=")) {
396 charsetName = charsetName.substring(8);
397 }
398 try {
399 return Charset.forName(charsetName);
400 }
401 catch (final UnsupportedCharsetException | IllegalCharsetNameException e) {
402 return DEFAULT_CHARSET;
403 }
404 }
405 return DEFAULT_CHARSET;
406 }
407
408 private static String extractMediaType(final String beforeData) {
409 if (beforeData.contains("/")) {
410 if (beforeData.contains(";")) {
411 return StringUtils.substringBefore(beforeData, ";");
412 }
413 return beforeData;
414 }
415 return DEFAULT_MEDIA_TYPE;
416 }
417
418
419
420
421
422 public String getMediaType() {
423 return mediaType_;
424 }
425
426
427
428
429
430
431 public String getContentType() {
432 if (contentType_ == null) {
433 return mediaType_ + ";charset=" + charset_.name();
434 }
435 return contentType_;
436 }
437
438
439
440
441
442
443
444 public String getContentType(final boolean standardSerialization) {
445 if (!standardSerialization || beforeData_ == null) {
446 return getContentType();
447 }
448 return toContentType(beforeData_, true);
449 }
450
451
452
453
454
455 public String getCharset() {
456 return charset_.name();
457 }
458
459
460
461
462
463 public byte[] getBytes() {
464 return content_;
465 }
466
467
468
469
470
471
472
473 public String getDataAsString() throws UnsupportedEncodingException {
474 return new String(content_, charset_);
475 }
476 }