Search in sources :

Example 6 with ByteArrayRequestEntity

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

the class ProxyServlet method doProxy.

private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ZimbraLog.clearContext();
    boolean isAdmin = isAdminRequest(req);
    AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true) : getAuthTokenFromCookie(req, resp, true);
    if (authToken == null) {
        String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
        if (zAuthToken != null) {
            try {
                authToken = AuthProvider.getAuthToken(zAuthToken);
                if (authToken.isExpired()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
                    return;
                }
                if (!authToken.isRegistered()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
                    return;
                }
                if (isAdmin && !authToken.isAdmin()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
                    return;
                }
            } catch (AuthTokenException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
                return;
            }
        }
    }
    if (authToken == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
        return;
    }
    // get the posted body before the server read and parse them.
    byte[] body = copyPostedData(req);
    // sanity check
    String target = req.getParameter(TARGET_PARAM);
    if (target == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    // check for permission
    URL url = new URL(target);
    if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    // determine whether to return the target inline or store it as an upload
    String uploadParam = req.getParameter(UPLOAD_PARAM);
    boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));
    HttpMethod method = null;
    try {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        String reqMethod = req.getMethod();
        if (reqMethod.equalsIgnoreCase("GET")) {
            method = new GetMethod(target);
        } else if (reqMethod.equalsIgnoreCase("POST")) {
            PostMethod post = new PostMethod(target);
            if (body != null)
                post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = post;
        } else if (reqMethod.equalsIgnoreCase("PUT")) {
            PutMethod put = new PutMethod(target);
            if (body != null)
                put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = put;
        } else if (reqMethod.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(target);
        } else {
            ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
        // handle basic auth
        String auth, user, pass;
        auth = req.getParameter(AUTH_PARAM);
        user = req.getParameter(USER_PARAM);
        pass = req.getParameter(PASS_PARAM);
        if (auth != null && user != null && pass != null) {
            if (!auth.equals(AUTH_BASIC)) {
                ZimbraLog.zimlet.info("unsupported auth type: " + auth);
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            HttpState state = new HttpState();
            state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
            client.setState(state);
            method.setDoAuthentication(true);
        }
        Enumeration headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = (String) headers.nextElement();
            ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
            if (canProxyHeader(hdr)) {
                ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
                if (hdr.equalsIgnoreCase("x-host"))
                    method.getParams().setVirtualHost(req.getHeader(hdr));
                else
                    method.addRequestHeader(hdr, req.getHeader(hdr));
            }
        }
        try {
            if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
                method.setFollowRedirects(true);
            }
            HttpClientUtil.executeMethod(client, method);
        } catch (HttpException ex) {
            ZimbraLog.zimlet.info("exception while proxying " + target, ex);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR : method.getStatusCode();
        // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
        Header ctHeader = method.getResponseHeader("Content-Type");
        String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE : ctHeader.getValue();
        InputStream targetResponseBody = method.getResponseBodyAsStream();
        if (asUpload) {
            String filename = req.getParameter(FILENAME_PARAM);
            if (filename == null || filename.equals(""))
                filename = new ContentType(contentType).getParameter("name");
            if ((filename == null || filename.equals("")) && method.getResponseHeader("Content-Disposition") != null)
                filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue()).getParameter("filename");
            if (filename == null || filename.equals(""))
                filename = "unknown";
            List<Upload> uploads = null;
            if (targetResponseBody != null) {
                try {
                    Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType, authToken.getAccountId());
                    uploads = Arrays.asList(up);
                } catch (ServiceException e) {
                    if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
                        status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
                    else
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
            }
            resp.setStatus(status);
            FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
        } else {
            resp.setStatus(status);
            resp.setContentType(contentType);
            for (Header h : method.getResponseHeaders()) if (canProxyHeader(h.getName()))
                resp.addHeader(h.getName(), h.getValue());
            if (targetResponseBody != null)
                ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}
Also used : ContentType(com.zimbra.common.mime.ContentType) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) Upload(com.zimbra.cs.service.FileUploadServlet.Upload) URL(java.net.URL) HttpException(org.apache.commons.httpclient.HttpException) DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) Enumeration(java.util.Enumeration) InputStream(java.io.InputStream) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Header(org.apache.commons.httpclient.Header) ContentDisposition(com.zimbra.common.mime.ContentDisposition) ServiceException(com.zimbra.common.service.ServiceException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) AuthTokenException(com.zimbra.cs.account.AuthTokenException) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) AuthToken(com.zimbra.cs.account.AuthToken) PutMethod(org.apache.commons.httpclient.methods.PutMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 7 with ByteArrayRequestEntity

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

the class ExchangeFreeBusyProvider method formAuth.

private boolean formAuth(HttpClient client, ServerInfo info) throws IOException {
    StringBuilder buf = new StringBuilder();
    buf.append("destination=");
    buf.append(URLEncoder.encode(info.url, "UTF-8"));
    buf.append("&username=");
    buf.append(info.authUsername);
    buf.append("&password=");
    buf.append(URLEncoder.encode(info.authPassword, "UTF-8"));
    buf.append("&flags=0");
    buf.append("&SubmitCreds=Log On");
    buf.append("&trusted=0");
    String url = info.url + LC.calendar_exchange_form_auth_url.value();
    PostMethod method = new PostMethod(url);
    ByteArrayRequestEntity re = new ByteArrayRequestEntity(buf.toString().getBytes(), "x-www-form-urlencoded");
    method.setRequestEntity(re);
    HttpState state = new HttpState();
    client.setState(state);
    try {
        int status = HttpClientUtil.executeMethod(client, method);
        if (status >= 400) {
            ZimbraLog.fb.error("form auth to Exchange returned an error: " + status);
            return false;
        }
    } finally {
        method.releaseConnection();
    }
    return true;
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpState(org.apache.commons.httpclient.HttpState) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 8 with ByteArrayRequestEntity

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

the class TestCalDav method testMkcol4addressBook.

@Test
public void testMkcol4addressBook() throws Exception {
    String xml = "<D:mkcol xmlns:D=\"DAV:\" xmlns:C=\"urn:ietf:params:xml:ns:carddav\">" + "     <D:set>" + "       <D:prop>" + "         <D:resourcetype>" + "           <D:collection/>" + "           <C:addressbook/>" + "         </D:resourcetype>" + "         <D:displayname>OtherContacts</D:displayname>" + "         <C:addressbook-description xml:lang=\"en\">Extra Contacts</C:addressbook-description>" + "       </D:prop>" + "     </D:set>" + "</D:mkcol>";
    Account dav1 = users[1].create();
    StringBuilder url = getLocalServerRoot();
    url.append(DavServlet.DAV_PATH).append("/").append(dav1.getName()).append("/OtherContacts/");
    MkColMethod method = new MkColMethod(url.toString());
    addBasicAuthHeaderForUser(method, dav1);
    HttpClient client = new HttpClient();
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    method.setRequestEntity(new ByteArrayRequestEntity(xml.getBytes(), MimeConstants.CT_TEXT_XML));
    HttpMethodExecutor.execute(client, method, HttpStatus.SC_MULTI_STATUS);
    ZMailbox.Options options = new ZMailbox.Options();
    options.setAccount(dav1.getName());
    options.setAccountBy(AccountBy.name);
    options.setPassword(TestUtil.DEFAULT_PASSWORD);
    options.setUri(TestUtil.getSoapUrl());
    options.setNoSession(true);
    ZMailbox mbox = ZMailbox.getMailbox(options);
    ZFolder folder = mbox.getFolderByPath("/OtherContacts");
    assertEquals("OtherContacts", folder.getName());
    assertEquals("OtherContacts default view", View.contact, folder.getDefaultView());
}
Also used : Account(com.zimbra.cs.account.Account) ZMailbox(com.zimbra.client.ZMailbox) HttpClient(org.apache.commons.httpclient.HttpClient) ZFolder(com.zimbra.client.ZFolder) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) Test(org.junit.Test)

Example 9 with ByteArrayRequestEntity

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

the class TestCalDav method doFreeBusyCheck.

public HttpMethodExecutor doFreeBusyCheck(Account organizer, List<Account> attendees, Date start, Date end) throws ServiceException, IOException {
    HttpClient client = new HttpClient();
    String outboxurl = getSchedulingOutboxUrl(organizer, organizer);
    PostMethod postMethod = new PostMethod(outboxurl);
    postMethod.addRequestHeader("Content-Type", "text/calendar");
    postMethod.addRequestHeader("Originator", "mailto:" + organizer.getName());
    for (Account attendee : attendees) {
        postMethod.addRequestHeader("Recipient", "mailto:" + attendee.getName());
    }
    addBasicAuthHeaderForUser(postMethod, organizer);
    String fbIcal = makeFreeBusyRequestIcal(organizer, attendees, start, end);
    postMethod.setRequestEntity(new ByteArrayRequestEntity(fbIcal.getBytes(), MimeConstants.CT_TEXT_CALENDAR));
    return HttpMethodExecutor.execute(client, postMethod, HttpStatus.SC_OK);
}
Also used : Account(com.zimbra.cs.account.Account) PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 10 with ByteArrayRequestEntity

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

the class TestCalDav method setGroupMemberSet.

public static Document setGroupMemberSet(String url, Account acct, Account memberAcct) throws IOException, XmlParseException {
    PropPatchMethod method = new PropPatchMethod(url);
    addBasicAuthHeaderForUser(method, acct);
    HttpClient client = new HttpClient();
    TestCalDav.HttpMethodExecutor executor;
    method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML);
    String body = TestCalDav.propPatchGroupMemberSetTemplate.replace("%%MEMBER%%", UrlNamespace.getPrincipalUrl(memberAcct, memberAcct));
    method.setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), MimeConstants.CT_TEXT_XML));
    executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS);
    String respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    Document doc = W3cDomUtil.parseXMLToDoc(respBody);
    org.w3c.dom.Element docElement = doc.getDocumentElement();
    assertEquals("Report node name", DavElements.P_MULTISTATUS, docElement.getLocalName());
    return doc;
}
Also used : HttpClient(org.apache.commons.httpclient.HttpClient) Document(org.w3c.dom.Document) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Aggregations

ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)30 HttpClient (org.apache.commons.httpclient.HttpClient)20 PostMethod (org.apache.commons.httpclient.methods.PostMethod)11 Account (com.zimbra.cs.account.Account)9 PutMethod (org.apache.commons.httpclient.methods.PutMethod)8 Test (org.junit.Test)8 Header (org.apache.commons.httpclient.Header)5 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)5 Document (org.w3c.dom.Document)5 Element (com.zimbra.common.soap.Element)4 GetMethod (org.apache.commons.httpclient.methods.GetMethod)4 ZMailbox (com.zimbra.client.ZMailbox)3 HttpMethod (org.apache.commons.httpclient.HttpMethod)3 EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)3 SearchRequest (com.zimbra.soap.mail.message.SearchRequest)2 SearchResponse (com.zimbra.soap.mail.message.SearchResponse)2 SearchHit (com.zimbra.soap.type.SearchHit)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2