1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.httpclient;
16
17 import static org.htmlunit.BrowserVersionFeatures.HTTP_COOKIE_HOST_PREFIX_ALLOWS_DOMAIN_OF_HOST;
18 import static org.htmlunit.BrowserVersionFeatures.HTTP_COOKIE_HOST_PREFIX_PATH_ATTRIBUTE_OPTIONAL;
19
20 import java.util.ArrayList;
21 import java.util.BitSet;
22 import java.util.Calendar;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.Date;
26 import java.util.List;
27 import java.util.Locale;
28
29 import org.apache.http.FormattedHeader;
30 import org.apache.http.Header;
31 import org.apache.http.HeaderElement;
32 import org.apache.http.NameValuePair;
33 import org.apache.http.ParseException;
34 import org.apache.http.client.utils.DateUtils;
35 import org.apache.http.cookie.ClientCookie;
36 import org.apache.http.cookie.Cookie;
37 import org.apache.http.cookie.CookieAttributeHandler;
38 import org.apache.http.cookie.CookieOrigin;
39 import org.apache.http.cookie.CookiePathComparator;
40 import org.apache.http.cookie.CookieRestrictionViolationException;
41 import org.apache.http.cookie.MalformedCookieException;
42 import org.apache.http.cookie.SM;
43 import org.apache.http.impl.cookie.BasicClientCookie;
44 import org.apache.http.impl.cookie.BasicCommentHandler;
45 import org.apache.http.impl.cookie.CookieSpecBase;
46 import org.apache.http.message.BasicHeader;
47 import org.apache.http.message.BasicHeaderElement;
48 import org.apache.http.message.BasicNameValuePair;
49 import org.apache.http.message.BufferedHeader;
50 import org.apache.http.message.ParserCursor;
51 import org.apache.http.message.TokenParser;
52 import org.apache.http.util.CharArrayBuffer;
53 import org.htmlunit.BrowserVersion;
54 import org.htmlunit.util.StringUtils;
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74 public class HtmlUnitBrowserCompatCookieSpec extends CookieSpecBase {
75
76
77 public static final String EMPTY_COOKIE_NAME = "HTMLUNIT_EMPTY_COOKIE";
78
79
80 public static final String LOCAL_FILESYSTEM_DOMAIN = "LOCAL_FILESYSTEM";
81
82 private static final String SECURE_PREFIX = "__Secure-";
83 private static final String HOST_PREFIX = "__Host-";
84
85
86
87
88
89
90
91 private static final Comparator<Cookie> COOKIE_COMPARATOR = new CookiePathComparator();
92
93 private static final NetscapeDraftHeaderParser DEFAULT_NETSCAPE_DRAFT_HEADER_PARSER
94 = new NetscapeDraftHeaderParser();
95
96 static final Date DATE_1_1_1970;
97
98 static {
99 final Calendar calendar = Calendar.getInstance(Locale.ROOT);
100 calendar.setTimeZone(DateUtils.GMT);
101 calendar.set(1970, Calendar.JANUARY, 1, 0, 0, 0);
102 calendar.set(Calendar.MILLISECOND, 0);
103 DATE_1_1_1970 = calendar.getTime();
104 }
105
106 private final BrowserVersion browserVersion_;
107
108
109
110
111
112
113 public HtmlUnitBrowserCompatCookieSpec(final BrowserVersion browserVersion) {
114 super(new HtmlUnitVersionAttributeHandler(),
115 new HtmlUnitDomainHandler(),
116 new HtmlUnitPathHandler(),
117 new HtmlUnitMaxAgeHandler(),
118 new HtmlUnitSecureHandler(),
119 new BasicCommentHandler(),
120 new HtmlUnitExpiresHandler(browserVersion),
121 new HtmlUnitHttpOnlyHandler(),
122 new HtmlUnitSameSiteHandler());
123 browserVersion_ = browserVersion;
124 }
125
126
127
128
129
130
131
132
133 @Override
134 public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException {
135 super.validate(cookie, origin);
136
137 final String name = cookie.getName();
138 if (StringUtils.startsWithIgnoreCase(name, SECURE_PREFIX)) {
139 if (!cookie.isSecure()) {
140 throw new CookieRestrictionViolationException(
141 "Cookie '" + name + "' requires the 'secure' attribute");
142 }
143 }
144 else if (StringUtils.startsWithIgnoreCase(name, HOST_PREFIX)) {
145 validateHostPrefix(cookie, origin);
146 }
147 }
148
149
150
151
152
153
154
155
156 private void validateHostPrefix(final Cookie cookie, final CookieOrigin origin)
157 throws CookieRestrictionViolationException {
158 final String name = cookie.getName();
159 if (!cookie.isSecure()) {
160 throw new CookieRestrictionViolationException(
161 "Cookie '" + name + "' requires the 'secure' attribute");
162 }
163
164 final ClientCookie clientCookie = cookie instanceof ClientCookie cc ? cc : null;
165 if (clientCookie != null && clientCookie.containsAttribute(ClientCookie.DOMAIN_ATTR)) {
166 String domain = cookie.getDomain();
167 if (domain != null && domain.startsWith(".")) {
168 domain = domain.substring(1);
169 }
170 final boolean domainOfHost = domain != null && domain.equalsIgnoreCase(origin.getHost());
171 if (!domainOfHost || !browserVersion_.hasFeature(HTTP_COOKIE_HOST_PREFIX_ALLOWS_DOMAIN_OF_HOST)) {
172 throw new CookieRestrictionViolationException(
173 "Cookie '" + name + "' does not allow the 'domain' attribute");
174 }
175 }
176
177 if (!"/".equals(cookie.getPath())
178 || (!browserVersion_.hasFeature(HTTP_COOKIE_HOST_PREFIX_PATH_ATTRIBUTE_OPTIONAL)
179 && (clientCookie == null || !clientCookie.containsAttribute(ClientCookie.PATH_ATTR)))) {
180 throw new CookieRestrictionViolationException(
181 "Cookie '" + name + "' requires the 'path' attribute '/'");
182 }
183 }
184
185
186
187
188
189
190
191 private static Header supportEmptyCookieName(final Header header) {
192 final String text = header.getValue();
193 int endPos = text.indexOf(';');
194 if (endPos < 0) {
195 endPos = text.indexOf('=');
196 }
197 else {
198 final int pos = text.indexOf('=');
199 if (pos > endPos) {
200 endPos = -1;
201 }
202 else {
203 endPos = pos;
204 }
205 }
206 if (endPos < 0) {
207 return new BasicHeader(header.getName(), EMPTY_COOKIE_NAME + "=" + header.getValue());
208 }
209 if (endPos == 0 || StringUtils.isBlank(text.substring(0, endPos))) {
210 return new BasicHeader(header.getName(), EMPTY_COOKIE_NAME + header.getValue());
211 }
212 return header;
213 }
214
215
216
217
218 @Override
219 public List<Cookie> parse(final Header rawHeader, final CookieOrigin origin) throws MalformedCookieException {
220 final Header header = supportEmptyCookieName(rawHeader);
221
222 final String headername = header.getName();
223 if (!SM.SET_COOKIE.equalsIgnoreCase(headername)) {
224 throw new MalformedCookieException("Unrecognized cookie header '" + header + "'");
225 }
226 final HeaderElement[] helems = header.getElements();
227 boolean versioned = false;
228 boolean netscape = false;
229 for (final HeaderElement helem: helems) {
230 if (helem.getParameterByName("version") != null) {
231 versioned = true;
232 }
233 if (helem.getParameterByName("expires") != null) {
234 netscape = true;
235 }
236 }
237
238 final List<Cookie> cookies;
239 if (netscape || !versioned) {
240
241
242 final CharArrayBuffer buffer;
243 final ParserCursor cursor;
244 if (header instanceof FormattedHeader formattedHeader) {
245 buffer = formattedHeader.getBuffer();
246 cursor = new ParserCursor(
247 formattedHeader.getValuePos(),
248 buffer.length());
249 }
250 else {
251 final String s = header.getValue();
252 if (s == null) {
253 throw new MalformedCookieException("Header value is null");
254 }
255 buffer = new CharArrayBuffer(s.length());
256 buffer.append(s);
257 cursor = new ParserCursor(0, buffer.length());
258 }
259 final HeaderElement elem = DEFAULT_NETSCAPE_DRAFT_HEADER_PARSER.parseHeader(buffer, cursor);
260 final String name = elem.getName();
261 if (name == null || name.isEmpty()) {
262 throw new MalformedCookieException("Cookie name may not be empty");
263 }
264 final String value = elem.getValue();
265 final BasicClientCookie cookie = new BasicClientCookie(name, value);
266
267 cookie.setCreationDate(new Date());
268 cookie.setPath(getDefaultPath(origin));
269 cookie.setDomain(getDefaultDomain(origin));
270
271
272 final NameValuePair[] attribs = elem.getParameters();
273 for (int j = attribs.length - 1; j >= 0; j--) {
274 final NameValuePair attrib = attribs[j];
275 final String s = attrib.getName().toLowerCase(Locale.ROOT);
276 cookie.setAttribute(s, attrib.getValue());
277 final CookieAttributeHandler handler = findAttribHandler(s);
278 if (handler != null) {
279 handler.parse(cookie, attrib.getValue());
280 }
281 }
282
283 if (netscape) {
284 cookie.setVersion(0);
285 }
286 cookies = Collections.singletonList(cookie);
287 }
288 else {
289 cookies = parse(helems, origin);
290 }
291
292 for (final Cookie c : cookies) {
293
294 if (header.getValue().contains(c.getName() + "=\"" + c.getValue())) {
295 ((BasicClientCookie) c).setValue('"' + c.getValue() + '"');
296 }
297 }
298 return cookies;
299 }
300
301 @Override
302 public List<Header> formatCookies(final List<Cookie> cookies) {
303 cookies.sort(COOKIE_COMPARATOR);
304
305 final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
306 buffer.append(SM.COOKIE);
307 buffer.append(": ");
308 final int size = cookies.size();
309 for (int i = 0; i < size; i++) {
310 final Cookie cookie = cookies.get(i);
311 if (i > 0) {
312 buffer.append("; ");
313 }
314 final String cookieName = cookie.getName();
315 final String cookieValue = cookie.getValue();
316 if (cookie.getVersion() > 0 && !isQuoteEnclosed(cookieValue)) {
317 HtmlUnitBrowserCompatCookieHeaderValueFormatter.INSTANCE.formatHeaderElement(
318 buffer,
319 new BasicHeaderElement(cookieName, cookieValue),
320 false);
321 }
322 else {
323
324 buffer.append(cookieName);
325 buffer.append("=");
326 if (cookieValue != null) {
327 buffer.append(cookieValue);
328 }
329 }
330 }
331 final List<Header> headers = new ArrayList<>(1);
332 headers.add(new BufferedHeader(buffer));
333 return headers;
334 }
335
336 private static boolean isQuoteEnclosed(final String s) {
337 return s != null
338 && s.length() > 1
339 && '\"' == s.charAt(0)
340 && '\"' == s.charAt(s.length() - 1);
341 }
342
343 @Override
344 public int getVersion() {
345 return 0;
346 }
347
348 @Override
349 public Header getVersionHeader() {
350 return null;
351 }
352
353 @Override
354 public String toString() {
355 return "compatibility";
356 }
357
358 private static final class NetscapeDraftHeaderParser {
359
360 private static final char PARAM_DELIMITER = ';';
361
362
363
364 private static final BitSet TOKEN_DELIMS = TokenParser.INIT_BITSET('=', PARAM_DELIMITER);
365 private static final BitSet VALUE_DELIMS = TokenParser.INIT_BITSET(PARAM_DELIMITER);
366
367 private static final TokenParser TOKEN_PARSER = TokenParser.INSTANCE;
368
369 HeaderElement parseHeader(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException {
370 final NameValuePair nvp = parseNameValuePair(buffer, cursor);
371 final List<NameValuePair> params = new ArrayList<>();
372 while (!cursor.atEnd()) {
373 final NameValuePair param = parseNameValuePair(buffer, cursor);
374 params.add(param);
375 }
376
377 return new BasicHeaderElement(nvp.getName(), nvp.getValue(),
378 params.toArray(new NameValuePair[0]));
379 }
380
381 private NameValuePair parseNameValuePair(final CharArrayBuffer buffer, final ParserCursor cursor) {
382 final String name = TOKEN_PARSER.parseToken(buffer, cursor, TOKEN_DELIMS);
383 if (cursor.atEnd()) {
384 return new BasicNameValuePair(name, null);
385 }
386
387 final int delim = buffer.charAt(cursor.getPos());
388 cursor.updatePos(cursor.getPos() + 1);
389 if (delim != '=') {
390 return new BasicNameValuePair(name, null);
391 }
392
393 final String value = TOKEN_PARSER.parseToken(buffer, cursor, VALUE_DELIMS);
394 if (!cursor.atEnd()) {
395 cursor.updatePos(cursor.getPos() + 1);
396 }
397
398 return new BasicNameValuePair(name, value);
399 }
400 }
401 }