1package eu.siacs.conversations.persistance;
2
3import android.content.ContentValues;
4import android.content.Context;
5import android.database.Cursor;
6import android.database.DatabaseUtils;
7import android.database.sqlite.SQLiteCantOpenDatabaseException;
8import android.database.sqlite.SQLiteDatabase;
9import android.database.sqlite.SQLiteOpenHelper;
10import android.util.Base64;
11import android.util.Log;
12import android.util.Pair;
13
14import org.json.JSONObject;
15import org.whispersystems.libaxolotl.AxolotlAddress;
16import org.whispersystems.libaxolotl.IdentityKey;
17import org.whispersystems.libaxolotl.IdentityKeyPair;
18import org.whispersystems.libaxolotl.InvalidKeyException;
19import org.whispersystems.libaxolotl.state.PreKeyRecord;
20import org.whispersystems.libaxolotl.state.SessionRecord;
21import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
22
23import java.io.ByteArrayInputStream;
24import java.io.IOException;
25import java.security.cert.CertificateEncodingException;
26import java.security.cert.CertificateException;
27import java.security.cert.CertificateFactory;
28import java.security.cert.X509Certificate;
29import java.util.ArrayList;
30import java.util.HashMap;
31import java.util.HashSet;
32import java.util.Iterator;
33import java.util.List;
34import java.util.Map;
35import java.util.Set;
36import java.util.concurrent.CopyOnWriteArrayList;
37import org.json.JSONException;
38
39import eu.siacs.conversations.Config;
40import eu.siacs.conversations.crypto.axolotl.AxolotlService;
41import eu.siacs.conversations.crypto.axolotl.FingerprintStatus;
42import eu.siacs.conversations.crypto.axolotl.SQLiteAxolotlStore;
43import eu.siacs.conversations.entities.Account;
44import eu.siacs.conversations.entities.Contact;
45import eu.siacs.conversations.entities.Conversation;
46import eu.siacs.conversations.entities.Message;
47import eu.siacs.conversations.entities.PresenceTemplate;
48import eu.siacs.conversations.entities.Roster;
49import eu.siacs.conversations.entities.ServiceDiscoveryResult;
50import eu.siacs.conversations.xmpp.jid.InvalidJidException;
51import eu.siacs.conversations.xmpp.jid.Jid;
52
53public class DatabaseBackend extends SQLiteOpenHelper {
54
55 private static DatabaseBackend instance = null;
56
57 private static final String DATABASE_NAME = "history";
58 private static final int DATABASE_VERSION = 32;
59
60 private static String CREATE_CONTATCS_STATEMENT = "create table "
61 + Contact.TABLENAME + "(" + Contact.ACCOUNT + " TEXT, "
62 + Contact.SERVERNAME + " TEXT, " + Contact.SYSTEMNAME + " TEXT,"
63 + Contact.JID + " TEXT," + Contact.KEYS + " TEXT,"
64 + Contact.PHOTOURI + " TEXT," + Contact.OPTIONS + " NUMBER,"
65 + Contact.SYSTEMACCOUNT + " NUMBER, " + Contact.AVATAR + " TEXT, "
66 + Contact.LAST_PRESENCE + " TEXT, " + Contact.LAST_TIME + " NUMBER, "
67 + Contact.GROUPS + " TEXT, FOREIGN KEY(" + Contact.ACCOUNT + ") REFERENCES "
68 + Account.TABLENAME + "(" + Account.UUID
69 + ") ON DELETE CASCADE, UNIQUE(" + Contact.ACCOUNT + ", "
70 + Contact.JID + ") ON CONFLICT REPLACE);";
71
72 private static String CREATE_DISCOVERY_RESULTS_STATEMENT = "create table "
73 + ServiceDiscoveryResult.TABLENAME + "("
74 + ServiceDiscoveryResult.HASH + " TEXT, "
75 + ServiceDiscoveryResult.VER + " TEXT, "
76 + ServiceDiscoveryResult.RESULT + " TEXT, "
77 + "UNIQUE(" + ServiceDiscoveryResult.HASH + ", "
78 + ServiceDiscoveryResult.VER + ") ON CONFLICT REPLACE);";
79
80 private static String CREATE_PRESENCE_TEMPLATES_STATEMENT = "CREATE TABLE "
81 + PresenceTemplate.TABELNAME + "("
82 + PresenceTemplate.UUID + " TEXT, "
83 + PresenceTemplate.LAST_USED + " NUMBER,"
84 + PresenceTemplate.MESSAGE + " TEXT,"
85 + PresenceTemplate.STATUS + " TEXT,"
86 + "UNIQUE("+PresenceTemplate.MESSAGE + "," +PresenceTemplate.STATUS+") ON CONFLICT REPLACE);";
87
88 private static String CREATE_PREKEYS_STATEMENT = "CREATE TABLE "
89 + SQLiteAxolotlStore.PREKEY_TABLENAME + "("
90 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
91 + SQLiteAxolotlStore.ID + " INTEGER, "
92 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
93 + SQLiteAxolotlStore.ACCOUNT
94 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
95 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
96 + SQLiteAxolotlStore.ID
97 + ") ON CONFLICT REPLACE"
98 + ");";
99
100 private static String CREATE_SIGNED_PREKEYS_STATEMENT = "CREATE TABLE "
101 + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME + "("
102 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
103 + SQLiteAxolotlStore.ID + " INTEGER, "
104 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
105 + SQLiteAxolotlStore.ACCOUNT
106 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
107 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
108 + SQLiteAxolotlStore.ID
109 + ") ON CONFLICT REPLACE" +
110 ");";
111
112 private static String CREATE_SESSIONS_STATEMENT = "CREATE TABLE "
113 + SQLiteAxolotlStore.SESSION_TABLENAME + "("
114 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
115 + SQLiteAxolotlStore.NAME + " TEXT, "
116 + SQLiteAxolotlStore.DEVICE_ID + " INTEGER, "
117 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
118 + SQLiteAxolotlStore.ACCOUNT
119 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
120 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
121 + SQLiteAxolotlStore.NAME + ", "
122 + SQLiteAxolotlStore.DEVICE_ID
123 + ") ON CONFLICT REPLACE"
124 + ");";
125
126 private static String CREATE_IDENTITIES_STATEMENT = "CREATE TABLE "
127 + SQLiteAxolotlStore.IDENTITIES_TABLENAME + "("
128 + SQLiteAxolotlStore.ACCOUNT + " TEXT, "
129 + SQLiteAxolotlStore.NAME + " TEXT, "
130 + SQLiteAxolotlStore.OWN + " INTEGER, "
131 + SQLiteAxolotlStore.FINGERPRINT + " TEXT, "
132 + SQLiteAxolotlStore.CERTIFICATE + " BLOB, "
133 + SQLiteAxolotlStore.TRUST + " TEXT, "
134 + SQLiteAxolotlStore.ACTIVE + " NUMBER, "
135 + SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER,"
136 + SQLiteAxolotlStore.KEY + " TEXT, FOREIGN KEY("
137 + SQLiteAxolotlStore.ACCOUNT
138 + ") REFERENCES " + Account.TABLENAME + "(" + Account.UUID + ") ON DELETE CASCADE, "
139 + "UNIQUE( " + SQLiteAxolotlStore.ACCOUNT + ", "
140 + SQLiteAxolotlStore.NAME + ", "
141 + SQLiteAxolotlStore.FINGERPRINT
142 + ") ON CONFLICT IGNORE"
143 + ");";
144
145 private static String START_TIMES_TABLE = "start_times";
146
147 private static String CREATE_START_TIMES_TABLE = "create table "+START_TIMES_TABLE+" (timestamp NUMBER);";
148
149 private DatabaseBackend(Context context) {
150 super(context, DATABASE_NAME, null, DATABASE_VERSION);
151 }
152
153 @Override
154 public void onCreate(SQLiteDatabase db) {
155 db.execSQL("PRAGMA foreign_keys=ON;");
156 db.execSQL("create table " + Account.TABLENAME + "(" + Account.UUID+ " TEXT PRIMARY KEY,"
157 + Account.USERNAME + " TEXT,"
158 + Account.SERVER + " TEXT,"
159 + Account.PASSWORD + " TEXT,"
160 + Account.DISPLAY_NAME + " TEXT, "
161 + Account.STATUS + " TEXT,"
162 + Account.STATUS_MESSAGE + " TEXT,"
163 + Account.ROSTERVERSION + " TEXT,"
164 + Account.OPTIONS + " NUMBER, "
165 + Account.AVATAR + " TEXT, "
166 + Account.KEYS + " TEXT, "
167 + Account.HOSTNAME + " TEXT, "
168 + Account.PORT + " NUMBER DEFAULT 5222)");
169 db.execSQL("create table " + Conversation.TABLENAME + " ("
170 + Conversation.UUID + " TEXT PRIMARY KEY, " + Conversation.NAME
171 + " TEXT, " + Conversation.CONTACT + " TEXT, "
172 + Conversation.ACCOUNT + " TEXT, " + Conversation.CONTACTJID
173 + " TEXT, " + Conversation.CREATED + " NUMBER, "
174 + Conversation.STATUS + " NUMBER, " + Conversation.MODE
175 + " NUMBER, " + Conversation.ATTRIBUTES + " TEXT, FOREIGN KEY("
176 + Conversation.ACCOUNT + ") REFERENCES " + Account.TABLENAME
177 + "(" + Account.UUID + ") ON DELETE CASCADE);");
178 db.execSQL("create table " + Message.TABLENAME + "( " + Message.UUID
179 + " TEXT PRIMARY KEY, " + Message.CONVERSATION + " TEXT, "
180 + Message.TIME_SENT + " NUMBER, " + Message.COUNTERPART
181 + " TEXT, " + Message.TRUE_COUNTERPART + " TEXT,"
182 + Message.BODY + " TEXT, " + Message.ENCRYPTION + " NUMBER, "
183 + Message.STATUS + " NUMBER," + Message.TYPE + " NUMBER, "
184 + Message.RELATIVE_FILE_PATH + " TEXT, "
185 + Message.SERVER_MSG_ID + " TEXT, "
186 + Message.FINGERPRINT + " TEXT, "
187 + Message.CARBON + " INTEGER, "
188 + Message.EDITED + " TEXT, "
189 + Message.READ + " NUMBER DEFAULT 1, "
190 + Message.OOB + " INTEGER, "
191 + Message.ERROR_MESSAGE + " TEXT,"
192 + Message.REMOTE_MSG_ID + " TEXT, FOREIGN KEY("
193 + Message.CONVERSATION + ") REFERENCES "
194 + Conversation.TABLENAME + "(" + Conversation.UUID
195 + ") ON DELETE CASCADE);");
196
197 db.execSQL(CREATE_CONTATCS_STATEMENT);
198 db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
199 db.execSQL(CREATE_SESSIONS_STATEMENT);
200 db.execSQL(CREATE_PREKEYS_STATEMENT);
201 db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
202 db.execSQL(CREATE_IDENTITIES_STATEMENT);
203 db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
204 db.execSQL(CREATE_START_TIMES_TABLE);
205 }
206
207 @Override
208 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
209 if (oldVersion < 2 && newVersion >= 2) {
210 db.execSQL("update " + Account.TABLENAME + " set "
211 + Account.OPTIONS + " = " + Account.OPTIONS + " | 8");
212 }
213 if (oldVersion < 3 && newVersion >= 3) {
214 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
215 + Message.TYPE + " NUMBER");
216 }
217 if (oldVersion < 5 && newVersion >= 5) {
218 db.execSQL("DROP TABLE " + Contact.TABLENAME);
219 db.execSQL(CREATE_CONTATCS_STATEMENT);
220 db.execSQL("UPDATE " + Account.TABLENAME + " SET "
221 + Account.ROSTERVERSION + " = NULL");
222 }
223 if (oldVersion < 6 && newVersion >= 6) {
224 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
225 + Message.TRUE_COUNTERPART + " TEXT");
226 }
227 if (oldVersion < 7 && newVersion >= 7) {
228 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
229 + Message.REMOTE_MSG_ID + " TEXT");
230 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
231 + Contact.AVATAR + " TEXT");
232 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN "
233 + Account.AVATAR + " TEXT");
234 }
235 if (oldVersion < 8 && newVersion >= 8) {
236 db.execSQL("ALTER TABLE " + Conversation.TABLENAME + " ADD COLUMN "
237 + Conversation.ATTRIBUTES + " TEXT");
238 }
239 if (oldVersion < 9 && newVersion >= 9) {
240 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
241 + Contact.LAST_TIME + " NUMBER");
242 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
243 + Contact.LAST_PRESENCE + " TEXT");
244 }
245 if (oldVersion < 10 && newVersion >= 10) {
246 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
247 + Message.RELATIVE_FILE_PATH + " TEXT");
248 }
249 if (oldVersion < 11 && newVersion >= 11) {
250 db.execSQL("ALTER TABLE " + Contact.TABLENAME + " ADD COLUMN "
251 + Contact.GROUPS + " TEXT");
252 db.execSQL("delete from " + Contact.TABLENAME);
253 db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
254 }
255 if (oldVersion < 12 && newVersion >= 12) {
256 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
257 + Message.SERVER_MSG_ID + " TEXT");
258 }
259 if (oldVersion < 13 && newVersion >= 13) {
260 db.execSQL("delete from " + Contact.TABLENAME);
261 db.execSQL("update " + Account.TABLENAME + " set " + Account.ROSTERVERSION + " = NULL");
262 }
263 if (oldVersion < 14 && newVersion >= 14) {
264 canonicalizeJids(db);
265 }
266 if (oldVersion < 15 && newVersion >= 15) {
267 recreateAxolotlDb(db);
268 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
269 + Message.FINGERPRINT + " TEXT");
270 } else if (oldVersion < 22 && newVersion >= 22) {
271 db.execSQL("ALTER TABLE " + SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN " + SQLiteAxolotlStore.CERTIFICATE);
272 }
273 if (oldVersion < 16 && newVersion >= 16) {
274 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN "
275 + Message.CARBON + " INTEGER");
276 }
277 if (oldVersion < 19 && newVersion >= 19) {
278 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.DISPLAY_NAME + " TEXT");
279 }
280 if (oldVersion < 20 && newVersion >= 20) {
281 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.HOSTNAME + " TEXT");
282 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.PORT + " NUMBER DEFAULT 5222");
283 }
284 if (oldVersion < 26 && newVersion >= 26) {
285 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS + " TEXT");
286 db.execSQL("ALTER TABLE " + Account.TABLENAME + " ADD COLUMN " + Account.STATUS_MESSAGE + " TEXT");
287 }
288 /* Any migrations that alter the Account table need to happen BEFORE this migration, as it
289 * depends on account de-serialization.
290 */
291 if (oldVersion < 17 && newVersion >= 17) {
292 List<Account> accounts = getAccounts(db);
293 for (Account account : accounts) {
294 String ownDeviceIdString = account.getKey(SQLiteAxolotlStore.JSONKEY_REGISTRATION_ID);
295 if (ownDeviceIdString == null) {
296 continue;
297 }
298 int ownDeviceId = Integer.valueOf(ownDeviceIdString);
299 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), ownDeviceId);
300 deleteSession(db, account, ownAddress);
301 IdentityKeyPair identityKeyPair = loadOwnIdentityKeyPair(db, account);
302 if (identityKeyPair != null) {
303 String[] selectionArgs = {
304 account.getUuid(),
305 identityKeyPair.getPublicKey().getFingerprint().replaceAll("\\s", "")
306 };
307 ContentValues values = new ContentValues();
308 values.put(SQLiteAxolotlStore.TRUSTED, 2);
309 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
310 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
311 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
312 selectionArgs);
313 } else {
314 Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": could not load own identity key pair");
315 }
316 }
317 }
318 if (oldVersion < 18 && newVersion >= 18) {
319 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.READ + " NUMBER DEFAULT 1");
320 }
321
322 if (oldVersion < 21 && newVersion >= 21) {
323 List<Account> accounts = getAccounts(db);
324 for (Account account : accounts) {
325 account.unsetPgpSignature();
326 db.update(Account.TABLENAME, account.getContentValues(), Account.UUID
327 + "=?", new String[]{account.getUuid()});
328 }
329 }
330
331 if (oldVersion < 23 && newVersion >= 23) {
332 db.execSQL(CREATE_DISCOVERY_RESULTS_STATEMENT);
333 }
334
335 if (oldVersion < 24 && newVersion >= 24) {
336 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.EDITED + " TEXT");
337 }
338
339 if (oldVersion < 25 && newVersion >= 25) {
340 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.OOB + " INTEGER");
341 }
342
343 if (oldVersion < 26 && newVersion >= 26) {
344 db.execSQL(CREATE_PRESENCE_TEMPLATES_STATEMENT);
345 }
346
347 if (oldVersion < 27 && newVersion >= 27) {
348 db.execSQL("DELETE FROM "+ServiceDiscoveryResult.TABLENAME);
349 }
350
351 if (oldVersion < 28 && newVersion >= 28) {
352 canonicalizeJids(db);
353 }
354
355 if (oldVersion < 29 && newVersion >= 29) {
356 db.execSQL("ALTER TABLE " + Message.TABLENAME + " ADD COLUMN " + Message.ERROR_MESSAGE + " TEXT");
357 }
358 if (oldVersion < 30 && newVersion >= 30) {
359 db.execSQL(CREATE_START_TIMES_TABLE);
360 }
361 if (oldVersion < 31 && newVersion >= 31) {
362 db.execSQL("ALTER TABLE "+ SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN "+SQLiteAxolotlStore.TRUST + " TEXT");
363 db.execSQL("ALTER TABLE "+ SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN "+SQLiteAxolotlStore.ACTIVE + " NUMBER");
364 HashMap<Integer,ContentValues> migration = new HashMap<>();
365 migration.put(0,createFingerprintStatusContentValues(FingerprintStatus.Trust.UNDECIDED,true));
366 migration.put(1,createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, true));
367 migration.put(2,createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, true));
368 migration.put(3,createFingerprintStatusContentValues(FingerprintStatus.Trust.COMPROMISED, false));
369 migration.put(4,createFingerprintStatusContentValues(FingerprintStatus.Trust.TRUSTED, false));
370 migration.put(5,createFingerprintStatusContentValues(FingerprintStatus.Trust.UNDECIDED, false));
371 migration.put(6,createFingerprintStatusContentValues(FingerprintStatus.Trust.UNTRUSTED, false));
372 migration.put(7,createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, true));
373 migration.put(8,createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED_X509, false));
374 for(Map.Entry<Integer,ContentValues> entry : migration.entrySet()) {
375 String whereClause = SQLiteAxolotlStore.TRUSTED+"=?";
376 String[] where = {String.valueOf(entry.getKey())};
377 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME,entry.getValue(),whereClause,where);
378 }
379
380 }
381 if (oldVersion < 32 && newVersion >= 32) {
382 db.execSQL("ALTER TABLE "+ SQLiteAxolotlStore.IDENTITIES_TABLENAME + " ADD COLUMN "+SQLiteAxolotlStore.LAST_ACTIVATION + " NUMBER");
383 ContentValues defaults = new ContentValues();
384 defaults.put(SQLiteAxolotlStore.LAST_ACTIVATION,System.currentTimeMillis());
385 db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME,defaults,null,null);
386 }
387 }
388
389 private static ContentValues createFingerprintStatusContentValues(FingerprintStatus.Trust trust, boolean active) {
390 ContentValues values = new ContentValues();
391 values.put(SQLiteAxolotlStore.TRUST,trust.toString());
392 values.put(SQLiteAxolotlStore.ACTIVE,active ? 1 : 0);
393 return values;
394 }
395
396 private void canonicalizeJids(SQLiteDatabase db) {
397 // migrate db to new, canonicalized JID domainpart representation
398
399 // Conversation table
400 Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
401 while (cursor.moveToNext()) {
402 String newJid;
403 try {
404 newJid = Jid.fromString(
405 cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
406 ).toPreppedString();
407 } catch (InvalidJidException ignored) {
408 Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
409 + cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
410 + ": " + ignored + ". Skipping...");
411 continue;
412 }
413
414 String updateArgs[] = {
415 newJid,
416 cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
417 };
418 db.execSQL("update " + Conversation.TABLENAME
419 + " set " + Conversation.CONTACTJID + " = ? "
420 + " where " + Conversation.UUID + " = ?", updateArgs);
421 }
422 cursor.close();
423
424 // Contact table
425 cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
426 while (cursor.moveToNext()) {
427 String newJid;
428 try {
429 newJid = Jid.fromString(
430 cursor.getString(cursor.getColumnIndex(Contact.JID))
431 ).toPreppedString();
432 } catch (InvalidJidException ignored) {
433 Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
434 + cursor.getString(cursor.getColumnIndex(Contact.JID))
435 + ": " + ignored + ". Skipping...");
436 continue;
437 }
438
439 String updateArgs[] = {
440 newJid,
441 cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
442 cursor.getString(cursor.getColumnIndex(Contact.JID)),
443 };
444 db.execSQL("update " + Contact.TABLENAME
445 + " set " + Contact.JID + " = ? "
446 + " where " + Contact.ACCOUNT + " = ? "
447 + " AND " + Contact.JID + " = ?", updateArgs);
448 }
449 cursor.close();
450
451 // Account table
452 cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
453 while (cursor.moveToNext()) {
454 String newServer;
455 try {
456 newServer = Jid.fromParts(
457 cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
458 cursor.getString(cursor.getColumnIndex(Account.SERVER)),
459 "mobile"
460 ).getDomainpart();
461 } catch (InvalidJidException ignored) {
462 Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
463 + cursor.getString(cursor.getColumnIndex(Account.SERVER))
464 + ": " + ignored + ". Skipping...");
465 continue;
466 }
467
468 String updateArgs[] = {
469 newServer,
470 cursor.getString(cursor.getColumnIndex(Account.UUID)),
471 };
472 db.execSQL("update " + Account.TABLENAME
473 + " set " + Account.SERVER + " = ? "
474 + " where " + Account.UUID + " = ?", updateArgs);
475 }
476 cursor.close();
477 }
478
479 public static synchronized DatabaseBackend getInstance(Context context) {
480 if (instance == null) {
481 instance = new DatabaseBackend(context);
482 }
483 return instance;
484 }
485
486 public void createConversation(Conversation conversation) {
487 SQLiteDatabase db = this.getWritableDatabase();
488 db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
489 }
490
491 public void createMessage(Message message) {
492 SQLiteDatabase db = this.getWritableDatabase();
493 db.insert(Message.TABLENAME, null, message.getContentValues());
494 }
495
496 public void createAccount(Account account) {
497 SQLiteDatabase db = this.getWritableDatabase();
498 db.insert(Account.TABLENAME, null, account.getContentValues());
499 }
500
501 public void insertDiscoveryResult(ServiceDiscoveryResult result) {
502 SQLiteDatabase db = this.getWritableDatabase();
503 db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
504 }
505
506 public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
507 SQLiteDatabase db = this.getReadableDatabase();
508 String[] selectionArgs = {hash, ver};
509 Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
510 ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
511 selectionArgs, null, null, null);
512 if (cursor.getCount() == 0) {
513 cursor.close();
514 return null;
515 }
516 cursor.moveToFirst();
517
518 ServiceDiscoveryResult result = null;
519 try {
520 result = new ServiceDiscoveryResult(cursor);
521 } catch (JSONException e) { /* result is still null */ }
522
523 cursor.close();
524 return result;
525 }
526
527 public void insertPresenceTemplate(PresenceTemplate template) {
528 SQLiteDatabase db = this.getWritableDatabase();
529 db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
530 }
531
532 public List<PresenceTemplate> getPresenceTemplates() {
533 ArrayList<PresenceTemplate> templates = new ArrayList<>();
534 SQLiteDatabase db = this.getReadableDatabase();
535 Cursor cursor = db.query(PresenceTemplate.TABELNAME,null,null,null,null,null,PresenceTemplate.LAST_USED+" desc");
536 while (cursor.moveToNext()) {
537 templates.add(PresenceTemplate.fromCursor(cursor));
538 }
539 cursor.close();
540 return templates;
541 }
542
543 public void deletePresenceTemplate(PresenceTemplate template) {
544 Log.d(Config.LOGTAG,"deleting presence template with uuid "+template.getUuid());
545 SQLiteDatabase db = this.getWritableDatabase();
546 String where = PresenceTemplate.UUID+"=?";
547 String[] whereArgs = {template.getUuid()};
548 db.delete(PresenceTemplate.TABELNAME,where,whereArgs);
549 }
550
551 public CopyOnWriteArrayList<Conversation> getConversations(int status) {
552 CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
553 SQLiteDatabase db = this.getReadableDatabase();
554 String[] selectionArgs = {Integer.toString(status)};
555 Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
556 + " where " + Conversation.STATUS + " = ? order by "
557 + Conversation.CREATED + " desc", selectionArgs);
558 while (cursor.moveToNext()) {
559 list.add(Conversation.fromCursor(cursor));
560 }
561 cursor.close();
562 return list;
563 }
564
565 public ArrayList<Message> getMessages(Conversation conversations, int limit) {
566 return getMessages(conversations, limit, -1);
567 }
568
569 public ArrayList<Message> getMessages(Conversation conversation, int limit,
570 long timestamp) {
571 ArrayList<Message> list = new ArrayList<>();
572 SQLiteDatabase db = this.getReadableDatabase();
573 Cursor cursor;
574 if (timestamp == -1) {
575 String[] selectionArgs = {conversation.getUuid()};
576 cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
577 + "=?", selectionArgs, null, null, Message.TIME_SENT
578 + " DESC", String.valueOf(limit));
579 } else {
580 String[] selectionArgs = {conversation.getUuid(),
581 Long.toString(timestamp)};
582 cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
583 + "=? and " + Message.TIME_SENT + "<?", selectionArgs,
584 null, null, Message.TIME_SENT + " DESC",
585 String.valueOf(limit));
586 }
587 if (cursor.getCount() > 0) {
588 cursor.moveToLast();
589 do {
590 Message message = Message.fromCursor(cursor);
591 message.setConversation(conversation);
592 list.add(message);
593 } while (cursor.moveToPrevious());
594 }
595 cursor.close();
596 return list;
597 }
598
599 public Iterable<Message> getMessagesIterable(final Conversation conversation) {
600 return new Iterable<Message>() {
601 @Override
602 public Iterator<Message> iterator() {
603 class MessageIterator implements Iterator<Message> {
604 SQLiteDatabase db = getReadableDatabase();
605 String[] selectionArgs = {conversation.getUuid()};
606 Cursor cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
607 + "=?", selectionArgs, null, null, Message.TIME_SENT
608 + " ASC", null);
609
610 public MessageIterator() {
611 cursor.moveToFirst();
612 }
613
614 @Override
615 public boolean hasNext() {
616 return !cursor.isAfterLast();
617 }
618
619 @Override
620 public Message next() {
621 Message message = Message.fromCursor(cursor);
622 cursor.moveToNext();
623 return message;
624 }
625
626 @Override
627 public void remove() {
628 throw new UnsupportedOperationException();
629 }
630 }
631 return new MessageIterator();
632 }
633 };
634 }
635
636 public Conversation findConversation(final Account account, final Jid contactJid) {
637 SQLiteDatabase db = this.getReadableDatabase();
638 String[] selectionArgs = {account.getUuid(),
639 contactJid.toBareJid().toPreppedString() + "/%",
640 contactJid.toBareJid().toPreppedString()
641 };
642 Cursor cursor = db.query(Conversation.TABLENAME, null,
643 Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
644 + " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null);
645 if (cursor.getCount() == 0) {
646 cursor.close();
647 return null;
648 }
649 cursor.moveToFirst();
650 Conversation conversation = Conversation.fromCursor(cursor);
651 cursor.close();
652 return conversation;
653 }
654
655 public void updateConversation(final Conversation conversation) {
656 final SQLiteDatabase db = this.getWritableDatabase();
657 final String[] args = {conversation.getUuid()};
658 db.update(Conversation.TABLENAME, conversation.getContentValues(),
659 Conversation.UUID + "=?", args);
660 }
661
662 public List<Account> getAccounts() {
663 SQLiteDatabase db = this.getReadableDatabase();
664 return getAccounts(db);
665 }
666
667 private List<Account> getAccounts(SQLiteDatabase db) {
668 List<Account> list = new ArrayList<>();
669 Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
670 null, null);
671 while (cursor.moveToNext()) {
672 list.add(Account.fromCursor(cursor));
673 }
674 cursor.close();
675 return list;
676 }
677
678 public boolean updateAccount(Account account) {
679 SQLiteDatabase db = this.getWritableDatabase();
680 String[] args = {account.getUuid()};
681 final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
682 return rows == 1;
683 }
684
685 public boolean deleteAccount(Account account) {
686 SQLiteDatabase db = this.getWritableDatabase();
687 String[] args = {account.getUuid()};
688 final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
689 return rows == 1;
690 }
691
692 public boolean hasEnabledAccounts() {
693 SQLiteDatabase db = this.getReadableDatabase();
694 Cursor cursor = db.rawQuery("select count(" + Account.UUID + ") from "
695 + Account.TABLENAME + " where not options & (1 <<1)", null);
696 try {
697 cursor.moveToFirst();
698 int count = cursor.getInt(0);
699 return (count > 0);
700 } catch (SQLiteCantOpenDatabaseException e) {
701 return true; // better safe than sorry
702 } catch (RuntimeException e) {
703 return true; // better safe than sorry
704 } finally {
705 if (cursor != null) {
706 cursor.close();
707 }
708 }
709 }
710
711 @Override
712 public SQLiteDatabase getWritableDatabase() {
713 SQLiteDatabase db = super.getWritableDatabase();
714 db.execSQL("PRAGMA foreign_keys=ON;");
715 return db;
716 }
717
718 public void updateMessage(Message message) {
719 SQLiteDatabase db = this.getWritableDatabase();
720 String[] args = {message.getUuid()};
721 db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
722 + "=?", args);
723 }
724
725 public void updateMessage(Message message, String uuid) {
726 SQLiteDatabase db = this.getWritableDatabase();
727 String[] args = {uuid};
728 db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
729 + "=?", args);
730 }
731
732 public void readRoster(Roster roster) {
733 SQLiteDatabase db = this.getReadableDatabase();
734 Cursor cursor;
735 String args[] = {roster.getAccount().getUuid()};
736 cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
737 while (cursor.moveToNext()) {
738 roster.initContact(Contact.fromCursor(cursor));
739 }
740 cursor.close();
741 }
742
743 public void writeRoster(final Roster roster) {
744 final Account account = roster.getAccount();
745 final SQLiteDatabase db = this.getWritableDatabase();
746 db.beginTransaction();
747 for (Contact contact : roster.getContacts()) {
748 if (contact.getOption(Contact.Options.IN_ROSTER)) {
749 db.insert(Contact.TABLENAME, null, contact.getContentValues());
750 } else {
751 String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
752 String[] whereArgs = {account.getUuid(), contact.getJid().toPreppedString()};
753 db.delete(Contact.TABLENAME, where, whereArgs);
754 }
755 }
756 db.setTransactionSuccessful();
757 db.endTransaction();
758 account.setRosterVersion(roster.getVersion());
759 updateAccount(account);
760 }
761
762 public void deleteMessagesInConversation(Conversation conversation) {
763 SQLiteDatabase db = this.getWritableDatabase();
764 String[] args = {conversation.getUuid()};
765 db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
766 }
767
768 public Pair<Long, String> getLastMessageReceived(Account account) {
769 Cursor cursor = null;
770 try {
771 SQLiteDatabase db = this.getReadableDatabase();
772 String sql = "select messages.timeSent,messages.serverMsgId from accounts join conversations on accounts.uuid=conversations.accountUuid join messages on conversations.uuid=messages.conversationUuid where accounts.uuid=? and (messages.status=0 or messages.carbon=1 or messages.serverMsgId not null) order by messages.timesent desc limit 1";
773 String[] args = {account.getUuid()};
774 cursor = db.rawQuery(sql, args);
775 if (cursor.getCount() == 0) {
776 return null;
777 } else {
778 cursor.moveToFirst();
779 return new Pair<>(cursor.getLong(0), cursor.getString(1));
780 }
781 } catch (Exception e) {
782 return null;
783 } finally {
784 if (cursor != null) {
785 cursor.close();
786 }
787 }
788 }
789
790 public Pair<Long,String> getLastClearDate(Account account) {
791 SQLiteDatabase db = this.getReadableDatabase();
792 String[] columns = {Conversation.ATTRIBUTES};
793 String selection = Conversation.ACCOUNT + "=?";
794 String[] args = {account.getUuid()};
795 Cursor cursor = db.query(Conversation.TABLENAME,columns,selection,args,null,null,null);
796 long maxClearDate = 0;
797 while (cursor.moveToNext()) {
798 try {
799 final JSONObject jsonObject = new JSONObject(cursor.getString(0));
800 maxClearDate = Math.max(maxClearDate, jsonObject.getLong(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY));
801 } catch (Exception e) {
802 //ignored
803 }
804 }
805 cursor.close();
806 return new Pair<>(maxClearDate,null);
807 }
808
809 private Cursor getCursorForSession(Account account, AxolotlAddress contact) {
810 final SQLiteDatabase db = this.getReadableDatabase();
811 String[] selectionArgs = {account.getUuid(),
812 contact.getName(),
813 Integer.toString(contact.getDeviceId())};
814 return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
815 null,
816 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
817 + SQLiteAxolotlStore.NAME + " = ? AND "
818 + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
819 selectionArgs,
820 null, null, null);
821 }
822
823 public SessionRecord loadSession(Account account, AxolotlAddress contact) {
824 SessionRecord session = null;
825 Cursor cursor = getCursorForSession(account, contact);
826 if (cursor.getCount() != 0) {
827 cursor.moveToFirst();
828 try {
829 session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
830 } catch (IOException e) {
831 cursor.close();
832 throw new AssertionError(e);
833 }
834 }
835 cursor.close();
836 return session;
837 }
838
839 public List<Integer> getSubDeviceSessions(Account account, AxolotlAddress contact) {
840 final SQLiteDatabase db = this.getReadableDatabase();
841 return getSubDeviceSessions(db, account, contact);
842 }
843
844 private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, AxolotlAddress contact) {
845 List<Integer> devices = new ArrayList<>();
846 String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
847 String[] selectionArgs = {account.getUuid(),
848 contact.getName()};
849 Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
850 columns,
851 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
852 + SQLiteAxolotlStore.NAME + " = ?",
853 selectionArgs,
854 null, null, null);
855
856 while (cursor.moveToNext()) {
857 devices.add(cursor.getInt(
858 cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
859 }
860
861 cursor.close();
862 return devices;
863 }
864
865 public boolean containsSession(Account account, AxolotlAddress contact) {
866 Cursor cursor = getCursorForSession(account, contact);
867 int count = cursor.getCount();
868 cursor.close();
869 return count != 0;
870 }
871
872 public void storeSession(Account account, AxolotlAddress contact, SessionRecord session) {
873 SQLiteDatabase db = this.getWritableDatabase();
874 ContentValues values = new ContentValues();
875 values.put(SQLiteAxolotlStore.NAME, contact.getName());
876 values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
877 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
878 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
879 db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
880 }
881
882 public void deleteSession(Account account, AxolotlAddress contact) {
883 SQLiteDatabase db = this.getWritableDatabase();
884 deleteSession(db, account, contact);
885 }
886
887 private void deleteSession(SQLiteDatabase db, Account account, AxolotlAddress contact) {
888 String[] args = {account.getUuid(),
889 contact.getName(),
890 Integer.toString(contact.getDeviceId())};
891 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
892 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
893 + SQLiteAxolotlStore.NAME + " = ? AND "
894 + SQLiteAxolotlStore.DEVICE_ID + " = ? ",
895 args);
896 }
897
898 public void deleteAllSessions(Account account, AxolotlAddress contact) {
899 SQLiteDatabase db = this.getWritableDatabase();
900 String[] args = {account.getUuid(), contact.getName()};
901 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
902 SQLiteAxolotlStore.ACCOUNT + "=? AND "
903 + SQLiteAxolotlStore.NAME + " = ?",
904 args);
905 }
906
907 private Cursor getCursorForPreKey(Account account, int preKeyId) {
908 SQLiteDatabase db = this.getReadableDatabase();
909 String[] columns = {SQLiteAxolotlStore.KEY};
910 String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
911 Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
912 columns,
913 SQLiteAxolotlStore.ACCOUNT + "=? AND "
914 + SQLiteAxolotlStore.ID + "=?",
915 selectionArgs,
916 null, null, null);
917
918 return cursor;
919 }
920
921 public PreKeyRecord loadPreKey(Account account, int preKeyId) {
922 PreKeyRecord record = null;
923 Cursor cursor = getCursorForPreKey(account, preKeyId);
924 if (cursor.getCount() != 0) {
925 cursor.moveToFirst();
926 try {
927 record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
928 } catch (IOException e) {
929 throw new AssertionError(e);
930 }
931 }
932 cursor.close();
933 return record;
934 }
935
936 public boolean containsPreKey(Account account, int preKeyId) {
937 Cursor cursor = getCursorForPreKey(account, preKeyId);
938 int count = cursor.getCount();
939 cursor.close();
940 return count != 0;
941 }
942
943 public void storePreKey(Account account, PreKeyRecord record) {
944 SQLiteDatabase db = this.getWritableDatabase();
945 ContentValues values = new ContentValues();
946 values.put(SQLiteAxolotlStore.ID, record.getId());
947 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
948 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
949 db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
950 }
951
952 public void deletePreKey(Account account, int preKeyId) {
953 SQLiteDatabase db = this.getWritableDatabase();
954 String[] args = {account.getUuid(), Integer.toString(preKeyId)};
955 db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
956 SQLiteAxolotlStore.ACCOUNT + "=? AND "
957 + SQLiteAxolotlStore.ID + "=?",
958 args);
959 }
960
961 private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
962 SQLiteDatabase db = this.getReadableDatabase();
963 String[] columns = {SQLiteAxolotlStore.KEY};
964 String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
965 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
966 columns,
967 SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
968 selectionArgs,
969 null, null, null);
970
971 return cursor;
972 }
973
974 public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
975 SignedPreKeyRecord record = null;
976 Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
977 if (cursor.getCount() != 0) {
978 cursor.moveToFirst();
979 try {
980 record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
981 } catch (IOException e) {
982 throw new AssertionError(e);
983 }
984 }
985 cursor.close();
986 return record;
987 }
988
989 public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
990 List<SignedPreKeyRecord> prekeys = new ArrayList<>();
991 SQLiteDatabase db = this.getReadableDatabase();
992 String[] columns = {SQLiteAxolotlStore.KEY};
993 String[] selectionArgs = {account.getUuid()};
994 Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
995 columns,
996 SQLiteAxolotlStore.ACCOUNT + "=?",
997 selectionArgs,
998 null, null, null);
999
1000 while (cursor.moveToNext()) {
1001 try {
1002 prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1003 } catch (IOException ignored) {
1004 }
1005 }
1006 cursor.close();
1007 return prekeys;
1008 }
1009
1010 public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1011 Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1012 int count = cursor.getCount();
1013 cursor.close();
1014 return count != 0;
1015 }
1016
1017 public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1018 SQLiteDatabase db = this.getWritableDatabase();
1019 ContentValues values = new ContentValues();
1020 values.put(SQLiteAxolotlStore.ID, record.getId());
1021 values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1022 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1023 db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1024 }
1025
1026 public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1027 SQLiteDatabase db = this.getWritableDatabase();
1028 String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1029 db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1030 SQLiteAxolotlStore.ACCOUNT + "=? AND "
1031 + SQLiteAxolotlStore.ID + "=?",
1032 args);
1033 }
1034
1035 private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1036 final SQLiteDatabase db = this.getReadableDatabase();
1037 return getIdentityKeyCursor(db, account, name, own);
1038 }
1039
1040 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1041 return getIdentityKeyCursor(db, account, name, own, null);
1042 }
1043
1044 private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1045 final SQLiteDatabase db = this.getReadableDatabase();
1046 return getIdentityKeyCursor(db, account, fingerprint);
1047 }
1048
1049 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1050 return getIdentityKeyCursor(db, account, null, null, fingerprint);
1051 }
1052
1053 private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1054 String[] columns = {SQLiteAxolotlStore.TRUST,
1055 SQLiteAxolotlStore.ACTIVE,
1056 SQLiteAxolotlStore.LAST_ACTIVATION,
1057 SQLiteAxolotlStore.KEY};
1058 ArrayList<String> selectionArgs = new ArrayList<>(4);
1059 selectionArgs.add(account.getUuid());
1060 String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1061 if (name != null) {
1062 selectionArgs.add(name);
1063 selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1064 }
1065 if (fingerprint != null) {
1066 selectionArgs.add(fingerprint);
1067 selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1068 }
1069 if (own != null) {
1070 selectionArgs.add(own ? "1" : "0");
1071 selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1072 }
1073 Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1074 columns,
1075 selectionString,
1076 selectionArgs.toArray(new String[selectionArgs.size()]),
1077 null, null, null);
1078
1079 return cursor;
1080 }
1081
1082 public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1083 SQLiteDatabase db = getReadableDatabase();
1084 return loadOwnIdentityKeyPair(db, account);
1085 }
1086
1087 private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1088 String name = account.getJid().toBareJid().toPreppedString();
1089 IdentityKeyPair identityKeyPair = null;
1090 Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1091 if (cursor.getCount() != 0) {
1092 cursor.moveToFirst();
1093 try {
1094 identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1095 } catch (InvalidKeyException e) {
1096 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().toBareJid() + ", address: " + name);
1097 }
1098 }
1099 cursor.close();
1100
1101 return identityKeyPair;
1102 }
1103
1104 public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1105 return loadIdentityKeys(account, name, null);
1106 }
1107
1108 public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1109 Set<IdentityKey> identityKeys = new HashSet<>();
1110 Cursor cursor = getIdentityKeyCursor(account, name, false);
1111
1112 while (cursor.moveToNext()) {
1113 if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1114 continue;
1115 }
1116 try {
1117 String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1118 if (key != null) {
1119 identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1120 } else {
1121 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().toBareJid() + ", address: " + name);
1122 }
1123 } catch (InvalidKeyException e) {
1124 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().toBareJid() + ", address: " + name);
1125 }
1126 }
1127 cursor.close();
1128
1129 return identityKeys;
1130 }
1131
1132 public long numTrustedKeys(Account account, String name) {
1133 SQLiteDatabase db = getReadableDatabase();
1134 String[] args = {
1135 account.getUuid(),
1136 name,
1137 FingerprintStatus.Trust.TRUSTED.toString(),
1138 FingerprintStatus.Trust.VERIFIED.toString(),
1139 FingerprintStatus.Trust.VERIFIED_X509.toString()
1140 };
1141 return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1142 SQLiteAxolotlStore.ACCOUNT + " = ?"
1143 + " AND " + SQLiteAxolotlStore.NAME + " = ?"
1144 + " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " +SQLiteAxolotlStore.TRUST +" = ?)"
1145 + " AND " +SQLiteAxolotlStore.ACTIVE + " > 0",
1146 args
1147 );
1148 }
1149
1150 private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1151 SQLiteDatabase db = this.getWritableDatabase();
1152 ContentValues values = new ContentValues();
1153 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1154 values.put(SQLiteAxolotlStore.NAME, name);
1155 values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1156 values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1157 values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1158 values.putAll(status.toContentValues());
1159 String where = SQLiteAxolotlStore.ACCOUNT+"=? AND "+SQLiteAxolotlStore.NAME+"=? AND "+SQLiteAxolotlStore.FINGERPRINT+" =?";
1160 String[] whereArgs = {account.getUuid(),name,fingerprint};
1161 int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME,values,where,whereArgs);
1162 if (rows == 0) {
1163 db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1164 }
1165 }
1166
1167 public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1168 SQLiteDatabase db = this.getWritableDatabase();
1169 ContentValues values = new ContentValues();
1170 values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1171 values.put(SQLiteAxolotlStore.NAME, name);
1172 values.put(SQLiteAxolotlStore.OWN, 0);
1173 values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1174 values.putAll(status.toContentValues());
1175 db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1176 }
1177
1178 public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1179 Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1180 final FingerprintStatus status;
1181 if (cursor.getCount() > 0) {
1182 cursor.moveToFirst();
1183 status = FingerprintStatus.fromCursor(cursor);
1184 } else {
1185 status = null;
1186 }
1187 cursor.close();
1188 return status;
1189 }
1190
1191 public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1192 SQLiteDatabase db = this.getWritableDatabase();
1193 return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1194 }
1195
1196 private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1197 String[] selectionArgs = {
1198 account.getUuid(),
1199 fingerprint
1200 };
1201 int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1202 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1203 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1204 selectionArgs);
1205 return rows == 1;
1206 }
1207
1208 public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1209 SQLiteDatabase db = this.getWritableDatabase();
1210 String[] selectionArgs = {
1211 account.getUuid(),
1212 fingerprint
1213 };
1214 try {
1215 ContentValues values = new ContentValues();
1216 values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1217 return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1218 SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1219 + SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1220 selectionArgs) == 1;
1221 } catch (CertificateEncodingException e) {
1222 Log.d(Config.LOGTAG, "could not encode certificate");
1223 return false;
1224 }
1225 }
1226
1227 public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1228 SQLiteDatabase db = this.getReadableDatabase();
1229 String[] selectionArgs = {
1230 account.getUuid(),
1231 fingerprint
1232 };
1233 String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1234 String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1235 Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1236 if (cursor.getCount() < 1) {
1237 return null;
1238 } else {
1239 cursor.moveToFirst();
1240 byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1241 cursor.close();
1242 if (certificate == null || certificate.length == 0) {
1243 return null;
1244 }
1245 try {
1246 CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1247 return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1248 } catch (CertificateException e) {
1249 Log.d(Config.LOGTAG,"certificate exception "+e.getMessage());
1250 return null;
1251 }
1252 }
1253 }
1254
1255 public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1256 storeIdentityKey(account, name, false, identityKey.getFingerprint().replaceAll("\\s", ""), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1257 }
1258
1259 public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1260 storeIdentityKey(account, account.getJid().toBareJid().toPreppedString(), true, identityKeyPair.getPublicKey().getFingerprint().replaceAll("\\s", ""), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1261 }
1262
1263
1264 public void recreateAxolotlDb(SQLiteDatabase db) {
1265 Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1266 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1267 db.execSQL(CREATE_SESSIONS_STATEMENT);
1268 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1269 db.execSQL(CREATE_PREKEYS_STATEMENT);
1270 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1271 db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1272 db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1273 db.execSQL(CREATE_IDENTITIES_STATEMENT);
1274 }
1275
1276 public void wipeAxolotlDb(Account account) {
1277 String accountName = account.getUuid();
1278 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1279 SQLiteDatabase db = this.getWritableDatabase();
1280 String[] deleteArgs = {
1281 accountName
1282 };
1283 db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1284 SQLiteAxolotlStore.ACCOUNT + " = ?",
1285 deleteArgs);
1286 db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1287 SQLiteAxolotlStore.ACCOUNT + " = ?",
1288 deleteArgs);
1289 db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1290 SQLiteAxolotlStore.ACCOUNT + " = ?",
1291 deleteArgs);
1292 db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1293 SQLiteAxolotlStore.ACCOUNT + " = ?",
1294 deleteArgs);
1295 }
1296
1297 public boolean startTimeCountExceedsThreshold() {
1298 SQLiteDatabase db = this.getWritableDatabase();
1299 long cleanBeforeTimestamp = System.currentTimeMillis() - Config.FREQUENT_RESTARTS_DETECTION_WINDOW;
1300 db.execSQL("delete from "+START_TIMES_TABLE+" where timestamp < "+cleanBeforeTimestamp);
1301 ContentValues values = new ContentValues();
1302 values.put("timestamp",System.currentTimeMillis());
1303 db.insert(START_TIMES_TABLE,null,values);
1304 String[] columns = new String[]{"count(timestamp)"};
1305 Cursor cursor = db.query(START_TIMES_TABLE,columns,null,null,null,null,null);
1306 int count;
1307 if (cursor.moveToFirst()) {
1308 count = cursor.getInt(0);
1309 } else {
1310 count = 0;
1311 }
1312 cursor.close();
1313 Log.d(Config.LOGTAG,"start time counter reached "+count);
1314 return count >= Config.FREQUENT_RESTARTS_THRESHOLD;
1315 }
1316
1317 public void clearStartTimeCounter() {
1318 Log.d(Config.LOGTAG,"resetting start time counter");
1319 SQLiteDatabase db = this.getWritableDatabase();
1320 db.execSQL("delete from "+START_TIMES_TABLE);
1321 }
1322}