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 boolean isConversationAxolotlCapable(Conversation conversation) {
 651		final List<Jid> jids = getCryptoTargets(conversation);
 652		for(Jid jid : jids) {
 653			if (!hasAny(jid) && (!deviceIds.containsKey(jid) || deviceIds.get(jid).isEmpty())) {
 654				return false;
 655			}
 656		}
 657		return jids.size() > 0;
 658	}
 659
 660	public List<Jid> getCryptoTargets(Conversation conversation) {
 661		final List<Jid> jids;
 662		if (conversation.getMode() == Conversation.MODE_SINGLE) {
 663			jids = Arrays.asList(conversation.getJid().toBareJid());
 664		} else {
 665			jids = conversation.getMucOptions().getMembers();
 666		}
 667		return jids;
 668	}
 669
 670	public XmppAxolotlSession.Trust getFingerprintTrust(String fingerprint) {
 671		return axolotlStore.getFingerprintTrust(fingerprint);
 672	}
 673
 674	public X509Certificate getFingerprintCertificate(String fingerprint) {
 675		return axolotlStore.getFingerprintCertificate(fingerprint);
 676	}
 677
 678	public void setFingerprintTrust(String fingerprint, XmppAxolotlSession.Trust trust) {
 679		axolotlStore.setFingerprintTrust(fingerprint, trust);
 680	}
 681
 682	private void verifySessionWithPEP(final XmppAxolotlSession session) {
 683		Log.d(Config.LOGTAG, "trying to verify fresh session (" + session.getRemoteAddress().getName() + ") with pep");
 684		final AxolotlAddress address = session.getRemoteAddress();
 685		final IdentityKey identityKey = session.getIdentityKey();
 686		try {
 687			IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.fromString(address.getName()), address.getDeviceId());
 688			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 689				@Override
 690				public void onIqPacketReceived(Account account, IqPacket packet) {
 691					Pair<X509Certificate[],byte[]> verification = mXmppConnectionService.getIqParser().verification(packet);
 692					if (verification != null) {
 693						try {
 694							Signature verifier = Signature.getInstance("sha256WithRSA");
 695							verifier.initVerify(verification.first[0]);
 696							verifier.update(identityKey.serialize());
 697							if (verifier.verify(verification.second)) {
 698								try {
 699									mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA");
 700									String fingerprint = session.getFingerprint();
 701									Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: "+fingerprint);
 702									setFingerprintTrust(fingerprint, XmppAxolotlSession.Trust.TRUSTED_X509);
 703									axolotlStore.setFingerprintCertificate(fingerprint, verification.first[0]);
 704									fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED);
 705									Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]);
 706									try {
 707										final String cn = information.getString("subject_cn");
 708										final Jid jid = Jid.fromString(address.getName());
 709										Log.d(Config.LOGTAG,"setting common name for "+jid+" to "+cn);
 710										account.getRoster().getContact(jid).setCommonName(cn);
 711									} catch (final InvalidJidException ignored) {
 712										//ignored
 713									}
 714									finishBuildingSessionsFromPEP(address);
 715									return;
 716								} catch (Exception e) {
 717									Log.d(Config.LOGTAG,"could not verify certificate");
 718								}
 719							}
 720						} catch (Exception e) {
 721							Log.d(Config.LOGTAG, "error during verification " + e.getMessage());
 722						}
 723					} else {
 724						Log.d(Config.LOGTAG,"no verification found");
 725					}
 726					fetchStatusMap.put(address, FetchStatus.SUCCESS);
 727					finishBuildingSessionsFromPEP(address);
 728				}
 729			});
 730		} catch (InvalidJidException e) {
 731			fetchStatusMap.put(address, FetchStatus.SUCCESS);
 732			finishBuildingSessionsFromPEP(address);
 733		}
 734	}
 735
 736	private void finishBuildingSessionsFromPEP(final AxolotlAddress address) {
 737		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
 738		if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
 739				&& !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) {
 740			FetchStatus report = null;
 741			if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.SUCCESS_VERIFIED)
 742					| fetchStatusMap.getAll(address).containsValue(FetchStatus.SUCCESS_VERIFIED)) {
 743				report = FetchStatus.SUCCESS_VERIFIED;
 744			} else if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.ERROR)
 745					|| fetchStatusMap.getAll(address).containsValue(FetchStatus.ERROR)) {
 746				report = FetchStatus.ERROR;
 747			}
 748			mXmppConnectionService.keyStatusUpdated(report);
 749		}
 750	}
 751
 752	private void buildSessionFromPEP(final AxolotlAddress address) {
 753		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.toString());
 754		if (address.getDeviceId() == getOwnDeviceId()) {
 755			throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
 756		}
 757
 758		try {
 759			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
 760					Jid.fromString(address.getName()), address.getDeviceId());
 761			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
 762			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
 763
 764				@Override
 765				public void onIqPacketReceived(Account account, IqPacket packet) {
 766					if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 767						fetchStatusMap.put(address, FetchStatus.TIMEOUT);
 768					} else if (packet.getType() == IqPacket.TYPE.RESULT) {
 769						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
 770						final IqParser parser = mXmppConnectionService.getIqParser();
 771						final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
 772						final PreKeyBundle bundle = parser.bundle(packet);
 773						if (preKeyBundleList.isEmpty() || bundle == null) {
 774							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
 775							fetchStatusMap.put(address, FetchStatus.ERROR);
 776							finishBuildingSessionsFromPEP(address);
 777							return;
 778						}
 779						Random random = new Random();
 780						final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
 781						if (preKey == null) {
 782							//should never happen
 783							fetchStatusMap.put(address, FetchStatus.ERROR);
 784							finishBuildingSessionsFromPEP(address);
 785							return;
 786						}
 787
 788						final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
 789								preKey.getPreKeyId(), preKey.getPreKey(),
 790								bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
 791								bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
 792
 793						try {
 794							SessionBuilder builder = new SessionBuilder(axolotlStore, address);
 795							builder.process(preKeyBundle);
 796							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey());
 797							sessions.put(address, session);
 798							if (Config.X509_VERIFICATION) {
 799								verifySessionWithPEP(session);
 800							} else {
 801								fetchStatusMap.put(address, FetchStatus.SUCCESS);
 802								finishBuildingSessionsFromPEP(address);
 803							}
 804						} catch (UntrustedIdentityException | InvalidKeyException e) {
 805							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
 806									+ e.getClass().getName() + ", " + e.getMessage());
 807							fetchStatusMap.put(address, FetchStatus.ERROR);
 808							finishBuildingSessionsFromPEP(address);
 809						}
 810					} else {
 811						fetchStatusMap.put(address, FetchStatus.ERROR);
 812						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
 813						finishBuildingSessionsFromPEP(address);
 814					}
 815				}
 816			});
 817		} catch (InvalidJidException e) {
 818			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
 819		}
 820	}
 821
 822	public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
 823		Set<AxolotlAddress> addresses = new HashSet<>();
 824		for(Jid jid : getCryptoTargets(conversation)) {
 825			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + jid);
 826			if (deviceIds.get(jid) != null) {
 827				for (Integer foreignId : this.deviceIds.get(jid)) {
 828					AxolotlAddress address = new AxolotlAddress(jid.toString(), foreignId);
 829					if (sessions.get(address) == null) {
 830						IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
 831						if (identityKey != null) {
 832							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
 833							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
 834							sessions.put(address, session);
 835						} else {
 836							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + jid + ":" + foreignId);
 837							if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
 838								addresses.add(address);
 839							} else {
 840								Log.d(Config.LOGTAG, getLogprefix(account) + "skipping over " + address + " because it's broken");
 841							}
 842						}
 843					}
 844				}
 845			} else {
 846				Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
 847			}
 848		}
 849		if (deviceIds.get(account.getJid().toBareJid()) != null) {
 850			for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
 851				AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
 852				if (sessions.get(address) == null) {
 853					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
 854					if (identityKey != null) {
 855						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
 856						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
 857						sessions.put(address, session);
 858					} else {
 859						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
 860						if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
 861							addresses.add(address);
 862						} else {
 863							Log.d(Config.LOGTAG,getLogprefix(account)+"skipping over "+address+" because it's broken");
 864						}
 865					}
 866				}
 867			}
 868		}
 869
 870		return addresses;
 871	}
 872
 873	public boolean createSessionsIfNeeded(final Conversation conversation) {
 874		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
 875		boolean newSessions = false;
 876		Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
 877		for (AxolotlAddress address : addresses) {
 878			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
 879			FetchStatus status = fetchStatusMap.get(address);
 880			if (status == null || status == FetchStatus.TIMEOUT) {
 881				fetchStatusMap.put(address, FetchStatus.PENDING);
 882				this.buildSessionFromPEP(address);
 883				newSessions = true;
 884			} else if (status == FetchStatus.PENDING) {
 885				newSessions = true;
 886			} else {
 887				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
 888			}
 889		}
 890
 891		return newSessions;
 892	}
 893
 894	public boolean trustedSessionVerified(final Conversation conversation) {
 895		Set<XmppAxolotlSession> sessions = findSessionsForConversation(conversation);
 896		sessions.addAll(findOwnSessions());
 897		boolean verified = false;
 898		for(XmppAxolotlSession session : sessions) {
 899			if (session.getTrust().trusted()) {
 900				if (session.getTrust() == XmppAxolotlSession.Trust.TRUSTED_X509) {
 901					verified = true;
 902				} else {
 903					return false;
 904				}
 905			}
 906		}
 907		return verified;
 908	}
 909
 910	public boolean hasPendingKeyFetches(Account account, List<Jid> jids) {
 911		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
 912		if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)) {
 913			return true;
 914		}
 915		for(Jid jid : jids) {
 916			AxolotlAddress foreignAddress = new AxolotlAddress(jid.toBareJid().toString(), 0);
 917			if (fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
 918				return true;
 919			}
 920		}
 921		return false;
 922	}
 923
 924	@Nullable
 925	private XmppAxolotlMessage buildHeader(Conversation conversation) {
 926		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(
 927				account.getJid().toBareJid(), getOwnDeviceId());
 928
 929		Set<XmppAxolotlSession> remoteSessions = findSessionsForConversation(conversation);
 930		Set<XmppAxolotlSession> ownSessions = findOwnSessions();
 931		if (remoteSessions.isEmpty()) {
 932			return null;
 933		}
 934		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl foreign keyElements...");
 935		for (XmppAxolotlSession session : remoteSessions) {
 936			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
 937			axolotlMessage.addDevice(session);
 938		}
 939		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl own keyElements...");
 940		for (XmppAxolotlSession session : ownSessions) {
 941			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
 942			axolotlMessage.addDevice(session);
 943		}
 944
 945		return axolotlMessage;
 946	}
 947
 948	@Nullable
 949	public XmppAxolotlMessage encrypt(Message message) {
 950		XmppAxolotlMessage axolotlMessage = buildHeader(message.getConversation());
 951
 952		if (axolotlMessage != null) {
 953			final String content;
 954			if (message.hasFileOnRemoteHost()) {
 955				content = message.getFileParams().url.toString();
 956			} else {
 957				content = message.getBody();
 958			}
 959			try {
 960				axolotlMessage.encrypt(content);
 961			} catch (CryptoFailedException e) {
 962				Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
 963				return null;
 964			}
 965		}
 966
 967		return axolotlMessage;
 968	}
 969
 970	public void preparePayloadMessage(final Message message, final boolean delay) {
 971		executor.execute(new Runnable() {
 972			@Override
 973			public void run() {
 974				XmppAxolotlMessage axolotlMessage = encrypt(message);
 975				if (axolotlMessage == null) {
 976					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
 977					//mXmppConnectionService.updateConversationUi();
 978				} else {
 979					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
 980					messageCache.put(message.getUuid(), axolotlMessage);
 981					mXmppConnectionService.resendMessage(message, delay);
 982				}
 983			}
 984		});
 985	}
 986
 987	public void prepareKeyTransportMessage(final Conversation conversation, final OnMessageCreatedCallback onMessageCreatedCallback) {
 988		executor.execute(new Runnable() {
 989			@Override
 990			public void run() {
 991				XmppAxolotlMessage axolotlMessage = buildHeader(conversation);
 992				onMessageCreatedCallback.run(axolotlMessage);
 993			}
 994		});
 995	}
 996
 997	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
 998		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
 999		if (axolotlMessage != null) {
1000			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
1001			messageCache.remove(message.getUuid());
1002		} else {
1003			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
1004		}
1005		return axolotlMessage;
1006	}
1007
1008	private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
1009		IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1010		return (identityKey != null)
1011				? new XmppAxolotlSession(account, axolotlStore, address, identityKey)
1012				: null;
1013	}
1014
1015	private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
1016		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
1017				message.getSenderDeviceId());
1018		XmppAxolotlSession session = sessions.get(senderAddress);
1019		if (session == null) {
1020			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
1021			session = recreateUncachedSession(senderAddress);
1022			if (session == null) {
1023				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
1024			}
1025		}
1026		return session;
1027	}
1028
1029	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
1030		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
1031
1032		XmppAxolotlSession session = getReceivingSession(message);
1033		try {
1034			plaintextMessage = message.decrypt(session, getOwnDeviceId());
1035			Integer preKeyId = session.getPreKeyId();
1036			if (preKeyId != null) {
1037				publishBundlesIfNeeded(false, false);
1038				session.resetPreKeyId();
1039			}
1040		} catch (CryptoFailedException e) {
1041			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
1042		}
1043
1044		if (session.isFresh() && plaintextMessage != null) {
1045			putFreshSession(session);
1046		}
1047
1048		return plaintextMessage;
1049	}
1050
1051	public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
1052		XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage;
1053
1054		XmppAxolotlSession session = getReceivingSession(message);
1055		keyTransportMessage = message.getParameters(session, getOwnDeviceId());
1056
1057		if (session.isFresh() && keyTransportMessage != null) {
1058			putFreshSession(session);
1059		}
1060
1061		return keyTransportMessage;
1062	}
1063
1064	private void putFreshSession(XmppAxolotlSession session) {
1065		Log.d(Config.LOGTAG,"put fresh session");
1066		sessions.put(session);
1067		if (Config.X509_VERIFICATION) {
1068			if (session.getIdentityKey() != null) {
1069				verifySessionWithPEP(session);
1070			} else {
1071				Log.e(Config.LOGTAG,account.getJid().toBareJid()+": identity key was empty after reloading for x509 verification");
1072			}
1073		}
1074	}
1075}