View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.impl.cookie;
29  
30  import java.util.Locale;
31  
32  import org.apache.http.annotation.Immutable;
33  import org.apache.http.cookie.ClientCookie;
34  import org.apache.http.cookie.CommonCookieAttributeHandler;
35  import org.apache.http.cookie.Cookie;
36  import org.apache.http.cookie.CookieOrigin;
37  import org.apache.http.cookie.CookieRestrictionViolationException;
38  import org.apache.http.cookie.MalformedCookieException;
39  import org.apache.http.cookie.SetCookie;
40  import org.apache.http.util.Args;
41  
42  /**
43   * {@code "Domain"} cookie attribute handler for RFC 2965 cookie spec.
44   *
45   *
46   * @since 3.1
47   */
48  @Immutable
49  public class RFC2965DomainAttributeHandler implements CommonCookieAttributeHandler {
50  
51      public RFC2965DomainAttributeHandler() {
52          super();
53      }
54  
55      /**
56       * Parse cookie domain attribute.
57       */
58      @Override
59      public void parse(
60              final SetCookie cookie, final String domain) throws MalformedCookieException {
61          Args.notNull(cookie, "Cookie");
62          if (domain == null) {
63              throw new MalformedCookieException(
64                      "Missing value for domain attribute");
65          }
66          if (domain.trim().isEmpty()) {
67              throw new MalformedCookieException(
68                      "Blank value for domain attribute");
69          }
70          String s = domain;
71          s = s.toLowerCase(Locale.ROOT);
72          if (!domain.startsWith(".")) {
73              // Per RFC 2965 section 3.2.2
74              // "... If an explicitly specified value does not start with
75              // a dot, the user agent supplies a leading dot ..."
76              // That effectively implies that the domain attribute
77              // MAY NOT be an IP address of a host name
78              s = '.' + s;
79          }
80          cookie.setDomain(s);
81      }
82  
83      /**
84       * Performs domain-match as defined by the RFC2965.
85       * <p>
86       * Host A's name domain-matches host B's if
87       * </p>
88       * <ol>
89       *   <li>their host name strings string-compare equal; or</li>
90       *   <li>A is a HDN string and has the form NB, where N is a non-empty
91       *       name string, B has the form .B', and B' is a HDN string.  (So,
92       *       x.y.com domain-matches .Y.com but not Y.com.)</li>
93       * </ol>
94       *
95       * @param host host name where cookie is received from or being sent to.
96       * @param domain The cookie domain attribute.
97       * @return true if the specified host matches the given domain.
98       */
99      public boolean domainMatch(final String host, final String domain) {
100         final boolean match = host.equals(domain)
101                         || (domain.startsWith(".") && host.endsWith(domain));
102 
103         return match;
104     }
105 
106     /**
107      * Validate cookie domain attribute.
108      */
109     @Override
110     public void validate(final Cookie cookie, final CookieOrigin origin)
111             throws MalformedCookieException {
112         Args.notNull(cookie, "Cookie");
113         Args.notNull(origin, "Cookie origin");
114         final String host = origin.getHost().toLowerCase(Locale.ROOT);
115         if (cookie.getDomain() == null) {
116             throw new CookieRestrictionViolationException("Invalid cookie state: " +
117                                                "domain not specified");
118         }
119         final String cookieDomain = cookie.getDomain().toLowerCase(Locale.ROOT);
120 
121         if (cookie instanceof ClientCookie
122                 && ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) {
123             // Domain attribute must start with a dot
124             if (!cookieDomain.startsWith(".")) {
125                 throw new CookieRestrictionViolationException("Domain attribute \"" +
126                     cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot");
127             }
128 
129             // Domain attribute must contain at least one embedded dot,
130             // or the value must be equal to .local.
131             final int dotIndex = cookieDomain.indexOf('.', 1);
132             if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1))
133                 && (!cookieDomain.equals(".local"))) {
134                 throw new CookieRestrictionViolationException(
135                         "Domain attribute \"" + cookie.getDomain()
136                         + "\" violates RFC 2965: the value contains no embedded dots "
137                         + "and the value is not .local");
138             }
139 
140             // The effective host name must domain-match domain attribute.
141             if (!domainMatch(host, cookieDomain)) {
142                 throw new CookieRestrictionViolationException(
143                         "Domain attribute \"" + cookie.getDomain()
144                         + "\" violates RFC 2965: effective host name does not "
145                         + "domain-match domain attribute.");
146             }
147 
148             // effective host name minus domain must not contain any dots
149             final String effectiveHostWithoutDomain = host.substring(
150                     0, host.length() - cookieDomain.length());
151             if (effectiveHostWithoutDomain.indexOf('.') != -1) {
152                 throw new CookieRestrictionViolationException("Domain attribute \""
153                                                    + cookie.getDomain() + "\" violates RFC 2965: "
154                                                    + "effective host minus domain may not contain any dots");
155             }
156         } else {
157             // Domain was not specified in header. In this case, domain must
158             // string match request host (case-insensitive).
159             if (!cookie.getDomain().equals(host)) {
160                 throw new CookieRestrictionViolationException("Illegal domain attribute: \""
161                                                    + cookie.getDomain() + "\"."
162                                                    + "Domain of origin: \""
163                                                    + host + "\"");
164             }
165         }
166     }
167 
168     /**
169      * Match cookie domain attribute.
170      */
171     @Override
172     public boolean match(final Cookie cookie, final CookieOrigin origin) {
173         Args.notNull(cookie, "Cookie");
174         Args.notNull(origin, "Cookie origin");
175         final String host = origin.getHost().toLowerCase(Locale.ROOT);
176         final String cookieDomain = cookie.getDomain();
177 
178         // The effective host name MUST domain-match the Domain
179         // attribute of the cookie.
180         if (!domainMatch(host, cookieDomain)) {
181             return false;
182         }
183         // effective host name minus domain must not contain any dots
184         final String effectiveHostWithoutDomain = host.substring(
185                 0, host.length() - cookieDomain.length());
186         return effectiveHostWithoutDomain.indexOf('.') == -1;
187     }
188 
189     @Override
190     public String getAttributeName() {
191         return ClientCookie.DOMAIN_ATTR;
192     }
193 
194 }