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.libsignal.SignalProtocolAddress;
  12import org.whispersystems.libsignal.IdentityKey;
  13import org.whispersystems.libsignal.IdentityKeyPair;
  14import org.whispersystems.libsignal.InvalidKeyException;
  15import org.whispersystems.libsignal.InvalidKeyIdException;
  16import org.whispersystems.libsignal.SessionBuilder;
  17import org.whispersystems.libsignal.UntrustedIdentityException;
  18import org.whispersystems.libsignal.ecc.ECPublicKey;
  19import org.whispersystems.libsignal.state.PreKeyBundle;
  20import org.whispersystems.libsignal.state.PreKeyRecord;
  21import org.whispersystems.libsignal.state.SignedPreKeyRecord;
  22import org.whispersystems.libsignal.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.Iterator;
  35import java.util.List;
  36import java.util.Map;
  37import java.util.Random;
  38import java.util.Set;
  39import java.util.concurrent.atomic.AtomicBoolean;
  40
  41import eu.siacs.conversations.Config;
  42import eu.siacs.conversations.entities.Account;
  43import eu.siacs.conversations.entities.Contact;
  44import eu.siacs.conversations.entities.Conversation;
  45import eu.siacs.conversations.entities.Message;
  46import eu.siacs.conversations.parser.IqParser;
  47import eu.siacs.conversations.services.XmppConnectionService;
  48import eu.siacs.conversations.utils.CryptoHelper;
  49import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
  50import eu.siacs.conversations.xml.Element;
  51import eu.siacs.conversations.xml.Namespace;
  52import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
  53import eu.siacs.conversations.xmpp.OnIqPacketReceived;
  54import eu.siacs.conversations.xmpp.pep.PublishOptions;
  55import eu.siacs.conversations.xmpp.stanzas.IqPacket;
  56import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
  57import rocks.xmpp.addr.Jid;
  58
  59public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {
  60
  61	public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl";
  62	public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist";
  63	public static final String PEP_DEVICE_LIST_NOTIFY = PEP_DEVICE_LIST + "+notify";
  64	public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
  65	public static final String PEP_VERIFICATION = PEP_PREFIX + ".verification";
  66	public static final String PEP_OMEMO_WHITELISTED = PEP_PREFIX + ".whitelisted";
  67
  68	public static final String LOGPREFIX = "AxolotlService";
  69
  70	public static final int NUM_KEYS_TO_PUBLISH = 100;
  71	public static final int publishTriesThreshold = 3;
  72
  73	private final Account account;
  74	private final XmppConnectionService mXmppConnectionService;
  75	private final SQLiteAxolotlStore axolotlStore;
  76	private final SessionMap sessions;
  77	private final Map<Jid, Set<Integer>> deviceIds;
  78	private final Map<String, XmppAxolotlMessage> messageCache;
  79	private final FetchStatusMap fetchStatusMap;
  80	private final Map<Jid, Boolean> fetchDeviceListStatus = new HashMap<>();
  81	private final HashMap<Jid, List<OnDeviceIdsFetched>> fetchDeviceIdsMap = new HashMap<>();
  82	private final SerialSingleThreadExecutor executor;
  83	private int numPublishTriesOnEmptyPep = 0;
  84	private boolean pepBroken = false;
  85	private int lastDeviceListNotificationHash = 0;
  86	private final HashSet<Integer> cleanedOwnDeviceIds = new HashSet<>();
  87	private Set<XmppAxolotlSession> postponedSessions = new HashSet<>(); //sessions stored here will receive after mam catchup treatment
  88
  89	private AtomicBoolean changeAccessMode = new AtomicBoolean(false);
  90
  91	@Override
  92	public void onAdvancedStreamFeaturesAvailable(Account account) {
  93		if (Config.supportOmemo()
  94				&& account.getXmppConnection() != null
  95				&& account.getXmppConnection().getFeatures().pep()) {
  96			publishBundlesIfNeeded(true, false);
  97		} else {
  98			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": skipping OMEMO initialization");
  99		}
 100	}
 101
 102	private boolean hasErrorFetchingDeviceList(Jid jid) {
 103		Boolean status = fetchDeviceListStatus.get(jid);
 104		return status != null && !status;
 105	}
 106
 107	public boolean hasErrorFetchingDeviceList(List<Jid> jids) {
 108		for(Jid jid : jids) {
 109			if (hasErrorFetchingDeviceList(jid)) {
 110				return true;
 111			}
 112		}
 113		return false;
 114	}
 115
 116	public boolean fetchMapHasErrors(List<Jid> jids) {
 117		for (Jid jid : jids) {
 118			if (deviceIds.get(jid) != null) {
 119				for (Integer foreignId : this.deviceIds.get(jid)) {
 120					SignalProtocolAddress address = new SignalProtocolAddress(jid.toString(), foreignId);
 121					if (fetchStatusMap.getAll(address.getName()).containsValue(FetchStatus.ERROR)) {
 122						return true;
 123					}
 124				}
 125			}
 126		}
 127		return false;
 128	}
 129
 130	public void preVerifyFingerprint(Contact contact, String fingerprint) {
 131		axolotlStore.preVerifyFingerprint(contact.getAccount(), contact.getJid().asBareJid().toString(), fingerprint);
 132	}
 133
 134	public void preVerifyFingerprint(Account account, String fingerprint) {
 135		axolotlStore.preVerifyFingerprint(account, account.getJid().asBareJid().toString(), fingerprint);
 136	}
 137
 138	public boolean hasVerifiedKeys(String name) {
 139		for (XmppAxolotlSession session : this.sessions.getAll(name).values()) {
 140			if (session.getTrust().isVerified()) {
 141				return true;
 142			}
 143		}
 144		return false;
 145	}
 146
 147	private static class AxolotlAddressMap<T> {
 148		protected Map<String, Map<Integer, T>> map;
 149		protected final Object MAP_LOCK = new Object();
 150
 151		public AxolotlAddressMap() {
 152			this.map = new HashMap<>();
 153		}
 154
 155		public void put(SignalProtocolAddress address, T value) {
 156			synchronized (MAP_LOCK) {
 157				Map<Integer, T> devices = map.get(address.getName());
 158				if (devices == null) {
 159					devices = new HashMap<>();
 160					map.put(address.getName(), devices);
 161				}
 162				devices.put(address.getDeviceId(), value);
 163			}
 164		}
 165
 166		public T get(SignalProtocolAddress address) {
 167			synchronized (MAP_LOCK) {
 168				Map<Integer, T> devices = map.get(address.getName());
 169				if (devices == null) {
 170					return null;
 171				}
 172				return devices.get(address.getDeviceId());
 173			}
 174		}
 175
 176		public Map<Integer, T> getAll(String name) {
 177			synchronized (MAP_LOCK) {
 178				Map<Integer, T> devices = map.get(name);
 179				if (devices == null) {
 180					return new HashMap<>();
 181				}
 182				return devices;
 183			}
 184		}
 185
 186		public boolean hasAny(SignalProtocolAddress address) {
 187			synchronized (MAP_LOCK) {
 188				Map<Integer, T> devices = map.get(address.getName());
 189				return devices != null && !devices.isEmpty();
 190			}
 191		}
 192
 193		public void clear() {
 194			map.clear();
 195		}
 196
 197	}
 198
 199	private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
 200		private final XmppConnectionService xmppConnectionService;
 201		private final Account account;
 202
 203		public SessionMap(XmppConnectionService service, SQLiteAxolotlStore store, Account account) {
 204			super();
 205			this.xmppConnectionService = service;
 206			this.account = account;
 207			this.fillMap(store);
 208		}
 209
 210		public Set<Jid> findCounterpartsForSourceId(Integer sid) {
 211			Set<Jid> candidates = new HashSet<>();
 212			synchronized (MAP_LOCK) {
 213				for(Map.Entry<String,Map<Integer,XmppAxolotlSession>> entry : map.entrySet()) {
 214					String key = entry.getKey();
 215					if (entry.getValue().containsKey(sid)) {
 216						candidates.add(Jid.of(key));
 217					}
 218				}
 219			}
 220			return candidates;
 221		}
 222
 223		private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
 224			for (Integer deviceId : deviceIds) {
 225				SignalProtocolAddress axolotlAddress = new SignalProtocolAddress(bareJid, deviceId);
 226				IdentityKey identityKey = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey();
 227				if (Config.X509_VERIFICATION) {
 228					X509Certificate certificate = store.getFingerprintCertificate(CryptoHelper.bytesToHex(identityKey.getPublicKey().serialize()));
 229					if (certificate != null) {
 230						Bundle information = CryptoHelper.extractCertificateInformation(certificate);
 231						try {
 232							final String cn = information.getString("subject_cn");
 233							final Jid jid = Jid.of(bareJid);
 234							Log.d(Config.LOGTAG, "setting common name for " + jid + " to " + cn);
 235							account.getRoster().getContact(jid).setCommonName(cn);
 236						} catch (final IllegalArgumentException ignored) {
 237							//ignored
 238						}
 239					}
 240				}
 241				this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, identityKey));
 242			}
 243		}
 244
 245		private void fillMap(SQLiteAxolotlStore store) {
 246			List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().asBareJid().toString());
 247			putDevicesForJid(account.getJid().asBareJid().toString(), deviceIds, store);
 248			for (String address : store.getKnownAddresses()) {
 249				deviceIds = store.getSubDeviceSessions(address);
 250				putDevicesForJid(address, deviceIds, store);
 251			}
 252		}
 253
 254		@Override
 255		public void put(SignalProtocolAddress address, XmppAxolotlSession value) {
 256			super.put(address, value);
 257			value.setNotFresh();
 258		}
 259
 260		public void put(XmppAxolotlSession session) {
 261			this.put(session.getRemoteAddress(), session);
 262		}
 263	}
 264
 265	public enum FetchStatus {
 266		PENDING,
 267		SUCCESS,
 268		SUCCESS_VERIFIED,
 269		TIMEOUT,
 270		SUCCESS_TRUSTED,
 271		ERROR
 272	}
 273
 274	private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
 275
 276		public void clearErrorFor(Jid jid) {
 277			synchronized (MAP_LOCK) {
 278				Map<Integer, FetchStatus> devices = this.map.get(jid.asBareJid().toString());
 279				if (devices == null) {
 280					return;
 281				}
 282				for (Map.Entry<Integer, FetchStatus> entry : devices.entrySet()) {
 283					if (entry.getValue() == FetchStatus.ERROR) {
 284						Log.d(Config.LOGTAG, "resetting error for " + jid.asBareJid() + "(" + entry.getKey() + ")");
 285						entry.setValue(FetchStatus.TIMEOUT);
 286					}
 287				}
 288			}
 289		}
 290	}
 291
 292	public static String getLogprefix(Account account) {
 293		return LOGPREFIX + " (" + account.getJid().asBareJid().toString() + "): ";
 294	}
 295
 296	public AxolotlService(Account account, XmppConnectionService connectionService) {
 297		if (account == null || connectionService == null) {
 298			throw new IllegalArgumentException("account and service cannot be null");
 299		}
 300		if (Security.getProvider("BC") == null) {
 301			Security.addProvider(new BouncyCastleProvider());
 302		}
 303		this.mXmppConnectionService = connectionService;
 304		this.account = account;
 305		this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
 306		this.deviceIds = new HashMap<>();
 307		this.messageCache = new HashMap<>();
 308		this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
 309		this.fetchStatusMap = new FetchStatusMap();
 310		this.executor = new SerialSingleThreadExecutor("Axolotl");
 311	}
 312
 313	public String getOwnFingerprint() {
 314		return CryptoHelper.bytesToHex(axolotlStore.getIdentityKeyPair().getPublicKey().serialize());
 315	}
 316
 317	public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status) {
 318		return axolotlStore.getContactKeysWithTrust(account.getJid().asBareJid().toString(), status);
 319	}
 320
 321	public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, Jid jid) {
 322		return axolotlStore.getContactKeysWithTrust(jid.asBareJid().toString(), status);
 323	}
 324
 325	public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, List<Jid> jids) {
 326		Set<IdentityKey> keys = new HashSet<>();
 327		for (Jid jid : jids) {
 328			keys.addAll(axolotlStore.getContactKeysWithTrust(jid.toString(), status));
 329		}
 330		return keys;
 331	}
 332
 333	public Set<Jid> findCounterpartsBySourceId(int sid) {
 334		return sessions.findCounterpartsForSourceId(sid);
 335	}
 336
 337	public long getNumTrustedKeys(Jid jid) {
 338		return axolotlStore.getContactNumTrustedKeys(jid.asBareJid().toString());
 339	}
 340
 341	public boolean anyTargetHasNoTrustedKeys(List<Jid> jids) {
 342		for (Jid jid : jids) {
 343			if (axolotlStore.getContactNumTrustedKeys(jid.asBareJid().toString()) == 0) {
 344				return true;
 345			}
 346		}
 347		return false;
 348	}
 349
 350	private SignalProtocolAddress getAddressForJid(Jid jid) {
 351		return new SignalProtocolAddress(jid.toString(), 0);
 352	}
 353
 354	public Collection<XmppAxolotlSession> findOwnSessions() {
 355		SignalProtocolAddress ownAddress = getAddressForJid(account.getJid().asBareJid());
 356		ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(ownAddress.getName()).values());
 357		Collections.sort(s);
 358		return s;
 359	}
 360
 361
 362	public Collection<XmppAxolotlSession> findSessionsForContact(Contact contact) {
 363		SignalProtocolAddress contactAddress = getAddressForJid(contact.getJid());
 364		ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(contactAddress.getName()).values());
 365		Collections.sort(s);
 366		return s;
 367	}
 368
 369	private Set<XmppAxolotlSession> findSessionsForConversation(Conversation conversation) {
 370		if (conversation.getContact().isSelf()) {
 371			//will be added in findOwnSessions()
 372			return Collections.emptySet();
 373		}
 374		HashSet<XmppAxolotlSession> sessions = new HashSet<>();
 375		for (Jid jid : conversation.getAcceptedCryptoTargets()) {
 376			sessions.addAll(this.sessions.getAll(getAddressForJid(jid).getName()).values());
 377		}
 378		return sessions;
 379	}
 380
 381	private boolean hasAny(Jid jid) {
 382		return sessions.hasAny(getAddressForJid(jid));
 383	}
 384
 385	public boolean isPepBroken() {
 386		return this.pepBroken;
 387	}
 388
 389	public void resetBrokenness() {
 390		this.pepBroken = false;
 391		this.numPublishTriesOnEmptyPep = 0;
 392		this.lastDeviceListNotificationHash = 0;
 393	}
 394
 395	public void clearErrorsInFetchStatusMap(Jid jid) {
 396		fetchStatusMap.clearErrorFor(jid);
 397		fetchDeviceListStatus.remove(jid);
 398	}
 399
 400	public void regenerateKeys(boolean wipeOther) {
 401		axolotlStore.regenerate();
 402		sessions.clear();
 403		fetchStatusMap.clear();
 404		fetchDeviceIdsMap.clear();
 405		fetchDeviceListStatus.clear();
 406		publishBundlesIfNeeded(true, wipeOther);
 407	}
 408
 409	public void destroy() {
 410		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": destroying old axolotl service. no longer in use");
 411		mXmppConnectionService.databaseBackend.wipeAxolotlDb(account);
 412	}
 413
 414	public AxolotlService makeNew() {
 415		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": make new axolotl service");
 416		return new AxolotlService(this.account, this.mXmppConnectionService);
 417	}
 418
 419	public int getOwnDeviceId() {
 420		return axolotlStore.getLocalRegistrationId();
 421	}
 422
 423	public SignalProtocolAddress getOwnAxolotlAddress() {
 424		return new SignalProtocolAddress(account.getJid().asBareJid().toString(), getOwnDeviceId());
 425	}
 426
 427	public Set<Integer> getOwnDeviceIds() {
 428		return this.deviceIds.get(account.getJid().asBareJid());
 429	}
 430
 431	public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
 432		final int hash = deviceIds.hashCode();
 433		final boolean me = jid.asBareJid().equals(account.getJid().asBareJid());
 434		if (me) {
 435			if (hash != 0 && hash == this.lastDeviceListNotificationHash) {
 436				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": ignoring duplicate own device id list");
 437				return;
 438			}
 439			this.lastDeviceListNotificationHash = hash;
 440		}
 441		boolean needsPublishing = me && !deviceIds.contains(getOwnDeviceId());
 442		if (me) {
 443			deviceIds.remove(getOwnDeviceId());
 444		}
 445		Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.asBareJid().toString()));
 446		expiredDevices.removeAll(deviceIds);
 447		for (Integer deviceId : expiredDevices) {
 448			SignalProtocolAddress address = new SignalProtocolAddress(jid.asBareJid().toString(), deviceId);
 449			XmppAxolotlSession session = sessions.get(address);
 450			if (session != null && session.getFingerprint() != null) {
 451				if (session.getTrust().isActive()) {
 452					session.setTrust(session.getTrust().toInactive());
 453				}
 454			}
 455		}
 456		Set<Integer> newDevices = new HashSet<>(deviceIds);
 457		for (Integer deviceId : newDevices) {
 458			SignalProtocolAddress address = new SignalProtocolAddress(jid.asBareJid().toString(), deviceId);
 459			XmppAxolotlSession session = sessions.get(address);
 460			if (session != null && session.getFingerprint() != null) {
 461				if (!session.getTrust().isActive()) {
 462					Log.d(Config.LOGTAG, "reactivating device with fingerprint " + session.getFingerprint());
 463					session.setTrust(session.getTrust().toActive());
 464				}
 465			}
 466		}
 467		if (me) {
 468			if (Config.OMEMO_AUTO_EXPIRY != 0) {
 469				needsPublishing |= deviceIds.removeAll(getExpiredDevices());
 470			}
 471			needsPublishing |= this.changeAccessMode.get();
 472			for (Integer deviceId : deviceIds) {
 473				SignalProtocolAddress ownDeviceAddress = new SignalProtocolAddress(jid.asBareJid().toString(), deviceId);
 474				if (sessions.get(ownDeviceAddress) == null) {
 475					FetchStatus status = fetchStatusMap.get(ownDeviceAddress);
 476					if (status == null || status == FetchStatus.TIMEOUT) {
 477						fetchStatusMap.put(ownDeviceAddress, FetchStatus.PENDING);
 478						this.buildSessionFromPEP(ownDeviceAddress);
 479					}
 480				}
 481			}
 482			if (needsPublishing) {
 483				publishOwnDeviceId(deviceIds);
 484			}
 485		}
 486		this.deviceIds.put(jid, deviceIds);
 487		mXmppConnectionService.updateConversationUi(); //update the lock icon
 488		mXmppConnectionService.keyStatusUpdated(null);
 489	}
 490
 491	public void wipeOtherPepDevices() {
 492		if (pepBroken) {
 493			Log.d(Config.LOGTAG, getLogprefix(account) + "wipeOtherPepDevices called, but PEP is broken. Ignoring... ");
 494			return;
 495		}
 496		Set<Integer> deviceIds = new HashSet<>();
 497		deviceIds.add(getOwnDeviceId());
 498		publishDeviceIdsAndRefineAccessModel(deviceIds);
 499	}
 500
 501	public void distrustFingerprint(final String fingerprint) {
 502		final String fp = fingerprint.replaceAll("\\s", "");
 503		final FingerprintStatus fingerprintStatus = axolotlStore.getFingerprintStatus(fp);
 504		axolotlStore.setFingerprintStatus(fp, fingerprintStatus.toUntrusted());
 505	}
 506
 507	private void publishOwnDeviceIdIfNeeded() {
 508		if (pepBroken) {
 509			Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
 510			return;
 511		}
 512		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().asBareJid());
 513		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 514			@Override
 515			public void onIqPacketReceived(Account account, IqPacket packet) {
 516				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 517					Log.d(Config.LOGTAG, getLogprefix(account) + "Timeout received while retrieving own Device Ids.");
 518				} else {
 519					Element item = mXmppConnectionService.getIqParser().getItem(packet);
 520					Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
 521					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": retrieved own device list: " + deviceIds);
 522					registerDevices(account.getJid().asBareJid(), deviceIds);
 523				}
 524			}
 525		});
 526	}
 527
 528	private Set<Integer> getExpiredDevices() {
 529		Set<Integer> devices = new HashSet<>();
 530		for (XmppAxolotlSession session : findOwnSessions()) {
 531			if (session.getTrust().isActive()) {
 532				long diff = System.currentTimeMillis() - session.getTrust().getLastActivation();
 533				if (diff > Config.OMEMO_AUTO_EXPIRY) {
 534					long lastMessageDiff = System.currentTimeMillis() - mXmppConnectionService.databaseBackend.getLastTimeFingerprintUsed(account, session.getFingerprint());
 535					long hours = Math.round(lastMessageDiff / (1000 * 60.0 * 60.0));
 536					if (lastMessageDiff > Config.OMEMO_AUTO_EXPIRY) {
 537						devices.add(session.getRemoteAddress().getDeviceId());
 538						session.setTrust(session.getTrust().toInactive());
 539						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": added own device " + session.getFingerprint() + " to list of expired devices. Last message received " + hours + " hours ago");
 540					} else {
 541						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": own device " + session.getFingerprint() + " was active " + hours + " hours ago");
 542					}
 543				}
 544			}
 545		}
 546		return devices;
 547	}
 548
 549	private void publishOwnDeviceId(Set<Integer> deviceIds) {
 550		Set<Integer> deviceIdsCopy = new HashSet<>(deviceIds);
 551		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "publishing own device ids");
 552		if (deviceIdsCopy.isEmpty()) {
 553			if (numPublishTriesOnEmptyPep >= publishTriesThreshold) {
 554				Log.w(Config.LOGTAG, getLogprefix(account) + "Own device publish attempt threshold exceeded, aborting...");
 555				pepBroken = true;
 556				return;
 557			} else {
 558				numPublishTriesOnEmptyPep++;
 559				Log.w(Config.LOGTAG, getLogprefix(account) + "Own device list empty, attempting to publish (try " + numPublishTriesOnEmptyPep + ")");
 560			}
 561		} else {
 562			numPublishTriesOnEmptyPep = 0;
 563		}
 564		deviceIdsCopy.add(getOwnDeviceId());
 565		publishDeviceIdsAndRefineAccessModel(deviceIdsCopy);
 566	}
 567
 568	private void publishDeviceIdsAndRefineAccessModel(Set<Integer> ids) {
 569		publishDeviceIdsAndRefineAccessModel(ids, true);
 570	}
 571
 572	private void publishDeviceIdsAndRefineAccessModel(final Set<Integer> ids, final boolean firstAttempt) {
 573		final Bundle publishOptions = account.getXmppConnection().getFeatures().pepPublishOptions() ? PublishOptions.openAccess() : null;
 574		IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(ids, publishOptions);
 575		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 576			@Override
 577			public void onIqPacketReceived(Account account, IqPacket packet) {
 578				final Element error = packet.getType() == IqPacket.TYPE.ERROR ? packet.findChild("error") : null;
 579				final boolean preConditionNotMet = error != null && error.hasChild("precondition-not-met", Namespace.PUBSUB_ERROR);
 580				if (firstAttempt && preConditionNotMet) {
 581					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": precondition wasn't met for device list. pushing node configuration");
 582					mXmppConnectionService.pushNodeConfiguration(account, AxolotlService.PEP_DEVICE_LIST, publishOptions, new XmppConnectionService.OnConfigurationPushed() {
 583						@Override
 584						public void onPushSucceeded() {
 585							publishDeviceIdsAndRefineAccessModel(ids, false);
 586						}
 587
 588						@Override
 589						public void onPushFailed() {
 590							publishDeviceIdsAndRefineAccessModel(ids, false);
 591						}
 592					});
 593				} else {
 594					if (AxolotlService.this.changeAccessMode.compareAndSet(true, false)) {
 595						Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": done changing access mode");
 596						account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, false);
 597						mXmppConnectionService.databaseBackend.updateAccount(account);
 598					}
 599					if (packet.getType() == IqPacket.TYPE.ERROR) {
 600						if (preConditionNotMet) {
 601							Log.d(Config.LOGTAG,account.getJid().asBareJid()+": device list pre condition still not met on second attempt");
 602						} else if (error != null) {
 603							pepBroken = true;
 604							Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing own device id" + packet.findChild("error"));
 605						}
 606
 607					}
 608				}
 609			}
 610		});
 611	}
 612
 613	public void publishDeviceVerificationAndBundle(final SignedPreKeyRecord signedPreKeyRecord,
 614	                                               final Set<PreKeyRecord> preKeyRecords,
 615	                                               final boolean announceAfter,
 616	                                               final boolean wipe) {
 617		try {
 618			IdentityKey axolotlPublicKey = axolotlStore.getIdentityKeyPair().getPublicKey();
 619			PrivateKey x509PrivateKey = KeyChain.getPrivateKey(mXmppConnectionService, account.getPrivateKeyAlias());
 620			X509Certificate[] chain = KeyChain.getCertificateChain(mXmppConnectionService, account.getPrivateKeyAlias());
 621			Signature verifier = Signature.getInstance("sha256WithRSA");
 622			verifier.initSign(x509PrivateKey, mXmppConnectionService.getRNG());
 623			verifier.update(axolotlPublicKey.serialize());
 624			byte[] signature = verifier.sign();
 625			IqPacket packet = mXmppConnectionService.getIqGenerator().publishVerification(signature, chain, getOwnDeviceId());
 626			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": publish verification for device " + getOwnDeviceId());
 627			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 628				@Override
 629				public void onIqPacketReceived(final Account account, IqPacket packet) {
 630					String node = AxolotlService.PEP_VERIFICATION + ":" + getOwnDeviceId();
 631					mXmppConnectionService.pushNodeConfiguration(account, node, PublishOptions.openAccess(), new XmppConnectionService.OnConfigurationPushed() {
 632						@Override
 633						public void onPushSucceeded() {
 634							Log.d(Config.LOGTAG, getLogprefix(account) + "configured verification node to be world readable");
 635							publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe);
 636						}
 637
 638						@Override
 639						public void onPushFailed() {
 640							Log.d(Config.LOGTAG, getLogprefix(account) + "unable to set access model on verification node");
 641							publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe);
 642						}
 643					});
 644				}
 645			});
 646		} catch (Exception e) {
 647			e.printStackTrace();
 648		}
 649	}
 650
 651	public void publishBundlesIfNeeded(final boolean announce, final boolean wipe) {
 652		if (pepBroken) {
 653			Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
 654			return;
 655		}
 656
 657		if (account.getXmppConnection().getFeatures().pepPublishOptions()) {
 658			this.changeAccessMode.set(account.isOptionSet(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE));
 659		} else {
 660			if (account.setOption(Account.OPTION_REQUIRES_ACCESS_MODE_CHANGE, true)) {
 661				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server doesn’t support publish-options. setting for later access mode change");
 662				mXmppConnectionService.databaseBackend.updateAccount(account);
 663			}
 664		}
 665		if (this.changeAccessMode.get()) {
 666			Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": server gained publish-options capabilities. changing access model");
 667		}
 668		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().asBareJid(), getOwnDeviceId());
 669		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 670			@Override
 671			public void onIqPacketReceived(Account account, IqPacket packet) {
 672
 673				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
 674					return; //ignore timeout. do nothing
 675				}
 676
 677				if (packet.getType() == IqPacket.TYPE.ERROR) {
 678					Element error = packet.findChild("error");
 679					if (error == null || !error.hasChild("item-not-found")) {
 680						pepBroken = true;
 681						Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "request for device bundles came back with something other than item-not-found" + packet);
 682						return;
 683					}
 684				}
 685
 686				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
 687				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
 688				boolean flush = false;
 689				if (bundle == null) {
 690					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
 691					bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
 692					flush = true;
 693				}
 694				if (keys == null) {
 695					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
 696				}
 697				try {
 698					boolean changed = false;
 699					// Validate IdentityKey
 700					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
 701					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
 702						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
 703						changed = true;
 704					}
 705
 706					// Validate signedPreKeyRecord + ID
 707					SignedPreKeyRecord signedPreKeyRecord;
 708					int numSignedPreKeys = axolotlStore.getSignedPreKeysCount();
 709					try {
 710						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
 711						if (flush
 712								|| !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
 713								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
 714							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 715							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 716							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 717							changed = true;
 718						}
 719					} catch (InvalidKeyIdException e) {
 720						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
 721						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
 722						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
 723						changed = true;
 724					}
 725
 726					// Validate PreKeys
 727					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
 728					if (keys != null) {
 729						for (Integer id : keys.keySet()) {
 730							try {
 731								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
 732								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
 733									preKeyRecords.add(preKeyRecord);
 734								}
 735							} catch (InvalidKeyIdException ignored) {
 736							}
 737						}
 738					}
 739					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
 740					if (newKeys > 0) {
 741						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
 742								axolotlStore.getCurrentPreKeyId() + 1, newKeys);
 743						preKeyRecords.addAll(newRecords);
 744						for (PreKeyRecord record : newRecords) {
 745							axolotlStore.storePreKey(record.getId(), record);
 746						}
 747						changed = true;
 748						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
 749					}
 750
 751
 752					if (changed || changeAccessMode.get()) {
 753						if (account.getPrivateKeyAlias() != null && Config.X509_VERIFICATION) {
 754							mXmppConnectionService.publishDisplayName(account);
 755							publishDeviceVerificationAndBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
 756						} else {
 757							publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
 758						}
 759					} else {
 760						Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
 761						if (wipe) {
 762							wipeOtherPepDevices();
 763						} else if (announce) {
 764							Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
 765							publishOwnDeviceIdIfNeeded();
 766						}
 767					}
 768				} catch (InvalidKeyException e) {
 769					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
 770				}
 771			}
 772		});
 773	}
 774
 775	private void publishDeviceBundle(SignedPreKeyRecord signedPreKeyRecord,
 776	                                 Set<PreKeyRecord> preKeyRecords,
 777	                                 final boolean announceAfter,
 778	                                 final boolean wipe) {
 779		publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe, true);
 780	}
 781
 782	private void publishDeviceBundle(final SignedPreKeyRecord signedPreKeyRecord,
 783	                                 final Set<PreKeyRecord> preKeyRecords,
 784	                                 final boolean announceAfter,
 785	                                 final boolean wipe,
 786	                                 final boolean firstAttempt) {
 787		final Bundle publishOptions = account.getXmppConnection().getFeatures().pepPublishOptions() ? PublishOptions.openAccess() : null;
 788		IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
 789				signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
 790				preKeyRecords, getOwnDeviceId(), publishOptions);
 791		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing...");
 792		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
 793			@Override
 794			public void onIqPacketReceived(final Account account, IqPacket packet) {
 795				final Element error = packet.getType() == IqPacket.TYPE.ERROR ? packet.findChild("error") : null;
 796				final boolean preconditionNotMet = error != null && error.hasChild("precondition-not-met", Namespace.PUBSUB_ERROR);
 797				if (firstAttempt && preconditionNotMet) {
 798					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": precondition wasn't met for bundle. pushing node configuration");
 799					final String node = AxolotlService.PEP_BUNDLES + ":" + getOwnDeviceId();
 800					mXmppConnectionService.pushNodeConfiguration(account, node, publishOptions, new XmppConnectionService.OnConfigurationPushed() {
 801						@Override
 802						public void onPushSucceeded() {
 803							publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe, false);
 804						}
 805
 806						@Override
 807						public void onPushFailed() {
 808							publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe, false);
 809						}
 810					});
 811				} else if (packet.getType() == IqPacket.TYPE.RESULT) {
 812					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
 813					if (wipe) {
 814						wipeOtherPepDevices();
 815					} else if (announceAfter) {
 816						Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
 817						publishOwnDeviceIdIfNeeded();
 818					}
 819				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
 820					if (preconditionNotMet) {
 821						Log.d(Config.LOGTAG,getLogprefix(account) + "bundle precondition still not met after second attempt");
 822					} else {
 823						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + error);
 824					}
 825					pepBroken = true;
 826				}
 827			}
 828		});
 829	}
 830
 831	public enum AxolotlCapability {
 832		FULL,
 833		MISSING_PRESENCE,
 834		MISSING_KEYS,
 835		WRONG_CONFIGURATION,
 836		NO_MEMBERS
 837	}
 838
 839	public boolean isConversationAxolotlCapable(Conversation conversation) {
 840		return conversation.isSingleOrPrivateAndNonAnonymous();
 841	}
 842
 843	public Pair<AxolotlCapability, Jid> isConversationAxolotlCapableDetailed(Conversation conversation) {
 844		if (conversation.isSingleOrPrivateAndNonAnonymous()) {
 845			final List<Jid> jids = getCryptoTargets(conversation);
 846			for (Jid jid : jids) {
 847				if (!hasAny(jid) && (!deviceIds.containsKey(jid) || deviceIds.get(jid).isEmpty())) {
 848					if (conversation.getAccount().getRoster().getContact(jid).mutualPresenceSubscription()) {
 849						return new Pair<>(AxolotlCapability.MISSING_KEYS, jid);
 850					} else {
 851						return new Pair<>(AxolotlCapability.MISSING_PRESENCE, jid);
 852					}
 853				}
 854			}
 855			if (jids.size() > 0) {
 856				return new Pair<>(AxolotlCapability.FULL, null);
 857			} else {
 858				return new Pair<>(AxolotlCapability.NO_MEMBERS, null);
 859			}
 860		} else {
 861			return new Pair<>(AxolotlCapability.WRONG_CONFIGURATION, null);
 862		}
 863	}
 864
 865	public List<Jid> getCryptoTargets(Conversation conversation) {
 866		final List<Jid> jids;
 867		if (conversation.getMode() == Conversation.MODE_SINGLE) {
 868			jids = new ArrayList<>();
 869			jids.add(conversation.getJid().asBareJid());
 870		} else {
 871			jids = conversation.getMucOptions().getMembers();
 872		}
 873		return jids;
 874	}
 875
 876	public FingerprintStatus getFingerprintTrust(String fingerprint) {
 877		return axolotlStore.getFingerprintStatus(fingerprint);
 878	}
 879
 880	public X509Certificate getFingerprintCertificate(String fingerprint) {
 881		return axolotlStore.getFingerprintCertificate(fingerprint);
 882	}
 883
 884	public void setFingerprintTrust(String fingerprint, FingerprintStatus status) {
 885		axolotlStore.setFingerprintStatus(fingerprint, status);
 886	}
 887
 888	private void verifySessionWithPEP(final XmppAxolotlSession session) {
 889		Log.d(Config.LOGTAG, "trying to verify fresh session (" + session.getRemoteAddress().getName() + ") with pep");
 890		final SignalProtocolAddress address = session.getRemoteAddress();
 891		final IdentityKey identityKey = session.getIdentityKey();
 892		try {
 893			IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.of(address.getName()), address.getDeviceId());
 894			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
 895				@Override
 896				public void onIqPacketReceived(Account account, IqPacket packet) {
 897					Pair<X509Certificate[], byte[]> verification = mXmppConnectionService.getIqParser().verification(packet);
 898					if (verification != null) {
 899						try {
 900							Signature verifier = Signature.getInstance("sha256WithRSA");
 901							verifier.initVerify(verification.first[0]);
 902							verifier.update(identityKey.serialize());
 903							if (verifier.verify(verification.second)) {
 904								try {
 905									mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA");
 906									String fingerprint = session.getFingerprint();
 907									Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: " + fingerprint);
 908									setFingerprintTrust(fingerprint, FingerprintStatus.createActiveVerified(true));
 909									axolotlStore.setFingerprintCertificate(fingerprint, verification.first[0]);
 910									fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED);
 911									Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]);
 912									try {
 913										final String cn = information.getString("subject_cn");
 914										final Jid jid = Jid.of(address.getName());
 915										Log.d(Config.LOGTAG, "setting common name for " + jid + " to " + cn);
 916										account.getRoster().getContact(jid).setCommonName(cn);
 917									} catch (final IllegalArgumentException ignored) {
 918										//ignored
 919									}
 920									finishBuildingSessionsFromPEP(address);
 921									return;
 922								} catch (Exception e) {
 923									Log.d(Config.LOGTAG, "could not verify certificate");
 924								}
 925							}
 926						} catch (Exception e) {
 927							Log.d(Config.LOGTAG, "error during verification " + e.getMessage());
 928						}
 929					} else {
 930						Log.d(Config.LOGTAG, "no verification found");
 931					}
 932					fetchStatusMap.put(address, FetchStatus.SUCCESS);
 933					finishBuildingSessionsFromPEP(address);
 934				}
 935			});
 936		} catch (IllegalArgumentException e) {
 937			fetchStatusMap.put(address, FetchStatus.SUCCESS);
 938			finishBuildingSessionsFromPEP(address);
 939		}
 940	}
 941
 942	private final Set<Integer> PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT = new HashSet<>();
 943
 944	private void finishBuildingSessionsFromPEP(final SignalProtocolAddress address) {
 945		SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), 0);
 946		Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress.getName());
 947		Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address.getName());
 948		if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) {
 949			FetchStatus report = null;
 950			if (own.containsValue(FetchStatus.SUCCESS) || remote.containsValue(FetchStatus.SUCCESS)) {
 951				report = FetchStatus.SUCCESS;
 952			} else if (own.containsValue(FetchStatus.SUCCESS_VERIFIED) || remote.containsValue(FetchStatus.SUCCESS_VERIFIED)) {
 953				report = FetchStatus.SUCCESS_VERIFIED;
 954			} else if (own.containsValue(FetchStatus.SUCCESS_TRUSTED) || remote.containsValue(FetchStatus.SUCCESS_TRUSTED)) {
 955				report = FetchStatus.SUCCESS_TRUSTED;
 956			} else if (own.containsValue(FetchStatus.ERROR) || remote.containsValue(FetchStatus.ERROR)) {
 957				report = FetchStatus.ERROR;
 958			}
 959			mXmppConnectionService.keyStatusUpdated(report);
 960		}
 961		if (Config.REMOVE_BROKEN_DEVICES) {
 962			Set<Integer> ownDeviceIds = new HashSet<>(getOwnDeviceIds());
 963			boolean publish = false;
 964			for (Map.Entry<Integer, FetchStatus> entry : own.entrySet()) {
 965				int id = entry.getKey();
 966				if (entry.getValue() == FetchStatus.ERROR && PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT.add(id) && ownDeviceIds.remove(id)) {
 967					publish = true;
 968					Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": error fetching own device with id " + id + ". removing from announcement");
 969				}
 970			}
 971			if (publish) {
 972				publishOwnDeviceId(ownDeviceIds);
 973			}
 974		}
 975	}
 976
 977	public boolean hasEmptyDeviceList(Jid jid) {
 978		return !hasAny(jid) && (!deviceIds.containsKey(jid) || deviceIds.get(jid).isEmpty());
 979	}
 980
 981	public interface OnDeviceIdsFetched {
 982		void fetched(Jid jid, Set<Integer> deviceIds);
 983	}
 984
 985	public interface OnMultipleDeviceIdFetched {
 986		void fetched();
 987	}
 988
 989	public void fetchDeviceIds(final Jid jid) {
 990		fetchDeviceIds(jid, null);
 991	}
 992
 993	private void fetchDeviceIds(final Jid jid, OnDeviceIdsFetched callback) {
 994		IqPacket packet;
 995		synchronized (this.fetchDeviceIdsMap) {
 996			List<OnDeviceIdsFetched> callbacks = this.fetchDeviceIdsMap.get(jid);
 997			if (callbacks != null) {
 998				if (callback != null) {
 999					callbacks.add(callback);
1000				}
1001				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching device ids for " + jid + " already running. adding callback");
1002				packet = null;
1003			} else {
1004				callbacks = new ArrayList<>();
1005				if (callback != null) {
1006					callbacks.add(callback);
1007				}
1008				this.fetchDeviceIdsMap.put(jid, callbacks);
1009				Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": fetching device ids for " + jid);
1010				packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(jid);
1011			}
1012		}
1013		if (packet != null) {
1014			mXmppConnectionService.sendIqPacket(account, packet, (account, response) -> {
1015				synchronized (fetchDeviceIdsMap) {
1016					List<OnDeviceIdsFetched> callbacks = fetchDeviceIdsMap.remove(jid);
1017					if (response.getType() == IqPacket.TYPE.RESULT) {
1018						fetchDeviceListStatus.put(jid, true);
1019						Element item = mXmppConnectionService.getIqParser().getItem(response);
1020						Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
1021						registerDevices(jid, deviceIds);
1022						if (callbacks != null) {
1023							for (OnDeviceIdsFetched c : callbacks) {
1024								c.fetched(jid, deviceIds);
1025							}
1026						}
1027					} else {
1028						if (response.getType() == IqPacket.TYPE.TIMEOUT) {
1029							fetchDeviceListStatus.remove(jid);
1030						} else {
1031							fetchDeviceListStatus.put(jid, false);
1032						}
1033						if (callbacks != null) {
1034							for (OnDeviceIdsFetched c : callbacks) {
1035								c.fetched(jid, null);
1036							}
1037						}
1038					}
1039				}
1040			});
1041		}
1042	}
1043
1044	private void fetchDeviceIds(List<Jid> jids, final OnMultipleDeviceIdFetched callback) {
1045		final ArrayList<Jid> unfinishedJids = new ArrayList<>(jids);
1046		synchronized (unfinishedJids) {
1047			for (Jid jid : unfinishedJids) {
1048				fetchDeviceIds(jid, (j, deviceIds) -> {
1049					synchronized (unfinishedJids) {
1050						unfinishedJids.remove(j);
1051						if (unfinishedJids.size() == 0 && callback != null) {
1052							callback.fetched();
1053						}
1054					}
1055				});
1056			}
1057		}
1058	}
1059
1060	private void buildSessionFromPEP(final SignalProtocolAddress address) {
1061		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new session for " + address.toString());
1062		if (address.equals(getOwnAxolotlAddress())) {
1063			throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
1064		}
1065
1066		final Jid jid = Jid.of(address.getName());
1067		final boolean oneOfOurs = jid.asBareJid().equals(account.getJid().asBareJid());
1068		IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(jid, address.getDeviceId());
1069		mXmppConnectionService.sendIqPacket(account, bundlesPacket, (account, packet) -> {
1070			if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
1071				fetchStatusMap.put(address, FetchStatus.TIMEOUT);
1072			} else if (packet.getType() == IqPacket.TYPE.RESULT) {
1073				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
1074				final IqParser parser = mXmppConnectionService.getIqParser();
1075				final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
1076				final PreKeyBundle bundle = parser.bundle(packet);
1077				if (preKeyBundleList.isEmpty() || bundle == null) {
1078					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
1079					fetchStatusMap.put(address, FetchStatus.ERROR);
1080					finishBuildingSessionsFromPEP(address);
1081					return;
1082				}
1083				Random random = new Random();
1084				final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
1085				if (preKey == null) {
1086					//should never happen
1087					fetchStatusMap.put(address, FetchStatus.ERROR);
1088					finishBuildingSessionsFromPEP(address);
1089					return;
1090				}
1091
1092				final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
1093						preKey.getPreKeyId(), preKey.getPreKey(),
1094						bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
1095						bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
1096
1097				try {
1098					SessionBuilder builder = new SessionBuilder(axolotlStore, address);
1099					builder.process(preKeyBundle);
1100					XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey());
1101					sessions.put(address, session);
1102					if (Config.X509_VERIFICATION) {
1103						verifySessionWithPEP(session);
1104					} else {
1105						FingerprintStatus status = getFingerprintTrust(CryptoHelper.bytesToHex(bundle.getIdentityKey().getPublicKey().serialize()));
1106						FetchStatus fetchStatus;
1107						if (status != null && status.isVerified()) {
1108							fetchStatus = FetchStatus.SUCCESS_VERIFIED;
1109						} else if (status != null && status.isTrusted()) {
1110							fetchStatus = FetchStatus.SUCCESS_TRUSTED;
1111						} else {
1112							fetchStatus = FetchStatus.SUCCESS;
1113						}
1114						fetchStatusMap.put(address, fetchStatus);
1115						finishBuildingSessionsFromPEP(address);
1116					}
1117				} catch (UntrustedIdentityException | InvalidKeyException e) {
1118					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
1119							+ e.getClass().getName() + ", " + e.getMessage());
1120					fetchStatusMap.put(address, FetchStatus.ERROR);
1121					finishBuildingSessionsFromPEP(address);
1122					if (oneOfOurs && cleanedOwnDeviceIds.add(address.getDeviceId())) {
1123						removeFromDeviceAnnouncement(address.getDeviceId());
1124					}
1125				}
1126			} else {
1127				fetchStatusMap.put(address, FetchStatus.ERROR);
1128				Element error = packet.findChild("error");
1129				boolean itemNotFound = error != null && error.hasChild("item-not-found");
1130				Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
1131				finishBuildingSessionsFromPEP(address);
1132				if (oneOfOurs && itemNotFound && cleanedOwnDeviceIds.add(address.getDeviceId())) {
1133					removeFromDeviceAnnouncement(address.getDeviceId());
1134				}
1135			}
1136		});
1137	}
1138
1139	private void removeFromDeviceAnnouncement(Integer id) {
1140		HashSet<Integer> temp = new HashSet<>(getOwnDeviceIds());
1141		if (temp.remove(id)) {
1142			Log.d(Config.LOGTAG,account.getJid().asBareJid()+" remove own device id "+id+" from announcement. devices left:"+temp);
1143			publishOwnDeviceId(temp);
1144		}
1145	}
1146
1147	public Set<SignalProtocolAddress> findDevicesWithoutSession(final Conversation conversation) {
1148		Set<SignalProtocolAddress> addresses = new HashSet<>();
1149		for (Jid jid : getCryptoTargets(conversation)) {
1150			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + jid);
1151			if (deviceIds.get(jid) != null) {
1152				for (Integer foreignId : this.deviceIds.get(jid)) {
1153					SignalProtocolAddress address = new SignalProtocolAddress(jid.toString(), foreignId);
1154					if (sessions.get(address) == null) {
1155						IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1156						if (identityKey != null) {
1157							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
1158							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
1159							sessions.put(address, session);
1160						} else {
1161							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + jid + ":" + foreignId);
1162							if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
1163								addresses.add(address);
1164							} else {
1165								Log.d(Config.LOGTAG, getLogprefix(account) + "skipping over " + address + " because it's broken");
1166							}
1167						}
1168					}
1169				}
1170			} else {
1171				mXmppConnectionService.keyStatusUpdated(FetchStatus.ERROR);
1172				Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
1173			}
1174		}
1175		if (deviceIds.get(account.getJid().asBareJid()) != null) {
1176			for (Integer ownId : this.deviceIds.get(account.getJid().asBareJid())) {
1177				SignalProtocolAddress address = new SignalProtocolAddress(account.getJid().asBareJid().toString(), ownId);
1178				if (sessions.get(address) == null) {
1179					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1180					if (identityKey != null) {
1181						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
1182						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
1183						sessions.put(address, session);
1184					} else {
1185						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().asBareJid() + ":" + ownId);
1186						if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
1187							addresses.add(address);
1188						} else {
1189							Log.d(Config.LOGTAG, getLogprefix(account) + "skipping over " + address + " because it's broken");
1190						}
1191					}
1192				}
1193			}
1194		}
1195
1196		return addresses;
1197	}
1198
1199	public boolean createSessionsIfNeeded(final Conversation conversation) {
1200		final List<Jid> jidsWithEmptyDeviceList = getCryptoTargets(conversation);
1201		for (Iterator<Jid> iterator = jidsWithEmptyDeviceList.iterator(); iterator.hasNext(); ) {
1202			final Jid jid = iterator.next();
1203			if (!hasEmptyDeviceList(jid)) {
1204				iterator.remove();
1205			}
1206		}
1207		Log.d(Config.LOGTAG, account.getJid().asBareJid() + ": createSessionsIfNeeded() - jids with empty device list: " + jidsWithEmptyDeviceList);
1208		if (jidsWithEmptyDeviceList.size() > 0) {
1209			fetchDeviceIds(jidsWithEmptyDeviceList, new OnMultipleDeviceIdFetched() {
1210				@Override
1211				public void fetched() {
1212					createSessionsIfNeededActual(conversation);
1213				}
1214			});
1215			return true;
1216		} else {
1217			return createSessionsIfNeededActual(conversation);
1218		}
1219	}
1220
1221	private boolean createSessionsIfNeededActual(final Conversation conversation) {
1222		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
1223		boolean newSessions = false;
1224		Set<SignalProtocolAddress> addresses = findDevicesWithoutSession(conversation);
1225		for (SignalProtocolAddress address : addresses) {
1226			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
1227			FetchStatus status = fetchStatusMap.get(address);
1228			if (status == null || status == FetchStatus.TIMEOUT) {
1229				fetchStatusMap.put(address, FetchStatus.PENDING);
1230				this.buildSessionFromPEP(address);
1231				newSessions = true;
1232			} else if (status == FetchStatus.PENDING) {
1233				newSessions = true;
1234			} else {
1235				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
1236			}
1237		}
1238
1239		return newSessions;
1240	}
1241
1242	public boolean trustedSessionVerified(final Conversation conversation) {
1243		final Set<XmppAxolotlSession> sessions = new HashSet<>();
1244		sessions.addAll(findSessionsForConversation(conversation));
1245		sessions.addAll(findOwnSessions());
1246		boolean verified = false;
1247		for (XmppAxolotlSession session : sessions) {
1248			if (session.getTrust().isTrustedAndActive()) {
1249				if (session.getTrust().getTrust() == FingerprintStatus.Trust.VERIFIED_X509) {
1250					verified = true;
1251				} else {
1252					return false;
1253				}
1254			}
1255		}
1256		return verified;
1257	}
1258
1259	public boolean hasPendingKeyFetches(Account account, List<Jid> jids) {
1260		SignalProtocolAddress ownAddress = new SignalProtocolAddress(account.getJid().asBareJid().toString(), 0);
1261		if (fetchStatusMap.getAll(ownAddress.getName()).containsValue(FetchStatus.PENDING)) {
1262			return true;
1263		}
1264		synchronized (this.fetchDeviceIdsMap) {
1265			for (Jid jid : jids) {
1266				SignalProtocolAddress foreignAddress = new SignalProtocolAddress(jid.asBareJid().toString(), 0);
1267				if (fetchStatusMap.getAll(foreignAddress.getName()).containsValue(FetchStatus.PENDING) || this.fetchDeviceIdsMap.containsKey(jid)) {
1268					return true;
1269				}
1270			}
1271		}
1272		return false;
1273	}
1274
1275	@Nullable
1276	private boolean buildHeader(XmppAxolotlMessage axolotlMessage, Conversation c) {
1277		Set<XmppAxolotlSession> remoteSessions = findSessionsForConversation(c);
1278		final boolean acceptEmpty = (c.getMode() == Conversation.MODE_MULTI && c.getMucOptions().getUserCount() == 0) || c.getContact().isSelf();
1279		Collection<XmppAxolotlSession> ownSessions = findOwnSessions();
1280		if (remoteSessions.isEmpty() && !acceptEmpty) {
1281			return false;
1282		}
1283		for (XmppAxolotlSession session : remoteSessions) {
1284			axolotlMessage.addDevice(session);
1285		}
1286		for (XmppAxolotlSession session : ownSessions) {
1287			axolotlMessage.addDevice(session);
1288		}
1289
1290		return true;
1291	}
1292
1293	//this is being used for private muc messages only
1294	private boolean buildHeader(XmppAxolotlMessage axolotlMessage, Jid jid) {
1295		if (jid == null) {
1296			return false;
1297		}
1298		HashSet<XmppAxolotlSession> sessions = new HashSet<>();
1299		sessions.addAll(this.sessions.getAll(getAddressForJid(jid).getName()).values());
1300		if (sessions.isEmpty()) {
1301			return false;
1302		}
1303		sessions.addAll(findOwnSessions());
1304		for(XmppAxolotlSession session : sessions) {
1305			axolotlMessage.addDevice(session);
1306		}
1307		return true;
1308	}
1309
1310	@Nullable
1311	public XmppAxolotlMessage encrypt(Message message) {
1312		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
1313		final String content;
1314		if (message.hasFileOnRemoteHost()) {
1315			content = message.getFileParams().url.toString();
1316		} else {
1317			content = message.getBody();
1318		}
1319		try {
1320			axolotlMessage.encrypt(content);
1321		} catch (CryptoFailedException e) {
1322			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
1323			return null;
1324		}
1325
1326		final boolean success;
1327		if (message.getType() == Message.TYPE_PRIVATE) {
1328			success = buildHeader(axolotlMessage, message.getTrueCounterpart());
1329		} else {
1330			success = buildHeader(axolotlMessage, (Conversation) message.getConversation());
1331		}
1332		return success ? axolotlMessage : null;
1333	}
1334
1335	public void preparePayloadMessage(final Message message, final boolean delay) {
1336		executor.execute(new Runnable() {
1337			@Override
1338			public void run() {
1339				XmppAxolotlMessage axolotlMessage = encrypt(message);
1340				if (axolotlMessage == null) {
1341					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
1342					//mXmppConnectionService.updateConversationUi();
1343				} else {
1344					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
1345					messageCache.put(message.getUuid(), axolotlMessage);
1346					mXmppConnectionService.resendMessage(message, delay);
1347				}
1348			}
1349		});
1350	}
1351
1352	public void prepareKeyTransportMessage(final Conversation conversation, final OnMessageCreatedCallback onMessageCreatedCallback) {
1353		executor.execute(new Runnable() {
1354			@Override
1355			public void run() {
1356				final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
1357				if (buildHeader(axolotlMessage, conversation)) {
1358					onMessageCreatedCallback.run(axolotlMessage);
1359				} else {
1360					onMessageCreatedCallback.run(null);
1361				}
1362			}
1363		});
1364	}
1365
1366	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
1367		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
1368		if (axolotlMessage != null) {
1369			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
1370			messageCache.remove(message.getUuid());
1371		} else {
1372			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
1373		}
1374		return axolotlMessage;
1375	}
1376
1377	private XmppAxolotlSession recreateUncachedSession(SignalProtocolAddress address) {
1378		IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
1379		return (identityKey != null)
1380				? new XmppAxolotlSession(account, axolotlStore, address, identityKey)
1381				: null;
1382	}
1383
1384	private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
1385		SignalProtocolAddress senderAddress = new SignalProtocolAddress(message.getFrom().toString(),
1386				message.getSenderDeviceId());
1387		XmppAxolotlSession session = sessions.get(senderAddress);
1388		if (session == null) {
1389			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
1390			session = recreateUncachedSession(senderAddress);
1391			if (session == null) {
1392				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
1393			}
1394		}
1395		return session;
1396	}
1397
1398	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message, boolean postponePreKeyMessageHandling) throws NotEncryptedForThisDeviceException {
1399		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
1400
1401		XmppAxolotlSession session = getReceivingSession(message);
1402		int ownDeviceId = getOwnDeviceId();
1403		try {
1404			plaintextMessage = message.decrypt(session, ownDeviceId);
1405			Integer preKeyId = session.getPreKeyIdAndReset();
1406			if (preKeyId != null) {
1407				postPreKeyMessageHandling(session, preKeyId, postponePreKeyMessageHandling);
1408			}
1409		} catch (NotEncryptedForThisDeviceException e) {
1410			if (account.getJid().asBareJid().equals(message.getFrom().asBareJid()) && message.getSenderDeviceId() == ownDeviceId) {
1411				Log.w(Config.LOGTAG, getLogprefix(account) + "Reflected omemo message received");
1412			} else {
1413				throw e;
1414			}
1415		} catch (CryptoFailedException e) {
1416			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message from " + message.getFrom() + ": " + e.getMessage());
1417		}
1418
1419		if (session.isFresh() && plaintextMessage != null) {
1420			putFreshSession(session);
1421		}
1422
1423		return plaintextMessage;
1424	}
1425
1426	private void postPreKeyMessageHandling(final XmppAxolotlSession session, int preKeyId, final boolean postpone) {
1427		if (postpone) {
1428			postponedSessions.add(session);
1429		} else {
1430			//TODO: do not republish if we already removed this preKeyId
1431			publishBundlesIfNeeded(false, false);
1432			completeSession(session);
1433		}
1434	}
1435
1436	public void processPostponed() {
1437		if (postponedSessions.size() > 0) {
1438			publishBundlesIfNeeded(false, false);
1439		}
1440		Iterator<XmppAxolotlSession> iterator = postponedSessions.iterator();
1441		while (iterator.hasNext()) {
1442			completeSession(iterator.next());
1443			iterator.remove();
1444		}
1445	}
1446
1447	private void completeSession(XmppAxolotlSession session) {
1448		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().asBareJid(), getOwnDeviceId());
1449		axolotlMessage.addDevice(session, true);
1450		try {
1451			Jid jid = Jid.of(session.getRemoteAddress().getName());
1452			MessagePacket packet = mXmppConnectionService.getMessageGenerator().generateKeyTransportMessage(jid, axolotlMessage);
1453			mXmppConnectionService.sendMessagePacket(account, packet);
1454		} catch (IllegalArgumentException e) {
1455			throw new Error("Remote addresses are created from jid and should convert back to jid", e);
1456		}
1457	}
1458
1459
1460	public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message, final boolean postponePreKeyMessageHandling) {
1461		XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage;
1462
1463		XmppAxolotlSession session = getReceivingSession(message);
1464		try {
1465			keyTransportMessage = message.getParameters(session, getOwnDeviceId());
1466			Integer preKeyId = session.getPreKeyIdAndReset();
1467			if (preKeyId != null) {
1468				postPreKeyMessageHandling(session, preKeyId, postponePreKeyMessageHandling);
1469			}
1470		} catch (CryptoFailedException e) {
1471			Log.d(Config.LOGTAG, "could not decrypt keyTransport message " + e.getMessage());
1472			keyTransportMessage = null;
1473		}
1474
1475		if (session.isFresh() && keyTransportMessage != null) {
1476			putFreshSession(session);
1477		}
1478
1479		return keyTransportMessage;
1480	}
1481
1482	private void putFreshSession(XmppAxolotlSession session) {
1483		Log.d(Config.LOGTAG, "put fresh session");
1484		sessions.put(session);
1485		if (Config.X509_VERIFICATION) {
1486			if (session.getIdentityKey() != null) {
1487				verifySessionWithPEP(session);
1488			} else {
1489				Log.e(Config.LOGTAG, account.getJid().asBareJid() + ": identity key was empty after reloading for x509 verification");
1490			}
1491		}
1492	}
1493}