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