Search in sources :

Example 16 with HttpState

use of org.apache.commons.httpclient.HttpState in project zm-mailbox by Zimbra.

the class TestFileUpload method testAdminUploadWithCsrfInHeader.

@Test
public void testAdminUploadWithCsrfInHeader() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    String csrfToken = authResp.getCsrfToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    PostMethod post = new PostMethod(Url);
    FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes()));
    String contentType = "application/x-msdownload";
    part.setContentType(contentType);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpState state = new HttpState();
    state.addCookie(new org.apache.commons.httpclient.Cookie("localhost", ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setState(state);
    post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams()));
    post.addRequestHeader(Constants.CSRF_TOKEN, csrfToken);
    int statusCode = HttpClientUtil.executeMethod(client, post);
    Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
    String resp = post.getResponseBodyAsString();
    Assert.assertNotNull("Response should not be empty", resp);
    Assert.assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HeaderElement(org.apache.commons.httpclient.HeaderElement) Element(com.zimbra.common.soap.Element) HttpState(org.apache.commons.httpclient.HttpState) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ServiceException(com.zimbra.common.service.ServiceException) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) SoapHttpTransport(com.zimbra.common.soap.SoapHttpTransport) Test(org.junit.Test)

Example 17 with HttpState

use of org.apache.commons.httpclient.HttpState in project zm-mailbox by Zimbra.

the class TestFileUpload method testMissingCsrfAdminUpload.

@Test
public void testMissingCsrfAdminUpload() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    PostMethod post = new PostMethod(Url);
    FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes()));
    String contentType = "application/x-msdownload";
    part.setContentType(contentType);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpState state = new HttpState();
    state.addCookie(new org.apache.commons.httpclient.Cookie("localhost", ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setState(state);
    post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams()));
    int statusCode = HttpClientUtil.executeMethod(client, post);
    Assert.assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK, statusCode);
    String resp = post.getResponseBodyAsString();
    Assert.assertNotNull("Response should not be empty", resp);
    Assert.assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HeaderElement(org.apache.commons.httpclient.HeaderElement) Element(com.zimbra.common.soap.Element) HttpState(org.apache.commons.httpclient.HttpState) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) ByteArrayPartSource(org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource) ServiceException(com.zimbra.common.service.ServiceException) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) HttpClient(org.apache.commons.httpclient.HttpClient) SoapHttpTransport(com.zimbra.common.soap.SoapHttpTransport) Test(org.junit.Test)

Example 18 with HttpState

use of org.apache.commons.httpclient.HttpState in project zm-mailbox by Zimbra.

the class ZimbraServlet method proxyServletRequest.

public static void proxyServletRequest(HttpServletRequest req, HttpServletResponse resp, Server server, String uri, AuthToken authToken) throws IOException, ServiceException {
    if (server == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "cannot find remote server");
        return;
    }
    HttpMethod method;
    String url = getProxyUrl(req, server, uri);
    mLog.debug("Proxy URL = %s", url);
    if (req.getMethod().equalsIgnoreCase("GET")) {
        method = new GetMethod(url.toString());
    } else if (req.getMethod().equalsIgnoreCase("POST") || req.getMethod().equalsIgnoreCase("PUT")) {
        PostMethod post = new PostMethod(url.toString());
        post.setRequestEntity(new InputStreamRequestEntity(req.getInputStream()));
        method = post;
    } else {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "cannot proxy method: " + req.getMethod());
        return;
    }
    HttpState state = new HttpState();
    String hostname = method.getURI().getHost();
    if (authToken != null) {
        authToken.encode(state, false, hostname);
    }
    try {
        proxyServletRequest(req, resp, method, state);
    } finally {
        method.releaseConnection();
    }
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) PostMethod(org.apache.commons.httpclient.methods.PostMethod) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpState(org.apache.commons.httpclient.HttpState) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 19 with HttpState

use of org.apache.commons.httpclient.HttpState in project zm-mailbox by Zimbra.

the class TestAccessKeyGrant method testCalendarGet_guest.

/*
     * use zmmailbox to grant guest access:
     * zmmailbox -z -m user1@phoebe.mac mfg Calendar guest g1@guest.com zzz r
     */
public void testCalendarGet_guest() throws Exception {
    HttpState initialState = new HttpState();
    /*
        Cookie authCookie = new Cookie(restURL.getURL().getHost(), "ZM_AUTH_TOKEN", mAuthToken, "/", null, false);
        Cookie sessionCookie = new Cookie(restURL.getURL().getHost(), "JSESSIONID", mSessionId, "/zimbra", null, false);
        initialState.addCookie(authCookie);
        initialState.addCookie(sessionCookie);
        */
    String guestName = "g1@guest.com";
    String guestPassword = "zzz";
    Credentials loginCredentials = new UsernamePasswordCredentials(guestName, guestPassword);
    initialState.setCredentials(AuthScope.ANY, loginCredentials);
    HttpClient client = new HttpClient();
    client.setState(initialState);
    String url = getRestCalendarUrl(OWNER_NAME);
    System.out.println("REST URL: " + url);
    HttpMethod method = new GetMethod(url);
    executeHttpMethod(client, method);
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) HttpState(org.apache.commons.httpclient.HttpState) GetMethod(org.apache.commons.httpclient.methods.GetMethod) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) HttpMethod(org.apache.commons.httpclient.HttpMethod) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials)

Example 20 with HttpState

use of org.apache.commons.httpclient.HttpState in project zm-mailbox by Zimbra.

the class SpamExtract method extract.

private static void extract(String authToken, Account account, Server server, String query, File outdir, boolean delete, boolean raw) throws ServiceException, HttpException, SoapFaultException, IOException {
    String soapURL = getSoapURL(server, false);
    URL restURL = getServerURL(server, false);
    // CLI only, don't need conn mgr
    HttpClient hc = new HttpClient();
    HttpState state = new HttpState();
    GetMethod gm = new GetMethod();
    gm.setFollowRedirects(true);
    Cookie authCookie = new Cookie(restURL.getHost(), ZimbraCookie.COOKIE_ZM_AUTH_TOKEN, authToken, "/", -1, false);
    state.addCookie(authCookie);
    hc.setState(state);
    hc.getHostConfiguration().setHost(restURL.getHost(), restURL.getPort(), Protocol.getProtocol(restURL.getProtocol()));
    gm.getParams().setSoTimeout(60000);
    if (verbose) {
        LOG.info("Mailbox requests to: " + restURL);
    }
    SoapHttpTransport transport = new SoapHttpTransport(soapURL);
    transport.setRetryCount(1);
    transport.setTimeout(0);
    transport.setAuthToken(authToken);
    int totalProcessed = 0;
    boolean haveMore = true;
    int offset = 0;
    while (haveMore) {
        Element searchReq = new Element.XMLElement(MailConstants.SEARCH_REQUEST);
        searchReq.addElement(MailConstants.A_QUERY).setText(query);
        searchReq.addAttribute(MailConstants.A_SEARCH_TYPES, MailItem.Type.MESSAGE.toString());
        searchReq.addAttribute(MailConstants.A_QUERY_OFFSET, offset);
        searchReq.addAttribute(MailConstants.A_LIMIT, BATCH_SIZE);
        try {
            if (LOG.isDebugEnabled()) {
                LOG.debug(searchReq.prettyPrint());
            }
            Element searchResp = transport.invoke(searchReq, false, true, account.getId());
            if (LOG.isDebugEnabled()) {
                LOG.debug(searchResp.prettyPrint());
            }
            StringBuilder deleteList = new StringBuilder();
            List<String> ids = new ArrayList<String>();
            for (Iterator<Element> iter = searchResp.elementIterator(MailConstants.E_MSG); iter.hasNext(); ) {
                offset++;
                Element e = iter.next();
                String mid = e.getAttribute(MailConstants.A_ID);
                if (mid == null) {
                    LOG.warn("null message id SOAP response");
                    continue;
                }
                LOG.debug("adding id %s", mid);
                ids.add(mid);
                if (ids.size() >= BATCH_SIZE || !iter.hasNext()) {
                    StringBuilder path = new StringBuilder("/service/user/" + account.getName() + "/?fmt=tgz&list=" + StringUtils.join(ids, ","));
                    LOG.debug("sending request for path %s", path.toString());
                    List<String> extractedIds = extractMessages(hc, gm, path.toString(), outdir, raw);
                    if (ids.size() > extractedIds.size()) {
                        ids.removeAll(extractedIds);
                        LOG.warn("failed to extract %s", ids);
                    }
                    for (String id : extractedIds) {
                        deleteList.append(id).append(',');
                    }
                    ids.clear();
                }
                totalProcessed++;
            }
            haveMore = false;
            String more = searchResp.getAttribute(MailConstants.A_QUERY_MORE);
            if (more != null && more.length() > 0) {
                try {
                    int m = Integer.parseInt(more);
                    if (m > 0) {
                        haveMore = true;
                        try {
                            Thread.sleep(SLEEP_TIME);
                        } catch (InterruptedException e) {
                        }
                    }
                } catch (NumberFormatException nfe) {
                    LOG.warn("more flag from server not a number: " + more, nfe);
                }
            }
            if (delete && deleteList.length() > 0) {
                // -1 removes trailing comma
                deleteList.deleteCharAt(deleteList.length() - 1);
                Element msgActionReq = new Element.XMLElement(MailConstants.MSG_ACTION_REQUEST);
                Element action = msgActionReq.addElement(MailConstants.E_ACTION);
                action.addAttribute(MailConstants.A_ID, deleteList.toString());
                action.addAttribute(MailConstants.A_OPERATION, ItemAction.OP_HARD_DELETE);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(msgActionReq.prettyPrint());
                }
                Element msgActionResp = transport.invoke(msgActionReq, false, true, account.getId());
                if (LOG.isDebugEnabled()) {
                    LOG.debug(msgActionResp.prettyPrint());
                }
                //put offset back to 0 so we always get top N messages even after delete
                offset = 0;
            }
        } finally {
            gm.releaseConnection();
        }
    }
    LOG.info("Total messages processed: " + totalProcessed);
}
Also used : ZimbraCookie(com.zimbra.common.util.ZimbraCookie) Cookie(org.apache.commons.httpclient.Cookie) Element(com.zimbra.common.soap.Element) HttpState(org.apache.commons.httpclient.HttpState) ArrayList(java.util.ArrayList) URL(java.net.URL) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) SoapHttpTransport(com.zimbra.common.soap.SoapHttpTransport)

Aggregations

HttpState (org.apache.commons.httpclient.HttpState)33 HttpClient (org.apache.commons.httpclient.HttpClient)25 GetMethod (org.apache.commons.httpclient.methods.GetMethod)18 Test (org.junit.Test)13 ServiceException (com.zimbra.common.service.ServiceException)9 ZAuthToken (com.zimbra.common.auth.ZAuthToken)8 URI (java.net.URI)8 Cookie (org.apache.commons.httpclient.Cookie)8 PostMethod (org.apache.commons.httpclient.methods.PostMethod)8 ZMailbox (com.zimbra.client.ZMailbox)7 AuthToken (com.zimbra.cs.account.AuthToken)7 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)6 Account (com.zimbra.cs.account.Account)5 IOException (java.io.IOException)5 Map (java.util.Map)5 HttpMethod (org.apache.commons.httpclient.HttpMethod)5 Element (com.zimbra.common.soap.Element)4 SoapHttpTransport (com.zimbra.common.soap.SoapHttpTransport)4 ZimbraAuthToken (com.zimbra.cs.account.ZimbraAuthToken)4 ArrayList (java.util.ArrayList)4