aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/eu/siacs/conversations/crypto/axolotl/AxolotlService.java
blob: 0061a77a73a604386c4c68c959bc73e467a9ae65 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
package eu.siacs.conversations.crypto.axolotl;

import android.os.Bundle;
import android.security.KeyChain;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.Pair;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.whispersystems.libaxolotl.AxolotlAddress;
import org.whispersystems.libaxolotl.IdentityKey;
import org.whispersystems.libaxolotl.IdentityKeyPair;
import org.whispersystems.libaxolotl.InvalidKeyException;
import org.whispersystems.libaxolotl.InvalidKeyIdException;
import org.whispersystems.libaxolotl.SessionBuilder;
import org.whispersystems.libaxolotl.UntrustedIdentityException;
import org.whispersystems.libaxolotl.ecc.ECPublicKey;
import org.whispersystems.libaxolotl.state.PreKeyBundle;
import org.whispersystems.libaxolotl.state.PreKeyRecord;
import org.whispersystems.libaxolotl.state.SignedPreKeyRecord;
import org.whispersystems.libaxolotl.util.KeyHelper;

import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import eu.siacs.conversations.Config;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.Conversation;
import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.parser.IqParser;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.utils.CryptoHelper;
import eu.siacs.conversations.utils.SerialSingleThreadExecutor;
import eu.siacs.conversations.xml.Element;
import eu.siacs.conversations.xmpp.OnAdvancedStreamFeaturesLoaded;
import eu.siacs.conversations.xmpp.OnIqPacketReceived;
import eu.siacs.conversations.xmpp.jid.InvalidJidException;
import eu.siacs.conversations.xmpp.jid.Jid;
import eu.siacs.conversations.xmpp.stanzas.IqPacket;

public class AxolotlService implements OnAdvancedStreamFeaturesLoaded {

	public static final String PEP_PREFIX = "eu.siacs.conversations.axolotl";
	public static final String PEP_DEVICE_LIST = PEP_PREFIX + ".devicelist";
	public static final String PEP_DEVICE_LIST_NOTIFY = PEP_DEVICE_LIST + "+notify";
	public static final String PEP_BUNDLES = PEP_PREFIX + ".bundles";
	public static final String PEP_VERIFICATION = PEP_PREFIX + ".verification";

	public static final String LOGPREFIX = "AxolotlService";

	public static final int NUM_KEYS_TO_PUBLISH = 100;
	public static final int publishTriesThreshold = 3;

	private final Account account;
	private final XmppConnectionService mXmppConnectionService;
	private final SQLiteAxolotlStore axolotlStore;
	private final SessionMap sessions;
	private final Map<Jid, Set<Integer>> deviceIds;
	private final Map<String, XmppAxolotlMessage> messageCache;
	private final FetchStatusMap fetchStatusMap;
	private final SerialSingleThreadExecutor executor;
	private int numPublishTriesOnEmptyPep = 0;
	private boolean pepBroken = false;

	private AtomicBoolean ownPushPending = new AtomicBoolean(false);

	@Override
	public void onAdvancedStreamFeaturesAvailable(Account account) {
		if (Config.supportOmemo()
				&& account.getXmppConnection() != null
				&& account.getXmppConnection().getFeatures().pep()) {
			publishBundlesIfNeeded(true, false);
		} else {
			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": skipping OMEMO initialization");
		}
	}

	public boolean fetchMapHasErrors(List<Jid> jids) {
		for(Jid jid : jids) {
			if (deviceIds.get(jid) != null) {
				for (Integer foreignId : this.deviceIds.get(jid)) {
					AxolotlAddress address = new AxolotlAddress(jid.toPreppedString(), foreignId);
					if (fetchStatusMap.getAll(address).containsValue(FetchStatus.ERROR)) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public void preVerifyFingerprint(Contact contact, String fingerprint) {
		axolotlStore.preVerifyFingerprint(contact.getAccount(), contact.getJid().toBareJid().toPreppedString(), fingerprint);
	}

	public void preVerifyFingerprint(Account account, String fingerprint) {
		axolotlStore.preVerifyFingerprint(account, account.getJid().toBareJid().toPreppedString(), fingerprint);
	}

	public boolean hasVerifiedKeys(String name) {
		for(XmppAxolotlSession session : this.sessions.getAll(new AxolotlAddress(name,0)).values()) {
			if (session.getTrust().isVerified()) {
				return true;
			}
		}
		return false;
	}

	private static class AxolotlAddressMap<T> {
		protected Map<String, Map<Integer, T>> map;
		protected final Object MAP_LOCK = new Object();

		public AxolotlAddressMap() {
			this.map = new HashMap<>();
		}

		public void put(AxolotlAddress address, T value) {
			synchronized (MAP_LOCK) {
				Map<Integer, T> devices = map.get(address.getName());
				if (devices == null) {
					devices = new HashMap<>();
					map.put(address.getName(), devices);
				}
				devices.put(address.getDeviceId(), value);
			}
		}

		public T get(AxolotlAddress address) {
			synchronized (MAP_LOCK) {
				Map<Integer, T> devices = map.get(address.getName());
				if (devices == null) {
					return null;
				}
				return devices.get(address.getDeviceId());
			}
		}

		public Map<Integer, T> getAll(AxolotlAddress address) {
			synchronized (MAP_LOCK) {
				Map<Integer, T> devices = map.get(address.getName());
				if (devices == null) {
					return new HashMap<>();
				}
				return devices;
			}
		}

		public boolean hasAny(AxolotlAddress address) {
			synchronized (MAP_LOCK) {
				Map<Integer, T> devices = map.get(address.getName());
				return devices != null && !devices.isEmpty();
			}
		}

		public void clear() {
			map.clear();
		}

	}

	private static class SessionMap extends AxolotlAddressMap<XmppAxolotlSession> {
		private final XmppConnectionService xmppConnectionService;
		private final Account account;

		public SessionMap(XmppConnectionService service, SQLiteAxolotlStore store, Account account) {
			super();
			this.xmppConnectionService = service;
			this.account = account;
			this.fillMap(store);
		}

		private void putDevicesForJid(String bareJid, List<Integer> deviceIds, SQLiteAxolotlStore store) {
			for (Integer deviceId : deviceIds) {
				AxolotlAddress axolotlAddress = new AxolotlAddress(bareJid, deviceId);
				IdentityKey identityKey = store.loadSession(axolotlAddress).getSessionState().getRemoteIdentityKey();
				if(Config.X509_VERIFICATION) {
					X509Certificate certificate = store.getFingerprintCertificate(identityKey.getFingerprint().replaceAll("\\s", ""));
					if (certificate != null) {
						Bundle information = CryptoHelper.extractCertificateInformation(certificate);
						try {
							final String cn = information.getString("subject_cn");
							final Jid jid = Jid.fromString(bareJid);
							Log.d(Config.LOGTAG,"setting common name for "+jid+" to "+cn);
							account.getRoster().getContact(jid).setCommonName(cn);
						} catch (final InvalidJidException ignored) {
							//ignored
						}
					}
				}
				this.put(axolotlAddress, new XmppAxolotlSession(account, store, axolotlAddress, identityKey));
			}
		}

		private void fillMap(SQLiteAxolotlStore store) {
			List<Integer> deviceIds = store.getSubDeviceSessions(account.getJid().toBareJid().toPreppedString());
			putDevicesForJid(account.getJid().toBareJid().toPreppedString(), deviceIds, store);
			for (Contact contact : account.getRoster().getContacts()) {
				Jid bareJid = contact.getJid().toBareJid();
				String address = bareJid.toString();
				deviceIds = store.getSubDeviceSessions(address);
				putDevicesForJid(address, deviceIds, store);
			}

		}

		@Override
		public void put(AxolotlAddress address, XmppAxolotlSession value) {
			super.put(address, value);
			value.setNotFresh();
			xmppConnectionService.syncRosterToDisk(account); //TODO why?
		}

		public void put(XmppAxolotlSession session) {
			this.put(session.getRemoteAddress(), session);
		}
	}

	public enum FetchStatus {
		PENDING,
		SUCCESS,
		SUCCESS_VERIFIED,
		TIMEOUT,
		SUCCESS_TRUSTED,
		ERROR
	}

	private static class FetchStatusMap extends AxolotlAddressMap<FetchStatus> {

		public void clearErrorFor(Jid jid) {
			synchronized (MAP_LOCK) {
				Map<Integer, FetchStatus> devices = this.map.get(jid.toBareJid().toPreppedString());
				if (devices == null) {
					return;
				}
				for(Map.Entry<Integer, FetchStatus> entry : devices.entrySet()) {
					if (entry.getValue() == FetchStatus.ERROR) {
						Log.d(Config.LOGTAG,"resetting error for "+jid.toBareJid()+"("+entry.getKey()+")");
						entry.setValue(FetchStatus.TIMEOUT);
					}
				}
			}
		}
	}

	public static String getLogprefix(Account account) {
		return LOGPREFIX + " (" + account.getJid().toBareJid().toString() + "): ";
	}

	public AxolotlService(Account account, XmppConnectionService connectionService) {
		if (Security.getProvider("BC") == null) {
			Security.addProvider(new BouncyCastleProvider());
		}
		this.mXmppConnectionService = connectionService;
		this.account = account;
		this.axolotlStore = new SQLiteAxolotlStore(this.account, this.mXmppConnectionService);
		this.deviceIds = new HashMap<>();
		this.messageCache = new HashMap<>();
		this.sessions = new SessionMap(mXmppConnectionService, axolotlStore, account);
		this.fetchStatusMap = new FetchStatusMap();
		this.executor = new SerialSingleThreadExecutor();
	}

	public String getOwnFingerprint() {
		return axolotlStore.getIdentityKeyPair().getPublicKey().getFingerprint().replaceAll("\\s", "");
	}

	public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status) {
		return axolotlStore.getContactKeysWithTrust(account.getJid().toBareJid().toPreppedString(), status);
	}

	public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, Jid jid) {
		return axolotlStore.getContactKeysWithTrust(jid.toBareJid().toPreppedString(), status);
	}

	public Set<IdentityKey> getKeysWithTrust(FingerprintStatus status, List<Jid> jids) {
		Set<IdentityKey> keys = new HashSet<>();
		for(Jid jid : jids) {
			keys.addAll(axolotlStore.getContactKeysWithTrust(jid.toPreppedString(), status));
		}
		return keys;
	}

	public long getNumTrustedKeys(Jid jid) {
		return axolotlStore.getContactNumTrustedKeys(jid.toBareJid().toPreppedString());
	}

	public boolean anyTargetHasNoTrustedKeys(List<Jid> jids) {
		for(Jid jid : jids) {
			if (axolotlStore.getContactNumTrustedKeys(jid.toBareJid().toPreppedString()) == 0) {
				return true;
			}
		}
		return false;
	}

	private AxolotlAddress getAddressForJid(Jid jid) {
		return new AxolotlAddress(jid.toPreppedString(), 0);
	}

	public Collection<XmppAxolotlSession> findOwnSessions() {
		AxolotlAddress ownAddress = getAddressForJid(account.getJid().toBareJid());
		ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(ownAddress).values());
		Collections.sort(s);
		return s;
	}



	public Collection<XmppAxolotlSession> findSessionsForContact(Contact contact) {
		AxolotlAddress contactAddress = getAddressForJid(contact.getJid());
		ArrayList<XmppAxolotlSession> s = new ArrayList<>(this.sessions.getAll(contactAddress).values());
		Collections.sort(s);
		return s;
	}

	private Set<XmppAxolotlSession> findSessionsForConversation(Conversation conversation) {
		HashSet<XmppAxolotlSession> sessions = new HashSet<>();
		for(Jid jid : conversation.getAcceptedCryptoTargets()) {
			sessions.addAll(this.sessions.getAll(getAddressForJid(jid)).values());
		}
		return sessions;
	}

	private boolean hasAny(Jid jid) {
		return sessions.hasAny(getAddressForJid(jid));
	}

	public boolean isPepBroken() {
		return this.pepBroken;
	}

	public void resetBrokenness() {
		this.pepBroken = false;
		numPublishTriesOnEmptyPep = 0;
	}

	public void clearErrorsInFetchStatusMap(Jid jid) {
		fetchStatusMap.clearErrorFor(jid);
	}

	public void regenerateKeys(boolean wipeOther) {
		axolotlStore.regenerate();
		sessions.clear();
		fetchStatusMap.clear();
		publishBundlesIfNeeded(true, wipeOther);
	}

	public int getOwnDeviceId() {
		return axolotlStore.getLocalRegistrationId();
	}

	public AxolotlAddress getOwnAxolotlAddress() {
		return new AxolotlAddress(account.getJid().toBareJid().toPreppedString(),getOwnDeviceId());
	}

	public Set<Integer> getOwnDeviceIds() {
		return this.deviceIds.get(account.getJid().toBareJid());
	}

	public void registerDevices(final Jid jid, @NonNull final Set<Integer> deviceIds) {
		boolean me = jid.toBareJid().equals(account.getJid().toBareJid());
		if (me && ownPushPending.getAndSet(false)) {
			Log.d(Config.LOGTAG,account.getJid().toBareJid()+": ignoring own device update because of pending push");
			return;
		}
		boolean needsPublishing = me && !deviceIds.contains(getOwnDeviceId());
		if (me) {
			deviceIds.remove(getOwnDeviceId());
		}
		Set<Integer> expiredDevices = new HashSet<>(axolotlStore.getSubDeviceSessions(jid.toBareJid().toPreppedString()));
		expiredDevices.removeAll(deviceIds);
		for (Integer deviceId : expiredDevices) {
			AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
			XmppAxolotlSession session = sessions.get(address);
			if (session != null && session.getFingerprint() != null) {
				if (session.getTrust().isActive()) {
					session.setTrust(session.getTrust().toInactive());
				}
			}
		}
		Set<Integer> newDevices = new HashSet<>(deviceIds);
		for (Integer deviceId : newDevices) {
			AxolotlAddress address = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
			XmppAxolotlSession session = sessions.get(address);
			if (session != null && session.getFingerprint() != null) {
				if (!session.getTrust().isActive()) {
					Log.d(Config.LOGTAG,"reactivating device with fingerprint "+session.getFingerprint());
					session.setTrust(session.getTrust().toActive());
				}
			}
		}
		if (me) {
			if (Config.OMEMO_AUTO_EXPIRY != 0) {
				needsPublishing |= deviceIds.removeAll(getExpiredDevices());
			}
			for (Integer deviceId : deviceIds) {
				AxolotlAddress ownDeviceAddress = new AxolotlAddress(jid.toBareJid().toPreppedString(), deviceId);
				if (sessions.get(ownDeviceAddress) == null) {
					FetchStatus status = fetchStatusMap.get(ownDeviceAddress);
					if (status == null || status == FetchStatus.TIMEOUT) {
						fetchStatusMap.put(ownDeviceAddress, FetchStatus.PENDING);
						this.buildSessionFromPEP(ownDeviceAddress);
					}
				}
			}
			if (needsPublishing) {
				publishOwnDeviceId(deviceIds);
			}
		}
		this.deviceIds.put(jid, deviceIds);
		mXmppConnectionService.updateConversationUi(); //update the lock icon
		mXmppConnectionService.keyStatusUpdated(null);
	}

	public void wipeOtherPepDevices() {
		if (pepBroken) {
			Log.d(Config.LOGTAG, getLogprefix(account) + "wipeOtherPepDevices called, but PEP is broken. Ignoring... ");
			return;
		}
		Set<Integer> deviceIds = new HashSet<>();
		deviceIds.add(getOwnDeviceId());
		IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIds);
		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Wiping all other devices from Pep:" + publish);
		mXmppConnectionService.sendIqPacket(account, publish, null);
	}

	public void distrustFingerprint(final String fingerprint) {
		final String fp = fingerprint.replaceAll("\\s", "");
		final FingerprintStatus fingerprintStatus = axolotlStore.getFingerprintStatus(fp);
		axolotlStore.setFingerprintStatus(fp,fingerprintStatus.toUntrusted());
	}

	public void publishOwnDeviceIdIfNeeded() {
		if (pepBroken) {
			Log.d(Config.LOGTAG, getLogprefix(account) + "publishOwnDeviceIdIfNeeded called, but PEP is broken. Ignoring... ");
			return;
		}
		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveDeviceIds(account.getJid().toBareJid());
		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
			@Override
			public void onIqPacketReceived(Account account, IqPacket packet) {
				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
					Log.d(Config.LOGTAG, getLogprefix(account) + "Timeout received while retrieving own Device Ids.");
				} else {
					Element item = mXmppConnectionService.getIqParser().getItem(packet);
					Set<Integer> deviceIds = mXmppConnectionService.getIqParser().deviceIds(item);
					Log.d(Config.LOGTAG,account.getJid().toBareJid()+": retrieved own device list: "+deviceIds);
					registerDevices(account.getJid().toBareJid(),deviceIds);
				}
			}
		});
	}

	private Set<Integer> getExpiredDevices() {
		Set<Integer> devices = new HashSet<>();
		for(XmppAxolotlSession session : findOwnSessions()) {
			if (session.getTrust().isActive()) {
				long diff = System.currentTimeMillis() - session.getTrust().getLastActivation();
				if (diff > Config.OMEMO_AUTO_EXPIRY) {
					long lastMessageDiff = System.currentTimeMillis() - mXmppConnectionService.databaseBackend.getLastTimeFingerprintUsed(account,session.getFingerprint());
					long hours = Math.round(lastMessageDiff/(1000*60.0*60.0));
					if (lastMessageDiff > Config.OMEMO_AUTO_EXPIRY) {
						devices.add(session.getRemoteAddress().getDeviceId());
						session.setTrust(session.getTrust().toInactive());
						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": added own device " + session.getFingerprint() + " to list of expired devices. Last message received "+hours+" hours ago");
					} else {
						Log.d(Config.LOGTAG,account.getJid().toBareJid()+": own device "+session.getFingerprint()+" was active "+hours+" hours ago");
					}
				}
			}
		}
		return devices;
	}

	public void publishOwnDeviceId(Set<Integer> deviceIds) {
		Set<Integer> deviceIdsCopy = new HashSet<>(deviceIds);
		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "publishing own device ids");
		if (deviceIdsCopy.isEmpty()) {
			if (numPublishTriesOnEmptyPep >= publishTriesThreshold) {
				Log.w(Config.LOGTAG, getLogprefix(account) + "Own device publish attempt threshold exceeded, aborting...");
				pepBroken = true;
				return;
			} else {
				numPublishTriesOnEmptyPep++;
				Log.w(Config.LOGTAG, getLogprefix(account) + "Own device list empty, attempting to publish (try " + numPublishTriesOnEmptyPep + ")");
			}
		} else {
			numPublishTriesOnEmptyPep = 0;
		}
		deviceIdsCopy.add(getOwnDeviceId());
		IqPacket publish = mXmppConnectionService.getIqGenerator().publishDeviceIds(deviceIdsCopy);
		ownPushPending.set(true);
		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
			@Override
			public void onIqPacketReceived(Account account, IqPacket packet) {
				ownPushPending.set(false);
				if (packet.getType() == IqPacket.TYPE.ERROR) {
					pepBroken = true;
					Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing own device id" + packet.findChild("error"));
				}
			}
		});
	}

	public void publishDeviceVerificationAndBundle(final SignedPreKeyRecord signedPreKeyRecord,
												   final Set<PreKeyRecord> preKeyRecords,
												   final boolean announceAfter,
												   final boolean wipe) {
		try {
			IdentityKey axolotlPublicKey = axolotlStore.getIdentityKeyPair().getPublicKey();
			PrivateKey x509PrivateKey = KeyChain.getPrivateKey(mXmppConnectionService, account.getPrivateKeyAlias());
			X509Certificate[] chain = KeyChain.getCertificateChain(mXmppConnectionService, account.getPrivateKeyAlias());
			Signature verifier = Signature.getInstance("sha256WithRSA");
			verifier.initSign(x509PrivateKey,mXmppConnectionService.getRNG());
			verifier.update(axolotlPublicKey.serialize());
			byte[] signature = verifier.sign();
			IqPacket packet = mXmppConnectionService.getIqGenerator().publishVerification(signature, chain, getOwnDeviceId());
			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": publish verification for device "+getOwnDeviceId());
			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
				@Override
				public void onIqPacketReceived(Account account, IqPacket packet) {
					publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announceAfter, wipe);
				}
			});
		} catch (Exception  e) {
			e.printStackTrace();
		}
	}

	public void publishBundlesIfNeeded(final boolean announce, final boolean wipe) {
		if (pepBroken) {
			Log.d(Config.LOGTAG, getLogprefix(account) + "publishBundlesIfNeeded called, but PEP is broken. Ignoring... ");
			return;
		}
		IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(account.getJid().toBareJid(), getOwnDeviceId());
		mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
			@Override
			public void onIqPacketReceived(Account account, IqPacket packet) {

				if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
					return; //ignore timeout. do nothing
				}

				if (packet.getType() == IqPacket.TYPE.ERROR) {
					Element error = packet.findChild("error");
					if (error == null || !error.hasChild("item-not-found")) {
						pepBroken = true;
						Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "request for device bundles came back with something other than item-not-found" + packet);
						return;
					}
				}

				PreKeyBundle bundle = mXmppConnectionService.getIqParser().bundle(packet);
				Map<Integer, ECPublicKey> keys = mXmppConnectionService.getIqParser().preKeyPublics(packet);
				boolean flush = false;
				if (bundle == null) {
					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid bundle:" + packet);
					bundle = new PreKeyBundle(-1, -1, -1, null, -1, null, null, null);
					flush = true;
				}
				if (keys == null) {
					Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received invalid prekeys:" + packet);
				}
				try {
					boolean changed = false;
					// Validate IdentityKey
					IdentityKeyPair identityKeyPair = axolotlStore.getIdentityKeyPair();
					if (flush || !identityKeyPair.getPublicKey().equals(bundle.getIdentityKey())) {
						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding own IdentityKey " + identityKeyPair.getPublicKey() + " to PEP.");
						changed = true;
					}

					// Validate signedPreKeyRecord + ID
					SignedPreKeyRecord signedPreKeyRecord;
					int numSignedPreKeys = axolotlStore.loadSignedPreKeys().size();
					try {
						signedPreKeyRecord = axolotlStore.loadSignedPreKey(bundle.getSignedPreKeyId());
						if (flush
								|| !bundle.getSignedPreKey().equals(signedPreKeyRecord.getKeyPair().getPublicKey())
								|| !Arrays.equals(bundle.getSignedPreKeySignature(), signedPreKeyRecord.getSignature())) {
							Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
							signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
							axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
							changed = true;
						}
					} catch (InvalidKeyIdException e) {
						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding new signedPreKey with ID " + (numSignedPreKeys + 1) + " to PEP.");
						signedPreKeyRecord = KeyHelper.generateSignedPreKey(identityKeyPair, numSignedPreKeys + 1);
						axolotlStore.storeSignedPreKey(signedPreKeyRecord.getId(), signedPreKeyRecord);
						changed = true;
					}

					// Validate PreKeys
					Set<PreKeyRecord> preKeyRecords = new HashSet<>();
					if (keys != null) {
						for (Integer id : keys.keySet()) {
							try {
								PreKeyRecord preKeyRecord = axolotlStore.loadPreKey(id);
								if (preKeyRecord.getKeyPair().getPublicKey().equals(keys.get(id))) {
									preKeyRecords.add(preKeyRecord);
								}
							} catch (InvalidKeyIdException ignored) {
							}
						}
					}
					int newKeys = NUM_KEYS_TO_PUBLISH - preKeyRecords.size();
					if (newKeys > 0) {
						List<PreKeyRecord> newRecords = KeyHelper.generatePreKeys(
								axolotlStore.getCurrentPreKeyId() + 1, newKeys);
						preKeyRecords.addAll(newRecords);
						for (PreKeyRecord record : newRecords) {
							axolotlStore.storePreKey(record.getId(), record);
						}
						changed = true;
						Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Adding " + newKeys + " new preKeys to PEP.");
					}


					if (changed) {
						if (account.getPrivateKeyAlias() != null && Config.X509_VERIFICATION) {
							mXmppConnectionService.publishDisplayName(account);
							publishDeviceVerificationAndBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
						} else {
							publishDeviceBundle(signedPreKeyRecord, preKeyRecords, announce, wipe);
						}
					} else {
						Log.d(Config.LOGTAG, getLogprefix(account) + "Bundle " + getOwnDeviceId() + " in PEP was current");
						if (wipe) {
							wipeOtherPepDevices();
						} else if (announce) {
							Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
							publishOwnDeviceIdIfNeeded();
						}
					}
				} catch (InvalidKeyException e) {
					Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Failed to publish bundle " + getOwnDeviceId() + ", reason: " + e.getMessage());
				}
			}
		});
	}

	private void publishDeviceBundle(SignedPreKeyRecord signedPreKeyRecord,
									 Set<PreKeyRecord> preKeyRecords,
									 final boolean announceAfter,
									 final boolean wipe) {
		IqPacket publish = mXmppConnectionService.getIqGenerator().publishBundles(
				signedPreKeyRecord, axolotlStore.getIdentityKeyPair().getPublicKey(),
				preKeyRecords, getOwnDeviceId());
		Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + ": Bundle " + getOwnDeviceId() + " in PEP not current. Publishing: " + publish);
		mXmppConnectionService.sendIqPacket(account, publish, new OnIqPacketReceived() {
			@Override
			public void onIqPacketReceived(Account account, IqPacket packet) {
				if (packet.getType() == IqPacket.TYPE.RESULT) {
					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Successfully published bundle. ");
					if (wipe) {
						wipeOtherPepDevices();
					} else if (announceAfter) {
						Log.d(Config.LOGTAG, getLogprefix(account) + "Announcing device " + getOwnDeviceId());
						publishOwnDeviceIdIfNeeded();
					}
				} else if (packet.getType() == IqPacket.TYPE.ERROR) {
					pepBroken = true;
					Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while publishing bundle: " + packet.findChild("error"));
				}
			}
		});
	}

	public enum AxolotlCapability {
		FULL,
		MISSING_PRESENCE,
		MISSING_KEYS,
		WRONG_CONFIGURATION,
		NO_MEMBERS
	}

	public boolean isConversationAxolotlCapable(Conversation conversation) {
		return isConversationAxolotlCapableDetailed(conversation).first == AxolotlCapability.FULL;
	}

	public Pair<AxolotlCapability,Jid> isConversationAxolotlCapableDetailed(Conversation conversation) {
		if (conversation.getMode() == Conversation.MODE_SINGLE
				|| (conversation.getMucOptions().membersOnly() && conversation.getMucOptions().nonanonymous())) {
			final List<Jid> jids = getCryptoTargets(conversation);
			for(Jid jid : jids) {
				if (!hasAny(jid) && (!deviceIds.containsKey(jid) || deviceIds.get(jid).isEmpty())) {
					if (conversation.getAccount().getRoster().getContact(jid).mutualPresenceSubscription()) {
						return new Pair<>(AxolotlCapability.MISSING_KEYS,jid);
					} else {
						return new Pair<>(AxolotlCapability.MISSING_PRESENCE,jid);
					}
				}
			}
			if (jids.size() > 0) {
				return new Pair<>(AxolotlCapability.FULL, null);
			} else {
				return new Pair<>(AxolotlCapability.NO_MEMBERS, null);
			}
		} else {
			return new Pair<>(AxolotlCapability.WRONG_CONFIGURATION, null);
		}
	}

	public List<Jid> getCryptoTargets(Conversation conversation) {
		final List<Jid> jids;
		if (conversation.getMode() == Conversation.MODE_SINGLE) {
			jids = Arrays.asList(conversation.getJid().toBareJid());
		} else {
			jids = conversation.getMucOptions().getMembers();
		}
		return jids;
	}

	public FingerprintStatus getFingerprintTrust(String fingerprint) {
		return axolotlStore.getFingerprintStatus(fingerprint);
	}

	public X509Certificate getFingerprintCertificate(String fingerprint) {
		return axolotlStore.getFingerprintCertificate(fingerprint);
	}

	public void setFingerprintTrust(String fingerprint, FingerprintStatus status) {
		axolotlStore.setFingerprintStatus(fingerprint, status);
	}

	private void verifySessionWithPEP(final XmppAxolotlSession session) {
		Log.d(Config.LOGTAG, "trying to verify fresh session (" + session.getRemoteAddress().getName() + ") with pep");
		final AxolotlAddress address = session.getRemoteAddress();
		final IdentityKey identityKey = session.getIdentityKey();
		try {
			IqPacket packet = mXmppConnectionService.getIqGenerator().retrieveVerificationForDevice(Jid.fromString(address.getName()), address.getDeviceId());
			mXmppConnectionService.sendIqPacket(account, packet, new OnIqPacketReceived() {
				@Override
				public void onIqPacketReceived(Account account, IqPacket packet) {
					Pair<X509Certificate[],byte[]> verification = mXmppConnectionService.getIqParser().verification(packet);
					if (verification != null) {
						try {
							Signature verifier = Signature.getInstance("sha256WithRSA");
							verifier.initVerify(verification.first[0]);
							verifier.update(identityKey.serialize());
							if (verifier.verify(verification.second)) {
								try {
									mXmppConnectionService.getMemorizingTrustManager().getNonInteractive().checkClientTrusted(verification.first, "RSA");
									String fingerprint = session.getFingerprint();
									Log.d(Config.LOGTAG, "verified session with x.509 signature. fingerprint was: "+fingerprint);
									setFingerprintTrust(fingerprint, FingerprintStatus.createActiveVerified(true));
									axolotlStore.setFingerprintCertificate(fingerprint, verification.first[0]);
									fetchStatusMap.put(address, FetchStatus.SUCCESS_VERIFIED);
									Bundle information = CryptoHelper.extractCertificateInformation(verification.first[0]);
									try {
										final String cn = information.getString("subject_cn");
										final Jid jid = Jid.fromString(address.getName());
										Log.d(Config.LOGTAG,"setting common name for "+jid+" to "+cn);
										account.getRoster().getContact(jid).setCommonName(cn);
									} catch (final InvalidJidException ignored) {
										//ignored
									}
									finishBuildingSessionsFromPEP(address);
									return;
								} catch (Exception e) {
									Log.d(Config.LOGTAG,"could not verify certificate");
								}
							}
						} catch (Exception e) {
							Log.d(Config.LOGTAG, "error during verification " + e.getMessage());
						}
					} else {
						Log.d(Config.LOGTAG,"no verification found");
					}
					fetchStatusMap.put(address, FetchStatus.SUCCESS);
					finishBuildingSessionsFromPEP(address);
				}
			});
		} catch (InvalidJidException e) {
			fetchStatusMap.put(address, FetchStatus.SUCCESS);
			finishBuildingSessionsFromPEP(address);
		}
	}

	private final Set<Integer> PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT = new HashSet<>();

	private void finishBuildingSessionsFromPEP(final AxolotlAddress address) {
		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), 0);
		Map<Integer, FetchStatus> own = fetchStatusMap.getAll(ownAddress);
		Map<Integer, FetchStatus> remote = fetchStatusMap.getAll(address);
		if (!own.containsValue(FetchStatus.PENDING) && !remote.containsValue(FetchStatus.PENDING)) {
			FetchStatus report = null;
			if (own.containsValue(FetchStatus.SUCCESS) || remote.containsValue(FetchStatus.SUCCESS)) {
				report = FetchStatus.SUCCESS;
			} else if (own.containsValue(FetchStatus.SUCCESS_VERIFIED) || remote.containsValue(FetchStatus.SUCCESS_VERIFIED)) {
				report = FetchStatus.SUCCESS_VERIFIED;
			} else if (own.containsValue(FetchStatus.SUCCESS_TRUSTED) || remote.containsValue(FetchStatus.SUCCESS_TRUSTED)) {
				report = FetchStatus.SUCCESS_TRUSTED;
			} else if (own.containsValue(FetchStatus.ERROR) || remote.containsValue(FetchStatus.ERROR)) {
				report = FetchStatus.ERROR;
			}
			mXmppConnectionService.keyStatusUpdated(report);
		}
		if (Config.REMOVE_BROKEN_DEVICES) {
			Set<Integer> ownDeviceIds = new HashSet<>(getOwnDeviceIds());
			boolean publish = false;
			for (Map.Entry<Integer, FetchStatus> entry : own.entrySet()) {
				int id = entry.getKey();
				if (entry.getValue() == FetchStatus.ERROR && PREVIOUSLY_REMOVED_FROM_ANNOUNCEMENT.add(id) && ownDeviceIds.remove(id)) {
					publish = true;
					Log.d(Config.LOGTAG, account.getJid().toBareJid() + ": error fetching own device with id " + id + ". removing from announcement");
				}
			}
			if (publish) {
				publishOwnDeviceId(ownDeviceIds);
			}
		}
	}

	private void buildSessionFromPEP(final AxolotlAddress address) {
		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Building new session for " + address.toString());
		if (address.equals(getOwnAxolotlAddress())) {
			throw new AssertionError("We should NEVER build a session with ourselves. What happened here?!");
		}

		try {
			IqPacket bundlesPacket = mXmppConnectionService.getIqGenerator().retrieveBundlesForDevice(
					Jid.fromString(address.getName()), address.getDeviceId());
			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Retrieving bundle: " + bundlesPacket);
			mXmppConnectionService.sendIqPacket(account, bundlesPacket, new OnIqPacketReceived() {

				@Override
				public void onIqPacketReceived(Account account, IqPacket packet) {
					if (packet.getType() == IqPacket.TYPE.TIMEOUT) {
						fetchStatusMap.put(address, FetchStatus.TIMEOUT);
					} else if (packet.getType() == IqPacket.TYPE.RESULT) {
						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Received preKey IQ packet, processing...");
						final IqParser parser = mXmppConnectionService.getIqParser();
						final List<PreKeyBundle> preKeyBundleList = parser.preKeys(packet);
						final PreKeyBundle bundle = parser.bundle(packet);
						if (preKeyBundleList.isEmpty() || bundle == null) {
							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "preKey IQ packet invalid: " + packet);
							fetchStatusMap.put(address, FetchStatus.ERROR);
							finishBuildingSessionsFromPEP(address);
							return;
						}
						Random random = new Random();
						final PreKeyBundle preKey = preKeyBundleList.get(random.nextInt(preKeyBundleList.size()));
						if (preKey == null) {
							//should never happen
							fetchStatusMap.put(address, FetchStatus.ERROR);
							finishBuildingSessionsFromPEP(address);
							return;
						}

						final PreKeyBundle preKeyBundle = new PreKeyBundle(0, address.getDeviceId(),
								preKey.getPreKeyId(), preKey.getPreKey(),
								bundle.getSignedPreKeyId(), bundle.getSignedPreKey(),
								bundle.getSignedPreKeySignature(), bundle.getIdentityKey());

						try {
							SessionBuilder builder = new SessionBuilder(axolotlStore, address);
							builder.process(preKeyBundle);
							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, bundle.getIdentityKey());
							sessions.put(address, session);
							if (Config.X509_VERIFICATION) {
								verifySessionWithPEP(session);
							} else {
								FingerprintStatus status = getFingerprintTrust(bundle.getIdentityKey().getFingerprint().replaceAll("\\s",""));
								FetchStatus fetchStatus;
								if (status != null && status.isVerified()) {
									fetchStatus = FetchStatus.SUCCESS_VERIFIED;
								} else if (status != null && status.isTrusted()) {
									fetchStatus = FetchStatus.SUCCESS_TRUSTED;
								} else {
									fetchStatus = FetchStatus.SUCCESS;
								}
								fetchStatusMap.put(address, fetchStatus);
								finishBuildingSessionsFromPEP(address);
							}
						} catch (UntrustedIdentityException | InvalidKeyException e) {
							Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Error building session for " + address + ": "
									+ e.getClass().getName() + ", " + e.getMessage());
							fetchStatusMap.put(address, FetchStatus.ERROR);
							finishBuildingSessionsFromPEP(address);
						}
					} else {
						fetchStatusMap.put(address, FetchStatus.ERROR);
						Log.d(Config.LOGTAG, getLogprefix(account) + "Error received while building session:" + packet.findChild("error"));
						finishBuildingSessionsFromPEP(address);
					}
				}
			});
		} catch (InvalidJidException e) {
			Log.e(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Got address with invalid jid: " + address.getName());
		}
	}

	public Set<AxolotlAddress> findDevicesWithoutSession(final Conversation conversation) {
		Set<AxolotlAddress> addresses = new HashSet<>();
		for(Jid jid : getCryptoTargets(conversation)) {
			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Finding devices without session for " + jid);
			if (deviceIds.get(jid) != null) {
				for (Integer foreignId : this.deviceIds.get(jid)) {
					AxolotlAddress address = new AxolotlAddress(jid.toPreppedString(), foreignId);
					if (sessions.get(address) == null) {
						IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
						if (identityKey != null) {
							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
							XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
							sessions.put(address, session);
						} else {
							Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + jid + ":" + foreignId);
							if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
								addresses.add(address);
							} else {
								Log.d(Config.LOGTAG, getLogprefix(account) + "skipping over " + address + " because it's broken");
							}
						}
					}
				}
			} else {
				Log.w(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Have no target devices in PEP!");
			}
		}
		if (deviceIds.get(account.getJid().toBareJid()) != null) {
			for (Integer ownId : this.deviceIds.get(account.getJid().toBareJid())) {
				AxolotlAddress address = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), ownId);
				if (sessions.get(address) == null) {
					IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
					if (identityKey != null) {
						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already have session for " + address.toString() + ", adding to cache...");
						XmppAxolotlSession session = new XmppAxolotlSession(account, axolotlStore, address, identityKey);
						sessions.put(address, session);
					} else {
						Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Found device " + account.getJid().toBareJid() + ":" + ownId);
						if (fetchStatusMap.get(address) != FetchStatus.ERROR) {
							addresses.add(address);
						} else {
							Log.d(Config.LOGTAG,getLogprefix(account)+"skipping over "+address+" because it's broken");
						}
					}
				}
			}
		}

		return addresses;
	}

	public boolean createSessionsIfNeeded(final Conversation conversation) {
		Log.i(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Creating axolotl sessions if needed...");
		boolean newSessions = false;
		Set<AxolotlAddress> addresses = findDevicesWithoutSession(conversation);
		for (AxolotlAddress address : addresses) {
			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Processing device: " + address.toString());
			FetchStatus status = fetchStatusMap.get(address);
			if (status == null || status == FetchStatus.TIMEOUT) {
				fetchStatusMap.put(address, FetchStatus.PENDING);
				this.buildSessionFromPEP(address);
				newSessions = true;
			} else if (status == FetchStatus.PENDING) {
				newSessions = true;
			} else {
				Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Already fetching bundle for " + address.toString());
			}
		}

		return newSessions;
	}

	public boolean trustedSessionVerified(final Conversation conversation) {
		Set<XmppAxolotlSession> sessions = findSessionsForConversation(conversation);
		sessions.addAll(findOwnSessions());
		boolean verified = false;
		for(XmppAxolotlSession session : sessions) {
			if (session.getTrust().isTrustedAndActive()) {
				if (session.getTrust().getTrust() == FingerprintStatus.Trust.VERIFIED_X509) {
					verified = true;
				} else {
					return false;
				}
			}
		}
		return verified;
	}

	public boolean hasPendingKeyFetches(Account account, List<Jid> jids) {
		AxolotlAddress ownAddress = new AxolotlAddress(account.getJid().toBareJid().toPreppedString(), 0);
		if (fetchStatusMap.getAll(ownAddress).containsValue(FetchStatus.PENDING)) {
			return true;
		}
		for(Jid jid : jids) {
			AxolotlAddress foreignAddress = new AxolotlAddress(jid.toBareJid().toPreppedString(), 0);
			if (fetchStatusMap.getAll(foreignAddress).containsValue(FetchStatus.PENDING)) {
				return true;
			}
		}
		return false;
	}

	@Nullable
	private boolean buildHeader(XmppAxolotlMessage axolotlMessage, Conversation conversation) {
		Set<XmppAxolotlSession> remoteSessions = findSessionsForConversation(conversation);
		Collection<XmppAxolotlSession> ownSessions = findOwnSessions();
		if (remoteSessions.isEmpty()) {
			return false;
		}
		for (XmppAxolotlSession session : remoteSessions) {
			axolotlMessage.addDevice(session);
		}
		for (XmppAxolotlSession session : ownSessions) {
			axolotlMessage.addDevice(session);
		}

		return true;
	}

	@Nullable
	public XmppAxolotlMessage encrypt(Message message) {
		final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().toBareJid(), getOwnDeviceId());
		final String content;
		if (message.hasFileOnRemoteHost()) {
			content = message.getFileParams().url.toString();
		} else {
			content = message.getBody();
		}
		try {
			axolotlMessage.encrypt(content);
		} catch (CryptoFailedException e) {
			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to encrypt message: " + e.getMessage());
			return null;
		}
		if (!buildHeader(axolotlMessage,message.getConversation())) {
			return null;
		}

		return axolotlMessage;
	}

	public void preparePayloadMessage(final Message message, final boolean delay) {
		executor.execute(new Runnable() {
			@Override
			public void run() {
				XmppAxolotlMessage axolotlMessage = encrypt(message);
				if (axolotlMessage == null) {
					mXmppConnectionService.markMessage(message, Message.STATUS_SEND_FAILED);
					//mXmppConnectionService.updateConversationUi();
				} else {
					Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Generated message, caching: " + message.getUuid());
					messageCache.put(message.getUuid(), axolotlMessage);
					mXmppConnectionService.resendMessage(message, delay);
				}
			}
		});
	}

	public void prepareKeyTransportMessage(final Conversation conversation, final OnMessageCreatedCallback onMessageCreatedCallback) {
		executor.execute(new Runnable() {
			@Override
			public void run() {
				final XmppAxolotlMessage axolotlMessage = new XmppAxolotlMessage(account.getJid().toBareJid(), getOwnDeviceId());
				if (buildHeader(axolotlMessage,conversation)) {
					onMessageCreatedCallback.run(axolotlMessage);
				} else {
					onMessageCreatedCallback.run(null);
				}
			}
		});
	}

	public XmppAxolotlMessage fetchAxolotlMessageFromCache(Message message) {
		XmppAxolotlMessage axolotlMessage = messageCache.get(message.getUuid());
		if (axolotlMessage != null) {
			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache hit: " + message.getUuid());
			messageCache.remove(message.getUuid());
		} else {
			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Cache miss: " + message.getUuid());
		}
		return axolotlMessage;
	}

	private XmppAxolotlSession recreateUncachedSession(AxolotlAddress address) {
		IdentityKey identityKey = axolotlStore.loadSession(address).getSessionState().getRemoteIdentityKey();
		return (identityKey != null)
				? new XmppAxolotlSession(account, axolotlStore, address, identityKey)
				: null;
	}

	private XmppAxolotlSession getReceivingSession(XmppAxolotlMessage message) {
		AxolotlAddress senderAddress = new AxolotlAddress(message.getFrom().toPreppedString(),
				message.getSenderDeviceId());
		XmppAxolotlSession session = sessions.get(senderAddress);
		if (session == null) {
			Log.d(Config.LOGTAG, AxolotlService.getLogprefix(account) + "Account: " + account.getJid() + " No axolotl session found while parsing received message " + message);
			session = recreateUncachedSession(senderAddress);
			if (session == null) {
				session = new XmppAxolotlSession(account, axolotlStore, senderAddress);
			}
		}
		return session;
	}

	public XmppAxolotlMessage.XmppAxolotlPlaintextMessage processReceivingPayloadMessage(XmppAxolotlMessage message) {
		XmppAxolotlMessage.XmppAxolotlPlaintextMessage plaintextMessage = null;

		XmppAxolotlSession session = getReceivingSession(message);
		try {
			plaintextMessage = message.decrypt(session, getOwnDeviceId());
			Integer preKeyId = session.getPreKeyId();
			if (preKeyId != null) {
				publishBundlesIfNeeded(false, false);
				session.resetPreKeyId();
			}
		} catch (CryptoFailedException e) {
			Log.w(Config.LOGTAG, getLogprefix(account) + "Failed to decrypt message: " + e.getMessage());
		}

		if (session.isFresh() && plaintextMessage != null) {
			putFreshSession(session);
		}

		return plaintextMessage;
	}

	public XmppAxolotlMessage.XmppAxolotlKeyTransportMessage processReceivingKeyTransportMessage(XmppAxolotlMessage message) {
		XmppAxolotlMessage.XmppAxolotlKeyTransportMessage keyTransportMessage;

		XmppAxolotlSession session = getReceivingSession(message);
		try {
			keyTransportMessage = message.getParameters(session, getOwnDeviceId());
		} catch (CryptoFailedException e) {
			Log.d(Config.LOGTAG,"could not decrypt keyTransport message "+e.getMessage());
			keyTransportMessage = null;
		}

		if (session.isFresh() && keyTransportMessage != null) {
			putFreshSession(session);
		}

		return keyTransportMessage;
	}

	private void putFreshSession(XmppAxolotlSession session) {
		Log.d(Config.LOGTAG,"put fresh session");
		sessions.put(session);
		if (Config.X509_VERIFICATION) {
			if (session.getIdentityKey() != null) {
				verifySessionWithPEP(session);
			} else {
				Log.e(Config.LOGTAG,account.getJid().toBareJid()+": identity key was empty after reloading for x509 verification");
			}
		}
	}
}