DatabaseBackend.java

   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 = 33;
  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.TRUSTED,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.TRUSTED, 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		if (oldVersion < 33 && newVersion >= 33) {
 388			String whereClause = SQLiteAxolotlStore.OWN+"=1";
 389			db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME,createFingerprintStatusContentValues(FingerprintStatus.Trust.VERIFIED,true),whereClause,null);
 390		}
 391	}
 392
 393	private static ContentValues createFingerprintStatusContentValues(FingerprintStatus.Trust trust, boolean active) {
 394		ContentValues values = new ContentValues();
 395		values.put(SQLiteAxolotlStore.TRUST,trust.toString());
 396		values.put(SQLiteAxolotlStore.ACTIVE,active ? 1 : 0);
 397		return values;
 398	}
 399
 400	private void canonicalizeJids(SQLiteDatabase db) {
 401		// migrate db to new, canonicalized JID domainpart representation
 402
 403		// Conversation table
 404		Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME, new String[0]);
 405		while (cursor.moveToNext()) {
 406			String newJid;
 407			try {
 408				newJid = Jid.fromString(
 409						cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
 410				).toPreppedString();
 411			} catch (InvalidJidException ignored) {
 412				Log.e(Config.LOGTAG, "Failed to migrate Conversation CONTACTJID "
 413						+ cursor.getString(cursor.getColumnIndex(Conversation.CONTACTJID))
 414						+ ": " + ignored + ". Skipping...");
 415				continue;
 416			}
 417
 418			String updateArgs[] = {
 419					newJid,
 420					cursor.getString(cursor.getColumnIndex(Conversation.UUID)),
 421			};
 422			db.execSQL("update " + Conversation.TABLENAME
 423					+ " set " + Conversation.CONTACTJID + " = ? "
 424					+ " where " + Conversation.UUID + " = ?", updateArgs);
 425		}
 426		cursor.close();
 427
 428		// Contact table
 429		cursor = db.rawQuery("select * from " + Contact.TABLENAME, new String[0]);
 430		while (cursor.moveToNext()) {
 431			String newJid;
 432			try {
 433				newJid = Jid.fromString(
 434						cursor.getString(cursor.getColumnIndex(Contact.JID))
 435				).toPreppedString();
 436			} catch (InvalidJidException ignored) {
 437				Log.e(Config.LOGTAG, "Failed to migrate Contact JID "
 438						+ cursor.getString(cursor.getColumnIndex(Contact.JID))
 439						+ ": " + ignored + ". Skipping...");
 440				continue;
 441			}
 442
 443			String updateArgs[] = {
 444					newJid,
 445					cursor.getString(cursor.getColumnIndex(Contact.ACCOUNT)),
 446					cursor.getString(cursor.getColumnIndex(Contact.JID)),
 447			};
 448			db.execSQL("update " + Contact.TABLENAME
 449					+ " set " + Contact.JID + " = ? "
 450					+ " where " + Contact.ACCOUNT + " = ? "
 451					+ " AND " + Contact.JID + " = ?", updateArgs);
 452		}
 453		cursor.close();
 454
 455		// Account table
 456		cursor = db.rawQuery("select * from " + Account.TABLENAME, new String[0]);
 457		while (cursor.moveToNext()) {
 458			String newServer;
 459			try {
 460				newServer = Jid.fromParts(
 461						cursor.getString(cursor.getColumnIndex(Account.USERNAME)),
 462						cursor.getString(cursor.getColumnIndex(Account.SERVER)),
 463						"mobile"
 464				).getDomainpart();
 465			} catch (InvalidJidException ignored) {
 466				Log.e(Config.LOGTAG, "Failed to migrate Account SERVER "
 467						+ cursor.getString(cursor.getColumnIndex(Account.SERVER))
 468						+ ": " + ignored + ". Skipping...");
 469				continue;
 470			}
 471
 472			String updateArgs[] = {
 473					newServer,
 474					cursor.getString(cursor.getColumnIndex(Account.UUID)),
 475			};
 476			db.execSQL("update " + Account.TABLENAME
 477					+ " set " + Account.SERVER + " = ? "
 478					+ " where " + Account.UUID + " = ?", updateArgs);
 479		}
 480		cursor.close();
 481	}
 482
 483	public static synchronized DatabaseBackend getInstance(Context context) {
 484		if (instance == null) {
 485			instance = new DatabaseBackend(context);
 486		}
 487		return instance;
 488	}
 489
 490	public void createConversation(Conversation conversation) {
 491		SQLiteDatabase db = this.getWritableDatabase();
 492		db.insert(Conversation.TABLENAME, null, conversation.getContentValues());
 493	}
 494
 495	public void createMessage(Message message) {
 496		SQLiteDatabase db = this.getWritableDatabase();
 497		db.insert(Message.TABLENAME, null, message.getContentValues());
 498	}
 499
 500	public void createAccount(Account account) {
 501		SQLiteDatabase db = this.getWritableDatabase();
 502		db.insert(Account.TABLENAME, null, account.getContentValues());
 503	}
 504
 505	public void insertDiscoveryResult(ServiceDiscoveryResult result) {
 506		SQLiteDatabase db = this.getWritableDatabase();
 507		db.insert(ServiceDiscoveryResult.TABLENAME, null, result.getContentValues());
 508	}
 509
 510	public ServiceDiscoveryResult findDiscoveryResult(final String hash, final String ver) {
 511		SQLiteDatabase db = this.getReadableDatabase();
 512		String[] selectionArgs = {hash, ver};
 513		Cursor cursor = db.query(ServiceDiscoveryResult.TABLENAME, null,
 514				ServiceDiscoveryResult.HASH + "=? AND " + ServiceDiscoveryResult.VER + "=?",
 515				selectionArgs, null, null, null);
 516		if (cursor.getCount() == 0) {
 517			cursor.close();
 518			return null;
 519		}
 520		cursor.moveToFirst();
 521
 522		ServiceDiscoveryResult result = null;
 523		try {
 524			result = new ServiceDiscoveryResult(cursor);
 525		} catch (JSONException e) { /* result is still null */ }
 526
 527		cursor.close();
 528		return result;
 529	}
 530
 531	public void insertPresenceTemplate(PresenceTemplate template) {
 532		SQLiteDatabase db = this.getWritableDatabase();
 533		db.insert(PresenceTemplate.TABELNAME, null, template.getContentValues());
 534	}
 535
 536	public List<PresenceTemplate> getPresenceTemplates() {
 537		ArrayList<PresenceTemplate> templates = new ArrayList<>();
 538		SQLiteDatabase db = this.getReadableDatabase();
 539		Cursor cursor = db.query(PresenceTemplate.TABELNAME,null,null,null,null,null,PresenceTemplate.LAST_USED+" desc");
 540		while (cursor.moveToNext()) {
 541			templates.add(PresenceTemplate.fromCursor(cursor));
 542		}
 543		cursor.close();
 544		return templates;
 545	}
 546
 547	public void deletePresenceTemplate(PresenceTemplate template) {
 548		Log.d(Config.LOGTAG,"deleting presence template with uuid "+template.getUuid());
 549		SQLiteDatabase db = this.getWritableDatabase();
 550		String where = PresenceTemplate.UUID+"=?";
 551		String[] whereArgs = {template.getUuid()};
 552		db.delete(PresenceTemplate.TABELNAME,where,whereArgs);
 553	}
 554
 555	public CopyOnWriteArrayList<Conversation> getConversations(int status) {
 556		CopyOnWriteArrayList<Conversation> list = new CopyOnWriteArrayList<>();
 557		SQLiteDatabase db = this.getReadableDatabase();
 558		String[] selectionArgs = {Integer.toString(status)};
 559		Cursor cursor = db.rawQuery("select * from " + Conversation.TABLENAME
 560				+ " where " + Conversation.STATUS + " = ? order by "
 561				+ Conversation.CREATED + " desc", selectionArgs);
 562		while (cursor.moveToNext()) {
 563			list.add(Conversation.fromCursor(cursor));
 564		}
 565		cursor.close();
 566		return list;
 567	}
 568
 569	public ArrayList<Message> getMessages(Conversation conversations, int limit) {
 570		return getMessages(conversations, limit, -1);
 571	}
 572
 573	public ArrayList<Message> getMessages(Conversation conversation, int limit,
 574										  long timestamp) {
 575		ArrayList<Message> list = new ArrayList<>();
 576		SQLiteDatabase db = this.getReadableDatabase();
 577		Cursor cursor;
 578		if (timestamp == -1) {
 579			String[] selectionArgs = {conversation.getUuid()};
 580			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 581					+ "=?", selectionArgs, null, null, Message.TIME_SENT
 582					+ " DESC", String.valueOf(limit));
 583		} else {
 584			String[] selectionArgs = {conversation.getUuid(),
 585					Long.toString(timestamp)};
 586			cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 587							+ "=? and " + Message.TIME_SENT + "<?", selectionArgs,
 588					null, null, Message.TIME_SENT + " DESC",
 589					String.valueOf(limit));
 590		}
 591		if (cursor.getCount() > 0) {
 592			cursor.moveToLast();
 593			do {
 594				Message message = Message.fromCursor(cursor);
 595				message.setConversation(conversation);
 596				list.add(message);
 597			} while (cursor.moveToPrevious());
 598		}
 599		cursor.close();
 600		return list;
 601	}
 602
 603	public Iterable<Message> getMessagesIterable(final Conversation conversation) {
 604		return new Iterable<Message>() {
 605			@Override
 606			public Iterator<Message> iterator() {
 607				class MessageIterator implements Iterator<Message> {
 608					SQLiteDatabase db = getReadableDatabase();
 609					String[] selectionArgs = {conversation.getUuid()};
 610					Cursor cursor = db.query(Message.TABLENAME, null, Message.CONVERSATION
 611							+ "=?", selectionArgs, null, null, Message.TIME_SENT
 612							+ " ASC", null);
 613
 614					public MessageIterator() {
 615						cursor.moveToFirst();
 616					}
 617
 618					@Override
 619					public boolean hasNext() {
 620						return !cursor.isAfterLast();
 621					}
 622
 623					@Override
 624					public Message next() {
 625						Message message = Message.fromCursor(cursor);
 626						cursor.moveToNext();
 627						return message;
 628					}
 629
 630					@Override
 631					public void remove() {
 632						throw new UnsupportedOperationException();
 633					}
 634				}
 635				return new MessageIterator();
 636			}
 637		};
 638	}
 639
 640	public Conversation findConversation(final Account account, final Jid contactJid) {
 641		SQLiteDatabase db = this.getReadableDatabase();
 642		String[] selectionArgs = {account.getUuid(),
 643				contactJid.toBareJid().toPreppedString() + "/%",
 644				contactJid.toBareJid().toPreppedString()
 645		};
 646		Cursor cursor = db.query(Conversation.TABLENAME, null,
 647				Conversation.ACCOUNT + "=? AND (" + Conversation.CONTACTJID
 648						+ " like ? OR " + Conversation.CONTACTJID + "=?)", selectionArgs, null, null, null);
 649		if (cursor.getCount() == 0) {
 650			cursor.close();
 651			return null;
 652		}
 653		cursor.moveToFirst();
 654		Conversation conversation = Conversation.fromCursor(cursor);
 655		cursor.close();
 656		return conversation;
 657	}
 658
 659	public void updateConversation(final Conversation conversation) {
 660		final SQLiteDatabase db = this.getWritableDatabase();
 661		final String[] args = {conversation.getUuid()};
 662		db.update(Conversation.TABLENAME, conversation.getContentValues(),
 663				Conversation.UUID + "=?", args);
 664	}
 665
 666	public List<Account> getAccounts() {
 667		SQLiteDatabase db = this.getReadableDatabase();
 668		return getAccounts(db);
 669	}
 670
 671	private List<Account> getAccounts(SQLiteDatabase db) {
 672		List<Account> list = new ArrayList<>();
 673		Cursor cursor = db.query(Account.TABLENAME, null, null, null, null,
 674				null, null);
 675		while (cursor.moveToNext()) {
 676			list.add(Account.fromCursor(cursor));
 677		}
 678		cursor.close();
 679		return list;
 680	}
 681
 682	public boolean updateAccount(Account account) {
 683		SQLiteDatabase db = this.getWritableDatabase();
 684		String[] args = {account.getUuid()};
 685		final int rows = db.update(Account.TABLENAME, account.getContentValues(), Account.UUID + "=?", args);
 686		return rows == 1;
 687	}
 688
 689	public boolean deleteAccount(Account account) {
 690		SQLiteDatabase db = this.getWritableDatabase();
 691		String[] args = {account.getUuid()};
 692		final int rows = db.delete(Account.TABLENAME, Account.UUID + "=?", args);
 693		return rows == 1;
 694	}
 695
 696	public boolean hasEnabledAccounts() {
 697		SQLiteDatabase db = this.getReadableDatabase();
 698		Cursor cursor = db.rawQuery("select count(" + Account.UUID + ")  from "
 699				+ Account.TABLENAME + " where not options & (1 <<1)", null);
 700		try {
 701			cursor.moveToFirst();
 702			int count = cursor.getInt(0);
 703			return (count > 0);
 704		} catch (SQLiteCantOpenDatabaseException e) {
 705			return true; // better safe than sorry
 706		} catch (RuntimeException e) {
 707			return true; // better safe than sorry
 708		} finally {
 709			if (cursor != null) {
 710				cursor.close();
 711			}
 712		}
 713	}
 714
 715	@Override
 716	public SQLiteDatabase getWritableDatabase() {
 717		SQLiteDatabase db = super.getWritableDatabase();
 718		db.execSQL("PRAGMA foreign_keys=ON;");
 719		return db;
 720	}
 721
 722	public void updateMessage(Message message) {
 723		SQLiteDatabase db = this.getWritableDatabase();
 724		String[] args = {message.getUuid()};
 725		db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
 726				+ "=?", args);
 727	}
 728
 729	public void updateMessage(Message message, String uuid) {
 730		SQLiteDatabase db = this.getWritableDatabase();
 731		String[] args = {uuid};
 732		db.update(Message.TABLENAME, message.getContentValues(), Message.UUID
 733				+ "=?", args);
 734	}
 735
 736	public void readRoster(Roster roster) {
 737		SQLiteDatabase db = this.getReadableDatabase();
 738		Cursor cursor;
 739		String args[] = {roster.getAccount().getUuid()};
 740		cursor = db.query(Contact.TABLENAME, null, Contact.ACCOUNT + "=?", args, null, null, null);
 741		while (cursor.moveToNext()) {
 742			roster.initContact(Contact.fromCursor(cursor));
 743		}
 744		cursor.close();
 745	}
 746
 747	public void writeRoster(final Roster roster) {
 748		final Account account = roster.getAccount();
 749		final SQLiteDatabase db = this.getWritableDatabase();
 750		db.beginTransaction();
 751		for (Contact contact : roster.getContacts()) {
 752			if (contact.getOption(Contact.Options.IN_ROSTER)) {
 753				db.insert(Contact.TABLENAME, null, contact.getContentValues());
 754			} else {
 755				String where = Contact.ACCOUNT + "=? AND " + Contact.JID + "=?";
 756				String[] whereArgs = {account.getUuid(), contact.getJid().toPreppedString()};
 757				db.delete(Contact.TABLENAME, where, whereArgs);
 758			}
 759		}
 760		db.setTransactionSuccessful();
 761		db.endTransaction();
 762		account.setRosterVersion(roster.getVersion());
 763		updateAccount(account);
 764	}
 765
 766	public void deleteMessagesInConversation(Conversation conversation) {
 767		SQLiteDatabase db = this.getWritableDatabase();
 768		String[] args = {conversation.getUuid()};
 769		db.delete(Message.TABLENAME, Message.CONVERSATION + "=?", args);
 770	}
 771
 772	public Pair<Long, String> getLastMessageReceived(Account account) {
 773		Cursor cursor = null;
 774		try {
 775			SQLiteDatabase db = this.getReadableDatabase();
 776			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";
 777			String[] args = {account.getUuid()};
 778			cursor = db.rawQuery(sql, args);
 779			if (cursor.getCount() == 0) {
 780				return null;
 781			} else {
 782				cursor.moveToFirst();
 783				return new Pair<>(cursor.getLong(0), cursor.getString(1));
 784			}
 785		} catch (Exception e) {
 786			return null;
 787		} finally {
 788			if (cursor != null) {
 789				cursor.close();
 790			}
 791		}
 792	}
 793
 794	public long getLastTimeFingerprintUsed(Account account, String fingerprint) {
 795		String SQL = "select messages.timeSent from accounts join conversations on accounts.uuid=conversations.accountUuid join messages on conversations.uuid=messages.conversationUuid where accounts.uuid=? and messages.axolotl_fingerprint=? order by messages.timesent desc limit 1";
 796		String[] args = {account.getUuid(), fingerprint};
 797		Cursor cursor = getReadableDatabase().rawQuery(SQL,args);
 798		long time;
 799		if (cursor.moveToFirst()) {
 800			time = cursor.getLong(0);
 801		} else {
 802			time = 0;
 803		}
 804		cursor.close();
 805		return time;
 806	}
 807
 808	public Pair<Long,String> getLastClearDate(Account account) {
 809		SQLiteDatabase db = this.getReadableDatabase();
 810		String[] columns = {Conversation.ATTRIBUTES};
 811		String selection = Conversation.ACCOUNT + "=?";
 812		String[] args = {account.getUuid()};
 813		Cursor cursor = db.query(Conversation.TABLENAME,columns,selection,args,null,null,null);
 814		long maxClearDate = 0;
 815		while (cursor.moveToNext()) {
 816			try {
 817				final JSONObject jsonObject = new JSONObject(cursor.getString(0));
 818				maxClearDate = Math.max(maxClearDate, jsonObject.getLong(Conversation.ATTRIBUTE_LAST_CLEAR_HISTORY));
 819			} catch (Exception e) {
 820				//ignored
 821			}
 822		}
 823		cursor.close();
 824		return new Pair<>(maxClearDate,null);
 825	}
 826
 827	private Cursor getCursorForSession(Account account, AxolotlAddress contact) {
 828		final SQLiteDatabase db = this.getReadableDatabase();
 829		String[] selectionArgs = {account.getUuid(),
 830				contact.getName(),
 831				Integer.toString(contact.getDeviceId())};
 832		return db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
 833				null,
 834				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 835						+ SQLiteAxolotlStore.NAME + " = ? AND "
 836						+ SQLiteAxolotlStore.DEVICE_ID + " = ? ",
 837				selectionArgs,
 838				null, null, null);
 839	}
 840
 841	public SessionRecord loadSession(Account account, AxolotlAddress contact) {
 842		SessionRecord session = null;
 843		Cursor cursor = getCursorForSession(account, contact);
 844		if (cursor.getCount() != 0) {
 845			cursor.moveToFirst();
 846			try {
 847				session = new SessionRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
 848			} catch (IOException e) {
 849				cursor.close();
 850				throw new AssertionError(e);
 851			}
 852		}
 853		cursor.close();
 854		return session;
 855	}
 856
 857	public List<Integer> getSubDeviceSessions(Account account, AxolotlAddress contact) {
 858		final SQLiteDatabase db = this.getReadableDatabase();
 859		return getSubDeviceSessions(db, account, contact);
 860	}
 861
 862	private List<Integer> getSubDeviceSessions(SQLiteDatabase db, Account account, AxolotlAddress contact) {
 863		List<Integer> devices = new ArrayList<>();
 864		String[] columns = {SQLiteAxolotlStore.DEVICE_ID};
 865		String[] selectionArgs = {account.getUuid(),
 866				contact.getName()};
 867		Cursor cursor = db.query(SQLiteAxolotlStore.SESSION_TABLENAME,
 868				columns,
 869				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 870						+ SQLiteAxolotlStore.NAME + " = ?",
 871				selectionArgs,
 872				null, null, null);
 873
 874		while (cursor.moveToNext()) {
 875			devices.add(cursor.getInt(
 876					cursor.getColumnIndex(SQLiteAxolotlStore.DEVICE_ID)));
 877		}
 878
 879		cursor.close();
 880		return devices;
 881	}
 882
 883	public boolean containsSession(Account account, AxolotlAddress contact) {
 884		Cursor cursor = getCursorForSession(account, contact);
 885		int count = cursor.getCount();
 886		cursor.close();
 887		return count != 0;
 888	}
 889
 890	public void storeSession(Account account, AxolotlAddress contact, SessionRecord session) {
 891		SQLiteDatabase db = this.getWritableDatabase();
 892		ContentValues values = new ContentValues();
 893		values.put(SQLiteAxolotlStore.NAME, contact.getName());
 894		values.put(SQLiteAxolotlStore.DEVICE_ID, contact.getDeviceId());
 895		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(session.serialize(), Base64.DEFAULT));
 896		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
 897		db.insert(SQLiteAxolotlStore.SESSION_TABLENAME, null, values);
 898	}
 899
 900	public void deleteSession(Account account, AxolotlAddress contact) {
 901		SQLiteDatabase db = this.getWritableDatabase();
 902		deleteSession(db, account, contact);
 903	}
 904
 905	private void deleteSession(SQLiteDatabase db, Account account, AxolotlAddress contact) {
 906		String[] args = {account.getUuid(),
 907				contact.getName(),
 908				Integer.toString(contact.getDeviceId())};
 909		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
 910				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
 911						+ SQLiteAxolotlStore.NAME + " = ? AND "
 912						+ SQLiteAxolotlStore.DEVICE_ID + " = ? ",
 913				args);
 914	}
 915
 916	public void deleteAllSessions(Account account, AxolotlAddress contact) {
 917		SQLiteDatabase db = this.getWritableDatabase();
 918		String[] args = {account.getUuid(), contact.getName()};
 919		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
 920				SQLiteAxolotlStore.ACCOUNT + "=? AND "
 921						+ SQLiteAxolotlStore.NAME + " = ?",
 922				args);
 923	}
 924
 925	private Cursor getCursorForPreKey(Account account, int preKeyId) {
 926		SQLiteDatabase db = this.getReadableDatabase();
 927		String[] columns = {SQLiteAxolotlStore.KEY};
 928		String[] selectionArgs = {account.getUuid(), Integer.toString(preKeyId)};
 929		Cursor cursor = db.query(SQLiteAxolotlStore.PREKEY_TABLENAME,
 930				columns,
 931				SQLiteAxolotlStore.ACCOUNT + "=? AND "
 932						+ SQLiteAxolotlStore.ID + "=?",
 933				selectionArgs,
 934				null, null, null);
 935
 936		return cursor;
 937	}
 938
 939	public PreKeyRecord loadPreKey(Account account, int preKeyId) {
 940		PreKeyRecord record = null;
 941		Cursor cursor = getCursorForPreKey(account, preKeyId);
 942		if (cursor.getCount() != 0) {
 943			cursor.moveToFirst();
 944			try {
 945				record = new PreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
 946			} catch (IOException e) {
 947				throw new AssertionError(e);
 948			}
 949		}
 950		cursor.close();
 951		return record;
 952	}
 953
 954	public boolean containsPreKey(Account account, int preKeyId) {
 955		Cursor cursor = getCursorForPreKey(account, preKeyId);
 956		int count = cursor.getCount();
 957		cursor.close();
 958		return count != 0;
 959	}
 960
 961	public void storePreKey(Account account, PreKeyRecord record) {
 962		SQLiteDatabase db = this.getWritableDatabase();
 963		ContentValues values = new ContentValues();
 964		values.put(SQLiteAxolotlStore.ID, record.getId());
 965		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
 966		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
 967		db.insert(SQLiteAxolotlStore.PREKEY_TABLENAME, null, values);
 968	}
 969
 970	public void deletePreKey(Account account, int preKeyId) {
 971		SQLiteDatabase db = this.getWritableDatabase();
 972		String[] args = {account.getUuid(), Integer.toString(preKeyId)};
 973		db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
 974				SQLiteAxolotlStore.ACCOUNT + "=? AND "
 975						+ SQLiteAxolotlStore.ID + "=?",
 976				args);
 977	}
 978
 979	private Cursor getCursorForSignedPreKey(Account account, int signedPreKeyId) {
 980		SQLiteDatabase db = this.getReadableDatabase();
 981		String[] columns = {SQLiteAxolotlStore.KEY};
 982		String[] selectionArgs = {account.getUuid(), Integer.toString(signedPreKeyId)};
 983		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
 984				columns,
 985				SQLiteAxolotlStore.ACCOUNT + "=? AND " + SQLiteAxolotlStore.ID + "=?",
 986				selectionArgs,
 987				null, null, null);
 988
 989		return cursor;
 990	}
 991
 992	public SignedPreKeyRecord loadSignedPreKey(Account account, int signedPreKeyId) {
 993		SignedPreKeyRecord record = null;
 994		Cursor cursor = getCursorForSignedPreKey(account, signedPreKeyId);
 995		if (cursor.getCount() != 0) {
 996			cursor.moveToFirst();
 997			try {
 998				record = new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
 999			} catch (IOException e) {
1000				throw new AssertionError(e);
1001			}
1002		}
1003		cursor.close();
1004		return record;
1005	}
1006
1007	public List<SignedPreKeyRecord> loadSignedPreKeys(Account account) {
1008		List<SignedPreKeyRecord> prekeys = new ArrayList<>();
1009		SQLiteDatabase db = this.getReadableDatabase();
1010		String[] columns = {SQLiteAxolotlStore.KEY};
1011		String[] selectionArgs = {account.getUuid()};
1012		Cursor cursor = db.query(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1013				columns,
1014				SQLiteAxolotlStore.ACCOUNT + "=?",
1015				selectionArgs,
1016				null, null, null);
1017
1018		while (cursor.moveToNext()) {
1019			try {
1020				prekeys.add(new SignedPreKeyRecord(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT)));
1021			} catch (IOException ignored) {
1022			}
1023		}
1024		cursor.close();
1025		return prekeys;
1026	}
1027
1028	public boolean containsSignedPreKey(Account account, int signedPreKeyId) {
1029		Cursor cursor = getCursorForPreKey(account, signedPreKeyId);
1030		int count = cursor.getCount();
1031		cursor.close();
1032		return count != 0;
1033	}
1034
1035	public void storeSignedPreKey(Account account, SignedPreKeyRecord record) {
1036		SQLiteDatabase db = this.getWritableDatabase();
1037		ContentValues values = new ContentValues();
1038		values.put(SQLiteAxolotlStore.ID, record.getId());
1039		values.put(SQLiteAxolotlStore.KEY, Base64.encodeToString(record.serialize(), Base64.DEFAULT));
1040		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1041		db.insert(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME, null, values);
1042	}
1043
1044	public void deleteSignedPreKey(Account account, int signedPreKeyId) {
1045		SQLiteDatabase db = this.getWritableDatabase();
1046		String[] args = {account.getUuid(), Integer.toString(signedPreKeyId)};
1047		db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1048				SQLiteAxolotlStore.ACCOUNT + "=? AND "
1049						+ SQLiteAxolotlStore.ID + "=?",
1050				args);
1051	}
1052
1053	private Cursor getIdentityKeyCursor(Account account, String name, boolean own) {
1054		final SQLiteDatabase db = this.getReadableDatabase();
1055		return getIdentityKeyCursor(db, account, name, own);
1056	}
1057
1058	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, boolean own) {
1059		return getIdentityKeyCursor(db, account, name, own, null);
1060	}
1061
1062	private Cursor getIdentityKeyCursor(Account account, String fingerprint) {
1063		final SQLiteDatabase db = this.getReadableDatabase();
1064		return getIdentityKeyCursor(db, account, fingerprint);
1065	}
1066
1067	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String fingerprint) {
1068		return getIdentityKeyCursor(db, account, null, null, fingerprint);
1069	}
1070
1071	private Cursor getIdentityKeyCursor(SQLiteDatabase db, Account account, String name, Boolean own, String fingerprint) {
1072		String[] columns = {SQLiteAxolotlStore.TRUST,
1073				SQLiteAxolotlStore.ACTIVE,
1074				SQLiteAxolotlStore.LAST_ACTIVATION,
1075				SQLiteAxolotlStore.KEY};
1076		ArrayList<String> selectionArgs = new ArrayList<>(4);
1077		selectionArgs.add(account.getUuid());
1078		String selectionString = SQLiteAxolotlStore.ACCOUNT + " = ?";
1079		if (name != null) {
1080			selectionArgs.add(name);
1081			selectionString += " AND " + SQLiteAxolotlStore.NAME + " = ?";
1082		}
1083		if (fingerprint != null) {
1084			selectionArgs.add(fingerprint);
1085			selectionString += " AND " + SQLiteAxolotlStore.FINGERPRINT + " = ?";
1086		}
1087		if (own != null) {
1088			selectionArgs.add(own ? "1" : "0");
1089			selectionString += " AND " + SQLiteAxolotlStore.OWN + " = ?";
1090		}
1091		Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1092				columns,
1093				selectionString,
1094				selectionArgs.toArray(new String[selectionArgs.size()]),
1095				null, null, null);
1096
1097		return cursor;
1098	}
1099
1100	public IdentityKeyPair loadOwnIdentityKeyPair(Account account) {
1101		SQLiteDatabase db = getReadableDatabase();
1102		return loadOwnIdentityKeyPair(db, account);
1103	}
1104
1105	private IdentityKeyPair loadOwnIdentityKeyPair(SQLiteDatabase db, Account account) {
1106		String name = account.getJid().toBareJid().toPreppedString();
1107		IdentityKeyPair identityKeyPair = null;
1108		Cursor cursor = getIdentityKeyCursor(db, account, name, true);
1109		if (cursor.getCount() != 0) {
1110			cursor.moveToFirst();
1111			try {
1112				identityKeyPair = new IdentityKeyPair(Base64.decode(cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY)), Base64.DEFAULT));
1113			} catch (InvalidKeyException e) {
1114				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().toBareJid() + ", address: " + name);
1115			}
1116		}
1117		cursor.close();
1118
1119		return identityKeyPair;
1120	}
1121
1122	public Set<IdentityKey> loadIdentityKeys(Account account, String name) {
1123		return loadIdentityKeys(account, name, null);
1124	}
1125
1126	public Set<IdentityKey> loadIdentityKeys(Account account, String name, FingerprintStatus status) {
1127		Set<IdentityKey> identityKeys = new HashSet<>();
1128		Cursor cursor = getIdentityKeyCursor(account, name, false);
1129
1130		while (cursor.moveToNext()) {
1131			if (status != null && !FingerprintStatus.fromCursor(cursor).equals(status)) {
1132				continue;
1133			}
1134			try {
1135				String key = cursor.getString(cursor.getColumnIndex(SQLiteAxolotlStore.KEY));
1136				if (key != null) {
1137					identityKeys.add(new IdentityKey(Base64.decode(key, Base64.DEFAULT), 0));
1138				} else {
1139					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Missing key (possibly preverified) in database for account" + account.getJid().toBareJid() + ", address: " + name);
1140				}
1141			} catch (InvalidKeyException e) {
1142				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Encountered invalid IdentityKey in database for account" + account.getJid().toBareJid() + ", address: " + name);
1143			}
1144		}
1145		cursor.close();
1146
1147		return identityKeys;
1148	}
1149
1150	public long numTrustedKeys(Account account, String name) {
1151		SQLiteDatabase db = getReadableDatabase();
1152		String[] args = {
1153				account.getUuid(),
1154				name,
1155				FingerprintStatus.Trust.TRUSTED.toString(),
1156				FingerprintStatus.Trust.VERIFIED.toString(),
1157				FingerprintStatus.Trust.VERIFIED_X509.toString()
1158		};
1159		return DatabaseUtils.queryNumEntries(db, SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1160				SQLiteAxolotlStore.ACCOUNT + " = ?"
1161						+ " AND " + SQLiteAxolotlStore.NAME + " = ?"
1162						+ " AND (" + SQLiteAxolotlStore.TRUST + " = ? OR " + SQLiteAxolotlStore.TRUST + " = ? OR " +SQLiteAxolotlStore.TRUST +" = ?)"
1163						+ " AND " +SQLiteAxolotlStore.ACTIVE + " > 0",
1164				args
1165		);
1166	}
1167
1168	private void storeIdentityKey(Account account, String name, boolean own, String fingerprint, String base64Serialized, FingerprintStatus status) {
1169		SQLiteDatabase db = this.getWritableDatabase();
1170		ContentValues values = new ContentValues();
1171		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1172		values.put(SQLiteAxolotlStore.NAME, name);
1173		values.put(SQLiteAxolotlStore.OWN, own ? 1 : 0);
1174		values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1175		values.put(SQLiteAxolotlStore.KEY, base64Serialized);
1176		values.putAll(status.toContentValues());
1177		String where = SQLiteAxolotlStore.ACCOUNT+"=? AND "+SQLiteAxolotlStore.NAME+"=? AND "+SQLiteAxolotlStore.FINGERPRINT+" =?";
1178		String[] whereArgs = {account.getUuid(),name,fingerprint};
1179		int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME,values,where,whereArgs);
1180		if (rows == 0) {
1181			db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1182		}
1183	}
1184
1185	public void storePreVerification(Account account, String name, String fingerprint, FingerprintStatus status) {
1186		SQLiteDatabase db = this.getWritableDatabase();
1187		ContentValues values = new ContentValues();
1188		values.put(SQLiteAxolotlStore.ACCOUNT, account.getUuid());
1189		values.put(SQLiteAxolotlStore.NAME, name);
1190		values.put(SQLiteAxolotlStore.OWN, 0);
1191		values.put(SQLiteAxolotlStore.FINGERPRINT, fingerprint);
1192		values.putAll(status.toContentValues());
1193		db.insert(SQLiteAxolotlStore.IDENTITIES_TABLENAME, null, values);
1194	}
1195
1196	public FingerprintStatus getFingerprintStatus(Account account, String fingerprint) {
1197		Cursor cursor = getIdentityKeyCursor(account, fingerprint);
1198		final FingerprintStatus status;
1199		if (cursor.getCount() > 0) {
1200			cursor.moveToFirst();
1201			status = FingerprintStatus.fromCursor(cursor);
1202		} else {
1203			status = null;
1204		}
1205		cursor.close();
1206		return status;
1207	}
1208
1209	public boolean setIdentityKeyTrust(Account account, String fingerprint, FingerprintStatus fingerprintStatus) {
1210		SQLiteDatabase db = this.getWritableDatabase();
1211		return setIdentityKeyTrust(db, account, fingerprint, fingerprintStatus);
1212	}
1213
1214	private boolean setIdentityKeyTrust(SQLiteDatabase db, Account account, String fingerprint, FingerprintStatus status) {
1215		String[] selectionArgs = {
1216				account.getUuid(),
1217				fingerprint
1218		};
1219		int rows = db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, status.toContentValues(),
1220				SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1221						+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1222				selectionArgs);
1223		return rows == 1;
1224	}
1225
1226	public boolean setIdentityKeyCertificate(Account account, String fingerprint, X509Certificate x509Certificate) {
1227		SQLiteDatabase db = this.getWritableDatabase();
1228		String[] selectionArgs = {
1229				account.getUuid(),
1230				fingerprint
1231		};
1232		try {
1233			ContentValues values = new ContentValues();
1234			values.put(SQLiteAxolotlStore.CERTIFICATE, x509Certificate.getEncoded());
1235			return db.update(SQLiteAxolotlStore.IDENTITIES_TABLENAME, values,
1236					SQLiteAxolotlStore.ACCOUNT + " = ? AND "
1237							+ SQLiteAxolotlStore.FINGERPRINT + " = ? ",
1238					selectionArgs) == 1;
1239		} catch (CertificateEncodingException e) {
1240			Log.d(Config.LOGTAG, "could not encode certificate");
1241			return false;
1242		}
1243	}
1244
1245	public X509Certificate getIdentityKeyCertifcate(Account account, String fingerprint) {
1246		SQLiteDatabase db = this.getReadableDatabase();
1247		String[] selectionArgs = {
1248				account.getUuid(),
1249				fingerprint
1250		};
1251		String[] colums = {SQLiteAxolotlStore.CERTIFICATE};
1252		String selection = SQLiteAxolotlStore.ACCOUNT + " = ? AND " + SQLiteAxolotlStore.FINGERPRINT + " = ? ";
1253		Cursor cursor = db.query(SQLiteAxolotlStore.IDENTITIES_TABLENAME, colums, selection, selectionArgs, null, null, null);
1254		if (cursor.getCount() < 1) {
1255			return null;
1256		} else {
1257			cursor.moveToFirst();
1258			byte[] certificate = cursor.getBlob(cursor.getColumnIndex(SQLiteAxolotlStore.CERTIFICATE));
1259			cursor.close();
1260			if (certificate == null || certificate.length == 0) {
1261				return null;
1262			}
1263			try {
1264				CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
1265				return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificate));
1266			} catch (CertificateException e) {
1267				Log.d(Config.LOGTAG,"certificate exception "+e.getMessage());
1268				return null;
1269			}
1270		}
1271	}
1272
1273	public void storeIdentityKey(Account account, String name, IdentityKey identityKey, FingerprintStatus status) {
1274		storeIdentityKey(account, name, false, identityKey.getFingerprint().replaceAll("\\s", ""), Base64.encodeToString(identityKey.serialize(), Base64.DEFAULT), status);
1275	}
1276
1277	public void storeOwnIdentityKeyPair(Account account, IdentityKeyPair identityKeyPair) {
1278		storeIdentityKey(account, account.getJid().toBareJid().toPreppedString(), true, identityKeyPair.getPublicKey().getFingerprint().replaceAll("\\s", ""), Base64.encodeToString(identityKeyPair.serialize(), Base64.DEFAULT), FingerprintStatus.createActiveVerified(false));
1279	}
1280
1281
1282	public void recreateAxolotlDb(SQLiteDatabase db) {
1283		Log.d(Config.LOGTAG, AxolotlService.LOGPREFIX + " : " + ">>> (RE)CREATING AXOLOTL DATABASE <<<");
1284		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SESSION_TABLENAME);
1285		db.execSQL(CREATE_SESSIONS_STATEMENT);
1286		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.PREKEY_TABLENAME);
1287		db.execSQL(CREATE_PREKEYS_STATEMENT);
1288		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME);
1289		db.execSQL(CREATE_SIGNED_PREKEYS_STATEMENT);
1290		db.execSQL("DROP TABLE IF EXISTS " + SQLiteAxolotlStore.IDENTITIES_TABLENAME);
1291		db.execSQL(CREATE_IDENTITIES_STATEMENT);
1292	}
1293
1294	public void wipeAxolotlDb(Account account) {
1295		String accountName = account.getUuid();
1296		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ">>> WIPING AXOLOTL DATABASE FOR ACCOUNT " + accountName + " <<<");
1297		SQLiteDatabase db = this.getWritableDatabase();
1298		String[] deleteArgs = {
1299				accountName
1300		};
1301		db.delete(SQLiteAxolotlStore.SESSION_TABLENAME,
1302				SQLiteAxolotlStore.ACCOUNT + " = ?",
1303				deleteArgs);
1304		db.delete(SQLiteAxolotlStore.PREKEY_TABLENAME,
1305				SQLiteAxolotlStore.ACCOUNT + " = ?",
1306				deleteArgs);
1307		db.delete(SQLiteAxolotlStore.SIGNED_PREKEY_TABLENAME,
1308				SQLiteAxolotlStore.ACCOUNT + " = ?",
1309				deleteArgs);
1310		db.delete(SQLiteAxolotlStore.IDENTITIES_TABLENAME,
1311				SQLiteAxolotlStore.ACCOUNT + " = ?",
1312				deleteArgs);
1313	}
1314
1315	public boolean startTimeCountExceedsThreshold() {
1316		SQLiteDatabase db = this.getWritableDatabase();
1317		long cleanBeforeTimestamp = System.currentTimeMillis() - Config.FREQUENT_RESTARTS_DETECTION_WINDOW;
1318		db.execSQL("delete from "+START_TIMES_TABLE+" where timestamp < "+cleanBeforeTimestamp);
1319		ContentValues values = new ContentValues();
1320		values.put("timestamp",System.currentTimeMillis());
1321		db.insert(START_TIMES_TABLE,null,values);
1322		String[] columns = new String[]{"count(timestamp)"};
1323		Cursor cursor = db.query(START_TIMES_TABLE,columns,null,null,null,null,null);
1324		int count;
1325		if (cursor.moveToFirst()) {
1326			count = cursor.getInt(0);
1327		} else {
1328			count = 0;
1329		}
1330		cursor.close();
1331		Log.d(Config.LOGTAG,"start time counter reached "+count);
1332		return count >= Config.FREQUENT_RESTARTS_THRESHOLD;
1333	}
1334
1335	public void clearStartTimeCounter(boolean justOne) {
1336		SQLiteDatabase db = this.getWritableDatabase();
1337		if (justOne) {
1338			db.execSQL("delete from "+START_TIMES_TABLE+" where timestamp in (select timestamp from "+START_TIMES_TABLE+" order by timestamp desc limit 1)");
1339			Log.d(Config.LOGTAG,"do not count start up after being swiped away");
1340		} else {
1341			Log.d(Config.LOGTAG,"resetting start time counter");
1342			db.execSQL("delete from " + START_TIMES_TABLE);
1343		}
1344	}
1345}