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