aboutsummaryrefslogtreecommitdiff
path: root/src/QXmppServer.cpp
blob: 54dcb9bcf28fa0e8552eb6f9ffb93c8701b699ec (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
/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *  Jeremy Lainé
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include <QDomElement>
#include <QFileInfo>
#include <QSslSocket>

#include "QXmppDialback.h"
#include "QXmppIq.h"
#include "QXmppIncomingClient.h"
#include "QXmppIncomingServer.h"
#include "QXmppOutgoingServer.h"
#include "QXmppServer.h"
#include "QXmppUtils.h"

static QString jidToDomain(const QString &to)
{
    return jidToBareJid(to).split("@").last();
}

class QXmppServerPrivate
{
public:
    QXmppServerPrivate();

    QString domain;
    QMap<QString, QSet<QString> > subscribers;
    QXmppLogger *logger;
    QXmppPasswordChecker *passwordChecker;

    // client-to-server
    QXmppSslServer *serverForClients;
    QList<QXmppIncomingClient*> incomingClients;

    // server-to-server
    QList<QXmppOutgoingServer*> outgoingServers;
    QXmppSslServer *serverForServers;
};

QXmppServerPrivate::QXmppServerPrivate()
    : logger(0),
    passwordChecker(0)
{
}

/// Constructs a new XMPP server instance.
///
/// \param parent

QXmppServer::QXmppServer(QObject *parent)
    : QObject(parent),
    d(new QXmppServerPrivate)
{
    d->serverForClients = new QXmppSslServer(this);
    bool check = connect(d->serverForClients, SIGNAL(newConnection(QSslSocket*)),
                         this, SLOT(slotClientConnection(QSslSocket*)));
    Q_ASSERT(check);

    d->serverForServers = new QXmppSslServer(this);
    check = connect(d->serverForServers, SIGNAL(newConnection(QSslSocket*)),
                    this, SLOT(slotServerConnection(QSslSocket*)));
    Q_ASSERT(check);
}

/// Destroys an XMPP server instance.
///

QXmppServer::~QXmppServer()
{
    delete d;
}

/// Returns the server's domain.
///

QString QXmppServer::domain() const
{
    return d->domain;
}

/// Sets the server's domain.
///
/// \param domain

void QXmppServer::setDomain(const QString &domain)
{
    d->domain = domain;
}

/// Returns the QXmppLogger associated with the server.

QXmppLogger *QXmppServer::logger()
{
    return d->logger;
}

/// Sets the QXmppLogger associated with the server.

void QXmppServer::setLogger(QXmppLogger *logger)
{
    d->logger = logger;
}

/// Returns the password checker used to verify client credentials.
///
/// \param checker
///

QXmppPasswordChecker *QXmppServer::passwordChecker()
{
    return d->passwordChecker;
}

/// Sets the password checker used to verify client credentials.
///
/// \param checker
///

void QXmppServer::setPasswordChecker(QXmppPasswordChecker *checker)
{
    d->passwordChecker = checker;
}

/// Sets the path for additional SSL CA certificates.
///
/// \param path

void QXmppServer::addCaCertificates(const QString &path)
{
    if (!path.isEmpty() && !QFileInfo(path).isReadable())
        qWarning() << "SSL CA certificates are not readable" << path;
    d->serverForClients->addCaCertificates(path);
    d->serverForServers->addCaCertificates(path);
}

/// Sets the path for the local SSL certificate.
///
/// \param path

void QXmppServer::setLocalCertificate(const QString &path)
{
    if (!path.isEmpty() && !QFileInfo(path).isReadable())
        qWarning() << "SSL certificate is not readable" << path;
    d->serverForClients->setLocalCertificate(path);
    d->serverForServers->setLocalCertificate(path);
}

/// Sets the path for the local SSL private key.
///
/// \param path

void QXmppServer::setPrivateKey(const QString &path)
{
    if (!path.isEmpty() && !QFileInfo(path).isReadable())
        qWarning() << "SSL key is not readable" << path;
    d->serverForClients->setPrivateKey(path);
    d->serverForServers->setPrivateKey(path);
}

/// Listen for incoming XMPP client connections.
///
/// \param address
/// \param port

bool QXmppServer::listenForClients(const QHostAddress &address, quint16 port)
{
    if (!d->serverForClients->listen(address, port))
    {
        if (logger())
            logger()->log(QXmppLogger::WarningMessage,
                QString("Could not start listening for C2S on port %1").arg(QString::number(port)));
        return false;
    }
    return true;
}

/// Listen for incoming XMPP server connections.
///
/// \param address
/// \param port

bool QXmppServer::listenForServers(const QHostAddress &address, quint16 port)
{
    if (!d->serverForServers->listen(address, port))
    {
        if (logger())
            logger()->log(QXmppLogger::WarningMessage,
                QString("Could not start listening for S2S on port %1").arg(QString::number(port)));
        return false;
    }
    return true;
}

QXmppOutgoingServer* QXmppServer::connectToDomain(const QString &domain)
{
    // initialise outgoing server-to-server
    QXmppOutgoingServer *stream = new QXmppOutgoingServer(d->domain, this);
    stream->setObjectName("S2S-out-" + domain);
    stream->setLocalStreamKey(generateStanzaHash().toAscii());
    stream->setLogger(d->logger);
    stream->configuration().setDomain(domain);
    stream->configuration().setHost(domain);
    stream->configuration().setPort(5269);
    bool check = connect(stream, SIGNAL(elementReceived(QDomElement, bool&)),
                         this, SLOT(slotElementReceived(QDomElement, bool&)));
    Q_ASSERT(check);
    Q_UNUSED(check);

    d->outgoingServers.append(stream);

    // connect to remote server
    stream->connectToHost();
    return stream;
}

/// Returns the XMPP streams for the given recipient.
///
/// \param to
///

QList<QXmppStream*> QXmppServer::getStreams(const QString &to)
{
    QList<QXmppStream*> found;
    if (to.isEmpty())
        return found;
    const QString toDomain = jidToDomain(to);
    if (toDomain == d->domain)
    {
        // look for a client connection
        foreach (QXmppIncomingClient *conn, d->incomingClients)
        {
            if (conn->jid() == to || jidToBareJid(conn->jid()) == to)
                found << conn;
        }
    } else {
        // look for an outgoing S2S connection
        foreach (QXmppOutgoingServer *conn, d->outgoingServers)
        {
            if (conn->configuration().domain() == toDomain && conn->isConnected())
            {
                found << conn;
                break;
            }
        }

        // if we did not find an outgoing server,
        // we need to establish the S2S connection
        if (found.isEmpty())
        {
            connectToDomain(toDomain);

            // FIXME : the current packet will not be delivered
        }
    }
    return found;
}

/// Handles an incoming XML element.
///
/// \param stream
/// \param element

void QXmppServer::handleStanza(QXmppStream *stream, const QDomElement &element)
{
    const QString to = element.attribute("to");
    if (!to.isEmpty() && to != d->domain)
    {
        // presence handling
        if (element.tagName() == "presence")
        {
            QXmppPresence presence;
            presence.parse(element);

            const QString from = presence.from();
            QSet<QString> subscribers = d->subscribers.value(from);
            if (presence.type() == QXmppPresence::Available)
            {
                //qDebug() << to << "is subscribed to" << stream->jid();
                subscribers.insert(to);
                d->subscribers[from] = subscribers;
            } else if (presence.type() == QXmppPresence::Unavailable) {
                //qDebug() << to << "is unsubscribed from" << stream->jid();
                subscribers.remove(to);
                d->subscribers[from] = subscribers;
            }
        }

        // route element or reply on behalf of missing peer
        if (!sendElement(element) && element.tagName() == "iq")
        {
            QXmppIq request;
            request.parse(element);

            QXmppIq response(QXmppIq::Error);
            QXmppStanza::Error error(QXmppStanza::Error::Cancel, QXmppStanza::Error::ServiceUnavailable);
            response.setError(error);
            response.setId(request.id());
            response.setFrom(request.to());
            response.setTo(request.from());
            stream->sendPacket(response);
        }
    }
}

/// Route an XMPP stanza.
///
/// \param element

bool QXmppServer::sendElement(const QDomElement &element)
{
    bool sent = false;
    const QString to = element.attribute("to");
    foreach (QXmppStream *conn, getStreams(to))
    {
        if (conn->sendElement(element))
            sent = true;
    }
    return sent;
}

/// Route an XMPP packet.
///
/// \param packet

bool QXmppServer::sendPacket(const QXmppStanza &packet)
{
    bool sent = false;
    foreach (QXmppStream *conn, getStreams(packet.to()))
    {
        if (conn->sendPacket(packet))
            sent = true;
    }
    return sent;
}

/// Handle a new incoming TCP connection from a client.
///
/// \param socket

void QXmppServer::slotClientConnection(QSslSocket *socket)
{
    QXmppIncomingClient *stream = new QXmppIncomingClient(socket, d->domain, this);
    socket->setParent(stream);
    stream->setLogger(d->logger);
    stream->setPasswordChecker(d->passwordChecker);

    bool check = connect(stream, SIGNAL(connected()),
                         this, SLOT(slotClientConnected()));
    Q_ASSERT(check);

    check = connect(stream, SIGNAL(disconnected()),
                    this, SLOT(slotClientDisconnected()));
    Q_ASSERT(check);

    check = connect(stream, SIGNAL(elementReceived(QDomElement, bool&)),
                    this, SLOT(slotElementReceived(QDomElement, bool&)));
    Q_ASSERT(check);

    d->incomingClients.append(stream);
}

/// Handle a successful client authentication.
///

void QXmppServer::slotClientConnected()
{
    QXmppIncomingClient *stream = qobject_cast<QXmppIncomingClient *>(sender());
    if (!stream || !d->incomingClients.contains(stream))
        return;

    // check whether the connection conflicts with another one
    foreach (QXmppIncomingClient *conn, d->incomingClients)
    {
        if (conn != stream && conn->jid() == stream->jid())
        {
            conn->sendData("<stream:error><conflict xmlns='urn:ietf:params:xml:ns:xmpp-streams'/><text xmlns='urn:ietf:params:xml:ns:xmpp-streams'>Replaced by new connection</text></stream:error>");
            conn->disconnectFromHost();
        }
    }

    // update statistics
    updateStatistics();
}

/// Handle a disconnection from a client.
///

void QXmppServer::slotClientDisconnected()
{
    QXmppIncomingClient *stream = qobject_cast<QXmppIncomingClient *>(sender());
    if (!stream || !d->incomingClients.contains(stream))
        return;

    // notify subscribed peers of disconnection
    if (stream->isConnected())
    {
        foreach (QString subscriber, d->subscribers.value(stream->jid()))
        {
            QXmppPresence presence;
            presence.setFrom(stream->jid());
            presence.setTo(subscriber);
            presence.setType(QXmppPresence::Unavailable);
            sendPacket(presence);
        }
    }
    d->incomingClients.removeAll(stream);
    stream->deleteLater();

    // update statistics
    updateStatistics();
}

void QXmppServer::slotDialbackRequestReceived(const QXmppDialback &dialback)
{
    QXmppIncomingServer *stream = qobject_cast<QXmppIncomingServer *>(sender());
    if (!stream)
        return;

    if (dialback.command() == QXmppDialback::Verify)
    {
        // handle a verify request
        foreach (QXmppOutgoingServer *out, d->outgoingServers)
        {
            if (out->configuration().domain() != dialback.from())
                continue;

            bool isValid = dialback.key() == out->localStreamKey();
            QXmppDialback verify;
            verify.setCommand(QXmppDialback::Verify);
            verify.setId(dialback.id());
            verify.setTo(dialback.from());
            verify.setFrom(d->domain);
            verify.setType(isValid ? "valid" : "invalid");
            stream->sendPacket(verify);
            return;
        }
    }
}

/// Handle an incoming XML element.

void QXmppServer::slotElementReceived(const QDomElement &element, bool &handled)
{
    QXmppStream *incoming = qobject_cast<QXmppStream *>(sender());
    if (!incoming)
        return;
    handleStanza(incoming, element);
}

/// Handle a new incoming TCP connection from a server.
///
/// \param socket

void QXmppServer::slotServerConnection(QSslSocket *socket)
{
    QXmppIncomingServer *stream = new QXmppIncomingServer(socket, d->domain, this);
    socket->setParent(stream);
    stream->setLogger(d->logger);

    bool check = connect(stream, SIGNAL(disconnected()),
                         stream, SLOT(deleteLater()));
    Q_ASSERT(check);

    check = connect(stream, SIGNAL(dialbackRequestReceived(QXmppDialback)),
                    this, SLOT(slotDialbackRequestReceived(QXmppDialback)));
    Q_ASSERT(check);

    check = connect(stream, SIGNAL(elementReceived(QDomElement, bool&)),
                    this, SLOT(slotElementReceived(QDomElement, bool&)));
    Q_ASSERT(check);
}

void QXmppServer::updateStatistics()
{
}

class QXmppSslServerPrivate
{
public:
    QString caCertificates;
    QString localCertificate;
    QString privateKey;
};

/// Constructs a new SSL server instance.
///
/// \param parent

QXmppSslServer::QXmppSslServer(QObject *parent)
    : QTcpServer(parent),
    d(new QXmppSslServerPrivate)
{
}

/// Destroys an SSL server instance.
///

QXmppSslServer::~QXmppSslServer()
{
    delete d;
}

void QXmppSslServer::incomingConnection(int socketDescriptor)
{
    QSslSocket *socket = new QSslSocket;
    socket->setSocketDescriptor(socketDescriptor);
    if (!d->localCertificate.isEmpty() && !d->privateKey.isEmpty())
    {
        socket->setProtocol(QSsl::AnyProtocol);
        socket->addCaCertificates(d->caCertificates);
        socket->setLocalCertificate(d->localCertificate);
        socket->setPrivateKey(d->privateKey);
    }
    emit newConnection(socket);
}

void QXmppSslServer::addCaCertificates(const QString &caCertificates)
{
    d->caCertificates = caCertificates;
}

void QXmppSslServer::setLocalCertificate(const QString &localCertificate)
{
    d->localCertificate = localCertificate;
}

void QXmppSslServer::setPrivateKey(const QString &privateKey)
{
    d->privateKey = privateKey;
}