AxolotlService.java

   1package eu.siacs.conversations.crypto.axolotl;
   2
   3import android.support.annotation.NonNull;
   4import android.support.annotation.Nullable;
   5import android.util.Base64;
   6import android.util.Log;
   7
   8import org.whispersystems.libaxolotl.AxolotlAddress;
   9import org.whispersystems.libaxolotl.DuplicateMessageException;
  10import org.whispersystems.libaxolotl.IdentityKey;
  11import org.whispersystems.libaxolotl.IdentityKeyPair;
  12import org.whispersystems.libaxolotl.InvalidKeyException;
  13import org.whispersystems.libaxolotl.InvalidKeyIdException;
  14import org.whispersystems.libaxolotl.InvalidMessageException;
  15import org.whispersystems.libaxolotl.InvalidVersionException;
  16import org.whispersystems.libaxolotl.LegacyMessageException;
  17import org.whispersystems.libaxolotl.NoSessionException;
  18import org.whispersystems.libaxolotl.SessionBuilder;
  19import org.whispersystems.libaxolotl.SessionCipher;
  20import org.whispersystems.libaxolotl.UntrustedIdentityException;
  21import org.whispersystems.libaxolotl.ecc.Curve;
  22import org.whispersystems.libaxolotl.ecc.ECKeyPair;
  23import org.whispersystems.libaxolotl.ecc.ECPublicKey;
  24import org.whispersystems.libaxolotl.protocol.CiphertextMessage;
  25import org.whispersystems.libaxolotl.protocol.PreKeyWhisperMessage;
  26import org.whispersystems.libaxolotl.protocol.WhisperMessage;
  27import org.whispersystems.libaxolotl.state.AxolotlStore;
  28import org.whispersystems.libaxolotl.state.PreKeyBundle;
  29import org.whispersystems.libaxolotl.state.PreKeyRecord;
  30import org.whispersystems.libaxolotl.state.SessionRecord;
  31import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
  32import org.whispersystems.libaxolotl.util.KeyHelper;
  33
  34import java.util.ArrayList;
  35import java.util.Arrays;
  36import java.util.HashMap;
  37import java.util.HashSet;
  38import java.util.List;
  39import java.util.Map;
  40import java.util.Random;
  41import java.util.Set;
  42
  43import eu.siacs.conversations.Config;
  44import eu.siacs.conversations.entities.Account;
  45import eu.siacs.conversations.entities.Contact;
  46import eu.siacs.conversations.entities.Conversation;
  47import eu.siacs.conversations.entities.Message;
  48import eu.siacs.conversations.parser.IqParser;
  49import eu.siacs.conversations.services.XmppConnectionService;
  50import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
  51import eu.siacs.conversations.xml.Element;
  52import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  53import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  54import eu.siacs.conversations.xmpp.jid.Jid;
  55import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  56import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  57
  58public class AxolotlService {
  59
  60	public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl";
  61	public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist";
  62	public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
  63
  64	public static final String LOGPREFIX = "AxolotlService";
  65
  66	public static final int NUM_KEYS_TO_PUBLISH = 10;
  67
  68	private final Account account;
  69	private final XmppConnectionService mXmppConnectionService;
  70	private final SQLiteAxolotlStore axolotlStore;
  71	private final SessionMap sessions;
  72	private final Map<Jid, Set<Integer>> deviceIds;
  73	private final Map<String, MessagePacket> messageCache;
  74	private final FetchStatusMap fetchStatusMap;
  75	private final SerialSingleThreadExecutor executor;
  76
  77	public static class SQLiteAxolotlStore implements AxolotlStore {
  78
  79		public static final String PREKEY_TABLENAME = "prekeys";
  80		public static final String SIGNED_PREKEY_TABLENAME = "signed_prekeys";
  81		public static final String SESSION_TABLENAME = "sessions";
  82		public static final String IDENTITIES_TABLENAME = "identities";
  83		public static final String ACCOUNT = "account";
  84		public static final String DEVICE_ID = "device_id";
  85		public static final String ID = "id";
  86		public static final String KEY = "key";
  87		public static final String FINGERPRINT = "fingerprint";
  88		public static final String NAME = "name";
  89		public static final String TRUSTED = "trusted";
  90		public static final String OWN = "ownkey";
  91
  92		public static final String JSONKEY_REGISTRATION_ID = "axolotl_reg_id";
  93		public static final String JSONKEY_CURRENT_PREKEY_ID = "axolotl_cur_prekey_id";
  94
  95		private final Account account;
  96		private final XmppConnectionService mXmppConnectionService;
  97
  98		private IdentityKeyPair identityKeyPair;
  99		private int localRegistrationId;
 100		private int currentPreKeyId = 0;
 101
 102		public enum Trust {
 103			UNDECIDED, // 0
 104			TRUSTED,
 105			UNTRUSTED;
 106
 107			public String toString() {
 108				switch(this){
 109					case UNDECIDED:
 110						return "Trust undecided";
 111					case TRUSTED:
 112						return "Trusted";
 113					case UNTRUSTED:
 114					default:
 115						return "Untrusted";
 116				}
 117			}
 118		};
 119
 120		private static IdentityKeyPair generateIdentityKeyPair() {
 121			Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Generating axolotl IdentityKeyPair...");
 122			ECKeyPair identityKeyPairKeys = Curve.generateKeyPair();
 123			IdentityKeyPair ownKey = new IdentityKeyPair(new IdentityKey(identityKeyPairKeys.getPublicKey()),
 124					identityKeyPairKeys.getPrivateKey());
 125			return ownKey;
 126		}
 127
 128		private static int generateRegistrationId() {
 129			Log.i(Config.LOGTAG, AxolotlService.LOGPREFIX+" : "+"Generating axolotl registration ID...");
 130			int reg_id = KeyHelper.generateRegistrationId(true);
 131			return reg_id;
 132		}
 133
 134		public SQLiteAxolotlStore(Account account, XmppConnectionService service) {
 135			this.account = account;
 136			this.mXmppConnectionService = service;
 137			this.localRegistrationId = loadRegistrationId();
 138			this.currentPreKeyId = loadCurrentPreKeyId();
 139			for (SignedPreKeyRecord record : loadSignedPreKeys()) {
 140				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Got Axolotl signed prekey record:" + record.getId());
 141			}
 142		}
 143
 144		public int getCurrentPreKeyId() {
 145			return currentPreKeyId;
 146		}
 147
 148		// --------------------------------------
 149		// IdentityKeyStore
 150		// --------------------------------------
 151
 152		private IdentityKeyPair loadIdentityKeyPair() {
 153			String ownName = account.getJid().toBareJid().toString();
 154			IdentityKeyPair ownKey = mXmppConnectionService.databaseBackend.loadOwnIdentityKeyPair(account,
 155					ownName);
 156
 157			if (ownKey != null) {
 158				return ownKey;
 159			} else {
 160				Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Could not retrieve axolotl key for account " + ownName);
 161				ownKey = generateIdentityKeyPair();
 162				mXmppConnectionService.databaseBackend.storeOwnIdentityKeyPair(account, ownName, ownKey);
 163			}
 164			return ownKey;
 165		}
 166
 167		private int loadRegistrationId() {
 168			return loadRegistrationId(false);
 169		}
 170
 171		private int loadRegistrationId(boolean regenerate) {
 172			String regIdString = this.account.getKey(JSONKEY_REGISTRATION_ID);
 173			int reg_id;
 174			if (!regenerate && regIdString != null) {
 175				reg_id = Integer.valueOf(regIdString);
 176			} else {
 177				Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Could not retrieve axolotl registration id for account " + account.getJid());
 178				reg_id = generateRegistrationId();
 179				boolean success = this.account.setKey(JSONKEY_REGISTRATION_ID, Integer.toString(reg_id));
 180				if (success) {
 181					mXmppConnectionService.databaseBackend.updateAccount(account);
 182				} else {
 183					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Failed to write new key to the database!");
 184				}
 185			}
 186			return reg_id;
 187		}
 188
 189		private int loadCurrentPreKeyId() {
 190			String regIdString = this.account.getKey(JSONKEY_CURRENT_PREKEY_ID);
 191			int reg_id;
 192			if (regIdString != null) {
 193				reg_id = Integer.valueOf(regIdString);
 194			} else {
 195				Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Could not retrieve current prekey id for account " + account.getJid());
 196				reg_id = 0;
 197			}
 198			return reg_id;
 199		}
 200
 201		public void regenerate() {
 202			mXmppConnectionService.databaseBackend.wipeAxolotlDb(account);
 203			account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(0));
 204			identityKeyPair = loadIdentityKeyPair();
 205			localRegistrationId = loadRegistrationId(true);
 206			currentPreKeyId = 0;
 207			mXmppConnectionService.updateAccountUi();
 208		}
 209
 210		/**
 211		 * Get the local client's identity key pair.
 212		 *
 213		 * @return The local client's persistent identity key pair.
 214		 */
 215		@Override
 216		public IdentityKeyPair getIdentityKeyPair() {
 217			if(identityKeyPair == null) {
 218				identityKeyPair = loadIdentityKeyPair();
 219			}
 220			return identityKeyPair;
 221		}
 222
 223		/**
 224		 * Return the local client's registration ID.
 225		 * <p/>
 226		 * Clients should maintain a registration ID, a random number
 227		 * between 1 and 16380 that's generated once at install time.
 228		 *
 229		 * @return the local client's registration ID.
 230		 */
 231		@Override
 232		public int getLocalRegistrationId() {
 233			return localRegistrationId;
 234		}
 235
 236		/**
 237		 * Save a remote client's identity key
 238		 * <p/>
 239		 * Store a remote client's identity key as trusted.
 240		 *
 241		 * @param name        The name of the remote client.
 242		 * @param identityKey The remote client's identity key.
 243		 */
 244		@Override
 245		public void saveIdentity(String name, IdentityKey identityKey) {
 246			if(!mXmppConnectionService.databaseBackend.loadIdentityKeys(account, name).contains(identityKey)) {
 247				mXmppConnectionService.databaseBackend.storeIdentityKey(account, name, identityKey);
 248			}
 249		}
 250
 251		/**
 252		 * Verify a remote client's identity key.
 253		 * <p/>
 254		 * Determine whether a remote client's identity is trusted.  Convention is
 255		 * that the TextSecure protocol is 'trust on first use.'  This means that
 256		 * an identity key is considered 'trusted' if there is no entry for the recipient
 257		 * in the local store, or if it matches the saved key for a recipient in the local
 258		 * store.  Only if it mismatches an entry in the local store is it considered
 259		 * 'untrusted.'
 260		 *
 261		 * @param name        The name of the remote client.
 262		 * @param identityKey The identity key to verify.
 263		 * @return true if trusted, false if untrusted.
 264		 */
 265		@Override
 266		public boolean isTrustedIdentity(String name, IdentityKey identityKey) {
 267			return true;
 268		}
 269
 270		public Trust getFingerprintTrust(String name, String fingerprint) {
 271			return mXmppConnectionService.databaseBackend.isIdentityKeyTrusted(account, name, fingerprint);
 272		}
 273
 274		public void setFingerprintTrust(String name, String fingerprint, Trust trust) {
 275			mXmppConnectionService.databaseBackend.setIdentityKeyTrust(account, name, fingerprint, trust);
 276		}
 277
 278		// --------------------------------------
 279		// SessionStore
 280		// --------------------------------------
 281
 282		/**
 283		 * Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple,
 284		 * or a new SessionRecord if one does not currently exist.
 285		 * <p/>
 286		 * It is important that implementations return a copy of the current durable information.  The
 287		 * returned SessionRecord may be modified, but those changes should not have an effect on the
 288		 * durable session state (what is returned by subsequent calls to this method) without the
 289		 * store method being called here first.
 290		 *
 291		 * @param address The name and device ID of the remote client.
 292		 * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or
 293		 * a new SessionRecord if one does not currently exist.
 294		 */
 295		@Override
 296		public SessionRecord loadSession(AxolotlAddress address) {
 297			SessionRecord session = mXmppConnectionService.databaseBackend.loadSession(this.account, address);
 298			return (session != null) ? session : new SessionRecord();
 299		}
 300
 301		/**
 302		 * Returns all known devices with active sessions for a recipient
 303		 *
 304		 * @param name the name of the client.
 305		 * @return all known sub-devices with active sessions.
 306		 */
 307		@Override
 308		public List<Integer> getSubDeviceSessions(String name) {
 309			return mXmppConnectionService.databaseBackend.getSubDeviceSessions(account,
 310					new AxolotlAddress(name, 0));
 311		}
 312
 313		/**
 314		 * Commit to storage the {@link SessionRecord} for a given recipientId + deviceId tuple.
 315		 *
 316		 * @param address the address of the remote client.
 317		 * @param record  the current SessionRecord for the remote client.
 318		 */
 319		@Override
 320		public void storeSession(AxolotlAddress address, SessionRecord record) {
 321			mXmppConnectionService.databaseBackend.storeSession(account, address, record);
 322		}
 323
 324		/**
 325		 * Determine whether there is a committed {@link SessionRecord} for a recipientId + deviceId tuple.
 326		 *
 327		 * @param address the address of the remote client.
 328		 * @return true if a {@link SessionRecord} exists, false otherwise.
 329		 */
 330		@Override
 331		public boolean containsSession(AxolotlAddress address) {
 332			return mXmppConnectionService.databaseBackend.containsSession(account, address);
 333		}
 334
 335		/**
 336		 * Remove a {@link SessionRecord} for a recipientId + deviceId tuple.
 337		 *
 338		 * @param address the address of the remote client.
 339		 */
 340		@Override
 341		public void deleteSession(AxolotlAddress address) {
 342			mXmppConnectionService.databaseBackend.deleteSession(account, address);
 343		}
 344
 345		/**
 346		 * Remove the {@link SessionRecord}s corresponding to all devices of a recipientId.
 347		 *
 348		 * @param name the name of the remote client.
 349		 */
 350		@Override
 351		public void deleteAllSessions(String name) {
 352			mXmppConnectionService.databaseBackend.deleteAllSessions(account,
 353					new AxolotlAddress(name, 0));
 354		}
 355
 356		// --------------------------------------
 357		// PreKeyStore
 358		// --------------------------------------
 359
 360		/**
 361		 * Load a local PreKeyRecord.
 362		 *
 363		 * @param preKeyId the ID of the local PreKeyRecord.
 364		 * @return the corresponding PreKeyRecord.
 365		 * @throws InvalidKeyIdException when there is no corresponding PreKeyRecord.
 366		 */
 367		@Override
 368		public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
 369			PreKeyRecord record = mXmppConnectionService.databaseBackend.loadPreKey(account, preKeyId);
 370			if (record == null) {
 371				throw new InvalidKeyIdException("No such PreKeyRecord: " + preKeyId);
 372			}
 373			return record;
 374		}
 375
 376		/**
 377		 * Store a local PreKeyRecord.
 378		 *
 379		 * @param preKeyId the ID of the PreKeyRecord to store.
 380		 * @param record   the PreKeyRecord.
 381		 */
 382		@Override
 383		public void storePreKey(int preKeyId, PreKeyRecord record) {
 384			mXmppConnectionService.databaseBackend.storePreKey(account, record);
 385			currentPreKeyId = preKeyId;
 386			boolean success = this.account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(preKeyId));
 387			if (success) {
 388				mXmppConnectionService.databaseBackend.updateAccount(account);
 389			} else {
 390				Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Failed to write new prekey id to the database!");
 391			}
 392		}
 393
 394		/**
 395		 * @param preKeyId A PreKeyRecord ID.
 396		 * @return true if the store has a record for the preKeyId, otherwise false.
 397		 */
 398		@Override
 399		public boolean containsPreKey(int preKeyId) {
 400			return mXmppConnectionService.databaseBackend.containsPreKey(account, preKeyId);
 401		}
 402
 403		/**
 404		 * Delete a PreKeyRecord from local storage.
 405		 *
 406		 * @param preKeyId The ID of the PreKeyRecord to remove.
 407		 */
 408		@Override
 409		public void removePreKey(int preKeyId) {
 410			mXmppConnectionService.databaseBackend.deletePreKey(account, preKeyId);
 411		}
 412
 413		// --------------------------------------
 414		// SignedPreKeyStore
 415		// --------------------------------------
 416
 417		/**
 418		 * Load a local SignedPreKeyRecord.
 419		 *
 420		 * @param signedPreKeyId the ID of the local SignedPreKeyRecord.
 421		 * @return the corresponding SignedPreKeyRecord.
 422		 * @throws InvalidKeyIdException when there is no corresponding SignedPreKeyRecord.
 423		 */
 424		@Override
 425		public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
 426			SignedPreKeyRecord record = mXmppConnectionService.databaseBackend.loadSignedPreKey(account, signedPreKeyId);
 427			if (record == null) {
 428				throw new InvalidKeyIdException("No such SignedPreKeyRecord: " + signedPreKeyId);
 429			}
 430			return record;
 431		}
 432
 433		/**
 434		 * Load all local SignedPreKeyRecords.
 435		 *
 436		 * @return All stored SignedPreKeyRecords.
 437		 */
 438		@Override
 439		public List<SignedPreKeyRecord> loadSignedPreKeys() {
 440			return mXmppConnectionService.databaseBackend.loadSignedPreKeys(account);
 441		}
 442
 443		/**
 444		 * Store a local SignedPreKeyRecord.
 445		 *
 446		 * @param signedPreKeyId the ID of the SignedPreKeyRecord to store.
 447		 * @param record         the SignedPreKeyRecord.
 448		 */
 449		@Override
 450		public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
 451			mXmppConnectionService.databaseBackend.storeSignedPreKey(account, record);
 452		}
 453
 454		/**
 455		 * @param signedPreKeyId A SignedPreKeyRecord ID.
 456		 * @return true if the store has a record for the signedPreKeyId, otherwise false.
 457		 */
 458		@Override
 459		public boolean containsSignedPreKey(int signedPreKeyId) {
 460			return mXmppConnectionService.databaseBackend.containsSignedPreKey(account, signedPreKeyId);
 461		}
 462
 463		/**
 464		 * Delete a SignedPreKeyRecord from local storage.
 465		 *
 466		 * @param signedPreKeyId The ID of the SignedPreKeyRecord to remove.
 467		 */
 468		@Override
 469		public void removeSignedPreKey(int signedPreKeyId) {
 470			mXmppConnectionService.databaseBackend.deleteSignedPreKey(account, signedPreKeyId);
 471		}
 472	}
 473
 474	public static class XmppAxolotlSession {
 475		private final SessionCipher cipher;
 476		private Integer preKeyId = null;
 477		private final SQLiteAxolotlStore sqLiteAxolotlStore;
 478		private final AxolotlAddress remoteAddress;
 479		private final Account account;
 480		private String fingerprint = null;
 481
 482		public XmppAxolotlSession(Account account, SQLiteAxolotlStore store, AxolotlAddress remoteAddress, String fingerprint) {
 483			this(account, store, remoteAddress);
 484			this.fingerprint = fingerprint;
 485		}
 486
 487		public XmppAxolotlSession(Account account, SQLiteAxolotlStore store, AxolotlAddress remoteAddress) {
 488			this.cipher = new SessionCipher(store, remoteAddress);
 489			this.remoteAddress = remoteAddress;
 490			this.sqLiteAxolotlStore = store;
 491			this.account = account;
 492		}
 493
 494		public Integer getPreKeyId() {
 495			return preKeyId;
 496		}
 497
 498		public void resetPreKeyId() {
 499
 500			preKeyId = null;
 501		}
 502
 503		public String getFingerprint() {
 504			return fingerprint;
 505		}
 506
 507		public byte[] processReceiving(XmppAxolotlMessage.XmppAxolotlMessageHeader incomingHeader) {
 508			byte[] plaintext = null;
 509			try {
 510				try {
 511					PreKeyWhisperMessage message = new PreKeyWhisperMessage(incomingHeader.getContents());
 512					Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"PreKeyWhisperMessage received, new session ID:" + message.getSignedPreKeyId() + "/" + message.getPreKeyId());
 513					String fingerprint = message.getIdentityKey().getFingerprint().replaceAll("\\s", "");
 514					if (this.fingerprint != null && !this.fingerprint.equals(fingerprint)) {
 515						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Had session with fingerprint "+ this.fingerprint+", received message with fingerprint "+fingerprint);
 516					} else {
 517						this.fingerprint = fingerprint;
 518						plaintext = cipher.decrypt(message);
 519						if (message.getPreKeyId().isPresent()) {
 520							preKeyId = message.getPreKeyId().get();
 521						}
 522					}
 523				} catch (InvalidMessageException | InvalidVersionException e) {
 524					Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"WhisperMessage received");
 525					WhisperMessage message = new WhisperMessage(incomingHeader.getContents());
 526					plaintext = cipher.decrypt(message);
 527				} catch (InvalidKeyException | InvalidKeyIdException | UntrustedIdentityException e) {
 528					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
 529				}
 530			} catch (LegacyMessageException | InvalidMessageException | DuplicateMessageException | NoSessionException  e) {
 531				Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
 532			}
 533			return plaintext;
 534		}
 535
 536		public XmppAxolotlMessage.XmppAxolotlMessageHeader processSending(byte[] outgoingMessage) {
 537			CiphertextMessage ciphertextMessage = cipher.encrypt(outgoingMessage);
 538			XmppAxolotlMessage.XmppAxolotlMessageHeader header =
 539					new XmppAxolotlMessage.XmppAxolotlMessageHeader(remoteAddress.getDeviceId(),
 540							ciphertextMessage.serialize());
 541			return header;
 542		}
 543	}
 544
 545	private static class AxolotlAddressMap<T> {
 546		protected Map<String, Map<Integer, T>> map;
 547		protected final Object MAP_LOCK = new Object();
 548
 549		public AxolotlAddressMap() {
 550			this.map = new HashMap<>();
 551		}
 552
 553		public void put(AxolotlAddress address, T value) {
 554			synchronized (MAP_LOCK) {
 555				Map<Integer, T> devices = map.get(address.getName());
 556				if (devices == null) {
 557					devices = new HashMap<>();
 558					map.put(address.getName(), devices);
 559				}
 560				devices.put(address.getDeviceId(), value);
 561			}
 562		}
 563
 564		public T get(AxolotlAddress address) {
 565			synchronized (MAP_LOCK) {
 566				Map<Integer, T> devices = map.get(address.getName());
 567				if (devices == null) {
 568					return null;
 569				}
 570				return devices.get(address.getDeviceId());
 571			}
 572		}
 573
 574		public Map<Integer, T> getAll(AxolotlAddress address) {
 575			synchronized (MAP_LOCK) {
 576				Map<Integer, T> devices = map.get(address.getName());
 577				if (devices == null) {
 578					return new HashMap<>();
 579				}
 580				return devices;
 581			}
 582		}
 583
 584		public boolean hasAny(AxolotlAddress address) {
 585			synchronized (MAP_LOCK) {
 586				Map<Integer, T> devices = map.get(address.getName());
 587				return devices != null && !devices.isEmpty();
 588			}
 589		}
 590
 591		public void clear() {
 592			map.clear();
 593		}
 594
 595	}
 596
 597	private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
 598
 599		public SessionMap(SQLiteAxolotlStore store, Account account) {
 600			super();
 601			this.fillMap(store, account);
 602		}
 603
 604		private void fillMap(SQLiteAxolotlStore store, Account account) {
 605			for (Contact contact : account.getRoster().getContacts()) {
 606				Jid bareJid = contact.getJid().toBareJid();
 607				if (bareJid == null) {
 608					continue; // FIXME: handle this?
 609				}
 610				String address = bareJid.toString();
 611				List<Integer> deviceIDs = store.getSubDeviceSessions(address);
 612				for (Integer deviceId : deviceIDs) {
 613					AxolotlAddress axolotlAddress = new AxolotlAddress(address, deviceId);
 614					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building session for remote address: "+axolotlAddress.toString());
 615					String fingerprint = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey().getFingerprint().replaceAll("\\s", "");
 616					this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, fingerprint));
 617				}
 618			}
 619		}
 620
 621	}
 622
 623	private static enum FetchStatus {
 624		PENDING,
 625		SUCCESS,
 626		ERROR
 627	}
 628
 629	private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
 630
 631	}
 632	
 633	public static String getLogprefix(Account account) {
 634		return LOGPREFIX+" ("+account.getJid().toBareJid().toString()+"): ";
 635	}
 636
 637	public AxolotlService(Account account, XmppConnectionService connectionService) {
 638		this.mXmppConnectionService = connectionService;
 639		this.account = account;
 640		this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
 641		this.deviceIds = new HashMap<>();
 642		this.messageCache = new HashMap<>();
 643		this.sessions = new SessionMap(axolotlStore, account);
 644		this.fetchStatusMap = new FetchStatusMap();
 645		this.executor = new SerialSingleThreadExecutor();
 646	}
 647
 648	public IdentityKey getOwnPublicKey() {
 649		return axolotlStore.getIdentityKeyPair().getPublicKey();
 650	}
 651
 652	private AxolotlAddress getAddressForJid(Jid jid) {
 653		return new AxolotlAddress(jid.toString(), 0);
 654	}
 655
 656	private Set<XmppAxolotlSession> findOwnSessions() {
 657		AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
 658		Set<XmppAxolotlSession> ownDeviceSessions = new HashSet<>(this.sessions.getAll(ownAddress).values());
 659		return ownDeviceSessions;
 660	}
 661
 662	private Set<XmppAxolotlSession> findSessionsforContact(Contact contact) {
 663		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
 664		Set<XmppAxolotlSession> sessions = new HashSet<>(this.sessions.getAll(contactAddress).values());
 665		return sessions;
 666	}
 667
 668	private boolean hasAny(Contact contact) {
 669		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
 670		return sessions.hasAny(contactAddress);
 671	}
 672
 673	public void regenerateKeys() {
 674		axolotlStore.regenerate();
 675		sessions.clear();
 676		fetchStatusMap.clear();
 677		publishBundlesIfNeeded();
 678		publishOwnDeviceIdIfNeeded();
 679	}
 680
 681	public int getOwnDeviceId() {
 682		return axolotlStore.loadRegistrationId();
 683	}
 684
 685	public Set<Integer> getOwnDeviceIds() {
 686		return this.deviceIds.get(account.getJid().toBareJid());
 687	}
 688
 689	public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
 690		if(deviceIds.contains(getOwnDeviceId())) {
 691			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Skipping own Device ID:"+ jid + ":"+getOwnDeviceId());
 692			deviceIds.remove(getOwnDeviceId());
 693		}
 694		for(Integer i:deviceIds) {
 695			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding Device ID:"+ jid + ":"+i);
 696		}
 697		this.deviceIds.put(jid, deviceIds);
 698		publishOwnDeviceIdIfNeeded();
 699	}
 700
 701	public void wipeOtherPepDevices() {
 702		Set<Integer> deviceIds = new HashSet<>();
 703		deviceIds.add(getOwnDeviceId());
 704		IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
 705		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Wiping all other devices from Pep:" + publish);
 706		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 707			@Override
 708			public void onIqPacketReceived(Account account, IqPacket packet) {
 709				// TODO: implement this!
 710			}
 711		});
 712	}
 713
 714	public void publishOwnDeviceIdIfNeeded() {
 715		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
 716		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 717			@Override
 718			public void onIqPacketReceived(Account account, IqPacket packet) {
 719				Element item = mXmppConnectionService.getIqParser().getItem(packet);
 720				Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
 721				if (deviceIds == null) {
 722					deviceIds = new HashSet<Integer>();
 723				}
 724				if (!deviceIds.contains(getOwnDeviceId())) {
 725					deviceIds.add(getOwnDeviceId());
 726					IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
 727					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Own device " + getOwnDeviceId() + " not in PEP devicelist. Publishing: " + publish);
 728					mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 729						@Override
 730						public void onIqPacketReceived(Account account, IqPacket packet) {
 731							// TODO: implement this!
 732						}
 733					});
 734				}
 735			}
 736		});
 737	}
 738
 739	public void publishBundlesIfNeeded() {
 740		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
 741		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 742			@Override
 743			public void onIqPacketReceived(Account account, IqPacket packet) {
 744				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
 745				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
 746				boolean flush = false;
 747				if (bundle == null) {
 748					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received invalid bundle:" + packet);
 749					bundle = new PreKeyBundle(-1, -1, -1 , null, -1, null, null, null);
 750					flush = true;
 751				}
 752				if (keys == null) {
 753					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received invalid prekeys:" + packet);
 754				}
 755				try {
 756					boolean changed = false;
 757					// Validate IdentityKey
 758					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
 759					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
 760						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
 761						changed = true;
 762					}
 763
 764					// Validate signedPreKeyRecord + ID
 765					SignedPreKeyRecord signedPreKeyRecord;
 766					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
 767					try {
 768						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
 769						if ( flush
 770								||!bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
 771								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
 772							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 773							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 774							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 775							changed = true;
 776						}
 777					} catch (InvalidKeyIdException e) {
 778						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 779						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 780						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 781						changed = true;
 782					}
 783
 784					// Validate PreKeys
 785					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
 786					if (keys != null) {
 787						for (Integer id : keys.keySet()) {
 788							try {
 789								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
 790								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
 791									preKeyRecords.add(preKeyRecord);
 792								}
 793							} catch (InvalidKeyIdException ignored) {
 794							}
 795						}
 796					}
 797					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
 798					if (newKeys > 0) {
 799						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
 800								axolotlStore.getCurrentPreKeyId()+1, newKeys);
 801						preKeyRecords.addAll(newRecords);
 802						for (PreKeyRecord record : newRecords) {
 803							axolotlStore.storePreKey(record.getId(), record);
 804						}
 805						changed = true;
 806						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding " + newKeys + " new preKeys to PEP.");
 807					}
 808
 809
 810					if(changed) {
 811						IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
 812								signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
 813								preKeyRecords, getOwnDeviceId());
 814						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+ ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
 815						mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 816							@Override
 817							public void onIqPacketReceived(Account account, IqPacket packet) {
 818								// TODO: implement this!
 819								Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Published bundle, got: " + packet);
 820							}
 821						});
 822					}
 823				} catch (InvalidKeyException e) {
 824						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
 825						return;
 826				}
 827			}
 828		});
 829	}
 830
 831	public boolean isContactAxolotlCapable(Contact contact) {
 832
 833		Jid jid = contact.getJid().toBareJid();
 834		AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
 835		return sessions.hasAny(address) ||
 836				( deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
 837	}
 838	public SQLiteAxolotlStore.Trust getFingerprintTrust(String name, String fingerprint) {
 839		return axolotlStore.getFingerprintTrust(name, fingerprint);
 840	}
 841
 842	public void setFingerprintTrust(String name, String fingerprint, SQLiteAxolotlStore.Trust trust) {
 843		axolotlStore.setFingerprintTrust(name, fingerprint, trust);
 844	}
 845
 846	private void buildSessionFromPEP(final Conversation conversation, final AxolotlAddress address) {
 847		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building new sesstion for " + address.getDeviceId());
 848
 849		try {
 850			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
 851					Jid.fromString(address.getName()), address.getDeviceId());
 852			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Retrieving bundle: " + bundlesPacket);
 853			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
 854				@Override
 855				public void onIqPacketReceived(Account account, IqPacket packet) {
 856					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received preKey IQ packet, processing...");
 857					final IqParser parser = mXmppConnectionService.getIqParser();
 858					final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
 859					final PreKeyBundle bundle = parser.bundle(packet);
 860					if (preKeyBundleList.isEmpty() || bundle == null) {
 861						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"preKey IQ packet invalid: " + packet);
 862						fetchStatusMap.put(address, FetchStatus.ERROR);
 863						return;
 864					}
 865					Random random = new Random();
 866					final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
 867					if (preKey == null) {
 868						//should never happen
 869						fetchStatusMap.put(address, FetchStatus.ERROR);
 870						return;
 871					}
 872
 873					final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
 874							preKey.getPreKeyId(), preKey.getPreKey(),
 875							bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
 876							bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
 877
 878					axolotlStore.saveIdentity(address.getName(), bundle.getIdentityKey());
 879
 880					try {
 881						SessionBuilder builder = new SessionBuilder(axolotlStore, address);
 882						builder.process(preKeyBundle);
 883						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
 884						sessions.put(address, session);
 885						fetchStatusMap.put(address, FetchStatus.SUCCESS);
 886					} catch (UntrustedIdentityException|InvalidKeyException e) {
 887						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Error building session for " + address + ": "
 888								+ e.getClass().getName() + ", " + e.getMessage());
 889						fetchStatusMap.put(address, FetchStatus.ERROR);
 890					}
 891
 892					AxolotlAddress ownAddress = new AxolotlAddress(conversation.getAccount().getJid().toBareJid().toString(),0);
 893					AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(),0);
 894					if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
 895							&& !fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
 896						conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_AXOLOTL,
 897								new Conversation.OnMessageFound() {
 898									@Override
 899									public void onMessageFound(Message message) {
 900										processSending(message);
 901									}
 902								});
 903					}
 904				}
 905			});
 906		} catch (InvalidJidException e) {
 907			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Got address with invalid jid: " + address.getName());
 908		}
 909	}
 910
 911	private boolean createSessionsIfNeeded(Conversation conversation) {
 912		boolean newSessions = false;
 913		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Creating axolotl sessions if needed...");
 914		Jid contactJid = conversation.getContact().getJid().toBareJid();
 915		Set<AxolotlAddress> addresses = new HashSet<>();
 916		if(deviceIds.get(contactJid) != null) {
 917			for(Integer foreignId:this.deviceIds.get(contactJid)) {
 918				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Found device "+account.getJid().toBareJid()+":"+foreignId);
 919				addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
 920			}
 921		} else {
 922			Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
 923		}
 924		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Checking own account "+account.getJid().toBareJid());
 925		if(deviceIds.get(account.getJid().toBareJid()) != null) {
 926			for(Integer ownId:this.deviceIds.get(account.getJid().toBareJid())) {
 927				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Found device "+account.getJid().toBareJid()+":"+ownId);
 928				addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
 929			}
 930		}
 931		for (AxolotlAddress address : addresses) {
 932			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Processing device: " + address.toString());
 933			FetchStatus status = fetchStatusMap.get(address);
 934			XmppAxolotlSession session = sessions.get(address);
 935			if ( session == null && ( status == null || status == FetchStatus.ERROR) ) {
 936				fetchStatusMap.put(address, FetchStatus.PENDING);
 937				this.buildSessionFromPEP(conversation,  address);
 938				newSessions = true;
 939			} else {
 940				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Already have session for " +  address.toString());
 941			}
 942		}
 943		return newSessions;
 944	}
 945
 946	@Nullable
 947	public XmppAxolotlMessage encrypt(Message message ){
 948		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(message.getContact().getJid().toBareJid(),
 949				getOwnDeviceId(), message.getBody());
 950
 951		if(findSessionsforContact(message.getContact()).isEmpty()) {
 952			return null;
 953		}
 954		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building axolotl foreign headers...");
 955		for (XmppAxolotlSession session : findSessionsforContact(message.getContact())) {
 956			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account)+session.remoteAddress.toString());
 957			//if(!session.isTrusted()) {
 958			// TODO: handle this properly
 959			//              continue;
 960			//        }
 961			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
 962		}
 963		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building axolotl own headers...");
 964		for (XmppAxolotlSession session : findOwnSessions()) {
 965			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account)+session.remoteAddress.toString());
 966			//        if(!session.isTrusted()) {
 967			// TODO: handle this properly
 968			//          continue;
 969			//    }
 970			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
 971		}
 972
 973		return axolotlMessage;
 974	}
 975
 976	private void processSending(final Message message) {
 977		executor.execute(new Runnable() {
 978			@Override
 979			public void run() {
 980				MessagePacket packet = mXmppConnectionService.getMessageGenerator()
 981						.generateAxolotlChat(message);
 982				if (packet == null) {
 983					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
 984					//mXmppConnectionService.updateConversationUi();
 985				} else {
 986					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Generated message, caching: " + message.getUuid());
 987					messageCache.put(message.getUuid(), packet);
 988					mXmppConnectionService.resendMessage(message);
 989				}
 990			}
 991		});
 992	}
 993
 994	public void prepareMessage(Message message) {
 995		if (!messageCache.containsKey(message.getUuid())) {
 996			boolean newSessions = createSessionsIfNeeded(message.getConversation());
 997
 998			if (!newSessions) {
 999				this.processSending(message);
1000			}
1001		}
1002	}
1003
1004	public MessagePacket fetchPacketFromCache(Message message) {
1005		MessagePacket packet = messageCache.get(message.getUuid());
1006		if (packet != null) {
1007			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Cache hit: " + message.getUuid());
1008			messageCache.remove(message.getUuid());
1009		} else {
1010			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Cache miss: " + message.getUuid());
1011		}
1012		return packet;
1013	}
1014
1015	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceiving(XmppAxolotlMessage message) {
1016		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
1017		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
1018				message.getSenderDeviceId());
1019
1020		boolean newSession = false;
1021		XmppAxolotlSession session = sessions.get(senderAddress);
1022		if (session == null) {
1023			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Account: "+account.getJid()+" No axolotl session found while parsing received message " + message);
1024			// TODO: handle this properly
1025			session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
1026			newSession = true;
1027		}
1028
1029		for (XmppAxolotlMessage.XmppAxolotlMessageHeader header : message.getHeaders()) {
1030			if (header.getRecipientDeviceId() == getOwnDeviceId()) {
1031				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Found axolotl header matching own device ID, processing...");
1032				byte[] payloadKey = session.processReceiving(header);
1033				if (payloadKey != null) {
1034					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Got payload key from axolotl header. Decrypting message...");
1035					plaintextMessage = message.decrypt(session, payloadKey, session.getFingerprint());
1036				}
1037				Integer preKeyId = session.getPreKeyId();
1038				if (preKeyId != null) {
1039					publishBundlesIfNeeded();
1040					session.resetPreKeyId();
1041				}
1042				break;
1043			}
1044		}
1045
1046		if (newSession && plaintextMessage != null) {
1047			sessions.put(senderAddress,session);
1048		}
1049
1050		return plaintextMessage;
1051	}
1052}