AxolotlService.java

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