ExportBackupService.java

  1package eu.siacs.conversations.services;
  2
  3import android.app.Notification;
  4import android.app.NotificationManager;
  5import android.app.PendingIntent;
  6import android.app.Service;
  7import android.content.Context;
  8import android.content.Intent;
  9import android.database.Cursor;
 10import android.database.DatabaseUtils;
 11import android.database.sqlite.SQLiteDatabase;
 12import android.net.Uri;
 13import android.os.IBinder;
 14import androidx.core.app.NotificationCompat;
 15import android.util.Log;
 16
 17import com.google.common.base.Strings;
 18
 19import java.io.DataOutputStream;
 20import java.io.File;
 21import java.io.FileOutputStream;
 22import java.io.PrintWriter;
 23import java.security.NoSuchAlgorithmException;
 24import java.security.SecureRandom;
 25import java.security.spec.InvalidKeySpecException;
 26import java.util.ArrayList;
 27import java.util.Arrays;
 28import java.util.Collections;
 29import java.util.List;
 30import java.util.concurrent.atomic.AtomicBoolean;
 31import java.util.zip.GZIPOutputStream;
 32
 33import javax.crypto.Cipher;
 34import javax.crypto.CipherOutputStream;
 35import javax.crypto.SecretKeyFactory;
 36import javax.crypto.spec.IvParameterSpec;
 37import javax.crypto.spec.PBEKeySpec;
 38import javax.crypto.spec.SecretKeySpec;
 39
 40import eu.siacs.conversations.Config;
 41import eu.siacs.conversations.R;
 42import eu.siacs.conversations.crypto.axolotl.SQLiteAxolotlStore;
 43import eu.siacs.conversations.entities.Account;
 44import eu.siacs.conversations.entities.Conversation;
 45import eu.siacs.conversations.entities.Message;
 46import eu.siacs.conversations.persistance.DatabaseBackend;
 47import eu.siacs.conversations.persistance.FileBackend;
 48import eu.siacs.conversations.utils.BackupFileHeader;
 49import eu.siacs.conversations.utils.Compatibility;
 50
 51public class ExportBackupService extends Service {
 52
 53    public static final String KEYTYPE = "AES";
 54    public static final String CIPHERMODE = "AES/GCM/NoPadding";
 55    public static final String PROVIDER = "BC";
 56
 57    public static final String MIME_TYPE = "application/vnd.conversations.backup";
 58
 59    private static final int NOTIFICATION_ID = 19;
 60    private static final int PAGE_SIZE = 20;
 61    private static final AtomicBoolean RUNNING = new AtomicBoolean(false);
 62    private DatabaseBackend mDatabaseBackend;
 63    private List<Account> mAccounts;
 64    private NotificationManager notificationManager;
 65
 66    private static List<Intent> getPossibleFileOpenIntents(final Context context, final String path) {
 67
 68        //http://www.openintents.org/action/android-intent-action-view/file-directory
 69        //do not use 'vnd.android.document/directory' since this will trigger system file manager
 70        final Intent openIntent = new Intent(Intent.ACTION_VIEW);
 71        openIntent.addCategory(Intent.CATEGORY_DEFAULT);
 72        if (Compatibility.runsAndTargetsTwentyFour(context)) {
 73            openIntent.setType("resource/folder");
 74        } else {
 75            openIntent.setDataAndType(Uri.parse("file://" + path), "resource/folder");
 76        }
 77        openIntent.putExtra("org.openintents.extra.ABSOLUTE_PATH", path);
 78
 79        final Intent amazeIntent = new Intent(Intent.ACTION_VIEW);
 80        amazeIntent.setDataAndType(Uri.parse("com.amaze.filemanager:" + path), "resource/folder");
 81
 82        //will open a file manager at root and user can navigate themselves
 83        final Intent systemFallBack = new Intent(Intent.ACTION_VIEW);
 84        systemFallBack.addCategory(Intent.CATEGORY_DEFAULT);
 85        systemFallBack.setData(Uri.parse("content://com.android.externalstorage.documents/root/primary"));
 86
 87        return Arrays.asList(openIntent, amazeIntent, systemFallBack);
 88    }
 89
 90    private static void accountExport(final SQLiteDatabase db, final String uuid, final PrintWriter writer) {
 91        final StringBuilder builder = new StringBuilder();
 92        final Cursor accountCursor = db.query(Account.TABLENAME, null, Account.UUID + "=?", new String[]{uuid}, null, null, null);
 93        while (accountCursor != null && accountCursor.moveToNext()) {
 94            builder.append("INSERT INTO ").append(Account.TABLENAME).append("(");
 95            for (int i = 0; i < accountCursor.getColumnCount(); ++i) {
 96                if (i != 0) {
 97                    builder.append(',');
 98                }
 99                builder.append(accountCursor.getColumnName(i));
100            }
101            builder.append(") VALUES(");
102            for (int i = 0; i < accountCursor.getColumnCount(); ++i) {
103                if (i != 0) {
104                    builder.append(',');
105                }
106                final String value = accountCursor.getString(i);
107                if (value == null || Account.ROSTERVERSION.equals(accountCursor.getColumnName(i))) {
108                    builder.append("NULL");
109                } else if (value.matches("\\d+")) {
110                    int intValue = Integer.parseInt(value);
111                    if (Account.OPTIONS.equals(accountCursor.getColumnName(i))) {
112                        intValue |= 1 << Account.OPTION_DISABLED;
113                    }
114                    builder.append(intValue);
115                } else {
116                    DatabaseUtils.appendEscapedSQLString(builder, value);
117                }
118            }
119            builder.append(")");
120            builder.append(';');
121            builder.append('\n');
122        }
123        if (accountCursor != null) {
124            accountCursor.close();
125        }
126        writer.append(builder.toString());
127    }
128
129    private static void simpleExport(SQLiteDatabase db, String table, String column, String uuid, PrintWriter writer) {
130        final Cursor cursor = db.query(table, null, column + "=?", new String[]{uuid}, null, null, null);
131        while (cursor != null && cursor.moveToNext()) {
132            writer.write(cursorToString(table, cursor, PAGE_SIZE));
133        }
134        if (cursor != null) {
135            cursor.close();
136        }
137    }
138
139    public static byte[] getKey(final String password, final byte[] salt) throws InvalidKeySpecException {
140        final SecretKeyFactory factory;
141        try {
142            factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
143        } catch (NoSuchAlgorithmException e) {
144            throw new IllegalStateException(e);
145        }
146        return factory.generateSecret(new PBEKeySpec(password.toCharArray(), salt, 1024, 128)).getEncoded();
147    }
148
149    private static String cursorToString(final String table, final Cursor cursor, final int max) {
150        return cursorToString(table, cursor, max, false);
151    }
152
153    private static String cursorToString(final String table, final Cursor cursor, int max, boolean ignore) {
154        final boolean identities = SQLiteAxolotlStore.IDENTITIES_TABLENAME.equals(table);
155        StringBuilder builder = new StringBuilder();
156        builder.append("INSERT ");
157        if (ignore) {
158            builder.append("OR IGNORE ");
159        }
160        builder.append("INTO ").append(table).append("(");
161        int skipColumn = -1;
162        for (int i = 0; i < cursor.getColumnCount(); ++i) {
163            final String name = cursor.getColumnName(i);
164            if (identities && SQLiteAxolotlStore.TRUSTED.equals(name)) {
165                skipColumn = i;
166                continue;
167            }
168            if (i != 0) {
169                builder.append(',');
170            }
171            builder.append(name);
172        }
173        builder.append(") VALUES");
174        for (int i = 0; i < max; ++i) {
175            if (i != 0) {
176                builder.append(',');
177            }
178            appendValues(cursor, builder, skipColumn);
179            if (i < max - 1 && !cursor.moveToNext()) {
180                break;
181            }
182        }
183        builder.append(';');
184        builder.append('\n');
185        return builder.toString();
186    }
187
188    private static void appendValues(final Cursor cursor, final StringBuilder builder, final int skipColumn) {
189        builder.append("(");
190        for (int i = 0; i < cursor.getColumnCount(); ++i) {
191            if (i == skipColumn) {
192                continue;
193            }
194            if (i != 0) {
195                builder.append(',');
196            }
197            final String value = cursor.getString(i);
198            if (value == null) {
199                builder.append("NULL");
200            } else if (value.matches("[0-9]+")) {
201                builder.append(value);
202            } else {
203                DatabaseUtils.appendEscapedSQLString(builder, value);
204            }
205        }
206        builder.append(")");
207
208    }
209
210    @Override
211    public void onCreate() {
212        mDatabaseBackend = DatabaseBackend.getInstance(getBaseContext());
213        mAccounts = mDatabaseBackend.getAccounts();
214        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
215    }
216
217    @Override
218    public int onStartCommand(Intent intent, int flags, int startId) {
219        if (RUNNING.compareAndSet(false, true)) {
220            new Thread(() -> {
221                boolean success;
222                List<File> files;
223                try {
224                    files = export();
225                    success = true;
226                } catch (final Exception e) {
227                    Log.d(Config.LOGTAG, "unable to create backup", e);
228                    success = false;
229                    files = Collections.emptyList();
230                }
231                stopForeground(true);
232                RUNNING.set(false);
233                if (success) {
234                    notifySuccess(files);
235                }
236                stopSelf();
237            }).start();
238            return START_STICKY;
239        } else {
240            Log.d(Config.LOGTAG, "ExportBackupService. ignoring start command because already running");
241        }
242        return START_NOT_STICKY;
243    }
244
245    private void messageExport(SQLiteDatabase db, String uuid, PrintWriter writer, Progress progress) {
246        Cursor cursor = db.rawQuery("select messages.* from messages join conversations on conversations.uuid=messages.conversationUuid where conversations.accountUuid=?", new String[]{uuid});
247        int size = cursor != null ? cursor.getCount() : 0;
248        Log.d(Config.LOGTAG, "exporting " + size + " messages for account " + uuid);
249        int i = 0;
250        int p = 0;
251        while (cursor != null && cursor.moveToNext()) {
252            writer.write(cursorToString(Message.TABLENAME, cursor, PAGE_SIZE, false));
253            if (i + PAGE_SIZE > size) {
254                i = size;
255            } else {
256                i += PAGE_SIZE;
257            }
258            final int percentage = i * 100 / size;
259            if (p < percentage) {
260                p = percentage;
261                notificationManager.notify(NOTIFICATION_ID, progress.build(p));
262            }
263        }
264        if (cursor != null) {
265            cursor.close();
266        }
267    }
268
269    private List<File> export() throws Exception {
270        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getBaseContext(), "backup");
271        mBuilder.setContentTitle(getString(R.string.notification_create_backup_title))
272                .setSmallIcon(R.drawable.ic_archive_white_24dp)
273                .setProgress(1, 0, false);
274        startForeground(NOTIFICATION_ID, mBuilder.build());
275        int count = 0;
276        final int max = this.mAccounts.size();
277        final SecureRandom secureRandom = new SecureRandom();
278        final List<File> files = new ArrayList<>();
279        Log.d(Config.LOGTAG, "starting backup for " + max + " accounts");
280        for (final Account account : this.mAccounts) {
281            final String password = account.getPassword();
282            if (Strings.nullToEmpty(password).trim().isEmpty()) {
283                Log.d(Config.LOGTAG, String.format("skipping backup for %s because password is empty. unable to encrypt", account.getJid().asBareJid()));
284                continue;
285            }
286            Log.d(Config.LOGTAG, String.format("exporting data for account %s (%s)", account.getJid().asBareJid(), account.getUuid()));
287            final byte[] IV = new byte[12];
288            final byte[] salt = new byte[16];
289            secureRandom.nextBytes(IV);
290            secureRandom.nextBytes(salt);
291            final BackupFileHeader backupFileHeader = new BackupFileHeader(getString(R.string.app_name), account.getJid(), System.currentTimeMillis(), IV, salt);
292            final Progress progress = new Progress(mBuilder, max, count);
293            final File file = new File(FileBackend.getBackupDirectory(this) + account.getJid().asBareJid().toEscapedString() + ".ceb");
294            files.add(file);
295            final File directory = file.getParentFile();
296            if (directory != null && directory.mkdirs()) {
297                Log.d(Config.LOGTAG, "created backup directory " + directory.getAbsolutePath());
298            }
299            final FileOutputStream fileOutputStream = new FileOutputStream(file);
300            final DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);
301            backupFileHeader.write(dataOutputStream);
302            dataOutputStream.flush();
303
304            final Cipher cipher = Compatibility.twentyEight() ? Cipher.getInstance(CIPHERMODE) : Cipher.getInstance(CIPHERMODE, PROVIDER);
305            final byte[] key = getKey(password, salt);
306            SecretKeySpec keySpec = new SecretKeySpec(key, KEYTYPE);
307            IvParameterSpec ivSpec = new IvParameterSpec(IV);
308            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
309            CipherOutputStream cipherOutputStream = new CipherOutputStream(fileOutputStream, cipher);
310
311            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(cipherOutputStream);
312            PrintWriter writer = new PrintWriter(gzipOutputStream);
313            SQLiteDatabase db = this.mDatabaseBackend.getReadableDatabase();
314            final String uuid = account.getUuid();
315            accountExport(db, uuid, writer);
316            simpleExport(db, Conversation.TABLENAME, Conversation.ACCOUNT, uuid, writer);
317            messageExport(db, uuid, writer, progress);
318            for (String table : Arrays.asList(SQLiteAxolotlStore.PREKEY_TABLENAME, SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, SQLiteAxolotlStore.SESSION_TABLENAME, SQLiteAxolotlStore.IDENTITIES_TABLENAME)) {
319                simpleExport(db, table, SQLiteAxolotlStore.ACCOUNT, uuid, writer);
320            }
321            writer.flush();
322            writer.close();
323            mediaScannerScanFile(file);
324            Log.d(Config.LOGTAG, "written backup to " + file.getAbsoluteFile());
325            count++;
326        }
327        return files;
328    }
329
330    private void mediaScannerScanFile(final File file) {
331        final Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
332        intent.setData(Uri.fromFile(file));
333        sendBroadcast(intent);
334    }
335
336    private void notifySuccess(final List<File> files) {
337        final String path = FileBackend.getBackupDirectory(this);
338
339        PendingIntent openFolderIntent = null;
340
341        for (Intent intent : getPossibleFileOpenIntents(this, path)) {
342            if (intent.resolveActivityInfo(getPackageManager(), 0) != null) {
343                openFolderIntent = PendingIntent.getActivity(this, 189, intent, PendingIntent.FLAG_UPDATE_CURRENT);
344                break;
345            }
346        }
347
348        PendingIntent shareFilesIntent = null;
349        if (files.size() > 0) {
350            final Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
351            ArrayList<Uri> uris = new ArrayList<>();
352            for (File file : files) {
353                uris.add(FileBackend.getUriForFile(this, file));
354            }
355            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
356            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
357            intent.setType(MIME_TYPE);
358            final Intent chooser = Intent.createChooser(intent, getString(R.string.share_backup_files));
359            shareFilesIntent = PendingIntent.getActivity(this, 190, chooser, PendingIntent.FLAG_UPDATE_CURRENT);
360        }
361
362        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getBaseContext(), "backup");
363        mBuilder.setContentTitle(getString(R.string.notification_backup_created_title))
364                .setContentText(getString(R.string.notification_backup_created_subtitle, path))
365                .setStyle(new NotificationCompat.BigTextStyle().bigText(getString(R.string.notification_backup_created_subtitle, FileBackend.getBackupDirectory(this))))
366                .setAutoCancel(true)
367                .setContentIntent(openFolderIntent)
368                .setSmallIcon(R.drawable.ic_archive_white_24dp);
369
370        if (shareFilesIntent != null) {
371            mBuilder.addAction(R.drawable.ic_share_white_24dp, getString(R.string.share_backup_files), shareFilesIntent);
372        }
373
374        notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
375    }
376
377    @Override
378    public IBinder onBind(Intent intent) {
379        return null;
380    }
381
382    private static class Progress {
383        private final NotificationCompat.Builder builder;
384        private final int max;
385        private final int count;
386
387        private Progress(NotificationCompat.Builder builder, int max, int count) {
388            this.builder = builder;
389            this.max = max;
390            this.count = count;
391        }
392
393        private Notification build(int percentage) {
394            builder.setProgress(max * 100, count * 100 + percentage, false);
395            return builder.build();
396        }
397    }
398}