1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.http.impl.cookie;
28
29 import org.apache.http.annotation.Immutable;
30
31 import org.apache.http.cookie.Cookie;
32 import org.apache.http.cookie.CookieAttributeHandler;
33 import org.apache.http.cookie.CookieOrigin;
34 import org.apache.http.cookie.CookieRestrictionViolationException;
35 import org.apache.http.cookie.MalformedCookieException;
36 import org.apache.http.cookie.SetCookie;
37
38
39
40
41
42 @Immutable
43 public class BasicDomainHandler implements CookieAttributeHandler {
44
45 public BasicDomainHandler() {
46 super();
47 }
48
49 public void parse(final SetCookie cookie, final String value)
50 throws MalformedCookieException {
51 if (cookie == null) {
52 throw new IllegalArgumentException("Cookie may not be null");
53 }
54 if (value == null) {
55 throw new MalformedCookieException("Missing value for domain attribute");
56 }
57 if (value.trim().length() == 0) {
58 throw new MalformedCookieException("Blank value for domain attribute");
59 }
60 cookie.setDomain(value);
61 }
62
63 public void validate(final Cookie cookie, final CookieOrigin origin)
64 throws MalformedCookieException {
65 if (cookie == null) {
66 throw new IllegalArgumentException("Cookie may not be null");
67 }
68 if (origin == null) {
69 throw new IllegalArgumentException("Cookie origin may not be null");
70 }
71
72
73
74
75
76 String host = origin.getHost();
77 String domain = cookie.getDomain();
78 if (domain == null) {
79 throw new CookieRestrictionViolationException("Cookie domain may not be null");
80 }
81 if (host.contains(".")) {
82
83
84
85
86 if (!host.endsWith(domain)) {
87 if (domain.startsWith(".")) {
88 domain = domain.substring(1, domain.length());
89 }
90 if (!host.equals(domain)) {
91 throw new CookieRestrictionViolationException(
92 "Illegal domain attribute \"" + domain
93 + "\". Domain of origin: \"" + host + "\"");
94 }
95 }
96 } else {
97 if (!host.equals(domain)) {
98 throw new CookieRestrictionViolationException(
99 "Illegal domain attribute \"" + domain
100 + "\". Domain of origin: \"" + host + "\"");
101 }
102 }
103 }
104
105 public boolean match(final Cookie cookie, final CookieOrigin origin) {
106 if (cookie == null) {
107 throw new IllegalArgumentException("Cookie may not be null");
108 }
109 if (origin == null) {
110 throw new IllegalArgumentException("Cookie origin may not be null");
111 }
112 String host = origin.getHost();
113 String domain = cookie.getDomain();
114 if (domain == null) {
115 return false;
116 }
117 if (host.equals(domain)) {
118 return true;
119 }
120 if (!domain.startsWith(".")) {
121 domain = '.' + domain;
122 }
123 return host.endsWith(domain) || host.equals(domain.substring(1));
124 }
125
126 }