AxolotlService.java

   1package eu.siacs.conversations.crypto.axolotl;
   2
   3import android.os.Bundle;
   4import android.security.KeyChain;
   5import android.support.annotation.NonNull;
   6import android.support.annotation.Nullable;
   7import android.util.Log;
   8import android.util.Pair;
   9
  10import org.bouncycastle.jce.provider.BouncyCastleProvider;
  11import org.whispersystems.libaxolotl.AxolotlAddress;
  12import org.whispersystems.libaxolotl.IdentityKey;
  13import org.whispersystems.libaxolotl.IdentityKeyPair;
  14import org.whispersystems.libaxolotl.InvalidKeyException;
  15import org.whispersystems.libaxolotl.InvalidKeyIdException;
  16import org.whispersystems.libaxolotl.SessionBuilder;
  17import org.whispersystems.libaxolotl.UntrustedIdentityException;
  18import org.whispersystems.libaxolotl.ecc.ECPublicKey;
  19import org.whispersystems.libaxolotl.state.PreKeyBundle;
  20import org.whispersystems.libaxolotl.state.PreKeyRecord;
  21import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
  22import org.whispersystems.libaxolotl.util.KeyHelper;
  23
  24import java.security.PrivateKey;
  25import java.security.Security;
  26import java.security.Signature;
  27import java.security.cert.X509Certificate;
  28import java.util.ArrayList;
  29import java.util.Arrays;
  30import java.util.Collection;
  31import java.util.Collections;
  32import java.util.HashMap;
  33import java.util.HashSet;
  34import java.util.List;
  35import java.util.Map;
  36import java.util.Random;
  37import java.util.Set;
  38import java.util.concurrent.atomic.AtomicBoolean;
  39
  40import eu.siacs.conversations.Config;
  41import eu.siacs.conversations.entities.Account;
  42import eu.siacs.conversations.entities.Contact;
  43import eu.siacs.conversations.entities.Conversation;
  44import eu.siacs.conversations.entities.Message;
  45import eu.siacs.conversations.parser.IqParser;
  46import eu.siacs.conversations.services.XmppConnectionService;
  47import eu.siacs.conversations.utils.CryptoHelper;
  48import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
  49import eu.siacs.conversations.xml.Element;
  50import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
  51import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  52import eu.siacs.conversations.xmpp.jid.InvalidJidException;
  53import eu.siacs.conversations.xmpp.jid.Jid;
  54import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  55
  56public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
  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_DEVICE_LIST_NOTIFY = PEP_DEVICE_LIST + "+notify";
  61	public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
  62	public static final String PEP_VERIFICATION = PEP_PREFIX + ".verification";
  63
  64	public static final String LOGPREFIX = "AxolotlService";
  65
  66	public static final int NUM_KEYS_TO_PUBLISH = 100;
  67	public static final int publishTriesThreshold = 3;
  68
  69	private final Account account;
  70	private final XmppConnectionService mXmppConnectionService;
  71	private final SQLiteAxolotlStore axolotlStore;
  72	private final SessionMap sessions;
  73	private final Map<Jid, Set<Integer>> deviceIds;
  74	private final Map<String, XmppAxolotlMessage> messageCache;
  75	private final FetchStatusMap fetchStatusMap;
  76	private final SerialSingleThreadExecutor executor;
  77	private int numPublishTriesOnEmptyPep = 0;
  78	private boolean pepBroken = false;
  79
  80	private AtomicBoolean ownPushPending = new AtomicBoolean(false);
  81
  82	@Override
  83	public void onAdvancedStreamFeaturesAvailable(Account account) {
  84		if (Config.supportOmemo()
  85				&& account.getXmppConnection() != null
  86				&& account.getXmppConnection().getFeatures().pep()) {
  87			publishBundlesIfNeeded(true, false);
  88		} else {
  89			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping OMEMO initialization");
  90		}
  91	}
  92
  93	public boolean fetchMapHasErrors(List<Jid> jids) {
  94		for(Jid jid : jids) {
  95			if (deviceIds.get(jid) != null) {
  96				for (Integer foreignId : this.deviceIds.get(jid)) {
  97					AxolotlAddress address = new AxolotlAddress(jid.toString(), foreignId);
  98					if (fetchStatusMap.getAll(address).containsValue(FetchStatus.ERROR)) {
  99						return true;
 100					}
 101				}
 102			}
 103		}
 104		return false;
 105	}
 106
 107	public void preVerifyFingerprint(Contact contact, String fingerprint) {
 108		axolotlStore.preVerifyFingerprint(contact.getAccount(), contact.getJid().toBareJid().toPreppedString(), fingerprint);
 109	}
 110
 111	public void preVerifyFingerprint(Account account, String fingerprint) {
 112		axolotlStore.preVerifyFingerprint(account, account.getJid().toBareJid().toPreppedString(), fingerprint);
 113	}
 114
 115	private static class AxolotlAddressMap<T> {
 116		protected Map<String, Map<Integer, T>> map;
 117		protected final Object MAP_LOCK = new Object();
 118
 119		public AxolotlAddressMap() {
 120			this.map = new HashMap<>();
 121		}
 122
 123		public void put(AxolotlAddress address, T value) {
 124			synchronized (MAP_LOCK) {
 125				Map<Integer, T> devices = map.get(address.getName());
 126				if (devices == null) {
 127					devices = new HashMap<>();
 128					map.put(address.getName(), devices);
 129				}
 130				devices.put(address.getDeviceId(), value);
 131			}
 132		}
 133
 134		public T get(AxolotlAddress address) {
 135			synchronized (MAP_LOCK) {
 136				Map<Integer, T> devices = map.get(address.getName());
 137				if (devices == null) {
 138					return null;
 139				}
 140				return devices.get(address.getDeviceId());
 141			}
 142		}
 143
 144		public Map<Integer, T> getAll(AxolotlAddress address) {
 145			synchronized (MAP_LOCK) {
 146				Map<Integer, T> devices = map.get(address.getName());
 147				if (devices == null) {
 148					return new HashMap<>();
 149				}
 150				return devices;
 151			}
 152		}
 153
 154		public boolean hasAny(AxolotlAddress address) {
 155			synchronized (MAP_LOCK) {
 156				Map<Integer, T> devices = map.get(address.getName());
 157				return devices != null && !devices.isEmpty();
 158			}
 159		}
 160
 161		public void clear() {
 162			map.clear();
 163		}
 164
 165	}
 166
 167	private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
 168		private final XmppConnectionService xmppConnectionService;
 169		private final Account account;
 170
 171		public SessionMap(XmppConnectionService service, SQLiteAxolotlStore store, Account account) {
 172			super();
 173			this.xmppConnectionService = service;
 174			this.account = account;
 175			this.fillMap(store);
 176		}
 177
 178		private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
 179			for (Integer deviceId : deviceIds) {
 180				AxolotlAddress axolotlAddress = new AxolotlAddress(bareJid, deviceId);
 181				IdentityKey identityKey = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey();
 182				if(Config.X509_VERIFICATION) {
 183					X509Certificate certificate = store.getFingerprintCertificate(identityKey.getFingerprint().replaceAll("\\s", ""));
 184					if (certificate != null) {
 185						Bundle information = CryptoHelper.extractCertificateInformation(certificate);
 186						try {
 187							final String cn = information.getString("subject_cn");
 188							final Jid jid = Jid.fromString(bareJid);
 189							Log.d(Config.LOGTAG,"setting common name for "+jid+" to "+cn);
 190							account.getRoster().getContact(jid).setCommonName(cn);
 191						} catch (final InvalidJidException ignored) {
 192							//ignored
 193						}
 194					}
 195				}
 196				this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, identityKey));
 197			}
 198		}
 199
 200		private void fillMap(SQLiteAxolotlStore store) {
 201			List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().toBareJid().toPreppedString());
 202			putDevicesForJid(account.getJid().toBareJid().toPreppedString(), deviceIds, store);
 203			for (Contact contact : account.getRoster().getContacts()) {
 204				Jid bareJid = contact.getJid().toBareJid();
 205				String address = bareJid.toString();
 206				deviceIds = store.getSubDeviceSessions(address);
 207				putDevicesForJid(address, deviceIds, store);
 208			}
 209
 210		}
 211
 212		@Override
 213		public void put(AxolotlAddress address, XmppAxolotlSession value) {
 214			super.put(address, value);
 215			value.setNotFresh();
 216			xmppConnectionService.syncRosterToDisk(account); //TODO why?
 217		}
 218
 219		public void put(XmppAxolotlSession session) {
 220			this.put(session.getRemoteAddress(), session);
 221		}
 222	}
 223
 224	public enum FetchStatus {
 225		PENDING,
 226		SUCCESS,
 227		SUCCESS_VERIFIED,
 228		TIMEOUT,
 229		ERROR
 230	}
 231
 232	private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
 233
 234		public void clearErrorFor(Jid jid) {
 235			synchronized (MAP_LOCK) {
 236				Map<Integer, FetchStatus> devices = this.map.get(jid.toBareJid().toPreppedString());
 237				if (devices == null) {
 238					return;
 239				}
 240				for(Map.Entry<Integer, FetchStatus> entry : devices.entrySet()) {
 241					if (entry.getValue() == FetchStatus.ERROR) {
 242						Log.d(Config.LOGTAG,"resetting error for "+jid.toBareJid()+"("+entry.getKey()+")");
 243						entry.setValue(FetchStatus.TIMEOUT);
 244					}
 245				}
 246			}
 247		}
 248	}
 249
 250	public static String getLogprefix(Account account) {
 251		return LOGPREFIX + " (" + account.getJid().toBareJid().toString() + "): ";
 252	}
 253
 254	public AxolotlService(Account account, XmppConnectionService connectionService) {
 255		if (Security.getProvider("BC") == null) {
 256			Security.addProvider(new BouncyCastleProvider());
 257		}
 258		this.mXmppConnectionService = connectionService;
 259		this.account = account;
 260		this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
 261		this.deviceIds = new HashMap<>();
 262		this.messageCache = new HashMap<>();
 263		this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
 264		this.fetchStatusMap = new FetchStatusMap();
 265		this.executor = new SerialSingleThreadExecutor();
 266	}
 267
 268	public String getOwnFingerprint() {
 269		return axolotlStore.getIdentityKeyPair().getPublicKey().getFingerprint().replaceAll("\\s", "");
 270	}
 271
 272	public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status) {
 273		return axolotlStore.getContactKeysWithTrust(account.getJid().toBareJid().toPreppedString(), status);
 274	}
 275
 276	public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, Jid jid) {
 277		return axolotlStore.getContactKeysWithTrust(jid.toBareJid().toPreppedString(), status);
 278	}
 279
 280	public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, List<Jid> jids) {
 281		Set<IdentityKey> keys = new HashSet<>();
 282		for(Jid jid : jids) {
 283			keys.addAll(axolotlStore.getContactKeysWithTrust(jid.toPreppedString(), status));
 284		}
 285		return keys;
 286	}
 287
 288	public long getNumTrustedKeys(Jid jid) {
 289		return axolotlStore.getContactNumTrustedKeys(jid.toBareJid().toPreppedString());
 290	}
 291
 292	public boolean anyTargetHasNoTrustedKeys(List<Jid> jids) {
 293		for(Jid jid : jids) {
 294			if (axolotlStore.getContactNumTrustedKeys(jid.toBareJid().toPreppedString()) == 0) {
 295				return true;
 296			}
 297		}
 298		return false;
 299	}
 300
 301	private AxolotlAddress getAddressForJid(Jid jid) {
 302		return new AxolotlAddress(jid.toPreppedString(), 0);
 303	}
 304
 305	public Collection<XmppAxolotlSession> findOwnSessions() {
 306		AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
 307		ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(ownAddress).values());
 308		Collections.sort(s);
 309		return s;
 310	}
 311
 312
 313
 314	public Collection<XmppAxolotlSession> findSessionsForContact(Contact contact) {
 315		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
 316		ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(contactAddress).values());
 317		Collections.sort(s);
 318		return s;
 319	}
 320
 321	private Set<XmppAxolotlSession> findSessionsForConversation(Conversation conversation) {
 322		HashSet<XmppAxolotlSession> sessions = new HashSet<>();
 323		for(Jid jid : conversation.getAcceptedCryptoTargets()) {
 324			sessions.addAll(this.sessions.getAll(getAddressForJid(jid)).values());
 325		}
 326		return sessions;
 327	}
 328
 329	private boolean hasAny(Jid jid) {
 330		return sessions.hasAny(getAddressForJid(jid));
 331	}
 332
 333	public boolean isPepBroken() {
 334		return this.pepBroken;
 335	}
 336
 337	public void resetBrokenness() {
 338		this.pepBroken = false;
 339		numPublishTriesOnEmptyPep = 0;
 340	}
 341
 342	public void clearErrorsInFetchStatusMap(Jid jid) {
 343		fetchStatusMap.clearErrorFor(jid);
 344	}
 345
 346	public void regenerateKeys(boolean wipeOther) {
 347		axolotlStore.regenerate();
 348		sessions.clear();
 349		fetchStatusMap.clear();
 350		publishBundlesIfNeeded(true, wipeOther);
 351	}
 352
 353	public int getOwnDeviceId() {
 354		return axolotlStore.getLocalRegistrationId();
 355	}
 356
 357	public Set<Integer> getOwnDeviceIds() {
 358		return this.deviceIds.get(account.getJid().toBareJid());
 359	}
 360
 361	public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
 362		boolean me = jid.toBareJid().equals(account.getJid().toBareJid());
 363		if (me && ownPushPending.getAndSet(false)) {
 364			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": ignoring own device update because of pending push");
 365			return;
 366		}
 367		boolean needsPublishing = me && !deviceIds.contains(getOwnDeviceId());
 368		if (me) {
 369			deviceIds.remove(getOwnDeviceId());
 370		}
 371		Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toPreppedString()));
 372		expiredDevices.removeAll(deviceIds);
 373		for (Integer deviceId : expiredDevices) {
 374			AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
 375			XmppAxolotlSession session = sessions.get(address);
 376			if (session != null && session.getFingerprint() != null) {
 377				if (session.getTrust().isActive()) {
 378					session.setTrust(session.getTrust().toInactive());
 379				}
 380			}
 381		}
 382		Set<Integer> newDevices = new HashSet<>(deviceIds);
 383		for (Integer deviceId : newDevices) {
 384			AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
 385			XmppAxolotlSession session = sessions.get(address);
 386			if (session != null && session.getFingerprint() != null) {
 387				if (!session.getTrust().isActive()) {
 388					Log.d(Config.LOGTAG,"reactivating device with fingprint "+session.getFingerprint());
 389					session.setTrust(session.getTrust().toActive());
 390				}
 391			}
 392		}
 393		if (me) {
 394			if (Config.OMEMO_AUTO_EXPIRY != 0) {
 395				needsPublishing |= deviceIds.removeAll(getExpiredDevices());
 396			}
 397			for (Integer deviceId : deviceIds) {
 398				AxolotlAddress ownDeviceAddress = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
 399				if (sessions.get(ownDeviceAddress) == null) {
 400					buildSessionFromPEP(ownDeviceAddress);
 401				}
 402			}
 403			if (needsPublishing) {
 404				publishOwnDeviceId(deviceIds);
 405			}
 406		}
 407		this.deviceIds.put(jid, deviceIds);
 408		mXmppConnectionService.keyStatusUpdated(null);
 409	}
 410
 411	public void wipeOtherPepDevices() {
 412		if (pepBroken) {
 413			Log.d(Config.LOGTAG, getLogprefix(account) + "wipeOtherPepDevices called, but PEP is broken. Ignoring... ");
 414			return;
 415		}
 416		Set<Integer> deviceIds = new HashSet<>();
 417		deviceIds.add(getOwnDeviceId());
 418		IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
 419		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Wiping all other devices from Pep:" + publish);
 420		mXmppConnectionService.sendIqPacket(account, publish, null);
 421	}
 422
 423	public void purgeKey(final String fingerprint) {
 424		axolotlStore.setFingerprintStatus(fingerprint.replaceAll("\\s", ""), FingerprintStatus.createCompromised());
 425	}
 426
 427	public void publishOwnDeviceIdIfNeeded() {
 428		if (pepBroken) {
 429			Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
 430			return;
 431		}
 432		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
 433		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 434			@Override
 435			public void onIqPacketReceived(Account account, IqPacket packet) {
 436				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 437					Log.d(Config.LOGTAG, getLogprefix(account) + "Timeout received while retrieving own Device Ids.");
 438				} else {
 439					Element item = mXmppConnectionService.getIqParser().getItem(packet);
 440					Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
 441					registerDevices(account.getJid().toBareJid(),deviceIds);
 442				}
 443			}
 444		});
 445	}
 446
 447	private Set<Integer> getExpiredDevices() {
 448		Set<Integer> devices = new HashSet<>();
 449		for(XmppAxolotlSession session : findOwnSessions()) {
 450			if (session.getTrust().isActive()) {
 451				long diff = System.currentTimeMillis() - session.getTrust().getLastActivation();
 452				if (diff > Config.OMEMO_AUTO_EXPIRY) {
 453					long lastMessageDiff = System.currentTimeMillis() - mXmppConnectionService.databaseBackend.getLastTimeFingerprintUsed(account,session.getFingerprint());
 454					if (lastMessageDiff > Config.OMEMO_AUTO_EXPIRY) {
 455						devices.add(session.getRemoteAddress().getDeviceId());
 456						session.setTrust(session.getTrust().toInactive());
 457						Log.d(Config.LOGTAG, "added own device " + session.getFingerprint() + " to list of expired devices. Last message received "+(lastMessageDiff/1000)+"s ago");
 458					}
 459				}
 460			}
 461		}
 462		return devices;
 463	}
 464
 465	public void publishOwnDeviceId(Set<Integer> deviceIds) {
 466		Set<Integer> deviceIdsCopy = new HashSet<>(deviceIds);
 467		if (!deviceIdsCopy.contains(getOwnDeviceId())) {
 468			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Own device " + getOwnDeviceId() + " not in PEP devicelist.");
 469			if (deviceIdsCopy.isEmpty()) {
 470				if (numPublishTriesOnEmptyPep >= publishTriesThreshold) {
 471					Log.w(Config.LOGTAG, getLogprefix(account) + "Own device publish attempt threshold exceeded, aborting...");
 472					pepBroken = true;
 473					return;
 474				} else {
 475					numPublishTriesOnEmptyPep++;
 476					Log.w(Config.LOGTAG, getLogprefix(account) + "Own device list empty, attempting to publish (try " + numPublishTriesOnEmptyPep + ")");
 477				}
 478			} else {
 479				numPublishTriesOnEmptyPep = 0;
 480			}
 481			deviceIdsCopy.add(getOwnDeviceId());
 482			IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIdsCopy);
 483			ownPushPending.set(true);
 484			mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 485				@Override
 486				public void onIqPacketReceived(Account account, IqPacket packet) {
 487					ownPushPending.set(false);
 488					if (packet.getType() == IqPacket.TYPE.ERROR) {
 489						pepBroken = true;
 490						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing own device id" + packet.findChild("error"));
 491					}
 492				}
 493			});
 494		}
 495	}
 496
 497	public void publishDeviceVerificationAndBundle(final SignedPreKeyRecord signedPreKeyRecord,
 498												   final Set<PreKeyRecord> preKeyRecords,
 499												   final boolean announceAfter,
 500												   final boolean wipe) {
 501		try {
 502			IdentityKey axolotlPublicKey = axolotlStore.getIdentityKeyPair().getPublicKey();
 503			PrivateKey x509PrivateKey = KeyChain.getPrivateKey(mXmppConnectionService, account.getPrivateKeyAlias());
 504			X509Certificate[] chain = KeyChain.getCertificateChain(mXmppConnectionService, account.getPrivateKeyAlias());
 505			Signature verifier = Signature.getInstance("sha256WithRSA");
 506			verifier.initSign(x509PrivateKey,mXmppConnectionService.getRNG());
 507			verifier.update(axolotlPublicKey.serialize());
 508			byte[] signature = verifier.sign();
 509			IqPacket packet = mXmppConnectionService.getIqGenerator().publishVerification(signature, chain, getOwnDeviceId());
 510			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": publish verification for device "+getOwnDeviceId());
 511			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 512				@Override
 513				public void onIqPacketReceived(Account account, IqPacket packet) {
 514					publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe);
 515				}
 516			});
 517		} catch (Exception  e) {
 518			e.printStackTrace();
 519		}
 520	}
 521
 522	public void publishBundlesIfNeeded(final boolean announce, final boolean wipe) {
 523		if (pepBroken) {
 524			Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
 525			return;
 526		}
 527		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
 528		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 529			@Override
 530			public void onIqPacketReceived(Account account, IqPacket packet) {
 531
 532				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 533					return; //ignore timeout. do nothing
 534				}
 535
 536				if (packet.getType() == IqPacket.TYPE.ERROR) {
 537					Element error = packet.findChild("error");
 538					if (error == null || !error.hasChild("item-not-found")) {
 539						pepBroken = true;
 540						Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "request for device bundles came back with something other than item-not-found" + packet);
 541						return;
 542					}
 543				}
 544
 545				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
 546				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
 547				boolean flush = false;
 548				if (bundle == null) {
 549					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
 550					bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
 551					flush = true;
 552				}
 553				if (keys == null) {
 554					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
 555				}
 556				try {
 557					boolean changed = false;
 558					// Validate IdentityKey
 559					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
 560					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
 561						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
 562						changed = true;
 563					}
 564
 565					// Validate signedPreKeyRecord + ID
 566					SignedPreKeyRecord signedPreKeyRecord;
 567					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
 568					try {
 569						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
 570						if (flush
 571								|| !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
 572								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
 573							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 574							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 575							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 576							changed = true;
 577						}
 578					} catch (InvalidKeyIdException e) {
 579						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 580						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 581						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 582						changed = true;
 583					}
 584
 585					// Validate PreKeys
 586					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
 587					if (keys != null) {
 588						for (Integer id : keys.keySet()) {
 589							try {
 590								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
 591								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
 592									preKeyRecords.add(preKeyRecord);
 593								}
 594							} catch (InvalidKeyIdException ignored) {
 595							}
 596						}
 597					}
 598					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
 599					if (newKeys > 0) {
 600						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
 601								axolotlStore.getCurrentPreKeyId() + 1, newKeys);
 602						preKeyRecords.addAll(newRecords);
 603						for (PreKeyRecord record : newRecords) {
 604							axolotlStore.storePreKey(record.getId(), record);
 605						}
 606						changed = true;
 607						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
 608					}
 609
 610
 611					if (changed) {
 612						if (account.getPrivateKeyAlias() != null && Config.X509_VERIFICATION) {
 613							mXmppConnectionService.publishDisplayName(account);
 614							publishDeviceVerificationAndBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
 615						} else {
 616							publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
 617						}
 618					} else {
 619						Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
 620						if (wipe) {
 621							wipeOtherPepDevices();
 622						} else if (announce) {
 623							Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
 624							publishOwnDeviceIdIfNeeded();
 625						}
 626					}
 627				} catch (InvalidKeyException e) {
 628					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
 629				}
 630			}
 631		});
 632	}
 633
 634	private void publishDeviceBundle(SignedPreKeyRecord signedPreKeyRecord,
 635									 Set<PreKeyRecord> preKeyRecords,
 636									 final boolean announceAfter,
 637									 final boolean wipe) {
 638		IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
 639				signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
 640				preKeyRecords, getOwnDeviceId());
 641		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
 642		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 643			@Override
 644			public void onIqPacketReceived(Account account, IqPacket packet) {
 645				if (packet.getType() == IqPacket.TYPE.RESULT) {
 646					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
 647					if (wipe) {
 648						wipeOtherPepDevices();
 649					} else if (announceAfter) {
 650						Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
 651						publishOwnDeviceIdIfNeeded();
 652					}
 653				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
 654					pepBroken = true;
 655					Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + packet.findChild("error"));
 656				}
 657			}
 658		});
 659	}
 660
 661	public enum AxolotlCapability {
 662		FULL,
 663		MISSING_PRESENCE,
 664		MISSING_KEYS,
 665		WRONG_CONFIGURATION,
 666		NO_MEMBERS
 667	}
 668
 669	public boolean isConversationAxolotlCapable(Conversation conversation) {
 670		return isConversationAxolotlCapableDetailed(conversation).first == AxolotlCapability.FULL;
 671	}
 672
 673	public Pair<AxolotlCapability,Jid> isConversationAxolotlCapableDetailed(Conversation conversation) {
 674		if (conversation.getMode() == Conversation.MODE_SINGLE
 675				|| (conversation.getMucOptions().membersOnly() && conversation.getMucOptions().nonanonymous())) {
 676			final List<Jid> jids = getCryptoTargets(conversation);
 677			for(Jid jid : jids) {
 678				if (!hasAny(jid) && (!deviceIds.containsKey(jid) || deviceIds.get(jid).isEmpty())) {
 679					if (conversation.getAccount().getRoster().getContact(jid).mutualPresenceSubscription()) {
 680						return new Pair<>(AxolotlCapability.MISSING_KEYS,jid);
 681					} else {
 682						return new Pair<>(AxolotlCapability.MISSING_PRESENCE,jid);
 683					}
 684				}
 685			}
 686			if (jids.size() > 0) {
 687				return new Pair<>(AxolotlCapability.FULL, null);
 688			} else {
 689				return new Pair<>(AxolotlCapability.NO_MEMBERS, null);
 690			}
 691		} else {
 692			return new Pair<>(AxolotlCapability.WRONG_CONFIGURATION, null);
 693		}
 694	}
 695
 696	public List<Jid> getCryptoTargets(Conversation conversation) {
 697		final List<Jid> jids;
 698		if (conversation.getMode() == Conversation.MODE_SINGLE) {
 699			jids = Arrays.asList(conversation.getJid().toBareJid());
 700		} else {
 701			jids = conversation.getMucOptions().getMembers();
 702		}
 703		return jids;
 704	}
 705
 706	public FingerprintStatus getFingerprintTrust(String fingerprint) {
 707		return axolotlStore.getFingerprintStatus(fingerprint);
 708	}
 709
 710	public X509Certificate getFingerprintCertificate(String fingerprint) {
 711		return axolotlStore.getFingerprintCertificate(fingerprint);
 712	}
 713
 714	public void setFingerprintTrust(String fingerprint, FingerprintStatus status) {
 715		axolotlStore.setFingerprintStatus(fingerprint, status);
 716	}
 717
 718	private void verifySessionWithPEP(final XmppAxolotlSession session) {
 719		Log.d(Config.LOGTAG, "trying to verify fresh session (" + session.getRemoteAddress().getName() + ") with pep");
 720		final AxolotlAddress address = session.getRemoteAddress();
 721		final IdentityKey identityKey = session.getIdentityKey();
 722		try {
 723			IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.fromString(address.getName()), address.getDeviceId());
 724			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 725				@Override
 726				public void onIqPacketReceived(Account account, IqPacket packet) {
 727					Pair<X509Certificate[],byte[]> verification = mXmppConnectionService.getIqParser().verification(packet);
 728					if (verification != null) {
 729						try {
 730							Signature verifier = Signature.getInstance("sha256WithRSA");
 731							verifier.initVerify(verification.first[0]);
 732							verifier.update(identityKey.serialize());
 733							if (verifier.verify(verification.second)) {
 734								try {
 735									mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA");
 736									String fingerprint = session.getFingerprint();
 737									Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: "+fingerprint);
 738									setFingerprintTrust(fingerprint, FingerprintStatus.createActiveVerified(true));
 739									axolotlStore.setFingerprintCertificate(fingerprint, verification.first[0]);
 740									fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED);
 741									Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]);
 742									try {
 743										final String cn = information.getString("subject_cn");
 744										final Jid jid = Jid.fromString(address.getName());
 745										Log.d(Config.LOGTAG,"setting common name for "+jid+" to "+cn);
 746										account.getRoster().getContact(jid).setCommonName(cn);
 747									} catch (final InvalidJidException ignored) {
 748										//ignored
 749									}
 750									finishBuildingSessionsFromPEP(address);
 751									return;
 752								} catch (Exception e) {
 753									Log.d(Config.LOGTAG,"could not verify certificate");
 754								}
 755							}
 756						} catch (Exception e) {
 757							Log.d(Config.LOGTAG, "error during verification " + e.getMessage());
 758						}
 759					} else {
 760						Log.d(Config.LOGTAG,"no verification found");
 761					}
 762					fetchStatusMap.put(address, FetchStatus.SUCCESS);
 763					finishBuildingSessionsFromPEP(address);
 764				}
 765			});
 766		} catch (InvalidJidException e) {
 767			fetchStatusMap.put(address, FetchStatus.SUCCESS);
 768			finishBuildingSessionsFromPEP(address);
 769		}
 770	}
 771
 772	private void finishBuildingSessionsFromPEP(final AxolotlAddress address) {
 773		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), 0);
 774		Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress);
 775		Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address);
 776		if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) {
 777			FetchStatus report = null;
 778			if (own.containsValue(FetchStatus.SUCCESS) || remote.containsValue(FetchStatus.SUCCESS)) {
 779				report = FetchStatus.SUCCESS;
 780			} else if (own.containsValue(FetchStatus.SUCCESS_VERIFIED) || remote.containsValue(FetchStatus.SUCCESS_VERIFIED)) {
 781				report = FetchStatus.SUCCESS_VERIFIED;
 782			} else if (own.containsValue(FetchStatus.ERROR) || remote.containsValue(FetchStatus.ERROR)) {
 783				report = FetchStatus.ERROR;
 784			}
 785			mXmppConnectionService.keyStatusUpdated(report);
 786		}
 787	}
 788
 789	private void buildSessionFromPEP(final AxolotlAddress address) {
 790		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.toString());
 791		if (address.getDeviceId() == getOwnDeviceId()) {
 792			throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
 793		}
 794
 795		try {
 796			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
 797					Jid.fromString(address.getName()), address.getDeviceId());
 798			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
 799			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
 800
 801				@Override
 802				public void onIqPacketReceived(Account account, IqPacket packet) {
 803					if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 804						fetchStatusMap.put(address, FetchStatus.TIMEOUT);
 805					} else if (packet.getType() == IqPacket.TYPE.RESULT) {
 806						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
 807						final IqParser parser = mXmppConnectionService.getIqParser();
 808						final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
 809						final PreKeyBundle bundle = parser.bundle(packet);
 810						if (preKeyBundleList.isEmpty() || bundle == null) {
 811							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
 812							fetchStatusMap.put(address, FetchStatus.ERROR);
 813							finishBuildingSessionsFromPEP(address);
 814							return;
 815						}
 816						Random random = new Random();
 817						final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
 818						if (preKey == null) {
 819							//should never happen
 820							fetchStatusMap.put(address, FetchStatus.ERROR);
 821							finishBuildingSessionsFromPEP(address);
 822							return;
 823						}
 824
 825						final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
 826								preKey.getPreKeyId(), preKey.getPreKey(),
 827								bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
 828								bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
 829
 830						try {
 831							SessionBuilder builder = new SessionBuilder(axolotlStore, address);
 832							builder.process(preKeyBundle);
 833							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey());
 834							sessions.put(address, session);
 835							if (Config.X509_VERIFICATION) {
 836								verifySessionWithPEP(session);
 837							} else {
 838								FingerprintStatus status = getFingerprintTrust(bundle.getIdentityKey().getFingerprint().replaceAll("\\s",""));
 839								boolean verified = status != null && status.isVerified();
 840								fetchStatusMap.put(address, verified ? FetchStatus.SUCCESS_VERIFIED : FetchStatus.SUCCESS);
 841								finishBuildingSessionsFromPEP(address);
 842							}
 843						} catch (UntrustedIdentityException | InvalidKeyException e) {
 844							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
 845									+ e.getClass().getName() + ", " + e.getMessage());
 846							fetchStatusMap.put(address, FetchStatus.ERROR);
 847							finishBuildingSessionsFromPEP(address);
 848						}
 849					} else {
 850						fetchStatusMap.put(address, FetchStatus.ERROR);
 851						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
 852						finishBuildingSessionsFromPEP(address);
 853					}
 854				}
 855			});
 856		} catch (InvalidJidException e) {
 857			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
 858		}
 859	}
 860
 861	public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
 862		Set<AxolotlAddress> addresses = new HashSet<>();
 863		for(Jid jid : getCryptoTargets(conversation)) {
 864			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + jid);
 865			if (deviceIds.get(jid) != null) {
 866				for (Integer foreignId : this.deviceIds.get(jid)) {
 867					AxolotlAddress address = new AxolotlAddress(jid.toString(), foreignId);
 868					if (sessions.get(address) == null) {
 869						IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
 870						if (identityKey != null) {
 871							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
 872							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
 873							sessions.put(address, session);
 874						} else {
 875							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + jid + ":" + foreignId);
 876							if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
 877								addresses.add(address);
 878							} else {
 879								Log.d(Config.LOGTAG, getLogprefix(account) + "skipping over " + address + " because it's broken");
 880							}
 881						}
 882					}
 883				}
 884			} else {
 885				Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
 886			}
 887		}
 888		if (deviceIds.get(account.getJid().toBareJid()) != null) {
 889			for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
 890				AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), ownId);
 891				if (sessions.get(address) == null) {
 892					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
 893					if (identityKey != null) {
 894						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
 895						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
 896						sessions.put(address, session);
 897					} else {
 898						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
 899						if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
 900							addresses.add(address);
 901						} else {
 902							Log.d(Config.LOGTAG,getLogprefix(account)+"skipping over "+address+" because it's broken");
 903						}
 904					}
 905				}
 906			}
 907		}
 908
 909		return addresses;
 910	}
 911
 912	public boolean createSessionsIfNeeded(final Conversation conversation) {
 913		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
 914		boolean newSessions = false;
 915		Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
 916		for (AxolotlAddress address : addresses) {
 917			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
 918			FetchStatus status = fetchStatusMap.get(address);
 919			if (status == null || status == FetchStatus.TIMEOUT) {
 920				fetchStatusMap.put(address, FetchStatus.PENDING);
 921				this.buildSessionFromPEP(address);
 922				newSessions = true;
 923			} else if (status == FetchStatus.PENDING) {
 924				newSessions = true;
 925			} else {
 926				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
 927			}
 928		}
 929
 930		return newSessions;
 931	}
 932
 933	public boolean trustedSessionVerified(final Conversation conversation) {
 934		Set<XmppAxolotlSession> sessions = findSessionsForConversation(conversation);
 935		sessions.addAll(findOwnSessions());
 936		boolean verified = false;
 937		for(XmppAxolotlSession session : sessions) {
 938			if (session.getTrust().isTrustedAndActive()) {
 939				if (session.getTrust().getTrust() == FingerprintStatus.Trust.VERIFIED_X509) {
 940					verified = true;
 941				} else {
 942					return false;
 943				}
 944			}
 945		}
 946		return verified;
 947	}
 948
 949	public boolean hasPendingKeyFetches(Account account, List<Jid> jids) {
 950		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), 0);
 951		if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)) {
 952			return true;
 953		}
 954		for(Jid jid : jids) {
 955			AxolotlAddress foreignAddress = new AxolotlAddress(jid.toBareJid().toPreppedString(), 0);
 956			if (fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
 957				return true;
 958			}
 959		}
 960		return false;
 961	}
 962
 963	@Nullable
 964	private XmppAxolotlMessage buildHeader(Conversation conversation) {
 965		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(
 966				account.getJid().toBareJid(), getOwnDeviceId());
 967
 968		Set<XmppAxolotlSession> remoteSessions = findSessionsForConversation(conversation);
 969		Collection<XmppAxolotlSession> ownSessions = findOwnSessions();
 970		if (remoteSessions.isEmpty()) {
 971			return null;
 972		}
 973		for (XmppAxolotlSession session : remoteSessions) {
 974			axolotlMessage.addDevice(session);
 975		}
 976		for (XmppAxolotlSession session : ownSessions) {
 977			axolotlMessage.addDevice(session);
 978		}
 979
 980		return axolotlMessage;
 981	}
 982
 983	@Nullable
 984	public XmppAxolotlMessage encrypt(Message message) {
 985		XmppAxolotlMessage axolotlMessage = buildHeader(message.getConversation());
 986
 987		if (axolotlMessage != null) {
 988			final String content;
 989			if (message.hasFileOnRemoteHost()) {
 990				content = message.getFileParams().url.toString();
 991			} else {
 992				content = message.getBody();
 993			}
 994			try {
 995				axolotlMessage.encrypt(content);
 996			} catch (CryptoFailedException e) {
 997				Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
 998				return null;
 999			}
1000		}
1001
1002		return axolotlMessage;
1003	}
1004
1005	public void preparePayloadMessage(final Message message, final boolean delay) {
1006		executor.execute(new Runnable() {
1007			@Override
1008			public void run() {
1009				XmppAxolotlMessage axolotlMessage = encrypt(message);
1010				if (axolotlMessage == null) {
1011					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1012					//mXmppConnectionService.updateConversationUi();
1013				} else {
1014					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
1015					messageCache.put(message.getUuid(), axolotlMessage);
1016					mXmppConnectionService.resendMessage(message, delay);
1017				}
1018			}
1019		});
1020	}
1021
1022	public void prepareKeyTransportMessage(final Conversation conversation, final OnMessageCreatedCallback onMessageCreatedCallback) {
1023		executor.execute(new Runnable() {
1024			@Override
1025			public void run() {
1026				XmppAxolotlMessage axolotlMessage = buildHeader(conversation);
1027				onMessageCreatedCallback.run(axolotlMessage);
1028			}
1029		});
1030	}
1031
1032	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
1033		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
1034		if (axolotlMessage != null) {
1035			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
1036			messageCache.remove(message.getUuid());
1037		} else {
1038			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
1039		}
1040		return axolotlMessage;
1041	}
1042
1043	private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
1044		IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1045		return (identityKey != null)
1046				? new XmppAxolotlSession(account, axolotlStore, address, identityKey)
1047				: null;
1048	}
1049
1050	private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
1051		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
1052				message.getSenderDeviceId());
1053		XmppAxolotlSession session = sessions.get(senderAddress);
1054		if (session == null) {
1055			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
1056			session = recreateUncachedSession(senderAddress);
1057			if (session == null) {
1058				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
1059			}
1060		}
1061		return session;
1062	}
1063
1064	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
1065		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
1066
1067		XmppAxolotlSession session = getReceivingSession(message);
1068		try {
1069			plaintextMessage = message.decrypt(session, getOwnDeviceId());
1070			Integer preKeyId = session.getPreKeyId();
1071			if (preKeyId != null) {
1072				publishBundlesIfNeeded(false, false);
1073				session.resetPreKeyId();
1074			}
1075		} catch (CryptoFailedException e) {
1076			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
1077		}
1078
1079		if (session.isFresh() && plaintextMessage != null) {
1080			putFreshSession(session);
1081		}
1082
1083		return plaintextMessage;
1084	}
1085
1086	public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
1087		XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage;
1088
1089		XmppAxolotlSession session = getReceivingSession(message);
1090		keyTransportMessage = message.getParameters(session, getOwnDeviceId());
1091
1092		if (session.isFresh() && keyTransportMessage != null) {
1093			putFreshSession(session);
1094		}
1095
1096		return keyTransportMessage;
1097	}
1098
1099	private void putFreshSession(XmppAxolotlSession session) {
1100		Log.d(Config.LOGTAG,"put fresh session");
1101		sessions.put(session);
1102		if (Config.X509_VERIFICATION) {
1103			if (session.getIdentityKey() != null) {
1104				verifySessionWithPEP(session);
1105			} else {
1106				Log.e(Config.LOGTAG,account.getJid().toBareJid()+": identity key was empty after reloading for x509 verification");
1107			}
1108		}
1109	}
1110}