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.http;
16  
17  import java.io.ByteArrayOutputStream;
18  import java.nio.charset.Charset;
19  import java.nio.charset.StandardCharsets;
20  import java.util.LinkedHashMap;
21  import java.util.Locale;
22  import java.util.Map;
23  
24  /**
25   * Parser for the {@code Content-Disposition} header.
26   * <ul>
27   * <li>RFC 6266 (HTTP) and RFC 2183 (disposition type and parameters)</li>
28   * <li>RFC 8187 extended parameters ({@code filename*=UTF-8''...}); supported charsets are
29   * UTF-8 and ISO-8859-1</li>
30   * </ul>
31   *
32   * <p>The parser is lenient like the browsers are: parameter names are case-insensitive,
33   * white space around names and values is ignored, an unterminated quoted string
34   * ends at the end of the header. An extended value with a broken percent encoding is ignored
35   * (like Firefox does), so the plain parameter can be used as fallback.</p>
36   *
37   * @author Ronald Brill
38   */
39  public final class ContentDispositionParser {
40  
41      /**
42       * Utility class, not intended to be instantiated.
43       */
44      private ContentDispositionParser() {
45          // Utility class
46      }
47  
48      /**
49       * Parses the value of a {@code Content-Disposition} header.
50       *
51       * @param header the header value
52       * @return the parsed header or {@code null} if the given value is {@code null}
53       */
54      public static ContentDisposition parse(final String header) {
55          if (header == null) {
56              return null;
57          }
58  
59          final Map<String, String> parameters = new LinkedHashMap<>();
60          final Map<String, String> extendedParameters = new LinkedHashMap<>();
61  
62          final int length = header.length();
63          int pos = header.indexOf(';');
64          final String type = (pos < 0 ? header : header.substring(0, pos)).trim().toLowerCase(Locale.ROOT);
65  
66          while (pos >= 0 && pos < length) {
67              pos++; // skip ';'
68  
69              // name
70              while (pos < length && Character.isWhitespace(header.charAt(pos))) {
71                  pos++;
72              }
73              final int nameStart = pos;
74              while (pos < length && header.charAt(pos) != '=' && header.charAt(pos) != ';') {
75                  pos++;
76              }
77              String name = header.substring(nameStart, pos).trim().toLowerCase(Locale.ROOT);
78  
79              // value
80              String value = "";
81              if (pos < length && header.charAt(pos) == '=') {
82                  pos++;
83                  while (pos < length && Character.isWhitespace(header.charAt(pos))) {
84                      pos++;
85                  }
86                  if (pos < length && header.charAt(pos) == '"') {
87                      // quoted string; a backslash escapes the next character
88                      final StringBuilder sb = new StringBuilder();
89                      pos++;
90                      while (pos < length && header.charAt(pos) != '"') {
91                          if (header.charAt(pos) == '\\' && pos + 1 < length) {
92                              pos++;
93                          }
94                          sb.append(header.charAt(pos));
95                          pos++;
96                      }
97                      if (pos < length) {
98                          pos++; // closing quote
99                      }
100                     // ignore everything up to the next ';'
101                     while (pos < length && header.charAt(pos) != ';') {
102                         pos++;
103                     }
104                     value = sb.toString();
105                 }
106                 else {
107                     final int valueStart = pos;
108                     while (pos < length && header.charAt(pos) != ';') {
109                         pos++;
110                     }
111                     value = header.substring(valueStart, pos).trim();
112                 }
113             }
114 
115             if (!name.isEmpty()) {
116                 if (name.endsWith("*")) {
117                     name = name.substring(0, name.length() - 1);
118                     if (!name.isEmpty() && !extendedParameters.containsKey(name)) {
119                         final String decoded = decodeExtendedValue(value);
120                         if (decoded != null) {
121                             extendedParameters.put(name, decoded);
122                         }
123                     }
124                 }
125                 else if (!parameters.containsKey(name)) {
126                     parameters.put(name, value);
127                 }
128             }
129 
130             pos = header.indexOf(';', pos);
131         }
132 
133         return new ContentDisposition(type, parameters, extendedParameters);
134     }
135 
136     /**
137      * Decodes a RFC 8187 value (charset'language'percent-encoded).
138      *
139      * @param value the raw value of the extended parameter
140      * @return the decoded value or {@code null} if the format is wrong, the charset is not supported
141      *         or the percent encoding is invalid
142      */
143     private static String decodeExtendedValue(final String value) {
144         final int first = value.indexOf('\'');
145         final int second = first < 0 ? -1 : value.indexOf('\'', first + 1);
146         if (second < 0) {
147             return null;
148         }
149 
150         final String charsetName = value.substring(0, first).trim();
151         final Charset charset;
152         if ("UTF-8".equalsIgnoreCase(charsetName)) {
153             charset = StandardCharsets.UTF_8;
154         }
155         else if ("ISO-8859-1".equalsIgnoreCase(charsetName)) {
156             charset = StandardCharsets.ISO_8859_1;
157         }
158         else {
159             return null;
160         }
161 
162         final String encoded = value.substring(second + 1);
163         final ByteArrayOutputStream out = new ByteArrayOutputStream();
164         for (int i = 0; i < encoded.length(); i++) {
165             final char c = encoded.charAt(i);
166             if (c == '%' && i + 2 < encoded.length() && isHex(encoded.charAt(i + 1))
167                     && isHex(encoded.charAt(i + 2))) {
168                 out.write((Character.digit(encoded.charAt(i + 1), 16) << 4)
169                         | Character.digit(encoded.charAt(i + 2), 16));
170                 i += 2;
171             }
172             else if (c == '%') {
173                 // invalid percent encoding; ignore the whole value
174                 return null;
175             }
176             else {
177                 final byte[] bytes = String.valueOf(c).getBytes(charset);
178                 out.write(bytes, 0, bytes.length);
179             }
180         }
181         return new String(out.toByteArray(), charset);
182     }
183 
184     /**
185      * Checks for a hexadecimal digit (ASCII only).
186      *
187      * @param c the character to check
188      * @return {@code true} if the character is a hexadecimal digit
189      */
190     private static boolean isHex(final char c) {
191         return c < 128 && Character.digit(c, 16) >= 0;
192     }
193 }