Java Code Examples for org.apache.commons.httpclient.Cookie#getDomain()

The following examples show how to use org.apache.commons.httpclient.Cookie#getDomain() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Match cookie domain attribute.
 */
public boolean match(final Cookie cookie, final CookieOrigin origin) {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (origin == null) {
        throw new IllegalArgumentException("Cookie origin may not be null");
    }
    String host = origin.getHost().toLowerCase();
    String cookieDomain = cookie.getDomain();

    // The effective host name MUST domain-match the Domain
    // attribute of the cookie.
    if (!domainMatch(host, cookieDomain)) {
        return false;
    }
    // effective host name minus domain must not contain any dots
    String effectiveHostWithoutDomain = host.substring(
            0, host.length() - cookieDomain.length());
    if (effectiveHostWithoutDomain.indexOf('.') != -1) {
        return false;
    }
    return true;
}
 
Example 2
Source File: RFC2109Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Return a string suitable for sending in a <tt>"Cookie"</tt> header 
 * as defined in RFC 2109 for backward compatibility with cookie version 0
 * @param buffer The string buffer to use for output
 * @param cookie The {@link Cookie} to be formatted as string
 * @param version The version to use.
 */
private void formatCookieAsVer(final StringBuffer buffer, final Cookie cookie, int version) {
    String value = cookie.getValue();
    if (value == null) {
        value = "";
    }
    formatParam(buffer, new NameValuePair(cookie.getName(), value), version);
    if ((cookie.getPath() != null) && cookie.isPathAttributeSpecified()) {
      buffer.append("; ");
      formatParam(buffer, new NameValuePair("$Path", cookie.getPath()), version);
    }
    if ((cookie.getDomain() != null) 
        && cookie.isDomainAttributeSpecified()) {
        buffer.append("; ");
        formatParam(buffer, new NameValuePair("$Domain", cookie.getDomain()), version);
    }
}
 
Example 3
Source File: NetscapeDraftSpec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
  * Performs Netscape draft compliant {@link Cookie} validation
  *
  * @param host the host from which the {@link Cookie} was received
  * @param port the port from which the {@link Cookie} was received
  * @param path the path from which the {@link Cookie} was received
  * @param secure <tt>true</tt> when the {@link Cookie} was received 
  * using a secure connection
  * @param cookie The cookie to validate.
  * @throws MalformedCookieException if an exception occurs during
  * validation
  */
public void validate(String host, int port, String path, 
    boolean secure, final Cookie cookie) 
    throws MalformedCookieException {
        
    LOG.trace("enterNetscapeDraftCookieProcessor "
        + "RCF2109CookieProcessor.validate(Cookie)");
    // Perform generic validation
    super.validate(host, port, path, secure, cookie);
    // Perform Netscape Cookie draft specific validation
    if (host.indexOf(".") >= 0) {
        int domainParts = new StringTokenizer(cookie.getDomain(), ".")
            .countTokens();

        if (isSpecialDomain(cookie.getDomain())) {
            if (domainParts < 2) {
                throw new MalformedCookieException("Domain attribute \""
                    + cookie.getDomain() 
                    + "\" violates the Netscape cookie specification for "
                    + "special domains");
            }
        } else {
            if (domainParts < 3) {
                throw new MalformedCookieException("Domain attribute \""
                    + cookie.getDomain() 
                    + "\" violates the Netscape cookie specification");
            }            
        }
    }
}
 
Example 4
Source File: RFC2965Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Validate cookie domain attribute.
 */
public void validate(final Cookie cookie, final CookieOrigin origin)
        throws MalformedCookieException {
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (origin == null) {
        throw new IllegalArgumentException("Cookie origin may not be null");
    }
    String host = origin.getHost().toLowerCase();
    if (cookie.getDomain() == null) {
        throw new MalformedCookieException("Invalid cookie state: " +
                                           "domain not specified");
    }
    String cookieDomain = cookie.getDomain().toLowerCase();

    if (cookie.isDomainAttributeSpecified()) {
        // Domain attribute must start with a dot
        if (!cookieDomain.startsWith(".")) {
            throw new MalformedCookieException("Domain attribute \"" +
                cookie.getDomain() + "\" violates RFC 2109: domain must start with a dot");
        }

        // Domain attribute must contain atleast one embedded dot,
        // or the value must be equal to .local.
        int dotIndex = cookieDomain.indexOf('.', 1);
        if (((dotIndex < 0) || (dotIndex == cookieDomain.length() - 1))
            && (!cookieDomain.equals(".local"))) {
            throw new MalformedCookieException(
                    "Domain attribute \"" + cookie.getDomain()
                    + "\" violates RFC 2965: the value contains no embedded dots "
                    + "and the value is not .local");
        }

        // The effective host name must domain-match domain attribute.
        if (!domainMatch(host, cookieDomain)) {
            throw new MalformedCookieException(
                    "Domain attribute \"" + cookie.getDomain()
                    + "\" violates RFC 2965: effective host name does not "
                    + "domain-match domain attribute.");
        }

        // effective host name minus domain must not contain any dots
        String effectiveHostWithoutDomain = host.substring(
                0, host.length() - cookieDomain.length());
        if (effectiveHostWithoutDomain.indexOf('.') != -1) {
            throw new MalformedCookieException("Domain attribute \""
                                               + cookie.getDomain() + "\" violates RFC 2965: "
                                               + "effective host minus domain may not contain any dots");
        }
    } else {
        // Domain was not specified in header. In this case, domain must
        // string match request host (case-insensitive).
        if (!cookie.getDomain().equals(host)) {
            throw new MalformedCookieException("Illegal domain attribute: \""
                                               + cookie.getDomain() + "\"."
                                               + "Domain of origin: \""
                                               + host + "\"");
        }
    }
}
 
Example 5
Source File: CookieSpecBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
  * Performs most common {@link Cookie} validation
  *
  * @param host the host from which the {@link Cookie} was received
  * @param port the port from which the {@link Cookie} was received
  * @param path the path from which the {@link Cookie} was received
  * @param secure <tt>true</tt> when the {@link Cookie} was received using a
  * secure connection
  * @param cookie The cookie to validate.
  * @throws MalformedCookieException if an exception occurs during
  * validation
  */

public void validate(String host, int port, String path, 
    boolean secure, final Cookie cookie) 
    throws MalformedCookieException {
        
    LOG.trace("enter CookieSpecBase.validate("
        + "String, port, path, boolean, Cookie)");
    if (host == null) {
        throw new IllegalArgumentException(
            "Host of origin may not be null");
    }
    if (host.trim().equals("")) {
        throw new IllegalArgumentException(
            "Host of origin may not be blank");
    }
    if (port < 0) {
        throw new IllegalArgumentException("Invalid port: " + port);
    }
    if (path == null) {
        throw new IllegalArgumentException(
            "Path of origin may not be null.");
    }
    if (path.trim().equals("")) {
        path = PATH_DELIM;
    }
    host = host.toLowerCase();
    // check version
    if (cookie.getVersion() < 0) {
        throw new MalformedCookieException ("Illegal version number " 
            + cookie.getValue());
    }

    // security check... we musn't allow the server to give us an
    // invalid domain scope

    // Validate the cookies domain attribute.  NOTE:  Domains without 
    // any dots are allowed to support hosts on private LANs that don't 
    // have DNS names.  Since they have no dots, to domain-match the 
    // request-host and domain must be identical for the cookie to sent 
    // back to the origin-server.
    if (host.indexOf(".") >= 0) {
        // Not required to have at least two dots.  RFC 2965.
        // A Set-Cookie2 with Domain=ajax.com will be accepted.

        // domain must match host
        if (!host.endsWith(cookie.getDomain())) {
            String s = cookie.getDomain();
            if (s.startsWith(".")) {
                s = s.substring(1, s.length());
            }
            if (!host.equals(s)) { 
                throw new MalformedCookieException(
                    "Illegal domain attribute \"" + cookie.getDomain() 
                    + "\". Domain of origin: \"" + host + "\"");
            }
        }
    } else {
        if (!host.equals(cookie.getDomain())) {
            throw new MalformedCookieException(
                "Illegal domain attribute \"" + cookie.getDomain() 
                + "\". Domain of origin: \"" + host + "\"");
        }
    }

    // another security check... we musn't allow the server to give us a
    // cookie that doesn't match this path

    if (!path.startsWith(cookie.getPath())) {
        throw new MalformedCookieException(
            "Illegal path attribute \"" + cookie.getPath() 
            + "\". Path of origin: \"" + path + "\"");
    }
}
 
Example 6
Source File: CookieSpecBase.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Return <tt>true</tt> if the cookie should be submitted with a request
 * with given attributes, <tt>false</tt> otherwise.
 * @param host the host to which the request is being submitted
 * @param port the port to which the request is being submitted (ignored)
 * @param path the path to which the request is being submitted
 * @param secure <tt>true</tt> if the request is using a secure connection
 * @param cookie {@link Cookie} to be matched
 * @return true if the cookie matches the criterium
 */

public boolean match(String host, int port, String path, 
    boolean secure, final Cookie cookie) {
        
    LOG.trace("enter CookieSpecBase.match("
        + "String, int, String, boolean, Cookie");
        
    if (host == null) {
        throw new IllegalArgumentException(
            "Host of origin may not be null");
    }
    if (host.trim().equals("")) {
        throw new IllegalArgumentException(
            "Host of origin may not be blank");
    }
    if (port < 0) {
        throw new IllegalArgumentException("Invalid port: " + port);
    }
    if (path == null) {
        throw new IllegalArgumentException(
            "Path of origin may not be null.");
    }
    if (cookie == null) {
        throw new IllegalArgumentException("Cookie may not be null");
    }
    if (path.trim().equals("")) {
        path = PATH_DELIM;
    }
    host = host.toLowerCase();
    if (cookie.getDomain() == null) {
        LOG.warn("Invalid cookie state: domain not specified");
        return false;
    }
    if (cookie.getPath() == null) {
        LOG.warn("Invalid cookie state: path not specified");
        return false;
    }
    
    return
        // only add the cookie if it hasn't yet expired 
        (cookie.getExpiryDate() == null 
            || cookie.getExpiryDate().after(new Date()))
        // and the domain pattern matches 
        && (domainMatch(host, cookie.getDomain()))
        // and the path is null or matching
        && (pathMatch(path, cookie.getPath()))
        // and if the secure flag is set, only if the request is 
        // actually secure 
        && (cookie.getSecure() ? secure : true);      
}
 
Example 7
Source File: RFC2109Spec.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
  * Performs RFC 2109 compliant {@link Cookie} validation
  *
  * @param host the host from which the {@link Cookie} was received
  * @param port the port from which the {@link Cookie} was received
  * @param path the path from which the {@link Cookie} was received
  * @param secure <tt>true</tt> when the {@link Cookie} was received using a
  * secure connection
  * @param cookie The cookie to validate
  * @throws MalformedCookieException if an exception occurs during
  * validation
  */
public void validate(String host, int port, String path, 
    boolean secure, final Cookie cookie) throws MalformedCookieException {
        
    LOG.trace("enter RFC2109Spec.validate(String, int, String, "
        + "boolean, Cookie)");
        
    // Perform generic validation
    super.validate(host, port, path, secure, cookie);
    // Perform RFC 2109 specific validation
    
    if (cookie.getName().indexOf(' ') != -1) {
        throw new MalformedCookieException("Cookie name may not contain blanks");
    }
    if (cookie.getName().startsWith("$")) {
        throw new MalformedCookieException("Cookie name may not start with $");
    }
    
    if (cookie.isDomainAttributeSpecified() 
        && (!cookie.getDomain().equals(host))) {
            
        // domain must start with dot
        if (!cookie.getDomain().startsWith(".")) {
            throw new MalformedCookieException("Domain attribute \"" 
                + cookie.getDomain() 
                + "\" violates RFC 2109: domain must start with a dot");
        }
        // domain must have at least one embedded dot
        int dotIndex = cookie.getDomain().indexOf('.', 1);
        if (dotIndex < 0 || dotIndex == cookie.getDomain().length() - 1) {
            throw new MalformedCookieException("Domain attribute \"" 
                + cookie.getDomain() 
                + "\" violates RFC 2109: domain must contain an embedded dot");
        }
        host = host.toLowerCase();
        if (!host.endsWith(cookie.getDomain())) {
            throw new MalformedCookieException(
                "Illegal domain attribute \"" + cookie.getDomain() 
                + "\". Domain of origin: \"" + host + "\"");
        }
        // host minus domain may not contain any dots
        String hostWithoutDomain = host.substring(0, host.length() 
            - cookie.getDomain().length());
        if (hostWithoutDomain.indexOf('.') != -1) {
            throw new MalformedCookieException("Domain attribute \"" 
                + cookie.getDomain() 
                + "\" violates RFC 2109: host minus domain may not contain any dots");
        }
    }
}
 
Example 8
Source File: Proxy.java    From odo with Apache License 2.0 4 votes vote down vote up
/**
 * Execute a request
 *
 * @param httpMethodProxyRequest
 * @param httpServletRequest
 * @param httpServletResponse
 * @param history
 * @throws Exception
 */
private void executeRequest(HttpMethod httpMethodProxyRequest,
                            HttpServletRequest httpServletRequest,
                            PluginResponse httpServletResponse,
                            History history) throws Exception {
    int intProxyResponseCode = 999;
    // Create a default HttpClient
    HttpClient httpClient = new HttpClient();
    HttpState state = new HttpState();

    try {
        httpMethodProxyRequest.setFollowRedirects(false);
        ArrayList<String> headersToRemove = getRemoveHeaders();

        httpClient.getParams().setSoTimeout(60000);

        httpServletRequest.setAttribute("com.groupon.odo.removeHeaders", headersToRemove);

        // exception handling for httpclient
        HttpMethodRetryHandler noretryhandler = new HttpMethodRetryHandler() {
            public boolean retryMethod(
                final HttpMethod method,
                final IOException exception,
                int executionCount) {
                return false;
            }
        };

        httpMethodProxyRequest.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noretryhandler);

        intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest.getHostConfiguration(), httpMethodProxyRequest, state);
    } catch (Exception e) {
        // Return a gateway timeout
        httpServletResponse.setStatus(504);
        httpServletResponse.setHeader(Constants.HEADER_STATUS, "504");
        httpServletResponse.flushBuffer();
        return;
    }
    logger.info("Response code: {}, {}", intProxyResponseCode,
                HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        // remove transfer-encoding header.  The http libraries will handle this encoding
        if (header.getName().toLowerCase().equals("transfer-encoding")) {
            continue;
        }

        httpServletResponse.setHeader(header.getName(), header.getValue());
    }

    // there is no data for a HTTP 304 or 204
    if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED &&
        intProxyResponseCode != HttpServletResponse.SC_NO_CONTENT) {
        // Send the content to the client
        httpServletResponse.resetBuffer();
        httpServletResponse.getOutputStream().write(httpMethodProxyRequest.getResponseBody());
    }

    // copy cookies to servlet response
    for (Cookie cookie : state.getCookies()) {
        javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());

        if (cookie.getPath() != null) {
            servletCookie.setPath(cookie.getPath());
        }

        if (cookie.getDomain() != null) {
            servletCookie.setDomain(cookie.getDomain());
        }

        // convert expiry date to max age
        if (cookie.getExpiryDate() != null) {
            servletCookie.setMaxAge((int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / 1000));
        }

        servletCookie.setSecure(cookie.getSecure());

        servletCookie.setVersion(cookie.getVersion());

        if (cookie.getComment() != null) {
            servletCookie.setComment(cookie.getComment());
        }

        httpServletResponse.addCookie(servletCookie);
    }
}