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