Example usage for org.apache.http.impl.cookie BasicClientCookie getDomain

List of usage examples for org.apache.http.impl.cookie BasicClientCookie getDomain

Introduction

In this page you can find the example usage for org.apache.http.impl.cookie BasicClientCookie getDomain.

Prototype

public String getDomain() 

Source Link

Document

Returns domain attribute of the cookie.

Usage

From source file:it.evilsocket.dsploit.core.System.java

public static String saveHijackerSession(String sessionName, Session session) throws IOException {
    StringBuilder builder = new StringBuilder();
    String filename = mStoragePath + '/' + sessionName + ".dhs", buffer = null;

    builder.append(SESSION_MAGIC + "\n");

    builder.append((session.mUserName == null ? "null" : session.mUserName) + "\n");
    builder.append(session.mHTTPS + "\n");
    builder.append(session.mAddress + "\n");
    builder.append(session.mDomain + "\n");
    builder.append(session.mUserAgent + "\n");
    builder.append(session.mCookies.size() + "\n");
    for (BasicClientCookie cookie : session.mCookies.values()) {
        builder.append(cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain()
                + "; path=/" + (session.mHTTPS ? ";secure" : "") + "\n");
    }/*from ww w .  java  2s.co m*/

    buffer = builder.toString();

    FileOutputStream ostream = new FileOutputStream(filename);
    GZIPOutputStream gzip = new GZIPOutputStream(ostream);

    gzip.write(buffer.getBytes());

    gzip.close();

    mSessionName = sessionName;

    return filename;
}

From source file:it.evilsocket.dsploit.plugins.mitm.hijacker.HijackerWebView.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    requestWindowFeature(Window.FEATURE_PROGRESS);
    setTitle(System.getCurrentTarget() + " > MITM > Session Hijacker");
    setContentView(R.layout.plugin_mitm_hijacker_webview);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    setSupportProgressBarIndeterminateVisibility(false);

    mWebView = (WebView) findViewById(R.id.webView);
    mSettings = mWebView.getSettings();//w w w.  jav  a2s.  c o  m

    mSettings.setJavaScriptEnabled(true);
    mSettings.setBuiltInZoomControls(true);
    mSettings.setAppCacheEnabled(false);
    mSettings.setUserAgentString(DEFAULT_USER_AGENT);

    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });

    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            if (mWebView != null)
                getSupportActionBar().setSubtitle(mWebView.getUrl());

            setSupportProgressBarIndeterminateVisibility(true);
            // Normalize our progress along the progress bar's scale
            int mmprogress = (Window.PROGRESS_END - Window.PROGRESS_START) / 100 * progress;
            setSupportProgress(mmprogress);

            if (progress == 100)
                setSupportProgressBarIndeterminateVisibility(false);
        }
    });

    CookieSyncManager.createInstance(this);
    CookieManager.getInstance().removeAllCookie();

    Session session = (Session) System.getCustomData();
    if (session != null) {
        String domain = null, rawcookie = null;

        for (BasicClientCookie cookie : session.mCookies.values()) {
            domain = cookie.getDomain();
            rawcookie = cookie.getName() + "=" + cookie.getValue() + "; domain=" + domain + "; path=/"
                    + (session.mHTTPS ? ";secure" : "");

            CookieManager.getInstance().setCookie(domain, rawcookie);
        }

        CookieSyncManager.getInstance().sync();

        if (session.mUserAgent != null && session.mUserAgent.isEmpty() == false)
            mSettings.setUserAgentString(session.mUserAgent);

        mWebView.loadUrl((session.mHTTPS ? "https" : "http") + "://www." + domain);
    }
}

From source file:ti.modules.titanium.network.NetworkModule.java

/**
 * Adds a cookie to the system cookie store. Any existing cookie with the same domain, path and name will be replaced with
 * the new cookie. The cookie being set must not have expired, otherwise it will be ignored.
 * @param cookieProxy the cookie to add/*from   ww w .  j  av a 2  s.com*/
 */
@Kroll.method
public void addSystemCookie(CookieProxy cookieProxy) {
    BasicClientCookie cookie = cookieProxy.getHTTPCookie();
    String cookieString = cookie.getName() + "=" + cookie.getValue();
    String domain = cookie.getDomain();
    if (domain == null) {
        Log.w(TAG, "Unable to add system cookie. Need to provide domain.");
        return;
    }
    cookieString += "; domain=" + domain;

    String path = cookie.getPath();
    Date expiryDate = cookie.getExpiryDate();
    boolean secure = cookie.isSecure();
    boolean httponly = TiConvert.toBoolean(cookieProxy.getProperty(TiC.PROPERTY_HTTP_ONLY), false);
    if (path != null) {
        cookieString += "; path=" + path;
    }
    if (expiryDate != null) {
        cookieString += "; expires=" + CookieProxy.systemExpiryDateFormatter.format(expiryDate);
    }
    if (secure) {
        cookieString += "; secure";
    }
    if (httponly) {
        cookieString += " httponly";
    }
    CookieSyncManager.createInstance(TiApplication.getInstance().getRootOrCurrentActivity());
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setCookie(domain, cookieString);
    CookieSyncManager.getInstance().sync();
}

From source file:com.intuit.karate.http.apache.ApacheHttpClient.java

@Override
protected void buildCookie(com.intuit.karate.http.Cookie c) {
    BasicClientCookie cookie = new BasicClientCookie(c.getName(), c.getValue());
    for (Entry<String, String> entry : c.entrySet()) {
        switch (entry.getKey()) {
        case DOMAIN:
            cookie.setDomain(entry.getValue());
            break;
        case PATH:
            cookie.setPath(entry.getValue());
            break;
        }//from   www  .j a  va 2 s.  c  om
    }
    if (cookie.getDomain() == null) {
        cookie.setDomain(uriBuilder.getHost());
    }
    cookieStore.addCookie(cookie);
}

From source file:org.archive.modules.fetcher.AbstractCookieStore.java

/**
 * Load cookies. The input is text in the Netscape's 'cookies.txt' file
 * format. Example entry of cookies.txt file:
 * <p>//  w w  w.  j  av  a  2  s  .c  o  m
 * www.archive.org FALSE / FALSE 1311699995 details-visit texts-cralond
 * </p>
 * <p>
 * Each line has 7 tab-separated fields:
 * </p>
 * <ol>
 * <li>DOMAIN: The domain that created and have access to the cookie value.</li>
 * <li>FLAG: A TRUE or FALSE value indicating if hosts within the given
 * domain can access the cookie value.</li>
 * <li>PATH: The path within the domain that the cookie value is valid for.</li>
 * <li>SECURE: A TRUE or FALSE value indicating if to use a secure
 * connection to access the cookie value.</li>
 * <li>EXPIRATION: The expiration time of the cookie value, or -1 for no
 * expiration</li>
 * <li>NAME: The name of the cookie value</li>
 * <li>VALUE: The cookie value</li>
 * </ol>
 *
 * @param reader
 *            input in the Netscape's 'cookies.txt' format.
 */
protected Collection<Cookie> readCookies(Reader reader) {
    LinkedList<Cookie> cookies = new LinkedList<Cookie>();
    BufferedReader br = new BufferedReader(reader);
    try {
        String line;
        int lineNo = 1;
        while ((line = br.readLine()) != null) {
            if (!line.matches("\\s*(?:#.*)?")) { // skip blank links and comments
                String[] tokens = line.split("\\t");
                if (tokens.length == 7) {
                    long epochSeconds = Long.parseLong(tokens[4]);
                    Date expirationDate = (epochSeconds >= 0 ? new Date(epochSeconds * 1000) : null);
                    BasicClientCookie cookie = new BasicClientCookie(tokens[5], tokens[6]);
                    cookie.setDomain(tokens[0]);
                    cookie.setExpiryDate(expirationDate);
                    cookie.setSecure(Boolean.valueOf(tokens[3]).booleanValue());
                    cookie.setPath(tokens[2]);
                    // XXX httpclient cookie doesn't have this thing?
                    // cookie.setDomainAttributeSpecified(Boolean.valueOf(tokens[1]).booleanValue());
                    logger.fine("Adding cookie: domain " + cookie.getDomain() + " cookie " + cookie);
                    cookies.add(cookie);
                } else {
                    logger.warning(
                            "cookies input line " + lineNo + " invalid, expected 7 tab-delimited tokens");
                }
            }

            lineNo++;
        }
    } catch (IOException e) {
        logger.log(Level.WARNING, e.getMessage(), e);
    }
    return cookies;
}

From source file:br.com.autonomiccs.apacheCloudStack.client.ApacheCloudStackClientTest.java

@Test
public void configureDomainForCookieTest() {
    BasicClientCookie basicClientCookie = new BasicClientCookie("name", "value");
    apacheCloudStackClient.configureDomainForCookie(basicClientCookie);

    Assert.assertEquals(cloudStackDomain, basicClientCookie.getDomain());
}

From source file:nl.esciencecenter.ptk.web.WebClient.java

protected void initJSession(boolean deletePrevious) throws WebException {
    logger.debugPrintf("initJSession(). Using JESSION URI init string:%s\n", config.jsessionInitPart);

    if (deletePrevious) {
        this.jsessionID = null;
    }/*  w ww . j  a  va2 s .c o m*/

    String uri = null;

    // re-use JSESSIONID:
    if (this.jsessionID != null) {

        BasicClientCookie cookie = new BasicClientCookie(WebConst.COOKIE_JSESSIONID, jsessionID);
        cookie.setPath(config.servicePath);
        cookie.setDomain(config.serverHostname);
        logger.infoPrintf(" - Using JSessionID   = %s\n", jsessionID);
        logger.debugPrintf(" - Cookie Domain/Path = %s/%s\n", cookie.getDomain(), cookie.getPath());

        this.httpClient.getCookieStore().addCookie(cookie);

        return;
    } else {
        logger.debugPrintf("initJSession():NO JSESSIONID\n");
    }

    try {
        uri = getServerURI().toString();

        // put slash between parts:
        if ((uri.endsWith("/") == false) && (config.servicePath.startsWith("/") == false)) {
            uri = uri + "/";
        }

        uri = uri + config.servicePath + "/" + config.jsessionInitPart;

        HttpPost postMethod = new HttpPost(uri);
        // get.setFollowRedirects(true);

        int result = executeAuthenticatedPut(postMethod, null, null);

        List<Cookie> cookies = this.httpClient.getCookieStore().getCookies();

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(WebConst.COOKIE_JSESSIONID)) {
                this.jsessionID = cookie.getValue();
                logger.infoPrintf(" - new JSessionID     = %s\n", jsessionID);
                logger.debugPrintf(" - Cookie Domain/Path = '%s','%s'\n", cookie.getDomain(), cookie.getPath());
            }
        }

        checkHttpStatus(result, "initJSession(): Couldn't initialize JSessionID.", null, null);

        // all ok here.
    } catch (WebException e) {
        Reason reason = e.getReason();

        if (reason == Reason.FORBIDDEN) {
            throw new WebException(reason, "Failed to authenticate: Forbidden.\n" + e.getMessage(), e);
        } else if (reason == Reason.UNAUTHORIZED) {
            if (this.config.useAuthentication() == false) {
                throw new WebException(reason,
                        "Need proper authentication for this service, but authentication is disabled for:"
                                + this.getServiceURI() + ".\n" + e.getMessage(),
                        e);
            }

            throw new WebException(reason, "Failed to authenticate: User or password wrong for URI:"
                    + this.getServiceURI() + ".\n" + e.getMessage(), e);
        } else {
            throw new WebException(reason,
                    "Failed to initialize JSession to: " + this.getServiceURI() + "\n" + e.getMessage(), e);
        }
    }
}

From source file:org.archive.modules.fetcher.CookieStoreTest.java

public void testConcurrentLoad() throws IOException, InterruptedException {
    bdbCookieStore().clear();//from   ww  w .j a va2  s  .c o  m
    basicCookieStore().clear();
    final Random rand = new Random();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                while (!Thread.interrupted()) {
                    BasicClientCookie cookie = new BasicClientCookie(UUID.randomUUID().toString(),
                            UUID.randomUUID().toString());
                    cookie.setDomain("d" + rand.nextInt(20) + ".example.com");
                    bdbCookieStore().addCookie(cookie);
                    basicCookieStore().addCookie(cookie);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };

    Thread[] threads = new Thread[200];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(runnable);
        threads[i].setName("cookie-load-test-" + i);
        threads[i].start();
    }

    Thread.sleep(1000);

    for (int i = 0; i < threads.length; i++) {
        threads[i].interrupt();
    }
    for (int i = 0; i < threads.length; i++) {
        threads[i].join();
    }

    ArrayList<Cookie> bdbCookieArrayList = new ArrayList<Cookie>(bdbCookieStore().getCookies());
    Map<String, Integer> domainCounts = new HashMap<String, Integer>();
    for (Cookie cookie : bdbCookieArrayList) {
        if (domainCounts.get(cookie.getDomain()) == null) {
            domainCounts.put(cookie.getDomain(), 1);
        } else {
            domainCounts.put(cookie.getDomain(), domainCounts.get(cookie.getDomain()) + 1);
        }
    }

    for (String domain : domainCounts.keySet()) {
        assertTrue(domainCounts.get(domain) <= BdbCookieStore.MAX_COOKIES_FOR_DOMAIN + 25);
    }
}

From source file:com.feigdev.webcom.PersistentCookieStore.java

/**
 * parseCookie() parses the cookieString which is a comma-separated list of
 * one or more cookies in the format of "NAME=VALUE; expires=DATE;
 * path=PATH; domain=DOMAIN_NAME; secure httponly" to a list of Cookies.
 * Here is a sample: IGDND=1, IGPC=ET=UB8TSNwtDmQ:AF=0; expires=Sun,
 * 17-Jan-2038 19:14:07 GMT; path=/ig; domain=.google.com, =,
 * PREF=ID=408909b1b304593d:TM=1156459854:LM=1156459854:S=V-vCAU6Sh-gobCfO;
 * expires=Sun, 17-Jan-2038 19:14:07 GMT; path=/; domain=.google.com which
 * contains 3 cookies IGDND, IGPC, PREF and an empty cookie
 * @param host The default host/*from  w w  w.j a v a 2 s. c  o m*/
 * @param path The default path
 * @param cookieString The string coming from "Set-Cookie:"
 * @return A list of Cookies
 */
private ArrayList<BasicClientCookie> parseCookie(String host, String path, String cookieString) {
    ArrayList<BasicClientCookie> ret = new ArrayList<BasicClientCookie>();

    int index = 0;
    int length = cookieString.length();
    while (true) {
        BasicClientCookie cookie = null;

        // done
        if (index < 0 || index >= length) {
            break;
        }

        // skip white space
        if (cookieString.charAt(index) == WHITE_SPACE) {
            index++;
            continue;
        }

        /*
         * get NAME=VALUE; pair. detecting the end of a pair is tricky, it
         * can be the end of a string, like "foo=bluh", it can be semicolon
         * like "foo=bluh;path=/"; or it can be enclosed by \", like
         * "foo=\"bluh bluh\";path=/"
         *
         * Note: in the case of "foo=bluh, bar=bluh;path=/", we interpret
         * it as one cookie instead of two cookies.
         */
        int semicolonIndex = cookieString.indexOf(SEMICOLON, index);
        int equalIndex = cookieString.indexOf(EQUAL, index);

        // Cookies like "testcookie; path=/;" are valid and used
        // (lovefilm.se).
        // Look for 2 cases:
        // 1. "foo" or "foo;" where equalIndex is -1
        // 2. "foo; path=..." where the first semicolon is before an equal
        //    and a semicolon exists.
        if ((semicolonIndex != -1 && (semicolonIndex < equalIndex)) || equalIndex == -1) {
            // Fix up the index in case we have a string like "testcookie"
            if (semicolonIndex == -1) {
                semicolonIndex = length;
            }
            cookie = new BasicClientCookie(cookieString.substring(index, semicolonIndex), null);
            cookie.setDomain(host);
            cookie.setPath(path);
        } else {
            cookie = new BasicClientCookie(cookieString.substring(index, equalIndex), null);
            cookie.setDomain(host);
            cookie.setPath(path);
            // Make sure we do not throw an exception if the cookie is like
            // "foo="
            if ((equalIndex < length - 1) && (cookieString.charAt(equalIndex + 1) == QUOTATION)) {
                index = cookieString.indexOf(QUOTATION, equalIndex + 2);
                if (index == -1) {
                    // bad format, force return
                    break;
                }
            }
            // Get the semicolon index again in case it was contained within
            // the quotations.
            semicolonIndex = cookieString.indexOf(SEMICOLON, index);
            if (semicolonIndex == -1) {
                semicolonIndex = length;
            }
            if (semicolonIndex - equalIndex > MAX_COOKIE_LENGTH) {
                // cookie is too big, trim it
                cookie.setValue(cookieString.substring(equalIndex + 1, equalIndex + 1 + MAX_COOKIE_LENGTH));
            } else if (equalIndex + 1 == semicolonIndex || semicolonIndex < equalIndex) {
                // this is an unusual case like "foo=;" or "foo="
                cookie.setValue("");
            } else {
                cookie.setValue(cookieString.substring(equalIndex + 1, semicolonIndex));
            }
        }
        // get attributes
        index = semicolonIndex;
        while (true) {
            // done
            if (index < 0 || index >= length) {
                break;
            }

            // skip white space and semicolon
            if (cookieString.charAt(index) == WHITE_SPACE || cookieString.charAt(index) == SEMICOLON) {
                index++;
                continue;
            }

            // comma means next cookie
            if (cookieString.charAt(index) == COMMA) {
                index++;
                break;
            }

            // "secure" is a known attribute doesn't use "=";
            // while sites like live.com uses "secure="
            if (length - index >= SECURE_LENGTH
                    && cookieString.substring(index, index + SECURE_LENGTH).equalsIgnoreCase(SECURE)) {
                index += SECURE_LENGTH;
                cookie.setSecure(true);
                if (index == length)
                    break;
                if (cookieString.charAt(index) == EQUAL)
                    index++;
                continue;
            }

            // "httponly" is a known attribute doesn't use "=";
            // while sites like live.com uses "httponly="
            if (length - index >= HTTP_ONLY_LENGTH
                    && cookieString.substring(index, index + HTTP_ONLY_LENGTH).equalsIgnoreCase(HTTP_ONLY)) {
                index += HTTP_ONLY_LENGTH;
                if (index == length)
                    break;
                if (cookieString.charAt(index) == EQUAL)
                    index++;
                // FIXME: currently only parse the attribute
                continue;
            }
            equalIndex = cookieString.indexOf(EQUAL, index);
            if (equalIndex > 0) {
                String name = cookieString.substring(index, equalIndex).toLowerCase();
                if (name.equals(EXPIRES)) {
                    int comaIndex = cookieString.indexOf(COMMA, equalIndex);

                    // skip ',' in (Wdy, DD-Mon-YYYY HH:MM:SS GMT) or
                    // (Weekday, DD-Mon-YY HH:MM:SS GMT) if it applies.
                    // "Wednesday" is the longest Weekday which has length 9
                    if ((comaIndex != -1) && (comaIndex - equalIndex <= 10)) {
                        index = comaIndex + 1;
                    }
                }
                semicolonIndex = cookieString.indexOf(SEMICOLON, index);
                int commaIndex = cookieString.indexOf(COMMA, index);
                if (semicolonIndex == -1 && commaIndex == -1) {
                    index = length;
                } else if (semicolonIndex == -1) {
                    index = commaIndex;
                } else if (commaIndex == -1) {
                    index = semicolonIndex;
                } else {
                    index = Math.min(semicolonIndex, commaIndex);
                }
                String value = cookieString.substring(equalIndex + 1, index);

                // Strip quotes if they exist
                if (value.length() > 2 && value.charAt(0) == QUOTATION) {
                    int endQuote = value.indexOf(QUOTATION, 1);
                    if (endQuote > 0) {
                        value = value.substring(1, endQuote);
                    }
                }
                if (name.equals(EXPIRES)) {
                    try {
                        cookie.setExpiryDate(new Date(AndroidHttpClient.parseDate(value)));
                    } catch (IllegalArgumentException ex) {
                        Log.e(LOGTAG, "illegal format for expires: " + value);
                    }
                } else if (name.equals(MAX_AGE)) {
                    try {
                        cookie.setExpiryDate(
                                new Date(System.currentTimeMillis() + 1000 * Long.parseLong(value)));
                    } catch (NumberFormatException ex) {
                        Log.e(LOGTAG, "illegal format for max-age: " + value);
                    }
                } else if (name.equals(PATH)) {
                    // only allow non-empty path value
                    if (value.length() > 0) {
                        cookie.setPath(value);
                    }
                } else if (name.equals(DOMAIN)) {
                    int lastPeriod = value.lastIndexOf(PERIOD);
                    if (lastPeriod == 0) {
                        // disallow cookies set for TLDs like [.com]
                        cookie.setDomain(null);
                        continue;
                    }
                    try {
                        Integer.parseInt(value.substring(lastPeriod + 1));
                        // no wildcard for ip address match
                        if (!value.equals(host)) {
                            // no cross-site cookie
                            cookie.setDomain(null);
                        }
                        continue;
                    } catch (NumberFormatException ex) {
                        // ignore the exception, value is a host name
                    }
                    value = value.toLowerCase();
                    if (value.charAt(0) != PERIOD) {
                        // pre-pended dot to make it as a domain cookie
                        value = PERIOD + value;
                        lastPeriod++;
                    }
                    if (host.endsWith(value.substring(1))) {
                        int len = value.length();
                        int hostLen = host.length();
                        if (hostLen > (len - 1) && host.charAt(hostLen - len) != PERIOD) {
                            // make sure the bar.com doesn't match .ar.com
                            cookie.setDomain(null);
                            continue;
                        }
                        // disallow cookies set on ccTLDs like [.co.uk]
                        if ((len == lastPeriod + 3) && (len >= 6 && len <= 8)) {
                            String s = value.substring(1, lastPeriod);
                            if (Arrays.binarySearch(BAD_COUNTRY_2LDS, s) >= 0) {
                                cookie.setDomain(null);
                                continue;
                            }
                        }
                        cookie.setDomain(value);
                    } else {
                        // no cross-site or more specific sub-domain cookie
                        cookie.setDomain(null);
                    }
                }
            } else {
                // bad format, force return
                index = length;
            }
        }
        if (cookie != null && cookie.getDomain() != null) {
            ret.add(cookie);
        }
    }
    return ret;
}