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