aboutsummaryrefslogtreecommitdiff
path: root/src/omemo/QXmppOmemoManager.cpp
blob: 7b38c73e00dc127769ec67d3282fe6431536dc8e (plain) (blame)
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
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
// SPDX-FileCopyrightText: 2022 Melvin Keskin <melvo@olomono.de>
// SPDX-FileCopyrightText: 2022 Linus Jahn <lnj@kaidan.im>
//
// SPDX-License-Identifier: LGPL-2.1-or-later

#include "QXmppClient.h"
#include "QXmppConstants_p.h"
#include "QXmppOmemoDeviceElement_p.h"
#include "QXmppOmemoDeviceList_p.h"
#include "QXmppOmemoElement_p.h"
#include "QXmppOmemoEnvelope_p.h"
#include "QXmppOmemoIq_p.h"
#include "QXmppOmemoItems_p.h"
#include "QXmppOmemoManager_p.h"
#include "QXmppPubSubEvent.h"
#include "QXmppTrustManager.h"
#include "QXmppUtils.h"

#include <QStringBuilder>

using namespace QXmpp;
using namespace QXmpp::Private;
using namespace QXmpp::Omemo::Private;

using Manager = QXmppOmemoManager;
using ManagerPrivate = QXmppOmemoManagerPrivate;

// default label used for the own device
const auto DEVICE_LABEL = QStringLiteral("QXmpp");

class QXmppOmemoOwnDevicePrivate : public QSharedData
{
public:
    QString label;
    QByteArray keyId;
};

///
/// \class QXmppOmemoOwnDevice
///
/// \brief The QXmppOmemoOwnDevice class represents the \xep{0384, OMEMO Encryption} device of this
/// client instance.
///

///
/// Constructs an OMEMO device for this client instance.
///
QXmppOmemoOwnDevice::QXmppOmemoOwnDevice()
    : d(new QXmppOmemoOwnDevicePrivate)
{
}

/// Copy-constructor.
QXmppOmemoOwnDevice::QXmppOmemoOwnDevice(const QXmppOmemoOwnDevice &other) = default;
/// Move-constructor.
QXmppOmemoOwnDevice::QXmppOmemoOwnDevice(QXmppOmemoOwnDevice &&) noexcept = default;
QXmppOmemoOwnDevice::~QXmppOmemoOwnDevice() = default;
/// Assignment operator.
QXmppOmemoOwnDevice &QXmppOmemoOwnDevice::operator=(const QXmppOmemoOwnDevice &) = default;
/// Move-assignment operator.
QXmppOmemoOwnDevice &QXmppOmemoOwnDevice::operator=(QXmppOmemoOwnDevice &&) = default;

///
/// Returns the human-readable string used to identify the device by users.
///
/// If no label is set, a default-constructed QString is returned.
///
/// \return the label to identify the device
///
QString QXmppOmemoOwnDevice::label() const
{
    return d->label;
}

///
/// Sets an optional human-readable string used to identify the device by users.
///
/// The label should not contain more than 53 characters.
///
/// \param label label to identify the device
///
void QXmppOmemoOwnDevice::setLabel(const QString &label)
{
    d->label = label;
}

///
/// Returns the ID of the public long-term key which never changes.
///
/// \return public long-term key ID
///
QByteArray QXmppOmemoOwnDevice::keyId() const
{
    return d->keyId;
}

///
/// Sets the ID of the public long-term key which never changes.
///
/// \param keyId public long-term key ID
///
void QXmppOmemoOwnDevice::setKeyId(const QByteArray &keyId)
{
    d->keyId = keyId;
}

class QXmppOmemoDevicePrivate : public QSharedData
{
public:
    QString jid;
    TrustLevel trustLevel = TrustLevel::Undecided;
    QString label;
    QByteArray keyId;
};

///
/// \class QXmppOmemoDevice
///
/// \brief The QXmppOmemoDevice class represents a \xep{0384, OMEMO Encryption} device.
///

///
/// Constructs an OMEMO device.
///
QXmppOmemoDevice::QXmppOmemoDevice()
    : d(new QXmppOmemoDevicePrivate)
{
}

/// Copy-constructor.
QXmppOmemoDevice::QXmppOmemoDevice(const QXmppOmemoDevice &other) = default;
/// Move-constructor.
QXmppOmemoDevice::QXmppOmemoDevice(QXmppOmemoDevice &&) noexcept = default;
QXmppOmemoDevice::~QXmppOmemoDevice() = default;
/// Assignment operator.
QXmppOmemoDevice &QXmppOmemoDevice::operator=(const QXmppOmemoDevice &) = default;
/// Move-assignment operator.
QXmppOmemoDevice &QXmppOmemoDevice::operator=(QXmppOmemoDevice &&) = default;

///
/// Returns the device owner's bare JID.
///
/// \return the bare JID
///
QString QXmppOmemoDevice::jid() const
{
    return d->jid;
}

///
/// Sets the device owner's bare JID.
///
/// \param jid bare JID of the device owner
///
void QXmppOmemoDevice::setJid(const QString &jid)
{
    d->jid = jid;
}

///
/// Returns the human-readable string used to identify the device by users.
///
/// If no label is set, a default-constructed QString is returned.
///
/// \return the label to identify the device
///
QString QXmppOmemoDevice::label() const
{
    return d->label;
}

///
/// Sets an optional human-readable string used to identify the device by users.
///
/// The label should not contain more than 53 characters.
///
/// \param label label to identify the device
///
void QXmppOmemoDevice::setLabel(const QString &label)
{
    d->label = label;
}

///
/// Returns the ID of the public long-term key which never changes.
///
/// \return public long-term key ID
///
QByteArray QXmppOmemoDevice::keyId() const
{
    return d->keyId;
}

///
/// Sets the ID of the public long-term key which never changes.
///
/// \param keyId public long-term key ID
///
void QXmppOmemoDevice::setKeyId(const QByteArray &keyId)
{
    d->keyId = keyId;
}

///
/// Returns the trust level of the key.
///
/// \return the key's trust level
///
TrustLevel QXmppOmemoDevice::trustLevel() const
{
    return d->trustLevel;
}

///
/// Sets the trust level of the key.
///
/// \param trustLevel key's trust level
///
void QXmppOmemoDevice::setTrustLevel(TrustLevel trustLevel)
{
    d->trustLevel = trustLevel;
}

///
/// \class QXmppOmemoManager
///
/// The QXmppOmemoManager class manages OMEMO encryption as defined in \xep{0384,
/// OMEMO Encryption}.
///
/// OMEMO uses \xep{0060, Publish-Subscribe} (PubSub) and \xep{0163, Personal Eventing Protocol}
/// (PEP).
/// Thus, they must be supported by the server and the corresponding PubSub manager must be added to
/// the client:
/// \code
/// QXmppPubSubManager *pubSubManager = new QXmppPubSubManager;
/// client->addExtension(pubSubManager);
/// \endcode
///
/// For interacting with the storage, corresponding implementations of the storage interfaces must
/// be instantiated.
/// Those implementations have to be adapted to your storage such as a database.
/// In case you only need memory and no persistent storage, you can use the existing
/// implementations:
/// \code
/// QXmppOmemoStorage *omemoStorage = new QXmppOmemoMemoryStorage;
/// QXmppTrustStorage *trustStorage = new QXmppTrustMemoryStorage;
/// \endcode
///
/// A trust manager using its storage must be added to the client:
/// \code
/// client->addNewExtension<QXmppAtmManager>(trustStorage);
/// \endcode
///
/// Afterwards, the OMEMO manager using its storage must be added to the client:
/// \code
/// auto *manager = client->addNewExtension<QXmppOmemoManager>(omemoStorage);
/// \endcode
///
/// You can set a security policy used by OMEMO.
/// Is is recommended to apply TOAKAFA for good security and usability when using
/// \xep{0450, Automatic Trust Management (ATM)}:
/// \code
/// manager->setSecurityPolicy(QXmpp::Toakafa);
/// \endcode
///
/// \xep{0280, Message Carbons} should be used for delivering messages to all endpoints of a user:
/// \code
/// client->addNewExtension<QXmppCarbonManagerV2>();
/// \endcode
///
/// The old QXmppCarbonManager cannot be used with OMEMO.
///
/// The OMEMO data must be loaded before connecting to the server:
/// \code
///     manager->load();
/// });
/// \endcode
///
/// If no OMEMO data could be loaded (i.e., the result of \c load() is "false"), it must be set up
/// first.
/// That can be done as soon as the user is logged in to the server:
/// \code
/// connect(client, &QXmppClient::connected, this, [=]() {
///     auto future = manager->start();
/// });
/// \endcode
///
/// Once the future is finished and the result is "true", the manager is ready for use.
/// Otherwise, check the logging output for details.
///
/// By default, stanzas are only sent to devices having keys with the following trust levels:
/// \code
/// QXmpp::TrustLevel::AutomaticallyTrusted | QXmpp::TrustLevel::ManuallyTrusted
/// | QXmpp::TrustLevel::Authenticated
/// \endcode
/// That behavior can be changed for each message being sent by specifying the
/// accepted trust levels:
/// \code
/// QXmppSendStanzaParams params;
/// params.setAcceptedTrustLevels(QXmpp::TrustLevel::Authenticated)
/// client->send(stanza, params);
/// \endcode
///
/// Stanzas can be encrypted for multiple JIDs which is needed in group chats:
/// \code
/// QXmppSendStanzaParams params;
/// params.setEncryptionJids({ "alice@example.org", "bob@example.com" })
/// client->send(stanza, params);
/// \endcode
///
/// \warning THIS API IS NOT FINALIZED YET!
///
/// \ingroup Managers
///
/// \since QXmpp 1.5
///

///
/// \typedef QXmppOmemoManager::Result
///
/// Contains QXmpp::Success for success or an QXmppStanza::Error for an error.
///

///
/// Constructs an OMEMO manager.
///
/// \param omemoStorage storage used to store all OMEMO data
///
QXmppOmemoManager::QXmppOmemoManager(QXmppOmemoStorage *omemoStorage)
    : d(new ManagerPrivate(this, omemoStorage))
{
    d->ownDevice.label = DEVICE_LABEL;
    d->init();
    d->schedulePeriodicTasks();
}

QXmppOmemoManager::~QXmppOmemoManager() = default;

///
/// Loads all locally stored OMEMO data.
///
/// This should be called after starting the client and before the login.
/// It must only be called after \c setUp() has been called once for the user
/// during one of the past login session.
/// It does not need to be called if setUp() has been called during the current
/// login session.
///
/// \see QXmppOmemoManager::setUp()
///
/// \return whether everything is loaded successfully
///
QXmppTask<bool> Manager::load()
{
    QXmppPromise<bool> interface;

    auto future = d->omemoStorage->allData();
    future.then(this, [=](QXmppOmemoStorage::OmemoData omemoData) mutable {
        const auto &optionalOwnDevice = omemoData.ownDevice;
        if (optionalOwnDevice) {
            d->ownDevice = *optionalOwnDevice;
        } else {
            debug("Device could not be loaded because it is not stored");
            interface.finish(false);
            return;
        }

        const auto &signedPreKeyPairs = omemoData.signedPreKeyPairs;
        if (signedPreKeyPairs.isEmpty()) {
            warning("Signed Pre keys could not be loaded because none is stored");
            interface.finish(false);
            return;
        } else {
            d->signedPreKeyPairs = signedPreKeyPairs;
            d->renewSignedPreKeyPairs();
        }

        const auto &preKeyPairs = omemoData.preKeyPairs;
        if (preKeyPairs.isEmpty()) {
            warning("Pre keys could not be loaded because none is stored");
            interface.finish(false);
            return;
        } else {
            d->preKeyPairs = preKeyPairs;
        }

        d->devices = omemoData.devices;
        d->removeDevicesRemovedFromServer();

        d->isStarted = true;
        interface.finish(true);
    });

    return interface.task();
}

///
/// Sets up all OMEMO data locally and on the server.
///
/// The user must be logged in while calling this.
///
/// \return whether everything is set up successfully
///
QXmppTask<bool> Manager::setUp()
{
    QXmppPromise<bool> interface;

    auto future = d->setUpDeviceId();
    future.then(this, [=](bool isDeviceIdSetUp) mutable {
        if (isDeviceIdSetUp) {
            // The identity key pair in its deserialized form is not stored as a
            // member variable because it is only needed by
            // updateSignedPreKeyPair().
            RefCountedPtr<ratchet_identity_key_pair> identityKeyPair;

            if (d->setUpIdentityKeyPair(identityKeyPair.ptrRef()) &&
                d->updateSignedPreKeyPair(identityKeyPair.get()) &&
                d->updatePreKeyPairs(PRE_KEY_INITIAL_CREATION_COUNT)) {
                auto future = d->omemoStorage->setOwnDevice(d->ownDevice);
                future.then(this, [=]() mutable {
                    auto future = d->publishOmemoData();
                    future.then(this, [=](bool isPublished) mutable {
                        d->isStarted = isPublished;
                        interface.finish(std::move(isPublished));
                    });
                });
            } else {
                interface.finish(false);
            }
        } else {
            interface.finish(false);
        }
    });

    return interface.task();
}

///
/// Returns the key of this client instance.
///
/// \return the own key
///
QXmppTask<QByteArray> Manager::ownKey()
{
    return d->trustManager->ownKey(ns_omemo_2);
}

///
/// Returns the JIDs of all key owners mapped to the IDs of their keys with
/// specific trust levels.
///
/// If no trust levels are passed, all keys are returned.
///
/// This should be called in order to get all stored keys which can be more than
/// the stored devices because of trust decisions made without a published or
/// received device.
///
/// \param trustLevels trust levels of the keys
///
/// \return the key owner JIDs mapped to their keys with specific trust levels
///
QXmppTask<QHash<QXmpp::TrustLevel, QMultiHash<QString, QByteArray>>> Manager::keys(QXmpp::TrustLevels trustLevels)
{
    return d->trustManager->keys(ns_omemo_2, trustLevels);
}

///
/// Returns the IDs of keys mapped to their trust levels for specific key
/// owners.
///
/// If no trust levels are passed, all keys for jids are returned.
///
/// This should be called in order to get the stored keys which can be more than
/// the stored devices because of trust decisions made without a published or
/// received device.
///
/// \param jids key owners' bare JIDs
/// \param trustLevels trust levels of the keys
///
/// \return the key IDs mapped to their trust levels for specific key owners
///
QXmppTask<QHash<QString, QHash<QByteArray, QXmpp::TrustLevel>>> Manager::keys(const QList<QString> &jids, QXmpp::TrustLevels trustLevels)
{
    return d->trustManager->keys(ns_omemo_2, jids, trustLevels);
}

///
/// Changes the label of the own (this client instance's current user's) device.
///
/// The label is a human-readable string used to identify the device by users.
///
/// If the OMEMO manager is not started yet, the device label is only changed
/// locally in memory.
/// It is stored persistently in the OMEMO storage and updated on the
/// server if the OMEMO manager is already started or once it is.
///
/// \param deviceLabel own device's label
///
/// \return whether the action was successful
///
QXmppTask<bool> Manager::changeDeviceLabel(const QString &deviceLabel)
{
    return d->changeDeviceLabel(deviceLabel);
}

///
/// Returns the maximum count of devices stored per JID.
///
/// If more devices than that maximum are received for one JID from a server,
/// they will not be stored locally and thus not used for encryption.
///
/// \return the maximum count of devices stored per JID
///
int Manager::maximumDevicesPerJid() const
{
    return d->maximumDevicesPerJid;
}

///
/// Sets the maximum count of devices stored per JID.
///
/// If more devices than that maximum are received for one JID from a server,
/// they will not be stored locally and thus not used for encryption.
///
/// \param maximum maximum count of devices stored per JID
///
void Manager::setMaximumDevicesPerJid(int maximum)
{
    d->maximumDevicesPerJid = maximum;
}

///
/// Returns the maximum count of devices for whom a stanza is encrypted.
///
/// If more devices than that maximum are stored for all addressed recipients of
/// a stanza, the stanza will only be encrypted for first devices until the
/// maximum is reached.
///
/// \return the maximum count of devices for whom a stanza is encrypted
///
int Manager::maximumDevicesPerStanza() const
{
    return d->maximumDevicesPerStanza;
}

/// Sets the maximum count of devices for whom a stanza is encrypted.
///
/// If more devices than that maximum are stored for all addressed recipients of
/// a stanza, the stanza will only be encrypted for first devices until the
/// maximum is reached.
///
/// \param maximum maximum count of devices for whom a stanza is encrypted
///
void Manager::setMaximumDevicesPerStanza(int maximum)
{
    d->maximumDevicesPerStanza = maximum;
}

///
/// Requests device lists from contacts and stores them locally.
///
/// The user must be logged in while calling this.
/// The JID of the current user must not be passed.
///
/// \param jids JIDs of the contacts whose device lists are being requested
///
/// \return the results of the requests for each JID
///
QXmppTask<QVector<Manager::DevicesResult>> Manager::requestDeviceLists(const QList<QString> &jids)
{
    if (const auto jidsCount = jids.size()) {
        struct State
        {
            int processed = 0;
            int jidsCount = 0;
            QXmppPromise<QVector<Manager::DevicesResult>> interface;
            QVector<Manager::DevicesResult> devicesResults;
        };

        auto state = std::make_shared<State>();
        state->jidsCount = jids.count();

        for (const auto &jid : jids) {
            Q_ASSERT_X(jid != d->ownBareJid(), "Requesting contact's device list", "Own JID passed");

            auto future = d->requestDeviceList(jid);
            future.then(this, [jid, state](auto result) mutable {
                state->devicesResults << DevicesResult {
                    jid,
                    mapSuccess(std::move(result), [](QXmppOmemoDeviceListItem) { return Success(); })
                };

                if (++(state->processed) == state->jidsCount) {
                    state->interface.finish(std::move(state->devicesResults));
                }
            });
        }
        return state->interface.task();
    }
    return makeReadyTask(QVector<Manager::DevicesResult>());
}

///
/// Subscribes the current user's resource to device lists manually.
///
/// This should be called after each login and only for contacts without
/// presence subscription because their device lists are not automatically
/// subscribed.
/// The user must be logged in while calling this.
///
/// Call \c QXmppOmemoManager::unsubscribeFromDeviceLists() before logout.
///
/// \param jids JIDs of the contacts whose device lists are being subscribed
///
/// \return the results of the subscription for each JID
///
QXmppTask<QVector<Manager::DevicesResult>> Manager::subscribeToDeviceLists(const QList<QString> &jids)
{
    if (const auto jidsCount = jids.size()) {
        struct State
        {
            int processed = 0;
            int jidsCount = 0;
            QXmppPromise<QVector<Manager::DevicesResult>> interface;
            QVector<Manager::DevicesResult> devicesResults;
        };

        auto state = std::make_shared<State>();
        state->jidsCount = jids.size();

        for (const auto &jid : jids) {
            d->subscribeToDeviceList(jid).then(this, [state, jid](QXmppPubSubManager::Result result) mutable {
                Manager::DevicesResult devicesResult;
                devicesResult.jid = jid;
                devicesResult.result = result;
                state->devicesResults << devicesResult;

                if (++(state->processed) == state->jidsCount) {
                    state->interface.finish(std::move(state->devicesResults));
                }
            });
        }
        return state->interface.task();
    }
    return makeReadyTask(QVector<Manager::DevicesResult>());
}

///
/// Unsubscribes the current user's resource from all device lists that were
/// manually subscribed by \c QXmppOmemoManager::subscribeToDeviceList().
///
/// This should be called before each logout.
/// The user must be logged in while calling this.
///
/// \return the results of the unsubscription for each JID
///
QXmppTask<QVector<Manager::DevicesResult>> Manager::unsubscribeFromDeviceLists()
{
    return d->unsubscribeFromDeviceLists(d->jidsOfManuallySubscribedDevices);
}

///
/// Returns the device of this client instance's current user.
///
/// \return the own device
///
QXmppOmemoOwnDevice Manager::ownDevice()
{
    const auto &ownDevice = d->ownDevice;

    QXmppOmemoOwnDevice device;
    device.setLabel(ownDevice.label);
    device.setKeyId(ownDevice.publicIdentityKey);

    return device;
}

/// Returns all locally stored devices except the own device.
///
/// Only devices that have been received after subscribing the corresponding
/// device lists on the server are stored locally.
/// Thus, only those are returned.
/// Call \c QXmppOmemoManager::subscribeToDeviceLists() for contacts without
/// presence subscription before.
///
/// /\return all devices except the own device
///
QXmppTask<QVector<QXmppOmemoDevice>> Manager::devices()
{
    return devices(d->devices.keys());
}

///
/// Returns locally stored devices except the own device.
///
/// Only devices that have been received after subscribing the corresponding
/// device lists on the server are stored locally.
/// Thus, only those are returned.
/// Call \c QXmppOmemoManager::subscribeToDeviceLists() for contacts without
/// presence subscription before.
///
/// \param jids JIDs whose devices are being retrieved
///
/// \return all devices of the passed JIDs
///
QXmppTask<QVector<QXmppOmemoDevice>> Manager::devices(const QList<QString> &jids)
{
    QXmppPromise<QVector<QXmppOmemoDevice>> interface;

    auto future = keys(jids);
    future.then(this, [=](QHash<QString, QHash<QByteArray, TrustLevel>> keys) mutable {
        QVector<QXmppOmemoDevice> devices;

        for (const auto &jid : jids) {
            const auto &storedDevices = d->devices.value(jid);
            const auto &storedKeys = keys.value(jid);

            for (const auto &storedDevice : storedDevices) {
                const auto &keyId = storedDevice.keyId;

                QXmppOmemoDevice device;
                device.setJid(jid);
                device.setLabel(storedDevice.label);

                if (!keyId.isEmpty()) {
                    device.setKeyId(keyId);
                    device.setTrustLevel(storedKeys.value(keyId));
                }

                devices.append(device);
            }
        }

        interface.finish(std::move(devices));
    });

    return interface.task();
}

///
/// Removes all devices of a contact and the subscription to the contact's
/// device list.
///
/// This should be called after removing a contact.
/// The JID of the current user must not be passed.
/// Use \c QXmppOmemoManager::resetAll() in order to remove all devices of the
/// user.
///
/// \param jid JID of the contact whose devices are being removed
///
/// \return the result of the contact device removals
///
QXmppTask<QXmppPubSubManager::Result> Manager::removeContactDevices(const QString &jid)
{
    QXmppPromise<QXmppPubSubManager::Result> interface;

    Q_ASSERT_X(jid != d->ownBareJid(), "Removing contact device", "Own JID passed");

    auto future = d->unsubscribeFromDeviceList(jid);
    future.then(this, [=](QXmppPubSubManager::Result result) mutable {
        if (std::holds_alternative<QXmppError>(result)) {
            warning("Contact '" % jid % "' could not be removed because the device list subscription could not be removed");
            interface.finish(std::move(result));
        } else {
            d->devices.remove(jid);

            auto future = d->omemoStorage->removeDevices(jid);
            future.then(this, [=]() mutable {
                auto future = d->trustManager->removeKeys(ns_omemo_2, jid);
                future.then(this, [=]() mutable {
                    interface.finish(std::move(result));
                    Q_EMIT devicesRemoved(jid);
                });
            });
        }
    });

    return interface.task();
}

///
/// Sets the trust levels keys must have in order to build sessions for their
/// devices.
///
/// \param trustLevels trust levels of the keys used for building sessions
///
void Manager::setAcceptedSessionBuildingTrustLevels(QXmpp::TrustLevels trustLevels)
{
    d->acceptedSessionBuildingTrustLevels = trustLevels;
}

///
/// Returns the trust levels keys must have in order to build sessions for their
/// devices.
///
/// \return the trust levels of the keys used for building sessions
///
TrustLevels Manager::acceptedSessionBuildingTrustLevels()
{
    return d->acceptedSessionBuildingTrustLevels;
}

///
/// Sets whether sessions are built when new devices are received from the
/// server.
///
/// This can be used to not call \c QXmppOmemoManager::buildMissingSessions
/// manually.
/// But it should not be used before the initial setup and storing lots of
/// devices locally.
/// Otherwise, it could lead to a massive computation and network load when
/// there are many devices for whom sessions are built.
///
/// \see QXmppOmemoManager::buildMissingSessions
///
/// \param isNewDeviceAutoSessionBuildingEnabled whether sessions are built for
///        incoming devices
///
void Manager::setNewDeviceAutoSessionBuildingEnabled(bool isNewDeviceAutoSessionBuildingEnabled)
{
    d->isNewDeviceAutoSessionBuildingEnabled = isNewDeviceAutoSessionBuildingEnabled;
}

///
/// Returns whether sessions are built when new devices are received from the
/// server.
///
/// \see QXmppOmemoManager::setNewDeviceAutoSessionBuildingEnabled
///
/// \return whether sessions are built for incoming devices
///
bool Manager::isNewDeviceAutoSessionBuildingEnabled()
{
    return d->isNewDeviceAutoSessionBuildingEnabled;
}

///
/// Builds sessions manually with devices for whom no sessions are available.
///
/// Usually, sessions are built during sending a first message to a device or
/// after a first message is received from a device.
/// This can be called in order to speed up the sending of a message.
/// If this method is called before sending the first message, all sessions can
/// be built and when the first message is sent, the message has only be
/// encrypted.
/// Especially chats with multiple devices, that can decrease the noticeable
/// time a user has to wait for sending a message.
/// Additionally, the keys are automatically retrieved from the server which is
/// helpful in order to get them when calling \c QXmppOmemoManager::devices().
///
/// The user must be logged in while calling this.
///
/// \param jids JIDs of the device owners for whom the sessions are built
///
QXmppTask<void> Manager::buildMissingSessions(const QList<QString> &jids)
{
    QXmppPromise<void> interface;

    auto &devices = d->devices;
    auto devicesCount = 0;

    for (const auto &jid : jids) {
        // Do not exceed the maximum of manageable devices.
        if (devicesCount > d->maximumDevicesPerStanza - devicesCount) {
            warning("Sessions could not be built for all JIDs because their devices are "
                    "altogether more than the maximum of manageable devices " %
                    QString::number(d->maximumDevicesPerStanza) %
                    u" - Use QXmppOmemoManager::setMaximumDevicesPerStanza() to increase the maximum");
            break;
        } else {
            devicesCount += devices.value(jid).size();
        }
    }

    if (devicesCount) {
        auto processedDevicesCount = std::make_shared<int>(0);

        for (const auto &jid : jids) {
            auto &processedDevices = devices[jid];

            for (auto itr = processedDevices.begin(); itr != processedDevices.end(); ++itr) {
                const auto &deviceId = itr.key();
                auto &device = itr.value();

                if (device.session.isEmpty()) {
                    auto future = d->buildSessionWithDeviceBundle(jid, deviceId, device);
                    future.then(this, [=](auto) mutable {
                        if (++(*processedDevicesCount) == devicesCount) {
                        }
                    });
                } else if (++(*processedDevicesCount) == devicesCount) {
                }
            }
        }
    } else {
    }

    return interface.task();
}

///
/// Resets all OMEMO data for this device and the trust data used by OMEMO.
///
/// ATTENTION: This should only be called when an account is removed locally or
/// if there are unrecoverable problems with the OMEMO setup of this device.
///
/// The data on the server for other own devices is not removed.
/// Call \c resetAll() for that purpose.
///
/// The user must be logged in while calling this.
///
/// Call \c setUp() once this method is finished if you want to set up
/// everything again for this device.
/// Existing sessions are reset, which might lead to undecryptable incoming
/// stanzas until everything is set up again.
///
QXmppTask<bool> Manager::resetOwnDevice()
{
    return d->resetOwnDevice();
}

///
/// Resets all OMEMO data for all own devices and the trust data used by OMEMO.
///
/// ATTENTION: This should only be called if there is a certain reason for it
/// since it deletes the data for this device and for other own devices from the
/// server.
///
/// Call \c resetOwnDevice() if you only want to delete the OMEMO data for this
/// device.
///
/// The user must be logged in while calling this.
///
/// Call \c setUp() once this method is finished if you want to set up
/// everything again.
/// Existing sessions are reset, which might lead to undecryptable incoming
/// stanzas until everything is set up again.
///
QXmppTask<bool> Manager::resetAll()
{
    return d->resetAll();
}

///
/// Sets the security policy used by this E2EE extension.
///
/// \param securityPolicy security policy being set
///
QXmppTask<void> Manager::setSecurityPolicy(QXmpp::TrustSecurityPolicy securityPolicy)
{
    return d->trustManager->setSecurityPolicy(ns_omemo_2, securityPolicy);
}

///
/// Returns the security policy used by this E2EE extension.
///
/// \return the used security policy
///
QXmppTask<QXmpp::TrustSecurityPolicy> Manager::securityPolicy()
{
    return d->trustManager->securityPolicy(ns_omemo_2);
}

///
/// Sets the trust level of keys.
///
/// If a key is not stored, it is added to the storage.
///
/// \param keyIds key owners' bare JIDs mapped to the IDs of their keys
/// \param trustLevel trust level being set
///
QXmppTask<void> Manager::setTrustLevel(const QMultiHash<QString, QByteArray> &keyIds, QXmpp::TrustLevel trustLevel)
{
    return d->trustManager->setTrustLevel(ns_omemo_2, keyIds, trustLevel);
}

///
/// Returns the trust level of a key.
///
/// If the key is not stored, the trust in that key is undecided.
///
/// \param keyOwnerJid key owner's bare JID
/// \param keyId ID of the key
///
/// \return the key's trust level
///
QXmppTask<QXmpp::TrustLevel> Manager::trustLevel(const QString &keyOwnerJid, const QByteArray &keyId)
{
    return d->trustManager->trustLevel(ns_omemo_2, keyOwnerJid, keyId);
}

/// \cond
QXmppTask<QXmppE2eeExtension::MessageEncryptResult> Manager::encryptMessage(QXmppMessage &&message, const std::optional<QXmppSendStanzaParams> &params)
{
    QVector<QString> recipientJids;
    std::optional<TrustLevels> acceptedTrustLevels;

    if (params) {
        recipientJids = params->encryptionJids();
        acceptedTrustLevels = params->acceptedTrustLevels();
    }

    if (recipientJids.isEmpty()) {
        recipientJids.append(QXmppUtils::jidToBareJid(message.to()));
    }

    if (!acceptedTrustLevels) {
        acceptedTrustLevels = ACCEPTED_TRUST_LEVELS;
    }

    return d->encryptMessageForRecipients(std::move(message), recipientJids, *acceptedTrustLevels);
}

QXmppTask<QXmppE2eeExtension::MessageDecryptResult> QXmppOmemoManager::decryptMessage(QXmppMessage &&message)
{
    if (!d->isStarted) {
        return makeReadyTask<MessageDecryptResult>(QXmppError {
            QStringLiteral("OMEMO manager must be started before decrypting"),
            SendError::EncryptionError });
    }

    auto omemoElement = message.omemoElement();
    if (!omemoElement) {
        return makeReadyTask<MessageDecryptResult>(NotEncrypted());
    }

    return chain<MessageDecryptResult>(d->decryptMessage(message), this, [](std::optional<QXmppMessage> message) -> MessageDecryptResult {
        if (message) {
            return std::move(*message);
        }
        return QXmppError {
            QStringLiteral("Couldn't decrypt message"),
            {}
        };
    });
}

QXmppTask<QXmppE2eeExtension::IqEncryptResult> Manager::encryptIq(QXmppIq &&iq, const std::optional<QXmppSendStanzaParams> &params)
{
    QXmppPromise<QXmppE2eeExtension::IqEncryptResult> interface;

    if (!d->isStarted) {
        interface.finish(QXmppError {
            QStringLiteral("OMEMO manager must be started before encrypting"),
            SendError::EncryptionError });
    } else {
        std::optional<TrustLevels> acceptedTrustLevels;

        if (params) {
            acceptedTrustLevels = params->acceptedTrustLevels();
        }

        if (!acceptedTrustLevels) {
            acceptedTrustLevels = ACCEPTED_TRUST_LEVELS;
        }

        auto future = d->encryptStanza(iq, { QXmppUtils::jidToBareJid(iq.to()) }, *acceptedTrustLevels);
        future.then(this, [=, iq = std::move(iq)](std::optional<QXmppOmemoElement> omemoElement) mutable {
            if (!omemoElement) {
                interface.finish(QXmppError {
                    QStringLiteral("OMEMO element could not be created"),
                    SendError::EncryptionError });

            } else {
                auto omemoIq = std::make_unique<QXmppOmemoIq>();
                omemoIq->setId(iq.id());
                omemoIq->setType(iq.type());
                omemoIq->setLang(iq.lang());
                omemoIq->setFrom(iq.from());
                omemoIq->setTo(iq.to());
                omemoIq->setOmemoElement(*omemoElement);

                interface.finish(std::move(omemoIq));
            }
        });
    }

    return interface.task();
}

QXmppTask<QXmppE2eeExtension::IqDecryptResult> Manager::decryptIq(const QDomElement &element)
{
    if (!d->isStarted) {
        // TODO: Add decryption queue to avoid this error
        return makeReadyTask<IqDecryptResult>(QXmppError {
            QStringLiteral("OMEMO manager must be started before decrypting"),
            SendError::EncryptionError });
    }

    if (QXmppOmemoIq::isOmemoIq(element)) {
        // Tag name and iq type are already checked in QXmppClient.
        return chain<IqDecryptResult>(d->decryptIq(element), this, [](auto result) -> IqDecryptResult {
            if (result) {
                return result->iq;
            }
            return QXmppError {
                QStringLiteral("OMEMO message could not be decrypted"),
                SendError::EncryptionError
            };
        });
    }

    return makeReadyTask<IqDecryptResult>(NotEncrypted());
}

bool QXmppOmemoManager::isEncrypted(const QDomElement &el)
{
    for (auto subEl = el.firstChildElement();
         !subEl.isNull();
         subEl = subEl.nextSiblingElement()) {
        if (subEl.tagName() == "encrypted" && subEl.namespaceURI() == ns_omemo_2) {
            return true;
        }
    }
    return false;
}

bool QXmppOmemoManager::isEncrypted(const QXmppMessage &message)
{
    return message.omemoElement().has_value();
}

QStringList Manager::discoveryFeatures() const
{
    return {
        QString(ns_omemo_2_devices) % "+notify"
    };
}

bool Manager::handleStanza(const QDomElement &stanza)
{
    if (stanza.tagName() != "iq" || !QXmppOmemoIq::isOmemoIq(stanza)) {
        return false;
    }

    // TODO: Queue incoming IQs until OMEMO is initialized
    if (!d->isStarted) {
        warning("Couldn't decrypt incoming IQ because the manager isn't initialized yet.");
        return false;
    }

    auto type = stanza.attribute("type");
    if (type != "get" && type != "set") {
        // ignore incoming result and error IQs (they are handled via Client::sendIq())
        return false;
    }

    d->decryptIq(stanza).then(this, [=](auto result) {
        if (result) {
            injectIq(result->iq, result->e2eeMetadata);
        } else {
            warning("Could not decrypt incoming OMEMO IQ.");
        }
    });
    return true;
}

bool Manager::handleMessage(const QXmppMessage &message)
{
    if (d->isStarted && message.omemoElement()) {
        auto future = d->decryptMessage(message);
        future.then(this, [=](std::optional<QXmppMessage> optionalDecryptedMessage) mutable {
            if (optionalDecryptedMessage) {
                injectMessage(std::move(*optionalDecryptedMessage));
            }
        });

        return true;
    }

    return false;
}
/// \endcond

///
/// \fn QXmppOmemoManager::trustLevelsChanged(const QMultiHash<QString, QByteArray> &modifiedKeys)
///
/// Emitted when the trust levels of keys changed.
///
/// \param modifiedKeys key owners' bare JIDs mapped to their modified keys
///

///
/// \fn QXmppOmemoManager::deviceAdded(const QString &jid, uint32_t deviceId)
///
/// Emitted when a device is added.
///
/// \param jid device owner's bare JID
/// \param deviceId ID of the device
///

///
/// \fn QXmppOmemoManager::deviceChanged(const QString &jid, uint32_t deviceId)
///
/// Emitted when a device changed.
///
/// \param jid device owner's bare JID
/// \param deviceId ID of the device
///

///
/// \fn QXmppOmemoManager::deviceRemoved(const QString &jid, uint32_t deviceId)
///
/// Emitted when a device is removed.
///
/// \param jid device owner's bare JID
/// \param deviceId ID of the device
///

///
/// \fn QXmppOmemoManager::devicesRemoved(const QString &jid)
///
/// Emitted when all devices of an owner are removed.
///
/// \param jid device owner's bare JID
///

///
/// \fn QXmppOmemoManager::allDevicesRemoved()
///
/// Emitted when all devices are removed.
///

/// \cond
void Manager::setClient(QXmppClient *client)
{
    QXmppClientExtension::setClient(client);
    client->setEncryptionExtension(this);

    d->trustManager = client->findExtension<QXmppTrustManager>();
    if (!d->trustManager) {
        qFatal("QXmppTrustManager is not available, it must be added to the client before adding QXmppOmemoManager");
    }

    d->pubSubManager = client->findExtension<QXmppPubSubManager>();
    if (!d->pubSubManager) {
        qFatal("QXmppPubSubManager is not available, it must be added to the client before adding QXmppOmemoManager");
    }

    connect(d->trustManager, &QXmppTrustManager::trustLevelsChanged, this, [=](const QHash<QString, QMultiHash<QString, QByteArray>> &modifiedKeys) {
        const auto &modifiedOmemoKeys = modifiedKeys.value(ns_omemo_2);
        Q_EMIT trustLevelsChanged(modifiedOmemoKeys);

        for (auto itr = modifiedOmemoKeys.cbegin(); itr != modifiedOmemoKeys.cend(); ++itr) {
            const auto &keyOwnerJid = itr.key();
            const auto &keyId = itr.value();

            // Emit 'deviceChanged()' only if there is a device with the key.
            const auto &devices = d->devices.value(keyOwnerJid);
            for (auto itr = devices.cbegin(); itr != devices.cend(); ++itr) {
                if (itr->keyId == keyId) {
                    Q_EMIT deviceChanged(keyOwnerJid, itr.key());
                    return;
                }
            }
        }
    });
}

bool Manager::handlePubSubEvent(const QDomElement &element, const QString &pubSubService, const QString &nodeName)
{
    if (nodeName == ns_omemo_2_devices && QXmppPubSubEvent<QXmppOmemoDeviceListItem>::isPubSubEvent(element)) {
        QXmppPubSubEvent<QXmppOmemoDeviceListItem> event;
        event.parse(element);

        switch (event.eventType()) {
        // Items have been published.
        case QXmppPubSubEventBase::Items: {
            const auto items = event.items();

            // Only process items if the event notification contains one.
            // That is necessary because PubSub allows publishing without
            // items leading to notification-only events.
            if (!items.isEmpty()) {
                const auto &deviceListItem = items.constFirst();
                if (deviceListItem.id() == QXmppPubSubManager::standardItemIdToString(QXmppPubSubManager::Current)) {
                    d->updateDevices(pubSubService, event.items().constFirst());
                } else {
                    d->handleIrregularDeviceListChanges(pubSubService);
                }
            }

            break;
        }
        // Items have been retracted.
        case QXmppPubSubEventBase::Retract: {
            // Specific items are deleted.
            const auto &retractedItem = event.retractIds().constFirst();
            if (retractedItem == QXmppPubSubManager::standardItemIdToString(QXmppPubSubManager::Current)) {
                d->handleIrregularDeviceListChanges(pubSubService);
            }
        }
        // All items are deleted.
        case QXmppPubSubEventBase::Purge:
        // The whole node is deleted.
        case QXmppPubSubEventBase::Delete:
            d->handleIrregularDeviceListChanges(pubSubService);
            break;
        case QXmppPubSubEventBase::Configuration:
        case QXmppPubSubEventBase::Subscription:
            break;
        }

        return true;
    }

    return false;
}
/// \endcond