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