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.IdentityKey;
10import org.whispersystems.libaxolotl.IdentityKeyPair;
11import org.whispersystems.libaxolotl.InvalidKeyException;
12import org.whispersystems.libaxolotl.InvalidKeyIdException;
13import org.whispersystems.libaxolotl.SessionBuilder;
14import org.whispersystems.libaxolotl.UntrustedIdentityException;
15import org.whispersystems.libaxolotl.ecc.ECPublicKey;
16import org.whispersystems.libaxolotl.state.PreKeyBundle;
17import org.whispersystems.libaxolotl.state.PreKeyRecord;
18import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
19import org.whispersystems.libaxolotl.util.KeyHelper;
20
21import java.security.Security;
22import java.util.Arrays;
23import java.util.HashMap;
24import java.util.HashSet;
25import java.util.List;
26import java.util.Map;
27import java.util.Random;
28import java.util.Set;
29
30import eu.siacs.conversations.Config;
31import eu.siacs.conversations.entities.Account;
32import eu.siacs.conversations.entities.Contact;
33import eu.siacs.conversations.entities.Conversation;
34import eu.siacs.conversations.entities.Message;
35import eu.siacs.conversations.parser.IqParser;
36import eu.siacs.conversations.services.XmppConnectionService;
37import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
38import eu.siacs.conversations.xml.Element;
39import eu.siacs.conversations.xmpp.OnIqPacketReceived;
40import eu.siacs.conversations.xmpp.jid.InvalidJidException;
41import eu.siacs.conversations.xmpp.jid.Jid;
42import eu.siacs.conversations.xmpp.stanzas.IqPacket;
43
44public class AxolotlService {
45
46 public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl";
47 public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist";
48 public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
49
50 public static final String LOGPREFIX = "AxolotlService";
51
52 public static final int NUM_KEYS_TO_PUBLISH = 10;
53
54 private final Account account;
55 private final XmppConnectionService mXmppConnectionService;
56 private final SQLiteAxolotlStore axolotlStore;
57 private final SessionMap sessions;
58 private final Map<Jid, Set<Integer>> deviceIds;
59 private final Map<String, XmppAxolotlMessage> messageCache;
60 private final FetchStatusMap fetchStatusMap;
61 private final SerialSingleThreadExecutor executor;
62
63 private static class AxolotlAddressMap<T> {
64 protected Map<String, Map<Integer, T>> map;
65 protected final Object MAP_LOCK = new Object();
66
67 public AxolotlAddressMap() {
68 this.map = new HashMap<>();
69 }
70
71 public void put(AxolotlAddress address, T value) {
72 synchronized (MAP_LOCK) {
73 Map<Integer, T> devices = map.get(address.getName());
74 if (devices == null) {
75 devices = new HashMap<>();
76 map.put(address.getName(), devices);
77 }
78 devices.put(address.getDeviceId(), value);
79 }
80 }
81
82 public T get(AxolotlAddress address) {
83 synchronized (MAP_LOCK) {
84 Map<Integer, T> devices = map.get(address.getName());
85 if (devices == null) {
86 return null;
87 }
88 return devices.get(address.getDeviceId());
89 }
90 }
91
92 public Map<Integer, T> getAll(AxolotlAddress address) {
93 synchronized (MAP_LOCK) {
94 Map<Integer, T> devices = map.get(address.getName());
95 if (devices == null) {
96 return new HashMap<>();
97 }
98 return devices;
99 }
100 }
101
102 public boolean hasAny(AxolotlAddress address) {
103 synchronized (MAP_LOCK) {
104 Map<Integer, T> devices = map.get(address.getName());
105 return devices != null && !devices.isEmpty();
106 }
107 }
108
109 public void clear() {
110 map.clear();
111 }
112
113 }
114
115 private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
116 private final XmppConnectionService xmppConnectionService;
117 private final Account account;
118
119 public SessionMap(XmppConnectionService service, SQLiteAxolotlStore store, Account account) {
120 super();
121 this.xmppConnectionService = service;
122 this.account = account;
123 this.fillMap(store);
124 }
125
126 private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
127 for (Integer deviceId : deviceIds) {
128 AxolotlAddress axolotlAddress = new AxolotlAddress(bareJid, deviceId);
129 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building session for remote address: " + axolotlAddress.toString());
130 String fingerprint = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey().getFingerprint().replaceAll("\\s", "");
131 this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, fingerprint));
132 }
133 }
134
135 private void fillMap(SQLiteAxolotlStore store) {
136 List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().toBareJid().toString());
137 putDevicesForJid(account.getJid().toBareJid().toString(), deviceIds, store);
138 for (Contact contact : account.getRoster().getContacts()) {
139 Jid bareJid = contact.getJid().toBareJid();
140 if (bareJid == null) {
141 continue; // FIXME: handle this?
142 }
143 String address = bareJid.toString();
144 deviceIds = store.getSubDeviceSessions(address);
145 putDevicesForJid(address, deviceIds, store);
146 }
147
148 }
149
150 @Override
151 public void put(AxolotlAddress address, XmppAxolotlSession value) {
152 super.put(address, value);
153 xmppConnectionService.syncRosterToDisk(account);
154 }
155 }
156
157 private static enum FetchStatus {
158 PENDING,
159 SUCCESS,
160 ERROR
161 }
162
163 private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {
164
165 }
166
167 public static String getLogprefix(Account account) {
168 return LOGPREFIX + " (" + account.getJid().toBareJid().toString() + "): ";
169 }
170
171 public AxolotlService(Account account, XmppConnectionService connectionService) {
172 if (Security.getProvider("BC") == null) {
173 Security.addProvider(new BouncyCastleProvider());
174 }
175 this.mXmppConnectionService = connectionService;
176 this.account = account;
177 this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
178 this.deviceIds = new HashMap<>();
179 this.messageCache = new HashMap<>();
180 this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
181 this.fetchStatusMap = new FetchStatusMap();
182 this.executor = new SerialSingleThreadExecutor();
183 }
184
185 public IdentityKey getOwnPublicKey() {
186 return axolotlStore.getIdentityKeyPair().getPublicKey();
187 }
188
189 public Set<IdentityKey> getKeysWithTrust(SQLiteAxolotlStore.Trust trust) {
190 return axolotlStore.getContactKeysWithTrust(account.getJid().toBareJid().toString(), trust);
191 }
192
193 public Set<IdentityKey> getKeysWithTrust(SQLiteAxolotlStore.Trust trust, Contact contact) {
194 return axolotlStore.getContactKeysWithTrust(contact.getJid().toBareJid().toString(), trust);
195 }
196
197 public long getNumTrustedKeys(Contact contact) {
198 return axolotlStore.getContactNumTrustedKeys(contact.getJid().toBareJid().toString());
199 }
200
201 private AxolotlAddress getAddressForJid(Jid jid) {
202 return new AxolotlAddress(jid.toString(), 0);
203 }
204
205 private Set<XmppAxolotlSession> findOwnSessions() {
206 AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
207 Set<XmppAxolotlSession> ownDeviceSessions = new HashSet<>(this.sessions.getAll(ownAddress).values());
208 return ownDeviceSessions;
209 }
210
211 private Set<XmppAxolotlSession> findSessionsforContact(Contact contact) {
212 AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
213 Set<XmppAxolotlSession> sessions = new HashSet<>(this.sessions.getAll(contactAddress).values());
214 return sessions;
215 }
216
217 private boolean hasAny(Contact contact) {
218 AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
219 return sessions.hasAny(contactAddress);
220 }
221
222 public void regenerateKeys() {
223 axolotlStore.regenerate();
224 sessions.clear();
225 fetchStatusMap.clear();
226 publishBundlesIfNeeded();
227 publishOwnDeviceIdIfNeeded();
228 }
229
230 public int getOwnDeviceId() {
231 return axolotlStore.getLocalRegistrationId();
232 }
233
234 public Set<Integer> getOwnDeviceIds() {
235 return this.deviceIds.get(account.getJid().toBareJid());
236 }
237
238 private void setTrustOnSessions(final Jid jid, @NonNull final Set<Integer> deviceIds,
239 final SQLiteAxolotlStore.Trust from,
240 final SQLiteAxolotlStore.Trust to) {
241 for (Integer deviceId : deviceIds) {
242 AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toString(), deviceId);
243 XmppAxolotlSession session = sessions.get(address);
244 if (session != null && session.getFingerprint() != null
245 && session.getTrust() == from) {
246 session.setTrust(to);
247 }
248 }
249 }
250
251 public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
252 if (jid.toBareJid().equals(account.getJid().toBareJid())) {
253 if (deviceIds.contains(getOwnDeviceId())) {
254 deviceIds.remove(getOwnDeviceId());
255 }
256 for (Integer deviceId : deviceIds) {
257 AxolotlAddress ownDeviceAddress = new AxolotlAddress(jid.toBareJid().toString(), deviceId);
258 if (sessions.get(ownDeviceAddress) == null) {
259 buildSessionFromPEP(null, ownDeviceAddress, false);
260 }
261 }
262 }
263 Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toString()));
264 expiredDevices.removeAll(deviceIds);
265 setTrustOnSessions(jid, expiredDevices, SQLiteAxolotlStore.Trust.TRUSTED,
266 SQLiteAxolotlStore.Trust.INACTIVE);
267 Set<Integer> newDevices = new HashSet<>(deviceIds);
268 setTrustOnSessions(jid, newDevices, SQLiteAxolotlStore.Trust.INACTIVE,
269 SQLiteAxolotlStore.Trust.TRUSTED);
270 this.deviceIds.put(jid, deviceIds);
271 mXmppConnectionService.keyStatusUpdated();
272 publishOwnDeviceIdIfNeeded();
273 }
274
275 public void wipeOtherPepDevices() {
276 Set<Integer> deviceIds = new HashSet<>();
277 deviceIds.add(getOwnDeviceId());
278 IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
279 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Wiping all other devices from Pep:" + publish);
280 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
281 @Override
282 public void onIqPacketReceived(Account account, IqPacket packet) {
283 // TODO: implement this!
284 }
285 });
286 }
287
288 public void purgeKey(IdentityKey identityKey) {
289 axolotlStore.setFingerprintTrust(identityKey.getFingerprint().replaceAll("\\s", ""), SQLiteAxolotlStore.Trust.COMPROMISED);
290 }
291
292 public void publishOwnDeviceIdIfNeeded() {
293 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
294 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
295 @Override
296 public void onIqPacketReceived(Account account, IqPacket packet) {
297 Element item = mXmppConnectionService.getIqParser().getItem(packet);
298 Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
299 if (deviceIds == null) {
300 deviceIds = new HashSet<Integer>();
301 }
302 if (!deviceIds.contains(getOwnDeviceId())) {
303 deviceIds.add(getOwnDeviceId());
304 IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
305 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Own device " + getOwnDeviceId() + " not in PEP devicelist. Publishing: " + publish);
306 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
307 @Override
308 public void onIqPacketReceived(Account account, IqPacket packet) {
309 // TODO: implement this!
310 }
311 });
312 }
313 }
314 });
315 }
316
317 public void publishBundlesIfNeeded() {
318 IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
319 mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
320 @Override
321 public void onIqPacketReceived(Account account, IqPacket packet) {
322 PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
323 Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
324 boolean flush = false;
325 if (bundle == null) {
326 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
327 bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
328 flush = true;
329 }
330 if (keys == null) {
331 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
332 }
333 try {
334 boolean changed = false;
335 // Validate IdentityKey
336 IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
337 if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
338 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
339 changed = true;
340 }
341
342 // Validate signedPreKeyRecord + ID
343 SignedPreKeyRecord signedPreKeyRecord;
344 int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
345 try {
346 signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
347 if (flush
348 || !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
349 || !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
350 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
351 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
352 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
353 changed = true;
354 }
355 } catch (InvalidKeyIdException e) {
356 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
357 signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
358 axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
359 changed = true;
360 }
361
362 // Validate PreKeys
363 Set<PreKeyRecord> preKeyRecords = new HashSet<>();
364 if (keys != null) {
365 for (Integer id : keys.keySet()) {
366 try {
367 PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
368 if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
369 preKeyRecords.add(preKeyRecord);
370 }
371 } catch (InvalidKeyIdException ignored) {
372 }
373 }
374 }
375 int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
376 if (newKeys > 0) {
377 List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
378 axolotlStore.getCurrentPreKeyId() + 1, newKeys);
379 preKeyRecords.addAll(newRecords);
380 for (PreKeyRecord record : newRecords) {
381 axolotlStore.storePreKey(record.getId(), record);
382 }
383 changed = true;
384 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
385 }
386
387
388 if (changed) {
389 IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
390 signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
391 preKeyRecords, getOwnDeviceId());
392 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
393 mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
394 @Override
395 public void onIqPacketReceived(Account account, IqPacket packet) {
396 // TODO: implement this!
397 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Published bundle, got: " + packet);
398 }
399 });
400 }
401 } catch (InvalidKeyException e) {
402 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
403 return;
404 }
405 }
406 });
407 }
408
409 public boolean isContactAxolotlCapable(Contact contact) {
410
411 Jid jid = contact.getJid().toBareJid();
412 AxolotlAddress address = new AxolotlAddress(jid.toString(), 0);
413 return sessions.hasAny(address) ||
414 (deviceIds.containsKey(jid) && !deviceIds.get(jid).isEmpty());
415 }
416
417 public SQLiteAxolotlStore.Trust getFingerprintTrust(String fingerprint) {
418 return axolotlStore.getFingerprintTrust(fingerprint);
419 }
420
421 public void setFingerprintTrust(String fingerprint, SQLiteAxolotlStore.Trust trust) {
422 axolotlStore.setFingerprintTrust(fingerprint, trust);
423 }
424
425 private void buildSessionFromPEP(final Conversation conversation, final AxolotlAddress address, final boolean flushWaitingQueueAfterFetch) {
426 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new sesstion for " + address.getDeviceId());
427
428 try {
429 IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
430 Jid.fromString(address.getName()), address.getDeviceId());
431 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
432 mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {
433 private void finish() {
434 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
435 if (!fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
436 && !fetchStatusMap.getAll(address).containsValue(FetchStatus.PENDING)) {
437 if (flushWaitingQueueAfterFetch && conversation != null) {
438 conversation.findUnsentMessagesWithEncryption(Message.ENCRYPTION_AXOLOTL,
439 new Conversation.OnMessageFound() {
440 @Override
441 public void onMessageFound(Message message) {
442 processSending(message, false);
443 }
444 });
445 }
446 mXmppConnectionService.keyStatusUpdated();
447 }
448 }
449
450 @Override
451 public void onIqPacketReceived(Account account, IqPacket packet) {
452 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
453 final IqParser parser = mXmppConnectionService.getIqParser();
454 final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
455 final PreKeyBundle bundle = parser.bundle(packet);
456 if (preKeyBundleList.isEmpty() || bundle == null) {
457 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
458 fetchStatusMap.put(address, FetchStatus.ERROR);
459 finish();
460 return;
461 }
462 Random random = new Random();
463 final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
464 if (preKey == null) {
465 //should never happen
466 fetchStatusMap.put(address, FetchStatus.ERROR);
467 finish();
468 return;
469 }
470
471 final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
472 preKey.getPreKeyId(), preKey.getPreKey(),
473 bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
474 bundle.getSignedPreKeySignature(), bundle.getIdentityKey());
475
476 axolotlStore.saveIdentity(address.getName(), bundle.getIdentityKey());
477
478 try {
479 SessionBuilder builder = new SessionBuilder(axolotlStore, address);
480 builder.process(preKeyBundle);
481 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey().getFingerprint().replaceAll("\\s", ""));
482 sessions.put(address, session);
483 fetchStatusMap.put(address, FetchStatus.SUCCESS);
484 } catch (UntrustedIdentityException | InvalidKeyException e) {
485 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
486 + e.getClass().getName() + ", " + e.getMessage());
487 fetchStatusMap.put(address, FetchStatus.ERROR);
488 }
489
490 finish();
491 }
492 });
493 } catch (InvalidJidException e) {
494 Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
495 }
496 }
497
498 public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
499 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + conversation.getContact().getJid().toBareJid());
500 Jid contactJid = conversation.getContact().getJid().toBareJid();
501 Set<AxolotlAddress> addresses = new HashSet<>();
502 if (deviceIds.get(contactJid) != null) {
503 for (Integer foreignId : this.deviceIds.get(contactJid)) {
504 AxolotlAddress address = new AxolotlAddress(contactJid.toString(), foreignId);
505 if (sessions.get(address) == null) {
506 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
507 if (identityKey != null) {
508 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
509 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
510 sessions.put(address, session);
511 } else {
512 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + foreignId);
513 addresses.add(new AxolotlAddress(contactJid.toString(), foreignId));
514 }
515 }
516 }
517 } else {
518 Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
519 }
520 if (deviceIds.get(account.getJid().toBareJid()) != null) {
521 for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
522 AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toString(), ownId);
523 if (sessions.get(address) == null) {
524 IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
525 if (identityKey != null) {
526 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
527 XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey.getFingerprint().replaceAll("\\s", ""));
528 sessions.put(address, session);
529 } else {
530 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
531 addresses.add(new AxolotlAddress(account.getJid().toBareJid().toString(), ownId));
532 }
533 }
534 }
535 }
536
537 return addresses;
538 }
539
540 public boolean createSessionsIfNeeded(final Conversation conversation, final boolean flushWaitingQueueAfterFetch) {
541 Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
542 boolean newSessions = false;
543 Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
544 for (AxolotlAddress address : addresses) {
545 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
546 FetchStatus status = fetchStatusMap.get(address);
547 if (status == null || status == FetchStatus.ERROR) {
548 fetchStatusMap.put(address, FetchStatus.PENDING);
549 this.buildSessionFromPEP(conversation, address, flushWaitingQueueAfterFetch);
550 newSessions = true;
551 } else {
552 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
553 }
554 }
555
556 return newSessions;
557 }
558
559 public boolean hasPendingKeyFetches(Conversation conversation) {
560 AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toString(), 0);
561 AxolotlAddress foreignAddress = new AxolotlAddress(conversation.getJid().toBareJid().toString(), 0);
562 return fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)
563 || fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING);
564
565 }
566
567 @Nullable
568 public XmppAxolotlMessage encrypt(Message message) {
569 final String content;
570 if (message.hasFileOnRemoteHost()) {
571 content = message.getFileParams().url.toString();
572 } else {
573 content = message.getBody();
574 }
575 final XmppAxolotlMessage axolotlMessage;
576 try {
577 axolotlMessage = new XmppAxolotlMessage(message.getContact().getJid().toBareJid(),
578 getOwnDeviceId(), content);
579 } catch (CryptoFailedException e) {
580 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
581 return null;
582 }
583
584 if (findSessionsforContact(message.getContact()).isEmpty()) {
585 return null;
586 }
587 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl foreign keyElements...");
588 for (XmppAxolotlSession session : findSessionsforContact(message.getContact())) {
589 Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
590 axolotlMessage.addKeyElement(session.processSending(axolotlMessage.getInnerKey()));
591 }
592 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building axolotl own keyElements...");
593 for (XmppAxolotlSession session : findOwnSessions()) {
594 Log.v(Config.LOGTAG, AxolotlService.getLogprefix(account) + session.getRemoteAddress().toString());
595 axolotlMessage.addKeyElement(session.processSending(axolotlMessage.getInnerKey()));
596 }
597
598 return axolotlMessage;
599 }
600
601 private void processSending(final Message message, final boolean delay) {
602 executor.execute(new Runnable() {
603 @Override
604 public void run() {
605 XmppAxolotlMessage axolotlMessage = encrypt(message);
606 if (axolotlMessage == null) {
607 mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
608 //mXmppConnectionService.updateConversationUi();
609 } else {
610 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
611 messageCache.put(message.getUuid(), axolotlMessage);
612 mXmppConnectionService.resendMessage(message, delay);
613 }
614 }
615 });
616 }
617
618 public void prepareMessage(final Message message, final boolean delay) {
619 if (!messageCache.containsKey(message.getUuid())) {
620 boolean newSessions = createSessionsIfNeeded(message.getConversation(), true);
621 if (!newSessions) {
622 this.processSending(message, delay);
623 }
624 }
625 }
626
627 public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
628 XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
629 if (axolotlMessage != null) {
630 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
631 messageCache.remove(message.getUuid());
632 } else {
633 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
634 }
635 return axolotlMessage;
636 }
637
638 public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceiving(XmppAxolotlMessage message) {
639 XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;
640 AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toString(),
641 message.getSenderDeviceId());
642
643 boolean newSession = false;
644 XmppAxolotlSession session = sessions.get(senderAddress);
645 if (session == null) {
646 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
647 IdentityKey identityKey = axolotlStore.loadSession(senderAddress).getSessionState().getRemoteIdentityKey();
648 if (identityKey != null) {
649 session = new XmppAxolotlSession(account, axolotlStore, senderAddress, identityKey.getFingerprint().replaceAll("\\s", ""));
650 } else {
651 session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
652 }
653 newSession = true;
654 }
655
656 for (XmppAxolotlMessage.XmppAxolotlKeyElement keyElement : message.getKeyElements()) {
657 if (keyElement.getRecipientDeviceId() == getOwnDeviceId()) {
658 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found axolotl keyElement matching own device ID, processing...");
659 byte[] payloadKey = session.processReceiving(keyElement);
660 if (payloadKey != null) {
661 Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got payload key from axolotl keyElement. Decrypting message...");
662 try {
663 plaintextMessage = message.decrypt(session, payloadKey, session.getFingerprint());
664 } catch (CryptoFailedException e) {
665 Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
666 break;
667 }
668 }
669 Integer preKeyId = session.getPreKeyId();
670 if (preKeyId != null) {
671 publishBundlesIfNeeded();
672 session.resetPreKeyId();
673 }
674 break;
675 }
676 }
677
678 if (newSession && plaintextMessage != null) {
679 sessions.put(senderAddress, session);
680 }
681
682 return plaintextMessage;
683 }
684}