Search in sources :

Example 1 with EOLConvertingOutputStream

use of com.fsck.k9.mail.filter.EOLConvertingOutputStream in project k-9 by k9mail.

the class PgpMessageBuilder method launchOpenPgpApiIntent.

private PendingIntent launchOpenPgpApiIntent(@NonNull Intent openPgpIntent, MimeBodyPart bodyPart, boolean captureOutputPart, boolean capturedOutputPartIs7Bit, boolean writeBodyContentOnly) throws MessagingException {
    OpenPgpDataSource dataSource = createOpenPgpDataSourceFromBodyPart(bodyPart, writeBodyContentOnly);
    BinaryTempFileBody pgpResultTempBody = null;
    OutputStream outputStream = null;
    if (captureOutputPart) {
        try {
            pgpResultTempBody = new BinaryTempFileBody(capturedOutputPartIs7Bit ? MimeUtil.ENC_7BIT : MimeUtil.ENC_8BIT);
            outputStream = pgpResultTempBody.getOutputStream();
            // OpenKeychain/BouncyCastle at this point use the system newline for formatting, which is LF on android.
            // we need this to be CRLF, so we convert the data after receiving.
            outputStream = new EOLConvertingOutputStream(outputStream);
        } catch (IOException e) {
            throw new MessagingException("could not allocate temp file for storage!", e);
        }
    }
    Intent result = openPgpApi.executeApi(openPgpIntent, dataSource, outputStream);
    switch(result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
        case OpenPgpApi.RESULT_CODE_SUCCESS:
            mimeBuildMessage(result, bodyPart, pgpResultTempBody);
            return null;
        case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
            PendingIntent returnedPendingIntent = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
            if (returnedPendingIntent == null) {
                throw new MessagingException("openpgp api needs user interaction, but returned no pendingintent!");
            }
            return returnedPendingIntent;
        case OpenPgpApi.RESULT_CODE_ERROR:
            OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
            if (error == null) {
                throw new MessagingException("internal openpgp api error");
            }
            /*
                boolean isOpportunisticError = error.getErrorId() == OpenPgpError.OPPORTUNISTIC_MISSING_KEYS;
                if (isOpportunisticError) {
                    if (!cryptoStatus.isEncryptionOpportunistic()) {
                        throw new IllegalStateException(
                                "Got opportunistic error, but encryption wasn't supposed to be opportunistic!");
                    }
                    Timber.d("Skipping encryption due to opportunistic mode");
                    return null;
                }
                */
            throw new MessagingException(error.getMessage());
    }
    throw new IllegalStateException("unreachable code segment reached");
}
Also used : EOLConvertingOutputStream(com.fsck.k9.mail.filter.EOLConvertingOutputStream) BinaryTempFileBody(com.fsck.k9.mail.internet.BinaryTempFileBody) MessagingException(com.fsck.k9.mail.MessagingException) EOLConvertingOutputStream(com.fsck.k9.mail.filter.EOLConvertingOutputStream) OutputStream(java.io.OutputStream) OpenPgpDataSource(org.openintents.openpgp.util.OpenPgpApi.OpenPgpDataSource) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) IOException(java.io.IOException) PendingIntent(android.app.PendingIntent) OpenPgpError(org.openintents.openpgp.OpenPgpError)

Example 2 with EOLConvertingOutputStream

use of com.fsck.k9.mail.filter.EOLConvertingOutputStream in project k-9 by k9mail.

the class Message method calculateSize.

public long calculateSize() {
    try (CountingOutputStream out = new CountingOutputStream()) {
        EOLConvertingOutputStream eolOut = new EOLConvertingOutputStream(out);
        writeTo(eolOut);
        eolOut.flush();
        return out.getCount();
    } catch (IOException | MessagingException e) {
        Timber.e(e, "Failed to calculate a message size");
    }
    return 0;
}
Also used : EOLConvertingOutputStream(com.fsck.k9.mail.filter.EOLConvertingOutputStream) CountingOutputStream(com.fsck.k9.mail.filter.CountingOutputStream) IOException(java.io.IOException)

Example 3 with EOLConvertingOutputStream

use of com.fsck.k9.mail.filter.EOLConvertingOutputStream in project k-9 by k9mail.

the class WebDavFolder method appendWebDavMessages.

public List<WebDavMessage> appendWebDavMessages(List<Message> messages) throws MessagingException {
    List<WebDavMessage> retMessages = new ArrayList<>(messages.size());
    WebDavHttpClient httpclient = store.getHttpClient();
    for (Message message : messages) {
        HttpGeneric httpmethod;
        HttpResponse response;
        StringEntity bodyEntity;
        int statusCode;
        try {
            ByteArrayOutputStream out;
            long size = message.getSize();
            if (size > Integer.MAX_VALUE) {
                throw new MessagingException("message size > Integer.MAX_VALUE!");
            }
            out = new ByteArrayOutputStream((int) size);
            open();
            EOLConvertingOutputStream msgOut = new EOLConvertingOutputStream(new BufferedOutputStream(out, 1024));
            message.writeTo(msgOut);
            msgOut.flush();
            bodyEntity = new StringEntity(out.toString(), "UTF-8");
            bodyEntity.setContentType("message/rfc822");
            String messageURL = mFolderUrl;
            if (!messageURL.endsWith("/")) {
                messageURL += "/";
            }
            messageURL += encodeUtf8(message.getUid() + ":" + System.currentTimeMillis() + ".eml");
            Timber.i("Uploading message as %s", messageURL);
            store.sendRequest(messageURL, "PUT", bodyEntity, null, true);
            WebDavMessage retMessage = new WebDavMessage(message.getUid(), this);
            retMessage.setUrl(messageURL);
            retMessages.add(retMessage);
        } catch (Exception e) {
            throw new MessagingException("Unable to append", e);
        }
    }
    return retMessages;
}
Also used : EOLConvertingOutputStream(com.fsck.k9.mail.filter.EOLConvertingOutputStream) Message(com.fsck.k9.mail.Message) MessagingException(com.fsck.k9.mail.MessagingException) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) MessagingException(com.fsck.k9.mail.MessagingException) StringEntity(org.apache.http.entity.StringEntity) BufferedOutputStream(java.io.BufferedOutputStream)

Example 4 with EOLConvertingOutputStream

use of com.fsck.k9.mail.filter.EOLConvertingOutputStream in project k-9 by k9mail.

the class ImapFolder method appendMessages.

/**
     * Appends the given messages to the selected folder.
     *
     * <p>
     * This implementation also determines the new UIDs of the given messages on the IMAP
     * server and changes the messages' UIDs to the new server UIDs.
     * </p>
     *
     * @param messages
     *         The messages to append to the folder.
     *
     * @return The mapping of original message UIDs to the new server UIDs.
     */
@Override
public Map<String, String> appendMessages(List<? extends Message> messages) throws MessagingException {
    open(OPEN_MODE_RW);
    checkOpen();
    try {
        Map<String, String> uidMap = new HashMap<>();
        for (Message message : messages) {
            long messageSize = message.calculateSize();
            String encodeFolderName = folderNameCodec.encode(getPrefixedName());
            String escapedFolderName = ImapUtility.encodeString(encodeFolderName);
            String command = String.format(Locale.US, "APPEND %s (%s) {%d}", escapedFolderName, combineFlags(message.getFlags()), messageSize);
            connection.sendCommand(command, false);
            ImapResponse response;
            do {
                response = connection.readResponse();
                handleUntaggedResponse(response);
                if (response.isContinuationRequested()) {
                    EOLConvertingOutputStream eolOut = new EOLConvertingOutputStream(connection.getOutputStream());
                    message.writeTo(eolOut);
                    eolOut.write('\r');
                    eolOut.write('\n');
                    eolOut.flush();
                }
            } while (response.getTag() == null);
            if (response.size() > 1) {
                /*
                     * If the server supports UIDPLUS, then along with the APPEND response it
                     * will return an APPENDUID response code, e.g.
                     *
                     * 11 OK [APPENDUID 2 238268] APPEND completed
                     *
                     * We can use the UID included in this response to update our records.
                     */
                Object responseList = response.get(1);
                if (responseList instanceof ImapList) {
                    ImapList appendList = (ImapList) responseList;
                    if (appendList.size() >= 3 && appendList.getString(0).equals("APPENDUID")) {
                        String newUid = appendList.getString(2);
                        if (!TextUtils.isEmpty(newUid)) {
                            message.setUid(newUid);
                            uidMap.put(message.getUid(), newUid);
                            continue;
                        }
                    }
                }
            }
            /*
                 * This part is executed in case the server does not support UIDPLUS or does
                 * not implement the APPENDUID response code.
                 */
            String newUid = getUidFromMessageId(message);
            if (K9MailLib.isDebug()) {
                Log.d(LOG_TAG, "Got UID " + newUid + " for message for " + getLogId());
            }
            if (!TextUtils.isEmpty(newUid)) {
                uidMap.put(message.getUid(), newUid);
                message.setUid(newUid);
            }
        }
        /*
             * We need uidMap to be null if new UIDs are not available to maintain consistency
             * with the behavior of other similar methods (copyMessages, moveMessages) which
             * return null.
             */
        return (uidMap.isEmpty()) ? null : uidMap;
    } catch (IOException ioe) {
        throw ioExceptionHandler(connection, ioe);
    }
}
Also used : EOLConvertingOutputStream(com.fsck.k9.mail.filter.EOLConvertingOutputStream) Message(com.fsck.k9.mail.Message) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException)

Example 5 with EOLConvertingOutputStream

use of com.fsck.k9.mail.filter.EOLConvertingOutputStream in project k-9 by k9mail.

the class PgpMessageBuilder method launchOpenPgpApiIntent.

private PendingIntent launchOpenPgpApiIntent(@NonNull Intent openPgpIntent, boolean captureOutputPart, boolean capturedOutputPartIs7Bit, boolean writeBodyContentOnly) throws MessagingException {
    final MimeBodyPart bodyPart = currentProcessedMimeMessage.toBodyPart();
    String[] contentType = currentProcessedMimeMessage.getHeader(MimeHeader.HEADER_CONTENT_TYPE);
    if (contentType.length > 0) {
        bodyPart.setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType[0]);
    }
    OpenPgpDataSource dataSource = createOpenPgpDataSourceFromBodyPart(bodyPart, writeBodyContentOnly);
    BinaryTempFileBody pgpResultTempBody = null;
    OutputStream outputStream = null;
    if (captureOutputPart) {
        try {
            pgpResultTempBody = new BinaryTempFileBody(capturedOutputPartIs7Bit ? MimeUtil.ENC_7BIT : MimeUtil.ENC_8BIT);
            outputStream = pgpResultTempBody.getOutputStream();
            // OpenKeychain/BouncyCastle at this point use the system newline for formatting, which is LF on android.
            // we need this to be CRLF, so we convert the data after receiving.
            outputStream = new EOLConvertingOutputStream(outputStream);
        } catch (IOException e) {
            throw new MessagingException("could not allocate temp file for storage!", e);
        }
    }
    Intent result = openPgpApi.executeApi(openPgpIntent, dataSource, outputStream);
    switch(result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
        case OpenPgpApi.RESULT_CODE_SUCCESS:
            mimeBuildMessage(result, bodyPart, pgpResultTempBody);
            return null;
        case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
            PendingIntent returnedPendingIntent = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
            if (returnedPendingIntent == null) {
                throw new MessagingException("openpgp api needs user interaction, but returned no pendingintent!");
            }
            return returnedPendingIntent;
        case OpenPgpApi.RESULT_CODE_ERROR:
            OpenPgpError error = result.getParcelableExtra(OpenPgpApi.RESULT_ERROR);
            if (error == null) {
                throw new MessagingException("internal openpgp api error");
            }
            boolean isOpportunisticError = error.getErrorId() == OpenPgpError.OPPORTUNISTIC_MISSING_KEYS;
            if (isOpportunisticError) {
                if (!cryptoStatus.isEncryptionOpportunistic()) {
                    throw new IllegalStateException("Got opportunistic error, but encryption wasn't supposed to be opportunistic!");
                }
                Timber.d("Skipping encryption due to opportunistic mode");
                return null;
            }
            throw new MessagingException(error.getMessage());
    }
    throw new IllegalStateException("unreachable code segment reached");
}
Also used : EOLConvertingOutputStream(com.fsck.k9.mail.filter.EOLConvertingOutputStream) MessagingException(com.fsck.k9.mail.MessagingException) EOLConvertingOutputStream(com.fsck.k9.mail.filter.EOLConvertingOutputStream) OutputStream(java.io.OutputStream) OpenPgpDataSource(org.openintents.openpgp.util.OpenPgpApi.OpenPgpDataSource) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) IOException(java.io.IOException) BinaryTempFileBody(com.fsck.k9.mail.internet.BinaryTempFileBody) PendingIntent(android.app.PendingIntent) OpenPgpError(org.openintents.openpgp.OpenPgpError) MimeBodyPart(com.fsck.k9.mail.internet.MimeBodyPart)

Aggregations

EOLConvertingOutputStream (com.fsck.k9.mail.filter.EOLConvertingOutputStream)8 IOException (java.io.IOException)8 MessagingException (com.fsck.k9.mail.MessagingException)6 Message (com.fsck.k9.mail.Message)3 URISyntaxException (java.net.URISyntaxException)3 PendingIntent (android.app.PendingIntent)2 Intent (android.content.Intent)2 Address (com.fsck.k9.mail.Address)2 AuthenticationFailedException (com.fsck.k9.mail.AuthenticationFailedException)2 CertificateValidationException (com.fsck.k9.mail.CertificateValidationException)2 LineWrapOutputStream (com.fsck.k9.mail.filter.LineWrapOutputStream)2 SmtpDataStuffing (com.fsck.k9.mail.filter.SmtpDataStuffing)2 BinaryTempFileBody (com.fsck.k9.mail.internet.BinaryTempFileBody)2 BufferedOutputStream (java.io.BufferedOutputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 OutputStream (java.io.OutputStream)2 Inet6Address (java.net.Inet6Address)2 InetAddress (java.net.InetAddress)2 InetSocketAddress (java.net.InetSocketAddress)2 SocketAddress (java.net.SocketAddress)2