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