001package org.json;
002
003/*
004Copyright (c) 2002 JSON.org
005
006Permission is hereby granted, free of charge, to any person obtaining a copy
007of this software and associated documentation files (the "Software"), to deal
008in the Software without restriction, including without limitation the rights
009to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
010copies of the Software, and to permit persons to whom the Software is
011furnished to do so, subject to the following conditions:
012
013The above copyright notice and this permission notice shall be included in all
014copies or substantial portions of the Software.
015
016The Software shall be used for Good, not Evil.
017
018THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
019IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
020FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
021AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
022LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
023OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
024SOFTWARE.
025*/
026
027/**
028 * Convert a web browser cookie specification to a JSONObject and back.
029 * JSON and Cookies are both notations for name/value pairs.
030 * @author JSON.org
031 * @version 2015-12-09
032 */
033public class Cookie {
034
035    /**
036     * Produce a copy of a string in which the characters '+', '%', '=', ';'
037     * and control characters are replaced with "%hh". This is a gentle form
038     * of URL encoding, attempting to cause as little distortion to the
039     * string as possible. The characters '=' and ';' are meta characters in
040     * cookies. By convention, they are escaped using the URL-encoding. This is
041     * only a convention, not a standard. Often, cookies are expected to have
042     * encoded values. We encode '=' and ';' because we must. We encode '%' and
043     * '+' because they are meta characters in URL encoding.
044     * @param string The source string.
045     * @return       The escaped result.
046     */
047    public static String escape(String string) {
048        char            c;
049        String          s = string.trim();
050        int             length = s.length();
051        StringBuilder   sb = new StringBuilder(length);
052        for (int i = 0; i < length; i += 1) {
053            c = s.charAt(i);
054            if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
055                sb.append('%');
056                sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
057                sb.append(Character.forDigit((char)(c & 0x0f), 16));
058            } else {
059                sb.append(c);
060            }
061        }
062        return sb.toString();
063    }
064
065
066    /**
067     * Convert a cookie specification string into a JSONObject. The string
068     * will contain a name value pair separated by '='. The name and the value
069     * will be unescaped, possibly converting '+' and '%' sequences. The
070     * cookie properties may follow, separated by ';', also represented as
071     * name=value (except the secure property, which does not have a value).
072     * The name will be stored under the key "name", and the value will be
073     * stored under the key "value". This method does not do checking or
074     * validation of the parameters. It only converts the cookie string into
075     * a JSONObject.
076     * @param string The cookie specification string.
077     * @return A JSONObject containing "name", "value", and possibly other
078     *  members.
079     * @throws JSONException
080     */
081    public static JSONObject toJSONObject(String string) throws JSONException {
082        String         name;
083        JSONObject     jo = new JSONObject();
084        Object         value;
085        JSONTokener x = new JSONTokener(string);
086        jo.put("name", x.nextTo('='));
087        x.next('=');
088        jo.put("value", x.nextTo(';'));
089        x.next();
090        while (x.more()) {
091            name = unescape(x.nextTo("=;"));
092            if (x.next() != '=') {
093                if (name.equals("secure")) {
094                    value = Boolean.TRUE;
095                } else {
096                    throw x.syntaxError("Missing '=' in cookie parameter.");
097                }
098            } else {
099                value = unescape(x.nextTo(';'));
100                x.next();
101            }
102            jo.put(name, value);
103        }
104        return jo;
105    }
106
107
108    /**
109     * Convert a JSONObject into a cookie specification string. The JSONObject
110     * must contain "name" and "value" members.
111     * If the JSONObject contains "expires", "domain", "path", or "secure"
112     * members, they will be appended to the cookie specification string.
113     * All other members are ignored.
114     * @param jo A JSONObject
115     * @return A cookie specification string
116     * @throws JSONException
117     */
118    public static String toString(JSONObject jo) throws JSONException {
119        StringBuilder sb = new StringBuilder();
120
121        sb.append(escape(jo.getString("name")));
122        sb.append("=");
123        sb.append(escape(jo.getString("value")));
124        if (jo.has("expires")) {
125            sb.append(";expires=");
126            sb.append(jo.getString("expires"));
127        }
128        if (jo.has("domain")) {
129            sb.append(";domain=");
130            sb.append(escape(jo.getString("domain")));
131        }
132        if (jo.has("path")) {
133            sb.append(";path=");
134            sb.append(escape(jo.getString("path")));
135        }
136        if (jo.optBoolean("secure")) {
137            sb.append(";secure");
138        }
139        return sb.toString();
140    }
141
142    /**
143     * Convert <code>%</code><i>hh</i> sequences to single characters, and
144     * convert plus to space.
145     * @param string A string that may contain
146     *      <code>+</code>&nbsp;<small>(plus)</small> and
147     *      <code>%</code><i>hh</i> sequences.
148     * @return The unescaped string.
149     */
150    public static String unescape(String string) {
151        int length = string.length();
152        StringBuilder sb = new StringBuilder(length);
153        for (int i = 0; i < length; ++i) {
154            char c = string.charAt(i);
155            if (c == '+') {
156                c = ' ';
157            } else if (c == '%' && i + 2 < length) {
158                int d = JSONTokener.dehexchar(string.charAt(i + 1));
159                int e = JSONTokener.dehexchar(string.charAt(i + 2));
160                if (d >= 0 && e >= 0) {
161                    c = (char)(d * 16 + e);
162                    i += 2;
163                }
164            }
165            sb.append(c);
166        }
167        return sb.toString();
168    }
169}