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.httpclient;
16  
17  import java.util.Locale;
18  
19  import org.apache.http.conn.util.InetAddressUtils;
20  import org.apache.http.conn.util.PublicSuffixMatcher;
21  import org.apache.http.cookie.ClientCookie;
22  import org.apache.http.cookie.Cookie;
23  import org.apache.http.cookie.CookieOrigin;
24  import org.apache.http.cookie.CookieRestrictionViolationException;
25  import org.apache.http.cookie.MalformedCookieException;
26  import org.apache.http.cookie.SetCookie;
27  import org.apache.http.impl.cookie.BasicClientCookie;
28  import org.apache.http.impl.cookie.BasicDomainHandler;
29  import org.apache.http.util.Args;
30  import org.apache.http.util.TextUtils;
31  import org.htmlunit.HttpHeader;
32  
33  /**
34   * Customized BasicDomainHandler for HtmlUnit.
35   *
36   * @author Ronald Brill
37   * @author Ahmed Ashour
38   * @author Vidya m
39   */
40  final class HtmlUnitDomainHandler extends BasicDomainHandler {
41      private static final PublicSuffixMatcher PUBLIC_SUFFIX_MATCHER = HttpClientConverter.getPublicSuffixMatcher();
42  
43      HtmlUnitDomainHandler() {
44          super();
45      }
46  
47      @Override
48      public void parse(final SetCookie cookie, final String value)
49              throws MalformedCookieException {
50          Args.notNull(cookie, HttpHeader.COOKIE);
51          if (TextUtils.isBlank(value)) {
52              throw new MalformedCookieException("Blank or null value for domain attribute");
53          }
54          // Ignore domain attributes ending with '.' per RFC 6265, 4.1.2.3
55          if (value.endsWith(".")) {
56              return;
57          }
58          String domain = value.toLowerCase(Locale.ROOT);
59  
60          final int dotIndex = domain.indexOf('.');
61          if (dotIndex == 0 && domain.length() > 1 && domain.indexOf('.', 1) == -1) {
62              // like the browsers, a single label domain is stored without the leading dot
63              // ('.intranet' is handled as 'intranet')
64              domain = domain.substring(1);
65          }
66          if (dotIndex > 0) {
67              domain = '.' + domain;
68          }
69  
70          cookie.setDomain(domain);
71      }
72  
73      /**
74       * {@inheritDoc}
75       * Like the browsers, cookies for a public suffix (e.g. 'co.uk')
76       * are rejected unless the domain is the host itself (RFC 6265 section 5.3, step 5).
77       */
78      @Override
79      public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException {
80          // like the browsers, a domain attribute with the ip address of the host is accepted;
81          // the cookie is a host-only cookie (no other host can match an ip address)
82          final String host = origin.getHost();
83          if (isIpAddress(host) && cookie instanceof BasicClientCookie clientCookie
84                  && clientCookie.containsAttribute(ClientCookie.DOMAIN_ATTR)) {
85              final String cookieDomain = cookie.getDomain();
86              if (cookieDomain != null
87                      && host.equalsIgnoreCase(cookieDomain.startsWith(".") ? cookieDomain.substring(1) : cookieDomain)) {
88                  clientCookie.setDomain(host);
89                  clientCookie.removeAttribute(ClientCookie.DOMAIN_ATTR);
90              }
91          }
92  
93          super.validate(cookie, origin);
94  
95          final String domain = cookie.getDomain();
96          final String normalizedDomain = domain.startsWith(".") ? domain.substring(1) : domain;
97          // top level domains (e.g. 'com') are public suffixes also; single label names
98          // not on the list (e.g. 'localhost', 'intranet') are no public suffixes
99          if (!normalizedDomain.equalsIgnoreCase(origin.getHost())
100                 && PUBLIC_SUFFIX_MATCHER.matches(normalizedDomain)) {
101             throw new CookieRestrictionViolationException("Illegal 'domain' attribute \"" + domain
102                     + "\"; cookies for a public suffix are not allowed");
103         }
104     }
105 
106     /**
107      * {@inheritDoc}
108      */
109     @Override
110     public boolean match(final Cookie cookie, final CookieOrigin origin) {
111         final String domain = cookie.getDomain();
112         if (domain == null) {
113             return false;
114         }
115 
116         final int dotIndex = domain.indexOf('.');
117         if (dotIndex == 0 && domain.length() > 1 && domain.indexOf('.', 1) == -1) {
118             // single label domain with leading dot (e.g. '.intranet', only possible for cookies
119             // added by the api); like the browsers the cookie matches the host itself
120             return origin.getHost().equalsIgnoreCase(domain.substring(1));
121         }
122 
123         // cookies for a public suffix (e.g. 'com') are rejected by validate() already; this check
124         // is for cookies added by the api. Single label names that are no public suffix
125         // (e.g. 'localhost', 'intranet') match like any other domain - without name resolution.
126         final String normalizedDomain = dotIndex == 0 ? domain.substring(1) : domain;
127         if (!normalizedDomain.equalsIgnoreCase(origin.getHost())
128                 && !HtmlUnitBrowserCompatCookieSpec.LOCAL_FILESYSTEM_DOMAIN.equalsIgnoreCase(normalizedDomain)
129                 && PUBLIC_SUFFIX_MATCHER.matches(normalizedDomain)) {
130             return false;
131         }
132 
133         return super.match(cookie, origin);
134     }
135 
136     private static boolean isIpAddress(final String host) {
137         String h = host;
138         if (h.startsWith("[") && h.endsWith("]")) {
139             h = h.substring(1, h.length() - 1);
140         }
141         return InetAddressUtils.isIPv4Address(h) || InetAddressUtils.isIPv6Address(h);
142     }
143 }