aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/crypto/PgpDecryptionService.java
blob: cc5e3fe7017fafd66e24dd2f860f29de8d6d23a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package de.pixart.messenger.crypto;

import android.app.PendingIntent;
import android.content.Intent;
import android.util.Log;

import org.openintents.openpgp.OpenPgpMetadata;
import org.openintents.openpgp.util.OpenPgpApi;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayDeque;
import java.util.HashSet;
import java.util.List;

import de.pixart.messenger.Config;
import de.pixart.messenger.entities.Conversation;
import de.pixart.messenger.entities.DownloadableFile;
import de.pixart.messenger.entities.Message;
import de.pixart.messenger.http.HttpConnectionManager;
import de.pixart.messenger.services.XmppConnectionService;
import de.pixart.messenger.utils.MimeUtils;

public class PgpDecryptionService {

    protected final ArrayDeque<Message> messages = new ArrayDeque<>();
    protected final HashSet<Message> pendingNotifications = new HashSet<>();
    private final XmppConnectionService mXmppConnectionService;
    private OpenPgpApi openPgpApi = null;
    private Message currentMessage;
    private PendingIntent pendingIntent;
    private Intent userInteractionResult;


    public PgpDecryptionService(XmppConnectionService service) {
        this.mXmppConnectionService = service;
    }

    public synchronized boolean decrypt(final Message message, boolean notify) {
        messages.add(message);
        if (notify && pendingIntent == null) {
            pendingNotifications.add(message);
            continueDecryption();
            return false;
        } else {
            continueDecryption();
            return notify;
        }
    }

    public synchronized void decrypt(final List<Message> list) {
        for (Message message : list) {
            if (message.getEncryption() == Message.ENCRYPTION_PGP) {
                messages.add(message);
            }
        }
        continueDecryption();
    }

    public synchronized void discard(List<Message> discards) {
        this.messages.removeAll(discards);
        this.pendingNotifications.removeAll(discards);
    }

    public synchronized void discard(Message message) {
        this.messages.remove(message);
        this.pendingNotifications.remove(message);
    }

    public void giveUpCurrentDecryption() {
        Message message;
        synchronized (this) {
            if (currentMessage != null) {
                return;
            }
            message = messages.peekFirst();
            if (message == null) {
                return;
            }
            discard(message);
        }
        synchronized (message) {
            if (message.getEncryption() == Message.ENCRYPTION_PGP) {
                message.setEncryption(Message.ENCRYPTION_DECRYPTION_FAILED);
            }
        }
        mXmppConnectionService.updateMessage(message, false);
        continueDecryption(true);
    }

    protected synchronized void decryptNext() {
        if (pendingIntent == null
                && getOpenPgpApi() != null
                && (currentMessage = messages.poll()) != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    executeApi(currentMessage);
                    decryptNext();
                }
            }).start();
        }
    }

    public synchronized void continueDecryption(boolean resetPending) {
        if (resetPending) {
            this.pendingIntent = null;
        }
        continueDecryption();
    }

    public synchronized void continueDecryption(Intent userInteractionResult) {
        this.pendingIntent = null;
        this.userInteractionResult = userInteractionResult;
        continueDecryption();
    }

    public synchronized void continueDecryption() {
        if (currentMessage == null) {
            decryptNext();
        }
    }

    private synchronized OpenPgpApi getOpenPgpApi() {
        if (openPgpApi == null) {
            this.openPgpApi = mXmppConnectionService.getOpenPgpApi();
        }
        return this.openPgpApi;
    }

    private void executeApi(Message message) {
        boolean skipNotificationPush = false;
        synchronized (message) {
            Intent params = userInteractionResult != null ? userInteractionResult : new Intent();
            params.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY);
            if (message.getType() == Message.TYPE_TEXT) {
                InputStream is = new ByteArrayInputStream(message.getBody().getBytes());
                final OutputStream os = new ByteArrayOutputStream();
                Intent result = getOpenPgpApi().executeApi(params, is, os);
                switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
                    case OpenPgpApi.RESULT_CODE_SUCCESS:
                        try {
                            os.flush();
                            final String body = os.toString();
                            if (body == null) {
                                throw new IOException("body was null");
                            }
                            message.setBody(body);
                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
                            final HttpConnectionManager manager = mXmppConnectionService.getHttpConnectionManager();
                            if (message.trusted()
                                    && message.treatAsDownloadable()
                                    && manager.getAutoAcceptFileSize() > 0) {
                                manager.createNewDownloadConnection(message);
                            }
                        } catch (IOException e) {
                            message.setEncryption(Message.ENCRYPTION_DECRYPTION_FAILED);
                        }
                        mXmppConnectionService.updateMessage(message);
                        break;
                    case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
                        synchronized (PgpDecryptionService.this) {
                            PendingIntent pendingIntent = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
                            messages.addFirst(message);
                            currentMessage = null;
                            storePendingIntent(pendingIntent);
                        }
                        break;
                    case OpenPgpApi.RESULT_CODE_ERROR:
                        message.setEncryption(Message.ENCRYPTION_DECRYPTION_FAILED);
                        mXmppConnectionService.updateMessage(message);
                        break;
                }
            } else if (message.isFileOrImage()) {
                try {
                    final DownloadableFile inputFile = mXmppConnectionService.getFileBackend().getFile(message, false);
                    final DownloadableFile outputFile = mXmppConnectionService.getFileBackend().getFile(message, true);
                    if (outputFile.getParentFile().mkdirs()) {
                        Log.d(Config.LOGTAG, "created parent directories for " + outputFile.getAbsolutePath());
                    }
                    outputFile.createNewFile();
                    InputStream is = new FileInputStream(inputFile);
                    OutputStream os = new FileOutputStream(outputFile);
                    Intent result = getOpenPgpApi().executeApi(params, is, os);
                    switch (result.getIntExtra(OpenPgpApi.RESULT_CODE, OpenPgpApi.RESULT_CODE_ERROR)) {
                        case OpenPgpApi.RESULT_CODE_SUCCESS:
                            OpenPgpMetadata openPgpMetadata = result.getParcelableExtra(OpenPgpApi.RESULT_METADATA);
                            String originalFilename = openPgpMetadata.getFilename();
                            String originalExtension = originalFilename == null ? null : MimeUtils.extractRelevantExtension(originalFilename);
                            if (originalExtension != null && MimeUtils.extractRelevantExtension(outputFile.getName()) == null) {
                                Log.d(Config.LOGTAG, "detected original filename during pgp decryption");
                                String mime = MimeUtils.guessMimeTypeFromExtension(originalExtension);
                                String path = outputFile.getName() + "." + originalExtension;
                                DownloadableFile fixedFile = mXmppConnectionService.getFileBackend().getFileForPath(path, mime);
                                if (fixedFile.getParentFile().mkdirs()) {
                                    Log.d(Config.LOGTAG, "created parent directories for " + fixedFile.getAbsolutePath());
                                }
                                if (outputFile.renameTo(fixedFile)) {
                                    Log.d(Config.LOGTAG, "renamed " + outputFile.getAbsolutePath() + " to " + fixedFile.getAbsolutePath());
                                    message.setRelativeFilePath(path);
                                }
                            }
                            URL url = message.getFileParams().url;
                            mXmppConnectionService.getFileBackend().updateFileParams(message, url);
                            message.setEncryption(Message.ENCRYPTION_DECRYPTED);
                            mXmppConnectionService.updateMessage(message);
                            if (!inputFile.delete()) {
                                Log.w(Config.LOGTAG, "unable to delete pgp encrypted source file " + inputFile.getAbsolutePath());
                            }
                            skipNotificationPush = true;
                            mXmppConnectionService.getFileBackend().updateMediaScanner(outputFile, () -> notifyIfPending(message));
                            break;
                        case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
                            synchronized (PgpDecryptionService.this) {
                                PendingIntent pendingIntent = result.getParcelableExtra(OpenPgpApi.RESULT_INTENT);
                                messages.addFirst(message);
                                currentMessage = null;
                                storePendingIntent(pendingIntent);
                            }
                            break;
                        case OpenPgpApi.RESULT_CODE_ERROR:
                            message.setEncryption(Message.ENCRYPTION_DECRYPTION_FAILED);
                            mXmppConnectionService.updateMessage(message);
                            break;
                    }
                } catch (final IOException e) {
                    message.setEncryption(Message.ENCRYPTION_DECRYPTION_FAILED);
                    mXmppConnectionService.updateMessage(message);
                }
            }
        }
        if (!skipNotificationPush) {
            notifyIfPending(message);
        }
    }

    private synchronized void notifyIfPending(Message message) {
        if (pendingNotifications.remove(message)) {
            mXmppConnectionService.getNotificationService().push(message);
        }
    }

    private void storePendingIntent(PendingIntent pendingIntent) {
        this.pendingIntent = pendingIntent;
        mXmppConnectionService.updateConversationUi();
    }

    public synchronized boolean hasPendingIntent(Conversation conversation) {
        if (pendingIntent == null) {
            return false;
        } else {
            for (Message message : messages) {
                if (message.getConversation() == conversation) {
                    return true;
                }
            }
            return false;
        }
    }

    public PendingIntent getPendingIntent() {
        return pendingIntent;
    }

    public boolean isConnected() {
        return getOpenPgpApi() != null;
    }
}