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(null, ownDeviceAddress, false);
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	public SQLiteAxolotlStore.Trust getFingerprintTrust(String fingerprint) {
417		return axolotlStore.getFingerprintTrust(fingerprint);
418	}
419
420	public void setFingerprintTrust(String fingerprint, SQLiteAxolotlStore.Trust trust) {
421		axolotlStore.setFingerprintTrust(fingerprint, trust);
422	}
423
424	private void buildSessionFromPEP(final Conversation conversation, final AxolotlAddress address, final boolean flushWaitingQueueAfterFetch) {
425		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.getDeviceId());
426
427		try {
428			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
429					Jid.fromString(address.getName()), address.getDeviceId());
430			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Retrieving bundle: " + bundlesPacket);
431			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
432				private void finish() {
433					AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(),0);
434					if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
435							&& !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) {
436						if (flushWaitingQueueAfterFetch && conversation != null) {
437							conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_AXOLOTL,
438									new Conversation.OnMessageFound() {
439										@Override
440										public void onMessageFound(Message message) {
441											processSending(message,false);
442										}
443									});
444						}
445						mXmppConnectionService.keyStatusUpdated();
446					}
447				}
448
449				@Override
450				public void onIqPacketReceived(Account account, IqPacket packet) {
451					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Received preKey IQ packet, processing...");
452					final IqParser parser = mXmppConnectionService.getIqParser();
453					final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
454					final PreKeyBundle bundle = parser.bundle(packet);
455					if (preKeyBundleList.isEmpty() || bundle == null) {
456						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"preKey IQ packet invalid: " + packet);
457						fetchStatusMap.put(address, FetchStatus.ERROR);
458						finish();
459						return;
460					}
461					Random random = new Random();
462					final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
463					if (preKey == null) {
464						//should never happen
465						fetchStatusMap.put(address, FetchStatus.ERROR);
466						finish();
467						return;
468					}
469
470					final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
471							preKey.getPreKeyId(), preKey.getPreKey(),
472							bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
473							bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
474
475					axolotlStore.saveIdentity(address.getName(), bundle.getIdentityKey());
476
477					try {
478						SessionBuilder builder = new SessionBuilder(axolotlStore, address);
479						builder.process(preKeyBundle);
480						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
481						sessions.put(address, session);
482						fetchStatusMap.put(address, FetchStatus.SUCCESS);
483					} catch (UntrustedIdentityException|InvalidKeyException e) {
484						Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Error building session for " + address + ": "
485								+ e.getClass().getName() + ", " + e.getMessage());
486						fetchStatusMap.put(address, FetchStatus.ERROR);
487					}
488
489					finish();
490				}
491			});
492		} catch (InvalidJidException e) {
493			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Got address with invalid jid: " + address.getName());
494		}
495	}
496
497	public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
498		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + conversation.getContact().getJid().toBareJid());
499		Jid contactJid = conversation.getContact().getJid().toBareJid();
500		Set<AxolotlAddress> addresses = new HashSet<>();
501		if(deviceIds.get(contactJid) != null) {
502			for(Integer foreignId:this.deviceIds.get(contactJid)) {
503				AxolotlAddress address = new AxolotlAddress(contactJid.toString(), foreignId);
504				if(sessions.get(address) == null) {
505					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
506					if ( identityKey != null ) {
507						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Already have session for " +  address.toString() + ", adding to cache...");
508						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
509						sessions.put(address, session);
510					} else {
511						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId);
512						addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
513					}
514				}
515			}
516		} else {
517			Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
518		}
519		if(deviceIds.get(account.getJid().toBareJid()) != null) {
520			for(Integer ownId:this.deviceIds.get(account.getJid().toBareJid())) {
521				AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
522				if(sessions.get(address) == null) {
523					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
524					if ( identityKey != null ) {
525						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Already have session for " +  address.toString() + ", adding to cache...");
526						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
527						sessions.put(address, session);
528					} else {
529						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
530						addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
531					}
532				}
533			}
534		}
535
536		return addresses;
537	}
538
539	public boolean createSessionsIfNeeded(final Conversation conversation, final boolean flushWaitingQueueAfterFetch) {
540		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
541		boolean newSessions = false;
542		Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
543		for (AxolotlAddress address : addresses) {
544			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
545			FetchStatus status = fetchStatusMap.get(address);
546			if ( status == null || status == FetchStatus.ERROR ) {
547					fetchStatusMap.put(address, FetchStatus.PENDING);
548					this.buildSessionFromPEP(conversation, address, flushWaitingQueueAfterFetch);
549					newSessions = true;
550			} else {
551				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Already fetching bundle for " +  address.toString());
552			}
553		}
554
555		return newSessions;
556	}
557
558	public boolean hasPendingKeyFetches(Conversation conversation) {
559		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(),0);
560		AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(),0);
561		return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
562				||fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING);
563
564	}
565
566	@Nullable
567	public XmppAxolotlMessage encrypt(Message message ){
568		final String content;
569		if (message.hasFileOnRemoteHost()) {
570				content = message.getFileParams().url.toString();
571		} else {
572			content = message.getBody();
573		}
574		final XmppAxolotlMessage axolotlMessage;
575		try {
576			axolotlMessage = new XmppAxolotlMessage(message.getContact().getJid().toBareJid(),
577					getOwnDeviceId(), content);
578		} catch (CryptoFailedException e) {
579			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
580			return null;
581		}
582
583		if(findSessionsforContact(message.getContact()).isEmpty()) {
584			return null;
585		}
586		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building axolotl foreign headers...");
587		for (XmppAxolotlSession session : findSessionsforContact(message.getContact())) {
588			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account)+session.getRemoteAddress().toString());
589			//if(!session.isTrusted()) {
590			// TODO: handle this properly
591			//              continue;
592			//        }
593			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
594		}
595		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Building axolotl own headers...");
596		for (XmppAxolotlSession session : findOwnSessions()) {
597			Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account)+session.getRemoteAddress().toString());
598			//        if(!session.isTrusted()) {
599			// TODO: handle this properly
600			//          continue;
601			//    }
602			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
603		}
604
605		return axolotlMessage;
606	}
607
608	private void processSending(final Message message, final boolean delay) {
609		executor.execute(new Runnable() {
610			@Override
611			public void run() {
612				XmppAxolotlMessage axolotlMessage = encrypt(message);
613				if (axolotlMessage == null) {
614					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
615					//mXmppConnectionService.updateConversationUi();
616				} else {
617					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Generated message, caching: " + message.getUuid());
618					messageCache.put(message.getUuid(), axolotlMessage);
619					mXmppConnectionService.resendMessage(message,delay);
620				}
621			}
622		});
623	}
624
625	public void prepareMessage(final Message message,final boolean delay) {
626		if (!messageCache.containsKey(message.getUuid())) {
627			boolean newSessions = createSessionsIfNeeded(message.getConversation(), true);
628			if (!newSessions) {
629				this.processSending(message,delay);
630			}
631		}
632	}
633
634	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
635		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
636		if (axolotlMessage != null) {
637			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Cache hit: " + message.getUuid());
638			messageCache.remove(message.getUuid());
639		} else {
640			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Cache miss: " + message.getUuid());
641		}
642		return axolotlMessage;
643	}
644
645	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceiving(XmppAxolotlMessage message) {
646		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
647		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
648				message.getSenderDeviceId());
649
650		boolean newSession = false;
651		XmppAxolotlSession session = sessions.get(senderAddress);
652		if (session == null) {
653			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Account: "+account.getJid()+" No axolotl session found while parsing received message " + message);
654			// TODO: handle this properly
655			IdentityKey identityKey = axolotlStore.loadSession(senderAddress).getSessionState().getRemoteIdentityKey();
656			if ( identityKey != null ) {
657				session = new XmppAxolotlSession(account, axolotlStore, senderAddress, identityKey.getFingerprint().replaceAll("\\s", ""));
658			} else {
659				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
660			}
661			newSession = true;
662		}
663
664		for (XmppAxolotlMessage.XmppAxolotlMessageHeader header : message.getHeaders()) {
665			if (header.getRecipientDeviceId() == getOwnDeviceId()) {
666				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Found axolotl header matching own device ID, processing...");
667				byte[] payloadKey = session.processReceiving(header);
668				if (payloadKey != null) {
669					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account)+"Got payload key from axolotl header. Decrypting message...");
670					try{
671						plaintextMessage = message.decrypt(session, payloadKey, session.getFingerprint());
672					} catch (CryptoFailedException e) {
673						Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
674						break;
675					}
676				}
677				Integer preKeyId = session.getPreKeyId();
678				if (preKeyId != null) {
679					publishBundlesIfNeeded();
680					session.resetPreKeyId();
681				}
682				break;
683			}
684		}
685
686		if (newSession && plaintextMessage != null) {
687			sessions.put(senderAddress, session);
688		}
689
690		return plaintextMessage;
691	}
692}