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