/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 2000 The Apache Software Foundation.  All rights 
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer. 
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:  
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "SOAP" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written 
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 2000, International
 * Business Machines, Inc., http://www.apache.org.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

package org.apache.soap.transport.http;

import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 * A cookie as defined in RFC 2109 and RFC 2965.  Since cookie support is a relatively
 * tangential feature, this implementation is <i>very</i> forgiving, allowing many
 * variations from the RFCs and staying mum regarding errors.
 *
 * This class also provides static methods to support management of an array
 * of <code>Cookie</code> instances.
 *
 * @author Scott Nichol (snichol@computer.org)
 */
public class Cookie {
    /* Default port for HTTP */
    private static final int DEFAULT_HTTP_PORT = 80;

    /* Time of creation for aging */
    private long createdMillis;

    /* URL from which the cookie originated, and defaults therefrom */
    private URL url;
    private String defaultDomain;
    private int defaultPort;
    private String defaultPath;

    /* Name and value defined in RFC 2109 */
    private String name;
    private String value;

    /* Attributes defined in RFC 2109 */
    private String comment = null;
    private String domain = null;
    private long maxAge = Long.MAX_VALUE;
    private String path = null;
    private boolean secure = false;
    private String version = null;

    /* Attributes defined in RFC 2965 */
    private String commentURL = null;
    private boolean discard = false;
    private int[] port = null;

    /* Legacy (Netscape) attributes */
    private long expires = Long.MAX_VALUE;

    /* For parsing expiration dates */
    private static SimpleDateFormat dateParser = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z");

    /**
     * Creates an instance from a cookie string.  A Set-Cookie or Set-Cookie2
     * header consists of a comma-separated list of such strings.
     *
     * @param   url    The URL from which the cookie came.
     * @param   cookieString    The cookie string.
     */
    public Cookie(URL url, String cookieString) {
        int index;
        String nameValue;
        String attributes;
        StringTokenizer st;
        String attrName;
        String attrValue;

        /* Split the string into name/value and attributes */
        cookieString = removeLeadingSpaces(cookieString);
        index = cookieString.indexOf(';');
        if (index != -1) {
            nameValue = cookieString.substring(0, index);
            if (cookieString.length() > index)
                attributes = cookieString.substring(index + 1);
            else
                attributes = "";
        } else {
            nameValue = cookieString;
            attributes = "";
        }

        /* Split the name/value into name and value */
        index = nameValue.indexOf('=');
        if (index != -1) {
            name = nameValue.substring(0, index);
            if (nameValue.length() > index)
                value = removeEnclosingQuotes(nameValue.substring(index + 1));
            else
                value = "";
        } else {
            /* It is not legal to have no '=', but try to be nice to non-conforming servers */
            name = nameValue;
            value = "";
        }

        /* Split the attributes */
        st = new StringTokenizer(attributes, ";");
        while (st.hasMoreTokens()) {
            nameValue = removeLeadingSpaces(st.nextToken());
            index = nameValue.indexOf('=');
            if (index != -1) {
                attrName = nameValue.substring(0, index);
                if (nameValue.length() > index)
                    attrValue = removeEnclosingQuotes(nameValue.substring(index + 1));
                else
                    attrValue = "";
            } else {
                /* For Discard, Secure, and (sometimes) Port, this is correct, otherwise we are being forgiving. */
                attrName = nameValue;
                attrValue = "";
            }
            if (attrName.equalsIgnoreCase("Comment")) {
                if (comment == null)
                    comment = attrValue;
            } else if (attrName.equalsIgnoreCase("Domain")) {
            	/* TODO: check validity according to RFC before accepting */
                if (domain == null)
                    domain = attrValue;
            } else if (attrName.equalsIgnoreCase("Max-Age")) {
                if (maxAge == Long.MAX_VALUE) {
                    try {
                        maxAge = Long.parseLong(attrValue);
                        expires = System.currentTimeMillis() + (maxAge * 1000);
                    } catch (NumberFormatException e) {
                    }
                }
            } else if (attrName.equalsIgnoreCase("Path")) {
                if (path == null)
                    path = attrValue;
            } else if (attrName.equalsIgnoreCase("Secure")) {
                secure = true;
            } else if (attrName.equalsIgnoreCase("Version")) {
                if (version == null)
                    version = attrValue;
            } else if (attrName.equalsIgnoreCase("CommentURL")) {
                if (commentURL == null)
                    commentURL = attrValue;
            } else if (attrName.equalsIgnoreCase("Discard")) {
                version = attrValue;
            } else if (attrName.equalsIgnoreCase("Port")) {
                if (port == null) {
                    if (attrValue.length() == 0) {
                        port = new int[0];
                    } else {
                        try {
                            StringTokenizer st2 = new StringTokenizer(attrValue, ",");
                            int[] ports = new int[st2.countTokens()];
                            int portNum = 0;
                            while (st2.hasMoreTokens())
                                ports[portNum++] = Integer.parseInt(st2.nextToken());
                            port = ports;
                        } catch (NumberFormatException e) {
                        }
                    }
                }
            } else if (attrName.equalsIgnoreCase("Expires")) {
                if (expires == Long.MAX_VALUE) {
                    try {
                        expires = dateParser.parse(attrValue).getTime();
                    } catch (ParseException e) {
                    }
                }
            } else {
                /* Just ignore attributes not in the RFC. */
            }
        }

        setURL(url);
        createdMillis = System.currentTimeMillis();
    }

    /**
     * Returns a Cookie or Cookie2 header value for an array of cookies being
     * sent to a URL.
     *
     * @param   url    The URL to which the header will be sent.
     * @param   cookies    The cookies that may be sent in the header.
     * @return  The Cookie or Cookie2 header value.
     */
    public static String buildCookieValue(URL url, Cookie[] cookies) {
        StringBuffer buf = new StringBuffer();

        /* TODO: order the cookies by path-specificity, cf. 4.3.4 of RFC 2109 */
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if ((!cookie.getExpired()) && cookie.sendToURL(url)) {
                if (buf.length() > 0)
                    buf.append(';');    /* RFC says to send ';', but server must accept ',', too. */
                buf.append(cookie.toString());
            }
        }

        return buf.toString();
    }

    /** 
     * Compares two Cookies.  Two Cookie objects are equal if
     * they have the same name, value, domain, path and port.
     *
     * @param   obj    The Cookie to compare against.
     * @return  true if the Cookies are the same, false otherwise.
     */
    public boolean equals(Object obj) {
        if (!(obj instanceof Cookie))
            return false;

        Cookie cookie = (Cookie) obj;
        return name.equals(cookie.name) && value.equals(cookie.value) &&
                sameAttribute(domain, defaultDomain, cookie.domain, cookie.defaultDomain) &&
                sameAttribute(path, defaultPath, cookie.path, cookie.defaultPath) &&
                samePort(port, defaultPort, cookie.port, cookie.defaultPort);
    }

    /**
     * Returns whether the cookie has expired.
     *
     * @return  True if the cookie has expired, false if it has not.
     */
    public boolean getExpired() {
        return System.currentTimeMillis() > expires;
    }

    /**
     * Creates an array of cookies from a Set-Cookie or Set-Cookie2 header value.
     *
     * @param   url    The URL from which the header came.
     * @param   setCookieValue    The value from the Set-Cookie or Set-Cookie2 header.
     * @return  An array of cookies.
     */
    public static Cookie[] parseCookies(URL url, String setCookieValue) {
        /*
         * Note that as of RFC 2965, one cannot simply split the string
         * apart with a StringTokenizer, because the Port attribute may
         * include a comma-separated list of ports.
         */
        int cookieOffset = 0;
        boolean inQuote = false;
		Vector cookieV = new Vector();

        for (int i = 0; i < setCookieValue.length(); i++) {
            char c = setCookieValue.charAt(i);
            if (c == '\"') {
                inQuote = !inQuote;
            } else if (c == ',' && !inQuote) {
                cookieV.addElement(new Cookie(url, setCookieValue.substring(cookieOffset, i)));
                cookieOffset = i + 1;
            }
        }
        /* Ignore the possibility that inQuote is true! */
        if (cookieOffset < setCookieValue.length())
    	    cookieV.addElement(new Cookie(url, setCookieValue.substring(cookieOffset)));

        Cookie[] cookies = new Cookie[cookieV.size()];
        for (int i = 0; i < cookieV.size(); i++)
            cookies[i] = (Cookie) cookieV.elementAt(i);
        return cookies;
    }

    /**
     * Removes enclosing quotes from a string.
     *
     * @param   s    The string to process.
     * @return  The result.
     */
    private static String removeEnclosingQuotes(String s) {
        return (s.startsWith("\"") && s.endsWith("\"")) ? s.substring(1, s.length() - 1) : s;
    }

    /**
     * Removes leading spaces from a string.
     *
     * @param   s    The string to process.
     * @return  The result.
     */
    private static String removeLeadingSpaces(String s) {
        int i;
        for (i = 0; i < s.length() && s.charAt(i) == ' '; i++)
            ;
        return i == 0 ? s : s.substring(i);
    }

    /**
     * Compares two attributes or their defaults.
     *
     * @param   a1    An attribute.
     * @param   da1   A default for the attribute.
     * @param   a2    An attribute.
     * @param   da2   A default for the attribute.
     * @return  true if the attributes are the same, false otherwise.
     */
    private static boolean sameAttribute(String a1, String da1, String a2, String da2) {
        if (a1 != null && a2 != null)
            return a1.equals(a2);
        if (a1 == null && a2 == null)
            return da1.equals(da2);
        return false;
    }

    /** 
     * Compares two Cookies.  Two Cookie objects are the &quot;same&quot; if
     * they have the same name, domain, path and port.
     *
     * @param   cookie1    A Cookie.
     * @param   cookie2 A Cookie.
     * @return  true if the Cookies are the same, false otherwise.
     */
    public static boolean sameCookie(Cookie cookie1, Cookie cookie2) {
        return cookie1.name.equals(cookie2.name) &&
                sameAttribute(cookie1.domain, cookie1.defaultDomain, cookie2.domain, cookie2.defaultDomain) &&
                sameAttribute(cookie1.path, cookie1.defaultPath, cookie2.path, cookie2.defaultPath) &&
                samePort(cookie1.port, cookie1.defaultPort, cookie2.port, cookie2.defaultPort);
    }

    /**
     * Compares two Cookie port attributes or their defaults.
     *
     * @param   port1    A port attribute.
     * @param   dport1   A default port attribute.
     * @param   port2    A port attribute.
     * @param   dport2   A default port attribute.
     * @return  true if the port attributes are the same, false otherwise.
     */
    private static boolean samePort(int[] port1, int dport1, int[] port2, int dport2) {
        if (port1 != null && port2 != null) {
            int i, j;
            if (port1.length != port2.length)
                return false;
            if (port1.length == 0)
                return dport1 == dport2;
            for (i = 0; i < port1.length; i++) {
                for (j = 0; j < port2.length; j++)
                    if (port1[i] == port2[j])
                        break;
                if (j >= port2.length)
                    return false;
            }
            return true;
        }

        if (port1 == null && port2 == null)
            return true;

        return false;
    }

    /**
     * Returns whether the cookie should be sent to the URL.
     *
     * @return  True if the cookie should be sent to the URL, false if it should not.
     */
    public boolean sendToURL(URL url) {
        /* Check the domain */
        /*
         * TODO: be more sophisticated in dealing with a mixture of numeric IP
         * addresses and host/domain names.  For example, see how java.net.URL
         * compares the host parts of URLs in the sameFile method.
         */
        if (domain != null) {
            if (url.getHost().indexOf(domain) == -1)
                return false;
        } else {
            if (url.getHost().indexOf(defaultDomain) == -1)
                return false;
        }
        /* Check the path */
        if (path != null) {
            if (!url.getPath().startsWith(path))
                return false;
        } else {
            if (!url.getPath().startsWith(defaultPath))
                return false;
        }
        /* Check the port */
        if (port != null) {
            int urlPort = url.getPort();
            if (urlPort == -1)
                urlPort = DEFAULT_HTTP_PORT;
            if (port.length == 0) {
                if (defaultPort != urlPort)
                    return false;
            } else {
                int i;
                for (i = 0; i < port.length; i++)
                    if (port[i] == urlPort)
                        break;
                if (i >= port.length)
                    return false;
            }
        }
        /* All checks passed */
        return true;
    }

    /**
     * Sets the URL and defaults therefrom.
     *
     * @param   url    The URL.
     */
    private void setURL(URL url) {
        this.url = url;
        defaultDomain = url.getHost();
        defaultPort = url.getPort();
        if (defaultPort == -1)
            defaultPort = DEFAULT_HTTP_PORT;
        defaultPath = url.getPath();
        int index = defaultPath.lastIndexOf('/');
        if (index != -1)
            defaultPath = defaultPath.substring(0, index);
    }

    /**
     * Returns the cookie as a string appropriate for a Cookie or Cookie2 header.
     *
     * @return  A string appropriate for a Cookie header.
     */
    public String toString() {
        StringBuffer buf = new StringBuffer();

        /*
         * According to RFC 2965, the version should appear before the first cookie
         * value only, but here some liberties are taken to place it before each
         * cookie value.  Presumably, it should also be checked that all cookies
         * have the same version.
         */
        if (version != null) {
            buf.append(";$version=");
            buf.append(version);
        }
        buf.append(name);
        buf.append('=');
        buf.append(value);
        if (domain != null) {
            buf.append(";$domain=");
            buf.append(domain);
        }
        if (path != null) {
            buf.append(";$path=");
            buf.append(path);
        }
        if (port != null) {
            buf.append(";$port");
            if (port.length > 0) {
                buf.append("=\"");
                for (int i = 0; i < port.length; i++) {
                    if (i > 0)
                        buf.append(',');
                    buf.append(port[i]);
                }
                buf.append('\"');
            }
        }
        
        return buf.toString();
    }

    /**
     * Updates an array of cookies with another array of cookies.  The cookies
     * in the <code>cookies1<code> array can be updated.  The returned array will
     * be a reference to a new array if cookies were added to it.
     *
     * @param   cookies1    The array of Cookies being updated.
     * @param   cookies2    The array of Cookies by which to update.
     * @return  An updated array, which may be different than <code>cookies1</code>.
     */
    public static Cookie[] updateCookies(Cookie[] cookies1, Cookie[] cookies2) {
        Vector newCookies = new Vector();
        int i, j;

        /* Compare the new cookie array with the old one */
        for (i = 0; i < cookies2.length; i++) {
            Cookie cookie2 = cookies2[i];
            Cookie cookie1 = null;
            /* Look for a match */
            for (j = 0; j < cookies1.length; j++) {
                cookie1 = cookies1[j];
                if (sameCookie(cookie1, cookie2))
                    break;
            }
            if (j < cookies1.length) {
                /* Update values on matching cookie */
                cookie1.value = cookie2.value;
                cookie1.comment = cookie2.comment;
                cookie1.commentURL = cookie2.commentURL;
                cookie1.maxAge = cookie2.maxAge;
                cookie1.secure = cookie2.secure;
                cookie1.version = cookie2.version;
                cookie1.expires = cookie2.expires;
            } else {
                /* Save new cookie */
                newCookies.addElement(cookie2);
            }
        }

        /* If there are no new cookies, just return the old array */
        if (newCookies.size() == 0)
            return cookies1;

        /* Create a new array that includes the new cookies */
        Cookie[] c = new Cookie[cookies1.length + newCookies.size()];
        for (i = 0; i < cookies1.length; i++)
            c[i] = cookies1[i];
        for (j = 0; j < newCookies.size(); j++)
            c[i + j] = (Cookie) newCookies.elementAt(j);

        return c;
    }
}
