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 distrustFingerprint(final String fingerprint) {
 443		final String fp = fingerprint.replaceAll("\\s", "");
 444		final FingerprintStatus fingerprintStatus = axolotlStore.getFingerprintStatus(fp);
 445		axolotlStore.setFingerprintStatus(fp,fingerprintStatus.toUntrusted());
 446	}
 447
 448	public void publishOwnDeviceIdIfNeeded() {
 449		if (pepBroken) {
 450			Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
 451			return;
 452		}
 453		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
 454		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 455			@Override
 456			public void onIqPacketReceived(Account account, IqPacket packet) {
 457				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 458					Log.d(Config.LOGTAG, getLogprefix(account) + "Timeout received while retrieving own Device Ids.");
 459				} else {
 460					Element item = mXmppConnectionService.getIqParser().getItem(packet);
 461					Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
 462					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved own device list: "+deviceIds);
 463					registerDevices(account.getJid().toBareJid(),deviceIds);
 464				}
 465			}
 466		});
 467	}
 468
 469	private Set<Integer> getExpiredDevices() {
 470		Set<Integer> devices = new HashSet<>();
 471		for(XmppAxolotlSession session : findOwnSessions()) {
 472			if (session.getTrust().isActive()) {
 473				long diff = System.currentTimeMillis() - session.getTrust().getLastActivation();
 474				if (diff > Config.OMEMO_AUTO_EXPIRY) {
 475					long lastMessageDiff = System.currentTimeMillis() - mXmppConnectionService.databaseBackend.getLastTimeFingerprintUsed(account,session.getFingerprint());
 476					long hours = Math.round(lastMessageDiff/(1000*60.0*60.0));
 477					if (lastMessageDiff > Config.OMEMO_AUTO_EXPIRY) {
 478						devices.add(session.getRemoteAddress().getDeviceId());
 479						session.setTrust(session.getTrust().toInactive());
 480						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": added own device " + session.getFingerprint() + " to list of expired devices. Last message received "+hours+" hours ago");
 481					} else {
 482						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": own device "+session.getFingerprint()+" was active "+hours+" hours ago");
 483					}
 484				}
 485			}
 486		}
 487		return devices;
 488	}
 489
 490	public void publishOwnDeviceId(Set<Integer> deviceIds) {
 491		Set<Integer> deviceIdsCopy = new HashSet<>(deviceIds);
 492		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "publishing own device ids");
 493		if (deviceIdsCopy.isEmpty()) {
 494			if (numPublishTriesOnEmptyPep >= publishTriesThreshold) {
 495				Log.w(Config.LOGTAG, getLogprefix(account) + "Own device publish attempt threshold exceeded, aborting...");
 496				pepBroken = true;
 497				return;
 498			} else {
 499				numPublishTriesOnEmptyPep++;
 500				Log.w(Config.LOGTAG, getLogprefix(account) + "Own device list empty, attempting to publish (try " + numPublishTriesOnEmptyPep + ")");
 501			}
 502		} else {
 503			numPublishTriesOnEmptyPep = 0;
 504		}
 505		deviceIdsCopy.add(getOwnDeviceId());
 506		IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIdsCopy);
 507		ownPushPending.set(true);
 508		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 509			@Override
 510			public void onIqPacketReceived(Account account, IqPacket packet) {
 511				ownPushPending.set(false);
 512				if (packet.getType() == IqPacket.TYPE.ERROR) {
 513					pepBroken = true;
 514					Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing own device id" + packet.findChild("error"));
 515				}
 516			}
 517		});
 518	}
 519
 520	public void publishDeviceVerificationAndBundle(final SignedPreKeyRecord signedPreKeyRecord,
 521												   final Set<PreKeyRecord> preKeyRecords,
 522												   final boolean announceAfter,
 523												   final boolean wipe) {
 524		try {
 525			IdentityKey axolotlPublicKey = axolotlStore.getIdentityKeyPair().getPublicKey();
 526			PrivateKey x509PrivateKey = KeyChain.getPrivateKey(mXmppConnectionService, account.getPrivateKeyAlias());
 527			X509Certificate[] chain = KeyChain.getCertificateChain(mXmppConnectionService, account.getPrivateKeyAlias());
 528			Signature verifier = Signature.getInstance("sha256WithRSA");
 529			verifier.initSign(x509PrivateKey,mXmppConnectionService.getRNG());
 530			verifier.update(axolotlPublicKey.serialize());
 531			byte[] signature = verifier.sign();
 532			IqPacket packet = mXmppConnectionService.getIqGenerator().publishVerification(signature, chain, getOwnDeviceId());
 533			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": publish verification for device "+getOwnDeviceId());
 534			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 535				@Override
 536				public void onIqPacketReceived(Account account, IqPacket packet) {
 537					publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe);
 538				}
 539			});
 540		} catch (Exception  e) {
 541			e.printStackTrace();
 542		}
 543	}
 544
 545	public void publishBundlesIfNeeded(final boolean announce, final boolean wipe) {
 546		if (pepBroken) {
 547			Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
 548			return;
 549		}
 550		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
 551		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 552			@Override
 553			public void onIqPacketReceived(Account account, IqPacket packet) {
 554
 555				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 556					return; //ignore timeout. do nothing
 557				}
 558
 559				if (packet.getType() == IqPacket.TYPE.ERROR) {
 560					Element error = packet.findChild("error");
 561					if (error == null || !error.hasChild("item-not-found")) {
 562						pepBroken = true;
 563						Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "request for device bundles came back with something other than item-not-found" + packet);
 564						return;
 565					}
 566				}
 567
 568				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
 569				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
 570				boolean flush = false;
 571				if (bundle == null) {
 572					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
 573					bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
 574					flush = true;
 575				}
 576				if (keys == null) {
 577					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
 578				}
 579				try {
 580					boolean changed = false;
 581					// Validate IdentityKey
 582					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
 583					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
 584						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
 585						changed = true;
 586					}
 587
 588					// Validate signedPreKeyRecord + ID
 589					SignedPreKeyRecord signedPreKeyRecord;
 590					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
 591					try {
 592						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
 593						if (flush
 594								|| !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
 595								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
 596							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 597							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 598							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 599							changed = true;
 600						}
 601					} catch (InvalidKeyIdException e) {
 602						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 603						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 604						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 605						changed = true;
 606					}
 607
 608					// Validate PreKeys
 609					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
 610					if (keys != null) {
 611						for (Integer id : keys.keySet()) {
 612							try {
 613								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
 614								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
 615									preKeyRecords.add(preKeyRecord);
 616								}
 617							} catch (InvalidKeyIdException ignored) {
 618							}
 619						}
 620					}
 621					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
 622					if (newKeys > 0) {
 623						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
 624								axolotlStore.getCurrentPreKeyId() + 1, newKeys);
 625						preKeyRecords.addAll(newRecords);
 626						for (PreKeyRecord record : newRecords) {
 627							axolotlStore.storePreKey(record.getId(), record);
 628						}
 629						changed = true;
 630						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
 631					}
 632
 633
 634					if (changed) {
 635						if (account.getPrivateKeyAlias() != null && Config.X509_VERIFICATION) {
 636							mXmppConnectionService.publishDisplayName(account);
 637							publishDeviceVerificationAndBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
 638						} else {
 639							publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
 640						}
 641					} else {
 642						Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
 643						if (wipe) {
 644							wipeOtherPepDevices();
 645						} else if (announce) {
 646							Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
 647							publishOwnDeviceIdIfNeeded();
 648						}
 649					}
 650				} catch (InvalidKeyException e) {
 651					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
 652				}
 653			}
 654		});
 655	}
 656
 657	private void publishDeviceBundle(SignedPreKeyRecord signedPreKeyRecord,
 658									 Set<PreKeyRecord> preKeyRecords,
 659									 final boolean announceAfter,
 660									 final boolean wipe) {
 661		IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
 662				signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
 663				preKeyRecords, getOwnDeviceId());
 664		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
 665		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 666			@Override
 667			public void onIqPacketReceived(Account account, IqPacket packet) {
 668				if (packet.getType() == IqPacket.TYPE.RESULT) {
 669					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
 670					if (wipe) {
 671						wipeOtherPepDevices();
 672					} else if (announceAfter) {
 673						Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
 674						publishOwnDeviceIdIfNeeded();
 675					}
 676				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
 677					pepBroken = true;
 678					Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + packet.findChild("error"));
 679				}
 680			}
 681		});
 682	}
 683
 684	public enum AxolotlCapability {
 685		FULL,
 686		MISSING_PRESENCE,
 687		MISSING_KEYS,
 688		WRONG_CONFIGURATION,
 689		NO_MEMBERS
 690	}
 691
 692	public boolean isConversationAxolotlCapable(Conversation conversation) {
 693		return isConversationAxolotlCapableDetailed(conversation).first == AxolotlCapability.FULL;
 694	}
 695
 696	public Pair<AxolotlCapability,Jid> isConversationAxolotlCapableDetailed(Conversation conversation) {
 697		if (conversation.getMode() == Conversation.MODE_SINGLE
 698				|| (conversation.getMucOptions().membersOnly() && conversation.getMucOptions().nonanonymous())) {
 699			final List<Jid> jids = getCryptoTargets(conversation);
 700			for(Jid jid : jids) {
 701				if (!hasAny(jid) && (!deviceIds.containsKey(jid) || deviceIds.get(jid).isEmpty())) {
 702					if (conversation.getAccount().getRoster().getContact(jid).mutualPresenceSubscription()) {
 703						return new Pair<>(AxolotlCapability.MISSING_KEYS,jid);
 704					} else {
 705						return new Pair<>(AxolotlCapability.MISSING_PRESENCE,jid);
 706					}
 707				}
 708			}
 709			if (jids.size() > 0) {
 710				return new Pair<>(AxolotlCapability.FULL, null);
 711			} else {
 712				return new Pair<>(AxolotlCapability.NO_MEMBERS, null);
 713			}
 714		} else {
 715			return new Pair<>(AxolotlCapability.WRONG_CONFIGURATION, null);
 716		}
 717	}
 718
 719	public List<Jid> getCryptoTargets(Conversation conversation) {
 720		final List<Jid> jids;
 721		if (conversation.getMode() == Conversation.MODE_SINGLE) {
 722			jids = Arrays.asList(conversation.getJid().toBareJid());
 723		} else {
 724			jids = conversation.getMucOptions().getMembers();
 725		}
 726		return jids;
 727	}
 728
 729	public FingerprintStatus getFingerprintTrust(String fingerprint) {
 730		return axolotlStore.getFingerprintStatus(fingerprint);
 731	}
 732
 733	public X509Certificate getFingerprintCertificate(String fingerprint) {
 734		return axolotlStore.getFingerprintCertificate(fingerprint);
 735	}
 736
 737	public void setFingerprintTrust(String fingerprint, FingerprintStatus status) {
 738		axolotlStore.setFingerprintStatus(fingerprint, status);
 739	}
 740
 741	private void verifySessionWithPEP(final XmppAxolotlSession session) {
 742		Log.d(Config.LOGTAG, "trying to verify fresh session (" + session.getRemoteAddress().getName() + ") with pep");
 743		final AxolotlAddress address = session.getRemoteAddress();
 744		final IdentityKey identityKey = session.getIdentityKey();
 745		try {
 746			IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.fromString(address.getName()), address.getDeviceId());
 747			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 748				@Override
 749				public void onIqPacketReceived(Account account, IqPacket packet) {
 750					Pair<X509Certificate[],byte[]> verification = mXmppConnectionService.getIqParser().verification(packet);
 751					if (verification != null) {
 752						try {
 753							Signature verifier = Signature.getInstance("sha256WithRSA");
 754							verifier.initVerify(verification.first[0]);
 755							verifier.update(identityKey.serialize());
 756							if (verifier.verify(verification.second)) {
 757								try {
 758									mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA");
 759									String fingerprint = session.getFingerprint();
 760									Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: "+fingerprint);
 761									setFingerprintTrust(fingerprint, FingerprintStatus.createActiveVerified(true));
 762									axolotlStore.setFingerprintCertificate(fingerprint, verification.first[0]);
 763									fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED);
 764									Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]);
 765									try {
 766										final String cn = information.getString("subject_cn");
 767										final Jid jid = Jid.fromString(address.getName());
 768										Log.d(Config.LOGTAG,"setting common name for "+jid+" to "+cn);
 769										account.getRoster().getContact(jid).setCommonName(cn);
 770									} catch (final InvalidJidException ignored) {
 771										//ignored
 772									}
 773									finishBuildingSessionsFromPEP(address);
 774									return;
 775								} catch (Exception e) {
 776									Log.d(Config.LOGTAG,"could not verify certificate");
 777								}
 778							}
 779						} catch (Exception e) {
 780							Log.d(Config.LOGTAG, "error during verification " + e.getMessage());
 781						}
 782					} else {
 783						Log.d(Config.LOGTAG,"no verification found");
 784					}
 785					fetchStatusMap.put(address, FetchStatus.SUCCESS);
 786					finishBuildingSessionsFromPEP(address);
 787				}
 788			});
 789		} catch (InvalidJidException e) {
 790			fetchStatusMap.put(address, FetchStatus.SUCCESS);
 791			finishBuildingSessionsFromPEP(address);
 792		}
 793	}
 794
 795	private final Set<Integer> PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT = new HashSet<>();
 796
 797	private void finishBuildingSessionsFromPEP(final AxolotlAddress address) {
 798		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), 0);
 799		Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress);
 800		Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address);
 801		if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) {
 802			FetchStatus report = null;
 803			if (own.containsValue(FetchStatus.SUCCESS) || remote.containsValue(FetchStatus.SUCCESS)) {
 804				report = FetchStatus.SUCCESS;
 805			} else if (own.containsValue(FetchStatus.SUCCESS_VERIFIED) || remote.containsValue(FetchStatus.SUCCESS_VERIFIED)) {
 806				report = FetchStatus.SUCCESS_VERIFIED;
 807			} else if (own.containsValue(FetchStatus.SUCCESS_TRUSTED) || remote.containsValue(FetchStatus.SUCCESS_TRUSTED)) {
 808				report = FetchStatus.SUCCESS_TRUSTED;
 809			} else if (own.containsValue(FetchStatus.ERROR) || remote.containsValue(FetchStatus.ERROR)) {
 810				report = FetchStatus.ERROR;
 811			}
 812			mXmppConnectionService.keyStatusUpdated(report);
 813		}
 814		if (Config.REMOVE_BROKEN_DEVICES) {
 815			Set<Integer> ownDeviceIds = new HashSet<>(getOwnDeviceIds());
 816			boolean publish = false;
 817			for (Map.Entry<Integer, FetchStatus> entry : own.entrySet()) {
 818				int id = entry.getKey();
 819				if (entry.getValue() == FetchStatus.ERROR && PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT.add(id) && ownDeviceIds.remove(id)) {
 820					publish = true;
 821					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": error fetching own device with id " + id + ". removing from announcement");
 822				}
 823			}
 824			if (publish) {
 825				publishOwnDeviceId(ownDeviceIds);
 826			}
 827		}
 828	}
 829
 830	private void buildSessionFromPEP(final AxolotlAddress address) {
 831		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new session for " + address.toString());
 832		if (address.equals(getOwnAxolotlAddress())) {
 833			throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
 834		}
 835
 836		try {
 837			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
 838					Jid.fromString(address.getName()), address.getDeviceId());
 839			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
 840			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
 841
 842				@Override
 843				public void onIqPacketReceived(Account account, IqPacket packet) {
 844					if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 845						fetchStatusMap.put(address, FetchStatus.TIMEOUT);
 846					} else if (packet.getType() == IqPacket.TYPE.RESULT) {
 847						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
 848						final IqParser parser = mXmppConnectionService.getIqParser();
 849						final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
 850						final PreKeyBundle bundle = parser.bundle(packet);
 851						if (preKeyBundleList.isEmpty() || bundle == null) {
 852							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
 853							fetchStatusMap.put(address, FetchStatus.ERROR);
 854							finishBuildingSessionsFromPEP(address);
 855							return;
 856						}
 857						Random random = new Random();
 858						final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
 859						if (preKey == null) {
 860							//should never happen
 861							fetchStatusMap.put(address, FetchStatus.ERROR);
 862							finishBuildingSessionsFromPEP(address);
 863							return;
 864						}
 865
 866						final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
 867								preKey.getPreKeyId(), preKey.getPreKey(),
 868								bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
 869								bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
 870
 871						try {
 872							SessionBuilder builder = new SessionBuilder(axolotlStore, address);
 873							builder.process(preKeyBundle);
 874							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey());
 875							sessions.put(address, session);
 876							if (Config.X509_VERIFICATION) {
 877								verifySessionWithPEP(session);
 878							} else {
 879								FingerprintStatus status = getFingerprintTrust(bundle.getIdentityKey().getFingerprint().replaceAll("\\s",""));
 880								FetchStatus fetchStatus;
 881								if (status != null && status.isVerified()) {
 882									fetchStatus = FetchStatus.SUCCESS_VERIFIED;
 883								} else if (status != null && status.isTrusted()) {
 884									fetchStatus = FetchStatus.SUCCESS_TRUSTED;
 885								} else {
 886									fetchStatus = FetchStatus.SUCCESS;
 887								}
 888								fetchStatusMap.put(address, fetchStatus);
 889								finishBuildingSessionsFromPEP(address);
 890							}
 891						} catch (UntrustedIdentityException | InvalidKeyException e) {
 892							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
 893									+ e.getClass().getName() + ", " + e.getMessage());
 894							fetchStatusMap.put(address, FetchStatus.ERROR);
 895							finishBuildingSessionsFromPEP(address);
 896						}
 897					} else {
 898						fetchStatusMap.put(address, FetchStatus.ERROR);
 899						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
 900						finishBuildingSessionsFromPEP(address);
 901					}
 902				}
 903			});
 904		} catch (InvalidJidException e) {
 905			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
 906		}
 907	}
 908
 909	public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
 910		Set<AxolotlAddress> addresses = new HashSet<>();
 911		for(Jid jid : getCryptoTargets(conversation)) {
 912			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + jid);
 913			if (deviceIds.get(jid) != null) {
 914				for (Integer foreignId : this.deviceIds.get(jid)) {
 915					AxolotlAddress address = new AxolotlAddress(jid.toPreppedString(), foreignId);
 916					if (sessions.get(address) == null) {
 917						IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
 918						if (identityKey != null) {
 919							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
 920							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
 921							sessions.put(address, session);
 922						} else {
 923							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + jid + ":" + foreignId);
 924							if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
 925								addresses.add(address);
 926							} else {
 927								Log.d(Config.LOGTAG, getLogprefix(account) + "skipping over " + address + " because it's broken");
 928							}
 929						}
 930					}
 931				}
 932			} else {
 933				Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
 934			}
 935		}
 936		if (deviceIds.get(account.getJid().toBareJid()) != null) {
 937			for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
 938				AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), ownId);
 939				if (sessions.get(address) == null) {
 940					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
 941					if (identityKey != null) {
 942						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
 943						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
 944						sessions.put(address, session);
 945					} else {
 946						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
 947						if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
 948							addresses.add(address);
 949						} else {
 950							Log.d(Config.LOGTAG,getLogprefix(account)+"skipping over "+address+" because it's broken");
 951						}
 952					}
 953				}
 954			}
 955		}
 956
 957		return addresses;
 958	}
 959
 960	public boolean createSessionsIfNeeded(final Conversation conversation) {
 961		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
 962		boolean newSessions = false;
 963		Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
 964		for (AxolotlAddress address : addresses) {
 965			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
 966			FetchStatus status = fetchStatusMap.get(address);
 967			if (status == null || status == FetchStatus.TIMEOUT) {
 968				fetchStatusMap.put(address, FetchStatus.PENDING);
 969				this.buildSessionFromPEP(address);
 970				newSessions = true;
 971			} else if (status == FetchStatus.PENDING) {
 972				newSessions = true;
 973			} else {
 974				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
 975			}
 976		}
 977
 978		return newSessions;
 979	}
 980
 981	public boolean trustedSessionVerified(final Conversation conversation) {
 982		Set<XmppAxolotlSession> sessions = findSessionsForConversation(conversation);
 983		sessions.addAll(findOwnSessions());
 984		boolean verified = false;
 985		for(XmppAxolotlSession session : sessions) {
 986			if (session.getTrust().isTrustedAndActive()) {
 987				if (session.getTrust().getTrust() == FingerprintStatus.Trust.VERIFIED_X509) {
 988					verified = true;
 989				} else {
 990					return false;
 991				}
 992			}
 993		}
 994		return verified;
 995	}
 996
 997	public boolean hasPendingKeyFetches(Account account, List<Jid> jids) {
 998		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), 0);
 999		if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)) {
1000			return true;
1001		}
1002		for(Jid jid : jids) {
1003			AxolotlAddress foreignAddress = new AxolotlAddress(jid.toBareJid().toPreppedString(), 0);
1004			if (fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
1005				return true;
1006			}
1007		}
1008		return false;
1009	}
1010
1011	@Nullable
1012	private boolean buildHeader(XmppAxolotlMessage axolotlMessage, Conversation conversation) {
1013		Set<XmppAxolotlSession> remoteSessions = findSessionsForConversation(conversation);
1014		Collection<XmppAxolotlSession> ownSessions = findOwnSessions();
1015		if (remoteSessions.isEmpty()) {
1016			return false;
1017		}
1018		for (XmppAxolotlSession session : remoteSessions) {
1019			axolotlMessage.addDevice(session);
1020		}
1021		for (XmppAxolotlSession session : ownSessions) {
1022			axolotlMessage.addDevice(session);
1023		}
1024
1025		return true;
1026	}
1027
1028	@Nullable
1029	public XmppAxolotlMessage encrypt(Message message) {
1030		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().toBareJid(), getOwnDeviceId());
1031		final String content;
1032		if (message.hasFileOnRemoteHost()) {
1033			content = message.getFileParams().url.toString();
1034		} else {
1035			content = message.getBody();
1036		}
1037		try {
1038			axolotlMessage.encrypt(content);
1039		} catch (CryptoFailedException e) {
1040			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
1041			return null;
1042		}
1043		if (!buildHeader(axolotlMessage,message.getConversation())) {
1044			return null;
1045		}
1046
1047		return axolotlMessage;
1048	}
1049
1050	public void preparePayloadMessage(final Message message, final boolean delay) {
1051		executor.execute(new Runnable() {
1052			@Override
1053			public void run() {
1054				XmppAxolotlMessage axolotlMessage = encrypt(message);
1055				if (axolotlMessage == null) {
1056					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1057					//mXmppConnectionService.updateConversationUi();
1058				} else {
1059					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
1060					messageCache.put(message.getUuid(), axolotlMessage);
1061					mXmppConnectionService.resendMessage(message, delay);
1062				}
1063			}
1064		});
1065	}
1066
1067	public void prepareKeyTransportMessage(final Conversation conversation, final OnMessageCreatedCallback onMessageCreatedCallback) {
1068		executor.execute(new Runnable() {
1069			@Override
1070			public void run() {
1071				final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().toBareJid(), getOwnDeviceId());
1072				if (buildHeader(axolotlMessage,conversation)) {
1073					onMessageCreatedCallback.run(axolotlMessage);
1074				} else {
1075					onMessageCreatedCallback.run(null);
1076				}
1077			}
1078		});
1079	}
1080
1081	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
1082		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
1083		if (axolotlMessage != null) {
1084			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
1085			messageCache.remove(message.getUuid());
1086		} else {
1087			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
1088		}
1089		return axolotlMessage;
1090	}
1091
1092	private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
1093		IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1094		return (identityKey != null)
1095				? new XmppAxolotlSession(account, axolotlStore, address, identityKey)
1096				: null;
1097	}
1098
1099	private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
1100		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toPreppedString(),
1101				message.getSenderDeviceId());
1102		XmppAxolotlSession session = sessions.get(senderAddress);
1103		if (session == null) {
1104			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
1105			session = recreateUncachedSession(senderAddress);
1106			if (session == null) {
1107				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
1108			}
1109		}
1110		return session;
1111	}
1112
1113	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
1114		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
1115
1116		XmppAxolotlSession session = getReceivingSession(message);
1117		try {
1118			plaintextMessage = message.decrypt(session, getOwnDeviceId());
1119			Integer preKeyId = session.getPreKeyId();
1120			if (preKeyId != null) {
1121				publishBundlesIfNeeded(false, false);
1122				session.resetPreKeyId();
1123			}
1124		} catch (CryptoFailedException e) {
1125			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message from "+message.getFrom()+": " + e.getMessage());
1126		}
1127
1128		if (session.isFresh() && plaintextMessage != null) {
1129			putFreshSession(session);
1130		}
1131
1132		return plaintextMessage;
1133	}
1134
1135	public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
1136		XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage;
1137
1138		XmppAxolotlSession session = getReceivingSession(message);
1139		try {
1140			keyTransportMessage = message.getParameters(session, getOwnDeviceId());
1141		} catch (CryptoFailedException e) {
1142			Log.d(Config.LOGTAG,"could not decrypt keyTransport message "+e.getMessage());
1143			keyTransportMessage = null;
1144		}
1145
1146		if (session.isFresh() && keyTransportMessage != null) {
1147			putFreshSession(session);
1148		}
1149
1150		return keyTransportMessage;
1151	}
1152
1153	private void putFreshSession(XmppAxolotlSession session) {
1154		Log.d(Config.LOGTAG,"put fresh session");
1155		sessions.put(session);
1156		if (Config.X509_VERIFICATION) {
1157			if (session.getIdentityKey() != null) {
1158				verifySessionWithPEP(session);
1159			} else {
1160				Log.e(Config.LOGTAG,account.getJid().toBareJid()+": identity key was empty after reloading for x509 verification");
1161			}
1162		}
1163	}
1164}