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 SQLiteAxolotlStore sqLiteAxolotlStore;
448		private AxolotlAddress remoteAddress;
449
450		public XmppAxolotlSession(SQLiteAxolotlStore store, AxolotlAddress remoteAddress) {
451			this.cipher = new SessionCipher(store, remoteAddress);
452			this.remoteAddress = remoteAddress;
453			this.sqLiteAxolotlStore = store;
454			this.isTrusted = sqLiteAxolotlStore.isTrustedSession(remoteAddress);
455		}
456
457		public void trust() {
458			sqLiteAxolotlStore.setTrustedSession(remoteAddress, true);
459			this.isTrusted = true;
460		}
461
462		public boolean isTrusted() {
463			return this.isTrusted;
464		}
465
466		public byte[] processReceiving(XmppAxolotlMessage.XmppAxolotlMessageHeader incomingHeader) {
467			byte[] plaintext = null;
468			try {
469				try {
470					PreKeyWhisperMessage message = new PreKeyWhisperMessage(incomingHeader.getContents());
471					Log.d(Config.LOGTAG, "PreKeyWhisperMessage ID:" + message.getSignedPreKeyId() + "/" + message.getPreKeyId());
472					plaintext = cipher.decrypt(message);
473				} catch (InvalidMessageException | InvalidVersionException e) {
474					WhisperMessage message = new WhisperMessage(incomingHeader.getContents());
475					plaintext = cipher.decrypt(message);
476				} catch (InvalidKeyException | InvalidKeyIdException | UntrustedIdentityException e) {
477					Log.d(Config.LOGTAG, "Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
478				}
479			} catch (LegacyMessageException | InvalidMessageException e) {
480				Log.d(Config.LOGTAG, "Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
481			} catch (DuplicateMessageException | NoSessionException e) {
482				Log.d(Config.LOGTAG, "Error decrypting axolotl header, "+e.getClass().getName()+": " + e.getMessage());
483			}
484			return plaintext;
485		}
486
487		public XmppAxolotlMessage.XmppAxolotlMessageHeader processSending(byte[] outgoingMessage) {
488			CiphertextMessage ciphertextMessage = cipher.encrypt(outgoingMessage);
489			XmppAxolotlMessage.XmppAxolotlMessageHeader header =
490					new XmppAxolotlMessage.XmppAxolotlMessageHeader(remoteAddress.getDeviceId(),
491							ciphertextMessage.serialize());
492			return header;
493		}
494	}
495
496	private static class AxolotlAddressMap<T> {
497		protected Map<String, Map<Integer, T>> map;
498		protected final Object MAP_LOCK = new Object();
499
500		public AxolotlAddressMap() {
501			this.map = new HashMap<>();
502		}
503
504		public void put(AxolotlAddress address, T value) {
505			synchronized (MAP_LOCK) {
506				Map<Integer, T> devices = map.get(address.getName());
507				if (devices == null) {
508					devices = new HashMap<>();
509					map.put(address.getName(), devices);
510				}
511				devices.put(address.getDeviceId(), value);
512			}
513		}
514
515		public T get(AxolotlAddress address) {
516			synchronized (MAP_LOCK) {
517				Map<Integer, T> devices = map.get(address.getName());
518				if (devices == null) {
519					return null;
520				}
521				return devices.get(address.getDeviceId());
522			}
523		}
524
525		public Map<Integer, T> getAll(AxolotlAddress address) {
526			synchronized (MAP_LOCK) {
527				Map<Integer, T> devices = map.get(address.getName());
528				if (devices == null) {
529					return new HashMap<>();
530				}
531				return devices;
532			}
533		}
534
535		public boolean hasAny(AxolotlAddress address) {
536			synchronized (MAP_LOCK) {
537				Map<Integer, T> devices = map.get(address.getName());
538				return devices != null && !devices.isEmpty();
539			}
540		}
541
542
543	}
544
545	private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
546
547		public SessionMap(SQLiteAxolotlStore store, Account account) {
548			super();
549			this.fillMap(store, account);
550		}
551
552		private void fillMap(SQLiteAxolotlStore store, Account account) {
553			for (Contact contact : account.getRoster().getContacts()) {
554				Jid bareJid = contact.getJid().toBareJid();
555				if (bareJid == null) {
556					continue; // FIXME: handle this?
557				}
558				String address = bareJid.toString();
559				List<Integer> deviceIDs = store.getSubDeviceSessions(address);
560				for (Integer deviceId : deviceIDs) {
561					AxolotlAddress axolotlAddress = new AxolotlAddress(address, deviceId);
562					this.put(axolotlAddress, new XmppAxolotlSession(store, axolotlAddress));
563				}
564			}
565		}
566
567	}
568
569	private static enum FetchStatus {
570		PENDING,
571		SUCCESS,
572		ERROR
573	}
574
575	private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
576
577	}
578
579	public AxolotlService(Account account, XmppConnectionService connectionService) {
580		this.mXmppConnectionService = connectionService;
581		this.account = account;
582		this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
583		this.deviceIds = new HashMap<>();
584		this.messageCache = new HashMap<>();
585		this.sessions = new SessionMap(axolotlStore, account);
586		this.fetchStatusMap = new FetchStatusMap();
587		this.executor = new SerialSingleThreadExecutor();
588		this.ownDeviceId = axolotlStore.getLocalRegistrationId();
589	}
590
591	public void trustSession(AxolotlAddress counterpart) {
592		XmppAxolotlSession session = sessions.get(counterpart);
593		if (session != null) {
594			session.trust();
595		}
596	}
597
598	public boolean isTrustedSession(AxolotlAddress counterpart) {
599		XmppAxolotlSession session = sessions.get(counterpart);
600		return session != null && session.isTrusted();
601	}
602
603	private AxolotlAddress getAddressForJid(Jid jid) {
604		return new AxolotlAddress(jid.toString(), 0);
605	}
606
607	private Set<XmppAxolotlSession> findOwnSessions() {
608		AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
609		Set<XmppAxolotlSession> ownDeviceSessions = new HashSet<>(this.sessions.getAll(ownAddress).values());
610		return ownDeviceSessions;
611	}
612
613	private Set<XmppAxolotlSession> findSessionsforContact(Contact contact) {
614		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
615		Set<XmppAxolotlSession> sessions = new HashSet<>(this.sessions.getAll(contactAddress).values());
616		return sessions;
617	}
618
619	private boolean hasAny(Contact contact) {
620		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
621		return sessions.hasAny(contactAddress);
622	}
623
624	public int getOwnDeviceId() {
625		return ownDeviceId;
626	}
627
628	public void registerDevices(final Jid jid, final Set<Integer> deviceIds) {
629		for(Integer i:deviceIds) {
630			Log.d(Config.LOGTAG, "Adding Device ID:"+ jid + ":"+i);
631		}
632		this.deviceIds.put(jid, deviceIds);
633	}
634
635	public void publishOwnDeviceIdIfNeeded() {
636		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
637		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
638			@Override
639			public void onIqPacketReceived(Account account, IqPacket packet) {
640				Element item = mXmppConnectionService.getIqParser().getItem(packet);
641				Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
642				if (deviceIds == null) {
643					deviceIds = new HashSet<Integer>();
644				}
645				if (!deviceIds.contains(getOwnDeviceId())) {
646					deviceIds.add(getOwnDeviceId());
647					IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
648					Log.d(Config.LOGTAG, "Own device " + getOwnDeviceId() + " not in PEP devicelist. Publishing: " + publish);
649					mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
650						@Override
651						public void onIqPacketReceived(Account account, IqPacket packet) {
652							// TODO: implement this!
653						}
654					});
655				}
656			}
657		});
658	}
659
660	public void publishBundlesIfNeeded() {
661		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), ownDeviceId);
662		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
663			@Override
664			public void onIqPacketReceived(Account account, IqPacket packet) {
665				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
666				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
667				boolean flush = false;
668				if (bundle == null) {
669					Log.e(Config.LOGTAG, "Received invalid bundle:" + packet);
670					bundle = new PreKeyBundle(-1, -1, -1 , null, -1, null, null, null);
671					flush = true;
672				}
673				if (keys == null) {
674					Log.e(Config.LOGTAG, "Received invalid prekeys:" + packet);
675				}
676				try {
677					boolean changed = false;
678					// Validate IdentityKey
679					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
680					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
681						Log.d(Config.LOGTAG, "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
682						changed = true;
683					}
684
685					// Validate signedPreKeyRecord + ID
686					SignedPreKeyRecord signedPreKeyRecord;
687					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
688					try {
689						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
690						if ( flush
691								||!bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
692								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
693							Log.d(Config.LOGTAG, "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
694							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
695							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
696							changed = true;
697						}
698					} catch (InvalidKeyIdException e) {
699						Log.d(Config.LOGTAG, "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
700						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
701						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
702						changed = true;
703					}
704
705					// Validate PreKeys
706					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
707					if (keys != null) {
708						for (Integer id : keys.keySet()) {
709							try {
710								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
711								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
712									preKeyRecords.add(preKeyRecord);
713								}
714							} catch (InvalidKeyIdException ignored) {
715							}
716						}
717					}
718					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
719					if (newKeys > 0) {
720						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
721								axolotlStore.getCurrentPreKeyId()+1, newKeys);
722						preKeyRecords.addAll(newRecords);
723						for (PreKeyRecord record : newRecords) {
724							axolotlStore.storePreKey(record.getId(), record);
725						}
726						changed = true;
727						Log.d(Config.LOGTAG, "Adding " + newKeys + " new preKeys to PEP.");
728					}
729
730
731					if(changed) {
732						IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
733								signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
734								preKeyRecords, ownDeviceId);
735						Log.d(Config.LOGTAG, "Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
736						mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
737							@Override
738							public void onIqPacketReceived(Account account, IqPacket packet) {
739								// TODO: implement this!
740								Log.d(Config.LOGTAG, "Published bundle, got: " + packet);
741							}
742						});
743					}
744				} catch (InvalidKeyException e) {
745						Log.e(Config.LOGTAG, "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
746						return;
747				}
748			}
749		});
750	}
751
752	public boolean isContactAxolotlCapable(Contact contact) {
753		Jid jid = contact.getJid().toBareJid();
754		AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
755		return sessions.hasAny(address) ||
756				( deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
757	}
758
759	private void buildSessionFromPEP(final Conversation conversation, final AxolotlAddress address) {
760		Log.d(Config.LOGTAG, "Building new sesstion for " + address.getDeviceId());
761
762		try {
763			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
764					Jid.fromString(address.getName()), address.getDeviceId());
765			Log.d(Config.LOGTAG, "Retrieving bundle: " + bundlesPacket);
766			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
767				@Override
768				public void onIqPacketReceived(Account account, IqPacket packet) {
769					Log.d(Config.LOGTAG, "Received preKey IQ packet, processing...");
770					final IqParser parser = mXmppConnectionService.getIqParser();
771					final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
772					final PreKeyBundle bundle = parser.bundle(packet);
773					if (preKeyBundleList.isEmpty() || bundle == null) {
774						Log.d(Config.LOGTAG, "preKey IQ packet invalid: " + packet);
775						fetchStatusMap.put(address, FetchStatus.ERROR);
776						return;
777					}
778					Random random = new Random();
779					final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
780					if (preKey == null) {
781						//should never happen
782						fetchStatusMap.put(address, FetchStatus.ERROR);
783						return;
784					}
785
786					final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
787							preKey.getPreKeyId(), preKey.getPreKey(),
788							bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
789							bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
790
791					axolotlStore.saveIdentity(address.getName(), bundle.getIdentityKey());
792
793					try {
794						SessionBuilder builder = new SessionBuilder(axolotlStore, address);
795						builder.process(preKeyBundle);
796						XmppAxolotlSession session = new XmppAxolotlSession(axolotlStore, address);
797						sessions.put(address, session);
798						fetchStatusMap.put(address, FetchStatus.SUCCESS);
799					} catch (UntrustedIdentityException|InvalidKeyException e) {
800						Log.d(Config.LOGTAG, "Error building session for " + address + ": "
801								+ e.getClass().getName() + ", " + e.getMessage());
802						fetchStatusMap.put(address, FetchStatus.ERROR);
803					}
804
805					AxolotlAddress ownAddress = new AxolotlAddress(conversation.getAccount().getJid().toBareJid().toString(),0);
806					AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(),0);
807					if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
808							&& !fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
809						conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_AXOLOTL,
810								new Conversation.OnMessageFound() {
811									@Override
812									public void onMessageFound(Message message) {
813										processSending(message);
814									}
815								});
816					}
817				}
818			});
819		} catch (InvalidJidException e) {
820			Log.e(Config.LOGTAG,"Got address with invalid jid: " + address.getName());
821		}
822	}
823
824	private boolean createSessionsIfNeeded(Conversation conversation) {
825		boolean newSessions = false;
826		Log.d(Config.LOGTAG, "Creating axolotl sessions if needed...");
827		Jid contactJid = conversation.getContact().getJid().toBareJid();
828		Set<AxolotlAddress> addresses = new HashSet<>();
829		if(deviceIds.get(contactJid) != null) {
830			for(Integer foreignId:this.deviceIds.get(contactJid)) {
831				Log.d(Config.LOGTAG, "Found device "+account.getJid().toBareJid()+":"+foreignId);
832				addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
833			}
834		} else {
835			Log.e(Config.LOGTAG, "Have no target devices in PEP!");
836		}
837		Log.d(Config.LOGTAG, "Checking own account "+account.getJid().toBareJid());
838		if(deviceIds.get(account.getJid().toBareJid()) != null) {
839			for(Integer ownId:this.deviceIds.get(account.getJid().toBareJid())) {
840				Log.d(Config.LOGTAG, "Found device "+account.getJid().toBareJid()+":"+ownId);
841				addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
842			}
843		}
844		for (AxolotlAddress address : addresses) {
845			Log.d(Config.LOGTAG, "Processing device: " + address.toString());
846			FetchStatus status = fetchStatusMap.get(address);
847			XmppAxolotlSession session = sessions.get(address);
848			if ( session == null && ( status == null || status == FetchStatus.ERROR) ) {
849				fetchStatusMap.put(address, FetchStatus.PENDING);
850				this.buildSessionFromPEP(conversation,  address);
851				newSessions = true;
852			} else {
853				Log.d(Config.LOGTAG, "Already have session for " +  address.toString());
854			}
855		}
856		return newSessions;
857	}
858
859	@Nullable
860	public XmppAxolotlMessage encrypt(Message message ){
861		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(message.getContact().getJid().toBareJid(),
862				ownDeviceId, message.getBody());
863
864		if(findSessionsforContact(message.getContact()).isEmpty()) {
865			return null;
866		}
867		Log.d(Config.LOGTAG, "Building axolotl foreign headers...");
868		for (XmppAxolotlSession session : findSessionsforContact(message.getContact())) {
869			Log.d(Config.LOGTAG, session.remoteAddress.toString());
870			//if(!session.isTrusted()) {
871			// TODO: handle this properly
872			//              continue;
873			//        }
874			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
875		}
876		Log.d(Config.LOGTAG, "Building axolotl own headers...");
877		for (XmppAxolotlSession session : findOwnSessions()) {
878			Log.d(Config.LOGTAG, session.remoteAddress.toString());
879			//        if(!session.isTrusted()) {
880			// TODO: handle this properly
881			//          continue;
882			//    }
883			axolotlMessage.addHeader(session.processSending(axolotlMessage.getInnerKey()));
884		}
885
886		return axolotlMessage;
887	}
888
889	private void processSending(final Message message) {
890		executor.execute(new Runnable() {
891			@Override
892			public void run() {
893				MessagePacket packet = mXmppConnectionService.getMessageGenerator()
894						.generateAxolotlChat(message);
895				if (packet == null) {
896					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
897					//mXmppConnectionService.updateConversationUi();
898				} else {
899					Log.d(Config.LOGTAG, "Generated message, caching: " + message.getUuid());
900					messageCache.put(message.getUuid(), packet);
901					mXmppConnectionService.resendMessage(message);
902				}
903			}
904		});
905	}
906
907	public void prepareMessage(Message message) {
908		if (!messageCache.containsKey(message.getUuid())) {
909			boolean newSessions = createSessionsIfNeeded(message.getConversation());
910
911			if (!newSessions) {
912				this.processSending(message);
913			}
914		}
915	}
916
917	public MessagePacket fetchPacketFromCache(Message message) {
918		MessagePacket packet = messageCache.get(message.getUuid());
919		if (packet != null) {
920			Log.d(Config.LOGTAG, "Cache hit: " + message.getUuid());
921			messageCache.remove(message.getUuid());
922		} else {
923			Log.d(Config.LOGTAG, "Cache miss: " + message.getUuid());
924		}
925		return packet;
926	}
927
928	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceiving(XmppAxolotlMessage message) {
929		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
930		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
931				message.getSenderDeviceId());
932
933		XmppAxolotlSession session = sessions.get(senderAddress);
934		if (session == null) {
935			Log.d(Config.LOGTAG, "Account: "+account.getJid()+" No axolotl session found while parsing received message " + message);
936			// TODO: handle this properly
937			session = new XmppAxolotlSession(axolotlStore, senderAddress);
938			sessions.put(senderAddress,session);
939		}
940
941		for (XmppAxolotlMessage.XmppAxolotlMessageHeader header : message.getHeaders()) {
942			if (header.getRecipientDeviceId() == ownDeviceId) {
943				Log.d(Config.LOGTAG, "Found axolotl header matching own device ID, processing...");
944				byte[] payloadKey = session.processReceiving(header);
945				if (payloadKey != null) {
946					Log.d(Config.LOGTAG, "Got payload key from axolotl header. Decrypting message...");
947					plaintextMessage = message.decrypt(session, payloadKey);
948				}
949			}
950		}
951
952		return plaintextMessage;
953	}
954}