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.Contract;
33 import org.apache.http.annotation.ThreadingBehavior;
34 import org.apache.http.cookie.ClientCookie;
35 import org.apache.http.cookie.CommonCookieAttributeHandler;
36 import org.apache.http.cookie.Cookie;
37 import org.apache.http.cookie.CookieOrigin;
38 import org.apache.http.cookie.CookieRestrictionViolationException;
39 import org.apache.http.cookie.MalformedCookieException;
40 import org.apache.http.cookie.SetCookie;
41 import org.apache.http.util.Args;
42
43 /**
44  * {@code "Domain"} cookie attribute handler for RFC 2965 cookie spec.
45  *
46  *
47  * @since 3.1
48  */

49 @Contract(threading = ThreadingBehavior.IMMUTABLE)
50 public class RFC2965DomainAttributeHandler implements CommonCookieAttributeHandler {
51
52     public RFC2965DomainAttributeHandler() {
53         super();
54     }
55
56     /**
57      * Parse cookie domain attribute.
58      */

59     @Override
60     public void parse(
61             final SetCookie cookie, final String domain) throws MalformedCookieException {
62         Args.notNull(cookie, "Cookie");
63         if (domain == null) {
64             throw new MalformedCookieException(
65                     "Missing value for domain attribute");
66         }
67         if (domain.trim().isEmpty()) {
68             throw new MalformedCookieException(
69                     "Blank value for domain attribute");
70         }
71         String s = domain;
72         s = s.toLowerCase(Locale.ROOT);
73         if (!domain.startsWith(".")) {
74             // Per RFC 2965 section 3.2.2
75             // "... If an explicitly specified value does not start with
76             // a dot, the user agent supplies a leading dot ..."
77             // That effectively implies that the domain attribute
78             // MAY NOT be an IP address of a host name
79             s = '.' + s;
80         }
81         cookie.setDomain(s);
82     }
83
84     /**
85      * Performs domain-match as defined by the RFC2965.
86      * <p>
87      * Host A's name domain-matches host B's if
88      * </p>
89      * <ol>
90      *   <li>their host name strings string-compare equal; or</li>
91      *   <li>A is a HDN string and has the form NB, where N is a non-empty
92      *       name string, B has the form .B', and B' is a HDN string.  (So,
93      *       x.y.com domain-matches .Y.com but not Y.com.)</li>
94      * </ol>
95      *
96      * @param host host name where cookie is received from or being sent to.
97      * @param domain The cookie domain attribute.
98      * @return true if the specified host matches the given domain.
99      */

100     public boolean domainMatch(final String host, final String domain) {
101         final boolean match = host.equals(domain)
102                         || (domain.startsWith(".") && host.endsWith(domain));
103
104         return match;
105     }
106
107     /**
108      * Validate cookie domain attribute.
109      */

110     @Override
111     public void validate(final Cookie cookie, final CookieOrigin origin)
112             throws MalformedCookieException {
113         Args.notNull(cookie, "Cookie");
114         Args.notNull(origin, "Cookie origin");
115         final String host = origin.getHost().toLowerCase(Locale.ROOT);
116         if (cookie.getDomain() == null) {
117             throw new CookieRestrictionViolationException("Invalid cookie state: " +
118                                                "domain not specified");
119         }
120         final String cookieDomain = cookie.getDomain().toLowerCase(Locale.ROOT);
121
122         if (cookie instanceof ClientCookie
123                 && ((ClientCookie) cookie).containsAttribute(ClientCookie.DOMAIN_ATTR)) {
124             // Domain attribute must start with a dot
125             if (!cookieDomain.startsWith(".")) {
126                 throw new CookieRestrictionViolationException("Domain attribute \"" +
127                     cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot");
128             }
129
130             // Domain attribute must contain at least one embedded dot,
131             // or the value must be equal to .local.
132             final int dotIndex = cookieDomain.indexOf('.', 1);
133             if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1))
134                 && (!cookieDomain.equals(".local"))) {
135                 throw new CookieRestrictionViolationException(
136                         "Domain attribute \"" + cookie.getDomain()
137                         + "\" violates RFC 2965: the value contains no embedded dots "
138                         + "and the value is not .local");
139             }
140
141             // The effective host name must domain-match domain attribute.
142             if (!domainMatch(host, cookieDomain)) {
143                 throw new CookieRestrictionViolationException(
144                         "Domain attribute \"" + cookie.getDomain()
145                         + "\" violates RFC 2965: effective host name does not "
146                         + "domain-match domain attribute.");
147             }
148
149             // effective host name minus domain must not contain any dots
150             final String effectiveHostWithoutDomain = host.substring(
151                     0, host.length() - cookieDomain.length());
152             if (effectiveHostWithoutDomain.indexOf('.') != -1) {
153                 throw new CookieRestrictionViolationException("Domain attribute \""
154                                                    + cookie.getDomain() + "\" violates RFC 2965: "
155                                                    + "effective host minus domain may not contain any dots");
156             }
157         } else {
158             // Domain was not specified in header. In this case, domain must
159             // string match request host (case-insensitive).
160             if (!cookie.getDomain().equals(host)) {
161                 throw new CookieRestrictionViolationException("Illegal domain attribute: \""
162                                                    + cookie.getDomain() + "\"."
163                                                    + "Domain of origin: \""
164                                                    + host + "\"");
165             }
166         }
167     }
168
169     /**
170      * Match cookie domain attribute.
171      */

172     @Override
173     public boolean match(final Cookie cookie, final CookieOrigin origin) {
174         Args.notNull(cookie, "Cookie");
175         Args.notNull(origin, "Cookie origin");
176         final String host = origin.getHost().toLowerCase(Locale.ROOT);
177         final String cookieDomain = cookie.getDomain();
178
179         // The effective host name MUST domain-match the Domain
180         // attribute of the cookie.
181         if (!domainMatch(host, cookieDomain)) {
182             return false;
183         }
184         // effective host name minus domain must not contain any dots
185         final String effectiveHostWithoutDomain = host.substring(
186                 0, host.length() - cookieDomain.length());
187         return effectiveHostWithoutDomain.indexOf('.') == -1;
188     }
189
190     @Override
191     public String getAttributeName() {
192         return ClientCookie.DOMAIN_ATTR;
193     }
194
195 }
196