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