|
15 | 15 | package org.htmlunit.httpclient; |
16 | 16 |
|
17 | 17 | import java.util.Date; |
| 18 | +import java.util.regex.Pattern; |
18 | 19 |
|
19 | 20 | import org.apache.http.cookie.MalformedCookieException; |
20 | 21 | import org.apache.http.cookie.SetCookie; |
|
25 | 26 | * Customized BasicMaxAgeHandler for HtmlUnit. |
26 | 27 | * |
27 | 28 | * @author Ronald Brill |
| 29 | + * @author Lai Quang Duong |
28 | 30 | */ |
29 | 31 | final class HtmlUnitMaxAgeHandler extends BasicMaxAgeHandler { |
30 | 32 |
|
| 33 | + // Max-Age should be 400 days at most |
| 34 | + // https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html#section-5.5 |
| 35 | + private static final int MAX_MAX_AGE = 400 * 24 * 60 * 60; |
| 36 | + |
| 37 | + private static final Pattern MAX_AGE_PATTERN = Pattern.compile("-?[0-9]+"); |
| 38 | + |
31 | 39 | @Override |
32 | 40 | public void parse(final SetCookie cookie, final String value) |
33 | 41 | throws MalformedCookieException { |
34 | 42 | Args.notNull(cookie, "Cookie"); |
35 | | - if (value == null) { |
| 43 | + if (value == null || value.isEmpty()) { |
36 | 44 | throw new MalformedCookieException("Missing value for 'max-age' attribute"); |
37 | 45 | } |
38 | | - final int age; |
| 46 | + if (!MAX_AGE_PATTERN.matcher(value).matches()) { |
| 47 | + throw new MalformedCookieException("Invalid 'max-age' attribute: " + value); |
| 48 | + } |
| 49 | + if (value.startsWith("-")) { |
| 50 | + cookie.setExpiryDate(new Date(0L)); |
| 51 | + return; |
| 52 | + } |
| 53 | + int age; |
39 | 54 | try { |
40 | | - age = Integer.parseInt(value); |
| 55 | + age = Math.min(Integer.parseInt(value), MAX_MAX_AGE); |
41 | 56 | } |
42 | 57 | catch (final NumberFormatException e) { |
43 | | - throw new MalformedCookieException("Invalid 'max-age' attribute: " + value, e); |
| 58 | + age = MAX_MAX_AGE; |
44 | 59 | } |
45 | 60 | cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L)); |
46 | 61 | } |
|
0 commit comments