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