AxolotlService.java

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