Search in sources :

Example 16 with Upload

use of com.zimbra.cs.service.FileUploadServlet.Upload in project zm-mailbox by Zimbra.

the class FileUploadServletTest method testConsecutiveFilenames.

@Test
public void testConsecutiveFilenames() throws Exception {
    ByteBuilder bb = new ByteBuilder(CharsetUtil.UTF_8);
    addFormField(bb, "_charset_", "");
    addFormField(bb, "filename1", filename1 + "\r\n" + filename2);
    addFormFile(bb, filename1, "text/plain", content1);
    addFormFile(bb, filename2, "text/plain", content2);
    addFormField(bb, "filename2", "");
    addFormFile(bb, "", null, null);
    addFormField(bb, "filename3", "");
    addFormFile(bb, "", null, null);
    endForm(bb);
    List<Upload> uploads = uploadForm(bb.toByteArray());
    Assert.assertEquals(2, uploads == null ? 0 : uploads.size());
    compareUploads(uploads.get(0), filename1, content1.getBytes(CharsetUtil.UTF_8));
    compareUploads(uploads.get(1), filename2, content2.getBytes(CharsetUtil.UTF_8));
}
Also used : ByteBuilder(com.zimbra.common.mime.HeaderUtils.ByteBuilder) Upload(com.zimbra.cs.service.FileUploadServlet.Upload) Test(org.junit.Test)

Example 17 with Upload

use of com.zimbra.cs.service.FileUploadServlet.Upload in project zm-mailbox by Zimbra.

the class ContentServlet method retrieveUpload.

private void retrieveUpload(HttpServletRequest req, HttpServletResponse resp, AuthToken authToken) throws IOException {
    // if it's another server fetching an already-uploaded file, just do that
    String uploadId = req.getParameter(PARAM_UPLOAD_ID);
    if (uploadId == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errMissingUploadId, req));
        return;
    }
    try {
        if (!FileUploadServlet.isLocalUpload(uploadId)) {
            // wrong server; proxy to the right one...
            String serverId = FileUploadServlet.getUploadServerId(uploadId);
            Server server = Provisioning.getInstance().get(Key.ServerBy.id, serverId);
            proxyServletRequest(req, resp, server, null);
            return;
        }
        Upload up = FileUploadServlet.fetchUpload(authToken.getAccountId(), uploadId, authToken);
        if (up == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errNoSuchUpload, req));
            return;
        }
        String filename = up.getName();
        ContentDisposition cd = new ContentDisposition(Part.ATTACHMENT).setParameter("filename", filename == null ? "unknown" : filename);
        resp.addHeader("Content-Disposition", cd.toString());
        sendbackOriginalDoc(up.getInputStream(), up.getContentType(), resp);
        boolean expunge = "true".equalsIgnoreCase(req.getParameter(PARAM_EXPUNGE)) || "1".equals(req.getParameter(PARAM_EXPUNGE));
        if (expunge)
            FileUploadServlet.deleteUpload(up);
    } catch (ServiceException e) {
        returnError(resp, e);
    }
}
Also used : Server(com.zimbra.cs.account.Server) ContentDisposition(com.zimbra.common.mime.ContentDisposition) ServiceException(com.zimbra.common.service.ServiceException) Upload(com.zimbra.cs.service.FileUploadServlet.Upload)

Example 18 with Upload

use of com.zimbra.cs.service.FileUploadServlet.Upload in project zm-mailbox by Zimbra.

the class BounceMsg method handle.

@Override
public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZimbraSoapContext zsc = getZimbraSoapContext(context);
    Account acct = getRequestedAccount(zsc);
    Mailbox mbox = getRequestedMailbox(zsc);
    OperationContext octxt = getOperationContext(zsc, context);
    Element msgElem = request.getElement(MailConstants.E_MSG);
    ItemId iid = new ItemId(msgElem.getAttribute(MailConstants.A_ID), zsc);
    MailSender msender = mbox.getMailSender().setSaveToSent(false).setRedirectMode(true).setSkipHeaderUpdate(true);
    Upload upload = null;
    try {
        InputStream is;
        if (iid.belongsTo(mbox)) {
            is = mbox.getMessageById(octxt, iid.getId()).getContentStream();
        } else if (iid.isLocal()) {
            Mailbox mboxSrc = MailboxManager.getInstance().getMailboxByAccountId(iid.getAccountId());
            is = mboxSrc.getMessageById(octxt, iid.getId()).getContentStream();
        } else {
            upload = UserServlet.getRemoteResourceAsUpload(zsc.getAuthToken(), iid, Maps.<String, String>newHashMap());
            is = upload.getInputStream();
        }
        ZMimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSmtpSession(acct), is);
        addResentHeaders(msgElem, mm, zsc, octxt, acct, msender);
        msender.sendMimeMessage(octxt, mbox, mm);
    } catch (MessagingException me) {
        throw ServiceException.FAILURE("error generating new message", me);
    } catch (IOException ioe) {
        throw ServiceException.FAILURE("error fetching remote message", ioe);
    } finally {
        // always want to delete the upload; msender.setUploads() deletes only on success
        if (upload != null) {
            FileUploadServlet.deleteUpload(upload);
        }
    }
    Element response = zsc.createElement(MailConstants.BOUNCE_MSG_RESPONSE);
    return response;
}
Also used : OperationContext(com.zimbra.cs.mailbox.OperationContext) Account(com.zimbra.cs.account.Account) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MessagingException(javax.mail.MessagingException) InputStream(java.io.InputStream) Element(com.zimbra.common.soap.Element) Upload(com.zimbra.cs.service.FileUploadServlet.Upload) MailSender(com.zimbra.cs.mailbox.MailSender) IOException(java.io.IOException) ItemId(com.zimbra.cs.service.util.ItemId) Mailbox(com.zimbra.cs.mailbox.Mailbox) ZimbraSoapContext(com.zimbra.soap.ZimbraSoapContext)

Example 19 with Upload

use of com.zimbra.cs.service.FileUploadServlet.Upload in project zm-mailbox by Zimbra.

the class DavServlet method service.

@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ZimbraLog.clearContext();
    addRemoteIpToLoggingContext(req);
    ZimbraLog.addUserAgentToContext(req.getHeader(DavProtocol.HEADER_USER_AGENT));
    //bug fix - send 400 for Range requests
    String rangeHeader = req.getHeader(DavProtocol.HEADER_RANGE);
    if (null != rangeHeader) {
        sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Range header not supported", null, Level.debug);
        return;
    }
    RequestType rtype = getAllowedRequestType(req);
    ZimbraLog.dav.debug("Allowable request types %s", rtype);
    if (rtype == RequestType.none) {
        sendError(resp, HttpServletResponse.SC_NOT_ACCEPTABLE, "Not an allowed request type", null, Level.debug);
        return;
    }
    logRequestInfo(req);
    Account authUser = null;
    DavContext ctxt;
    try {
        AuthToken at = AuthProvider.getAuthToken(req, false);
        if (at != null && (at.isExpired() || !at.isRegistered())) {
            at = null;
        }
        if (at != null && (rtype == RequestType.both || rtype == RequestType.authtoken)) {
            authUser = Provisioning.getInstance().get(AccountBy.id, at.getAccountId());
        } else if (at == null && (rtype == RequestType.both || rtype == RequestType.password)) {
            AuthUtil.AuthResult result = AuthUtil.basicAuthRequest(req, resp, true, this);
            if (result.sendErrorCalled) {
                logResponseInfo(resp);
                return;
            }
            authUser = result.authorizedAccount;
        }
        if (authUser == null) {
            try {
                sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Authentication failed", null, Level.debug);
            } catch (Exception e) {
            }
            return;
        }
        ZimbraLog.addToContext(ZimbraLog.C_ANAME, authUser.getName());
        ctxt = new DavContext(req, resp, authUser);
    } catch (AuthTokenException e) {
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error getting authenticated user", e);
        return;
    } catch (ServiceException e) {
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error getting authenticated user", e);
        return;
    }
    DavMethod method = sMethods.get(req.getMethod());
    if (method == null) {
        setAllowHeader(resp);
        sendError(resp, HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Not an allowed method", null, Level.debug);
        return;
    }
    long t0 = System.currentTimeMillis();
    CacheStates cache = null;
    try {
        if (ZimbraLog.dav.isDebugEnabled()) {
            try {
                Upload upload = ctxt.getUpload();
                if (upload.getSize() > 0 && upload.getContentType().startsWith("text")) {
                    if (ZimbraLog.dav.isDebugEnabled()) {
                        StringBuilder logMsg = new StringBuilder("REQUEST\n").append(new String(ByteUtil.readInput(upload.getInputStream(), -1, 20480), "UTF-8"));
                        ZimbraLog.dav.debug(logMsg.toString());
                    }
                }
            } catch (DavException de) {
                throw de;
            } catch (Exception e) {
                ZimbraLog.dav.debug("ouch", e);
            }
        }
        cache = checkCachedResponse(ctxt, authUser);
        if (!ctxt.isResponseSent() && !isProxyRequest(ctxt, method)) {
            method.checkPrecondition(ctxt);
            method.handle(ctxt);
            method.checkPostcondition(ctxt);
            if (!ctxt.isResponseSent()) {
                resp.setStatus(ctxt.getStatus());
            }
        }
        if (!ctxt.isResponseSent()) {
            logResponseInfo(resp);
        }
    } catch (DavException e) {
        if (e.getCause() instanceof MailServiceException.NoSuchItemException || e.getStatus() == HttpServletResponse.SC_NOT_FOUND)
            ZimbraLog.dav.info(ctxt.getUri() + " not found");
        else if (e.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY || e.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY)
            ZimbraLog.dav.info("sending redirect");
        try {
            if (e.isStatusSet()) {
                resp.setStatus(e.getStatus());
                if (e.hasErrorMessage())
                    e.writeErrorMsg(resp.getOutputStream());
                if (ZimbraLog.dav.isDebugEnabled()) {
                    ZimbraLog.dav.info("sending http error %d because: %s", e.getStatus(), e.getMessage(), e);
                } else {
                    ZimbraLog.dav.info("sending http error %d because: %s", e.getStatus(), e.getMessage());
                }
                if (e.getCause() != null)
                    ZimbraLog.dav.debug("exception: ", e.getCause());
            } else {
                sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error handling method " + method.getName(), e);
            }
        } catch (IllegalStateException ise) {
            ZimbraLog.dav.debug("can't write error msg", ise);
        }
    } catch (ServiceException e) {
        if (e instanceof MailServiceException.NoSuchItemException) {
            sendError(resp, HttpServletResponse.SC_NOT_FOUND, ctxt.getUri() + " not found", null, Level.info);
            return;
        }
        sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error handling method " + method.getName(), e);
    } catch (Exception e) {
        try {
            sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "error handling method " + method.getName(), e);
        } catch (Exception ex) {
        }
    } finally {
        long t1 = System.currentTimeMillis();
        ZimbraLog.dav.info("DavServlet operation " + method.getName() + " to " + req.getPathInfo() + " (depth: " + ctxt.getDepth().name() + ") finished in " + (t1 - t0) + "ms");
        if (cache != null)
            cacheCleanUp(ctxt, cache);
        ctxt.cleanup();
    }
}
Also used : Account(com.zimbra.cs.account.Account) DavException(com.zimbra.cs.dav.DavException) Upload(com.zimbra.cs.service.FileUploadServlet.Upload) ServletException(javax.servlet.ServletException) XmlParseException(com.zimbra.common.soap.XmlParseException) ServiceException(com.zimbra.common.service.ServiceException) IOException(java.io.IOException) AuthTokenException(com.zimbra.cs.account.AuthTokenException) DavException(com.zimbra.cs.dav.DavException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) ServiceException(com.zimbra.common.service.ServiceException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) AuthTokenException(com.zimbra.cs.account.AuthTokenException) AuthToken(com.zimbra.cs.account.AuthToken) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) DavContext(com.zimbra.cs.dav.DavContext)

Example 20 with Upload

use of com.zimbra.cs.service.FileUploadServlet.Upload in project zm-mailbox by Zimbra.

the class SendMsg method parseUploadedMessage.

static MimeMessage parseUploadedMessage(ZimbraSoapContext zsc, String attachId, MimeMessageData mimeData, boolean needCalendarSentByFixup) throws ServiceException {
    boolean anySystemMutators = MimeVisitor.anyMutatorsRegistered();
    Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), attachId, zsc.getAuthToken());
    if (up == null) {
        throw MailServiceException.NO_SUCH_UPLOAD(attachId);
    }
    (mimeData.uploads = new ArrayList<Upload>(1)).add(up);
    try {
        // if we may need to mutate the message, we can't use the "updateHeaders" hack...
        if (anySystemMutators || needCalendarSentByFixup) {
            MimeMessage mm = new ZMimeMessage(JMSession.getSession(), up.getInputStream());
            if (anySystemMutators) {
                return mm;
            }
            OutlookICalendarFixupMimeVisitor.ICalendarModificationCallback callback = new OutlookICalendarFixupMimeVisitor.ICalendarModificationCallback();
            MimeVisitor mv = new OutlookICalendarFixupMimeVisitor(getRequestedAccount(zsc), getRequestedMailbox(zsc)).needFixup(true).setCallback(callback);
            try {
                mv.accept(mm);
            } catch (MessagingException e) {
            }
            if (callback.wouldCauseModification()) {
                return mm;
            }
        }
        // ... but in general, for most installs this is safe
        return new ZMimeMessage(JMSession.getSession(), up.getInputStream()) {

            @Override
            protected void updateHeaders() throws MessagingException {
                setHeader("MIME-Version", "1.0");
                if (getMessageID() == null)
                    updateMessageID();
            }
        };
    } catch (MessagingException e) {
        throw MailServiceException.MESSAGE_PARSE_ERROR(e);
    } catch (IOException e) {
        throw ServiceException.FAILURE("IOException when parsing upload", e);
    }
}
Also used : ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) MimeVisitor(com.zimbra.cs.mime.MimeVisitor) Upload(com.zimbra.cs.service.FileUploadServlet.Upload) IOException(java.io.IOException)

Aggregations

Upload (com.zimbra.cs.service.FileUploadServlet.Upload)24 IOException (java.io.IOException)12 ServiceException (com.zimbra.common.service.ServiceException)6 Element (com.zimbra.common.soap.Element)5 ItemId (com.zimbra.cs.service.util.ItemId)5 ZimbraSoapContext (com.zimbra.soap.ZimbraSoapContext)5 InputStream (java.io.InputStream)5 ByteBuilder (com.zimbra.common.mime.HeaderUtils.ByteBuilder)4 MailServiceException (com.zimbra.cs.mailbox.MailServiceException)4 Mailbox (com.zimbra.cs.mailbox.Mailbox)4 Test (org.junit.Test)4 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)3 Account (com.zimbra.cs.account.Account)3 AuthToken (com.zimbra.cs.account.AuthToken)3 OperationContext (com.zimbra.cs.mailbox.OperationContext)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ZVCalendar (com.zimbra.common.calendar.ZCalendar.ZVCalendar)2 ContentDisposition (com.zimbra.common.mime.ContentDisposition)2 ContentType (com.zimbra.common.mime.ContentType)2 AuthTokenException (com.zimbra.cs.account.AuthTokenException)2