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