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
|
// SPDX-FileCopyrightText: 2009 Manjeet Dahiya <manjeetdahiya@gmail.com>
//
// SPDX-License-Identifier: LGPL-2.1-or-later
#include "QXmppClient.h"
#include "QXmppClientExtension.h"
#include "QXmppClient_p.h"
#include "QXmppConstants_p.h"
#include "QXmppDiscoveryIq.h"
#include "QXmppDiscoveryManager.h"
#include "QXmppE2eeExtension.h"
#include "QXmppE2eeMetadata.h"
#include "QXmppEntityTimeManager.h"
#include "QXmppFutureUtils_p.h"
#include "QXmppLogger.h"
#include "QXmppMessage.h"
#include "QXmppMessageHandler.h"
#include "QXmppOutgoingClient.h"
#include "QXmppPacket_p.h"
#include "QXmppPromise.h"
#include "QXmppRosterManager.h"
#include "QXmppTask.h"
#include "QXmppTlsManager_p.h"
#include "QXmppUtils.h"
#include "QXmppVCardManager.h"
#include "QXmppVersionManager.h"
#include <QDomElement>
#include <QSslSocket>
#include <QTimer>
using namespace QXmpp::Private;
using MessageEncryptResult = QXmppE2eeExtension::MessageEncryptResult;
using IqEncryptResult = QXmppE2eeExtension::IqEncryptResult;
using IqDecryptResult = QXmppE2eeExtension::IqDecryptResult;
static bool isIqResponse(const QDomElement &el)
{
auto type = el.attribute("type");
return el.tagName() == "iq" && (type == "result" || type == "error");
}
/// \cond
QXmppClientPrivate::QXmppClientPrivate(QXmppClient *qq)
: clientPresence(QXmppPresence::Available),
logger(nullptr),
stream(nullptr),
encryptionExtension(nullptr),
receivedConflict(false),
reconnectionTries(0),
reconnectionTimer(nullptr),
isActive(true),
q(qq)
{
}
void QXmppClientPrivate::addProperCapability(QXmppPresence &presence)
{
auto *ext = q->findExtension<QXmppDiscoveryManager>();
if (ext) {
presence.setCapabilityHash("sha-1");
presence.setCapabilityNode(ext->clientCapabilitiesNode());
presence.setCapabilityVer(ext->capabilities().verificationString());
}
}
int QXmppClientPrivate::getNextReconnectTime() const
{
if (reconnectionTries < 5) {
return 10 * 1000;
} else if (reconnectionTries < 10) {
return 20 * 1000;
} else if (reconnectionTries < 15) {
return 40 * 1000;
} else {
return 60 * 1000;
}
}
QStringList QXmppClientPrivate::discoveryFeatures()
{
return {
// XEP-0004: Data Forms
ns_data,
// XEP-0059: Result Set Management
ns_rsm,
// XEP-0066: Out of Band Data
ns_oob,
// XEP-0071: XHTML-IM
ns_xhtml_im,
// XEP-0085: Chat State Notifications
ns_chat_states,
// XEP-0115: Entity Capabilities
ns_capabilities,
// XEP-0199: XMPP Ping
ns_ping,
// XEP-0249: Direct MUC Invitations
ns_conference,
// XEP-0308: Last Message Correction
ns_message_correct,
// XEP-0333: Chat Markers
ns_chat_markers,
// XEP-0334: Message Processing Hints
ns_message_processing_hints,
// XEP-0359: Unique and Stable Stanza IDs
ns_sid,
// XEP-0367: Message Attaching
ns_message_attaching,
// XEP-0380: Explicit Message Encryption
ns_eme,
// XEP-0382: Spoiler messages
ns_spoiler,
// XEP-0428: Fallback Indication
ns_fallback_indication,
// XEP-0444: Message Reactions
ns_reactions,
};
}
/// \endcond
namespace QXmpp::Private::StanzaPipeline {
bool process(const QList<QXmppClientExtension *> &extensions, const QDomElement &element, const std::optional<QXmppE2eeMetadata> &e2eeMetadata)
{
const bool unencrypted = !e2eeMetadata.has_value();
for (auto *extension : extensions) {
// e2e encrypted stanzas are not passed to the old handleStanza() overload, because such
// managers are likely not handling the encrypted contents correctly (e.g. sending
// unencrypted replies and thereby leaking information).
if (extension->handleStanza(element, e2eeMetadata) ||
(unencrypted && extension->handleStanza(element))) {
return true;
}
}
return false;
}
} // namespace QXmpp::Private::StanzaPipeline
namespace QXmpp::Private::MessagePipeline {
bool process(QXmppClient *client, const QList<QXmppClientExtension *> &extensions, QXmppMessage &&message)
{
for (auto *extension : extensions) {
if (auto *messageHandler = dynamic_cast<QXmppMessageHandler *>(extension)) {
if (messageHandler->handleMessage(message)) {
return true;
}
}
}
return false;
}
bool process(QXmppClient *client, const QList<QXmppClientExtension *> &extensions, const QDomElement &element)
{
if (element.tagName() != "message") {
return false;
}
QXmppMessage message;
message.parse(element);
return process(client, extensions, std::move(message));
}
} // namespace QXmpp::Private::MessagePipeline
///
/// \typedef QXmppClient::IqResult
///
/// Result of an IQ request, either contains the QDomElement of the IQ answer
/// (with type 'error' or 'result') or it contains the packet error, if the
/// request couldn't be sent.
///
/// \since QXmpp 1.5
///
///
/// \typedef QXmppClient::EmptyResult
///
/// Result of a generic request without a return value. Contains Success in case
/// everything went well. If the returned IQ contained an error a
/// QXmppStanza::Error is reported.
///
/// \since QXmpp 1.5
///
/// Creates a QXmppClient object.
/// \param parent is passed to the QObject's constructor.
/// The default value is 0.
QXmppClient::QXmppClient(QObject *parent)
: QXmppLoggable(parent),
d(new QXmppClientPrivate(this))
{
d->stream = new QXmppOutgoingClient(this);
d->addProperCapability(d->clientPresence);
connect(d->stream, &QXmppOutgoingClient::elementReceived,
this, &QXmppClient::_q_elementReceived);
connect(d->stream, &QXmppOutgoingClient::messageReceived,
this, &QXmppClient::messageReceived);
connect(d->stream, &QXmppOutgoingClient::presenceReceived,
this, &QXmppClient::presenceReceived);
connect(d->stream, &QXmppOutgoingClient::iqReceived,
this, &QXmppClient::iqReceived);
connect(d->stream, &QXmppOutgoingClient::sslErrors,
this, &QXmppClient::sslErrors);
connect(d->stream->socket(), &QAbstractSocket::stateChanged,
this, &QXmppClient::_q_socketStateChanged);
connect(d->stream, &QXmppStream::connected,
this, &QXmppClient::_q_streamConnected);
connect(d->stream, &QXmppStream::disconnected,
this, &QXmppClient::_q_streamDisconnected);
connect(d->stream, &QXmppOutgoingClient::error,
this, &QXmppClient::_q_streamError);
// reconnection
d->reconnectionTimer = new QTimer(this);
d->reconnectionTimer->setSingleShot(true);
connect(d->reconnectionTimer, &QTimer::timeout,
this, &QXmppClient::_q_reconnect);
// logging
setLogger(QXmppLogger::getLogger());
addExtension(new QXmppTlsManager);
addExtension(new QXmppRosterManager(this));
addExtension(new QXmppVCardManager);
addExtension(new QXmppVersionManager);
addExtension(new QXmppEntityTimeManager());
addExtension(new QXmppDiscoveryManager());
}
QXmppClient::~QXmppClient() = default;
///
/// \fn QXmppClient::addNewExtension()
///
/// Creates a new extension and adds it to the client.
///
/// \returns the newly created extension
///
/// \since QXmpp 1.5
///
/// Registers a new \a extension with the client.
///
/// \param extension
bool QXmppClient::addExtension(QXmppClientExtension *extension)
{
return insertExtension(d->extensions.size(), extension);
}
/// Registers a new \a extension with the client at the given \a index.
///
/// \param index
/// \param extension
bool QXmppClient::insertExtension(int index, QXmppClientExtension *extension)
{
if (d->extensions.contains(extension)) {
qWarning("Cannot add extension, it has already been added");
return false;
}
extension->setParent(this);
extension->setClient(this);
d->extensions.insert(index, extension);
return true;
}
/// Unregisters the given extension from the client. If the extension
/// is found, it will be destroyed.
///
/// \param extension
bool QXmppClient::removeExtension(QXmppClientExtension *extension)
{
if (d->extensions.contains(extension)) {
d->extensions.removeAll(extension);
delete extension;
return true;
} else {
qWarning("Cannot remove extension, it was never added");
return false;
}
}
///
/// Returns the currently used encryption extension.
///
/// \since QXmpp 1.5
///
QXmppE2eeExtension *QXmppClient::encryptionExtension() const
{
return d->encryptionExtension;
}
///
/// Sets the extension to be used for end-to-end-encryption.
///
/// \since QXmpp 1.5
///
void QXmppClient::setEncryptionExtension(QXmppE2eeExtension *extension)
{
d->encryptionExtension = extension;
}
/// Returns a list containing all the client's extensions.
///
QList<QXmppClientExtension *> QXmppClient::extensions()
{
return d->extensions;
}
/// Returns a modifiable reference to the current configuration of QXmppClient.
/// \return Reference to the QXmppClient's configuration for the connection.
QXmppConfiguration &QXmppClient::configuration()
{
return d->stream->configuration();
}
///
/// Attempts to connect to the XMPP server. Server details and other configurations
/// are specified using the config parameter. Use signals connected(), error(QXmppClient::Error)
/// and disconnected() to know the status of the connection.
///
/// \param config Specifies the configuration object for connecting the XMPP server.
/// This contains the host name, user, password etc. See QXmppConfiguration for details.
/// \param initialPresence The initial presence which will be set for this user
/// after establishing the session. The default value is QXmppPresence::Available
///
void QXmppClient::connectToServer(const QXmppConfiguration &config,
const QXmppPresence &initialPresence)
{
// reset package cache from last connection
if (d->stream->configuration().jidBare() != config.jidBare()) {
d->stream->resetPacketCache();
}
d->stream->configuration() = config;
d->clientPresence = initialPresence;
d->addProperCapability(d->clientPresence);
d->stream->connectToHost();
}
/// Overloaded function to simply connect to an XMPP server with a JID and password.
///
/// \param jid JID for the account.
/// \param password Password for the account.
void QXmppClient::connectToServer(const QString &jid, const QString &password)
{
QXmppConfiguration config;
config.setJid(jid);
config.setPassword(password);
connectToServer(config);
}
///
/// After successfully connecting to the server use this function to send
/// stanzas to the server. This function can solely be used to send various kind
/// of stanzas to the server. QXmppStanza is a parent class of all the stanzas
/// QXmppMessage, QXmppPresence, QXmppIq, QXmppBind, QXmppRosterIq, QXmppSession
/// and QXmppVCard.
///
/// This function does not end-to-end encrypt the packets.
///
/// \return Returns true if the packet was sent, false otherwise.
///
/// Following code snippet illustrates how to send a message using this function:
/// \code
/// QXmppMessage message(from, to, message);
/// client.sendPacket(message);
/// \endcode
///
/// \param packet A valid XMPP stanza. It can be an iq, a message or a presence stanza.
///
bool QXmppClient::sendPacket(const QXmppNonza &packet)
{
return d->stream->sendPacket(packet);
}
///
/// Sends a packet and reports the result via QXmppTask.
///
/// If stream management is enabled, the task continues to be active until the
/// server acknowledges the packet. On success, QXmpp::SendSuccess with
/// acknowledged == true is reported and the task finishes.
///
/// If connection errors occur, the packet is resent if possible. If
/// reconnecting is not possible, an error is reported.
///
/// \warning THIS API IS NOT FINALIZED YET!
///
/// \returns A QXmppTask that makes it possible to track the state of the packet.
///
/// \since QXmpp 1.5
///
QXmppTask<QXmpp::SendResult> QXmppClient::sendSensitive(QXmppStanza &&stanza, const std::optional<QXmppSendStanzaParams> ¶ms)
{
const auto sendEncrypted = [this](auto &&task) {
QXmppPromise<QXmpp::SendResult> interface;
task.then(this, [this, interface](auto &&result) mutable {
std::visit(overloaded {
[&](std::unique_ptr<QXmppMessage> &&message) {
QByteArray xml;
QXmlStreamWriter writer(&xml);
message->toXml(&writer, QXmpp::ScePublic);
d->stream->send(QXmppPacket(xml, true, std::move(interface)));
},
[&](std::unique_ptr<QXmppIq> &&iq) {
d->stream->send(QXmppPacket(*iq, std::move(interface)));
},
[&](QXmppError &&error) {
interface.finish(std::move(error));
} },
std::move(result));
});
return interface.task();
};
if (d->encryptionExtension) {
if (dynamic_cast<QXmppMessage *>(&stanza)) {
return sendEncrypted(
d->encryptionExtension->encryptMessage(
std::move(dynamic_cast<QXmppMessage &&>(stanza)), params));
} else if (dynamic_cast<QXmppIq *>(&stanza)) {
return sendEncrypted(
d->encryptionExtension->encryptIq(
std::move(dynamic_cast<QXmppIq &&>(stanza)), params));
}
}
return d->stream->send(stanza);
}
///
/// Sends a packet always without end-to-end-encryption.
///
/// This does the same as send(), but does not do any end-to-end encryption on
/// the stanza.
///
/// \warning THIS API IS NOT FINALIZED YET!
///
/// \returns A QXmppTask that makes it possible to track the state of the packet.
///
/// \since QXmpp 1.5
///
QXmppTask<QXmpp::SendResult> QXmppClient::send(QXmppStanza &&stanza, const std::optional<QXmppSendStanzaParams> &)
{
return d->stream->send(stanza);
}
///
/// Sends the stanza with the same encryption as \p e2eeMetadata.
///
/// When there is no e2eeMetadata given this always sends the stanza without
/// end-to-end encryption.
/// Intended to be used for replies to IQs and messages.
///
/// \since QXmpp 1.5
///
QXmppTask<QXmpp::SendResult> QXmppClient::reply(QXmppStanza &&stanza, const std::optional<QXmppE2eeMetadata> &e2eeMetadata, const std::optional<QXmppSendStanzaParams> ¶ms)
{
// This should pick the right e2ee manager as soon as multiple encryptions
// in parallel are supported.
if (e2eeMetadata) {
return sendSensitive(std::move(stanza), params);
}
return send(std::move(stanza), params);
}
///
/// Sends an IQ packet and returns the response asynchronously.
///
/// This is useful for further processing and parsing of the returned
/// QDomElement. If you don't expect a special response, you may want use
/// sendGenericIq().
///
/// This does not do any end-to-encryption on the IQ.
///
/// \sa sendSensitiveIq()
///
/// \warning THIS API IS NOT FINALIZED YET!
///
/// \since QXmpp 1.5
///
QXmppTask<QXmppClient::IqResult> QXmppClient::sendIq(QXmppIq &&iq, const std::optional<QXmppSendStanzaParams> &)
{
return d->stream->sendIq(std::move(iq));
}
///
/// Tries to encrypt and send an IQ packet and returns the response
/// asynchronously.
///
/// This can be used for sensitive IQ requests performed from client to client.
/// Most IQ requests like service discovery requests cannot be end-to-end
/// encrypted or it only makes little sense to do so. This is why the default
/// sendIq() does not do any additional end-to-end encryption.
///
/// \warning THIS API IS NOT FINALIZED YET!
///
/// \since QXmpp 1.5
///
QXmppTask<QXmppClient::IqResult> QXmppClient::sendSensitiveIq(QXmppIq &&iq, const std::optional<QXmppSendStanzaParams> ¶ms)
{
if (d->encryptionExtension) {
QXmppPromise<IqResult> p;
auto task = p.task();
d->encryptionExtension->encryptIq(std::move(iq), params).then(this, [this, p = std::move(p)](IqEncryptResult result) mutable {
std::visit(overloaded {
[&](std::unique_ptr<QXmppIq> &&iq) {
// success (encrypted)
d->stream->sendIq(std::move(*iq)).then(this, [this, p = std::move(p)](auto &&result) mutable {
// iq sent, response received
std::visit(overloaded {
[&](QDomElement &&el) {
if (!isIqResponse(el)) {
p.finish(QXmppError {
QStringLiteral("Invalid IQ response received."),
QXmpp::SendError::EncryptionError });
return;
}
if (!d->encryptionExtension) {
p.finish(QXmppError {
QStringLiteral("No decryption extension found."),
QXmpp::SendError::EncryptionError });
return;
}
// try to decrypt the result (should be encrypted)
d->encryptionExtension->decryptIq(el).then(this, [p = std::move(p), encryptedEl = el](IqDecryptResult result) mutable {
std::visit(overloaded {
[&](QDomElement &&decryptedEl) {
p.finish(decryptedEl);
},
[&](QXmppE2eeExtension::NotEncrypted) {
// the IQ response from the other entity was not encrypted
// then report IQ response without modifications
// TODO: should we return a QXmppError instead?
p.finish(std::move(encryptedEl));
},
[&](QXmppError &&error) {
p.finish(error);
} },
std::move(result));
});
},
[&](QXmppError &&e) {
p.finish(std::move(e));
} },
std::move(result));
});
},
[&](QXmppError &&error) {
// error (encryption)
p.finish(std::move(error));
} },
std::move(result));
});
return task;
}
return d->stream->sendIq(std::move(iq));
}
///
/// Sends an IQ and returns possible stanza errors.
///
/// If you want to parse a special IQ response in the result case, you can use
/// sendIq() and parse the returned QDomElement.
///
/// \returns Returns QXmpp::Success (on response type 'result') or the contained
/// QXmppStanza::Error (on response type 'error')
///
/// \warning THIS API IS NOT FINALIZED YET!
///
/// \since QXmpp 1.5
///
QXmppTask<QXmppClient::EmptyResult> QXmppClient::sendGenericIq(QXmppIq &&iq, const std::optional<QXmppSendStanzaParams> &)
{
return chainIq(sendIq(std::move(iq)), this, [](const QXmppIq &) -> EmptyResult {
return QXmpp::Success();
});
}
/// Disconnects the client and the current presence of client changes to
/// QXmppPresence::Unavailable and status text changes to "Logged out".
///
/// \note Make sure that the clientPresence is changed to
/// QXmppPresence::Available, if you are again calling connectToServer() after
/// calling the disconnectFromServer() function.
///
void QXmppClient::disconnectFromServer()
{
// cancel reconnection
d->reconnectionTimer->stop();
d->clientPresence.setType(QXmppPresence::Unavailable);
d->clientPresence.setStatusText("Logged out");
if (d->stream->isConnected()) {
sendPacket(d->clientPresence);
}
d->stream->disconnectFromHost();
}
/// Returns true if the client has authenticated with the XMPP server.
bool QXmppClient::isAuthenticated() const
{
return d->stream->isAuthenticated();
}
/// Returns true if the client is connected to the XMPP server.
///
bool QXmppClient::isConnected() const
{
return d->stream->isConnected();
}
///
/// Returns true if the current client state is "active", false if it is
/// "inactive". See \xep{0352}: Client State Indication for details.
///
/// On connect this is always reset to true.
///
/// \since QXmpp 1.0
///
bool QXmppClient::isActive() const
{
return d->isActive;
}
///
/// Sets the client state as described in \xep{0352}: Client State Indication.
///
/// On connect this is always reset to true.
///
/// \since QXmpp 1.0
///
void QXmppClient::setActive(bool active)
{
if (active != d->isActive && isConnected() && d->stream->isClientStateIndicationEnabled()) {
d->isActive = active;
QString packet = "<%1 xmlns='%2'/>";
d->stream->sendData(packet.arg(active ? "active" : "inactive", ns_csi).toUtf8());
}
}
///
/// Returns the current \xep{0198}: Stream Management state of the connection.
///
/// Upon connection of the client this can be used to check whether the
/// previous stream has been resumed.
///
/// \since QXmpp 1.4
///
QXmppClient::StreamManagementState QXmppClient::streamManagementState() const
{
if (d->stream->isStreamManagementEnabled()) {
if (d->stream->isStreamResumed()) {
return ResumedStream;
}
return NewStream;
}
return NoStreamManagement;
}
/// Returns the reference to QXmppRosterManager object of the client.
///
/// \return Reference to the roster object of the connected client. Use this to
/// get the list of friends in the roster and their presence information.
///
/// \deprecated This method is deprecated since QXmpp 1.1. Use
/// \c QXmppClient::findExtension<QXmppRosterManager>() instead.
QXmppRosterManager &QXmppClient::rosterManager()
{
return *findExtension<QXmppRosterManager>();
}
/// Utility function to send message to all the resources associated with the
/// specified bareJid. If there are no resources available, that is the contact
/// is offline or not present in the roster, it will still send a message to
/// the bareJid.
///
/// \note Usage of this method is discouraged because most modern clients use
/// carbon messages (\xep{0280}: Message Carbons) and MAM (\xep{0313}: Message
/// Archive Management) and so could possibly receive messages multiple times
/// or not receive them at all.
/// \c QXmppClient::sendPacket() should be used instead with a \c QXmppMessage.
///
/// \param bareJid bareJid of the receiving entity
/// \param message Message string to be sent.
void QXmppClient::sendMessage(const QString &bareJid, const QString &message)
{
QXmppRosterManager *rosterManager = findExtension<QXmppRosterManager>();
const QStringList resources = rosterManager
? rosterManager->getResources(bareJid)
: QStringList();
if (!resources.isEmpty()) {
for (const auto &resource : resources) {
sendPacket(
QXmppMessage({}, bareJid + QStringLiteral("/") + resource, message));
}
} else {
sendPacket(QXmppMessage({}, bareJid, message));
}
}
QXmppClient::State QXmppClient::state() const
{
if (d->stream->isConnected()) {
return QXmppClient::ConnectedState;
} else if (d->stream->socket()->state() != QAbstractSocket::UnconnectedState &&
d->stream->socket()->state() != QAbstractSocket::ClosingState) {
return QXmppClient::ConnectingState;
} else {
return QXmppClient::DisconnectedState;
}
}
/// Returns the client's current presence.
///
QXmppPresence QXmppClient::clientPresence() const
{
return d->clientPresence;
}
/// Changes the presence of the connected client.
///
/// The connection to the server will be updated accordingly:
///
/// \li If the presence type is QXmppPresence::Unavailable, the connection
/// to the server will be closed.
///
/// \li Otherwise, the connection to the server will be established
/// as needed.
///
/// \param presence QXmppPresence object
///
void QXmppClient::setClientPresence(const QXmppPresence &presence)
{
d->clientPresence = presence;
d->addProperCapability(d->clientPresence);
if (presence.type() == QXmppPresence::Unavailable) {
// cancel reconnection
d->reconnectionTimer->stop();
// NOTE: we can't call disconnect() because it alters
// the client presence
if (d->stream->isConnected()) {
sendPacket(d->clientPresence);
}
d->stream->disconnectFromHost();
} else if (d->stream->isConnected()) {
sendPacket(d->clientPresence);
} else {
connectToServer(d->stream->configuration(), presence);
}
}
/// Returns the socket error if error() is QXmppClient::SocketError.
///
QAbstractSocket::SocketError QXmppClient::socketError()
{
return d->stream->socket()->error();
}
/// Returns the human-readable description of the last socket error if error() is QXmppClient::SocketError.
QString QXmppClient::socketErrorString() const
{
return d->stream->socket()->errorString();
}
/// Returns the XMPP stream error if QXmppClient::Error is QXmppClient::XmppStreamError.
QXmppStanza::Error::Condition QXmppClient::xmppStreamError()
{
return d->stream->xmppStreamError();
}
///
/// Returns the reference to QXmppVCardManager, implementation of \xep{0054}.
/// http://xmpp.org/extensions/xep-0054.html
///
/// \deprecated This method is deprecated since QXmpp 1.1. Use
/// \c QXmppClient::findExtension<QXmppVCardManager>() instead.
///
QXmppVCardManager &QXmppClient::vCardManager()
{
return *findExtension<QXmppVCardManager>();
}
///
/// Returns the reference to QXmppVersionManager, implementation of \xep{0092}.
/// http://xmpp.org/extensions/xep-0092.html
///
/// \deprecated This method is deprecated since QXmpp 1.1. Use
/// \c QXmppClient::findExtension<QXmppVersionManager>() instead.
///
QXmppVersionManager &QXmppClient::versionManager()
{
return *findExtension<QXmppVersionManager>();
}
void QXmppClient::injectIq(const QDomElement &element, const std::optional<QXmppE2eeMetadata> &e2eeMetadata)
{
if (element.tagName() != "iq") {
return;
}
if (!StanzaPipeline::process(d->extensions, element, e2eeMetadata)) {
const auto iqType = element.attribute("type");
if (iqType == "get" || iqType == "set") {
// send error IQ
using Err = QXmppStanza::Error;
QXmppIq iq(QXmppIq::Error);
iq.setTo(element.attribute("from"));
iq.setId(element.attribute("id"));
const auto errMessage = e2eeMetadata.has_value()
? QStringLiteral("Feature not implemented or not supported with end-to-end encryption.")
: QStringLiteral("Feature not implemented.");
iq.setError(Err(Err::Cancel, Err::FeatureNotImplemented, errMessage));
reply(std::move(iq), e2eeMetadata);
}
// don't do anything for "result" and "error" IQs
}
}
///
/// Processes the message with message handlers and emits messageReceived as a fallback.
///
bool QXmppClient::injectMessage(QXmppMessage &&message)
{
auto handled = MessagePipeline::process(this, d->extensions, std::move(message));
if (!handled) {
// no extension handled the message
Q_EMIT messageReceived(message);
}
return handled;
}
///
/// Give extensions a chance to handle incoming stanzas.
///
void QXmppClient::_q_elementReceived(const QDomElement &element, bool &handled)
{
// The stanza comes directly from the XMPP stream, so it's not end-to-end
// encrypted and there's no e2ee metadata (std::nullopt).
handled = StanzaPipeline::process(d->extensions, element, std::nullopt) ||
MessagePipeline::process(this, d->extensions, element);
}
void QXmppClient::_q_reconnect()
{
if (d->stream->configuration().autoReconnectionEnabled()) {
debug("Reconnecting to server");
d->stream->connectToHost();
}
}
void QXmppClient::_q_socketStateChanged(QAbstractSocket::SocketState socketState)
{
Q_UNUSED(socketState);
Q_EMIT stateChanged(state());
}
/// At connection establishment, send initial presence.
void QXmppClient::_q_streamConnected()
{
d->receivedConflict = false;
d->reconnectionTries = 0;
d->isActive = true;
// notify managers
Q_EMIT connected();
Q_EMIT stateChanged(QXmppClient::ConnectedState);
// send initial presence
if (d->stream->isAuthenticated()) {
sendPacket(d->clientPresence);
}
}
void QXmppClient::_q_streamDisconnected()
{
// notify managers
Q_EMIT disconnected();
Q_EMIT stateChanged(QXmppClient::DisconnectedState);
}
void QXmppClient::_q_streamError(QXmppClient::Error err)
{
if (d->stream->configuration().autoReconnectionEnabled()) {
if (err == QXmppClient::XmppStreamError) {
// if we receive a resource conflict, inhibit reconnection
if (d->stream->xmppStreamError() == QXmppStanza::Error::Conflict) {
d->receivedConflict = true;
}
} else if (err == QXmppClient::SocketError && !d->receivedConflict) {
// schedule reconnect
d->reconnectionTimer->start(d->getNextReconnectTime());
} else if (err == QXmppClient::KeepAliveError) {
// if we got a keepalive error, reconnect in one second
d->reconnectionTimer->start(1000);
}
}
// notify managers
Q_EMIT error(err);
}
QXmppLogger *QXmppClient::logger() const
{
return d->logger;
}
/// Sets the QXmppLogger associated with the current QXmppClient.
void QXmppClient::setLogger(QXmppLogger *logger)
{
if (logger != d->logger) {
if (d->logger) {
disconnect(this, &QXmppLoggable::logMessage,
d->logger, &QXmppLogger::log);
disconnect(this, &QXmppLoggable::setGauge,
d->logger, &QXmppLogger::setGauge);
disconnect(this, &QXmppLoggable::updateCounter,
d->logger, &QXmppLogger::updateCounter);
}
d->logger = logger;
if (d->logger) {
connect(this, &QXmppLoggable::logMessage,
d->logger, &QXmppLogger::log);
connect(this, &QXmppLoggable::setGauge,
d->logger, &QXmppLogger::setGauge);
connect(this, &QXmppLoggable::updateCounter,
d->logger, &QXmppLogger::updateCounter);
}
Q_EMIT loggerChanged(d->logger);
}
}
|