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