AxolotlService.java

  1package eu.siacs.conversations.crypto.axolotl;
  2
  3import android.support.annotation.NonNull;
  4import android.support.annotation.Nullable;
  5import android.util.Log;
  6
  7import org.bouncycastle.jce.provider.BouncyCastleProvider;
  8import org.whispersystems.libaxolotl.AxolotlAddress;
  9import org.whispersystems.libaxolotl.IdentityKey;
 10import org.whispersystems.libaxolotl.IdentityKeyPair;
 11import org.whispersystems.libaxolotl.InvalidKeyException;
 12import org.whispersystems.libaxolotl.InvalidKeyIdException;
 13import org.whispersystems.libaxolotl.SessionBuilder;
 14import org.whispersystems.libaxolotl.UntrustedIdentityException;
 15import org.whispersystems.libaxolotl.ecc.ECPublicKey;
 16import org.whispersystems.libaxolotl.state.PreKeyBundle;
 17import org.whispersystems.libaxolotl.state.PreKeyRecord;
 18import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
 19import org.whispersystems.libaxolotl.util.KeyHelper;
 20
 21import java.security.Security;
 22import java.util.Arrays;
 23import java.util.HashMap;
 24import java.util.HashSet;
 25import java.util.List;
 26import java.util.Map;
 27import java.util.Random;
 28import java.util.Set;
 29
 30import eu.siacs.conversations.Config;
 31import eu.siacs.conversations.entities.Account;
 32import eu.siacs.conversations.entities.Contact;
 33import eu.siacs.conversations.entities.Conversation;
 34import eu.siacs.conversations.entities.Message;
 35import eu.siacs.conversations.parser.IqParser;
 36import eu.siacs.conversations.services.XmppConnectionService;
 37import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 38import eu.siacs.conversations.xml.Element;
 39import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 40import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 41import eu.siacs.conversations.xmpp.jid.Jid;
 42import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 43
 44public class AxolotlService {
 45
 46	public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl";
 47	public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist";
 48	public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
 49
 50	public static final String LOGPREFIX = "AxolotlService";
 51
 52	public static final int NUM_KEYS_TO_PUBLISH = 100;
 53	public static final int publishTriesThreshold = 3;
 54
 55	private final Account account;
 56	private final XmppConnectionService mXmppConnectionService;
 57	private final SQLiteAxolotlStore axolotlStore;
 58	private final SessionMap sessions;
 59	private final Map<Jid, Set<Integer>> deviceIds;
 60	private final Map<String, XmppAxolotlMessage> messageCache;
 61	private final FetchStatusMap fetchStatusMap;
 62	private final SerialSingleThreadExecutor executor;
 63	private int numPublishTriesOnEmptyPep = 0;
 64	private boolean pepBroken = false;
 65
 66	private static class AxolotlAddressMap<T> {
 67		protected Map<String, Map<Integer, T>> map;
 68		protected final Object MAP_LOCK = new Object();
 69
 70		public AxolotlAddressMap() {
 71			this.map = new HashMap<>();
 72		}
 73
 74		public void put(AxolotlAddress address, T value) {
 75			synchronized (MAP_LOCK) {
 76				Map<Integer, T> devices = map.get(address.getName());
 77				if (devices == null) {
 78					devices = new HashMap<>();
 79					map.put(address.getName(), devices);
 80				}
 81				devices.put(address.getDeviceId(), value);
 82			}
 83		}
 84
 85		public T get(AxolotlAddress address) {
 86			synchronized (MAP_LOCK) {
 87				Map<Integer, T> devices = map.get(address.getName());
 88				if (devices == null) {
 89					return null;
 90				}
 91				return devices.get(address.getDeviceId());
 92			}
 93		}
 94
 95		public Map<Integer, T> getAll(AxolotlAddress address) {
 96			synchronized (MAP_LOCK) {
 97				Map<Integer, T> devices = map.get(address.getName());
 98				if (devices == null) {
 99					return new HashMap<>();
100				}
101				return devices;
102			}
103		}
104
105		public boolean hasAny(AxolotlAddress address) {
106			synchronized (MAP_LOCK) {
107				Map<Integer, T> devices = map.get(address.getName());
108				return devices != null && !devices.isEmpty();
109			}
110		}
111
112		public void clear() {
113			map.clear();
114		}
115
116	}
117
118	private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
119		private final XmppConnectionService xmppConnectionService;
120		private final Account account;
121
122		public SessionMap(XmppConnectionService service, SQLiteAxolotlStore store, Account account) {
123			super();
124			this.xmppConnectionService = service;
125			this.account = account;
126			this.fillMap(store);
127		}
128
129		private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
130			for (Integer deviceId : deviceIds) {
131				AxolotlAddress axolotlAddress = new AxolotlAddress(bareJid, deviceId);
132				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building session for remote address: " + axolotlAddress.toString());
133				String fingerprint = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey().getFingerprint().replaceAll("\\s", "");
134				this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, fingerprint));
135			}
136		}
137
138		private void fillMap(SQLiteAxolotlStore store) {
139			List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().toBareJid().toString());
140			putDevicesForJid(account.getJid().toBareJid().toString(), deviceIds, store);
141			for (Contact contact : account.getRoster().getContacts()) {
142				Jid bareJid = contact.getJid().toBareJid();
143				if (bareJid == null) {
144					continue; // FIXME: handle this?
145				}
146				String address = bareJid.toString();
147				deviceIds = store.getSubDeviceSessions(address);
148				putDevicesForJid(address, deviceIds, store);
149			}
150
151		}
152
153		@Override
154		public void put(AxolotlAddress address, XmppAxolotlSession value) {
155			super.put(address, value);
156			value.setNotFresh();
157			xmppConnectionService.syncRosterToDisk(account);
158		}
159
160		public void put(XmppAxolotlSession session) {
161			this.put(session.getRemoteAddress(), session);
162		}
163	}
164
165	private static enum FetchStatus {
166		PENDING,
167		SUCCESS,
168		ERROR
169	}
170
171	private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
172
173	}
174
175	public static String getLogprefix(Account account) {
176		return LOGPREFIX + " (" + account.getJid().toBareJid().toString() + "): ";
177	}
178
179	public AxolotlService(Account account, XmppConnectionService connectionService) {
180		if (Security.getProvider("BC") == null) {
181			Security.addProvider(new BouncyCastleProvider());
182		}
183		this.mXmppConnectionService = connectionService;
184		this.account = account;
185		this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
186		this.deviceIds = new HashMap<>();
187		this.messageCache = new HashMap<>();
188		this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
189		this.fetchStatusMap = new FetchStatusMap();
190		this.executor = new SerialSingleThreadExecutor();
191	}
192
193	public IdentityKey getOwnPublicKey() {
194		return axolotlStore.getIdentityKeyPair().getPublicKey();
195	}
196
197	public Set<IdentityKey> getKeysWithTrust(XmppAxolotlSession.Trust trust) {
198		return axolotlStore.getContactKeysWithTrust(account.getJid().toBareJid().toString(), trust);
199	}
200
201	public Set<IdentityKey> getKeysWithTrust(XmppAxolotlSession.Trust trust, Contact contact) {
202		return axolotlStore.getContactKeysWithTrust(contact.getJid().toBareJid().toString(), trust);
203	}
204
205	public long getNumTrustedKeys(Contact contact) {
206		return axolotlStore.getContactNumTrustedKeys(contact.getJid().toBareJid().toString());
207	}
208
209	private AxolotlAddress getAddressForJid(Jid jid) {
210		return new AxolotlAddress(jid.toString(), 0);
211	}
212
213	private Set<XmppAxolotlSession> findOwnSessions() {
214		AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
215		Set<XmppAxolotlSession> ownDeviceSessions = new HashSet<>(this.sessions.getAll(ownAddress).values());
216		return ownDeviceSessions;
217	}
218
219	private Set<XmppAxolotlSession> findSessionsforContact(Contact contact) {
220		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
221		Set<XmppAxolotlSession> sessions = new HashSet<>(this.sessions.getAll(contactAddress).values());
222		return sessions;
223	}
224
225	private boolean hasAny(Contact contact) {
226		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
227		return sessions.hasAny(contactAddress);
228	}
229
230	public void regenerateKeys() {
231		axolotlStore.regenerate();
232		sessions.clear();
233		fetchStatusMap.clear();
234		publishBundlesIfNeeded();
235		publishOwnDeviceIdIfNeeded();
236	}
237
238	public int getOwnDeviceId() {
239		return axolotlStore.getLocalRegistrationId();
240	}
241
242	public Set<Integer> getOwnDeviceIds() {
243		return this.deviceIds.get(account.getJid().toBareJid());
244	}
245
246	private void setTrustOnSessions(final Jid jid, @NonNull final Set<Integer> deviceIds,
247	                                final XmppAxolotlSession.Trust from,
248	                                final XmppAxolotlSession.Trust to) {
249		for (Integer deviceId : deviceIds) {
250			AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toString(), deviceId);
251			XmppAxolotlSession session = sessions.get(address);
252			if (session != null && session.getFingerprint() != null
253					&& session.getTrust() == from) {
254				session.setTrust(to);
255			}
256		}
257	}
258
259	public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
260		if (jid.toBareJid().equals(account.getJid().toBareJid())) {
261			if (!deviceIds.isEmpty()) {
262				Log.d(Config.LOGTAG, getLogprefix(account) + "Received non-empty own device list. Resetting publish attemps and pepBroken status.");
263				pepBroken = false;
264				numPublishTriesOnEmptyPep = 0;
265			}
266			if (deviceIds.contains(getOwnDeviceId())) {
267				deviceIds.remove(getOwnDeviceId());
268			} else {
269				publishOwnDeviceId(deviceIds);
270			}
271			for (Integer deviceId : deviceIds) {
272				AxolotlAddress ownDeviceAddress = new AxolotlAddress(jid.toBareJid().toString(), deviceId);
273				if (sessions.get(ownDeviceAddress) == null) {
274					buildSessionFromPEP(ownDeviceAddress);
275				}
276			}
277		}
278		Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toString()));
279		expiredDevices.removeAll(deviceIds);
280		setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.TRUSTED,
281				XmppAxolotlSession.Trust.INACTIVE_TRUSTED);
282		setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.UNDECIDED,
283				XmppAxolotlSession.Trust.INACTIVE_UNDECIDED);
284		setTrustOnSessions(jid, expiredDevices, XmppAxolotlSession.Trust.UNTRUSTED,
285				XmppAxolotlSession.Trust.INACTIVE_UNTRUSTED);
286		Set<Integer> newDevices = new HashSet<>(deviceIds);
287		setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_TRUSTED,
288				XmppAxolotlSession.Trust.TRUSTED);
289		setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_UNDECIDED,
290				XmppAxolotlSession.Trust.UNDECIDED);
291		setTrustOnSessions(jid, newDevices, XmppAxolotlSession.Trust.INACTIVE_UNTRUSTED,
292				XmppAxolotlSession.Trust.UNTRUSTED);
293		this.deviceIds.put(jid, deviceIds);
294		mXmppConnectionService.keyStatusUpdated();
295	}
296
297	public void wipeOtherPepDevices() {
298		if (pepBroken) {
299			Log.d(Config.LOGTAG, getLogprefix(account) + "wipeOtherPepDevices called, but PEP is broken. Ignoring... ");
300			return;
301		}
302		Set<Integer> deviceIds = new HashSet<>();
303		deviceIds.add(getOwnDeviceId());
304		IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
305		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Wiping all other devices from Pep:" + publish);
306		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
307			@Override
308			public void onIqPacketReceived(Account account, IqPacket packet) {
309				// TODO: implement this!
310			}
311		});
312	}
313
314	public void purgeKey(IdentityKey identityKey) {
315		axolotlStore.setFingerprintTrust(identityKey.getFingerprint().replaceAll("\\s", ""), XmppAxolotlSession.Trust.COMPROMISED);
316	}
317
318	public void publishOwnDeviceIdIfNeeded() {
319		if (pepBroken) {
320			Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
321			return;
322		}
323		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
324		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
325			@Override
326			public void onIqPacketReceived(Account account, IqPacket packet) {
327				if (packet.getType() == IqPacket.TYPE.RESULT) {
328					Element item = mXmppConnectionService.getIqParser().getItem(packet);
329					Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
330					if (!deviceIds.contains(getOwnDeviceId())) {
331						publishOwnDeviceId(deviceIds);
332					}
333				} else {
334					Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while retrieving Device Ids" + packet.findChild("error"));
335				}
336			}
337		});
338	}
339
340	public void publishOwnDeviceId(Set<Integer> deviceIds) {
341		if (!deviceIds.contains(getOwnDeviceId())) {
342			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Own device " + getOwnDeviceId() + " not in PEP devicelist.");
343			if (deviceIds.isEmpty()) {
344				if (numPublishTriesOnEmptyPep >= publishTriesThreshold) {
345					Log.w(Config.LOGTAG, getLogprefix(account) + "Own device publish attempt threshold exceeded, aborting...");
346					pepBroken = true;
347					return;
348				} else {
349					numPublishTriesOnEmptyPep++;
350					Log.w(Config.LOGTAG, getLogprefix(account) + "Own device list empty, attempting to publish (try " + numPublishTriesOnEmptyPep + ")");
351				}
352			} else {
353				numPublishTriesOnEmptyPep = 0;
354			}
355			deviceIds.add(getOwnDeviceId());
356			IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
357			mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
358				@Override
359				public void onIqPacketReceived(Account account, IqPacket packet) {
360					if (packet.getType() != IqPacket.TYPE.RESULT) {
361						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing own device id" + packet.findChild("error"));
362					}
363				}
364			});
365		}
366	}
367
368	public void publishBundlesIfNeeded() {
369		if (pepBroken) {
370			Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
371			return;
372		}
373		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
374		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
375			@Override
376			public void onIqPacketReceived(Account account, IqPacket packet) {
377				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
378				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
379				boolean flush = false;
380				if (bundle == null) {
381					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
382					bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
383					flush = true;
384				}
385				if (keys == null) {
386					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
387				}
388				try {
389					boolean changed = false;
390					// Validate IdentityKey
391					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
392					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
393						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
394						changed = true;
395					}
396
397					// Validate signedPreKeyRecord + ID
398					SignedPreKeyRecord signedPreKeyRecord;
399					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
400					try {
401						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
402						if (flush
403								|| !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
404								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
405							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
406							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
407							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
408							changed = true;
409						}
410					} catch (InvalidKeyIdException e) {
411						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
412						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
413						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
414						changed = true;
415					}
416
417					// Validate PreKeys
418					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
419					if (keys != null) {
420						for (Integer id : keys.keySet()) {
421							try {
422								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
423								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
424									preKeyRecords.add(preKeyRecord);
425								}
426							} catch (InvalidKeyIdException ignored) {
427							}
428						}
429					}
430					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
431					if (newKeys > 0) {
432						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
433								axolotlStore.getCurrentPreKeyId() + 1, newKeys);
434						preKeyRecords.addAll(newRecords);
435						for (PreKeyRecord record : newRecords) {
436							axolotlStore.storePreKey(record.getId(), record);
437						}
438						changed = true;
439						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
440					}
441
442
443					if (changed) {
444						IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
445								signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
446								preKeyRecords, getOwnDeviceId());
447						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
448						mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
449							@Override
450							public void onIqPacketReceived(Account account, IqPacket packet) {
451								// TODO: implement this!
452								Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Published bundle, got: " + packet);
453							}
454						});
455					}
456				} catch (InvalidKeyException e) {
457					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
458					return;
459				}
460			}
461		});
462	}
463
464	public boolean isContactAxolotlCapable(Contact contact) {
465
466		Jid jid = contact.getJid().toBareJid();
467		AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
468		return sessions.hasAny(address) ||
469				(deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
470	}
471
472	public XmppAxolotlSession.Trust getFingerprintTrust(String fingerprint) {
473		return axolotlStore.getFingerprintTrust(fingerprint);
474	}
475
476	public void setFingerprintTrust(String fingerprint, XmppAxolotlSession.Trust trust) {
477		axolotlStore.setFingerprintTrust(fingerprint, trust);
478	}
479
480	private void buildSessionFromPEP(final AxolotlAddress address) {
481		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.getDeviceId());
482
483		try {
484			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
485					Jid.fromString(address.getName()), address.getDeviceId());
486			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
487			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
488				private void finish() {
489					AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
490					if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
491							&& !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) {
492						mXmppConnectionService.keyStatusUpdated();
493					}
494				}
495
496				@Override
497				public void onIqPacketReceived(Account account, IqPacket packet) {
498					if (packet.getType() == IqPacket.TYPE.RESULT) {
499						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
500						final IqParser parser = mXmppConnectionService.getIqParser();
501						final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
502						final PreKeyBundle bundle = parser.bundle(packet);
503						if (preKeyBundleList.isEmpty() || bundle == null) {
504							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
505							fetchStatusMap.put(address, FetchStatus.ERROR);
506							finish();
507							return;
508						}
509						Random random = new Random();
510						final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
511						if (preKey == null) {
512							//should never happen
513							fetchStatusMap.put(address, FetchStatus.ERROR);
514							finish();
515							return;
516						}
517
518						final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
519								preKey.getPreKeyId(), preKey.getPreKey(),
520								bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
521								bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
522
523						axolotlStore.saveIdentity(address.getName(), bundle.getIdentityKey());
524
525						try {
526							SessionBuilder builder = new SessionBuilder(axolotlStore, address);
527							builder.process(preKeyBundle);
528							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
529							sessions.put(address, session);
530							fetchStatusMap.put(address, FetchStatus.SUCCESS);
531						} catch (UntrustedIdentityException | InvalidKeyException e) {
532							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
533									+ e.getClass().getName() + ", " + e.getMessage());
534							fetchStatusMap.put(address, FetchStatus.ERROR);
535						}
536
537						finish();
538					} else {
539						fetchStatusMap.put(address, FetchStatus.ERROR);
540						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
541						finish();
542						return;
543					}
544				}
545			});
546		} catch (InvalidJidException e) {
547			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
548		}
549	}
550
551	public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
552		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + conversation.getContact().getJid().toBareJid());
553		Jid contactJid = conversation.getContact().getJid().toBareJid();
554		Set<AxolotlAddress> addresses = new HashSet<>();
555		if (deviceIds.get(contactJid) != null) {
556			for (Integer foreignId : this.deviceIds.get(contactJid)) {
557				AxolotlAddress address = new AxolotlAddress(contactJid.toString(), foreignId);
558				if (sessions.get(address) == null) {
559					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
560					if (identityKey != null) {
561						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
562						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
563						sessions.put(address, session);
564					} else {
565						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId);
566						addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
567					}
568				}
569			}
570		} else {
571			Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
572		}
573		if (deviceIds.get(account.getJid().toBareJid()) != null) {
574			for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
575				AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
576				if (sessions.get(address) == null) {
577					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
578					if (identityKey != null) {
579						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
580						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
581						sessions.put(address, session);
582					} else {
583						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
584						addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
585					}
586				}
587			}
588		}
589
590		return addresses;
591	}
592
593	public boolean createSessionsIfNeeded(final Conversation conversation) {
594		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
595		boolean newSessions = false;
596		Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
597		for (AxolotlAddress address : addresses) {
598			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
599			FetchStatus status = fetchStatusMap.get(address);
600			if (status == null || status == FetchStatus.ERROR) {
601				fetchStatusMap.put(address, FetchStatus.PENDING);
602				this.buildSessionFromPEP(address);
603				newSessions = true;
604			} else if (status == FetchStatus.PENDING) {
605				newSessions = true;
606			} else {
607				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
608			}
609		}
610
611		return newSessions;
612	}
613
614	public boolean hasPendingKeyFetches(Conversation conversation) {
615		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
616		AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(), 0);
617		return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
618				|| fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING);
619
620	}
621
622	@Nullable
623	private XmppAxolotlMessage buildHeader(Contact contact) {
624		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(
625				contact.getJid().toBareJid(), getOwnDeviceId());
626
627		Set<XmppAxolotlSession> contactSessions = findSessionsforContact(contact);
628		Set<XmppAxolotlSession> ownSessions = findOwnSessions();
629		if (contactSessions.isEmpty()) {
630			return null;
631		}
632		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl foreign keyElements...");
633		for (XmppAxolotlSession session : contactSessions) {
634			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
635			axolotlMessage.addDevice(session);
636		}
637		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl own keyElements...");
638		for (XmppAxolotlSession session : ownSessions) {
639			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
640			axolotlMessage.addDevice(session);
641		}
642
643		return axolotlMessage;
644	}
645
646	@Nullable
647	public XmppAxolotlMessage encrypt(Message message) {
648		XmppAxolotlMessage axolotlMessage = buildHeader(message.getContact());
649
650		if (axolotlMessage != null) {
651			final String content;
652			if (message.hasFileOnRemoteHost()) {
653				content = message.getFileParams().url.toString();
654			} else {
655				content = message.getBody();
656			}
657			try {
658				axolotlMessage.encrypt(content);
659			} catch (CryptoFailedException e) {
660				Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
661				return null;
662			}
663		}
664
665		return axolotlMessage;
666	}
667
668	public void preparePayloadMessage(final Message message, final boolean delay) {
669		executor.execute(new Runnable() {
670			@Override
671			public void run() {
672				XmppAxolotlMessage axolotlMessage = encrypt(message);
673				if (axolotlMessage == null) {
674					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
675					//mXmppConnectionService.updateConversationUi();
676				} else {
677					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
678					messageCache.put(message.getUuid(), axolotlMessage);
679					mXmppConnectionService.resendMessage(message, delay);
680				}
681			}
682		});
683	}
684
685	public void prepareKeyTransportMessage(final Contact contact, final OnMessageCreatedCallback onMessageCreatedCallback) {
686		executor.execute(new Runnable() {
687			@Override
688			public void run() {
689				XmppAxolotlMessage axolotlMessage = buildHeader(contact);
690				onMessageCreatedCallback.run(axolotlMessage);
691			}
692		});
693	}
694
695	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
696		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
697		if (axolotlMessage != null) {
698			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
699			messageCache.remove(message.getUuid());
700		} else {
701			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
702		}
703		return axolotlMessage;
704	}
705
706	private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
707		IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
708		return (identityKey != null)
709				? new XmppAxolotlSession(account, axolotlStore, address,
710						identityKey.getFingerprint().replaceAll("\\s", ""))
711				: null;
712	}
713
714	private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
715		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
716				message.getSenderDeviceId());
717		XmppAxolotlSession session = sessions.get(senderAddress);
718		if (session == null) {
719			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
720			session = recreateUncachedSession(senderAddress);
721			if (session == null) {
722				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
723			}
724		}
725		return session;
726	}
727
728	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
729		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
730
731		XmppAxolotlSession session = getReceivingSession(message);
732		try {
733			plaintextMessage = message.decrypt(session, getOwnDeviceId());
734			Integer preKeyId = session.getPreKeyId();
735			if (preKeyId != null) {
736				publishBundlesIfNeeded();
737				session.resetPreKeyId();
738			}
739		} catch (CryptoFailedException e) {
740			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
741		}
742
743		if (session.isFresh() && plaintextMessage != null) {
744			sessions.put(session);
745		}
746
747		return plaintextMessage;
748	}
749
750	public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
751		XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage = null;
752
753		XmppAxolotlSession session = getReceivingSession(message);
754		keyTransportMessage = message.getParameters(session, getOwnDeviceId());
755
756		if (session.isFresh() && keyTransportMessage != null) {
757			sessions.put(session);
758		}
759
760		return keyTransportMessage;
761	}
762}