AxolotlService.java

  1package eu.siacs.conversations.crypto.axolotl;
  2
  3import android.support.annotation.Nullable;
  4import android.util.Base64;
  5import android.util.Log;
  6
  7import org.whispersystems.libaxolotl.AxolotlAddress;
  8import org.whispersystems.libaxolotl.DuplicateMessageException;
  9import org.whispersystems.libaxolotl.IdentityKey;
 10import org.whispersystems.libaxolotl.IdentityKeyPair;
 11import org.whispersystems.libaxolotl.InvalidKeyException;
 12import org.whispersystems.libaxolotl.InvalidKeyIdException;
 13import org.whispersystems.libaxolotl.InvalidMessageException;
 14import org.whispersystems.libaxolotl.InvalidVersionException;
 15import org.whispersystems.libaxolotl.LegacyMessageException;
 16import org.whispersystems.libaxolotl.NoSessionException;
 17import org.whispersystems.libaxolotl.SessionBuilder;
 18import org.whispersystems.libaxolotl.SessionCipher;
 19import org.whispersystems.libaxolotl.UntrustedIdentityException;
 20import org.whispersystems.libaxolotl.ecc.Curve;
 21import org.whispersystems.libaxolotl.ecc.ECKeyPair;
 22import org.whispersystems.libaxolotl.ecc.ECPublicKey;
 23import org.whispersystems.libaxolotl.protocol.CiphertextMessage;
 24import org.whispersystems.libaxolotl.protocol.PreKeyWhisperMessage;
 25import org.whispersystems.libaxolotl.protocol.WhisperMessage;
 26import org.whispersystems.libaxolotl.state.AxolotlStore;
 27import org.whispersystems.libaxolotl.state.PreKeyBundle;
 28import org.whispersystems.libaxolotl.state.PreKeyRecord;
 29import org.whispersystems.libaxolotl.state.SessionRecord;
 30import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
 31import org.whispersystems.libaxolotl.util.KeyHelper;
 32
 33import java.util.ArrayList;
 34import java.util.Arrays;
 35import java.util.HashMap;
 36import java.util.HashSet;
 37import java.util.List;
 38import java.util.Map;
 39import java.util.Random;
 40import java.util.Set;
 41
 42import eu.siacs.conversations.Config;
 43import eu.siacs.conversations.entities.Account;
 44import eu.siacs.conversations.entities.Contact;
 45import eu.siacs.conversations.entities.Conversation;
 46import eu.siacs.conversations.entities.Message;
 47import eu.siacs.conversations.parser.IqParser;
 48import eu.siacs.conversations.services.XmppConnectionService;
 49import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
 50import eu.siacs.conversations.xml.Element;
 51import eu.siacs.conversations.xmpp.OnIqPacketReceived;
 52import eu.siacs.conversations.xmpp.jid.InvalidJidException;
 53import eu.siacs.conversations.xmpp.jid.Jid;
 54import eu.siacs.conversations.xmpp.stanzas.IqPacket;
 55import eu.siacs.conversations.xmpp.stanzas.MessagePacket;
 56
 57public class AxolotlService {
 58
 59	public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl";
 60	public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist";
 61	public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
 62
 63	public static final int NUM_KEYS_TO_PUBLISH = 10;
 64
 65	private final Account account;
 66	private final XmppConnectionService mXmppConnectionService;
 67	private final SQLiteAxolotlStore axolotlStore;
 68	private final SessionMap sessions;
 69	private final Map<Jid, Set<Integer>> deviceIds;
 70	private final Map<String, MessagePacket> messageCache;
 71	private final FetchStatusMap fetchStatusMap;
 72	private final SerialSingleThreadExecutor executor;
 73	private int ownDeviceId;
 74
 75	public static class SQLiteAxolotlStore implements AxolotlStore {
 76
 77		public static final String PREKEY_TABLENAME = "prekeys";
 78		public static final String SIGNED_PREKEY_TABLENAME = "signed_prekeys";
 79		public static final String SESSION_TABLENAME = "sessions";
 80		public static final String IDENTITIES_TABLENAME = "identities";
 81		public static final String ACCOUNT = "account";
 82		public static final String DEVICE_ID = "device_id";
 83		public static final String ID = "id";
 84		public static final String KEY = "key";
 85		public static final String NAME = "name";
 86		public static final String TRUSTED = "trusted";
 87		public static final String OWN = "ownkey";
 88
 89		public static final String JSONKEY_IDENTITY_KEY_PAIR = "axolotl_key";
 90		public static final String JSONKEY_REGISTRATION_ID = "axolotl_reg_id";
 91		public static final String JSONKEY_CURRENT_PREKEY_ID = "axolotl_cur_prekey_id";
 92
 93		private final Account account;
 94		private final XmppConnectionService mXmppConnectionService;
 95
 96		private IdentityKeyPair identityKeyPair;
 97		private final int localRegistrationId;
 98		private int currentPreKeyId = 0;
 99
100
101		private static IdentityKeyPair generateIdentityKeyPair() {
102			Log.d(Config.LOGTAG, "Generating axolotl IdentityKeyPair...");
103			ECKeyPair identityKeyPairKeys = Curve.generateKeyPair();
104			IdentityKeyPair ownKey = new IdentityKeyPair(new IdentityKey(identityKeyPairKeys.getPublicKey()),
105					identityKeyPairKeys.getPrivateKey());
106			return ownKey;
107		}
108
109		private static int generateRegistrationId() {
110			Log.d(Config.LOGTAG, "Generating axolotl registration ID...");
111			int reg_id = KeyHelper.generateRegistrationId(false);
112			return reg_id;
113		}
114
115		public SQLiteAxolotlStore(Account account, XmppConnectionService service) {
116			this.account = account;
117			this.mXmppConnectionService = service;
118			this.localRegistrationId = loadRegistrationId();
119			this.currentPreKeyId = loadCurrentPreKeyId();
120			for (SignedPreKeyRecord record : loadSignedPreKeys()) {
121				Log.d(Config.LOGTAG, "Got Axolotl signed prekey record:" + record.getId());
122			}
123		}
124
125		public int getCurrentPreKeyId() {
126			return currentPreKeyId;
127		}
128
129		// --------------------------------------
130		// IdentityKeyStore
131		// --------------------------------------
132
133		private IdentityKeyPair loadIdentityKeyPair() {
134			String ownName = account.getJid().toBareJid().toString();
135			IdentityKeyPair ownKey = mXmppConnectionService.databaseBackend.loadOwnIdentityKeyPair(account,
136					ownName);
137
138			if (ownKey != null) {
139				return ownKey;
140			} else {
141				Log.d(Config.LOGTAG, "Could not retrieve axolotl key for account " + ownName);
142				ownKey = generateIdentityKeyPair();
143				mXmppConnectionService.databaseBackend.storeOwnIdentityKeyPair(account, ownName, ownKey);
144			}
145			return ownKey;
146		}
147
148		private int loadRegistrationId() {
149			String regIdString = this.account.getKey(JSONKEY_REGISTRATION_ID);
150			int reg_id;
151			if (regIdString != null) {
152				reg_id = Integer.valueOf(regIdString);
153			} else {
154				Log.d(Config.LOGTAG, "Could not retrieve axolotl registration id for account " + account.getJid());
155				reg_id = generateRegistrationId();
156				boolean success = this.account.setKey(JSONKEY_REGISTRATION_ID, Integer.toString(reg_id));
157				if (success) {
158					mXmppConnectionService.databaseBackend.updateAccount(account);
159				} else {
160					Log.e(Config.LOGTAG, "Failed to write new key to the database!");
161				}
162			}
163			return reg_id;
164		}
165
166		private int loadCurrentPreKeyId() {
167			String regIdString = this.account.getKey(JSONKEY_CURRENT_PREKEY_ID);
168			int reg_id;
169			if (regIdString != null) {
170				reg_id = Integer.valueOf(regIdString);
171			} else {
172				Log.d(Config.LOGTAG, "Could not retrieve current prekey id for account " + account.getJid());
173				reg_id = 0;
174			}
175			return reg_id;
176		}
177
178
179		/**
180		 * Get the local client's identity key pair.
181		 *
182		 * @return The local client's persistent identity key pair.
183		 */
184		@Override
185		public IdentityKeyPair getIdentityKeyPair() {
186			if(identityKeyPair == null) {
187				identityKeyPair = loadIdentityKeyPair();
188			}
189			return identityKeyPair;
190		}
191
192		/**
193		 * Return the local client's registration ID.
194		 * <p/>
195		 * Clients should maintain a registration ID, a random number
196		 * between 1 and 16380 that's generated once at install time.
197		 *
198		 * @return the local client's registration ID.
199		 */
200		@Override
201		public int getLocalRegistrationId() {
202			return localRegistrationId;
203		}
204
205		/**
206		 * Save a remote client's identity key
207		 * <p/>
208		 * Store a remote client's identity key as trusted.
209		 *
210		 * @param name        The name of the remote client.
211		 * @param identityKey The remote client's identity key.
212		 */
213		@Override
214		public void saveIdentity(String name, IdentityKey identityKey) {
215			if(!mXmppConnectionService.databaseBackend.loadIdentityKeys(account, name).contains(identityKey)) {
216				mXmppConnectionService.databaseBackend.storeIdentityKey(account, name, identityKey);
217			}
218		}
219
220		/**
221		 * Verify a remote client's identity key.
222		 * <p/>
223		 * Determine whether a remote client's identity is trusted.  Convention is
224		 * that the TextSecure protocol is 'trust on first use.'  This means that
225		 * an identity key is considered 'trusted' if there is no entry for the recipient
226		 * in the local store, or if it matches the saved key for a recipient in the local
227		 * store.  Only if it mismatches an entry in the local store is it considered
228		 * 'untrusted.'
229		 *
230		 * @param name        The name of the remote client.
231		 * @param identityKey The identity key to verify.
232		 * @return true if trusted, false if untrusted.
233		 */
234		@Override
235		public boolean isTrustedIdentity(String name, IdentityKey identityKey) {
236			Set<IdentityKey> trustedKeys = mXmppConnectionService.databaseBackend.loadIdentityKeys(account, name);
237			return trustedKeys.isEmpty() || trustedKeys.contains(identityKey);
238		}
239
240		// --------------------------------------
241		// SessionStore
242		// --------------------------------------
243
244		/**
245		 * Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple,
246		 * or a new SessionRecord if one does not currently exist.
247		 * <p/>
248		 * It is important that implementations return a copy of the current durable information.  The
249		 * returned SessionRecord may be modified, but those changes should not have an effect on the
250		 * durable session state (what is returned by subsequent calls to this method) without the
251		 * store method being called here first.
252		 *
253		 * @param address The name and device ID of the remote client.
254		 * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or
255		 * a new SessionRecord if one does not currently exist.
256		 */
257		@Override
258		public SessionRecord loadSession(AxolotlAddress address) {
259			SessionRecord session = mXmppConnectionService.databaseBackend.loadSession(this.account, address);
260			return (session != null) ? session : new SessionRecord();
261		}
262
263		/**
264		 * Returns all known devices with active sessions for a recipient
265		 *
266		 * @param name the name of the client.
267		 * @return all known sub-devices with active sessions.
268		 */
269		@Override
270		public List<Integer> getSubDeviceSessions(String name) {
271			return mXmppConnectionService.databaseBackend.getSubDeviceSessions(account,
272					new AxolotlAddress(name, 0));
273		}
274
275		/**
276		 * Commit to storage the {@link SessionRecord} for a given recipientId + deviceId tuple.
277		 *
278		 * @param address the address of the remote client.
279		 * @param record  the current SessionRecord for the remote client.
280		 */
281		@Override
282		public void storeSession(AxolotlAddress address, SessionRecord record) {
283			mXmppConnectionService.databaseBackend.storeSession(account, address, record);
284		}
285
286		/**
287		 * Determine whether there is a committed {@link SessionRecord} for a recipientId + deviceId tuple.
288		 *
289		 * @param address the address of the remote client.
290		 * @return true if a {@link SessionRecord} exists, false otherwise.
291		 */
292		@Override
293		public boolean containsSession(AxolotlAddress address) {
294			return mXmppConnectionService.databaseBackend.containsSession(account, address);
295		}
296
297		/**
298		 * Remove a {@link SessionRecord} for a recipientId + deviceId tuple.
299		 *
300		 * @param address the address of the remote client.
301		 */
302		@Override
303		public void deleteSession(AxolotlAddress address) {
304			mXmppConnectionService.databaseBackend.deleteSession(account, address);
305		}
306
307		/**
308		 * Remove the {@link SessionRecord}s corresponding to all devices of a recipientId.
309		 *
310		 * @param name the name of the remote client.
311		 */
312		@Override
313		public void deleteAllSessions(String name) {
314			mXmppConnectionService.databaseBackend.deleteAllSessions(account,
315					new AxolotlAddress(name, 0));
316		}
317
318		public boolean isTrustedSession(AxolotlAddress address) {
319			return mXmppConnectionService.databaseBackend.isTrustedSession(this.account, address);
320		}
321
322		public void setTrustedSession(AxolotlAddress address, boolean trusted) {
323			mXmppConnectionService.databaseBackend.setTrustedSession(this.account, address, trusted);
324		}
325
326		// --------------------------------------
327		// PreKeyStore
328		// --------------------------------------
329
330		/**
331		 * Load a local PreKeyRecord.
332		 *
333		 * @param preKeyId the ID of the local PreKeyRecord.
334		 * @return the corresponding PreKeyRecord.
335		 * @throws InvalidKeyIdException when there is no corresponding PreKeyRecord.
336		 */
337		@Override
338		public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
339			PreKeyRecord record = mXmppConnectionService.databaseBackend.loadPreKey(account, preKeyId);
340			if (record == null) {
341				throw new InvalidKeyIdException("No such PreKeyRecord: " + preKeyId);
342			}
343			return record;
344		}
345
346		/**
347		 * Store a local PreKeyRecord.
348		 *
349		 * @param preKeyId the ID of the PreKeyRecord to store.
350		 * @param record   the PreKeyRecord.
351		 */
352		@Override
353		public void storePreKey(int preKeyId, PreKeyRecord record) {
354			mXmppConnectionService.databaseBackend.storePreKey(account, record);
355			currentPreKeyId = preKeyId;
356			boolean success = this.account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(preKeyId));
357			if (success) {
358				mXmppConnectionService.databaseBackend.updateAccount(account);
359			} else {
360				Log.e(Config.LOGTAG, "Failed to write new prekey id to the database!");
361			}
362		}
363
364		/**
365		 * @param preKeyId A PreKeyRecord ID.
366		 * @return true if the store has a record for the preKeyId, otherwise false.
367		 */
368		@Override
369		public boolean containsPreKey(int preKeyId) {
370			return mXmppConnectionService.databaseBackend.containsPreKey(account, preKeyId);
371		}
372
373		/**
374		 * Delete a PreKeyRecord from local storage.
375		 *
376		 * @param preKeyId The ID of the PreKeyRecord to remove.
377		 */
378		@Override
379		public void removePreKey(int preKeyId) {
380			mXmppConnectionService.databaseBackend.deletePreKey(account, preKeyId);
381		}
382
383		// --------------------------------------
384		// SignedPreKeyStore
385		// --------------------------------------
386
387		/**
388		 * Load a local SignedPreKeyRecord.
389		 *
390		 * @param signedPreKeyId the ID of the local SignedPreKeyRecord.
391		 * @return the corresponding SignedPreKeyRecord.
392		 * @throws InvalidKeyIdException when there is no corresponding SignedPreKeyRecord.
393		 */
394		@Override
395		public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
396			SignedPreKeyRecord record = mXmppConnectionService.databaseBackend.loadSignedPreKey(account, signedPreKeyId);
397			if (record == null) {
398				throw new InvalidKeyIdException("No such SignedPreKeyRecord: " + signedPreKeyId);
399			}
400			return record;
401		}
402
403		/**
404		 * Load all local SignedPreKeyRecords.
405		 *
406		 * @return All stored SignedPreKeyRecords.
407		 */
408		@Override
409		public List<SignedPreKeyRecord> loadSignedPreKeys() {
410			return mXmppConnectionService.databaseBackend.loadSignedPreKeys(account);
411		}
412
413		/**
414		 * Store a local SignedPreKeyRecord.
415		 *
416		 * @param signedPreKeyId the ID of the SignedPreKeyRecord to store.
417		 * @param record         the SignedPreKeyRecord.
418		 */
419		@Override
420		public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
421			mXmppConnectionService.databaseBackend.storeSignedPreKey(account, record);
422		}
423
424		/**
425		 * @param signedPreKeyId A SignedPreKeyRecord ID.
426		 * @return true if the store has a record for the signedPreKeyId, otherwise false.
427		 */
428		@Override
429		public boolean containsSignedPreKey(int signedPreKeyId) {
430			return mXmppConnectionService.databaseBackend.containsSignedPreKey(account, signedPreKeyId);
431		}
432
433		/**
434		 * Delete a SignedPreKeyRecord from local storage.
435		 *
436		 * @param signedPreKeyId The ID of the SignedPreKeyRecord to remove.
437		 */
438		@Override
439		public void removeSignedPreKey(int signedPreKeyId) {
440			mXmppConnectionService.databaseBackend.deleteSignedPreKey(account, signedPreKeyId);
441		}
442	}
443
444	public static class XmppAxolotlSession {
445		private SessionCipher cipher;
446		private boolean isTrusted = false;
447		private Integer preKeyId = null;
448		private SQLiteAxolotlStore sqLiteAxolotlStore;
449		private AxolotlAddress remoteAddress;
450
451		public XmppAxolotlSession(SQLiteAxolotlStore store, AxolotlAddress remoteAddress) {
452			this.cipher = new SessionCipher(store, remoteAddress);
453			this.remoteAddress = remoteAddress;
454			this.sqLiteAxolotlStore = store;
455			this.isTrusted = sqLiteAxolotlStore.isTrustedSession(remoteAddress);
456		}
457
458		public void trust() {
459			sqLiteAxolotlStore.setTrustedSession(remoteAddress, true);
460			this.isTrusted = true;
461		}
462
463		public boolean isTrusted() {
464			return this.isTrusted;
465		}
466
467		public Integer getPreKeyId() {
468			return preKeyId;
469		}
470
471		public void resetPreKeyId() {
472			preKeyId = null;
473		}
474
475		public byte[] processReceiving(XmppAxolotlMessage.XmppAxolotlMessageHeader incomingHeader) {
476			byte[] plaintext = null;
477			try {
478				try {
479					PreKeyWhisperMessage message = new PreKeyWhisperMessage(incomingHeader.getContents());
480					Log.d(Config.LOGTAG, "PreKeyWhisperMessage ID:" + message.getSignedPreKeyId() + "/" + message.getPreKeyId());
481					plaintext = cipher.decrypt(message);
482					if (message.getPreKeyId().isPresent()) {
483						preKeyId = message.getPreKeyId().get();
484					}
485				} catch (InvalidMessageException | InvalidVersionException e) {
486					WhisperMessage message = new WhisperMessage(incomingHeader.getContents());
487					plaintext = cipher.decrypt(message);
488				} catch (InvalidKeyException | InvalidKeyIdException | UntrustedIdentityException e) {
489					Log.d(Config.LOGTAG, "Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
490				}
491			} catch (LegacyMessageException | InvalidMessageException e) {
492				Log.d(Config.LOGTAG, "Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
493			} catch (DuplicateMessageException | NoSessionException e) {
494				Log.d(Config.LOGTAG, "Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
495			}
496			return plaintext;
497		}
498
499		public XmppAxolotlMessage.XmppAxolotlMessageHeader processSending(byte[] outgoingMessage) {
500			CiphertextMessage ciphertextMessage = cipher.encrypt(outgoingMessage);
501			XmppAxolotlMessage.XmppAxolotlMessageHeader header =
502					new XmppAxolotlMessage.XmppAxolotlMessageHeader(remoteAddress.getDeviceId(),
503							ciphertextMessage.serialize());
504			return header;
505		}
506	}
507
508	private static class AxolotlAddressMap<T> {
509		protected Map<String, Map<Integer, T>> map;
510		protected final Object MAP_LOCK = new Object();
511
512		public AxolotlAddressMap() {
513			this.map = new HashMap<>();
514		}
515
516		public void put(AxolotlAddress address, T value) {
517			synchronized (MAP_LOCK) {
518				Map<Integer, T> devices = map.get(address.getName());
519				if (devices == null) {
520					devices = new HashMap<>();
521					map.put(address.getName(), devices);
522				}
523				devices.put(address.getDeviceId(), value);
524			}
525		}
526
527		public T get(AxolotlAddress address) {
528			synchronized (MAP_LOCK) {
529				Map<Integer, T> devices = map.get(address.getName());
530				if (devices == null) {
531					return null;
532				}
533				return devices.get(address.getDeviceId());
534			}
535		}
536
537		public Map<Integer, T> getAll(AxolotlAddress address) {
538			synchronized (MAP_LOCK) {
539				Map<Integer, T> devices = map.get(address.getName());
540				if (devices == null) {
541					return new HashMap<>();
542				}
543				return devices;
544			}
545		}
546
547		public boolean hasAny(AxolotlAddress address) {
548			synchronized (MAP_LOCK) {
549				Map<Integer, T> devices = map.get(address.getName());
550				return devices != null && !devices.isEmpty();
551			}
552		}
553
554
555	}
556
557	private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
558
559		public SessionMap(SQLiteAxolotlStore store, Account account) {
560			super();
561			this.fillMap(store, account);
562		}
563
564		private void fillMap(SQLiteAxolotlStore store, Account account) {
565			for (Contact contact : account.getRoster().getContacts()) {
566				Jid bareJid = contact.getJid().toBareJid();
567				if (bareJid == null) {
568					continue; // FIXME: handle this?
569				}
570				String address = bareJid.toString();
571				List<Integer> deviceIDs = store.getSubDeviceSessions(address);
572				for (Integer deviceId : deviceIDs) {
573					AxolotlAddress axolotlAddress = new AxolotlAddress(address, deviceId);
574					this.put(axolotlAddress, new XmppAxolotlSession(store, axolotlAddress));
575				}
576			}
577		}
578
579	}
580
581	private static enum FetchStatus {
582		PENDING,
583		SUCCESS,
584		ERROR
585	}
586
587	private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
588
589	}
590
591	public AxolotlService(Account account, XmppConnectionService connectionService) {
592		this.mXmppConnectionService = connectionService;
593		this.account = account;
594		this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
595		this.deviceIds = new HashMap<>();
596		this.messageCache = new HashMap<>();
597		this.sessions = new SessionMap(axolotlStore, account);
598		this.fetchStatusMap = new FetchStatusMap();
599		this.executor = new SerialSingleThreadExecutor();
600		this.ownDeviceId = axolotlStore.getLocalRegistrationId();
601	}
602
603	public void trustSession(AxolotlAddress counterpart) {
604		XmppAxolotlSession session = sessions.get(counterpart);
605		if (session != null) {
606			session.trust();
607		}
608	}
609
610	public boolean isTrustedSession(AxolotlAddress counterpart) {
611		XmppAxolotlSession session = sessions.get(counterpart);
612		return session != null && session.isTrusted();
613	}
614
615	private AxolotlAddress getAddressForJid(Jid jid) {
616		return new AxolotlAddress(jid.toString(), 0);
617	}
618
619	private Set<XmppAxolotlSession> findOwnSessions() {
620		AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
621		Set<XmppAxolotlSession> ownDeviceSessions = new HashSet<>(this.sessions.getAll(ownAddress).values());
622		return ownDeviceSessions;
623	}
624
625	private Set<XmppAxolotlSession> findSessionsforContact(Contact contact) {
626		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
627		Set<XmppAxolotlSession> sessions = new HashSet<>(this.sessions.getAll(contactAddress).values());
628		return sessions;
629	}
630
631	private boolean hasAny(Contact contact) {
632		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
633		return sessions.hasAny(contactAddress);
634	}
635
636	public int getOwnDeviceId() {
637		return ownDeviceId;
638	}
639
640	public void registerDevices(final Jid jid, final Set<Integer> deviceIds) {
641		for(Integer i:deviceIds) {
642			Log.d(Config.LOGTAG, "Adding Device ID:"+ jid + ":"+i);
643		}
644		this.deviceIds.put(jid, deviceIds);
645	}
646
647	public void publishOwnDeviceIdIfNeeded() {
648		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
649		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
650			@Override
651			public void onIqPacketReceived(Account account, IqPacket packet) {
652				Element item = mXmppConnectionService.getIqParser().getItem(packet);
653				Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
654				if (deviceIds == null) {
655					deviceIds = new HashSet<Integer>();
656				}
657				if (!deviceIds.contains(getOwnDeviceId())) {
658					deviceIds.add(getOwnDeviceId());
659					IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
660					Log.d(Config.LOGTAG, "Own device " + getOwnDeviceId() + " not in PEP devicelist. Publishing: " + publish);
661					mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
662						@Override
663						public void onIqPacketReceived(Account account, IqPacket packet) {
664							// TODO: implement this!
665						}
666					});
667				}
668			}
669		});
670	}
671
672	public void publishBundlesIfNeeded() {
673		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), ownDeviceId);
674		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
675			@Override
676			public void onIqPacketReceived(Account account, IqPacket packet) {
677				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
678				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
679				boolean flush = false;
680				if (bundle == null) {
681					Log.e(Config.LOGTAG, "Received invalid bundle:" + packet);
682					bundle = new PreKeyBundle(-1, -1, -1 , null, -1, null, null, null);
683					flush = true;
684				}
685				if (keys == null) {
686					Log.e(Config.LOGTAG, "Received invalid prekeys:" + packet);
687				}
688				try {
689					boolean changed = false;
690					// Validate IdentityKey
691					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
692					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
693						Log.d(Config.LOGTAG, "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
694						changed = true;
695					}
696
697					// Validate signedPreKeyRecord + ID
698					SignedPreKeyRecord signedPreKeyRecord;
699					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
700					try {
701						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
702						if ( flush
703								||!bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
704								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
705							Log.d(Config.LOGTAG, "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
706							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
707							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
708							changed = true;
709						}
710					} catch (InvalidKeyIdException e) {
711						Log.d(Config.LOGTAG, "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
712						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
713						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
714						changed = true;
715					}
716
717					// Validate PreKeys
718					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
719					if (keys != null) {
720						for (Integer id : keys.keySet()) {
721							try {
722								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
723								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
724									preKeyRecords.add(preKeyRecord);
725								}
726							} catch (InvalidKeyIdException ignored) {
727							}
728						}
729					}
730					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
731					if (newKeys > 0) {
732						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
733								axolotlStore.getCurrentPreKeyId()+1, newKeys);
734						preKeyRecords.addAll(newRecords);
735						for (PreKeyRecord record : newRecords) {
736							axolotlStore.storePreKey(record.getId(), record);
737						}
738						changed = true;
739						Log.d(Config.LOGTAG, "Adding " + newKeys + " new preKeys to PEP.");
740					}
741
742
743					if(changed) {
744						IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
745								signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
746								preKeyRecords, ownDeviceId);
747						Log.d(Config.LOGTAG, "Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
748						mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
749							@Override
750							public void onIqPacketReceived(Account account, IqPacket packet) {
751								// TODO: implement this!
752								Log.d(Config.LOGTAG, "Published bundle, got: " + packet);
753							}
754						});
755					}
756				} catch (InvalidKeyException e) {
757						Log.e(Config.LOGTAG, "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
758						return;
759				}
760			}
761		});
762	}
763
764	public boolean isContactAxolotlCapable(Contact contact) {
765		Jid jid = contact.getJid().toBareJid();
766		AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
767		return sessions.hasAny(address) ||
768				( deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
769	}
770
771	private void buildSessionFromPEP(final Conversation conversation, final AxolotlAddress address) {
772		Log.d(Config.LOGTAG, "Building new sesstion for " + address.getDeviceId());
773
774		try {
775			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
776					Jid.fromString(address.getName()), address.getDeviceId());
777			Log.d(Config.LOGTAG, "Retrieving bundle: " + bundlesPacket);
778			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
779				@Override
780				public void onIqPacketReceived(Account account, IqPacket packet) {
781					Log.d(Config.LOGTAG, "Received preKey IQ packet, processing...");
782					final IqParser parser = mXmppConnectionService.getIqParser();
783					final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
784					final PreKeyBundle bundle = parser.bundle(packet);
785					if (preKeyBundleList.isEmpty() || bundle == null) {
786						Log.d(Config.LOGTAG, "preKey IQ packet invalid: " + packet);
787						fetchStatusMap.put(address, FetchStatus.ERROR);
788						return;
789					}
790					Random random = new Random();
791					final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
792					if (preKey == null) {
793						//should never happen
794						fetchStatusMap.put(address, FetchStatus.ERROR);
795						return;
796					}
797
798					final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
799							preKey.getPreKeyId(), preKey.getPreKey(),
800							bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
801							bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
802
803					axolotlStore.saveIdentity(address.getName(), bundle.getIdentityKey());
804
805					try {
806						SessionBuilder builder = new SessionBuilder(axolotlStore, address);
807						builder.process(preKeyBundle);
808						XmppAxolotlSession session = new XmppAxolotlSession(axolotlStore, address);
809						sessions.put(address, session);
810						fetchStatusMap.put(address, FetchStatus.SUCCESS);
811					} catch (UntrustedIdentityException|InvalidKeyException e) {
812						Log.d(Config.LOGTAG, "Error building session for " + address + ": "
813								+ e.getClass().getName() + ", " + e.getMessage());
814						fetchStatusMap.put(address, FetchStatus.ERROR);
815					}
816
817					AxolotlAddress ownAddress = new AxolotlAddress(conversation.getAccount().getJid().toBareJid().toString(),0);
818					AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(),0);
819					if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
820							&& !fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
821						conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_AXOLOTL,
822								new Conversation.OnMessageFound() {
823									@Override
824									public void onMessageFound(Message message) {
825										processSending(message);
826									}
827								});
828					}
829				}
830			});
831		} catch (InvalidJidException e) {
832			Log.e(Config.LOGTAG,"Got address with invalid jid: " + address.getName());
833		}
834	}
835
836	private boolean createSessionsIfNeeded(Conversation conversation) {
837		boolean newSessions = false;
838		Log.d(Config.LOGTAG, "Creating axolotl sessions if needed...");
839		Jid contactJid = conversation.getContact().getJid().toBareJid();
840		Set<AxolotlAddress> addresses = new HashSet<>();
841		if(deviceIds.get(contactJid) != null) {
842			for(Integer foreignId:this.deviceIds.get(contactJid)) {
843				Log.d(Config.LOGTAG, "Found device "+account.getJid().toBareJid()+":"+foreignId);
844				addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
845			}
846		} else {
847			Log.e(Config.LOGTAG, "Have no target devices in PEP!");
848		}
849		Log.d(Config.LOGTAG, "Checking own account "+account.getJid().toBareJid());
850		if(deviceIds.get(account.getJid().toBareJid()) != null) {
851			for(Integer ownId:this.deviceIds.get(account.getJid().toBareJid())) {
852				Log.d(Config.LOGTAG, "Found device "+account.getJid().toBareJid()+":"+ownId);
853				addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
854			}
855		}
856		for (AxolotlAddress address : addresses) {
857			Log.d(Config.LOGTAG, "Processing device: " + address.toString());
858			FetchStatus status = fetchStatusMap.get(address);
859			XmppAxolotlSession session = sessions.get(address);
860			if ( session == null && ( status == null || status == FetchStatus.ERROR) ) {
861				fetchStatusMap.put(address, FetchStatus.PENDING);
862				this.buildSessionFromPEP(conversation,  address);
863				newSessions = true;
864			} else {
865				Log.d(Config.LOGTAG, "Already have session for " +  address.toString());
866			}
867		}
868		return newSessions;
869	}
870
871	@Nullable
872	public XmppAxolotlMessage encrypt(Message message ){
873		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(message.getContact().getJid().toBareJid(),
874				ownDeviceId, message.getBody());
875
876		if(findSessionsforContact(message.getContact()).isEmpty()) {
877			return null;
878		}
879		Log.d(Config.LOGTAG, "Building axolotl foreign headers...");
880		for (XmppAxolotlSession session : findSessionsforContact(message.getContact())) {
881			Log.d(Config.LOGTAG, session.remoteAddress.toString());
882			//if(!session.isTrusted()) {
883			// TODO: handle this properly
884			//              continue;
885			//        }
886			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
887		}
888		Log.d(Config.LOGTAG, "Building axolotl own headers...");
889		for (XmppAxolotlSession session : findOwnSessions()) {
890			Log.d(Config.LOGTAG, session.remoteAddress.toString());
891			//        if(!session.isTrusted()) {
892			// TODO: handle this properly
893			//          continue;
894			//    }
895			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
896		}
897
898		return axolotlMessage;
899	}
900
901	private void processSending(final Message message) {
902		executor.execute(new Runnable() {
903			@Override
904			public void run() {
905				MessagePacket packet = mXmppConnectionService.getMessageGenerator()
906						.generateAxolotlChat(message);
907				if (packet == null) {
908					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
909					//mXmppConnectionService.updateConversationUi();
910				} else {
911					Log.d(Config.LOGTAG, "Generated message, caching: " + message.getUuid());
912					messageCache.put(message.getUuid(), packet);
913					mXmppConnectionService.resendMessage(message);
914				}
915			}
916		});
917	}
918
919	public void prepareMessage(Message message) {
920		if (!messageCache.containsKey(message.getUuid())) {
921			boolean newSessions = createSessionsIfNeeded(message.getConversation());
922
923			if (!newSessions) {
924				this.processSending(message);
925			}
926		}
927	}
928
929	public MessagePacket fetchPacketFromCache(Message message) {
930		MessagePacket packet = messageCache.get(message.getUuid());
931		if (packet != null) {
932			Log.d(Config.LOGTAG, "Cache hit: " + message.getUuid());
933			messageCache.remove(message.getUuid());
934		} else {
935			Log.d(Config.LOGTAG, "Cache miss: " + message.getUuid());
936		}
937		return packet;
938	}
939
940	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceiving(XmppAxolotlMessage message) {
941		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
942		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
943				message.getSenderDeviceId());
944
945		XmppAxolotlSession session = sessions.get(senderAddress);
946		if (session == null) {
947			Log.d(Config.LOGTAG, "Account: "+account.getJid()+" No axolotl session found while parsing received message " + message);
948			// TODO: handle this properly
949			session = new XmppAxolotlSession(axolotlStore, senderAddress);
950			sessions.put(senderAddress,session);
951		}
952
953		for (XmppAxolotlMessage.XmppAxolotlMessageHeader header : message.getHeaders()) {
954			if (header.getRecipientDeviceId() == ownDeviceId) {
955				Log.d(Config.LOGTAG, "Found axolotl header matching own device ID, processing...");
956				byte[] payloadKey = session.processReceiving(header);
957				if (payloadKey != null) {
958					Log.d(Config.LOGTAG, "Got payload key from axolotl header. Decrypting message...");
959					plaintextMessage = message.decrypt(session, payloadKey);
960				}
961				Integer preKeyId = session.getPreKeyId();
962				if (preKeyId != null) {
963					publishBundlesIfNeeded();
964					session.resetPreKeyId();
965				}
966				break;
967			}
968		}
969
970		return plaintextMessage;
971	}
972}