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.Cookie;
35  import org.apache.http.cookie.CookieAttributeHandler;
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 CookieAttributeHandler {
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       * <ol>
88       *   <ul>their host name strings string-compare equal; or</ul>
89       *   <ul>A is a HDN string and has the form NB, where N is a non-empty
90       *       name string, B has the form .B', and B' is a HDN string.  (So,
91       *       x.y.com domain-matches .Y.com but not Y.com.)</ul>
92       * </ol>
93       *
94       * @param host host name where cookie is received from or being sent to.
95       * @param domain The cookie domain attribute.
96       * @return true if the specified host matches the given domain.
97       */
98      public boolean domainMatch(final String host, final String domain) {
99          final boolean match = host.equals(domain)
100                         || (domain.startsWith(".") && host.endsWith(domain));
101 
102         return match;
103     }
104 
105     /**
106      * Validate cookie domain attribute.
107      */
108     @Override
109     public void validate(final Cookie cookie, final CookieOrigin origin)
110             throws MalformedCookieException {
111         Args.notNull(cookie, "Cookie");
112         Args.notNull(origin, "Cookie origin");
113         final String host = origin.getHost().toLowerCase(Locale.ROOT);
114         if (cookie.getDomain() == null) {
115             throw new CookieRestrictionViolationException("Invalid cookie state: " +
116                                                "domain not specified");
117         }
118         final String cookieDomain = cookie.getDomain().toLowerCase(Locale.ROOT);
119 
120         if (cookie instanceof ClientCookie
121                 && ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) {
122             // Domain attribute must start with a dot
123             if (!cookieDomain.startsWith(".")) {
124                 throw new CookieRestrictionViolationException("Domain attribute \"" +
125                     cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot");
126             }
127 
128             // Domain attribute must contain at least one embedded dot,
129             // or the value must be equal to .local.
130             final int dotIndex = cookieDomain.indexOf('.', 1);
131             if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1))
132                 && (!cookieDomain.equals(".local"))) {
133                 throw new CookieRestrictionViolationException(
134                         "Domain attribute \"" + cookie.getDomain()
135                         + "\" violates RFC 2965: the value contains no embedded dots "
136                         + "and the value is not .local");
137             }
138 
139             // The effective host name must domain-match domain attribute.
140             if (!domainMatch(host, cookieDomain)) {
141                 throw new CookieRestrictionViolationException(
142                         "Domain attribute \"" + cookie.getDomain()
143                         + "\" violates RFC 2965: effective host name does not "
144                         + "domain-match domain attribute.");
145             }
146 
147             // effective host name minus domain must not contain any dots
148             final String effectiveHostWithoutDomain = host.substring(
149                     0, host.length() - cookieDomain.length());
150             if (effectiveHostWithoutDomain.indexOf('.') != -1) {
151                 throw new CookieRestrictionViolationException("Domain attribute \""
152                                                    + cookie.getDomain() + "\" violates RFC 2965: "
153                                                    + "effective host minus domain may not contain any dots");
154             }
155         } else {
156             // Domain was not specified in header. In this case, domain must
157             // string match request host (case-insensitive).
158             if (!cookie.getDomain().equals(host)) {
159                 throw new CookieRestrictionViolationException("Illegal domain attribute: \""
160                                                    + cookie.getDomain() + "\"."
161                                                    + "Domain of origin: \""
162                                                    + host + "\"");
163             }
164         }
165     }
166 
167     /**
168      * Match cookie domain attribute.
169      */
170     @Override
171     public boolean match(final Cookie cookie, final CookieOrigin origin) {
172         Args.notNull(cookie, "Cookie");
173         Args.notNull(origin, "Cookie origin");
174         final String host = origin.getHost().toLowerCase(Locale.ROOT);
175         final String cookieDomain = cookie.getDomain();
176 
177         // The effective host name MUST domain-match the Domain
178         // attribute of the cookie.
179         if (!domainMatch(host, cookieDomain)) {
180             return false;
181         }
182         // effective host name minus domain must not contain any dots
183         final String effectiveHostWithoutDomain = host.substring(
184                 0, host.length() - cookieDomain.length());
185         return effectiveHostWithoutDomain.indexOf('.') == -1;
186     }
187 
188 }