1/*
2 * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/impl/cookie/RFC2965PortAttributeHandler.java $
3 * $Revision: 590695 $
4 * $Date: 2007-10-31 07:55:41 -0700 (Wed, 31 Oct 2007) $
5 *
6 * ====================================================================
7 * Licensed to the Apache Software Foundation (ASF) under one
8 * or more contributor license agreements.  See the NOTICE file
9 * distributed with this work for additional information
10 * regarding copyright ownership.  The ASF licenses this file
11 * to you under the Apache License, Version 2.0 (the
12 * "License"); you may not use this file except in compliance
13 * with the License.  You may obtain a copy of the License at
14 *
15 *   http://www.apache.org/licenses/LICENSE-2.0
16 *
17 * Unless required by applicable law or agreed to in writing,
18 * software distributed under the License is distributed on an
19 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
20 * KIND, either express or implied.  See the License for the
21 * specific language governing permissions and limitations
22 * under the License.
23 * ====================================================================
24 *
25 * This software consists of voluntary contributions made by many
26 * individuals on behalf of the Apache Software Foundation.  For more
27 * information on the Apache Software Foundation, please see
28 * <http://www.apache.org/>.
29 *
30 */
31
32package org.apache.http.impl.cookie;
33
34import java.util.StringTokenizer;
35
36import org.apache.http.cookie.ClientCookie;
37import org.apache.http.cookie.Cookie;
38import org.apache.http.cookie.CookieAttributeHandler;
39import org.apache.http.cookie.CookieOrigin;
40import org.apache.http.cookie.MalformedCookieException;
41import org.apache.http.cookie.SetCookie;
42import org.apache.http.cookie.SetCookie2;
43
44/**
45 * <tt>"Port"</tt> cookie attribute handler for RFC 2965 cookie spec.
46 *
47 * @deprecated Please use {@link java.net.URL#openConnection} instead.
48 *     Please visit <a href="http://android-developers.blogspot.com/2011/09/androids-http-clients.html">this webpage</a>
49 *     for further details.
50 */
51@Deprecated
52public class RFC2965PortAttributeHandler implements CookieAttributeHandler {
53
54    public RFC2965PortAttributeHandler() {
55        super();
56    }
57
58    /**
59     * Parses the given Port attribute value (e.g. "8000,8001,8002")
60     * into an array of ports.
61     *
62     * @param portValue port attribute value
63     * @return parsed array of ports
64     * @throws MalformedCookieException if there is a problem in
65     *          parsing due to invalid portValue.
66     */
67    private static int[] parsePortAttribute(final String portValue)
68            throws MalformedCookieException {
69        StringTokenizer st = new StringTokenizer(portValue, ",");
70        int[] ports = new int[st.countTokens()];
71        try {
72            int i = 0;
73            while(st.hasMoreTokens()) {
74                ports[i] = Integer.parseInt(st.nextToken().trim());
75                if (ports[i] < 0) {
76                  throw new MalformedCookieException ("Invalid Port attribute.");
77                }
78                ++i;
79            }
80        } catch (NumberFormatException e) {
81            throw new MalformedCookieException ("Invalid Port "
82                                                + "attribute: " + e.getMessage());
83        }
84        return ports;
85    }
86
87    /**
88     * Returns <tt>true</tt> if the given port exists in the given
89     * ports list.
90     *
91     * @param port port of host where cookie was received from or being sent to.
92     * @param ports port list
93     * @return true returns <tt>true</tt> if the given port exists in
94     *         the given ports list; <tt>false</tt> otherwise.
95     */
96    private static boolean portMatch(int port, int[] ports) {
97        boolean portInList = false;
98        for (int i = 0, len = ports.length; i < len; i++) {
99            if (port == ports[i]) {
100                portInList = true;
101                break;
102            }
103        }
104        return portInList;
105    }
106
107    /**
108     * Parse cookie port attribute.
109     */
110    public void parse(final SetCookie cookie, final String portValue)
111            throws MalformedCookieException {
112        if (cookie == null) {
113            throw new IllegalArgumentException("Cookie may not be null");
114        }
115        if (cookie instanceof SetCookie2) {
116            SetCookie2 cookie2 = (SetCookie2) cookie;
117            if (portValue != null && portValue.trim().length() > 0) {
118                int[] ports = parsePortAttribute(portValue);
119                cookie2.setPorts(ports);
120            }
121        }
122    }
123
124    /**
125     * Validate cookie port attribute. If the Port attribute was specified
126     * in header, the request port must be in cookie's port list.
127     */
128    public void validate(final Cookie cookie, final CookieOrigin origin)
129            throws MalformedCookieException {
130        if (cookie == null) {
131            throw new IllegalArgumentException("Cookie may not be null");
132        }
133        if (origin == null) {
134            throw new IllegalArgumentException("Cookie origin may not be null");
135        }
136        int port = origin.getPort();
137        if (cookie instanceof ClientCookie
138                && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) {
139            if (!portMatch(port, cookie.getPorts())) {
140                throw new MalformedCookieException(
141                        "Port attribute violates RFC 2965: "
142                        + "Request port not found in cookie's port list.");
143            }
144        }
145    }
146
147    /**
148     * Match cookie port attribute. If the Port attribute is not specified
149     * in header, the cookie can be sent to any port. Otherwise, the request port
150     * must be in the cookie's port list.
151     */
152    public boolean match(final Cookie cookie, final CookieOrigin origin) {
153        if (cookie == null) {
154            throw new IllegalArgumentException("Cookie may not be null");
155        }
156        if (origin == null) {
157            throw new IllegalArgumentException("Cookie origin may not be null");
158        }
159        int port = origin.getPort();
160        if (cookie instanceof ClientCookie
161                && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) {
162            if (cookie.getPorts() == null) {
163                // Invalid cookie state: port not specified
164                return false;
165            }
166            if (!portMatch(port, cookie.getPorts())) {
167                return false;
168            }
169        }
170        return true;
171    }
172
173}
174