View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
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   * Helper to work with data URLs.
36   * @see <a href="http://www.ietf.org/rfc/rfc2397.txt">RFC2397</a>
37   * @author Marc Guillemot
38   * @author Ronald Brill
39   * @author Carsten Steul
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      /** The MIME type of a data url without (valid) MIME type. */
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       * C'tor.
55       * @param data the data
56       * @param mediaType the media type
57       * @param charset the charset
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       * Decodes a data URL providing simple access to the information contained by the URL.
67       * @param url the URL to decode
68       * @return the {@link DataUrlDecoder} holding decoded information
69       * @throws UnsupportedEncodingException if the encoding specified by the data URL is invalid or not
70       */
71      public static DataUrlDecoder decode(final URL url) throws UnsupportedEncodingException {
72          return decodeDataURL(url.toExternalForm());
73      }
74  
75      /**
76       * Decodes a data URL providing simple access to the information contained by the URL.
77       * @param url the string representation of the URL to decode
78       * @return the {@link DataUrlDecoder} holding decoded information
79       * @throws UnsupportedEncodingException if the encoding specified by the data URL is invalid or not
80       *         available on the JVM
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          // ';base64' at the end (case-insensitive, spaces allowed)
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      * Returns the content type like the fetch standard does it for the MIME type part of a data url.
123      *
124      * @param beforeData the part of the url between 'data:' and the comma
125      * @param standardSerialization whether to serialize like the MIME Sniffing Standard
126      *        (see {@link #parseAndSerializeMimeType(String, boolean)}); like Firefox all whitespace
127      *        is removed from base64 data urls (e.g. 'a="b c";base64' is 'a=bc')
128      * @return the serialized MIME type
129      * @see <a href="https://fetch.spec.whatwg.org/#data-url-processor">Fetch Standard - data: URL processor</a>
130      */
131     static String toContentType(final String beforeData, final boolean standardSerialization) {
132         String mimeType = beforeData.strip();
133 
134         // remove ';base64' (case-insensitive, spaces allowed before 'base64')
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             // Firefox removes all whitespace from base64 data urls (also from the MIME type)
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      * Parses the MIME type and serializes it again like Chrome does it for data urls
165      * (see {@link #parseAndSerializeMimeType(String, boolean)}).
166      *
167      * @param input the MIME type
168      * @return the serialized MIME type or {@code null} if the input is not a valid MIME type
169      */
170     static String parseAndSerializeMimeType(final String input) {
171         return parseAndSerializeMimeType(input, false);
172     }
173 
174     /**
175      * Parses the MIME type and serializes it again like the browsers do it for data urls;
176      * type and subtype are lower case, invalid parameters are ignored.
177      * <ul>
178      * <li>With standard serialization (like Firefox) the parameters are parsed and serialized like the
179      * MIME Sniffing Standard does it: the parameter names are lower case, only the first parameter of a
180      * name is used, values are quoted if needed.</li>
181      * <li>Otherwise (like Chrome) the parameters are split at every ';' (also inside quotes), names and
182      * values are kept as they are (no quotes added), duplicates are kept, the first charset parameter is
183      * moved to the end.</li>
184      * </ul>
185      *
186      * @param input the MIME type
187      * @param standardSerialization whether to serialize like the MIME Sniffing Standard
188      * @return the serialized MIME type or {@code null} if the input is not a valid MIME type
189      * @see <a href="https://mimesniff.spec.whatwg.org/#parse-a-mime-type">MIME Sniffing Standard
190      *      - parse a MIME type</a>
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             // skip the ';' and the leading whitespace
227             position++;
228             while (position < length && isHttpWhitespace(mimeType.charAt(position))) {
229                 position++;
230             }
231 
232             // the name
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             // skip the '='
245             position++;
246 
247             // the value
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                 // ignore the rest up to the next ';'
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      * Appends the parameters like Chrome does it for data urls: split at every ';', parameters without
289      * '=' or with whitespace around the '=' are ignored, names and values are kept (a quoted value ends
290      * at the next not escaped quote or at the end of the parameter), the first charset parameter is moved
291      * to the end (without quotes).
292      *
293      * @param result the serialized type and subtype
294      * @param parameters the parameter part of the MIME type (starting with ';' or empty)
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             // whitespace around the '=' makes the parameter invalid ('a = b')
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                 // the raw value (with escapes) up to the closing quote
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      * Gets the media type information contained in the data URL.
420      * @return "text/plain" if the URL didn't contain any media type information
421      */
422     public String getMediaType() {
423         return mediaType_;
424     }
425 
426     /**
427      * Gets the content type of the data URL, serialized like the browsers do it
428      * (e.g. 'text/plain;charset=utf-8' for 'data:text/plain;charset=utf-8,...').
429      * @return the content type; "text/plain;charset=US-ASCII" if the URL didn't contain a valid MIME type
430      */
431     public String getContentType() {
432         if (contentType_ == null) {
433             return mediaType_ + ";charset=" + charset_.name();
434         }
435         return contentType_;
436     }
437 
438     /**
439      * Gets the content type of the data URL, serialized like the browsers do it.
440      * @param standardSerialization whether to serialize like the MIME Sniffing Standard (like Firefox;
441      *        duplicate parameters are ignored) or like Chrome (see {@link #getContentType()})
442      * @return the content type; "text/plain;charset=US-ASCII" if the URL didn't contain a valid MIME type
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      * Gets the charset information specified in the data URL.
453      * @return "US-ASCII" if the URL didn't contain any charset information
454      */
455     public String getCharset() {
456         return charset_.name();
457     }
458 
459     /**
460      * Gets the bytes contained in the data URL.
461      * @return the content
462      */
463     public byte[] getBytes() {
464         return content_;
465     }
466 
467     /**
468      * Gets the text content of the data URL. This makes sense only for data URL that
469      * represents some text.
470      * @return the text content
471      * @throws UnsupportedEncodingException if decoding failed using the specified charset
472      */
473     public String getDataAsString() throws UnsupportedEncodingException {
474         return new String(content_, charset_);
475     }
476 }