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(jid.toBareJid().equals(account.getJid().toBareJid())) {
 807			if (deviceIds.contains(getOwnDeviceId())) {
 808				deviceIds.remove(getOwnDeviceId());
 809			}
 810			for(Integer deviceId : deviceIds) {
 811				AxolotlAddress ownDeviceAddress = new AxolotlAddress(jid.toBareJid().toString(),deviceId);
 812				if(sessions.get(ownDeviceAddress) == null) {
 813					buildSessionFromPEP(null, ownDeviceAddress, false);
 814				}
 815			}
 816		}
 817		Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toString()));
 818		expiredDevices.removeAll(deviceIds);
 819		setTrustOnSessions(jid, expiredDevices, SQLiteAxolotlStore.Trust.TRUSTED,
 820				SQLiteAxolotlStore.Trust.INACTIVE);
 821		Set<Integer> newDevices = new HashSet<>(deviceIds);
 822		setTrustOnSessions(jid, newDevices, SQLiteAxolotlStore.Trust.INACTIVE,
 823				SQLiteAxolotlStore.Trust.TRUSTED);
 824		this.deviceIds.put(jid, deviceIds);
 825		mXmppConnectionService.keyStatusUpdated();
 826		publishOwnDeviceIdIfNeeded();
 827	}
 828
 829	public void wipeOtherPepDevices() {
 830		Set<Integer> deviceIds = new HashSet<>();
 831		deviceIds.add(getOwnDeviceId());
 832		IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
 833		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Wiping all other devices from Pep:" + publish);
 834		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 835			@Override
 836			public void onIqPacketReceived(Account account, IqPacket packet) {
 837				// TODO: implement this!
 838			}
 839		});
 840	}
 841
 842	public void purgeKey(IdentityKey identityKey) {
 843		axolotlStore.setFingerprintTrust(identityKey.getFingerprint().replaceAll("\\s",""), SQLiteAxolotlStore.Trust.COMPROMISED);
 844	}
 845
 846	public void publishOwnDeviceIdIfNeeded() {
 847		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
 848		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 849			@Override
 850			public void onIqPacketReceived(Account account, IqPacket packet) {
 851				Element item = mXmppConnectionService.getIqParser().getItem(packet);
 852				Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
 853				if (deviceIds == null) {
 854					deviceIds = new HashSet<Integer>();
 855				}
 856				if (!deviceIds.contains(getOwnDeviceId())) {
 857					deviceIds.add(getOwnDeviceId());
 858					IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
 859					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Own device " + getOwnDeviceId() + " not in PEP devicelist. Publishing: " + publish);
 860					mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 861						@Override
 862						public void onIqPacketReceived(Account account, IqPacket packet) {
 863							// TODO: implement this!
 864						}
 865					});
 866				}
 867			}
 868		});
 869	}
 870
 871	public void publishBundlesIfNeeded() {
 872		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
 873		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 874			@Override
 875			public void onIqPacketReceived(Account account, IqPacket packet) {
 876				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
 877				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
 878				boolean flush = false;
 879				if (bundle == null) {
 880					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received invalid bundle:" + packet);
 881					bundle = new PreKeyBundle(-1, -1, -1 , null, -1, null, null, null);
 882					flush = true;
 883				}
 884				if (keys == null) {
 885					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received invalid prekeys:" + packet);
 886				}
 887				try {
 888					boolean changed = false;
 889					// Validate IdentityKey
 890					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
 891					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
 892						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
 893						changed = true;
 894					}
 895
 896					// Validate signedPreKeyRecord + ID
 897					SignedPreKeyRecord signedPreKeyRecord;
 898					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
 899					try {
 900						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
 901						if ( flush
 902								||!bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
 903								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
 904							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 905							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 906							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 907							changed = true;
 908						}
 909					} catch (InvalidKeyIdException e) {
 910						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 911						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 912						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 913						changed = true;
 914					}
 915
 916					// Validate PreKeys
 917					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
 918					if (keys != null) {
 919						for (Integer id : keys.keySet()) {
 920							try {
 921								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
 922								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
 923									preKeyRecords.add(preKeyRecord);
 924								}
 925							} catch (InvalidKeyIdException ignored) {
 926							}
 927						}
 928					}
 929					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
 930					if (newKeys > 0) {
 931						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
 932								axolotlStore.getCurrentPreKeyId()+1, newKeys);
 933						preKeyRecords.addAll(newRecords);
 934						for (PreKeyRecord record : newRecords) {
 935							axolotlStore.storePreKey(record.getId(), record);
 936						}
 937						changed = true;
 938						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Adding " + newKeys + " new preKeys to PEP.");
 939					}
 940
 941
 942					if(changed) {
 943						IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
 944								signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
 945								preKeyRecords, getOwnDeviceId());
 946						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+ ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
 947						mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 948							@Override
 949							public void onIqPacketReceived(Account account, IqPacket packet) {
 950								// TODO: implement this!
 951								Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Published bundle, got: " + packet);
 952							}
 953						});
 954					}
 955				} catch (InvalidKeyException e) {
 956						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
 957						return;
 958				}
 959			}
 960		});
 961	}
 962
 963	public boolean isContactAxolotlCapable(Contact contact) {
 964
 965		Jid jid = contact.getJid().toBareJid();
 966		AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
 967		return sessions.hasAny(address) ||
 968				( deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
 969	}
 970	public SQLiteAxolotlStore.Trust getFingerprintTrust(String fingerprint) {
 971		return axolotlStore.getFingerprintTrust(fingerprint);
 972	}
 973
 974	public void setFingerprintTrust(String fingerprint, SQLiteAxolotlStore.Trust trust) {
 975		axolotlStore.setFingerprintTrust(fingerprint, trust);
 976	}
 977
 978	private void buildSessionFromPEP(final Conversation conversation, final AxolotlAddress address, final boolean flushWaitingQueueAfterFetch) {
 979		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.getDeviceId());
 980
 981		try {
 982			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
 983					Jid.fromString(address.getName()), address.getDeviceId());
 984			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Retrieving bundle: " + bundlesPacket);
 985			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
 986				private void finish() {
 987					AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(),0);
 988					if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
 989							&& !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) {
 990						if (flushWaitingQueueAfterFetch && conversation != null) {
 991							conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_AXOLOTL,
 992									new Conversation.OnMessageFound() {
 993										@Override
 994										public void onMessageFound(Message message) {
 995											processSending(message,false);
 996										}
 997									});
 998						}
 999						mXmppConnectionService.keyStatusUpdated();
1000					}
1001				}
1002
1003				@Override
1004				public void onIqPacketReceived(Account account, IqPacket packet) {
1005					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received preKey IQ packet, processing...");
1006					final IqParser parser = mXmppConnectionService.getIqParser();
1007					final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
1008					final PreKeyBundle bundle = parser.bundle(packet);
1009					if (preKeyBundleList.isEmpty() || bundle == null) {
1010						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"preKey IQ packet invalid: " + packet);
1011						fetchStatusMap.put(address, FetchStatus.ERROR);
1012						finish();
1013						return;
1014					}
1015					Random random = new Random();
1016					final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
1017					if (preKey == null) {
1018						//should never happen
1019						fetchStatusMap.put(address, FetchStatus.ERROR);
1020						finish();
1021						return;
1022					}
1023
1024					final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
1025							preKey.getPreKeyId(), preKey.getPreKey(),
1026							bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
1027							bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
1028
1029					axolotlStore.saveIdentity(address.getName(), bundle.getIdentityKey());
1030
1031					try {
1032						SessionBuilder builder = new SessionBuilder(axolotlStore, address);
1033						builder.process(preKeyBundle);
1034						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
1035						sessions.put(address, session);
1036						fetchStatusMap.put(address, FetchStatus.SUCCESS);
1037					} catch (UntrustedIdentityException|InvalidKeyException e) {
1038						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Error building session for " + address + ": "
1039								+ e.getClass().getName() + ", " + e.getMessage());
1040						fetchStatusMap.put(address, FetchStatus.ERROR);
1041					}
1042
1043					finish();
1044				}
1045			});
1046		} catch (InvalidJidException e) {
1047			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Got address with invalid jid: " + address.getName());
1048		}
1049	}
1050
1051	public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
1052		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + conversation.getContact().getJid().toBareJid());
1053		Jid contactJid = conversation.getContact().getJid().toBareJid();
1054		Set<AxolotlAddress> addresses = new HashSet<>();
1055		if(deviceIds.get(contactJid) != null) {
1056			for(Integer foreignId:this.deviceIds.get(contactJid)) {
1057				AxolotlAddress address = new AxolotlAddress(contactJid.toString(), foreignId);
1058				if(sessions.get(address) == null) {
1059					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1060					if ( identityKey != null ) {
1061						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Already have session for " +  address.toString() + ", adding to cache...");
1062						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
1063						sessions.put(address, session);
1064					} else {
1065						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId);
1066						addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
1067					}
1068				}
1069			}
1070		} else {
1071			Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
1072		}
1073		if(deviceIds.get(account.getJid().toBareJid()) != null) {
1074			for(Integer ownId:this.deviceIds.get(account.getJid().toBareJid())) {
1075				AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
1076				if(sessions.get(address) == null) {
1077					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1078					if ( identityKey != null ) {
1079						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Already have session for " +  address.toString() + ", adding to cache...");
1080						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
1081						sessions.put(address, session);
1082					} else {
1083						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
1084						addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
1085					}
1086				}
1087			}
1088		}
1089
1090		return addresses;
1091	}
1092
1093	public boolean createSessionsIfNeeded(final Conversation conversation, final boolean flushWaitingQueueAfterFetch) {
1094		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
1095		boolean newSessions = false;
1096		Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
1097		for (AxolotlAddress address : addresses) {
1098			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
1099			FetchStatus status = fetchStatusMap.get(address);
1100			if ( status == null || status == FetchStatus.ERROR ) {
1101					fetchStatusMap.put(address, FetchStatus.PENDING);
1102					this.buildSessionFromPEP(conversation, address, flushWaitingQueueAfterFetch);
1103					newSessions = true;
1104			} else {
1105				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Already fetching bundle for " +  address.toString());
1106			}
1107		}
1108
1109		return newSessions;
1110	}
1111
1112	public boolean hasPendingKeyFetches(Conversation conversation) {
1113		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(),0);
1114		AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(),0);
1115		return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
1116				||fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING);
1117
1118	}
1119
1120	@Nullable
1121	public XmppAxolotlMessage encrypt(Message message ){
1122		final String content;
1123		if (message.hasFileOnRemoteHost()) {
1124				content = message.getFileParams().url.toString();
1125		} else {
1126			content = message.getBody();
1127		}
1128		final XmppAxolotlMessage axolotlMessage;
1129		try {
1130			axolotlMessage = new XmppAxolotlMessage(message.getContact().getJid().toBareJid(),
1131					getOwnDeviceId(), content);
1132		} catch (CryptoFailedException e) {
1133			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
1134			return null;
1135		}
1136
1137		if(findSessionsforContact(message.getContact()).isEmpty()) {
1138			return null;
1139		}
1140		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building axolotl foreign headers...");
1141		for (XmppAxolotlSession session : findSessionsforContact(message.getContact())) {
1142			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account)+session.remoteAddress.toString());
1143			//if(!session.isTrusted()) {
1144			// TODO: handle this properly
1145			//              continue;
1146			//        }
1147			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
1148		}
1149		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building axolotl own headers...");
1150		for (XmppAxolotlSession session : findOwnSessions()) {
1151			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account)+session.remoteAddress.toString());
1152			//        if(!session.isTrusted()) {
1153			// TODO: handle this properly
1154			//          continue;
1155			//    }
1156			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
1157		}
1158
1159		return axolotlMessage;
1160	}
1161
1162	private void processSending(final Message message, final boolean delay) {
1163		executor.execute(new Runnable() {
1164			@Override
1165			public void run() {
1166				XmppAxolotlMessage axolotlMessage = encrypt(message);
1167				if (axolotlMessage == null) {
1168					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1169					//mXmppConnectionService.updateConversationUi();
1170				} else {
1171					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Generated message, caching: " + message.getUuid());
1172					messageCache.put(message.getUuid(), axolotlMessage);
1173					mXmppConnectionService.resendMessage(message,delay);
1174				}
1175			}
1176		});
1177	}
1178
1179	public void prepareMessage(final Message message,final boolean delay) {
1180		if (!messageCache.containsKey(message.getUuid())) {
1181			boolean newSessions = createSessionsIfNeeded(message.getConversation(), true);
1182			if (!newSessions) {
1183				this.processSending(message,delay);
1184			}
1185		}
1186	}
1187
1188	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
1189		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
1190		if (axolotlMessage != null) {
1191			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Cache hit: " + message.getUuid());
1192			messageCache.remove(message.getUuid());
1193		} else {
1194			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Cache miss: " + message.getUuid());
1195		}
1196		return axolotlMessage;
1197	}
1198
1199	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceiving(XmppAxolotlMessage message) {
1200		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
1201		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
1202				message.getSenderDeviceId());
1203
1204		boolean newSession = false;
1205		XmppAxolotlSession session = sessions.get(senderAddress);
1206		if (session == null) {
1207			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Account: "+account.getJid()+" No axolotl session found while parsing received message " + message);
1208			// TODO: handle this properly
1209			IdentityKey identityKey = axolotlStore.loadSession(senderAddress).getSessionState().getRemoteIdentityKey();
1210			if ( identityKey != null ) {
1211				session = new XmppAxolotlSession(account, axolotlStore, senderAddress, identityKey.getFingerprint().replaceAll("\\s", ""));
1212			} else {
1213				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
1214			}
1215			newSession = true;
1216		}
1217
1218		for (XmppAxolotlMessage.XmppAxolotlMessageHeader header : message.getHeaders()) {
1219			if (header.getRecipientDeviceId() == getOwnDeviceId()) {
1220				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Found axolotl header matching own device ID, processing...");
1221				byte[] payloadKey = session.processReceiving(header);
1222				if (payloadKey != null) {
1223					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Got payload key from axolotl header. Decrypting message...");
1224					try{
1225						plaintextMessage = message.decrypt(session, payloadKey, session.getFingerprint());
1226					} catch (CryptoFailedException e) {
1227						Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
1228						break;
1229					}
1230				}
1231				Integer preKeyId = session.getPreKeyId();
1232				if (preKeyId != null) {
1233					publishBundlesIfNeeded();
1234					session.resetPreKeyId();
1235				}
1236				break;
1237			}
1238		}
1239
1240		if (newSession && plaintextMessage != null) {
1241			sessions.put(senderAddress, session);
1242		}
1243
1244		return plaintextMessage;
1245	}
1246}