Search in sources :

Example 6 with ContentDisposition

use of com.zimbra.common.mime.ContentDisposition in project zm-mailbox by Zimbra.

the class CollectConfigFiles method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        //check the auth token
        AuthToken authToken = getAdminAuthTokenFromCookie(req, resp);
        if (authToken == null) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        if (!authToken.isAdmin()) {
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //take the host name
        Provisioning prov = Provisioning.getInstance();
        String hostName = req.getParameter(P_HOST);
        Server server = prov.get(Key.ServerBy.name, hostName);
        if (server == null) {
            throw ServiceException.INVALID_REQUEST("server with name " + hostName + " could not be found", null);
        }
        //call RemoteManager
        RemoteManager rmgr = RemoteManager.getRemoteManager(server);
        RemoteResult rr = rmgr.execute(RemoteCommands.COLLECT_CONFIG_FILES);
        //stream the data
        resp.setContentType(DOWNLOAD_CONTENT_TYPE);
        ContentDisposition cd = new ContentDisposition(Part.INLINE).setParameter("filename", hostName + ".conf.tgz");
        resp.addHeader("Content-Disposition", cd.toString());
        ByteUtil.copy(new ByteArrayInputStream(rr.getMStdout()), true, resp.getOutputStream(), false);
    } catch (ServiceException e) {
        returnError(resp, e);
        return;
    }
}
Also used : RemoteResult(com.zimbra.cs.rmgmt.RemoteResult) Server(com.zimbra.cs.account.Server) ContentDisposition(com.zimbra.common.mime.ContentDisposition) ServiceException(com.zimbra.common.service.ServiceException) ByteArrayInputStream(java.io.ByteArrayInputStream) RemoteManager(com.zimbra.cs.rmgmt.RemoteManager) AuthToken(com.zimbra.cs.account.AuthToken) Provisioning(com.zimbra.cs.account.Provisioning)

Example 7 with ContentDisposition

use of com.zimbra.common.mime.ContentDisposition in project zm-mailbox by Zimbra.

the class ImapMessage method ndisposition.

private static void ndisposition(PrintStream ps, String disposition) {
    if (disposition == null) {
        ps.print("NIL");
    } else {
        ContentDisposition cdisp = new ContentDisposition(disposition);
        ps.write('(');
        astring(ps, cdisp.getDisposition());
        ps.write(' ');
        nparams(ps, cdisp);
        ps.write(')');
    }
}
Also used : ContentDisposition(com.zimbra.common.mime.ContentDisposition)

Example 8 with ContentDisposition

use of com.zimbra.common.mime.ContentDisposition in project zm-mailbox by Zimbra.

the class FileUploadServlet method fetchRemoteUpload.

private static Upload fetchRemoteUpload(String accountId, String uploadId, AuthToken authtoken) throws ServiceException {
    // check if we have fetched the Upload from the remote server previously
    String localUploadId = null;
    synchronized (mProxiedUploadIds) {
        localUploadId = mProxiedUploadIds.get(uploadId);
    }
    if (localUploadId != null) {
        synchronized (mPending) {
            Upload up = mPending.get(localUploadId);
            if (up != null)
                return up;
        }
    }
    // the first half of the upload id is the server id where it lives
    Server server = Provisioning.getInstance().get(Key.ServerBy.id, getUploadServerId(uploadId));
    String url = AccountUtil.getBaseUri(server);
    if (url == null)
        return null;
    String hostname = server.getServiceHostname();
    url += ContentServlet.SERVLET_PATH + ContentServlet.PREFIX_PROXY + '?' + ContentServlet.PARAM_UPLOAD_ID + '=' + uploadId + '&' + ContentServlet.PARAM_EXPUNGE + "=true";
    // create an HTTP client with auth cookie to fetch the file from the remote ContentServlet
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    GetMethod get = new GetMethod(url);
    authtoken.encode(client, get, false, hostname);
    try {
        // fetch the remote item
        int statusCode = HttpClientUtil.executeMethod(client, get);
        if (statusCode != HttpStatus.SC_OK)
            return null;
        // metadata is encoded in the response's HTTP headers
        Header ctHeader = get.getResponseHeader("Content-Type");
        String contentType = ctHeader == null ? "text/plain" : ctHeader.getValue();
        Header cdispHeader = get.getResponseHeader("Content-Disposition");
        String filename = cdispHeader == null ? "unknown" : new ContentDisposition(cdispHeader.getValue()).getParameter("filename");
        // store the fetched upload along with original uploadId
        Upload up = saveUpload(get.getResponseBodyAsStream(), filename, contentType, accountId);
        synchronized (mProxiedUploadIds) {
            mProxiedUploadIds.put(uploadId, up.uuid);
        }
        return up;
    } catch (HttpException e) {
        throw ServiceException.PROXY_ERROR(e, url);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("can't fetch remote upload", e, new InternalArgument(ServiceException.URL, url, Argument.Type.STR));
    } finally {
        get.releaseConnection();
    }
}
Also used : Server(com.zimbra.cs.account.Server) Header(org.apache.commons.httpclient.Header) ContentDisposition(com.zimbra.common.mime.ContentDisposition) HttpClient(org.apache.commons.httpclient.HttpClient) InternalArgument(com.zimbra.common.service.ServiceException.InternalArgument) GetMethod(org.apache.commons.httpclient.methods.GetMethod) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 9 with ContentDisposition

use of com.zimbra.common.mime.ContentDisposition in project zm-mailbox by Zimbra.

the class UserServletContext method getRequestInputStream.

public InputStream getRequestInputStream(long limit) throws IOException, ServiceException, UserServletException {
    String contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM;
    String filename = null;
    InputStream is = null;
    final long DEFAULT_MAX_SIZE = 10 * 1024 * 1024;
    if (limit == 0) {
        if (req.getParameter("lbfums") != null) {
            limit = Provisioning.getInstance().getLocalServer().getLongAttr(Provisioning.A_zimbraFileUploadMaxSize, DEFAULT_MAX_SIZE);
        } else {
            limit = Provisioning.getInstance().getConfig().getLongAttr(Provisioning.A_zimbraMtaMaxMessageSize, DEFAULT_MAX_SIZE);
        }
    }
    boolean doCsrfCheck = false;
    if (req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK) != null) {
        doCsrfCheck = (Boolean) req.getAttribute(CsrfFilter.CSRF_TOKEN_CHECK);
    }
    if (ServletFileUpload.isMultipartContent(req)) {
        ServletFileUpload sfu = new ServletFileUpload();
        try {
            FileItemIterator iter = sfu.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream fis = iter.next();
                if (fis.isFormField()) {
                    is = fis.openStream();
                    params.put(fis.getFieldName(), new String(ByteUtil.getContent(is, -1), "UTF-8"));
                    if (doCsrfCheck && !this.csrfAuthSucceeded) {
                        String csrfToken = params.get(FileUploadServlet.PARAM_CSRF_TOKEN);
                        if (UserServlet.log.isDebugEnabled()) {
                            String paramValue = req.getParameter(UserServlet.QP_AUTH);
                            UserServlet.log.debug("CSRF check is: %s, CSRF token is: %s, Authentication recd with request is: %s", doCsrfCheck, csrfToken, paramValue);
                        }
                        if (!CsrfUtil.isValidCsrfToken(csrfToken, authToken)) {
                            setCsrfAuthSucceeded(Boolean.FALSE);
                            UserServlet.log.debug("CSRF token validation failed for account: %s" + ", Auth token is CSRF enabled:  %s" + "CSRF token is: %s", authToken, authToken.isCsrfTokenEnabled(), csrfToken);
                            throw new UserServletException(HttpServletResponse.SC_UNAUTHORIZED, L10nUtil.getMessage(MsgKey.errMustAuthenticate));
                        } else {
                            setCsrfAuthSucceeded(Boolean.TRUE);
                        }
                    }
                    is.close();
                    is = null;
                } else {
                    is = new UploadInputStream(fis.openStream(), limit);
                    break;
                }
            }
        } catch (UserServletException e) {
            throw new UserServletException(e.getHttpStatusCode(), e.getMessage(), e);
        } catch (Exception e) {
            throw new UserServletException(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, e.toString());
        }
        if (is == null)
            throw new UserServletException(HttpServletResponse.SC_NO_CONTENT, "No file content");
    } else {
        ContentType ctype = new ContentType(req.getContentType());
        String contentEncoding = req.getHeader("Content-Encoding");
        contentType = ctype.getContentType();
        filename = ctype.getParameter("name");
        if (filename == null || filename.trim().equals(""))
            filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename");
        is = new UploadInputStream(contentEncoding != null && contentEncoding.indexOf("gzip") != -1 ? new GZIPInputStream(req.getInputStream()) : req.getInputStream(), limit);
    }
    if (filename == null || filename.trim().equals(""))
        filename = "unknown";
    else
        params.put(UserServlet.UPLOAD_NAME, filename);
    params.put(UserServlet.UPLOAD_TYPE, contentType);
    ZimbraLog.mailbox.info("UserServlet received file %s - %d request bytes", filename, req.getContentLength());
    return is;
}
Also used : ContentType(com.zimbra.common.mime.ContentType) GZIPInputStream(java.util.zip.GZIPInputStream) InputStream(java.io.InputStream) ServiceException(com.zimbra.common.service.ServiceException) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ContentDisposition(com.zimbra.common.mime.ContentDisposition) FileItemStream(org.apache.commons.fileupload.FileItemStream) FileItemIterator(org.apache.commons.fileupload.FileItemIterator)

Example 10 with ContentDisposition

use of com.zimbra.common.mime.ContentDisposition in project zm-mailbox by Zimbra.

the class UUEncodeConverter method visitMessage.

@Override
protected boolean visitMessage(MimeMessage mm, VisitPhase visitKind) throws MessagingException {
    // do the decode in the exit phase
    if (visitKind != VisitPhase.VISIT_END)
        return false;
    MimeMultipart mmp = null;
    try {
        // only check "text/plain" parts for uudecodeable attachments
        if (!mm.isMimeType(MimeConstants.CT_TEXT_PLAIN))
            return false;
        // don't check transfer-encoded parts for uudecodeable attachments
        String cte = mm.getHeader("Content-Transfer-Encoding", null);
        if (cte != null) {
            cte = cte.trim().toLowerCase();
            if (!cte.equals(MimeConstants.ET_7BIT) && !cte.equals(MimeConstants.ET_8BIT) && !cte.equals(MimeConstants.ET_BINARY))
                return false;
        }
        List<UUDecodedFile> uufiles = null;
        // go through top-level text/plain part and extract uuencoded files
        PositionInputStream is = null;
        long size;
        try {
            is = new PositionInputStream(new BufferedInputStream(mm.getInputStream()));
            for (int c = is.read(); c != -1; ) {
                long start = is.getPosition() - 1;
                // check for uuencode header: "begin NNN filename"
                if (c == 'b' && (c = is.read()) == 'e' && (c = is.read()) == 'g' && (c = is.read()) == 'i' && (c = is.read()) == 'n' && ((c = is.read()) == ' ' || c == '\t') && Character.isDigit((c = is.read())) && Character.isDigit(c = is.read()) && Character.isDigit(c = is.read()) && ((c = is.read()) == ' ' || c == '\t')) {
                    StringBuilder sb = new StringBuilder();
                    while ((c = is.read()) != '\r' && c != '\n' && c != -1) sb.append((char) c);
                    String filename = FileUtil.trimFilename(sb.toString().trim());
                    if (c != -1 && filename.length() > 0) {
                        if (uufiles == null)
                            uufiles = new ArrayList<UUDecodedFile>(3);
                        try {
                            uufiles.add(new UUDecodedFile(is, filename, start));
                            // check to make sure that the caller's OK with altering the message
                            if (uufiles.size() == 1 && mCallback != null && !mCallback.onModification())
                                return false;
                        } catch (IOException ioe) {
                        }
                    }
                }
                // skip to the beginning of the next line
                while (c != '\r' && c != '\n' && c != -1) c = is.read();
                while (c == '\r' || c == '\n') c = is.read();
            }
            size = is.getPosition();
        } finally {
            ByteUtil.closeStream(is);
        }
        if (uufiles == null || uufiles.isEmpty())
            return false;
        // create MimeParts for the extracted files
        mmp = new ZMimeMultipart("mixed");
        for (UUDecodedFile uu : uufiles) {
            MimeBodyPart mbp = new ZMimeBodyPart();
            mbp.setHeader("Content-Type", uu.getContentType());
            mbp.setHeader("Content-Disposition", new ContentDisposition(Part.ATTACHMENT).setParameter("filename", uu.getFilename()).toString());
            mbp.setDataHandler(new DataHandler(uu.getDataSource()));
            mmp.addBodyPart(mbp);
            size -= uu.getEndOffset() - uu.getStartOffset();
        }
        // take the remaining text and put it in as the first "related" part
        InputStream isOrig = null;
        try {
            isOrig = mm.getInputStream();
            long offset = 0;
            ByteArrayOutputStream baos = new ByteArrayOutputStream((int) size);
            byte[] buffer = new byte[8192];
            for (UUDecodedFile uu : uufiles) {
                long count = uu.getStartOffset() - offset, numRead;
                while (count > 0 && (numRead = isOrig.read(buffer, 0, (int) Math.min(count, 8192))) >= 0) {
                    baos.write(buffer, 0, (int) numRead);
                    count -= numRead;
                }
                isOrig.skip(uu.getEndOffset() - uu.getStartOffset());
                offset = uu.getEndOffset();
            }
            ByteUtil.copy(isOrig, true, baos, true);
            MimeBodyPart mbp = new ZMimeBodyPart();
            mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(baos.toByteArray(), MimeConstants.CT_TEXT_PLAIN)));
            mmp.addBodyPart(mbp, 0);
        } finally {
            ByteUtil.closeStream(isOrig);
        }
    } catch (MessagingException e) {
        ZimbraLog.extensions.warn("exception while uudecoding message part; skipping part", e);
        return false;
    } catch (IOException e) {
        ZimbraLog.extensions.warn("exception while uudecoding message part; skipping part", e);
        return false;
    }
    // replace the top-level part with a new multipart/related
    mm.setContent(mmp);
    mm.setHeader("Content-Type", mmp.getContentType() + "; generated=true");
    return true;
}
Also used : ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MessagingException(javax.mail.MessagingException) BufferedInputStream(java.io.BufferedInputStream) PositionInputStream(com.zimbra.common.util.ByteUtil.PositionInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DataHandler(javax.activation.DataHandler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ContentDisposition(com.zimbra.common.mime.ContentDisposition) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) BufferedInputStream(java.io.BufferedInputStream) PositionInputStream(com.zimbra.common.util.ByteUtil.PositionInputStream) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Aggregations

ContentDisposition (com.zimbra.common.mime.ContentDisposition)18 ContentType (com.zimbra.common.mime.ContentType)8 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)8 IOException (java.io.IOException)7 MimeBodyPart (javax.mail.internet.MimeBodyPart)7 ServiceException (com.zimbra.common.service.ServiceException)6 DataHandler (javax.activation.DataHandler)6 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)5 MessagingException (javax.mail.MessagingException)5 MimeMessage (javax.mail.internet.MimeMessage)5 MimeMultipart (javax.mail.internet.MimeMultipart)5 Server (com.zimbra.cs.account.Server)4 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)4 AuthToken (com.zimbra.cs.account.AuthToken)3 Provisioning (com.zimbra.cs.account.Provisioning)3 InputStream (java.io.InputStream)3 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)3 Header (org.apache.commons.httpclient.Header)3 Attachment (com.zimbra.cs.mailbox.Contact.Attachment)2 MailServiceException (com.zimbra.cs.mailbox.MailServiceException)2