AxolotlService.java

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