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