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			return true;
239		}
240
241		// --------------------------------------
242		// SessionStore
243		// --------------------------------------
244
245		/**
246		 * Returns a copy of the {@link SessionRecord} corresponding to the recipientId + deviceId tuple,
247		 * or a new SessionRecord if one does not currently exist.
248		 * <p/>
249		 * It is important that implementations return a copy of the current durable information.  The
250		 * returned SessionRecord may be modified, but those changes should not have an effect on the
251		 * durable session state (what is returned by subsequent calls to this method) without the
252		 * store method being called here first.
253		 *
254		 * @param address The name and device ID of the remote client.
255		 * @return a copy of the SessionRecord corresponding to the recipientId + deviceId tuple, or
256		 * a new SessionRecord if one does not currently exist.
257		 */
258		@Override
259		public SessionRecord loadSession(AxolotlAddress address) {
260			SessionRecord session = mXmppConnectionService.databaseBackend.loadSession(this.account, address);
261			return (session != null) ? session : new SessionRecord();
262		}
263
264		/**
265		 * Returns all known devices with active sessions for a recipient
266		 *
267		 * @param name the name of the client.
268		 * @return all known sub-devices with active sessions.
269		 */
270		@Override
271		public List<Integer> getSubDeviceSessions(String name) {
272			return mXmppConnectionService.databaseBackend.getSubDeviceSessions(account,
273					new AxolotlAddress(name, 0));
274		}
275
276		/**
277		 * Commit to storage the {@link SessionRecord} for a given recipientId + deviceId tuple.
278		 *
279		 * @param address the address of the remote client.
280		 * @param record  the current SessionRecord for the remote client.
281		 */
282		@Override
283		public void storeSession(AxolotlAddress address, SessionRecord record) {
284			mXmppConnectionService.databaseBackend.storeSession(account, address, record);
285		}
286
287		/**
288		 * Determine whether there is a committed {@link SessionRecord} for a recipientId + deviceId tuple.
289		 *
290		 * @param address the address of the remote client.
291		 * @return true if a {@link SessionRecord} exists, false otherwise.
292		 */
293		@Override
294		public boolean containsSession(AxolotlAddress address) {
295			return mXmppConnectionService.databaseBackend.containsSession(account, address);
296		}
297
298		/**
299		 * Remove a {@link SessionRecord} for a recipientId + deviceId tuple.
300		 *
301		 * @param address the address of the remote client.
302		 */
303		@Override
304		public void deleteSession(AxolotlAddress address) {
305			mXmppConnectionService.databaseBackend.deleteSession(account, address);
306		}
307
308		/**
309		 * Remove the {@link SessionRecord}s corresponding to all devices of a recipientId.
310		 *
311		 * @param name the name of the remote client.
312		 */
313		@Override
314		public void deleteAllSessions(String name) {
315			mXmppConnectionService.databaseBackend.deleteAllSessions(account,
316					new AxolotlAddress(name, 0));
317		}
318
319		public boolean isTrustedSession(AxolotlAddress address) {
320			return mXmppConnectionService.databaseBackend.isTrustedSession(this.account, address);
321		}
322
323		public void setTrustedSession(AxolotlAddress address, boolean trusted) {
324			mXmppConnectionService.databaseBackend.setTrustedSession(this.account, address, trusted);
325		}
326
327		// --------------------------------------
328		// PreKeyStore
329		// --------------------------------------
330
331		/**
332		 * Load a local PreKeyRecord.
333		 *
334		 * @param preKeyId the ID of the local PreKeyRecord.
335		 * @return the corresponding PreKeyRecord.
336		 * @throws InvalidKeyIdException when there is no corresponding PreKeyRecord.
337		 */
338		@Override
339		public PreKeyRecord loadPreKey(int preKeyId) throws InvalidKeyIdException {
340			PreKeyRecord record = mXmppConnectionService.databaseBackend.loadPreKey(account, preKeyId);
341			if (record == null) {
342				throw new InvalidKeyIdException("No such PreKeyRecord: " + preKeyId);
343			}
344			return record;
345		}
346
347		/**
348		 * Store a local PreKeyRecord.
349		 *
350		 * @param preKeyId the ID of the PreKeyRecord to store.
351		 * @param record   the PreKeyRecord.
352		 */
353		@Override
354		public void storePreKey(int preKeyId, PreKeyRecord record) {
355			mXmppConnectionService.databaseBackend.storePreKey(account, record);
356			currentPreKeyId = preKeyId;
357			boolean success = this.account.setKey(JSONKEY_CURRENT_PREKEY_ID, Integer.toString(preKeyId));
358			if (success) {
359				mXmppConnectionService.databaseBackend.updateAccount(account);
360			} else {
361				Log.e(Config.LOGTAG, "Failed to write new prekey id to the database!");
362			}
363		}
364
365		/**
366		 * @param preKeyId A PreKeyRecord ID.
367		 * @return true if the store has a record for the preKeyId, otherwise false.
368		 */
369		@Override
370		public boolean containsPreKey(int preKeyId) {
371			return mXmppConnectionService.databaseBackend.containsPreKey(account, preKeyId);
372		}
373
374		/**
375		 * Delete a PreKeyRecord from local storage.
376		 *
377		 * @param preKeyId The ID of the PreKeyRecord to remove.
378		 */
379		@Override
380		public void removePreKey(int preKeyId) {
381			mXmppConnectionService.databaseBackend.deletePreKey(account, preKeyId);
382		}
383
384		// --------------------------------------
385		// SignedPreKeyStore
386		// --------------------------------------
387
388		/**
389		 * Load a local SignedPreKeyRecord.
390		 *
391		 * @param signedPreKeyId the ID of the local SignedPreKeyRecord.
392		 * @return the corresponding SignedPreKeyRecord.
393		 * @throws InvalidKeyIdException when there is no corresponding SignedPreKeyRecord.
394		 */
395		@Override
396		public SignedPreKeyRecord loadSignedPreKey(int signedPreKeyId) throws InvalidKeyIdException {
397			SignedPreKeyRecord record = mXmppConnectionService.databaseBackend.loadSignedPreKey(account, signedPreKeyId);
398			if (record == null) {
399				throw new InvalidKeyIdException("No such SignedPreKeyRecord: " + signedPreKeyId);
400			}
401			return record;
402		}
403
404		/**
405		 * Load all local SignedPreKeyRecords.
406		 *
407		 * @return All stored SignedPreKeyRecords.
408		 */
409		@Override
410		public List<SignedPreKeyRecord> loadSignedPreKeys() {
411			return mXmppConnectionService.databaseBackend.loadSignedPreKeys(account);
412		}
413
414		/**
415		 * Store a local SignedPreKeyRecord.
416		 *
417		 * @param signedPreKeyId the ID of the SignedPreKeyRecord to store.
418		 * @param record         the SignedPreKeyRecord.
419		 */
420		@Override
421		public void storeSignedPreKey(int signedPreKeyId, SignedPreKeyRecord record) {
422			mXmppConnectionService.databaseBackend.storeSignedPreKey(account, record);
423		}
424
425		/**
426		 * @param signedPreKeyId A SignedPreKeyRecord ID.
427		 * @return true if the store has a record for the signedPreKeyId, otherwise false.
428		 */
429		@Override
430		public boolean containsSignedPreKey(int signedPreKeyId) {
431			return mXmppConnectionService.databaseBackend.containsSignedPreKey(account, signedPreKeyId);
432		}
433
434		/**
435		 * Delete a SignedPreKeyRecord from local storage.
436		 *
437		 * @param signedPreKeyId The ID of the SignedPreKeyRecord to remove.
438		 */
439		@Override
440		public void removeSignedPreKey(int signedPreKeyId) {
441			mXmppConnectionService.databaseBackend.deleteSignedPreKey(account, signedPreKeyId);
442		}
443	}
444
445	public static class XmppAxolotlSession {
446		private SessionCipher cipher;
447		private boolean isTrusted = false;
448		private Integer preKeyId = null;
449		private SQLiteAxolotlStore sqLiteAxolotlStore;
450		private AxolotlAddress remoteAddress;
451
452		public XmppAxolotlSession(SQLiteAxolotlStore store, AxolotlAddress remoteAddress) {
453			this.cipher = new SessionCipher(store, remoteAddress);
454			this.remoteAddress = remoteAddress;
455			this.sqLiteAxolotlStore = store;
456			this.isTrusted = sqLiteAxolotlStore.isTrustedSession(remoteAddress);
457		}
458
459		public void trust() {
460			sqLiteAxolotlStore.setTrustedSession(remoteAddress, true);
461			this.isTrusted = true;
462		}
463
464		public boolean isTrusted() {
465			return this.isTrusted;
466		}
467
468		public Integer getPreKeyId() {
469			return preKeyId;
470		}
471
472		public void resetPreKeyId() {
473			preKeyId = null;
474		}
475
476		public byte[] processReceiving(XmppAxolotlMessage.XmppAxolotlMessageHeader incomingHeader) {
477			byte[] plaintext = null;
478			try {
479				try {
480					PreKeyWhisperMessage message = new PreKeyWhisperMessage(incomingHeader.getContents());
481					Log.d(Config.LOGTAG, "PreKeyWhisperMessage ID:" + message.getSignedPreKeyId() + "/" + message.getPreKeyId());
482					plaintext = cipher.decrypt(message);
483					if (message.getPreKeyId().isPresent()) {
484						preKeyId = message.getPreKeyId().get();
485					}
486				} catch (InvalidMessageException | InvalidVersionException e) {
487					WhisperMessage message = new WhisperMessage(incomingHeader.getContents());
488					plaintext = cipher.decrypt(message);
489				} catch (InvalidKeyException | InvalidKeyIdException | UntrustedIdentityException e) {
490					Log.d(Config.LOGTAG, "Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
491				}
492			} catch (LegacyMessageException | InvalidMessageException e) {
493				Log.d(Config.LOGTAG, "Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
494			} catch (DuplicateMessageException | NoSessionException e) {
495				Log.d(Config.LOGTAG, "Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
496			}
497			return plaintext;
498		}
499
500		public XmppAxolotlMessage.XmppAxolotlMessageHeader processSending(byte[] outgoingMessage) {
501			CiphertextMessage ciphertextMessage = cipher.encrypt(outgoingMessage);
502			XmppAxolotlMessage.XmppAxolotlMessageHeader header =
503					new XmppAxolotlMessage.XmppAxolotlMessageHeader(remoteAddress.getDeviceId(),
504							ciphertextMessage.serialize());
505			return header;
506		}
507	}
508
509	private static class AxolotlAddressMap<T> {
510		protected Map<String, Map<Integer, T>> map;
511		protected final Object MAP_LOCK = new Object();
512
513		public AxolotlAddressMap() {
514			this.map = new HashMap<>();
515		}
516
517		public void put(AxolotlAddress address, T value) {
518			synchronized (MAP_LOCK) {
519				Map<Integer, T> devices = map.get(address.getName());
520				if (devices == null) {
521					devices = new HashMap<>();
522					map.put(address.getName(), devices);
523				}
524				devices.put(address.getDeviceId(), value);
525			}
526		}
527
528		public T get(AxolotlAddress address) {
529			synchronized (MAP_LOCK) {
530				Map<Integer, T> devices = map.get(address.getName());
531				if (devices == null) {
532					return null;
533				}
534				return devices.get(address.getDeviceId());
535			}
536		}
537
538		public Map<Integer, T> getAll(AxolotlAddress address) {
539			synchronized (MAP_LOCK) {
540				Map<Integer, T> devices = map.get(address.getName());
541				if (devices == null) {
542					return new HashMap<>();
543				}
544				return devices;
545			}
546		}
547
548		public boolean hasAny(AxolotlAddress address) {
549			synchronized (MAP_LOCK) {
550				Map<Integer, T> devices = map.get(address.getName());
551				return devices != null && !devices.isEmpty();
552			}
553		}
554
555
556	}
557
558	private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
559
560		public SessionMap(SQLiteAxolotlStore store, Account account) {
561			super();
562			this.fillMap(store, account);
563		}
564
565		private void fillMap(SQLiteAxolotlStore store, Account account) {
566			for (Contact contact : account.getRoster().getContacts()) {
567				Jid bareJid = contact.getJid().toBareJid();
568				if (bareJid == null) {
569					continue; // FIXME: handle this?
570				}
571				String address = bareJid.toString();
572				List<Integer> deviceIDs = store.getSubDeviceSessions(address);
573				for (Integer deviceId : deviceIDs) {
574					AxolotlAddress axolotlAddress = new AxolotlAddress(address, deviceId);
575					this.put(axolotlAddress, new XmppAxolotlSession(store, axolotlAddress));
576				}
577			}
578		}
579
580	}
581
582	private static enum FetchStatus {
583		PENDING,
584		SUCCESS,
585		ERROR
586	}
587
588	private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
589
590	}
591
592	public AxolotlService(Account account, XmppConnectionService connectionService) {
593		this.mXmppConnectionService = connectionService;
594		this.account = account;
595		this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
596		this.deviceIds = new HashMap<>();
597		this.messageCache = new HashMap<>();
598		this.sessions = new SessionMap(axolotlStore, account);
599		this.fetchStatusMap = new FetchStatusMap();
600		this.executor = new SerialSingleThreadExecutor();
601		this.ownDeviceId = axolotlStore.getLocalRegistrationId();
602	}
603
604	public void trustSession(AxolotlAddress counterpart) {
605		XmppAxolotlSession session = sessions.get(counterpart);
606		if (session != null) {
607			session.trust();
608		}
609	}
610
611	public boolean isTrustedSession(AxolotlAddress counterpart) {
612		XmppAxolotlSession session = sessions.get(counterpart);
613		return session != null && session.isTrusted();
614	}
615
616	private AxolotlAddress getAddressForJid(Jid jid) {
617		return new AxolotlAddress(jid.toString(), 0);
618	}
619
620	private Set<XmppAxolotlSession> findOwnSessions() {
621		AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
622		Set<XmppAxolotlSession> ownDeviceSessions = new HashSet<>(this.sessions.getAll(ownAddress).values());
623		return ownDeviceSessions;
624	}
625
626	private Set<XmppAxolotlSession> findSessionsforContact(Contact contact) {
627		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
628		Set<XmppAxolotlSession> sessions = new HashSet<>(this.sessions.getAll(contactAddress).values());
629		return sessions;
630	}
631
632	private boolean hasAny(Contact contact) {
633		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
634		return sessions.hasAny(contactAddress);
635	}
636
637	public int getOwnDeviceId() {
638		return ownDeviceId;
639	}
640
641	public void registerDevices(final Jid jid, final Set<Integer> deviceIds) {
642		for(Integer i:deviceIds) {
643			Log.d(Config.LOGTAG, "Adding Device ID:"+ jid + ":"+i);
644		}
645		this.deviceIds.put(jid, deviceIds);
646	}
647
648	public void publishOwnDeviceIdIfNeeded() {
649		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
650		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
651			@Override
652			public void onIqPacketReceived(Account account, IqPacket packet) {
653				Element item = mXmppConnectionService.getIqParser().getItem(packet);
654				Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
655				if (deviceIds == null) {
656					deviceIds = new HashSet<Integer>();
657				}
658				if (!deviceIds.contains(getOwnDeviceId())) {
659					deviceIds.add(getOwnDeviceId());
660					IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
661					Log.d(Config.LOGTAG, "Own device " + getOwnDeviceId() + " not in PEP devicelist. Publishing: " + publish);
662					mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
663						@Override
664						public void onIqPacketReceived(Account account, IqPacket packet) {
665							// TODO: implement this!
666						}
667					});
668				}
669			}
670		});
671	}
672
673	public void publishBundlesIfNeeded() {
674		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), ownDeviceId);
675		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
676			@Override
677			public void onIqPacketReceived(Account account, IqPacket packet) {
678				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
679				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
680				boolean flush = false;
681				if (bundle == null) {
682					Log.e(Config.LOGTAG, "Received invalid bundle:" + packet);
683					bundle = new PreKeyBundle(-1, -1, -1 , null, -1, null, null, null);
684					flush = true;
685				}
686				if (keys == null) {
687					Log.e(Config.LOGTAG, "Received invalid prekeys:" + packet);
688				}
689				try {
690					boolean changed = false;
691					// Validate IdentityKey
692					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
693					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
694						Log.d(Config.LOGTAG, "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
695						changed = true;
696					}
697
698					// Validate signedPreKeyRecord + ID
699					SignedPreKeyRecord signedPreKeyRecord;
700					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
701					try {
702						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
703						if ( flush
704								||!bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
705								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
706							Log.d(Config.LOGTAG, "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
707							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
708							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
709							changed = true;
710						}
711					} catch (InvalidKeyIdException e) {
712						Log.d(Config.LOGTAG, "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
713						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
714						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
715						changed = true;
716					}
717
718					// Validate PreKeys
719					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
720					if (keys != null) {
721						for (Integer id : keys.keySet()) {
722							try {
723								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
724								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
725									preKeyRecords.add(preKeyRecord);
726								}
727							} catch (InvalidKeyIdException ignored) {
728							}
729						}
730					}
731					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
732					if (newKeys > 0) {
733						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
734								axolotlStore.getCurrentPreKeyId()+1, newKeys);
735						preKeyRecords.addAll(newRecords);
736						for (PreKeyRecord record : newRecords) {
737							axolotlStore.storePreKey(record.getId(), record);
738						}
739						changed = true;
740						Log.d(Config.LOGTAG, "Adding " + newKeys + " new preKeys to PEP.");
741					}
742
743
744					if(changed) {
745						IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
746								signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
747								preKeyRecords, ownDeviceId);
748						Log.d(Config.LOGTAG, "Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
749						mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
750							@Override
751							public void onIqPacketReceived(Account account, IqPacket packet) {
752								// TODO: implement this!
753								Log.d(Config.LOGTAG, "Published bundle, got: " + packet);
754							}
755						});
756					}
757				} catch (InvalidKeyException e) {
758						Log.e(Config.LOGTAG, "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
759						return;
760				}
761			}
762		});
763	}
764
765	public boolean isContactAxolotlCapable(Contact contact) {
766		Jid jid = contact.getJid().toBareJid();
767		AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
768		return sessions.hasAny(address) ||
769				( deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
770	}
771
772	private void buildSessionFromPEP(final Conversation conversation, final AxolotlAddress address) {
773		Log.d(Config.LOGTAG, "Building new sesstion for " + address.getDeviceId());
774
775		try {
776			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
777					Jid.fromString(address.getName()), address.getDeviceId());
778			Log.d(Config.LOGTAG, "Retrieving bundle: " + bundlesPacket);
779			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
780				@Override
781				public void onIqPacketReceived(Account account, IqPacket packet) {
782					Log.d(Config.LOGTAG, "Received preKey IQ packet, processing...");
783					final IqParser parser = mXmppConnectionService.getIqParser();
784					final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
785					final PreKeyBundle bundle = parser.bundle(packet);
786					if (preKeyBundleList.isEmpty() || bundle == null) {
787						Log.d(Config.LOGTAG, "preKey IQ packet invalid: " + packet);
788						fetchStatusMap.put(address, FetchStatus.ERROR);
789						return;
790					}
791					Random random = new Random();
792					final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
793					if (preKey == null) {
794						//should never happen
795						fetchStatusMap.put(address, FetchStatus.ERROR);
796						return;
797					}
798
799					final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
800							preKey.getPreKeyId(), preKey.getPreKey(),
801							bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
802							bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
803
804					axolotlStore.saveIdentity(address.getName(), bundle.getIdentityKey());
805
806					try {
807						SessionBuilder builder = new SessionBuilder(axolotlStore, address);
808						builder.process(preKeyBundle);
809						XmppAxolotlSession session = new XmppAxolotlSession(axolotlStore, address);
810						sessions.put(address, session);
811						fetchStatusMap.put(address, FetchStatus.SUCCESS);
812					} catch (UntrustedIdentityException|InvalidKeyException e) {
813						Log.d(Config.LOGTAG, "Error building session for " + address + ": "
814								+ e.getClass().getName() + ", " + e.getMessage());
815						fetchStatusMap.put(address, FetchStatus.ERROR);
816					}
817
818					AxolotlAddress ownAddress = new AxolotlAddress(conversation.getAccount().getJid().toBareJid().toString(),0);
819					AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(),0);
820					if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
821							&& !fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
822						conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_AXOLOTL,
823								new Conversation.OnMessageFound() {
824									@Override
825									public void onMessageFound(Message message) {
826										processSending(message);
827									}
828								});
829					}
830				}
831			});
832		} catch (InvalidJidException e) {
833			Log.e(Config.LOGTAG,"Got address with invalid jid: " + address.getName());
834		}
835	}
836
837	private boolean createSessionsIfNeeded(Conversation conversation) {
838		boolean newSessions = false;
839		Log.d(Config.LOGTAG, "Creating axolotl sessions if needed...");
840		Jid contactJid = conversation.getContact().getJid().toBareJid();
841		Set<AxolotlAddress> addresses = new HashSet<>();
842		if(deviceIds.get(contactJid) != null) {
843			for(Integer foreignId:this.deviceIds.get(contactJid)) {
844				Log.d(Config.LOGTAG, "Found device "+account.getJid().toBareJid()+":"+foreignId);
845				addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
846			}
847		} else {
848			Log.e(Config.LOGTAG, "Have no target devices in PEP!");
849		}
850		Log.d(Config.LOGTAG, "Checking own account "+account.getJid().toBareJid());
851		if(deviceIds.get(account.getJid().toBareJid()) != null) {
852			for(Integer ownId:this.deviceIds.get(account.getJid().toBareJid())) {
853				Log.d(Config.LOGTAG, "Found device "+account.getJid().toBareJid()+":"+ownId);
854				addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
855			}
856		}
857		for (AxolotlAddress address : addresses) {
858			Log.d(Config.LOGTAG, "Processing device: " + address.toString());
859			FetchStatus status = fetchStatusMap.get(address);
860			XmppAxolotlSession session = sessions.get(address);
861			if ( session == null && ( status == null || status == FetchStatus.ERROR) ) {
862				fetchStatusMap.put(address, FetchStatus.PENDING);
863				this.buildSessionFromPEP(conversation,  address);
864				newSessions = true;
865			} else {
866				Log.d(Config.LOGTAG, "Already have session for " +  address.toString());
867			}
868		}
869		return newSessions;
870	}
871
872	@Nullable
873	public XmppAxolotlMessage encrypt(Message message ){
874		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(message.getContact().getJid().toBareJid(),
875				ownDeviceId, message.getBody());
876
877		if(findSessionsforContact(message.getContact()).isEmpty()) {
878			return null;
879		}
880		Log.d(Config.LOGTAG, "Building axolotl foreign headers...");
881		for (XmppAxolotlSession session : findSessionsforContact(message.getContact())) {
882			Log.d(Config.LOGTAG, session.remoteAddress.toString());
883			//if(!session.isTrusted()) {
884			// TODO: handle this properly
885			//              continue;
886			//        }
887			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
888		}
889		Log.d(Config.LOGTAG, "Building axolotl own headers...");
890		for (XmppAxolotlSession session : findOwnSessions()) {
891			Log.d(Config.LOGTAG, session.remoteAddress.toString());
892			//        if(!session.isTrusted()) {
893			// TODO: handle this properly
894			//          continue;
895			//    }
896			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
897		}
898
899		return axolotlMessage;
900	}
901
902	private void processSending(final Message message) {
903		executor.execute(new Runnable() {
904			@Override
905			public void run() {
906				MessagePacket packet = mXmppConnectionService.getMessageGenerator()
907						.generateAxolotlChat(message);
908				if (packet == null) {
909					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
910					//mXmppConnectionService.updateConversationUi();
911				} else {
912					Log.d(Config.LOGTAG, "Generated message, caching: " + message.getUuid());
913					messageCache.put(message.getUuid(), packet);
914					mXmppConnectionService.resendMessage(message);
915				}
916			}
917		});
918	}
919
920	public void prepareMessage(Message message) {
921		if (!messageCache.containsKey(message.getUuid())) {
922			boolean newSessions = createSessionsIfNeeded(message.getConversation());
923
924			if (!newSessions) {
925				this.processSending(message);
926			}
927		}
928	}
929
930	public MessagePacket fetchPacketFromCache(Message message) {
931		MessagePacket packet = messageCache.get(message.getUuid());
932		if (packet != null) {
933			Log.d(Config.LOGTAG, "Cache hit: " + message.getUuid());
934			messageCache.remove(message.getUuid());
935		} else {
936			Log.d(Config.LOGTAG, "Cache miss: " + message.getUuid());
937		}
938		return packet;
939	}
940
941	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceiving(XmppAxolotlMessage message) {
942		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
943		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
944				message.getSenderDeviceId());
945
946		XmppAxolotlSession session = sessions.get(senderAddress);
947		if (session == null) {
948			Log.d(Config.LOGTAG, "Account: "+account.getJid()+" No axolotl session found while parsing received message " + message);
949			// TODO: handle this properly
950			session = new XmppAxolotlSession(axolotlStore, senderAddress);
951			sessions.put(senderAddress,session);
952		}
953
954		for (XmppAxolotlMessage.XmppAxolotlMessageHeader header : message.getHeaders()) {
955			if (header.getRecipientDeviceId() == ownDeviceId) {
956				Log.d(Config.LOGTAG, "Found axolotl header matching own device ID, processing...");
957				byte[] payloadKey = session.processReceiving(header);
958				if (payloadKey != null) {
959					Log.d(Config.LOGTAG, "Got payload key from axolotl header. Decrypting message...");
960					plaintextMessage = message.decrypt(session, payloadKey);
961				}
962				Integer preKeyId = session.getPreKeyId();
963				if (preKeyId != null) {
964					publishBundlesIfNeeded();
965					session.resetPreKeyId();
966				}
967				break;
968			}
969		}
970
971		return plaintextMessage;
972	}
973}