AxolotlService.java

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