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   * <tt>"Domain"</tt> 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      public void parse(
59              final SetCookie cookie, final String domain) throws MalformedCookieException {
60          Args.notNull(cookie, "Cookie");
61          if (domain == null) {
62              throw new MalformedCookieException(
63                      "Missing value for domain attribute");
64          }
65          if (domain.trim().length() == 0) {
66              throw new MalformedCookieException(
67                      "Blank value for domain attribute");
68          }
69          String s = domain;
70          s = s.toLowerCase(Locale.ENGLISH);
71          if (!domain.startsWith(".")) {
72              // Per RFC 2965 section 3.2.2
73              // "... If an explicitly specified value does not start with
74              // a dot, the user agent supplies a leading dot ..."
75              // That effectively implies that the domain attribute
76              // MAY NOT be an IP address of a host name
77              s = '.' + s;
78          }
79          cookie.setDomain(s);
80      }
81  
82      /**
83       * Performs domain-match as defined by the RFC2965.
84       * <p>
85       * Host A's name domain-matches host B's if
86       * <ol>
87       *   <ul>their host name strings string-compare equal; or</ul>
88       *   <ul>A is a HDN string and has the form NB, where N is a non-empty
89       *       name string, B has the form .B', and B' is a HDN string.  (So,
90       *       x.y.com domain-matches .Y.com but not Y.com.)</ul>
91       * </ol>
92       *
93       * @param host host name where cookie is received from or being sent to.
94       * @param domain The cookie domain attribute.
95       * @return true if the specified host matches the given domain.
96       */
97      public boolean domainMatch(final String host, final String domain) {
98          final boolean match = host.equals(domain)
99                          || (domain.startsWith(".") && host.endsWith(domain));
100 
101         return match;
102     }
103 
104     /**
105      * Validate cookie domain attribute.
106      */
107     public void validate(final Cookie cookie, final CookieOrigin origin)
108             throws MalformedCookieException {
109         Args.notNull(cookie, "Cookie");
110         Args.notNull(origin, "Cookie origin");
111         final String host = origin.getHost().toLowerCase(Locale.ENGLISH);
112         if (cookie.getDomain() == null) {
113             throw new CookieRestrictionViolationException("Invalid cookie state: " +
114                                                "domain not specified");
115         }
116         final String cookieDomain = cookie.getDomain().toLowerCase(Locale.ENGLISH);
117 
118         if (cookie instanceof ClientCookie
119                 && ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) {
120             // Domain attribute must start with a dot
121             if (!cookieDomain.startsWith(".")) {
122                 throw new CookieRestrictionViolationException("Domain attribute \"" +
123                     cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot");
124             }
125 
126             // Domain attribute must contain at least one embedded dot,
127             // or the value must be equal to .local.
128             final int dotIndex = cookieDomain.indexOf('.', 1);
129             if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1))
130                 && (!cookieDomain.equals(".local"))) {
131                 throw new CookieRestrictionViolationException(
132                         "Domain attribute \"" + cookie.getDomain()
133                         + "\" violates RFC 2965: the value contains no embedded dots "
134                         + "and the value is not .local");
135             }
136 
137             // The effective host name must domain-match domain attribute.
138             if (!domainMatch(host, cookieDomain)) {
139                 throw new CookieRestrictionViolationException(
140                         "Domain attribute \"" + cookie.getDomain()
141                         + "\" violates RFC 2965: effective host name does not "
142                         + "domain-match domain attribute.");
143             }
144 
145             // effective host name minus domain must not contain any dots
146             final String effectiveHostWithoutDomain = host.substring(
147                     0, host.length() - cookieDomain.length());
148             if (effectiveHostWithoutDomain.indexOf('.') != -1) {
149                 throw new CookieRestrictionViolationException("Domain attribute \""
150                                                    + cookie.getDomain() + "\" violates RFC 2965: "
151                                                    + "effective host minus domain may not contain any dots");
152             }
153         } else {
154             // Domain was not specified in header. In this case, domain must
155             // string match request host (case-insensitive).
156             if (!cookie.getDomain().equals(host)) {
157                 throw new CookieRestrictionViolationException("Illegal domain attribute: \""
158                                                    + cookie.getDomain() + "\"."
159                                                    + "Domain of origin: \""
160                                                    + host + "\"");
161             }
162         }
163     }
164 
165     /**
166      * Match cookie domain attribute.
167      */
168     public boolean match(final Cookie cookie, final CookieOrigin origin) {
169         Args.notNull(cookie, "Cookie");
170         Args.notNull(origin, "Cookie origin");
171         final String host = origin.getHost().toLowerCase(Locale.ENGLISH);
172         final String cookieDomain = cookie.getDomain();
173 
174         // The effective host name MUST domain-match the Domain
175         // attribute of the cookie.
176         if (!domainMatch(host, cookieDomain)) {
177             return false;
178         }
179         // effective host name minus domain must not contain any dots
180         final String effectiveHostWithoutDomain = host.substring(
181                 0, host.length() - cookieDomain.length());
182         return effectiveHostWithoutDomain.indexOf('.') == -1;
183     }
184 
185 }