diff options
| author | Jeremy Lainé <jeremy.laine@m4x.org> | 2010-08-11 07:31:23 +0000 |
|---|---|---|
| committer | Jeremy Lainé <jeremy.laine@m4x.org> | 2010-08-11 07:31:23 +0000 |
| commit | 40c39853816cfab113d79682c34bc76a2c79c357 (patch) | |
| tree | e4d6a184cf565cb87477339ce738299ff9787bc3 /source | |
| parent | 551c284e35280b7b91a939fe7352e496ffea402a (diff) | |
| download | qxmpp-40c39853816cfab113d79682c34bc76a2c79c357.tar.gz | |
rename "source" directory to "src"
Diffstat (limited to 'source')
90 files changed, 0 insertions, 18544 deletions
diff --git a/source/QXmppArchiveIq.cpp b/source/QXmppArchiveIq.cpp deleted file mode 100644 index d452f67a..00000000 --- a/source/QXmppArchiveIq.cpp +++ /dev/null @@ -1,296 +0,0 @@ -/* - * 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 "QXmppArchiveIq.h" -#include "QXmppUtils.h" - -#include <QDebug> -#include <QDomElement> - -static const char *ns_archive = "urn:xmpp:archive"; - -QString QXmppArchiveMessage::body() const -{ - return m_body; -} - -void QXmppArchiveMessage::setBody(const QString &body) -{ - m_body = body; -} - -QDateTime QXmppArchiveMessage::date() const -{ - return m_date; -} - -void QXmppArchiveMessage::setDate(const QDateTime &date) -{ - m_date = date; -} - -bool QXmppArchiveMessage::isReceived() const -{ - return m_received; -} - -void QXmppArchiveMessage::setReceived(bool isReceived) -{ - m_received = isReceived; -} - -void QXmppArchiveChat::parse(const QDomElement &element) -{ - m_start = datetimeFromString(element.attribute("start")); - m_subject = element.attribute("subject"); - m_version = element.attribute("version").toInt(); - m_with = element.attribute("with"); - - QDomElement child = element.firstChildElement(); - while (!child.isNull()) - { - if ((child.tagName() == "from") || (child.tagName() == "to")) - { - QXmppArchiveMessage message; - message.setBody(child.firstChildElement("body").text()); - message.setDate(m_start.addSecs(child.attribute("secs").toInt())); - message.setReceived(child.tagName() == "from"); - m_messages << message; - } - child = child.nextSiblingElement(); - } -} - -QList<QXmppArchiveMessage> QXmppArchiveChat::messages() const -{ - return m_messages; -} - -QDateTime QXmppArchiveChat::start() const -{ - return m_start; -} - -QString QXmppArchiveChat::subject() const -{ - return m_subject; -} - -int QXmppArchiveChat::version() const -{ - return m_version; -} - -QString QXmppArchiveChat::with() const -{ - return m_with; -} - -QXmppArchiveChat QXmppArchiveChatIq::chat() const -{ - return m_chat; -} - -bool QXmppArchiveChatIq::isArchiveChatIq(const QDomElement &element) -{ - QDomElement chatElement = element.firstChildElement("chat"); - return !chatElement.attribute("with").isEmpty(); - //return (chatElement.namespaceURI() == ns_archive); -} - -void QXmppArchiveChatIq::parse(const QDomElement &element) -{ - QXmppStanza::parse(element); - - m_chat.parse(element.firstChildElement("chat")); -} - -QXmppArchiveListIq::QXmppArchiveListIq() - : QXmppIq(QXmppIq::Get), m_max(0) -{ -} - -QList<QXmppArchiveChat> QXmppArchiveListIq::chats() const -{ - return m_chats; -} - -int QXmppArchiveListIq::max() const -{ - return m_max; -} - -void QXmppArchiveListIq::setMax(int max) -{ - m_max = max; -} - -QString QXmppArchiveListIq::with() const -{ - return m_with; -} - -void QXmppArchiveListIq::setWith(const QString &with) -{ - m_with = with; -} - -QDateTime QXmppArchiveListIq::start() const -{ - return m_start; -} - -void QXmppArchiveListIq::setStart(const QDateTime &start) -{ - m_start = start; -} - -QDateTime QXmppArchiveListIq::end() const -{ - return m_end; -} - -void QXmppArchiveListIq::setEnd(const QDateTime &end) -{ - m_end = end; -} - -bool QXmppArchiveListIq::isArchiveListIq(const QDomElement &element) -{ - QDomElement listElement = element.firstChildElement("list"); - return (listElement.namespaceURI() == ns_archive); -} - -void QXmppArchiveListIq::parse(const QDomElement &element) -{ - QXmppStanza::parse(element); - - QDomElement listElement = element.firstChildElement("list"); - m_with = element.attribute("with"); - - QDomElement child = listElement.firstChildElement(); - while (!child.isNull()) - { - if (child.tagName() == "chat") - { - QXmppArchiveChat chat; - chat.parse(child); - m_chats << chat; - } - child = child.nextSiblingElement(); - } -} - -void QXmppArchiveListIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("list"); - helperToXmlAddAttribute(writer, "xmlns", ns_archive); - if (!m_with.isEmpty()) - helperToXmlAddAttribute(writer, "with", m_with); - if (m_start.isValid()) - helperToXmlAddAttribute(writer, "start", datetimeToString(m_start)); - if (m_end.isValid()) - helperToXmlAddAttribute(writer, "end", datetimeToString(m_start)); - if (m_max > 0) - { - writer->writeStartElement("set"); - helperToXmlAddAttribute(writer, "xmlns", "http://jabber.org/protocol/rsm"); - if (m_max > 0) - helperToXmlAddTextElement(writer, "max", QString::number(m_max)); - writer->writeEndElement(); - } - writer->writeEndElement(); -} - -bool QXmppArchivePrefIq::isArchivePrefIq(const QDomElement &element) -{ - QDomElement prefElement = element.firstChildElement("pref"); - return (prefElement.namespaceURI() == ns_archive); -} - -void QXmppArchivePrefIq::parse(const QDomElement &element) -{ - QXmppStanza::parse(element); - - QDomElement queryElement = element.firstChildElement("pref"); - //setId( element.attribute("id")); -} - -void QXmppArchivePrefIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("pref"); - helperToXmlAddAttribute(writer, "xmlns", ns_archive); - writer->writeEndElement(); -} - -QXmppArchiveRetrieveIq::QXmppArchiveRetrieveIq() - : QXmppIq(QXmppIq::Get), m_max(0) -{ -} - -int QXmppArchiveRetrieveIq::max() const -{ - return m_max; -} - -void QXmppArchiveRetrieveIq::setMax(int max) -{ - m_max = max; -} - -QDateTime QXmppArchiveRetrieveIq::start() const -{ - return m_start; -} - -void QXmppArchiveRetrieveIq::setStart(const QDateTime &start) -{ - m_start = start; -} - -QString QXmppArchiveRetrieveIq::with() const -{ - return m_with; -} - -void QXmppArchiveRetrieveIq::setWith(const QString &with) -{ - m_with = with; -} - -void QXmppArchiveRetrieveIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("retrieve"); - helperToXmlAddAttribute(writer, "xmlns", ns_archive); - helperToXmlAddAttribute(writer, "with", m_with); - helperToXmlAddAttribute(writer, "start", datetimeToString(m_start)); - if (m_max > 0) - { - writer->writeStartElement("set"); - helperToXmlAddAttribute(writer, "xmlns", "http://jabber.org/protocol/rsm"); - if (m_max > 0) - helperToXmlAddTextElement(writer, "max", QString::number(m_max)); - writer->writeEndElement(); - } - writer->writeEndElement(); -} diff --git a/source/QXmppArchiveIq.h b/source/QXmppArchiveIq.h deleted file mode 100644 index d8cc7c6f..00000000 --- a/source/QXmppArchiveIq.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPARCHIVEIQ_H -#define QXMPPARCHIVEIQ_H - -#include "QXmppIq.h" - -#include <QDateTime> - -class QXmlStreamWriter; -class QDomElement; - -class QXmppArchiveMessage -{ -public: - QString body() const; - void setBody(const QString &body); - - QDateTime date() const; - void setDate(const QDateTime &date); - - bool isReceived() const; - void setReceived(bool isReceived); - -private: - QString m_body; - QDateTime m_date; - bool m_received; -}; - -class QXmppArchiveChat -{ -public: - QList<QXmppArchiveMessage> messages() const; - QDateTime start() const; - QString subject() const; - int version() const; - QString with() const; - - void parse(const QDomElement &element); - -private: - QList<QXmppArchiveMessage> m_messages; - QDateTime m_start; - QString m_subject; - int m_version; - QString m_with; -}; - -class QXmppArchiveChatIq : public QXmppIq -{ -public: - static bool isArchiveChatIq(const QDomElement &element); - void parse(const QDomElement &element); - - QXmppArchiveChat chat() const; - -private: - QXmppArchiveChat m_chat; -}; - -class QXmppArchiveListIq : public QXmppIq -{ -public: - QXmppArchiveListIq(); - - QList<QXmppArchiveChat> chats() const; - - int max() const; - void setMax(int max); - - QString with() const; - void setWith( const QString &with ); - - QDateTime start() const; - void setStart(const QDateTime &start ); - - QDateTime end() const; - void setEnd(const QDateTime &end ); - - static bool isArchiveListIq(const QDomElement &element); - void parse(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - -private: - int m_max; - QString m_with; - QDateTime m_start; - QDateTime m_end; - QList<QXmppArchiveChat> m_chats; -}; - -class QXmppArchiveRetrieveIq : public QXmppIq -{ -public: - QXmppArchiveRetrieveIq(); - - int max() const; - void setMax(int max); - - QDateTime start() const; - void setStart( const QDateTime &start ); - - QString with() const; - void setWith( const QString &with ); - - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - -private: - int m_max; - QString m_with; - QDateTime m_start; -}; - -class QXmppArchivePrefIq : public QXmppIq -{ -public: - static bool isArchivePrefIq(const QDomElement &element); - void parse(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; -}; - -#endif // QXMPPARCHIVEIQ_H diff --git a/source/QXmppArchiveManager.cpp b/source/QXmppArchiveManager.cpp deleted file mode 100644 index 6f5aee07..00000000 --- a/source/QXmppArchiveManager.cpp +++ /dev/null @@ -1,102 +0,0 @@ -/* - * 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 "QXmppArchiveIq.h" -#include "QXmppArchiveManager.h" -#include "QXmppStream.h" - -#include <QDebug> - -QXmppArchiveManager::QXmppArchiveManager(QXmppStream *stream, QObject *parent) - : QObject(parent), - m_stream(stream) -{ - bool check = QObject::connect(m_stream, SIGNAL(archiveChatIqReceived(const QXmppArchiveChatIq&)), - this, SLOT(archiveChatIqReceived(const QXmppArchiveChatIq&))); - Q_ASSERT(check); - - check = QObject::connect(m_stream, SIGNAL(archiveListIqReceived(const QXmppArchiveListIq&)), - this, SLOT(archiveListIqReceived(const QXmppArchiveListIq&))); - Q_ASSERT(check); - - check = QObject::connect(m_stream, SIGNAL(archivePrefIqReceived(const QXmppArchivePrefIq&)), - this, SLOT(archivePrefIqReceived(const QXmppArchivePrefIq&))); - Q_ASSERT(check); -} - -void QXmppArchiveManager::archiveChatIqReceived(const QXmppArchiveChatIq &chatIq) -{ - emit archiveChatReceived(chatIq.chat()); -} - -void QXmppArchiveManager::archiveListIqReceived(const QXmppArchiveListIq &listIq) -{ - emit archiveListReceived(listIq.chats()); -} - -void QXmppArchiveManager::archivePrefIqReceived(const QXmppArchivePrefIq &prefIq) -{ - Q_UNUSED(prefIq); -} - -/// Retrieves the list of available collections. Once the results are -/// received, the archiveChatReceived() signal will be emitted. -/// -/// \param jid Optional JID if you only want conversations with a specific JID. -/// \param start Optional start time. -/// \param end Optional end time. -/// \param max Optional maximum. -/// -void QXmppArchiveManager::listCollections(const QString &jid, const QDateTime &start, const QDateTime &end, int max) -{ - QXmppArchiveListIq packet; - packet.setMax(max); - packet.setWith(jid); - packet.setStart(start); - packet.setEnd(end); - m_stream->sendPacket(packet); -} - -/// Retrieves the specified collection. Once the results are received, -/// the archiveChatReceived() will be emitted. -/// -/// \param jid The JID of the collection -/// \param start The start time of the collection. -/// \param max Optional maximum number of messages to retrieve. -/// -void QXmppArchiveManager::retrieveCollection(const QString &jid, const QDateTime &start, int max) -{ - QXmppArchiveRetrieveIq packet; - packet.setMax(max); - packet.setStart(start); - packet.setWith(jid); - m_stream->sendPacket(packet); -} - -#if 0 -void QXmppArchiveManager::getPreferences() -{ - QXmppArchivePrefIq packet; - m_stream->sendPacket(packet); -} -#endif diff --git a/source/QXmppArchiveManager.h b/source/QXmppArchiveManager.h deleted file mode 100644 index 70e32aff..00000000 --- a/source/QXmppArchiveManager.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPARCHIVEMANAGER_H -#define QXMPPARCHIVEMANAGER_H - -#include <QDateTime> -#include <QObject> - -class QXmppArchiveChat; -class QXmppArchiveChatIq; -class QXmppArchiveListIq; -class QXmppArchivePrefIq; -class QXmppStream; - -/// \brief The QXmppArchiveManager class makes it possible to access message -/// archives as defined by XEP-0136: Message Archiving. -/// -/// \ingroup Managers - -class QXmppArchiveManager : public QObject -{ - Q_OBJECT - -public: - QXmppArchiveManager(QXmppStream* stream, QObject *parent = 0); - void listCollections(const QString &jid, const QDateTime &start = QDateTime(), const QDateTime &end = QDateTime(), int max = 0); - void retrieveCollection(const QString &jid, const QDateTime &start, int max = 0); - -signals: - void archiveListReceived(const QList<QXmppArchiveChat>&); - void archiveChatReceived(const QXmppArchiveChat&); - -private slots: - void archiveChatIqReceived(const QXmppArchiveChatIq&); - void archiveListIqReceived(const QXmppArchiveListIq&); - void archivePrefIqReceived(const QXmppArchivePrefIq&); - -private: - // reference to xmpp stream (no ownership) - QXmppStream* m_stream; -}; - -#endif diff --git a/source/QXmppBind.cpp b/source/QXmppBind.cpp deleted file mode 100644 index 583efe39..00000000 --- a/source/QXmppBind.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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 <QTextStream> -#include <QXmlStreamWriter> - -#include "QXmppBind.h" -#include "QXmppUtils.h" -#include "QXmppConstants.h" - -QXmppBind::QXmppBind() -{ -} - -QXmppBind::QXmppBind(QXmppIq::Type type) - : QXmppIq(type) -{ -} - -QString QXmppBind::jid() const -{ - return m_jid; -} - -QString QXmppBind::resource() const -{ - return m_resource; -} - -void QXmppBind::setJid(const QString& str) -{ - m_jid = str; -} - -void QXmppBind::setResource(const QString& str) -{ - m_resource = str; -} - -bool QXmppBind::isBind(const QDomElement &element) -{ - QDomElement bindElement = element.firstChildElement("bind"); - return (bindElement.namespaceURI() == ns_bind); -} - -void QXmppBind::parseElementFromChild(const QDomElement &element) -{ - QDomElement bindElement = element.firstChildElement("bind"); - m_jid = bindElement.firstChildElement("jid").text(); - m_resource = bindElement.firstChildElement("resource").text(); -} - -void QXmppBind::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("bind"); - helperToXmlAddAttribute(writer, "xmlns", ns_bind); - if (!m_jid.isEmpty()) - helperToXmlAddTextElement(writer, "jid", m_jid); - if (!m_resource.isEmpty()) - helperToXmlAddTextElement(writer, "resource", m_resource); - writer->writeEndElement(); -} - -QString QXmppBind::getJid() const -{ - return m_jid; -} - -QString QXmppBind::getResource() const -{ - return m_resource; -} diff --git a/source/QXmppBind.h b/source/QXmppBind.h deleted file mode 100644 index d498d415..00000000 --- a/source/QXmppBind.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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. - * - */ - - -#ifndef QXMPPBIND_H -#define QXMPPBIND_H - -#include "QXmppIq.h" - -class QXmppBind : public QXmppIq -{ -public: - QXmppBind(); - QXmppBind(QXmppIq::Type type); - - QString jid() const; - QString resource() const; - - void setJid(const QString&); - void setResource(const QString&); - - static bool isBind(const QDomElement &element); - - // deprecated accessors, use the form without "get" instead - /// \cond - QString Q_DECL_DEPRECATED getJid() const; - QString Q_DECL_DEPRECATED getResource() const; - /// \endcond - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QString m_jid; - QString m_resource; -}; - -#endif // QXMPPBIND_H diff --git a/source/QXmppByteStreamIq.cpp b/source/QXmppByteStreamIq.cpp deleted file mode 100644 index 36ad94a7..00000000 --- a/source/QXmppByteStreamIq.cpp +++ /dev/null @@ -1,183 +0,0 @@ -/* - * 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 "QXmppByteStreamIq.h" -#include "QXmppConstants.h" -#include "QXmppUtils.h" - -QHostAddress QXmppByteStreamIq::StreamHost::host() const -{ - return m_host; -} - -void QXmppByteStreamIq::StreamHost::setHost(const QHostAddress &host) -{ - m_host = host; -} - -QString QXmppByteStreamIq::StreamHost::jid() const -{ - return m_jid; -} - -void QXmppByteStreamIq::StreamHost::setJid(const QString &jid) -{ - m_jid = jid; -} - -quint16 QXmppByteStreamIq::StreamHost::port() const -{ - return m_port; -} - -void QXmppByteStreamIq::StreamHost::setPort(quint16 port) -{ - m_port = port; -} - -QString QXmppByteStreamIq::StreamHost::zeroconf() const -{ - return m_zeroconf; -} - -void QXmppByteStreamIq::StreamHost::setZeroconf(const QString &zeroconf) -{ - m_zeroconf = zeroconf; -} - -QXmppByteStreamIq::Mode QXmppByteStreamIq::mode() const -{ - return m_mode; -} - -void QXmppByteStreamIq::setMode(QXmppByteStreamIq::Mode mode) -{ - m_mode = mode; -} - -QString QXmppByteStreamIq::sid() const -{ - return m_sid; -} - -void QXmppByteStreamIq::setSid(const QString &sid) -{ - m_sid = sid; -} - -QString QXmppByteStreamIq::activate() const -{ - return m_activate; -} - -void QXmppByteStreamIq::setActivate(const QString &activate) -{ - m_activate = activate; -} - -QList<QXmppByteStreamIq::StreamHost> QXmppByteStreamIq::streamHosts() const -{ - return m_streamHosts; -} - -void QXmppByteStreamIq::setStreamHosts(const QList<QXmppByteStreamIq::StreamHost> &streamHosts) -{ - m_streamHosts = streamHosts; -} - -QString QXmppByteStreamIq::streamHostUsed() const -{ - return m_streamHostUsed; -} - -void QXmppByteStreamIq::setStreamHostUsed(const QString &jid) -{ - m_streamHostUsed = jid; -} - -bool QXmppByteStreamIq::isByteStreamIq(const QDomElement &element) -{ - return element.firstChildElement("query").namespaceURI() == ns_bytestreams; -} - -void QXmppByteStreamIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - m_sid = queryElement.attribute("sid"); - const QString modeStr = queryElement.attribute("mode"); - if (modeStr == "tcp") - m_mode = Tcp; - else if (modeStr == "udp") - m_mode = Udp; - else - m_mode = None; - - QDomElement hostElement = queryElement.firstChildElement("streamhost"); - while (!hostElement.isNull()) - { - StreamHost streamHost; - streamHost.setHost(QHostAddress(hostElement.attribute("host"))); - streamHost.setJid(hostElement.attribute("jid")); - streamHost.setPort(hostElement.attribute("port").toInt()); - streamHost.setZeroconf(hostElement.attribute("zeroconf")); - m_streamHosts.append(streamHost); - - hostElement = hostElement.nextSiblingElement("streamhost"); - } - m_activate = queryElement.firstChildElement("activate").text(); - m_streamHostUsed = queryElement.firstChildElement("streamhost-used").attribute("jid"); -} - -void QXmppByteStreamIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("query"); - helperToXmlAddAttribute(writer, "xmlns", ns_bytestreams); - helperToXmlAddAttribute(writer, "sid", m_sid); - QString modeStr; - if (m_mode == Tcp) - modeStr = "tcp"; - else if (m_mode == Udp) - modeStr = "udp"; - helperToXmlAddAttribute(writer, "mode", modeStr); - foreach (const StreamHost& streamHost, m_streamHosts) - { - writer->writeStartElement("streamhost"); - helperToXmlAddAttribute(writer, "host", streamHost.host().toString()); - helperToXmlAddAttribute(writer, "jid", streamHost.jid()); - helperToXmlAddAttribute(writer, "port", QString::number(streamHost.port())); - helperToXmlAddAttribute(writer, "zeroconf", streamHost.zeroconf()); - writer->writeEndElement(); - } - if (!m_activate.isEmpty()) - helperToXmlAddTextElement(writer, "activate", m_activate); - if (!m_streamHostUsed.isEmpty()) - { - writer->writeStartElement("streamhost-used"); - helperToXmlAddAttribute(writer, "jid", m_streamHostUsed); - writer->writeEndElement(); - } - - writer->writeEndElement(); -} diff --git a/source/QXmppByteStreamIq.h b/source/QXmppByteStreamIq.h deleted file mode 100644 index 401929f5..00000000 --- a/source/QXmppByteStreamIq.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPBYTESTREAMIQ_H -#define QXMPPBYTESTREAMIQ_H - -#include "QXmppIq.h" - -#include <QHostAddress> - -class QDomElement; -class QXmlStreamWriter; - -class QXmppByteStreamIq : public QXmppIq -{ -public: - enum Mode { - None = 0, - Tcp, - Udp, - }; - - class StreamHost - { - public: - QString jid() const; - void setJid(const QString &jid); - - QHostAddress host() const; - void setHost(const QHostAddress &host); - - quint16 port() const; - void setPort(quint16 port); - - QString zeroconf() const; - void setZeroconf(const QString &zeroconf); - - private: - QHostAddress m_host; - QString m_jid; - quint16 m_port; - QString m_zeroconf; - }; - - QXmppByteStreamIq::Mode mode() const; - void setMode(QXmppByteStreamIq::Mode mode); - - QString sid() const; - void setSid(const QString &sid); - - QString activate() const; - void setActivate(const QString &activate); - - QList<QXmppByteStreamIq::StreamHost> streamHosts() const; - void setStreamHosts(const QList<QXmppByteStreamIq::StreamHost> &streamHosts); - - QString streamHostUsed() const; - void setStreamHostUsed(const QString &jid); - - static bool isByteStreamIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - Mode m_mode; - QString m_sid; - - QString m_activate; - QList<StreamHost> m_streamHosts; - QString m_streamHostUsed; -}; - -#endif diff --git a/source/QXmppCallManager.cpp b/source/QXmppCallManager.cpp deleted file mode 100644 index 975fcf1b..00000000 --- a/source/QXmppCallManager.cpp +++ /dev/null @@ -1,818 +0,0 @@ -/* - * 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 <QTimer> - -#include "QXmppCallManager.h" -#include "QXmppCodec.h" -#include "QXmppConstants.h" -#include "QXmppJingleIq.h" -#include "QXmppStream.h" -#include "QXmppStun.h" -#include "QXmppUtils.h" - -const quint8 RTP_VERSION = 0x02; - -enum CodecId { - G711u = 0, - GSM = 3, - G723 = 4, - G711a = 8, - G722 = 9, - L16Stereo = 10, - L16Mono = 11, - G728 = 15, - G729 = 18, -}; - -#define SAMPLE_BYTES 2 - -QXmppCall::QXmppCall(const QString &jid, QXmppCall::Direction direction, QObject *parent) - : QIODevice(parent), - m_direction(direction), - m_jid(jid), - m_state(OfferState), - m_signalsEmitted(false), - m_writtenSinceLastEmit(0), - m_codec(0), - m_incomingBuffering(true), - m_incomingMinimum(0), - m_incomingSequence(0), - m_incomingStamp(0), - m_outgoingMarker(true), - m_outgoingSequence(0), - m_outgoingStamp(0) -{ - bool iceControlling = (m_direction == OutgoingDirection); - - // RTP socket - m_socket = new QXmppStunSocket(iceControlling, this); - m_socket->setComponent(1); - - bool check = connect(m_socket, SIGNAL(logMessage(QXmppLogger::MessageType, QString)), - this, SIGNAL(logMessage(QXmppLogger::MessageType, QString))); - Q_ASSERT(check); - - check = connect(m_socket, SIGNAL(connected()), - this, SLOT(updateOpenMode())); - Q_ASSERT(check); - - check = connect(m_socket, SIGNAL(datagramReceived(QByteArray)), - this, SLOT(datagramReceived(QByteArray))); - Q_ASSERT(check); - - // RTCP socket - m_rtcpSocket = new QXmppStunSocket(iceControlling, this); - m_rtcpSocket->setComponent(2); - m_rtcpSocket->setLocalUser(m_socket->localUser()); - m_rtcpSocket->setLocalPassword(m_socket->localPassword()); - - check = connect(m_rtcpSocket, SIGNAL(logMessage(QXmppLogger::MessageType, QString)), - this, SIGNAL(logMessage(QXmppLogger::MessageType, QString))); - Q_ASSERT(check); -} - -/// Call this method if you wish to accept an incoming call. -/// - -void QXmppCall::accept() -{ - if (m_direction == IncomingDirection && m_state == OfferState) - setState(QXmppCall::ConnectingState); -} - -/// Returns the number of bytes that are available for reading. -/// - -qint64 QXmppCall::bytesAvailable() const -{ - return m_incomingBuffer.size(); -} - -void QXmppCall::terminate() -{ - if (m_state == FinishedState) - return; - - m_state = QXmppCall::FinishedState; - - close(); - m_socket->close(); - m_rtcpSocket->close(); - - // emit signals later - QTimer::singleShot(0, this, SLOT(terminated())); -} - -void QXmppCall::terminated() -{ - emit stateChanged(m_state); - emit finished(); -} - -void QXmppCall::connectToHost() -{ - m_socket->connectToHost(); - m_rtcpSocket->connectToHost(); -} - -/// Returns the call's direction. -/// - -QXmppCall::Direction QXmppCall::direction() const -{ - return m_direction; -} - -void QXmppCall::emitSignals() -{ - emit bytesWritten(m_writtenSinceLastEmit); - m_writtenSinceLastEmit = 0; - m_signalsEmitted = false; -} - -/// Hangs up the call. -/// - -void QXmppCall::hangup() -{ - if (m_state != QXmppCall::FinishedState) - setState(QXmppCall::DisconnectingState); -} - -bool QXmppCall::isSequential() const -{ - return true; -} - -/// Returns the remote party's JID. -/// - -QString QXmppCall::jid() const -{ - return m_jid; -} - -QList<QXmppJingleCandidate> QXmppCall::localCandidates() const -{ - return m_socket->localCandidates() + m_rtcpSocket->localCandidates(); -} - -/// Returns the negociated payload type. -/// -/// You can use this to determine the QAudioFormat to use with your -/// QAudioInput/QAudioOutput. - -QXmppJinglePayloadType QXmppCall::payloadType() const -{ - return m_payloadType; -} - -void QXmppCall::setPayloadType(const QXmppJinglePayloadType &payloadType) -{ - m_payloadType = payloadType; - if (payloadType.id() == G711u) - m_codec = new QXmppG711uCodec(payloadType.clockrate()); - else if (payloadType.id() == G711a) - m_codec = new QXmppG711aCodec(payloadType.clockrate()); -#ifdef QXMPP_USE_SPEEX - else if (payloadType.name().toLower() == "speex") - m_codec = new QXmppSpeexCodec(payloadType.clockrate()); -#endif - else - { - emit logMessage(QXmppLogger::WarningMessage, - QString("QXmppCall got an unknown codec : %1 (%2)") - .arg(QString::number(payloadType.id())) - .arg(payloadType.name())); - return; - } - - // size in bytes of an unencoded packet - m_outgoingChunk = SAMPLE_BYTES * payloadType.ptime() * payloadType.clockrate() / 1000; - - // initial number of bytes to buffer - m_incomingMinimum = m_outgoingChunk * 5; - - updateOpenMode(); -} - -void QXmppCall::addRemoteCandidates(const QList<QXmppJingleCandidate> &candidates) -{ - foreach (const QXmppJingleCandidate &candidate, candidates) - { - m_socket->addRemoteCandidate(candidate); - m_rtcpSocket->addRemoteCandidate(candidate); - } -} - -void QXmppCall::setRemoteUser(const QString &user) -{ - m_socket->setRemoteUser(user); - m_rtcpSocket->setRemoteUser(user); -} - -void QXmppCall::setRemotePassword(const QString &password) -{ - m_socket->setRemotePassword(password); - m_rtcpSocket->setRemotePassword(password); -} - -void QXmppCall::updateOpenMode() -{ - // determine mode - if (m_codec && m_socket->isConnected() && m_state != ActiveState) - { - open(QIODevice::ReadWrite); - setState(ActiveState); - emit connected(); - } -} - -void QXmppCall::datagramReceived(const QByteArray &buffer) -{ - if (!m_codec) - { - emit logMessage(QXmppLogger::WarningMessage, - QLatin1String("QXmppCall:datagramReceived before codec selection")); - return; - } - - if (buffer.size() < 12 || (quint8(buffer.at(0)) >> 6) != RTP_VERSION) - { - emit logMessage(QXmppLogger::WarningMessage, - QLatin1String("QXmppCall::datagramReceived got an invalid RTP packet")); - return; - } - - // parse RTP header - QDataStream stream(buffer); - quint8 version, type; - quint32 ssrc; - quint16 sequence; - quint32 stamp; - stream >> version; - stream >> type; - stream >> sequence; - stream >> stamp; - stream >> ssrc; - const qint64 packetLength = buffer.size() - 12; - -#ifdef QXMPP_DEBUG_RTP - emit logMessage(QXmppLogger::ReceivedMessage, - QString("RTP packet seq %1 stamp %2 size %3") - .arg(QString::number(sequence)) - .arg(QString::number(stamp)) - .arg(QString::number(packetLength))); -#endif - - // check sequence number - if (sequence != m_incomingSequence + 1) - emit logMessage(QXmppLogger::WarningMessage, - QString("RTP packet seq %1 is out of order, previous was %2") - .arg(QString::number(sequence)) - .arg(QString::number(m_incomingSequence))); - m_incomingSequence = sequence; - - // determine packet's position in the buffer (in bytes) - qint64 packetOffset = 0; - if (!buffer.isEmpty()) - { - packetOffset = (stamp - m_incomingStamp) * SAMPLE_BYTES; - if (packetOffset < 0) - { - emit logMessage(QXmppLogger::WarningMessage, - QString("RTP packet stamp %1 is too old, buffer start is %2") - .arg(QString::number(stamp)) - .arg(QString::number(m_incomingStamp))); - return; - } - } else { - m_incomingStamp = stamp; - } - - // allocate space for new packet - if (packetOffset + packetLength > m_incomingBuffer.size()) - m_incomingBuffer += QByteArray(packetOffset + packetLength - m_incomingBuffer.size(), 0); - QDataStream output(&m_incomingBuffer, QIODevice::WriteOnly); - output.device()->seek(packetOffset); - output.setByteOrder(QDataStream::LittleEndian); - m_codec->decode(stream, output); - - // check whether we have filled the initial buffer - if (m_incomingBuffer.size() >= m_incomingMinimum) - m_incomingBuffering = false; - if (!m_incomingBuffering) - emit readyRead(); -} - -/// Returns the call's session identifier. -/// - -QString QXmppCall::sid() const -{ - return m_sid; -} - -/// Returns the call's state. -/// -/// \sa stateChanged() - -QXmppCall::State QXmppCall::state() const -{ - return m_state; -} - -void QXmppCall::setState(QXmppCall::State state) -{ - if (m_state != state) - { - m_state = state; - emit stateChanged(m_state); - } -} - -qint64 QXmppCall::readData(char * data, qint64 maxSize) -{ - // if we are filling the buffer, return empty samples - if (m_incomingBuffering) - { - memset(data, 0, maxSize); - return maxSize; - } - - qint64 readSize = qMin(maxSize, qint64(m_incomingBuffer.size())); - memcpy(data, m_incomingBuffer.constData(), readSize); - m_incomingBuffer.remove(0, readSize); - if (readSize < maxSize) - { - emit logMessage(QXmppLogger::InformationMessage, - QString("QXmppCall::readData missing %1 bytes").arg(QString::number(maxSize - readSize))); - memset(data + readSize, 0, maxSize - readSize); - } - m_incomingStamp += readSize / SAMPLE_BYTES; - return maxSize; -} - -qint64 QXmppCall::writeData(const char * data, qint64 maxSize) -{ - if (!m_codec) - { - emit logMessage(QXmppLogger::WarningMessage, - QLatin1String("QXmppCall::writeData before codec was set")); - return -1; - } - - m_outgoingBuffer.append(data, maxSize); - while (m_outgoingBuffer.size() >= m_outgoingChunk) - { - QByteArray header; - QDataStream stream(&header, QIODevice::WriteOnly); - quint8 version = RTP_VERSION << 6; - stream << version; - quint8 type = m_payloadType.id(); - if (m_outgoingMarker) - { - type |= 0x80; - m_outgoingMarker= false; - } - stream << type; - stream << ++m_outgoingSequence; - stream << m_outgoingStamp; - const quint32 ssrc = 0; - stream << ssrc; - - QByteArray chunk = m_outgoingBuffer.left(m_outgoingChunk); - QDataStream input(chunk); - input.setByteOrder(QDataStream::LittleEndian); - m_outgoingStamp += m_codec->encode(input, stream); - - if (m_socket->writeDatagram(header) < 0) - emit logMessage(QXmppLogger::WarningMessage, - QLatin1String("QXmppCall:writeData could not send audio data")); -#ifdef QXMPP_DEBUG_RTP - else - emit logMessage(QXmppLogger::SentMessage, - QString("RTP packet seq %1 stamp %2 size %3") - .arg(QString::number(m_outgoingSequence)) - .arg(QString::number(m_outgoingStamp)) - .arg(QString::number(header.size() - 12))); -#endif - - m_outgoingBuffer.remove(0, chunk.size()); - } - - m_writtenSinceLastEmit += maxSize; - if (!m_signalsEmitted && !signalsBlocked()) { - m_signalsEmitted = true; - QMetaObject::invokeMethod(this, "emitSignals", Qt::QueuedConnection); - } - - return maxSize; -} - -QXmppCallManager::QXmppCallManager(QXmppStream *stream, QObject *parent) - : QObject(parent), m_stream(stream) -{ - // setup logging - bool check = connect(this, SIGNAL(logMessage(QXmppLogger::MessageType, QString)), - m_stream, SIGNAL(logMessage(QXmppLogger::MessageType, QString))); - Q_ASSERT(check); - - check = connect(stream, SIGNAL(iqReceived(QXmppIq)), - this, SLOT(iqReceived(QXmppIq))); - Q_ASSERT(check); - - check = connect(stream, SIGNAL(jingleIqReceived(QXmppJingleIq)), - this, SLOT(jingleIqReceived(QXmppJingleIq))); - Q_ASSERT(check); -} - -/// Initiates a new outgoing call to the specified recipient. -/// -/// \param jid - -QXmppCall *QXmppCallManager::call(const QString &jid) -{ - QXmppCall *call = new QXmppCall(jid, QXmppCall::OutgoingDirection, this); - call->m_sid = generateStanzaHash(); - m_calls << call; - connect(call, SIGNAL(destroyed(QObject*)), this, SLOT(callDestroyed(QObject*))); - connect(call, SIGNAL(stateChanged(QXmppCall::State)), - this, SLOT(callStateChanged(QXmppCall::State))); - connect(call, SIGNAL(logMessage(QXmppLogger::MessageType, QString)), - this, SIGNAL(logMessage(QXmppLogger::MessageType, QString))); - - QXmppJingleIq iq; - iq.setTo(jid); - iq.setType(QXmppIq::Set); - iq.setAction(QXmppJingleIq::SessionInitiate); - iq.setInitiator(m_stream->configuration().jid()); - iq.setSid(call->m_sid); - iq.content().setCreator("initiator"); - iq.content().setName("voice"); - iq.content().setSenders("both"); - - // description - iq.content().setDescriptionMedia("audio"); - foreach (const QXmppJinglePayloadType &payload, localPayloadTypes()) - iq.content().addPayloadType(payload); - - // transport - iq.content().setTransportUser(call->m_socket->localUser()); - iq.content().setTransportPassword(call->m_socket->localPassword()); - foreach (const QXmppJingleCandidate &candidate, call->localCandidates()) - iq.content().addTransportCandidate(candidate); - - sendRequest(call, iq); - - return call; -} - -void QXmppCallManager::callDestroyed(QObject *object) -{ - m_calls.removeAll(static_cast<QXmppCall*>(object)); -} - -void QXmppCallManager::callStateChanged(QXmppCall::State state) -{ - QXmppCall *call = qobject_cast<QXmppCall*>(sender()); - if (!call || !m_calls.contains(call)) - return; - -#if 0 - // disconnect from the signal - disconnect(call, SIGNAL(stateChanged(QXmppCall::State)), - this, SLOT(callStateChanged(QXmppCall::State))); -#endif - - if (state == QXmppCall::DisconnectingState) - { - // hangup up call - QXmppJingleIq iq; - iq.setTo(call->jid()); - iq.setType(QXmppIq::Set); - iq.setAction(QXmppJingleIq::SessionTerminate); - iq.setSid(call->m_sid); - sendRequest(call, iq); - - // schedule forceful termination in 5s - QTimer::singleShot(5000, call, SLOT(terminate())); - } - else if (state == QXmppCall::ConnectingState && - call->direction() == QXmppCall::IncomingDirection) - { - // accept incoming call - QXmppJingleIq iq; - iq.setTo(call->jid()); - iq.setType(QXmppIq::Set); - iq.setAction(QXmppJingleIq::SessionAccept); - iq.setResponder(m_stream->configuration().jid()); - iq.setSid(call->m_sid); - iq.content().setCreator("initiator"); - iq.content().setName(call->m_contentName); - - // description - iq.content().setDescriptionMedia("audio"); - foreach (const QXmppJinglePayloadType &payload, call->m_commonPayloadTypes) - iq.content().addPayloadType(payload); - - // transport - iq.content().setTransportUser(call->m_socket->localUser()); - iq.content().setTransportPassword(call->m_socket->localPassword()); - foreach (const QXmppJingleCandidate &candidate, call->localCandidates()) - iq.content().addTransportCandidate(candidate); - - sendRequest(call, iq); - - // perform ICE negotiation - call->connectToHost(); - } -} - -/// Determine common payload types for a call. -/// - -bool QXmppCallManager::checkPayloadTypes(QXmppCall *call, const QList<QXmppJinglePayloadType> &remotePayloadTypes) -{ - foreach (const QXmppJinglePayloadType &payload, localPayloadTypes()) - { - int payloadIndex = remotePayloadTypes.indexOf(payload); - if (payloadIndex >= 0) - call->m_commonPayloadTypes << remotePayloadTypes[payloadIndex]; - } - if (call->m_commonPayloadTypes.isEmpty()) - { - emit logMessage(QXmppLogger::WarningMessage, - QString("Remote party %1 did not provide any known payload types for call %2").arg(call->jid(), call->sid())); - - // terminate call - QXmppJingleIq iq; - iq.setTo(call->jid()); - iq.setType(QXmppIq::Set); - iq.setAction(QXmppJingleIq::SessionTerminate); - iq.setSid(call->sid()); - iq.reason().setType(QXmppJingleIq::Reason::FailedApplication); - sendRequest(call, iq); - return false; - } else { - call->setPayloadType(call->m_commonPayloadTypes.first()); - return true; - } -} - -QXmppCall *QXmppCallManager::findCall(const QString &sid) const -{ - foreach (QXmppCall *call, m_calls) - if (call->m_sid == sid) - return call; - return 0; -} - -QXmppCall *QXmppCallManager::findCall(const QString &sid, QXmppCall::Direction direction) const -{ - foreach (QXmppCall *call, m_calls) - if (call->m_sid == sid && call->m_direction == direction) - return call; - return 0; -} - -/// Returns the list of locally supported payload types. -/// - -QList<QXmppJinglePayloadType> QXmppCallManager::localPayloadTypes() const -{ - QList<QXmppJinglePayloadType> payloads; - QXmppJinglePayloadType payload; - -#ifdef QXMPP_USE_SPEEX - payload.setId(96); - payload.setChannels(1); - payload.setName("SPEEX"); - payload.setClockrate(16000); - payloads << payload; - - payload.setId(97); - payload.setChannels(1); - payload.setName("SPEEX"); - payload.setClockrate(8000); - payloads << payload; -#endif - - payload.setId(G711u); - payload.setChannels(1); - payload.setName("PCMU"); - payload.setClockrate(8000); - payloads << payload; - - payload.setId(G711a); - payload.setChannels(1); - payload.setName("PCMA"); - payload.setClockrate(8000); - payloads << payload; - - return payloads; -} - -/// Handles acknowledgements -/// - -void QXmppCallManager::iqReceived(const QXmppIq &ack) -{ - if (ack.type() != QXmppIq::Result) - return; - - // find request - bool found = false; - QXmppCall *call = 0; - QXmppJingleIq request; - foreach (call, m_calls) - { - for (int i = 0; i < call->m_requests.size(); i++) - { - if (ack.id() == call->m_requests[i].id()) - { - request = call->m_requests.takeAt(i); - found = true; - break; - } - } - if (found) - break; - } - if (!found) - return; - - // process acknowledgement - emit logMessage(QXmppLogger::DebugMessage, QString("Received ACK for packet %1").arg(ack.id())); - if (request.action() == QXmppJingleIq::SessionTerminate) - { - // terminate - call->terminate(); - } -} - -/// Handle Jingle IQs. -/// - -void QXmppCallManager::jingleIqReceived(const QXmppJingleIq &iq) -{ - if (iq.type() != QXmppIq::Set) - return; - - if (iq.action() == QXmppJingleIq::SessionInitiate) - { - // build call - QXmppCall *call = new QXmppCall(iq.from(), QXmppCall::IncomingDirection, this); - call->m_sid = iq.sid(); - call->m_contentName = iq.content().name(); - call->setRemoteUser(iq.content().transportUser()); - call->setRemotePassword(iq.content().transportPassword()); - call->addRemoteCandidates(iq.content().transportCandidates()); - - // send ack - sendAck(iq); - - // determine common payload types - if (!checkPayloadTypes(call, iq.content().payloadTypes())) - { - delete call; - return; - } - - // register call - m_calls.append(call); - connect(call, SIGNAL(stateChanged(QXmppCall::State)), - this, SLOT(callStateChanged(QXmppCall::State))); - connect(call, SIGNAL(logMessage(QXmppLogger::MessageType, QString)), - this, SIGNAL(logMessage(QXmppLogger::MessageType, QString))); - - // send ringing indication - QXmppJingleIq ringing; - ringing.setTo(call->jid()); - ringing.setType(QXmppIq::Set); - ringing.setAction(QXmppJingleIq::SessionInfo); - ringing.setSid(call->sid()); - ringing.setRinging(true); - sendRequest(call, ringing); - - // notify user - emit callReceived(call); - - } else if (iq.action() == QXmppJingleIq::SessionAccept) { - QXmppCall *call = findCall(iq.sid(), QXmppCall::OutgoingDirection); - if (!call) - { - emit logMessage(QXmppLogger::WarningMessage, - QString("Remote party %1 accepted unknown call %2").arg(iq.from(), iq.sid())); - return; - } - - // send ack - sendAck(iq); - - // determine common payload types - if (!checkPayloadTypes(call, iq.content().payloadTypes())) - { - delete call; - return; - } - - // perform ICE negotiation - if (!iq.content().transportCandidates().isEmpty()) - { - call->setRemoteUser(iq.content().transportUser()); - call->setRemotePassword(iq.content().transportPassword()); - call->addRemoteCandidates(iq.content().transportCandidates()); - } - call->connectToHost(); - - } else if (iq.action() == QXmppJingleIq::SessionInfo) { - - QXmppCall *call = findCall(iq.sid()); - if (!call) - return; - - // notify user - QTimer::singleShot(0, call, SIGNAL(ringing())); - - } else if (iq.action() == QXmppJingleIq::SessionTerminate) { - - QXmppCall *call = findCall(iq.sid()); - if (!call) - { - emit logMessage(QXmppLogger::WarningMessage, - QString("Remote party %1 terminated unknown call %2").arg(iq.from(), iq.sid())); - return; - } - - emit logMessage(QXmppLogger::InformationMessage, - QString("Remote party %1 terminated call %2").arg(iq.from(), iq.sid())); - - // send ack - sendAck(iq); - - // terminate - call->terminate(); - - } else if (iq.action() == QXmppJingleIq::TransportInfo) { - QXmppCall *call = findCall(iq.sid()); - if (!call) - { - emit logMessage(QXmppLogger::WarningMessage, - QString("Remote party %1 sent transports for unknown call %2").arg(iq.from(), iq.sid())); - return; - } - - // send ack - sendAck(iq); - - // perform ICE negotiation - call->setRemoteUser(iq.content().transportUser()); - call->setRemotePassword(iq.content().transportPassword()); - call->addRemoteCandidates(iq.content().transportCandidates()); - call->connectToHost(); - } -} - -/// Sends an acknowledgement for a Jingle IQ. -/// - -bool QXmppCallManager::sendAck(const QXmppJingleIq &iq) -{ - QXmppIq ack; - ack.setId(iq.id()); - ack.setTo(iq.from()); - ack.setType(QXmppIq::Result); - return m_stream->sendPacket(ack); -} - -/// Sends a Jingle IQ and adds it to outstanding requests. -/// - -bool QXmppCallManager::sendRequest(QXmppCall *call, const QXmppJingleIq &iq) -{ - call->m_requests << iq; - return m_stream->sendPacket(iq); -} - diff --git a/source/QXmppCallManager.h b/source/QXmppCallManager.h deleted file mode 100644 index 6cc18b19..00000000 --- a/source/QXmppCallManager.h +++ /dev/null @@ -1,218 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPCALLMANAGER_H -#define QXMPPCALLMANAGER_H - -#include <QObject> -#include <QIODevice> - -#include "QXmppJingleIq.h" -#include "QXmppLogger.h" - -class QXmppCodec; -class QXmppJingleCandidate; -class QXmppJingleIq; -class QXmppJinglePayloadType; -class QXmppStream; -class QXmppStunSocket; - -/// \brief The QXmppCall class represents a Voice-Over-IP call to a remote party. -/// -/// It acts as a QIODevice so that you can read / write audio samples, for -/// instance using a QAudioOutput and a QAudioInput. -/// -/// \note THIS API IS NOT FINALIZED YET - -class QXmppCall : public QIODevice -{ - Q_OBJECT - -public: - /// This enum is used to describe the direction of a call. - enum Direction - { - IncomingDirection, ///< The call is incoming. - OutgoingDirection, ///< The call is outgoing. - }; - - /// This enum is used to describe the state of a call. - enum State - { - OfferState = 0, ///< The remote part is being called. - ConnectingState = 1, ///< The call is being connected. - ActiveState = 2, ///< The call is active. - DisconnectingState = 3, ///< The call is being disconnected. - FinishedState = 4, ///< The call is finished. - }; - - QXmppCall::Direction direction() const; - QString jid() const; - QString sid() const; - QXmppCall::State state() const; - - QXmppJinglePayloadType payloadType() const; - - /// \cond - qint64 bytesAvailable() const; - bool isSequential() const; - /// \endcond - -signals: - /// This signal is emitted when a call is connected. - /// - /// Once this signal is emitted, you can connect a QAudioOutput and - /// QAudioInput to the call. You can determine the appropriate clockrate - /// and the number of channels by calling payloadType(). - void connected(); - - /// This signal is emitted when a call is finished. - /// - /// Note: Do not delete the call in the slot connected to this signal, - /// instead use deleteLater(). - void finished(); - - /// This signal is emitted when the remote party is ringing. - void ringing(); - - /// This signal is emitted to send logging messages. - void logMessage(QXmppLogger::MessageType type, const QString &msg); - - /// This signal is emitted when the call state changes. - void stateChanged(QXmppCall::State state); - -public slots: - void accept(); - void hangup(); - -private slots: - void datagramReceived(const QByteArray &datagram); - void emitSignals(); - void updateOpenMode(); - void terminate(); - void terminated(); - -protected: - /// \cond - qint64 readData(char * data, qint64 maxSize); - qint64 writeData(const char * data, qint64 maxSize); - /// \endcond - -private: - QXmppCall(const QString &jid, QXmppCall::Direction direction, QObject *parent); - void connectToHost(); - QList<QXmppJingleCandidate> localCandidates() const; - void setPayloadType(const QXmppJinglePayloadType &type); - void addRemoteCandidates(const QList<QXmppJingleCandidate> &candidates); - void setRemoteUser(const QString &user); - void setRemotePassword(const QString &password); - void setState(QXmppCall::State state); - - Direction m_direction; - QString m_jid; - QString m_sid; - State m_state; - QString m_contentName; - QXmppJinglePayloadType m_payloadType; - - QList<QXmppJingleIq> m_requests; - QList<QXmppJinglePayloadType> m_commonPayloadTypes; - - // ICE-UDP - QXmppStunSocket *m_socket; - QXmppStunSocket *m_rtcpSocket; - - // signals - bool m_signalsEmitted; - qint64 m_writtenSinceLastEmit; - - // RTP - QXmppCodec *m_codec; - - QByteArray m_incomingBuffer; - bool m_incomingBuffering; - int m_incomingMinimum; - quint16 m_incomingSequence; - quint32 m_incomingStamp; - - quint16 m_outgoingChunk; - QByteArray m_outgoingBuffer; - bool m_outgoingMarker; - quint16 m_outgoingSequence; - quint32 m_outgoingStamp; - - friend class QXmppCallManager; -}; - -/// \brief The QXmppCallManager class provides support for making and -/// receiving voice calls. -/// -/// Session initiation is performed as described by XEP-0166: Jingle, -/// XEP-0167: Jingle RTP Sessions and XEP-0176: Jingle ICE-UDP Transport -/// Method. -/// -/// The data stream is connected using Interactive Connectivity Establishment -/// (RFC 5245) and data is transfered using Real Time Protocol (RFC 3550) -/// packets. -/// -/// \ingroup Managers - -class QXmppCallManager : public QObject -{ - Q_OBJECT - -public: - QXmppCallManager(QXmppStream *stream, QObject *parent = 0); - QXmppCall *call(const QString &jid); - -signals: - /// This signal is emitted when a new incoming call is received. - /// - /// To accept the call, invoke the call's QXmppCall::accept() method. - /// To refuse the call, invoke the call's QXmppCall::abort() method. - void callReceived(QXmppCall *call); - - /// This signal is emitted to send logging messages. - void logMessage(QXmppLogger::MessageType type, const QString &msg); - -private slots: - void callDestroyed(QObject *object); - void callStateChanged(QXmppCall::State state); - void iqReceived(const QXmppIq &iq); - void jingleIqReceived(const QXmppJingleIq &iq); - -private: - bool checkPayloadTypes(QXmppCall *call, const QList<QXmppJinglePayloadType> &remotePayloadTypes); - QXmppCall *findCall(const QString &sid) const; - QXmppCall *findCall(const QString &sid, QXmppCall::Direction direction) const; - QList<QXmppJinglePayloadType> localPayloadTypes() const; - bool sendAck(const QXmppJingleIq &iq); - bool sendRequest(QXmppCall *call, const QXmppJingleIq &iq); - - QList<QXmppCall*> m_calls; - - // reference to xmpp stream (no ownership) - QXmppStream* m_stream; -}; - -#endif diff --git a/source/QXmppClient.cpp b/source/QXmppClient.cpp deleted file mode 100644 index e88449b0..00000000 --- a/source/QXmppClient.cpp +++ /dev/null @@ -1,642 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppClient.h" -#include "QXmppLogger.h" -#include "QXmppStream.h" -#include "QXmppMessage.h" - -#include "QXmppArchiveManager.h" -#include "QXmppCallManager.h" -#include "QXmppInvokable.h" -#include "QXmppMucManager.h" -#include "QXmppReconnectionManager.h" -#include "QXmppRpcIq.h" -#include "QXmppRemoteMethod.h" -#include "QXmppRosterManager.h" -#include "QXmppUtils.h" -#include "QXmppTransferManager.h" -#include "QXmppVCardManager.h" - -/// \mainpage -/// -/// QXmpp is a cross-platform C++ XMPP client library based on the Qt -/// framework. It tries to use Qt's programming conventions in order to ease -/// the learning curve for new programmers. -/// -/// QXmpp based clients are built using QXmppClient instances which handle the -/// establishment of the XMPP connection and provide a number of high-level -/// "managers" to perform specific tasks: -/// -/// \sa QXmppCallManager -/// \sa QXmppMucManager -/// \sa QXmppRosterManager -/// \sa QXmppVCardManager -/// \sa QXmppTransferManager -/// -/// If you are interested in a more low-level API, you can refer to the -/// classes which represent XMPP stanzas. -/// -/// \sa QXmppIq -/// \sa QXmppMessage -/// \sa QXmppPresence - -/// Creates a QXmppClient object. -/// \param parent is passed to the QObject's contructor. -/// The default value is 0. - -QXmppClient::QXmppClient(QObject *parent) - : QObject(parent), - m_stream(0), - m_clientPresence(QXmppPresence::Available), - m_reconnectionManager(0) -{ - m_stream = new QXmppStream(this); - m_clientPresence.setExtensions(m_stream->presenceExtensions()); - - bool check = connect(m_stream, SIGNAL(elementReceived(const QDomElement&, bool&)), - this, SIGNAL(elementReceived(const QDomElement&, bool&))); - Q_ASSERT(check); - - check = connect(m_stream, SIGNAL(messageReceived(const QXmppMessage&)), - this, SIGNAL(messageReceived(const QXmppMessage&))); - Q_ASSERT(check); - - check = connect(m_stream, SIGNAL(presenceReceived(const QXmppPresence&)), - this, SIGNAL(presenceReceived(const QXmppPresence&))); - Q_ASSERT(check); - - check = connect(m_stream, SIGNAL(iqReceived(const QXmppIq&)), this, - SIGNAL(iqReceived(const QXmppIq&))); - Q_ASSERT(check); - - check = connect(m_stream, SIGNAL(discoveryIqReceived(const QXmppDiscoveryIq&)), this, - SIGNAL(discoveryIqReceived(const QXmppDiscoveryIq&))); - Q_ASSERT(check); - - check = connect(m_stream, SIGNAL(disconnected()), this, - SIGNAL(disconnected())); - Q_ASSERT(check); - - check = connect(m_stream, SIGNAL(xmppConnected()), this, - SLOT(xmppConnected())); - Q_ASSERT(check); - - check = connect(m_stream, SIGNAL(xmppConnected()), this, - SIGNAL(connected())); - Q_ASSERT(check); - - check = connect(m_stream, SIGNAL(error(QXmppClient::Error)), this, - SIGNAL(error(QXmppClient::Error))); - Q_ASSERT(check); - - check = setReconnectionManager(new QXmppReconnectionManager(this)); - Q_ASSERT(check); - - // rpc - check = connect(m_stream, SIGNAL(rpcCallInvoke(QXmppRpcInvokeIq)), - this, SLOT(invokeInterfaceMethod(QXmppRpcInvokeIq))); - Q_ASSERT(check); - - // logging - check = connect(this, SIGNAL(logMessage(QXmppLogger::MessageType, QString)), - m_stream, SIGNAL(logMessage(QXmppLogger::MessageType, QString))); - Q_ASSERT(check); - - // create managers - m_rosterManager = new QXmppRosterManager(m_stream, this); - m_archiveManager = new QXmppArchiveManager(m_stream, this); - m_callManager = new QXmppCallManager(m_stream, this); - m_mucManager = new QXmppMucManager(m_stream, this); - m_transferManager = new QXmppTransferManager(m_stream, this); - m_vCardManager = new QXmppVCardManager(m_stream, this); -} - -/// Destructor, destroys the QXmppClient object. -/// - -QXmppClient::~QXmppClient() -{ -} - -/// Returns a modifiable reference to the current configuration of QXmppClient. -/// \return Reference to the QXmppClient's configuration for the connection. - -QXmppConfiguration& QXmppClient::configuration() -{ - return m_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, passwd 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) -{ - m_stream->configuration() = config; - if(!config.autoReconnectionEnabled()) - { - delete m_reconnectionManager; - m_reconnectionManager = 0; - } - - m_clientPresence = initialPresence; - m_clientPresence.setExtensions(m_stream->presenceExtensions()); - - m_stream->connect(); -} - -/// Overloaded function. -/// \param host host name of the XMPP server where connection has to be made -/// (e.g. "jabber.org" and "talk.google.com"). It can also be an IP address in -/// the form of a string (e.g. "192.168.1.25"). -/// \param user Username of the account at the specified XMPP server. It should -/// be the name without the domain name. E.g. "qxmpp.test1" and not -/// "qxmpp.test1@gmail.com" -/// \param passwd Password for the specified username -/// \param domain Domain name e.g. "gmail.com" and "jabber.org". -/// \param port Port number at which the XMPP server is listening. The default -/// value is 5222. -/// \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 QString& host, const QString& user, - const QString& passwd, const QString& domain, - int port, - const QXmppPresence& initialPresence) -{ - QXmppConfiguration &config = m_stream->configuration(); - config.setHost(host); - config.setUser(user); - config.setPasswd(passwd); - config.setDomain(domain); - config.setPort(port); - - m_clientPresence = initialPresence; - m_clientPresence.setExtensions(m_stream->presenceExtensions()); - - m_stream->connect(); -} - -/// Overloaded function. -/// \param host host name of the XMPP server where connection has to be made -/// (e.g. "jabber.org" and "talk.google.com"). It can also be an IP address in -/// the form of a string (e.g. "192.168.1.25"). -/// \param bareJid BareJid of the account at the specified XMPP server. -/// (e.g. "qxmpp.test1@gmail.com" or qxmpptest@jabber.org.) -/// \param passwd Password for the specified username -/// \param port Port number at which the XMPP server is listening. The default -/// value is 5222. -/// \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 QString& host, - const QString& bareJid, - const QString& passwd, - int port, - const QXmppPresence& initialPresence) -{ - QString user, domain; - QStringList list = bareJid.split("@"); - if(list.size() == 2) - { - user = list.at(0); - domain = list.at(1); - connectToServer(host, user, passwd, domain, port, initialPresence); - } - else - { - emit logMessage(QXmppLogger::WarningMessage, "Invalid bareJid"); - } -} - -/// 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. QXmppPacket is a parent class of all the stanzas -/// QXmppMessage, QXmppPresence, QXmppIq, QXmppBind, QXmppRosterIq, QXmppSession -/// and QXmppVCard. -/// -/// \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 QXmppPacket& packet) -{ - return m_stream->sendPacket(packet); -} - -/// 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 disconnect() function. -/// - -void QXmppClient::disconnect() -{ - m_clientPresence.setType(QXmppPresence::Unavailable); - m_clientPresence.status().setType(QXmppPresence::Status::Offline); - m_clientPresence.status().setStatusText("Logged out"); - if (m_stream->isConnected()) - { - sendPacket(m_clientPresence); - m_stream->disconnect(); - } -} - -/// Returns true if the client is connected to the XMPP server. -/// - -bool QXmppClient::isConnected() const -{ - return m_stream && m_stream->isConnected(); -} - -/// 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. -/// - -QXmppRosterManager& QXmppClient::rosterManager() -{ - return *m_rosterManager; -} - -/// Utility function to send message to all the resources associated with the -/// specified bareJid. -/// -/// \param bareJid bareJid of the receiving entity -/// \param message Message string to be sent. - -void QXmppClient::sendMessage(const QString& bareJid, const QString& message) -{ - QStringList resources = rosterManager().getResources(bareJid); - for(int i = 0; i < resources.size(); ++i) - { - sendPacket(QXmppMessage("", bareJid + "/" + resources.at(i), message)); - } -} - -/// Returns the client's current presence. -/// - -QXmppPresence QXmppClient::clientPresence() const -{ - return m_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) -{ - if (presence.type() == QXmppPresence::Unavailable) - { - m_clientPresence = presence; - - // NOTE: we can't call disconnect() because it alters - // the client presence - if (m_stream->isConnected()) - { - sendPacket(m_clientPresence); - m_stream->disconnect(); - } - } - else if (!m_stream->isConnected()) - connectToServer(m_stream->configuration(), presence); - else - { - m_clientPresence = presence; - m_clientPresence.setExtensions(m_stream->presenceExtensions()); - sendPacket(m_clientPresence); - } -} - -/// Function to get reconnection manager. By default there exists a reconnection -/// manager. See QXmppReconnectionManager for more details of the reconnection -/// mechanism. -/// -/// \return Pointer to QXmppReconnectionManager -/// - -QXmppReconnectionManager* QXmppClient::getReconnectionManager() -{ - return m_reconnectionManager; -} - -/// Sets the user defined reconnection manager. -/// -/// \return true if all the signal-slot connections are made correctly. -/// - -bool QXmppClient::setReconnectionManager(QXmppReconnectionManager* - reconnectionManager) -{ - if(!reconnectionManager) - return false; - - if(m_reconnectionManager) - delete m_reconnectionManager; - - m_reconnectionManager = reconnectionManager; - - bool check = connect(this, SIGNAL(connected()), m_reconnectionManager, - SLOT(connected())); - Q_ASSERT(check); - if(!check) - return false; - - check = connect(this, SIGNAL(error(QXmppClient::Error)), - m_reconnectionManager, SLOT(error(QXmppClient::Error))); - Q_ASSERT(check); - if(!check) - return false; - - return true; -} - -/// Returns the socket error if error() is QXmppClient::SocketError. -/// - -QAbstractSocket::SocketError QXmppClient::socketError() -{ - return m_stream->socketError(); -} - -/// Returns the XMPP stream error if QXmppClient::Error is QXmppClient::XmppStreamError. -/// - -QXmppStanza::Error::Condition QXmppClient::xmppStreamError() -{ - return m_stream->xmppStreamError(); -} - -/// Returns the reference to QXmppVCardManager, implimentation of XEP-0054. -/// http://xmpp.org/extensions/xep-0054.html -/// - -QXmppVCardManager& QXmppClient::vCardManager() -{ - return *m_vCardManager; -} - -void QXmppClient::addInvokableInterface( QXmppInvokable *interface ) -{ - m_interfaces[ interface->metaObject()->className() ] = interface; -} - - -void QXmppClient::invokeInterfaceMethod( const QXmppRpcInvokeIq &iq ) -{ - QXmppStanza::Error error; - - const QStringList methodBits = iq.method().split('.'); - if (methodBits.size() != 2) - return; - const QString interface = methodBits.first(); - const QString method = methodBits.last(); - QXmppInvokable *iface = m_interfaces.value(interface); - if (iface) - { - if ( iface->isAuthorized( iq.from() ) ) - { - - if ( iface->interfaces().contains(method) ) - { - QVariant result = iface->dispatch(method.toLatin1(), - iq.arguments() ); - QXmppRpcResponseIq resultIq; - resultIq.setId(iq.id()); - resultIq.setTo(iq.from()); - resultIq.setFrom(m_stream->configuration().jid()); - resultIq.setValues(QVariantList() << result); - m_stream->sendPacket( resultIq ); - return; - } - else - { - error.setType(QXmppStanza::Error::Cancel); - error.setCondition(QXmppStanza::Error::ItemNotFound); - - } - } - else - { - error.setType(QXmppStanza::Error::Auth); - error.setCondition(QXmppStanza::Error::Forbidden); - } - } - else - { - error.setType(QXmppStanza::Error::Cancel); - error.setCondition(QXmppStanza::Error::ItemNotFound); - } - QXmppRpcErrorIq errorIq; - errorIq.setId(iq.id()); - errorIq.setTo(iq.from()); - errorIq.setFrom(m_stream->configuration().jid()); - errorIq.setQuery( iq ); - errorIq.setError( error ); - m_stream->sendPacket( errorIq ); -} - -QXmppRemoteMethodResult QXmppClient::callRemoteMethod( const QString &jid, - const QString &interface, - const QVariant &arg1, - const QVariant &arg2, - const QVariant &arg3, - const QVariant &arg4, - const QVariant &arg5, - const QVariant &arg6, - const QVariant &arg7, - const QVariant &arg8, - const QVariant &arg9, - const QVariant &arg10 ) -{ - QVariantList args; - if( arg1.isValid() ) args << arg1; - if( arg2.isValid() ) args << arg2; - if( arg3.isValid() ) args << arg3; - if( arg4.isValid() ) args << arg4; - if( arg5.isValid() ) args << arg5; - if( arg6.isValid() ) args << arg6; - if( arg7.isValid() ) args << arg7; - if( arg8.isValid() ) args << arg8; - if( arg9.isValid() ) args << arg9; - if( arg10.isValid() ) args << arg10; - - QXmppRemoteMethod method( jid, interface, args, this ); - connect( m_stream, SIGNAL(rpcCallResponse(QXmppRpcResponseIq)), - &method, SLOT(gotResult(QXmppRpcResponseIq))); - connect( m_stream, SIGNAL(rpcCallError(QXmppRpcErrorIq)), - &method, SLOT(gotError(QXmppRpcErrorIq))); - - - return method.call(); -} - -/// Returns the reference to QXmppArchiveManager, implementation of XEP-0136. -/// http://xmpp.org/extensions/xep-0136.html -/// - -QXmppArchiveManager& QXmppClient::archiveManager() -{ - return *m_archiveManager; -} - -/// Returns the reference to QXmppCallManager, implementation of XEP-0166. -/// http://xmpp.org/extensions/xep-0166.html -/// - -QXmppCallManager& QXmppClient::callManager() -{ - return *m_callManager; -} - -/// Returns the reference to QXmppMucManager, implementation of XEP-0045. -/// http://xmpp.org/extensions/xep-045.html -/// -QXmppMucManager& QXmppClient::mucManager() -{ - return *m_mucManager; -} - -/// Returns the reference to QXmppTransferManager, implementation of: -/// -/// * XEP-0047: In-Band Bytestreams -/// * XEP-0095: Stream Initiation -/// * XEP-0096: SI File Transfer -/// - -QXmppTransferManager& QXmppClient::transferManager() -{ - return *m_transferManager; -} - -/// Returns the QXmppLogger associated with the current QXmppClient. - -QXmppLogger *QXmppClient::logger() -{ - return m_stream->logger(); -} - -/// Sets the QXmppLogger associated with the current QXmppClient. - -void QXmppClient::setLogger(QXmppLogger *logger) -{ - m_stream->setLogger(logger); -} - -/// At connection establishment, send initial presence. - -void QXmppClient::xmppConnected() -{ - sendPacket(m_clientPresence); -} - -// obsolete - -const QXmppPresence& QXmppClient::getClientPresence() const -{ - return m_clientPresence; -} - -QXmppConfiguration& QXmppClient::getConfiguration() -{ - return m_stream->configuration(); -} - -const QXmppConfiguration& QXmppClient::getConfiguration() const -{ - return m_stream->configuration(); -} - -QXmppRosterManager& QXmppClient::getRoster() -{ - return *m_rosterManager; -} - -QAbstractSocket::SocketError QXmppClient::getSocketError() -{ - return m_stream->socketError(); -} - -QXmppVCardManager& QXmppClient::getVCardManager() -{ - return *m_vCardManager; -} - -QXmppStanza::Error::Condition QXmppClient::getXmppStreamError() -{ - return m_stream->xmppStreamError(); -} - -void QXmppClient::setClientPresence(const QString& statusText) -{ - QXmppPresence newPresence = m_clientPresence; - newPresence.status().setStatusText(statusText); - setClientPresence(newPresence); -} - -void QXmppClient::setClientPresence(QXmppPresence::Type presenceType) -{ - QXmppPresence newPresence = m_clientPresence; - newPresence.setType(presenceType); - setClientPresence(newPresence); -} - -void QXmppClient::setClientPresence(QXmppPresence::Status::Type statusType) -{ - QXmppPresence newPresence = m_clientPresence; - if (statusType == QXmppPresence::Status::Offline) - newPresence.setType(QXmppPresence::Unavailable); - else - newPresence.setType(QXmppPresence::Available); - newPresence.status().setType(statusType); - setClientPresence(newPresence); -} - diff --git a/source/QXmppClient.h b/source/QXmppClient.h deleted file mode 100644 index 1c748bb4..00000000 --- a/source/QXmppClient.h +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - -#ifndef QXMPPCLIENT_H -#define QXMPPCLIENT_H - -#include <QObject> -#include <QTcpSocket> -#include <QHash> -#include <QVariant> - -#include "QXmppConfiguration.h" -#include "QXmppLogger.h" -#include "QXmppPresence.h" - -class QXmppStream; -class QXmppPresence; -class QXmppMessage; -class QXmppPacket; -class QXmppIq; -class QXmppInvokable; -class QXmppRpcInvokeIq; -class QXmppRemoteMethod; -struct QXmppRemoteMethodResult; - -// managers -class QXmppArchiveManager; -class QXmppCallManager; -class QXmppDiscoveryIq; -class QXmppMucManager; -class QXmppReconnectionManager; -class QXmppRosterManager; -class QXmppTransferManager; -class QXmppVCardManager; - -/// \defgroup Core - -/// \defgroup Managers - -/// \brief The QXmppClient class is the main class for using QXmpp. -/// -/// It provides the user all the required functionality to connect to the server -/// and perform operations afterwards. -/// -/// This class will provide the handle/reference to QXmppRosterManager (roster management), -/// QXmppVCardManager (vCard manager), QXmppReconnectionManager (reconnection -/// mechanism) and QXmppTransferManager (file transfers). -/// -/// By default, a reconnection mechanism exists, which makes sure of reconnecting -/// to the server on disconnections due to an error. User can have a custom -/// reconnection mechanism as well. -/// -/// For removing QXmpp dependency in QtGui, use DEFINES += QXMPP_NO_GUI -/// in the source.pro file and build as usual. -/// -/// \ingroup Core - -class QXmppClient : public QObject -{ - Q_OBJECT - -public: - /// An enumeration for type of error. - /// Error could come due a TCP socket or XML stream or due to various stanzas. - enum Error - { - SocketError, ///< Error due to TCP socket - KeepAliveError, ///< Error due to no response to a keep alive - XmppStreamError, ///< Error due to XML stream - }; - - QXmppClient(QObject *parent = 0); - ~QXmppClient(); - void connectToServer(const QString& host, - const QString& user, - const QString& passwd, - const QString& domain, - int port = 5222, - const QXmppPresence& initialPresence = - QXmppPresence()); - void connectToServer(const QString& host, - const QString& bareJid, - const QString& passwd, - int port = 5222, - const QXmppPresence& initialPresence = - QXmppPresence()); - void connectToServer(const QXmppConfiguration&, - const QXmppPresence& initialPresence = - QXmppPresence()); - void disconnect(); - bool isConnected() const; - - QXmppPresence clientPresence() const; - void setClientPresence(const QXmppPresence &presence); - - QXmppConfiguration &configuration(); - QXmppLogger *logger(); - void setLogger(QXmppLogger *logger); - - QAbstractSocket::SocketError socketError(); - QXmppStanza::Error::Condition xmppStreamError(); - - QXmppArchiveManager& archiveManager(); - QXmppCallManager& callManager(); - QXmppMucManager& mucManager(); - QXmppRosterManager& rosterManager(); - QXmppTransferManager& transferManager(); - QXmppVCardManager& vCardManager(); - - // FIXME: these accessors should be deprecated in favour of - // versions without the "get". - QXmppReconnectionManager* getReconnectionManager(); - bool setReconnectionManager(QXmppReconnectionManager*); - - /// \cond - // FIXME: these methods are not in keeping with the "manager" approach, - // the whole RPC support either needs some love or should be pulled. - void addInvokableInterface( QXmppInvokable *interface ); - QXmppRemoteMethodResult callRemoteMethod( const QString &jid, - const QString &interface, - const QVariant &arg1 = QVariant(), - const QVariant &arg2 = QVariant(), - const QVariant &arg3 = QVariant(), - const QVariant &arg4 = QVariant(), - const QVariant &arg5 = QVariant(), - const QVariant &arg6 = QVariant(), - const QVariant &arg7 = QVariant(), - const QVariant &arg8 = QVariant(), - const QVariant &arg9 = QVariant(), - const QVariant &arg10 = QVariant() ); - - // deprecated accessors, use the form without "get" instead - const QXmppPresence Q_DECL_DEPRECATED & getClientPresence() const; - QXmppConfiguration Q_DECL_DEPRECATED & getConfiguration(); - const QXmppConfiguration Q_DECL_DEPRECATED & getConfiguration() const; - QXmppRosterManager Q_DECL_DEPRECATED & getRoster(); - QXmppVCardManager Q_DECL_DEPRECATED & getVCardManager(); - QAbstractSocket::SocketError Q_DECL_DEPRECATED getSocketError(); - QXmppStanza::Error::Condition Q_DECL_DEPRECATED getXmppStreamError(); - - // deprecated methods, use setClientPresence(QXmppPresence) instead. - void Q_DECL_DEPRECATED setClientPresence(const QString& statusText); - void Q_DECL_DEPRECATED setClientPresence(QXmppPresence::Type presenceType); - void Q_DECL_DEPRECATED setClientPresence(QXmppPresence::Status::Type statusType); - /// \endcond - -signals: - - /// This signal is emitted when the client connects sucessfully to the XMPP - /// server i.e. when a successful XMPP connection is established. - /// XMPP Connection involves following sequential steps: - /// - TCP socket connection - /// - Client sends start stream - /// - Server sends start stream - /// - TLS negotiation (encryption) - /// - Authentication - /// - Resource binding - /// - Session establishment - /// - /// After all these steps a successful XMPP connection is established and - /// connected() signal is emitted. - /// - /// After the connected() signal is emitted QXmpp will send the roster request - /// to the server. On receiving the roster, QXmpp will emit - /// QXmppRosterManager::rosterReceived(). After this signal, QXmppRosterManager object gets - /// populated and you can use rosterManager() to get the handle of QXmppRosterManager object. - /// - void connected(); - - /// This signal is emitted when the XMPP connection disconnects. - /// - void disconnected(); - - /// This signal is emitted when the XMPP connection encounters any error. - /// The QXmppClient::Error parameter specifies the type of error occured. - /// It could be due to TCP socket or the xml stream or the stanza. - /// Depending upon the type of error occured use the respective get function to - /// know the error. - void error(QXmppClient::Error); - - /// This signal is emitted when a raw XML element is received. You can - /// connect to this signal if you want to handle raw XML elements yourself. - /// - /// WARNING: this signal is experimental and you can seriously disrupt - /// packet handling when using it, so use with care and at your own risk. - /// - /// Set 'handled' to true if you handled the element yourself and you wish - /// to bypass normal handling for the element. If you do this, QXmpp will - /// do absolutely no processing itself, so do not expect the usual signals - /// to be emitted. - void elementReceived(const QDomElement &element, bool &handled); - - /// Notifies that an XMPP message stanza is received. The QXmppMessage - /// parameter contains the details of the message sent to this client. - /// In other words whenever someone sends you a message this signal is - /// emitted. - void messageReceived(const QXmppMessage&); - - /// Notifies that an XMPP presence stanza is received. The QXmppPresence - /// parameter contains the details of the presence sent to this client. - /// This signal is emitted when someone login/logout or when someone's status - /// changes Busy, Idle, Invisible etc. - void presenceReceived(const QXmppPresence&); - - /// Notifies that an XMPP iq stanza is received. The QXmppIq - /// parameter contains the details of the iq sent to this client. - /// IQ stanzas provide a structured request-response mechanism. Roster - /// management, setting-getting vCards etc is done using iq stanzas. - void iqReceived(const QXmppIq&); - - /// Notifies that an XMPP service discovery iq stanza is received. - void discoveryIqReceived(const QXmppDiscoveryIq&); - - /// This signal is emitted to send logging messages. - void logMessage(QXmppLogger::MessageType type, const QString &msg); - -public slots: - bool sendPacket(const QXmppPacket&); - void sendMessage(const QString& bareJid, const QString& message); - -private slots: - void invokeInterfaceMethod( const QXmppRpcInvokeIq &iq ); - void xmppConnected(); - -private: - QXmppStream* m_stream; ///< Pointer to QXmppStream object a wrapper over - ///< TCP socket and XMPP protocol - QXmppPresence m_clientPresence; ///< Stores the current presence of the connected client - QXmppArchiveManager *m_archiveManager; ///< Pointer to the archive manager - QXmppCallManager *m_callManager; ///< Pointer to the call manager - QXmppMucManager* m_mucManager; ///< Pointer to the multi-user chat manager - QXmppReconnectionManager* m_reconnectionManager; ///< Pointer to the reconnection manager - QXmppRosterManager *m_rosterManager; ///< Pointer to the roster manager - QXmppTransferManager *m_transferManager;///< Pointer to the transfer manager - QXmppVCardManager *m_vCardManager; ///< Pointer to the vCard manager - QHash<QString,QXmppInvokable *> m_interfaces; -}; - -#endif // QXMPPCLIENT_H diff --git a/source/QXmppCodec.cpp b/source/QXmppCodec.cpp deleted file mode 100644 index b9c49220..00000000 --- a/source/QXmppCodec.cpp +++ /dev/null @@ -1,352 +0,0 @@ -/* - * 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. - * - */ - -/* - * G.711 based on reference implementation by Sun Microsystems, Inc. - */ - -#include <QDataStream> -#include <QDebug> - -#include "QXmppCodec.h" - -#ifdef QXMPP_USE_SPEEX -#include <speex/speex.h> -#endif - -#define BIAS (0x84) /* Bias for linear code. */ -#define CLIP 8159 - -#define SIGN_BIT (0x80) /* Sign bit for a A-law byte. */ -#define QUANT_MASK (0xf) /* Quantization field mask. */ -#define NSEGS (8) /* Number of A-law segments. */ -#define SEG_SHIFT (4) /* Left shift for segment number. */ -#define SEG_MASK (0x70) /* Segment field mask. */ - -static qint16 seg_aend[8] = {0x1F, 0x3F, 0x7F, 0xFF, - 0x1FF, 0x3FF, 0x7FF, 0xFFF}; -static qint16 seg_uend[8] = {0x3F, 0x7F, 0xFF, 0x1FF, - 0x3FF, 0x7FF, 0xFFF, 0x1FFF}; - -static qint16 search(qint16 val, qint16 *table, qint16 size) -{ - qint16 i; - - for (i = 0; i < size; i++) { - if (val <= *table++) - return (i); - } - return (size); -} - -/* - * linear2alaw() - Convert a 16-bit linear PCM value to 8-bit A-law - * - * Accepts a 16-bit integer and encodes it as A-law data. - * - * Linear Input Code Compressed Code - * ------------------------ --------------- - * 0000000wxyza 000wxyz - * 0000001wxyza 001wxyz - * 000001wxyzab 010wxyz - * 00001wxyzabc 011wxyz - * 0001wxyzabcd 100wxyz - * 001wxyzabcde 101wxyz - * 01wxyzabcdef 110wxyz - * 1wxyzabcdefg 111wxyz - * - * For further information see John C. Bellamy's Digital Telephony, 1982, - * John Wiley & Sons, pps 98-111 and 472-476. - */ -quint8 linear2alaw(qint16 pcm_val) -{ - qint16 mask; - qint16 seg; - quint8 aval; - - pcm_val = pcm_val >> 3; - - if (pcm_val >= 0) { - mask = 0xD5; /* sign (7th) bit = 1 */ - } else { - mask = 0x55; /* sign bit = 0 */ - pcm_val = -pcm_val - 1; - } - - /* Convert the scaled magnitude to segment number. */ - seg = search(pcm_val, seg_aend, 8); - - /* Combine the sign, segment, and quantization bits. */ - - if (seg >= 8) /* out of range, return maximum value. */ - return (quint8) (0x7F ^ mask); - else { - aval = (quint8) seg << SEG_SHIFT; - if (seg < 2) - aval |= (pcm_val >> 1) & QUANT_MASK; - else - aval |= (pcm_val >> seg) & QUANT_MASK; - return (aval ^ mask); - } -} - -/* - * alaw2linear() - Convert an A-law value to 16-bit linear PCM - * - */ -qint16 alaw2linear(quint8 a_val) -{ - qint16 t; - qint16 seg; - - a_val ^= 0x55; - - t = (a_val & QUANT_MASK) << 4; - seg = ((qint16)a_val & SEG_MASK) >> SEG_SHIFT; - switch (seg) { - case 0: - t += 8; - break; - case 1: - t += 0x108; - break; - default: - t += 0x108; - t <<= seg - 1; - } - return ((a_val & SIGN_BIT) ? t : -t); -} - -/* - * linear2ulaw() - Convert a linear PCM value to u-law - * - * In order to simplify the encoding process, the original linear magnitude - * is biased by adding 33 which shifts the encoding range from (0 - 8158) to - * (33 - 8191). The result can be seen in the following encoding table: - * - * Biased Linear Input Code Compressed Code - * ------------------------ --------------- - * 00000001wxyza 000wxyz - * 0000001wxyzab 001wxyz - * 000001wxyzabc 010wxyz - * 00001wxyzabcd 011wxyz - * 0001wxyzabcde 100wxyz - * 001wxyzabcdef 101wxyz - * 01wxyzabcdefg 110wxyz - * 1wxyzabcdefgh 111wxyz - * - * Each biased linear code has a leading 1 which identifies the segment - * number. The value of the segment number is equal to 7 minus the number - * of leading 0's. The quantization interval is directly available as the - * four bits wxyz. * The trailing bits (a - h) are ignored. - * - * Ordinarily the complement of the resulting code word is used for - * transmission, and so the code word is complemented before it is returned. - * - * For further information see John C. Bellamy's Digital Telephony, 1982, - * John Wiley & Sons, pps 98-111 and 472-476. - */ -quint8 linear2ulaw(qint16 pcm_val) -{ - qint16 mask; - qint16 seg; - quint8 uval; - - /* Get the sign and the magnitude of the value. */ - pcm_val = pcm_val >> 2; - if (pcm_val < 0) { - pcm_val = -pcm_val; - mask = 0x7F; - } else { - mask = 0xFF; - } - if (pcm_val > CLIP) pcm_val = CLIP; /* clip the magnitude */ - pcm_val += (BIAS >> 2); - - /* Convert the scaled magnitude to segment number. */ - seg = search(pcm_val, seg_uend, 8); - - /* - * Combine the sign, segment, quantization bits; - * and complement the code word. - */ - if (seg >= 8) /* out of range, return maximum value. */ - return (quint8) (0x7F ^ mask); - else { - uval = (quint8) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF); - return (uval ^ mask); - } -} - -/* - * ulaw2linear() - Convert a u-law value to 16-bit linear PCM - * - * First, a biased linear code is derived from the code word. An unbiased - * output can then be obtained by subtracting 33 from the biased code. - * - * Note that this function expects to be passed the complement of the - * original code word. This is in keeping with ISDN conventions. - */ -qint16 ulaw2linear(quint8 u_val) -{ - qint16 t; - - /* Complement to obtain normal u-law value. */ - u_val = ~u_val; - - /* - * Extract and bias the quantization bits. Then - * shift up by the segment number and subtract out the bias. - */ - t = ((u_val & QUANT_MASK) << 3) + BIAS; - t <<= ((unsigned)u_val & SEG_MASK) >> SEG_SHIFT; - - return ((u_val & SIGN_BIT) ? (BIAS - t) : (t - BIAS)); -} - -QXmppG711aCodec::QXmppG711aCodec(int clockrate) -{ - m_frequency = clockrate; -} - -qint64 QXmppG711aCodec::encode(QDataStream &input, QDataStream &output) -{ - qint64 samples = 0; - qint16 pcm; - while (!input.atEnd()) - { - input >> pcm; - output << linear2alaw(pcm); - ++samples; - } - return samples; -} - -qint64 QXmppG711aCodec::decode(QDataStream &input, QDataStream &output) -{ - qint64 samples = 0; - quint8 g711; - while (!input.atEnd()) - { - input >> g711; - output << alaw2linear(g711); - ++samples; - } - return samples; -} - -QXmppG711uCodec::QXmppG711uCodec(int clockrate) -{ - m_frequency = clockrate; -} - -qint64 QXmppG711uCodec::encode(QDataStream &input, QDataStream &output) -{ - qint64 samples = 0; - qint16 pcm; - while (!input.atEnd()) - { - input >> pcm; - output << linear2ulaw(pcm); - ++samples; - } - return samples; -} - -qint64 QXmppG711uCodec::decode(QDataStream &input, QDataStream &output) -{ - qint64 samples = 0; - quint8 g711; - while (!input.atEnd()) - { - input >> g711; - output << ulaw2linear(g711); - ++samples; - } - return samples; -} - -#ifdef QXMPP_USE_SPEEX -QXmppSpeexCodec::QXmppSpeexCodec(int clockrate) -{ - const SpeexMode *mode = &speex_nb_mode; - if (clockrate == 32000) - mode = &speex_uwb_mode; - else if (clockrate == 16000) - mode = &speex_wb_mode; - else if (clockrate == 8000) - mode = &speex_nb_mode; - else - qWarning() << "QXmppSpeexCodec got invalid clockrate" << clockrate; - - // encoder - encoder_bits = new SpeexBits; - speex_bits_init(encoder_bits); - encoder_state = speex_encoder_init(mode); - - // decoder - decoder_bits = new SpeexBits; - speex_bits_init(decoder_bits); - decoder_state = speex_decoder_init(mode); - - // get frame size in samples - speex_encoder_ctl(encoder_state, SPEEX_GET_FRAME_SIZE, &frame_samples); -} - -QXmppSpeexCodec::~QXmppSpeexCodec() -{ - delete encoder_bits; - delete decoder_bits; -} - -qint64 QXmppSpeexCodec::encode(QDataStream &input, QDataStream &output) -{ - QByteArray pcm_buffer(frame_samples * 2, 0); - const int length = input.readRawData(pcm_buffer.data(), pcm_buffer.size()); - if (length != pcm_buffer.size()) - { - qWarning() << "Read only read" << length << "bytes"; - return 0; - } - speex_bits_reset(encoder_bits); - speex_encode_int(encoder_state, (short*)pcm_buffer.data(), encoder_bits); - QByteArray speex_buffer(speex_bits_nbytes(encoder_bits), 0); - speex_bits_write(encoder_bits, speex_buffer.data(), speex_buffer.size()); - output.writeRawData(speex_buffer.data(), speex_buffer.size()); - return frame_samples; -} - -qint64 QXmppSpeexCodec::decode(QDataStream &input, QDataStream &output) -{ - const int length = input.device()->bytesAvailable(); - QByteArray speex_buffer(length, 0); - input.readRawData(speex_buffer.data(), speex_buffer.size()); - speex_bits_read_from(decoder_bits, speex_buffer.data(), speex_buffer.size()); - QByteArray pcm_buffer(frame_samples * 2, 0); - speex_decode_int(decoder_state, decoder_bits, (short*)pcm_buffer.data()); - output.writeRawData(pcm_buffer.data(), pcm_buffer.size()); - return frame_samples; -} - -#endif - diff --git a/source/QXmppCodec.h b/source/QXmppCodec.h deleted file mode 100644 index 5c328b5f..00000000 --- a/source/QXmppCodec.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPCODEC_H -#define QXMPPCODEC_H - -#include <QtGlobal> - -/// \brief The QXmppCodec class is the base class for audio codecs capable of -/// encoding and decoding audio samples. -/// -/// Samples must be 16-bit little endian. - -class QXmppCodec -{ -public: - /// Reads samples from the input stream, encodes them and writes the - /// encoded data to the output stream. - virtual qint64 encode(QDataStream &input, QDataStream &output) = 0; - - /// Reads encoded data from the input stream, decodes it and writes the - /// decoded samples to the output stream. - virtual qint64 decode(QDataStream &input, QDataStream &output) = 0; -}; - -/// \internal -/// -/// The QXmppG711aCodec class represent a G.711 a-law PCM codec. - -class QXmppG711aCodec : public QXmppCodec -{ -public: - QXmppG711aCodec(int clockrate); - - qint64 encode(QDataStream &input, QDataStream &output); - qint64 decode(QDataStream &input, QDataStream &output); - -private: - int m_frequency; -}; - -/// \internal -/// -/// The QXmppG711uCodec class represent a G.711 u-law PCM codec. - -class QXmppG711uCodec : public QXmppCodec -{ -public: - QXmppG711uCodec(int clockrate); - - qint64 encode(QDataStream &input, QDataStream &output); - qint64 decode(QDataStream &input, QDataStream &output); - -private: - int m_frequency; -}; - -#ifdef QXMPP_USE_SPEEX -typedef struct SpeexBits SpeexBits; - -/// \internal -/// -/// The QXmppSpeexCodec class represent a SPEEX codec. - -class QXmppSpeexCodec : public QXmppCodec -{ -public: - QXmppSpeexCodec(int clockrate); - ~QXmppSpeexCodec(); - - qint64 encode(QDataStream &input, QDataStream &output); - qint64 decode(QDataStream &input, QDataStream &output); - -private: - SpeexBits *encoder_bits; - void *encoder_state; - SpeexBits *decoder_bits; - void *decoder_state; - int frame_samples; -}; -#endif - -#endif diff --git a/source/QXmppConfiguration.cpp b/source/QXmppConfiguration.cpp deleted file mode 100644 index 79a3acc3..00000000 --- a/source/QXmppConfiguration.cpp +++ /dev/null @@ -1,484 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppConfiguration.h" - -/// Creates a QXmppConfiguration object. - -QXmppConfiguration::QXmppConfiguration() : m_port(5222), - m_resource("QXmpp"), - m_autoAcceptSubscriptions(false), - m_sendIntialPresence(true), - m_sendRosterRequest(true), - m_keepAliveInterval(0), - m_keepAliveTimeout(0), - m_autoReconnectionEnabled(true), - m_useSASLAuthentication(true), - m_ignoreSslErrors(true), - m_streamSecurityMode(QXmppConfiguration::TLSEnabled), - m_nonSASLAuthMechanism(QXmppConfiguration::NonSASLDigest), - m_SASLAuthMechanism(QXmppConfiguration::SASLDigestMD5) -{ - -} - -/// Destructor, destroys the QXmppConfiguration object. -/// - -QXmppConfiguration::~QXmppConfiguration() -{ - -} - -/// Sets the host name. -/// -/// \param host host name of the XMPP server where connection has to be made -/// (e.g. "jabber.org" and "talk.google.com"). It can also be an IP address in -/// the form of a string (e.g. "192.168.1.25"). -/// - -void QXmppConfiguration::setHost(const QString& host) -{ - m_host = host; -} - -/// Sets the domain name. -/// -/// \param domain Domain name e.g. "gmail.com" and "jabber.org". -/// \note host name and domain name can be different for google -/// domain name is gmail.com and host name is talk.google.com -/// - -void QXmppConfiguration::setDomain(const QString& domain) -{ - m_domain = domain; -} - -/// Sets the port number. -/// -/// \param port Port number at which the XMPP server is listening. The default -/// value is 5222. -/// - -void QXmppConfiguration::setPort(int port) -{ - m_port = port; -} - -/// Sets the username. -/// -/// \param user Username of the account at the specified XMPP server. It should -/// be the name without the domain name. E.g. "qxmpp.test1" and not -/// "qxmpp.test1@gmail.com" -/// - -void QXmppConfiguration::setUser(const QString& user) -{ - m_user = user; -} - -/// Sets the password. -/// -/// \param passwd Password for the specified username -/// - -void QXmppConfiguration::setPasswd(const QString& passwd) -{ - m_passwd = passwd; -} - -/// Sets the resource identifier. -/// -/// Multiple resources (e.g., devices or locations) may connect simultaneously -/// to a server on behalf of each authorized client, with each resource -/// differentiated by the resource identifier of an XMPP address -/// (e.g. node@domain/home vs. node@domain/work) -/// -/// The default value is "QXmpp". -/// -/// \param resource Resource identifier of the client in connection. - -void QXmppConfiguration::setResource(const QString& resource) -{ - m_resource = resource; -} - -/// Returns the host name. -/// -/// \return host name -/// - -QString QXmppConfiguration::host() const -{ - return m_host; -} - -/// Returns the domain name. -/// -/// \return domain name -/// - -QString QXmppConfiguration::domain() const -{ - return m_domain; -} - -/// Returns the port number. -/// -/// \return port number -/// - -int QXmppConfiguration::port() const -{ - return m_port; -} - -/// Returns the username. -/// -/// \return username -/// - -QString QXmppConfiguration::user() const -{ - return m_user; -} - -/// Returns the password. -/// -/// \return password -/// - -QString QXmppConfiguration::passwd() const -{ - return m_passwd; -} - -/// Returns the resource identifier. -/// -/// \return resource identifier -/// - -QString QXmppConfiguration::resource() const -{ - return m_resource; -} - -/// Returns the jabber id (jid). -/// -/// \return jabber id (jid) -/// (e.g. "qxmpp.test1@gmail.com/resource" or qxmpptest@jabber.org/QXmpp156) -/// - -QString QXmppConfiguration::jid() const -{ - return jidBare() + "/" + m_resource; -} - -/// Returns the bare jabber id (jid), without the resource identifier. -/// -/// \return bare jabber id (jid) -/// (e.g. "qxmpp.test1@gmail.com" or qxmpptest@jabber.org) -/// - -QString QXmppConfiguration::jidBare() const -{ - return m_user+"@"+m_domain; -} - -/// Returns the auto-accept-subscriptions-request configuration. -/// -/// \return boolean value -/// true means that auto-accept-subscriptions-request is enabled else disabled for false -/// - -bool QXmppConfiguration::autoAcceptSubscriptions() const -{ - return m_autoAcceptSubscriptions; -} - -/// Sets the auto-accept-subscriptions-request configuration. -/// -/// \param value boolean value -/// true means that auto-accept-subscriptions-request is enabled else disabled for false -/// - -void QXmppConfiguration::setAutoAcceptSubscriptions(bool value) -{ - m_autoAcceptSubscriptions = value; -} - -/// Returns the auto-reconnect-on-disconnection-on-error configuration. -/// -/// \return boolean value -/// true means that auto-reconnect is enabled else disabled for false -/// - -bool QXmppConfiguration::autoReconnectionEnabled() const -{ - return m_autoReconnectionEnabled; -} - -/// Sets the auto-reconnect-on-disconnection-on-error configuration. -/// -/// \param value boolean value -/// true means that auto-reconnect is enabled else disabled for false -/// - -void QXmppConfiguration::setAutoReconnectionEnabled(bool value) -{ - m_autoReconnectionEnabled = value; -} - -/// Returns whether SSL errors (such as certificate validation errors) -/// are to be ignored when connecting to the XMPP server. - -bool QXmppConfiguration::ignoreSslErrors() const -{ - return m_ignoreSslErrors; -} - -/// Specifies whether SSL errors (such as certificate validation errors) -/// are to be ignored when connecting to an XMPP server. - -void QXmppConfiguration::setIgnoreSslErrors(bool value) -{ - m_ignoreSslErrors = value; -} - -/// Returns the type of authentication system specified by the user. -/// \return true if SASL was specified else false. If the specified -/// system is not available QXmpp will resort to the other one. - -bool QXmppConfiguration::useSASLAuthentication() const -{ - return m_useSASLAuthentication; -} - -/// Returns the type of authentication system specified by the user. -/// \param useSASL to hint to use SASL authentication system if available. -/// false will specify to use NonSASL XEP-0078: Non-SASL Authentication -/// If the specified one is not availbe, library will use the othe one - -void QXmppConfiguration::setUseSASLAuthentication(bool useSASL) -{ - m_useSASLAuthentication = useSASL; -} - -/// Returns the specified security mode for the stream. The default value is -/// QXmppConfiguration::TLSEnabled. -/// \return StreamSecurityMode - -QXmppConfiguration::StreamSecurityMode QXmppConfiguration::streamSecurityMode() const -{ - return m_streamSecurityMode; -} - -/// Specifies the specified security mode for the stream. The default value is -/// QXmppConfiguration::TLSEnabled. -/// \param mode StreamSecurityMode - -void QXmppConfiguration::setStreamSecurityMode( - QXmppConfiguration::StreamSecurityMode mode) -{ - m_streamSecurityMode = mode; -} - -/// Returns the Non-SASL authentication mechanism configuration. -/// -/// \return QXmppConfiguration::NonSASLAuthMechanism -/// - -QXmppConfiguration::NonSASLAuthMechanism QXmppConfiguration::nonSASLAuthMechanism() const -{ - return m_nonSASLAuthMechanism; -} - -/// Hints the library the Non-SASL authentication mechanism to be used for authentication. -/// -/// \param mech QXmppConfiguration::NonSASLAuthMechanism -/// - -void QXmppConfiguration::setNonSASLAuthMechanism( - QXmppConfiguration::NonSASLAuthMechanism mech) -{ - m_nonSASLAuthMechanism = mech; -} - -/// Returns the SASL authentication mechanism configuration. -/// -/// \return QXmppConfiguration::SASLAuthMechanism -/// - -QXmppConfiguration::SASLAuthMechanism QXmppConfiguration::sASLAuthMechanism() const -{ - return m_SASLAuthMechanism; -} - -/// Hints the library the SASL authentication mechanism to be used for authentication. -/// -/// \param mech QXmppConfiguration::SASLAuthMechanism -/// - -void QXmppConfiguration::setSASLAuthMechanism( - QXmppConfiguration::SASLAuthMechanism mech) -{ - m_SASLAuthMechanism = mech; -} - -/// Specifies the network proxy used for the connection made by QXmppClient. -/// The default value is QNetworkProxy::DefaultProxy that is the proxy is -/// determined based on the application proxy set using -/// QNetworkProxy::setApplicationProxy(). -/// \param proxy QNetworkProxy - -void QXmppConfiguration::setNetworkProxy(const QNetworkProxy& proxy) -{ - m_networkProxy = proxy; -} - -/// Returns the specified network proxy. -/// The default value is QNetworkProxy::DefaultProxy that is the proxy is -/// determined based on the application proxy set using -/// QNetworkProxy::setApplicationProxy(). -/// \return QNetworkProxy - -QNetworkProxy QXmppConfiguration::networkProxy() const -{ - return m_networkProxy; -} - -/// Specifies the interval in seconds at which keep alive (ping) packets -/// will be sent to the server. -/// If set to zero, no keep alive packets will be sent. - -void QXmppConfiguration::setKeepAliveInterval(int secs) -{ - m_keepAliveInterval = secs; -} - -/// Returns the keep alive interval in seconds. - -int QXmppConfiguration::keepAliveInterval() const -{ - return m_keepAliveInterval; -} - -/// Specifies the maximum time in seconds to wait for a keep alive response -/// from the server before considering we are disconnected. -/// -/// If set to zero or a value larger than the keep alive interval, -/// no timeout will occur. - -void QXmppConfiguration::setKeepAliveTimeout(int secs) -{ - m_keepAliveTimeout = secs; -} - -/// Returns the keep alive timeout in seconds. - -int QXmppConfiguration::keepAliveTimeout() const -{ - return m_keepAliveTimeout; -} - -QString QXmppConfiguration::getHost() const -{ - return m_host; -} - -QString QXmppConfiguration::getDomain() const -{ - return m_domain; -} - -int QXmppConfiguration::getPort() const -{ - return m_port; -} - -QString QXmppConfiguration::getUser() const -{ - return m_user; -} - -QString QXmppConfiguration::getPasswd() const -{ - return m_passwd; -} - -QString QXmppConfiguration::getResource() const -{ - return m_resource; -} - -QString QXmppConfiguration::getJid() const -{ - return jidBare() + "/" + m_resource; -} - -QString QXmppConfiguration::getJidBare() const -{ - return m_user+"@"+m_domain; -} - -bool QXmppConfiguration::getAutoAcceptSubscriptions() const -{ - return m_autoAcceptSubscriptions; -} - -bool QXmppConfiguration::getAutoReconnectionEnabled() const -{ - return m_autoReconnectionEnabled; -} - -bool QXmppConfiguration::getUseSASLAuthentication() const -{ - return m_useSASLAuthentication; -} - -bool QXmppConfiguration::getIgnoreSslErrors() const -{ - return m_ignoreSslErrors; -} - -QXmppConfiguration::StreamSecurityMode QXmppConfiguration::getStreamSecurityMode() const -{ - return m_streamSecurityMode; -} - -QXmppConfiguration::NonSASLAuthMechanism QXmppConfiguration::getNonSASLAuthMechanism() const -{ - return m_nonSASLAuthMechanism; -} - -QXmppConfiguration::SASLAuthMechanism QXmppConfiguration::getSASLAuthMechanism() const -{ - return m_SASLAuthMechanism; -} - -QNetworkProxy QXmppConfiguration::getNetworkProxy() const -{ - return m_networkProxy; -} - diff --git a/source/QXmppConfiguration.h b/source/QXmppConfiguration.h deleted file mode 100644 index 52f7d810..00000000 --- a/source/QXmppConfiguration.h +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPCONFIGURATION_H -#define QXMPPCONFIGURATION_H - -#include <QString> -#include <QNetworkProxy> - -/// \brief The QXmppConfiguration class holds configuration options. -/// -/// It can be passed to QXmppClient to specify the options when connecting to -/// an XMPP server. -/// -/// It is a container of all the settings, configuration required for -/// connecting to an XMPP server. E.g. server name, username, port, type -/// of authentication mechanism, type of security used by stream (encryption), -/// etc.. -/// - -class QXmppConfiguration -{ -public: - /// An enumeration for type of the Security Mode that is stream is encrypted or not. - /// The server may or may not have TLS feature. Server may force the encryption. - /// Depending upon all this user can specify following options. - enum StreamSecurityMode - { - TLSEnabled = 0, ///< Encryption is used if available (default) - TLSDisabled, ///< No encryption is server allows - TLSRequired ///< Encryption is a must otherwise connection would not - ///< be established - }; - - /// An enumeration for various Non-SASL authentication mechanisms available. - /// The server may or may not allow QXmppConfiguration::Plain mechanism. So - /// specifying the mechanism is just a hint to the library. - enum NonSASLAuthMechanism - { - NonSASLPlain = 0,///< Plain - NonSASLDigest ///< Digest (default) - }; - - /// An enumeration for various SASL authentication mechanisms available. - /// The server may or may not allow any particular mechanism. So depending - /// upon the availability of mechanisms on the server the library will choose - /// a mechanism. - enum SASLAuthMechanism - { - SASLPlain = 0, ///< Plain - SASLDigestMD5, ///< Digest MD5 (default) - SASLAnonymous ///< Anonymous - }; - - QXmppConfiguration(); - ~QXmppConfiguration(); - - QString host() const; - QString domain() const; - int port() const; - QString user() const; - QString passwd() const; - QString resource() const; - QString jid() const; - QString jidBare() const; - - bool autoAcceptSubscriptions() const; - bool autoReconnectionEnabled() const; - bool useSASLAuthentication() const; - bool ignoreSslErrors() const; - QXmppConfiguration::StreamSecurityMode streamSecurityMode() const; - QXmppConfiguration::NonSASLAuthMechanism nonSASLAuthMechanism() const; - QXmppConfiguration::SASLAuthMechanism sASLAuthMechanism() const; - QNetworkProxy networkProxy() const; - - int keepAliveInterval() const; - void setKeepAliveInterval(int secs); - int keepAliveTimeout() const; - void setKeepAliveTimeout(int secs); - - void setHost(const QString&); - void setDomain(const QString&); - void setPort(int); - void setUser(const QString&); - void setPasswd(const QString&); - void setResource(const QString&); - - void setAutoAcceptSubscriptions(bool); - void setAutoReconnectionEnabled(bool); - void setUseSASLAuthentication(bool); - void setIgnoreSslErrors(bool); - - void setStreamSecurityMode(QXmppConfiguration::StreamSecurityMode mode); - void setNonSASLAuthMechanism(QXmppConfiguration::NonSASLAuthMechanism); - void setSASLAuthMechanism(QXmppConfiguration::SASLAuthMechanism); - - void setNetworkProxy(const QNetworkProxy& proxy); - - // deprecated accessors, use the form without "get" instead - /// \cond - QString Q_DECL_DEPRECATED getHost() const; - QString Q_DECL_DEPRECATED getDomain() const; - int Q_DECL_DEPRECATED getPort() const; - QString Q_DECL_DEPRECATED getUser() const; - QString Q_DECL_DEPRECATED getPasswd() const; - QString Q_DECL_DEPRECATED getResource() const; - QString Q_DECL_DEPRECATED getJid() const; - QString Q_DECL_DEPRECATED getJidBare() const; - - bool Q_DECL_DEPRECATED getAutoAcceptSubscriptions() const; - bool Q_DECL_DEPRECATED getAutoReconnectionEnabled() const; - bool Q_DECL_DEPRECATED getUseSASLAuthentication() const; - bool Q_DECL_DEPRECATED getIgnoreSslErrors() const; - QXmppConfiguration::StreamSecurityMode Q_DECL_DEPRECATED getStreamSecurityMode() const; - QXmppConfiguration::NonSASLAuthMechanism Q_DECL_DEPRECATED getNonSASLAuthMechanism() const; - QXmppConfiguration::SASLAuthMechanism Q_DECL_DEPRECATED getSASLAuthMechanism() const; - QNetworkProxy Q_DECL_DEPRECATED getNetworkProxy() const; - /// \endcond - -private: - QString m_host; - int m_port; - QString m_user; - QString m_passwd; - QString m_domain; - QString m_resource; - - // default is false - bool m_autoAcceptSubscriptions; - // default is true - bool m_sendIntialPresence; - // default is true - bool m_sendRosterRequest; - // interval in seconds, if zero won't ping - int m_keepAliveInterval; - // interval in seconds, if zero won't timeout - int m_keepAliveTimeout; - // will keep reconnecting if disconnected, default is true - bool m_autoReconnectionEnabled; - bool m_useSASLAuthentication; ///< flag to specify what authentication system - ///< to be used - ///< defualt is true and use SASL - ///< false would use NonSASL if available - // default is true - bool m_ignoreSslErrors; - - StreamSecurityMode m_streamSecurityMode; - NonSASLAuthMechanism m_nonSASLAuthMechanism; - SASLAuthMechanism m_SASLAuthMechanism; - - QNetworkProxy m_networkProxy; -}; - -#endif // QXMPPCONFIGURATION_H diff --git a/source/QXmppConstants.cpp b/source/QXmppConstants.cpp deleted file mode 100644 index 28d5e7d1..00000000 --- a/source/QXmppConstants.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppConstants.h" - -const char* ns_stream = "http://etherx.jabber.org/streams"; -const char* ns_client = "jabber:client"; -const char* ns_roster = "jabber:iq:roster"; -const char* ns_tls = "urn:ietf:params:xml:ns:xmpp-tls"; -const char* ns_sasl = "urn:ietf:params:xml:ns:xmpp-sasl"; -const char* ns_bind = "urn:ietf:params:xml:ns:xmpp-bind"; -const char* ns_session = "urn:ietf:params:xml:ns:xmpp-session"; -const char* ns_stanza = "urn:ietf:params:xml:ns:xmpp-stanzas"; -const char* ns_vcard = "vcard-temp"; -const char* ns_auth = "jabber:iq:auth"; -const char* ns_authFeature = "http://jabber.org/features/iq-auth"; -const char* ns_capabilities = "http://jabber.org/protocol/caps"; -const char* ns_disco_info = "http://jabber.org/protocol/disco#info"; -const char* ns_disco_items = "http://jabber.org/protocol/disco#items"; -const char* ns_ibb = "http://jabber.org/protocol/ibb"; -const char* ns_rpc = "jabber:iq:rpc"; -const char *ns_ping = "urn:xmpp:ping"; -const char *ns_conference = "jabber:x:conference"; -const char *ns_delayed_delivery = "urn:xmpp:delay"; -const char *ns_legacy_delayed_delivery = "jabber:x:delay"; -const char *ns_muc = "http://jabber.org/protocol/muc"; -const char *ns_muc_admin = "http://jabber.org/protocol/muc#admin"; -const char *ns_muc_owner = "http://jabber.org/protocol/muc#owner"; -const char *ns_muc_user = "http://jabber.org/protocol/muc#user"; -const char *ns_chat_states = "http://jabber.org/protocol/chatstates"; -const char *ns_stream_initiation = "http://jabber.org/protocol/si"; -const char *ns_stream_initiation_file_transfer = "http://jabber.org/protocol/si/profile/file-transfer"; -const char *ns_feature_negotiation = "http://jabber.org/protocol/feature-neg"; -const char *ns_bytestreams = "http://jabber.org/protocol/bytestreams"; -// XEP-0092: Software Version -const char *ns_version = "jabber:iq:version"; -const char *ns_data = "jabber:x:data"; -// XEP-0166: Jingle -const char *ns_jingle = "urn:xmpp:jingle:1"; -const char *ns_jingle_raw_udp = "urn:xmpp:jingle:transports:raw-udp:1"; -const char* ns_jingle_ice_udp = "urn:xmpp:jingle:transports:ice-udp:1"; -const char *ns_jingle_rtp = "urn:xmpp:jingle:apps:rtp:1"; -const char *ns_jingle_rtp_audio = "urn:xmpp:jingle:apps:rtp:audio"; -const char *ns_jingle_rtp_video = "urn:xmpp:jingle:apps:rtp:video"; - -const char *svn_revision = "$Rev$"; diff --git a/source/QXmppConstants.h b/source/QXmppConstants.h deleted file mode 100644 index 02d5b9ef..00000000 --- a/source/QXmppConstants.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPCONSTANTS_H -#define QXMPPCONSTANTS_H - -extern const char* ns_stream; -extern const char* ns_client; -extern const char* ns_roster; -extern const char* ns_tls; -extern const char* ns_sasl; -extern const char* ns_bind; -extern const char* ns_session; -extern const char* ns_stanza; -extern const char* ns_vcard; -extern const char* ns_auth; -extern const char* ns_authFeature; -extern const char* ns_capabilities; -extern const char* ns_disco_info; -extern const char* ns_disco_items; -extern const char* ns_ibb; -extern const char* ns_rpc; -extern const char* ns_ping; -extern const char *ns_conference; -extern const char *ns_delayed_delivery; -extern const char *ns_legacy_delayed_delivery; -extern const char *ns_muc; -extern const char *ns_muc_admin; -extern const char *ns_muc_owner; -extern const char *ns_muc_user; -extern const char *ns_chat_states; -extern const char *ns_stream_initiation; -extern const char *ns_stream_initiation_file_transfer; -extern const char *ns_feature_negotiation; -extern const char *ns_bytestreams; -extern const char *ns_version; -extern const char *ns_data; -extern const char *ns_jingle; -extern const char* ns_jingle_ice_udp; -extern const char* ns_jingle_raw_udp; -extern const char *ns_jingle_rtp; -extern const char *ns_jingle_rtp_audio; -extern const char *ns_jingle_rtp_video; -extern const char *svn_revision; - -#endif // QXMPPCONSTANTS_H diff --git a/source/QXmppDataForm.cpp b/source/QXmppDataForm.cpp deleted file mode 100644 index 1200fa26..00000000 --- a/source/QXmppDataForm.cpp +++ /dev/null @@ -1,371 +0,0 @@ -/* - * 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 <QDebug> -#include <QDomElement> -#include <QStringList> - -#include "QXmppConstants.h" -#include "QXmppDataForm.h" -#include "QXmppUtils.h" - -struct field_type { - QXmppDataForm::Field::Type type; - const char *str; -}; - -static field_type field_types[] = { - {QXmppDataForm::Field::BooleanField, "boolean"}, - {QXmppDataForm::Field::FixedField, "fixed"}, - {QXmppDataForm::Field::HiddenField, "hidden"}, - {QXmppDataForm::Field::JidMultiField, "jid-multi"}, - {QXmppDataForm::Field::JidSingleField, "jid-single"}, - {QXmppDataForm::Field::ListMultiField, "list-multi"}, - {QXmppDataForm::Field::ListSingleField, "list-single"}, - {QXmppDataForm::Field::TextMultiField, "text-multi"}, - {QXmppDataForm::Field::TextPrivateField, "text-private"}, - {QXmppDataForm::Field::TextSingleField, "text-single"}, - {static_cast<QXmppDataForm::Field::Type>(-1), NULL}, -}; - -QXmppDataForm::Field::Field(QXmppDataForm::Field::Type type) - : m_type(type) -{ -} - -QString QXmppDataForm::Field::description() const -{ - return m_description; -} - -void QXmppDataForm::Field::setDescription(const QString &description) -{ - m_description = description; -} - -QString QXmppDataForm::Field::key() const -{ - return m_key; -} - -void QXmppDataForm::Field::setKey(const QString &key) -{ - m_key = key; -} - -QString QXmppDataForm::Field::label() const -{ - return m_label; -} - -void QXmppDataForm::Field::setLabel(const QString &label) -{ - m_label = label; -} - -QList<QPair<QString, QString> > QXmppDataForm::Field::options() const -{ - return m_options; -} - -void QXmppDataForm::Field::setOptions(const QList<QPair<QString, QString> > &options) -{ - m_options = options; -} - -bool QXmppDataForm::Field::isRequired() const -{ - return m_required; -} - -void QXmppDataForm::Field::setRequired(bool required) -{ - m_required = required; -} - -QXmppDataForm::Field::Type QXmppDataForm::Field::type() const -{ - return m_type; -} - -void QXmppDataForm::Field::setType(QXmppDataForm::Field::Type type) -{ - m_type = type; -} - -QVariant QXmppDataForm::Field::value() const -{ - return m_value; -} - -void QXmppDataForm::Field::setValue(const QVariant &value) -{ - m_value = value; -} - -QXmppDataForm::QXmppDataForm(QXmppDataForm::Type type) - : m_type(type) -{ -} - -QList<QXmppDataForm::Field> QXmppDataForm::fields() const -{ - return m_fields; -} - -QList<QXmppDataForm::Field> &QXmppDataForm::fields() -{ - return m_fields; -} - -void QXmppDataForm::setFields(const QList<QXmppDataForm::Field> &fields) -{ - m_fields = fields; -} - -QString QXmppDataForm::instructions() const -{ - return m_instructions; -} - -void QXmppDataForm::setInstructions(const QString &instructions) -{ - m_instructions = instructions; -} - -QString QXmppDataForm::title() const -{ - return m_title; -} - -void QXmppDataForm::setTitle(const QString &title) -{ - m_title = title; -} - -QXmppDataForm::Type QXmppDataForm::type() const -{ - return m_type; -} - -void QXmppDataForm::setType(QXmppDataForm::Type type) -{ - m_type = type; -} - -bool QXmppDataForm::isNull() const -{ - return m_type == QXmppDataForm::None; -} - -void QXmppDataForm::parse(const QDomElement &element) -{ - if (element.isNull()) - return; - - /* form type */ - const QString typeStr = element.attribute("type"); - if (typeStr == "form") - m_type = QXmppDataForm::Form; - else if (typeStr == "submit") - m_type = QXmppDataForm::Submit; - else if (typeStr == "cancel") - m_type = QXmppDataForm::Cancel; - else if (typeStr == "result") - m_type = QXmppDataForm::Result; - else - { - qWarning() << "Unknown form type" << typeStr; - return; - } - - /* form properties */ - m_title = element.firstChildElement("title").text(); - m_instructions = element.firstChildElement("instructions").text(); - - QDomElement fieldElement = element.firstChildElement("field"); - while (!fieldElement.isNull()) - { - QXmppDataForm::Field field; - - /* field type */ - QXmppDataForm::Field::Type type = static_cast<QXmppDataForm::Field::Type>(-1); - const QString typeStr = fieldElement.attribute("type"); - struct field_type *ptr; - for (ptr = field_types; ptr->str; ptr++) - { - if (typeStr == ptr->str) - { - type = ptr->type; - break; - } - } - if (type < 0) - qWarning() << "Unknown field type" << typeStr; - field.setType(type); - - /* field attributes */ - field.setLabel(fieldElement.attribute("label")); - field.setKey(fieldElement.attribute("var")); - - /* field value(s) */ - if (type == QXmppDataForm::Field::BooleanField) - { - const QString valueStr = fieldElement.firstChildElement("value").text(); - field.setValue(valueStr == "1" || valueStr == "true"); - } - else if (type == QXmppDataForm::Field::ListMultiField || - type == QXmppDataForm::Field::JidMultiField || - type == QXmppDataForm::Field::TextMultiField) - { - QStringList values; - QDomElement valueElement = fieldElement.firstChildElement("value"); - while (!valueElement.isNull()) - { - values.append(valueElement.text()); - valueElement = valueElement.nextSiblingElement("value"); - } - field.setValue(values); - } - else - { - field.setValue(fieldElement.firstChildElement("value").text()); - } - - /* field options */ - if (type == QXmppDataForm::Field::ListMultiField || - type == QXmppDataForm::Field::ListSingleField) - { - QList<QPair<QString, QString> > options; - QDomElement optionElement = fieldElement.firstChildElement("option"); - while (!optionElement.isNull()) - { - options.append(QPair<QString, QString>(optionElement.attribute("label"), - optionElement.firstChildElement("value").text())); - optionElement = optionElement.nextSiblingElement("option"); - } - field.setOptions(options); - } - - /* other properties */ - field.setDescription(fieldElement.firstChildElement("description").text()); - field.setRequired(!fieldElement.firstChildElement("required").isNull()); - - m_fields.append(field); - - fieldElement = fieldElement.nextSiblingElement("field"); - } -} - -void QXmppDataForm::toXml(QXmlStreamWriter *writer) const -{ - if (isNull()) - return; - - writer->writeStartElement("x"); - helperToXmlAddAttribute(writer, "xmlns", ns_data); - - /* form type */ - QString typeStr; - if (m_type == QXmppDataForm::Form) - typeStr = "form"; - else if (m_type == QXmppDataForm::Submit) - typeStr = "submit"; - else if (m_type == QXmppDataForm::Cancel) - typeStr = "cancel"; - else if (m_type == QXmppDataForm::Result) - typeStr = "result"; - helperToXmlAddAttribute(writer, "type", typeStr); - - /* form properties */ - if (!m_title.isEmpty()) - helperToXmlAddTextElement(writer, "title", m_title); - if (!m_instructions.isEmpty()) - helperToXmlAddTextElement(writer, "instructions", m_instructions); - - - foreach (const QXmppDataForm::Field &field, m_fields) - { - writer->writeStartElement("field"); - - /* field type */ - const QXmppDataForm::Field::Type type = field.type(); - QString typeStr; - struct field_type *ptr; - for (ptr = field_types; ptr->str; ptr++) - { - if (type == ptr->type) - { - typeStr = ptr->str; - break; - } - } - helperToXmlAddAttribute(writer, "type", typeStr); - - /* field attributes */ - helperToXmlAddAttribute(writer, "label", field.label()); - helperToXmlAddAttribute(writer, "var", field.key()); - - /* field value(s) */ - if (type == QXmppDataForm::Field::BooleanField) - { - helperToXmlAddTextElement(writer, "value", field.value().toBool() ? "1" : "0"); - } - else if (type == QXmppDataForm::Field::ListMultiField || - type == QXmppDataForm::Field::JidMultiField || - type == QXmppDataForm::Field::TextMultiField) - { - foreach (const QString &value, field.value().toStringList()) - helperToXmlAddTextElement(writer, "value", value); - } - else - { - helperToXmlAddTextElement(writer, "value", field.value().toString()); - } - - /* field options */ - if (type == QXmppDataForm::Field::ListMultiField || - type == QXmppDataForm::Field::ListSingleField) - { - QPair<QString, QString> option; - foreach (option, field.options()) - { - writer->writeStartElement("option"); - helperToXmlAddAttribute(writer, "label", option.first); - helperToXmlAddTextElement(writer, "value", option.second); - writer->writeEndElement(); - } - } - - /* other properties */ - if (!field.description().isEmpty()) - helperToXmlAddTextElement(writer, "description", field.description()); - if (field.isRequired()) - helperToXmlAddTextElement(writer, "required", ""); - - writer->writeEndElement(); - } - - writer->writeEndElement(); -} - diff --git a/source/QXmppDataForm.h b/source/QXmppDataForm.h deleted file mode 100644 index 813c35eb..00000000 --- a/source/QXmppDataForm.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPDATAFORM_H -#define QXMPPDATAFORM_H - -#include <QPair> -#include <QString> -#include <QVariant> -#include <QXmlStreamWriter> - -class QDomElement; - -/// \brief The QXmppDataForm class represents a data form as defined by -/// XEP-0004: Data Forms. -/// - -class QXmppDataForm -{ -public: - class Field - { - public: - enum Type - { - BooleanField, - FixedField, - HiddenField, - JidMultiField, - JidSingleField, - ListMultiField, - ListSingleField, - TextMultiField, - TextPrivateField, - TextSingleField, - }; - - Field(QXmppDataForm::Field::Type type = QXmppDataForm::Field::TextSingleField); - - QString description() const; - void setDescription(const QString &description); - - QString key() const; - void setKey(const QString &key); - - QString label() const; - void setLabel(const QString &label); - - QList<QPair<QString, QString> > options() const; - void setOptions(const QList<QPair<QString, QString> > &options); - - bool isRequired() const; - void setRequired(bool required); - - QXmppDataForm::Field::Type type() const; - void setType(QXmppDataForm::Field::Type type); - - QVariant value() const; - void setValue(const QVariant &value); - - private: - QString m_description; - QString m_key; - QString m_label; - QList<QPair<QString, QString> > m_options; - bool m_required; - QXmppDataForm::Field::Type m_type; - QVariant m_value; - }; - - enum Type - { - None, - Form, - Submit, - Cancel, - Result, - }; - - QXmppDataForm(QXmppDataForm::Type type = QXmppDataForm::None); - - QString instructions() const; - void setInstructions(const QString &instructions); - - QList<Field> fields() const; - QList<Field> &fields(); - void setFields(const QList<QXmppDataForm::Field> &fields); - - QString title() const; - void setTitle(const QString &title); - - QXmppDataForm::Type type() const; - void setType(QXmppDataForm::Type type); - - bool isNull() const; - - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - -private: - QString m_instructions; - QList<Field> m_fields; - QString m_title; - QXmppDataForm::Type m_type; -}; - -#endif diff --git a/source/QXmppDiscoveryIq.cpp b/source/QXmppDiscoveryIq.cpp deleted file mode 100644 index 75d5d03f..00000000 --- a/source/QXmppDiscoveryIq.cpp +++ /dev/null @@ -1,300 +0,0 @@ -/* - * 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 <QCryptographicHash> -#include <QDomElement> - -#include "QXmppConstants.h" -#include "QXmppDiscoveryIq.h" -#include "QXmppUtils.h" - -static bool identityLessThan(const QXmppDiscoveryIq::Identity &i1, const QXmppDiscoveryIq::Identity &i2) -{ - if (i1.category() < i2.category()) - return true; - else if (i1.category() > i2.category()) - return false; - - if (i1.type() < i2.type()) - return true; - else if (i1.type() > i2.type()) - return false; - - if (i1.language() < i2.language()) - return true; - else if (i1.language() > i2.language()) - return false; - - if (i1.name() < i2.name()) - return true; - else if (i1.name() > i2.name()) - return false; - - return false; -} - -QString QXmppDiscoveryIq::Identity::category() const -{ - return m_category; -} - -void QXmppDiscoveryIq::Identity::setCategory(const QString &category) -{ - m_category = category; -} - -QString QXmppDiscoveryIq::Identity::language() const -{ - return m_language; -} - -void QXmppDiscoveryIq::Identity::setLanguage(const QString &language) -{ - m_language = language; -} - -QString QXmppDiscoveryIq::Identity::name() const -{ - return m_name; -} - -void QXmppDiscoveryIq::Identity::setName(const QString &name) -{ - m_name = name; -} - -QString QXmppDiscoveryIq::Identity::type() const -{ - return m_type; -} - -void QXmppDiscoveryIq::Identity::setType(const QString &type) -{ - m_type = type; -} - -QString QXmppDiscoveryIq::Item::jid() const -{ - return m_jid; -} - -void QXmppDiscoveryIq::Item::setJid(const QString &jid) -{ - m_jid = jid; -} - -QString QXmppDiscoveryIq::Item::name() const -{ - return m_name; -} - -void QXmppDiscoveryIq::Item::setName(const QString &name) -{ - m_name = name; -} - -QString QXmppDiscoveryIq::Item::node() const -{ - return m_node; -} - -void QXmppDiscoveryIq::Item::setNode(const QString &node) -{ - m_node = node; -} - -QStringList QXmppDiscoveryIq::features() const -{ - return m_features; -} - -void QXmppDiscoveryIq::setFeatures(const QStringList &features) -{ - m_features = features; -} - -QList<QXmppDiscoveryIq::Identity> QXmppDiscoveryIq::identities() const -{ - return m_identities; -} - -void QXmppDiscoveryIq::setIdentities(const QList<QXmppDiscoveryIq::Identity> &identities) -{ - m_identities = identities; -} - -QList<QXmppDiscoveryIq::Item> QXmppDiscoveryIq::items() const -{ - return m_items; -} - -void QXmppDiscoveryIq::setItems(const QList<QXmppDiscoveryIq::Item> &items) -{ - m_items = items; -} - -/// Returns the QXmppDataForm for this IQ, as defined by -/// XEP-0128: Service Discovery Extensions. -/// - -QXmppDataForm QXmppDiscoveryIq::form() const -{ - return m_form; -} - -/// Sets the QXmppDataForm for this IQ, as define by -/// XEP-0128: Service Discovery Extensions. -/// -/// \param form -/// - -void QXmppDiscoveryIq::setForm(const QXmppDataForm &form) -{ - m_form = form; -} - -QString QXmppDiscoveryIq::queryNode() const -{ - return m_queryNode; -} - -void QXmppDiscoveryIq::setQueryNode(const QString &node) -{ - m_queryNode = node; -} - -enum QXmppDiscoveryIq::QueryType QXmppDiscoveryIq::queryType() const -{ - return m_queryType; -} - -void QXmppDiscoveryIq::setQueryType(enum QXmppDiscoveryIq::QueryType type) -{ - m_queryType = type; -} - -/// Calculate the verification string for XEP-0115 : Entity Capabilities - -QByteArray QXmppDiscoveryIq::verificationString() const -{ - QString S; - QList<QXmppDiscoveryIq::Identity> sortedIdentities = m_identities; - qSort(sortedIdentities.begin(), sortedIdentities.end(), identityLessThan); - QStringList sortedFeatures = m_features; - qSort(sortedFeatures); - foreach (const QXmppDiscoveryIq::Identity &identity, sortedIdentities) - S += QString("%1/%2/%3/%4<").arg(identity.category(), identity.type(), identity.language(), identity.name()); - foreach (const QString &feature, sortedFeatures) - S += feature + QLatin1String("<"); - QCryptographicHash hasher(QCryptographicHash::Sha1); - hasher.addData(S.toUtf8()); - return hasher.result(); -} - -bool QXmppDiscoveryIq::isDiscoveryIq(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - return (queryElement.namespaceURI() == ns_disco_info || - queryElement.namespaceURI() == ns_disco_items); -} - -void QXmppDiscoveryIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - m_queryNode = queryElement.attribute("node"); - if (queryElement.namespaceURI() == ns_disco_items) - m_queryType = ItemsQuery; - else - m_queryType = InfoQuery; - - QDomElement itemElement = queryElement.firstChildElement(); - while (!itemElement.isNull()) - { - if (itemElement.tagName() == "feature") - { - m_features.append(itemElement.attribute("var")); - } - else if (itemElement.tagName() == "identity") - { - QXmppDiscoveryIq::Identity identity; - identity.setLanguage(itemElement.attribute("xml:lang")); - identity.setCategory(itemElement.attribute("category")); - identity.setName(itemElement.attribute("name")); - identity.setType(itemElement.attribute("type")); - m_identities.append(identity); - } - else if (itemElement.tagName() == "item") - { - QXmppDiscoveryIq::Item item; - item.setJid(itemElement.attribute("jid")); - item.setName(itemElement.attribute("name")); - item.setNode(itemElement.attribute("node")); - m_items.append(item); - } - else if (itemElement.tagName() == "x" && - itemElement.namespaceURI() == ns_data) - { - m_form.parse(itemElement); - } - itemElement = itemElement.nextSiblingElement(); - } -} - -void QXmppDiscoveryIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("query"); - helperToXmlAddAttribute(writer, "xmlns", - m_queryType == InfoQuery ? ns_disco_info : ns_disco_items); - helperToXmlAddAttribute(writer, "node", m_queryNode); - - foreach (const QString &feature, m_features) - { - writer->writeStartElement("feature"); - helperToXmlAddAttribute(writer, "var", feature); - writer->writeEndElement(); - } - - foreach (const QXmppDiscoveryIq::Identity& identity, m_identities) - { - writer->writeStartElement("identity"); - helperToXmlAddAttribute(writer, "xml:lang", identity.language()); - helperToXmlAddAttribute(writer, "category", identity.category()); - helperToXmlAddAttribute(writer, "name", identity.name()); - helperToXmlAddAttribute(writer, "type", identity.type()); - writer->writeEndElement(); - } - - foreach (const QXmppDiscoveryIq::Item& item, m_items) - { - writer->writeStartElement("item"); - helperToXmlAddAttribute(writer, "jid", item.jid()); - helperToXmlAddAttribute(writer, "name", item.name()); - helperToXmlAddAttribute(writer, "node", item.node()); - writer->writeEndElement(); - } - - m_form.toXml(writer); - - writer->writeEndElement(); -} - diff --git a/source/QXmppDiscoveryIq.h b/source/QXmppDiscoveryIq.h deleted file mode 100644 index 38bdc867..00000000 --- a/source/QXmppDiscoveryIq.h +++ /dev/null @@ -1,118 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPDISCOVERY_H -#define QXMPPDISCOVERY_H - -#include "QXmppElement.h" -#include "QXmppDataForm.h" -#include "QXmppIq.h" - -class QDomElement; - -class QXmppDiscoveryIq : public QXmppIq -{ -public: - class Identity - { - public: - QString category() const; - void setCategory(const QString &category); - - QString language() const; - void setLanguage(const QString &language); - - QString name() const; - void setName(const QString &name); - - QString type() const; - void setType(const QString &type); - - private: - QString m_category; - QString m_language; - QString m_name; - QString m_type; - }; - - class Item - { - public: - QString jid() const; - void setJid(const QString &jid); - - QString name() const; - void setName(const QString &name); - - QString node() const; - void setNode(const QString &node); - - private: - QString m_jid; - QString m_name; - QString m_node; - }; - - enum QueryType { - InfoQuery, - ItemsQuery, - }; - - QStringList features() const; - void setFeatures(const QStringList &features); - - QList<QXmppDiscoveryIq::Identity> identities() const; - void setIdentities(const QList<QXmppDiscoveryIq::Identity> &identities); - - QList<QXmppDiscoveryIq::Item> items() const; - void setItems(const QList<QXmppDiscoveryIq::Item> &items); - - QXmppDataForm form() const; - void setForm(const QXmppDataForm &form); - - QString queryNode() const; - void setQueryNode(const QString &node); - - enum QueryType queryType() const; - void setQueryType(enum QueryType type); - - QByteArray verificationString() const; - - static bool isDiscoveryIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QStringList m_features; - QList<QXmppDiscoveryIq::Identity> m_identities; - QList<QXmppDiscoveryIq::Item> m_items; - QXmppDataForm m_form; - QString m_queryNode; - enum QueryType m_queryType; -}; - -#endif diff --git a/source/QXmppElement.cpp b/source/QXmppElement.cpp deleted file mode 100644 index c282fdec..00000000 --- a/source/QXmppElement.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/* - * 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 "QXmppElement.h" -#include "QXmppUtils.h" - -#include <QDomElement> - -class QXmppElementPrivate -{ -public: - QXmppElementPrivate(); - QXmppElementPrivate(const QDomElement &element); - ~QXmppElementPrivate(); - - QAtomicInt counter; - - QXmppElementPrivate *parent; - QMap<QString, QString> attributes; - QList<QXmppElementPrivate*> children; - QString name; - QString value; -}; - -QXmppElementPrivate::QXmppElementPrivate() - : counter(1), parent(NULL) -{ -} - -QXmppElementPrivate::QXmppElementPrivate(const QDomElement &element) - : counter(1), parent(NULL) -{ - if (element.isNull()) - return; - - name = element.tagName(); - QString xmlns = element.namespaceURI(); - QString parentns = element.parentNode().namespaceURI(); - if (!xmlns.isEmpty() && xmlns != parentns) - attributes.insert("xmlns", xmlns); - QDomNamedNodeMap attrs = element.attributes(); - for (int i = 0; i < attrs.size(); i++) - { - QDomAttr attr = attrs.item(i).toAttr(); - attributes.insert(attr.name(), attr.value()); - } - - QDomNode childNode = element.firstChild(); - while (!childNode.isNull()) - { - if (childNode.isElement()) - { - QXmppElementPrivate *child = new QXmppElementPrivate(childNode.toElement()); - child->parent = this; - children.append(child); - } else if (childNode.isText()) { - value += childNode.toText().data(); - } - childNode = childNode.nextSibling(); - } -} - -QXmppElementPrivate::~QXmppElementPrivate() -{ - foreach (QXmppElementPrivate *child, children) - if (!child->counter.deref()) - delete child; -} - -QXmppElement::QXmppElement() -{ - d = new QXmppElementPrivate(); -} - -QXmppElement::QXmppElement(const QXmppElement &other) -{ - other.d->counter.ref(); - d = other.d; -} - -QXmppElement::QXmppElement(QXmppElementPrivate *other) -{ - other->counter.ref(); - d = other; -} - -QXmppElement::QXmppElement(const QDomElement &element) -{ - d = new QXmppElementPrivate(element); -} - -QXmppElement::~QXmppElement() -{ - if (!d->counter.deref()) - delete d; -} - -QXmppElement &QXmppElement::operator=(const QXmppElement &other) -{ - other.d->counter.ref(); - if (!d->counter.deref()) - delete d; - d = other.d; - return *this; -} - -QStringList QXmppElement::attributeNames() const -{ - return d->attributes.keys(); -} - -QString QXmppElement::attribute(const QString &name) const -{ - return d->attributes.value(name); -} - -void QXmppElement::setAttribute(const QString &name, const QString &value) -{ - d->attributes.insert(name, value); -} - -void QXmppElement::appendChild(const QXmppElement &child) -{ - if (child.d->parent == d) - return; - - if (child.d->parent) - child.d->parent->children.removeAll(child.d); - else - child.d->counter.ref(); - d->children.append(child.d); -} - -QXmppElement QXmppElement::firstChildElement(const QString &name) const -{ - foreach (QXmppElementPrivate *child_d, d->children) - if (name.isEmpty() || child_d->name == name) - return QXmppElement(child_d); - return QXmppElement(); -} - -QXmppElement QXmppElement::nextSiblingElement(const QString &name) const -{ - if (!d->parent) - return QXmppElement(); - const QList<QXmppElementPrivate*> &siblings_d = d->parent->children; - for (int i = siblings_d.indexOf(d) + 1; i < siblings_d.size(); i++) - if (name.isEmpty() || siblings_d[i]->name == name) - return QXmppElement(siblings_d[i]); - return QXmppElement(); -} - -bool QXmppElement::isNull() const -{ - return d->name.isEmpty(); -} - -void QXmppElement::removeChild(const QXmppElement &child) -{ - if (child.d->parent != d) - return; - - d->children.removeAll(child.d); - child.d->counter.deref(); - child.d->parent = NULL; -} - -QString QXmppElement::tagName() const -{ - return d->name; -} - -void QXmppElement::setTagName(const QString &tagName) -{ - d->name = tagName; -} - -QString QXmppElement::value() const -{ - return d->value; -} - -void QXmppElement::setValue(const QString &value) -{ - d->value = value; -} - -void QXmppElement::toXml(QXmlStreamWriter *writer) const -{ - if (isNull()) - return; - - writer->writeStartElement(d->name); - if (d->attributes.contains("xmlns")) - helperToXmlAddAttribute(writer, "xmlns", d->attributes.value("xmlns")); - foreach (const QString &attr, d->attributes.keys()) - if (attr != "xmlns") - helperToXmlAddAttribute(writer, attr, d->attributes.value(attr)); - if (!d->value.isEmpty()) - writer->writeCharacters(d->value); - foreach (const QXmppElement &child, d->children) - child.toXml(writer); - writer->writeEndElement(); -} - -QXmppElementList::QXmppElementList() -{ -} - -QXmppElementList::QXmppElementList(const QXmppElement &element) -{ - append(element); -} - - -QXmppElementList::QXmppElementList(const QList<QXmppElement> &other) - : QList<QXmppElement>(other) -{ -} - diff --git a/source/QXmppElement.h b/source/QXmppElement.h deleted file mode 100644 index f576cd1a..00000000 --- a/source/QXmppElement.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPELEMENT_H -#define QXMPPELEMENT_H - -#include <QMap> -#include <QStringList> -#include <QXmlStreamWriter> - -class QDomElement; -class QXmppElement; -class QXmppElementPrivate; - -class QXmppElementList : public QList<QXmppElement> -{ -public: - QXmppElementList(); - QXmppElementList(const QXmppElement &element); - QXmppElementList(const QList<QXmppElement> &other); -}; - -class QXmppElement -{ -public: - QXmppElement(); - QXmppElement(const QXmppElement &other); - QXmppElement(const QDomElement &element); - ~QXmppElement(); - - QStringList attributeNames() const; - - QString attribute(const QString &name) const; - void setAttribute(const QString &name, const QString &value); - - void appendChild(const QXmppElement &child); - QXmppElement firstChildElement(const QString &name = QString()) const; - QXmppElement nextSiblingElement(const QString &name = QString()) const; - void removeChild(const QXmppElement &child); - - QString tagName() const; - void setTagName(const QString &type); - - QString value() const; - void setValue(const QString &text); - - bool isNull() const; - void toXml(QXmlStreamWriter *writer) const; - - QXmppElement &operator=(const QXmppElement &other); - -private: - QXmppElement(QXmppElementPrivate *other); - QXmppElementPrivate *d; -}; - -#endif diff --git a/source/QXmppIbbIq.cpp b/source/QXmppIbbIq.cpp deleted file mode 100644 index 4b85f6c2..00000000 --- a/source/QXmppIbbIq.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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 <QXmlStreamWriter> - -#include "QXmppConstants.h" -#include "QXmppIbbIq.h" - -QXmppIbbOpenIq::QXmppIbbOpenIq() : QXmppIq(QXmppIq::Set), m_block_size(1024) -{ - -} - -long QXmppIbbOpenIq::blockSize() const -{ - return m_block_size; -} - -void QXmppIbbOpenIq::setBlockSize( long block_size ) -{ - m_block_size = block_size; -} - -QString QXmppIbbOpenIq::sid() const -{ - return m_sid; -} - -void QXmppIbbOpenIq::setSid( const QString &sid ) -{ - m_sid = sid; -} - -bool QXmppIbbOpenIq::isIbbOpenIq(const QDomElement &element) -{ - QDomElement openElement = element.firstChildElement("open"); - return openElement.namespaceURI() == ns_ibb; -} - -void QXmppIbbOpenIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement openElement = element.firstChildElement("open"); - m_sid = openElement.attribute( "sid" ); - m_block_size = openElement.attribute( "block-size" ).toLong(); -} - -void QXmppIbbOpenIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("open"); - writer->writeAttribute( "xmlns",ns_ibb); - writer->writeAttribute( "sid",m_sid); - writer->writeAttribute( "block-size",QString::number(m_block_size) ); - writer->writeEndElement(); -} - -QXmppIbbCloseIq::QXmppIbbCloseIq() : QXmppIq(QXmppIq::Set) -{ - -} - -QString QXmppIbbCloseIq::sid() const -{ - return m_sid; -} - -void QXmppIbbCloseIq::setSid( const QString &sid ) -{ - m_sid = sid; -} - -bool QXmppIbbCloseIq::isIbbCloseIq(const QDomElement &element) -{ - QDomElement openElement = element.firstChildElement("close"); - return openElement.namespaceURI() == ns_ibb; -} - -void QXmppIbbCloseIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement openElement = element.firstChildElement("close"); - m_sid = openElement.attribute( "sid" ); -} - -void QXmppIbbCloseIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("close"); - writer->writeAttribute( "xmlns",ns_ibb); - writer->writeAttribute( "sid",m_sid); - writer->writeEndElement(); -} - -QXmppIbbDataIq::QXmppIbbDataIq() : QXmppIq( QXmppIq::Set ), m_seq(0) -{ -} - -quint16 QXmppIbbDataIq::sequence() const -{ - return m_seq; -} - -void QXmppIbbDataIq::setSequence( quint16 seq ) -{ - m_seq = seq; -} - -QString QXmppIbbDataIq::sid() const -{ - return m_sid; -} - -void QXmppIbbDataIq::setSid( const QString &sid ) -{ - m_sid = sid; -} - -QByteArray QXmppIbbDataIq::payload() const -{ - return m_payload; -} - -void QXmppIbbDataIq::setPayload( const QByteArray &data ) -{ - m_payload = data; -} - -bool QXmppIbbDataIq::isIbbDataIq(const QDomElement &element) -{ - QDomElement dataElement = element.firstChildElement("data"); - return dataElement.namespaceURI() == ns_ibb; -} - -void QXmppIbbDataIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement dataElement = element.firstChildElement("data"); - m_sid = dataElement.attribute( "sid" ); - m_seq = dataElement.attribute( "seq" ).toLong(); - m_payload = QByteArray::fromBase64( dataElement.text().toLatin1() ); -} - -void QXmppIbbDataIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("data"); - writer->writeAttribute( "xmlns",ns_ibb); - writer->writeAttribute( "sid",m_sid); - writer->writeAttribute( "seq",QString::number(m_seq) ); - writer->writeCharacters( m_payload.toBase64() ); - writer->writeEndElement(); -} diff --git a/source/QXmppIbbIq.h b/source/QXmppIbbIq.h deleted file mode 100644 index 05240178..00000000 --- a/source/QXmppIbbIq.h +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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. - * - */ - -#ifndef QXMPPIBBIQ_H -#define QXMPPIBBIQ_H - -#include "QXmppIq.h" - -class QDomElement; -class QXmlStreamWriter; - -class QXmppIbbOpenIq: public QXmppIq -{ -public: - QXmppIbbOpenIq(); - - long blockSize() const; - void setBlockSize( long block_size ); - - QString sid() const; - void setSid( const QString &sid ); - - static bool isIbbOpenIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - long m_block_size; - QString m_sid; -}; - -class QXmppIbbCloseIq: public QXmppIq -{ -public: - QXmppIbbCloseIq(); - - QString sid() const; - void setSid( const QString &sid ); - - static bool isIbbCloseIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QString m_sid; -}; - -class QXmppIbbDataIq : public QXmppIq -{ -public: - QXmppIbbDataIq(); - - quint16 sequence() const; - void setSequence( quint16 seq ); - - QString sid() const; - void setSid( const QString &sid ); - - QByteArray payload() const; - void setPayload( const QByteArray &data ); - - static bool isIbbDataIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - quint16 m_seq; - QString m_sid; - QByteArray m_payload; -}; - -#endif // QXMPPIBBIQS_H diff --git a/source/QXmppInvokable.cpp b/source/QXmppInvokable.cpp deleted file mode 100644 index 86faae55..00000000 --- a/source/QXmppInvokable.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Ian Reinhard Geiser - * - * 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 "QXmppInvokable.h" - -#include <QVariant> -#include <QMetaMethod> -#include <QStringList> - -#include <qdebug.h> - -QXmppInvokable::QXmppInvokable( QObject *parent ) - : QObject( parent ) -{ - -} - - -QXmppInvokable::~QXmppInvokable() -{ - -} - -QVariant QXmppInvokable::dispatch( const QByteArray & method, const QList< QVariant > & args ) -{ - buildMethodHash(); - - if( !m_methodHash.contains(method)) - return QVariant(); - - int idx = m_methodHash[method]; - if( paramTypes( args) != metaObject()->method(idx).parameterTypes ()) - return QVariant(); - - const char *typeName = metaObject()->method(idx).typeName(); - int resultType = QMetaType::type(typeName); - void *result = QMetaType::construct(resultType, 0); - - QGenericReturnArgument ret( typeName, result ); - QList<QGenericArgument> genericArgs; - QList<QVariant>::ConstIterator iter = args.begin(); - while( iter != args.end()) - { - const void *data = iter->data(); - const char *name = iter->typeName(); - genericArgs << QGenericArgument(name,data); - ++iter; - } - - if( QMetaObject::invokeMethod ( this, method.constData(), ret, - genericArgs.value(0, QGenericArgument() ), - genericArgs.value(1, QGenericArgument() ), - genericArgs.value(2, QGenericArgument() ), - genericArgs.value(3, QGenericArgument() ), - genericArgs.value(4, QGenericArgument() ), - genericArgs.value(5, QGenericArgument() ), - genericArgs.value(6, QGenericArgument() ), - genericArgs.value(7, QGenericArgument() ), - genericArgs.value(8, QGenericArgument() ), - genericArgs.value(9, QGenericArgument() )) ) - { - QVariant returnValue( resultType, result); - QMetaType::destroy(resultType, result); - return returnValue; - } - else - { - qDebug("No such method '%s'", method.constData() ); - return QVariant(); - } -} - -QList< QByteArray > QXmppInvokable::paramTypes( const QList< QVariant > & params ) -{ - QList<QByteArray> types; - foreach( QVariant variant, params) - types << variant.typeName(); - return types; -} - -void QXmppInvokable::buildMethodHash( ) -{ - QWriteLocker locker(&m_lock); - if( m_methodHash.size() > 0 ) - return; - - int methodCount = metaObject()->methodCount (); - for( int idx = 0; idx < methodCount; ++idx) - { - QByteArray signature = metaObject()->method(idx).signature(); - m_methodHash[signature.left(signature.indexOf('('))] = idx; -// qDebug() << metaObject()->method(idx).parameterTypes(); - } -} - -QStringList QXmppInvokable::interfaces( ) const -{ - QStringList results; - int methodCount = metaObject()->methodCount (); - for( int idx = 0; idx < methodCount; ++idx) - { - if( metaObject()->method(idx).methodType() == QMetaMethod::Slot ) - { - QByteArray signature = metaObject()->method(idx).signature(); - results << signature.left(signature.indexOf('(')); - } - } - return results; -} - diff --git a/source/QXmppInvokable.h b/source/QXmppInvokable.h deleted file mode 100644 index eb6b72e7..00000000 --- a/source/QXmppInvokable.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Ian Reinhard Geiser - * - * 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. - * - */ - -#ifndef QXMPPINVOKABLE_H -#define QXMPPINVOKABLE_H - -#include <QObject> -#include <QHash> -#include <QVariant> -#include <QWriteLocker> -#include <QStringList> - -/** -This is the base class for all objects that will be invokable via RPC. All public slots of objects derived from this class will be exposed to the RPC interface. As a note for all methods, they can only understand types that QVariant knows about. - - @author Ian Reinhart Geiser <geiseri@kde.org> -*/ -class QXmppInvokable : public QObject -{ - Q_OBJECT -public: - QXmppInvokable( QObject *parent = 0 ); - - ~QXmppInvokable(); - - /** - * Execute a method on an object. with a set of arguments. This method is reentrant, and the method - * that is invoked will be done in a thread safe manner. It should be noted that while this method - * is threadsafe and reentrant the side affects of the methods invoked may not be. - */ - QVariant dispatch( const QByteArray &method, const QList<QVariant> &args = QList<QVariant>() ); - - /** - * Utility method to convert a QList<QVariant> to a list of types for type - * checking. - */ - static QList<QByteArray> paramTypes( const QList<QVariant> ¶ms ); - - /** - * Reimplement this method to return a true if the invoking JID is allowed to execute the method. - */ - virtual bool isAuthorized( const QString &jid ) const = 0; - -public slots: - /** - * This provides a list of interfaces for introspection of the presented interface. - */ - QStringList interfaces() const; - -private: - void buildMethodHash(); - QHash<QByteArray,int> m_methodHash; - QReadWriteLock m_lock; -}; - - -#endif diff --git a/source/QXmppIq.cpp b/source/QXmppIq.cpp deleted file mode 100644 index 072b219a..00000000 --- a/source/QXmppIq.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppUtils.h" -#include "QXmppIq.h" - -#include <QDomElement> -#include <QXmlStreamWriter> - -QXmppIq::QXmppIq(QXmppIq::Type type) - : QXmppStanza(), m_type(type) -{ - generateAndSetNextId(); -} - -/// Returns the IQ's type. -/// - -QXmppIq::Type QXmppIq::type() const -{ - return m_type; -} - -/// Sets the IQ's type. -/// -/// \param type - -void QXmppIq::setType(QXmppIq::Type type) -{ - m_type = type; -} - -void QXmppIq::parse(const QDomElement &element) -{ - QXmppStanza::parse(element); - setTypeFromStr(element.attribute("type")); - parseElementFromChild(element); -} - -void QXmppIq::parseElementFromChild(const QDomElement &element) -{ - QXmppElementList extensions; - QDomElement itemElement = element.firstChildElement(); - while (!itemElement.isNull()) - { - extensions.append(QXmppElement(itemElement)); - itemElement = itemElement.nextSiblingElement(); - } - setExtensions(extensions); -} - -void QXmppIq::toXml( QXmlStreamWriter *xmlWriter ) const -{ - xmlWriter->writeStartElement("iq"); - - helperToXmlAddAttribute(xmlWriter, "id", id()); - helperToXmlAddAttribute(xmlWriter, "to", to()); - helperToXmlAddAttribute(xmlWriter, "from", from()); - if(getTypeStr().isEmpty()) - helperToXmlAddAttribute(xmlWriter, "type", "get"); - else - helperToXmlAddAttribute(xmlWriter, "type", getTypeStr()); - toXmlElementFromChild(xmlWriter); - error().toXml(xmlWriter); - xmlWriter->writeEndElement(); -} - -void QXmppIq::toXmlElementFromChild( QXmlStreamWriter *writer ) const -{ - foreach (const QXmppElement &extension, extensions()) - extension.toXml(writer); -} - -QString QXmppIq::getTypeStr() const -{ - switch(m_type) - { - case QXmppIq::Error: - return "error"; - case QXmppIq::Get: - return "get"; - case QXmppIq::Set: - return "set"; - case QXmppIq::Result: - return "result"; - default: - qWarning("QXmppIq::getTypeStr() invalid type %d", (int)m_type); - return ""; - } -} - -void QXmppIq::setTypeFromStr(const QString& str) -{ - if(str == "error") - { - setType(QXmppIq::Error); - return; - } - else if(str == "get") - { - setType(QXmppIq::Get); - return; - } - else if(str == "set") - { - setType(QXmppIq::Set); - return; - } - else if(str == "result") - { - setType(QXmppIq::Result); - return; - } - else - { - setType(static_cast<QXmppIq::Type>(-1)); - qWarning("QXmppIq::setTypeFromStr() invalid input string type: %s", - qPrintable(str)); - return; - } -} - -// deprecated - -QXmppIq::Type QXmppIq::getType() const -{ - return m_type; -} - diff --git a/source/QXmppIq.h b/source/QXmppIq.h deleted file mode 100644 index 867b1cdd..00000000 --- a/source/QXmppIq.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPIQ_H -#define QXMPPIQ_H - -#include "QXmppStanza.h" - -// forward declarations of QXmlStream* classes will not work on Mac, we need to -// include the whole header. -// See http://lists.trolltech.com/qt-interest/2008-07/thread00798-0.html -// for an explanation. -#include <QXmlStreamWriter> - -/// \brief The QXmppIq class is the base class for all IQs. -/// -/// \ingroup Stanzas - -class QXmppIq : public QXmppStanza -{ -public: - /// This enum describes the type of IQ. - enum Type - { - Error = 0, ///< Error response. - Get, ///< Get request. - Set, ///< Set request. - Result ///< Result. - }; - - QXmppIq(QXmppIq::Type type = QXmppIq::Get); - - QXmppIq::Type type() const; - void setType(QXmppIq::Type); - - /// \cond - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - - // deprecated accessors, use the form without "get" instead - QXmppIq::Type Q_DECL_DEPRECATED getType() const; - -protected: - virtual void parseElementFromChild(const QDomElement &element); - virtual void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QString getTypeStr() const; - void setTypeFromStr(const QString& str); - - Type m_type; -}; - -#endif // QXMPPIQ_H diff --git a/source/QXmppJingleIq.cpp b/source/QXmppJingleIq.cpp deleted file mode 100644 index b5dedfe9..00000000 --- a/source/QXmppJingleIq.cpp +++ /dev/null @@ -1,741 +0,0 @@ -/* - * 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 "QXmppConstants.h" -#include "QXmppJingleIq.h" -#include "QXmppUtils.h" - -static const char* ns_jingle_rtp_info = "urn:xmpp:jingle:apps:rtp:info:1"; - -static const char* jingle_actions[] = { - "content-accept", - "content-add", - "content-modify", - "content-reject", - "content-remove", - "description-info", - "security-info", - "session-accept", - "session-info", - "session-initiate", - "session-terminate", - "transport-accept", - "transport-info", - "transport-reject", - "transport-replace", -}; - -static const char* jingle_reasons[] = { - "", - "alternative-session", - "busy", - "cancel", - "connectivity-error", - "decline", - "expired", - "failed-application", - "failed-transport", - "general-error", - "gone", - "incompatible-parameters", - "media-error", - "security-error", - "success", - "timeout", - "unsupported-applications", - "unsupported-transports", -}; - -QXmppJingleIq::Content::Content() -{ -} - -QString QXmppJingleIq::Content::creator() const -{ - return m_creator; -} - -void QXmppJingleIq::Content::setCreator(const QString &creator) -{ - m_creator = creator; -} - -QString QXmppJingleIq::Content::name() const -{ - return m_name; -} - -void QXmppJingleIq::Content::setName(const QString &name) -{ - m_name = name; -} - -QString QXmppJingleIq::Content::senders() const -{ - return m_senders; -} - -void QXmppJingleIq::Content::setSenders(const QString &senders) -{ - m_senders = senders; -} - -QString QXmppJingleIq::Content::descriptionMedia() const -{ - return m_descriptionMedia; -} - -void QXmppJingleIq::Content::setDescriptionMedia(const QString &media) -{ - m_descriptionMedia = media; -} - -void QXmppJingleIq::Content::addPayloadType(const QXmppJinglePayloadType &payload) -{ - m_descriptionType = ns_jingle_rtp; - m_payloadTypes << payload; -} - -QList<QXmppJinglePayloadType> QXmppJingleIq::Content::payloadTypes() const -{ - return m_payloadTypes; -} - -void QXmppJingleIq::Content::setPayloadTypes(const QList<QXmppJinglePayloadType> &payloadTypes) -{ - m_descriptionType = payloadTypes.isEmpty() ? QString() : ns_jingle_rtp; - m_payloadTypes = payloadTypes; -} - -void QXmppJingleIq::Content::addTransportCandidate(const QXmppJingleCandidate &candidate) -{ - m_transportType = ns_jingle_ice_udp; - m_transportCandidates << candidate; -} - -QList<QXmppJingleCandidate> QXmppJingleIq::Content::transportCandidates() const -{ - return m_transportCandidates; -} - -QString QXmppJingleIq::Content::transportUser() const -{ - return m_transportUser; -} - -void QXmppJingleIq::Content::setTransportUser(const QString &user) -{ - m_transportUser = user; -} - -QString QXmppJingleIq::Content::transportPassword() const -{ - return m_transportPassword; -} - -void QXmppJingleIq::Content::setTransportPassword(const QString &password) -{ - m_transportPassword = password; -} - -void QXmppJingleIq::Content::parse(const QDomElement &element) -{ - m_creator = element.attribute("creator"); - m_disposition = element.attribute("disposition"); - m_name = element.attribute("name"); - m_senders = element.attribute("senders"); - - // description - QDomElement descriptionElement = element.firstChildElement("description"); - m_descriptionType = descriptionElement.namespaceURI(); - m_descriptionMedia = descriptionElement.attribute("media"); - QDomElement child = descriptionElement.firstChildElement("payload-type"); - while (!child.isNull()) - { - QXmppJinglePayloadType payload; - payload.parse(child); - m_payloadTypes << payload; - child = child.nextSiblingElement("payload-type"); - } - - // transport - QDomElement transportElement = element.firstChildElement("transport"); - m_transportType = transportElement.namespaceURI(); - m_transportUser = transportElement.attribute("ufrag"); - m_transportPassword = transportElement.attribute("pwd"); - child = transportElement.firstChildElement("candidate"); - while (!child.isNull()) - { - QXmppJingleCandidate candidate; - candidate.parse(child); - m_transportCandidates << candidate; - child = child.nextSiblingElement("candidate"); - } -} - -void QXmppJingleIq::Content::toXml(QXmlStreamWriter *writer) const -{ - if (m_creator.isEmpty() || m_name.isEmpty()) - return; - - writer->writeStartElement("content"); - helperToXmlAddAttribute(writer, "creator", m_creator); - helperToXmlAddAttribute(writer, "disposition", m_disposition); - helperToXmlAddAttribute(writer, "name", m_name); - helperToXmlAddAttribute(writer, "senders", m_senders); - - // description - if (!m_descriptionType.isEmpty() || !m_payloadTypes.isEmpty()) - { - writer->writeStartElement("description"); - helperToXmlAddAttribute(writer, "xmlns", m_descriptionType); - helperToXmlAddAttribute(writer, "media", m_descriptionMedia); - foreach (const QXmppJinglePayloadType &payload, m_payloadTypes) - payload.toXml(writer); - writer->writeEndElement(); - } - - // transport - if (!m_transportType.isEmpty() || !m_transportCandidates.isEmpty()) - { - writer->writeStartElement("transport"); - helperToXmlAddAttribute(writer, "xmlns", m_transportType); - helperToXmlAddAttribute(writer, "ufrag", m_transportUser); - helperToXmlAddAttribute(writer, "pwd", m_transportPassword); - foreach (const QXmppJingleCandidate &candidate, m_transportCandidates) - candidate.toXml(writer); - writer->writeEndElement(); - } - writer->writeEndElement(); -} - -QXmppJingleIq::Reason::Reason() - : m_type(None) -{ -} - -QString QXmppJingleIq::Reason::text() const -{ - return m_text; -} - -void QXmppJingleIq::Reason::setText(const QString &text) -{ - m_text = text; -} - -QXmppJingleIq::Reason::Type QXmppJingleIq::Reason::type() const -{ - return m_type; -} - -void QXmppJingleIq::Reason::setType(QXmppJingleIq::Reason::Type type) -{ - m_type = type; -} - -void QXmppJingleIq::Reason::parse(const QDomElement &element) -{ - m_text = element.firstChildElement("text").text(); - for (int i = AlternativeSession; i <= UnsupportedTransports; i++) - { - if (!element.firstChildElement(jingle_reasons[i]).isNull()) - { - m_type = static_cast<Type>(i); - break; - } - } -} - -void QXmppJingleIq::Reason::toXml(QXmlStreamWriter *writer) const -{ - if (m_type < AlternativeSession || m_type > UnsupportedTransports) - return; - - writer->writeStartElement("reason"); - if (!m_text.isEmpty()) - helperToXmlAddTextElement(writer, "text", m_text); - writer->writeEmptyElement(jingle_reasons[m_type]); - writer->writeEndElement(); -} - -QXmppJingleIq::QXmppJingleIq() - : m_ringing(false) -{ -} - -QXmppJingleIq::Action QXmppJingleIq::action() const -{ - return m_action; -} - -void QXmppJingleIq::setAction(QXmppJingleIq::Action action) -{ - m_action = action; -} - -QString QXmppJingleIq::initiator() const -{ - return m_initiator; -} - -void QXmppJingleIq::setInitiator(const QString &initiator) -{ - m_initiator = initiator; -} - -QString QXmppJingleIq::responder() const -{ - return m_responder; -} - -void QXmppJingleIq::setResponder(const QString &responder) -{ - m_responder = responder; -} - -QString QXmppJingleIq::sid() const -{ - return m_sid; -} - -void QXmppJingleIq::setSid(const QString &sid) -{ - m_sid = sid; -} - -bool QXmppJingleIq::isJingleIq(const QDomElement &element) -{ - QDomElement jingleElement = element.firstChildElement("jingle"); - return (jingleElement.namespaceURI() == ns_jingle); -} - -bool QXmppJingleIq::ringing() const -{ - return m_ringing; -} - -void QXmppJingleIq::setRinging(bool ringing) -{ - m_ringing = ringing; -} - -void QXmppJingleIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement jingleElement = element.firstChildElement("jingle"); - const QString action = jingleElement.attribute("action"); - for (int i = ContentAccept; i <= TransportReplace; i++) - { - if (action == jingle_actions[i]) - { - m_action = static_cast<Action>(i); - break; - } - } - m_initiator = jingleElement.attribute("initiator"); - m_responder = jingleElement.attribute("responder"); - m_sid = jingleElement.attribute("sid"); - - // content - QDomElement contentElement = jingleElement.firstChildElement("content"); - m_content.parse(contentElement); - QDomElement reasonElement = jingleElement.firstChildElement("reason"); - m_reason.parse(reasonElement); - - // ringing - QDomElement ringingElement = jingleElement.firstChildElement("ringing"); - m_ringing = (ringingElement.namespaceURI() == ns_jingle_rtp_info); -} - -void QXmppJingleIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("jingle"); - helperToXmlAddAttribute(writer, "xmlns", ns_jingle); - helperToXmlAddAttribute(writer, "action", jingle_actions[m_action]); - helperToXmlAddAttribute(writer, "initiator", m_initiator); - helperToXmlAddAttribute(writer, "responder", m_responder); - helperToXmlAddAttribute(writer, "sid", m_sid); - m_content.toXml(writer); - m_reason.toXml(writer); - - // ringing - if (m_ringing) - { - writer->writeStartElement("ringing"); - helperToXmlAddAttribute(writer, "xmlns", ns_jingle_rtp_info); - writer->writeEndElement(); - } - - writer->writeEndElement(); -} - -QXmppJingleCandidate::QXmppJingleCandidate() - : m_component(0), - m_foundation(0), - m_generation(0), - m_network(0), - m_port(0), - m_priority(0) -{ -} - -/// Returns the candidate's component ID. - -int QXmppJingleCandidate::component() const -{ - return m_component; -} - -/// Sets the candidates's component ID. -/// -/// \param component - -void QXmppJingleCandidate::setComponent(int component) -{ - m_component = component; -} - -/// Returns the candidate's foundation. - -int QXmppJingleCandidate::foundation() const -{ - return m_foundation; -} - -/// Sets the candidate's foundation. -/// -/// \param foundation - -void QXmppJingleCandidate::setFoundation(int foundation) -{ - m_foundation = foundation; -} - -/// Returns the candidate's host address. -/// - -QHostAddress QXmppJingleCandidate::host() const -{ - return m_host; -} - -/// Sets the candidate's host address. -/// -/// \param host - -void QXmppJingleCandidate::setHost(const QHostAddress &host) -{ - m_host = host; -} - -/// Returns the candidate's unique identifier. -/// - -QString QXmppJingleCandidate::id() const -{ - return m_id; -} - -/// Sets the candidate's unique identifier. -/// -/// \param id - -void QXmppJingleCandidate::setId(const QString &id) -{ - m_id = id; -} - -/// Returns the network index (starting at 0) the candidate is on. -/// - -int QXmppJingleCandidate::network() const -{ - return m_network; -} - -/// Sets the network index (starting at 0) the candidate is on. -/// -/// \param network - -void QXmppJingleCandidate::setNetwork(int network) -{ - m_network = network; -} - -/// Returns the candidate's port number. -/// - -quint16 QXmppJingleCandidate::port() const -{ - return m_port; -} - -/// Sets the candidate's port number. -/// -/// \param port - -void QXmppJingleCandidate::setPort(quint16 port) -{ - m_port = port; -} - -/// Returns the candidate's priority. -/// - -int QXmppJingleCandidate::priority() const -{ - return m_priority; -} - -/// Sets the candidate's priority. -/// -/// \param priority - -void QXmppJingleCandidate::setPriority(int priority) -{ - m_priority = priority; -} - -/// Returns the candidate's protocol (e.g. "udp"). -/// - -QString QXmppJingleCandidate::protocol() const -{ - return m_protocol; -} - -/// Sets the candidate's protocol (e.g. "udp"). -/// -/// \param protocol - -void QXmppJingleCandidate::setProtocol(const QString &protocol) -{ - m_protocol = protocol; -} - -/// Returns the candidate type (e.g. "host"). -/// - -QString QXmppJingleCandidate::type() const -{ - return m_type; -} - -/// Sets the candidate type (e.g. "host"). -/// -/// \param type - -void QXmppJingleCandidate::setType(const QString &type) -{ - m_type = type; -} - -/// Returns true if the host address or port are empty. -/// - -bool QXmppJingleCandidate::isNull() const -{ - return m_host.isNull() || !m_port; -} - -void QXmppJingleCandidate::parse(const QDomElement &element) -{ - m_component = element.attribute("component").toInt(); - m_foundation = element.attribute("foundation").toInt(); - m_generation = element.attribute("generation").toInt(); - m_host = QHostAddress(element.attribute("ip")); - m_id = element.attribute("id"); - m_network = element.attribute("network").toInt(); - m_port = element.attribute("port").toInt(); - m_priority = element.attribute("priority").toInt(); - m_protocol = element.attribute("protocol"); - m_type = element.attribute("type"); -} - -void QXmppJingleCandidate::toXml(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("candidate"); - helperToXmlAddAttribute(writer, "component", QString::number(m_component)); - helperToXmlAddAttribute(writer, "foundation", QString::number(m_foundation)); - helperToXmlAddAttribute(writer, "generation", QString::number(m_generation)); - helperToXmlAddAttribute(writer, "id", m_id); - helperToXmlAddAttribute(writer, "ip", m_host.toString()); - helperToXmlAddAttribute(writer, "network", QString::number(m_network)); - helperToXmlAddAttribute(writer, "port", QString::number(m_port)); - helperToXmlAddAttribute(writer, "priority", QString::number(m_priority)); - helperToXmlAddAttribute(writer, "protocol", m_protocol); - helperToXmlAddAttribute(writer, "type", m_type); - writer->writeEndElement(); -} - -QXmppJinglePayloadType::QXmppJinglePayloadType() - : m_channels(1), - m_clockrate(0), - m_id(0), - m_maxptime(0), - m_ptime(0) -{ -} - -/// Returns the number of channels (e.g. 1 for mono, 2 for stereo). -/// - -unsigned char QXmppJinglePayloadType::channels() const -{ - return m_channels; -} - -/// Sets the number of channels (e.g. 1 for mono, 2 for stereo). -/// -/// \param channels - -void QXmppJinglePayloadType::setChannels(unsigned char channels) -{ - m_channels = channels; -} - -/// Returns the clockrate in Hz, i.e. the number of samples per second. -/// - -unsigned int QXmppJinglePayloadType::clockrate() const -{ - return m_clockrate; -} - -/// Sets the clockrate in Hz, i.e. the number of samples per second. -/// -/// \param clockrate - -void QXmppJinglePayloadType::setClockrate(unsigned int clockrate) -{ - m_clockrate = clockrate; -} - -/// Returns the payload type identifier. -/// - -unsigned char QXmppJinglePayloadType::id() const -{ - return m_id; -} - -/// Sets the payload type identifier. -/// - -void QXmppJinglePayloadType::setId(unsigned char id) -{ - Q_ASSERT(id <= 127); - m_id = id; -} - -/// Returns the maximum packet time in milliseconds. -/// - -unsigned int QXmppJinglePayloadType::maxptime() const -{ - return m_maxptime; -} - -/// Sets the maximum packet type in milliseconds. -/// -/// \param maxptime - -void QXmppJinglePayloadType::setMaxptime(unsigned int maxptime) -{ - m_maxptime = maxptime; -} - -/// Returns the payload type name. -/// - -QString QXmppJinglePayloadType::name() const -{ - return m_name; -} - -/// Sets the payload type name. -/// -/// \param name - -void QXmppJinglePayloadType::setName(const QString &name) -{ - m_name = name; -} - -/// Returns the packet time in milliseconds (20 by default). -/// - -unsigned int QXmppJinglePayloadType::ptime() const -{ - return m_ptime ? m_ptime : 20; -} - -/// Sets the packet time in milliseconds (20 by default). -/// -/// \param ptime - -void QXmppJinglePayloadType::setPtime(unsigned int ptime) -{ - m_ptime = ptime; -} - -void QXmppJinglePayloadType::parse(const QDomElement &element) -{ - m_id = element.attribute("id").toInt(); - m_name = element.attribute("name"); - m_channels = element.attribute("channels").toInt(); - if (!m_channels) - m_channels = 1; - m_clockrate = element.attribute("clockrate").toInt(); - m_maxptime = element.attribute("maxptime").toInt(); - m_ptime = element.attribute("ptime").toInt(); -} - -void QXmppJinglePayloadType::toXml(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("payload-type"); - helperToXmlAddAttribute(writer, "id", QString::number(m_id)); - helperToXmlAddAttribute(writer, "name", m_name); - if (m_channels > 1) - helperToXmlAddAttribute(writer, "channels", QString::number(m_channels)); - if (m_clockrate > 0) - helperToXmlAddAttribute(writer, "clockrate", QString::number(m_clockrate)); - if (m_maxptime > 0) - helperToXmlAddAttribute(writer, "maxptime", QString::number(m_maxptime)); - if (m_ptime > 0) - helperToXmlAddAttribute(writer, "ptime", QString::number(m_ptime)); - writer->writeEndElement(); -} - -bool QXmppJinglePayloadType::operator==(const QXmppJinglePayloadType &other) const -{ - // FIXME : what to do with m_ptime and m_maxptime? - if (m_id <= 95) - return other.m_id == m_id && other.m_clockrate == m_clockrate; - else - return other.m_channels == m_channels && - other.m_clockrate == m_clockrate && - other.m_name.toLower() == m_name.toLower(); -} diff --git a/source/QXmppJingleIq.h b/source/QXmppJingleIq.h deleted file mode 100644 index 5e80ad25..00000000 --- a/source/QXmppJingleIq.h +++ /dev/null @@ -1,302 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPJINGLEIQ_H -#define QXMPPJINGLEIQ_H - -#include <QHostAddress> - -#include "QXmppIq.h" - -/// \brief The QXmppJinglePayloadType class represents a payload type -/// as specified by XEP-0167: Jingle RTP Sessions and RFC 5245. -/// - -class QXmppJinglePayloadType -{ -public: - QXmppJinglePayloadType(); - - unsigned char channels() const; - void setChannels(unsigned char channels); - - unsigned int clockrate() const; - void setClockrate(unsigned int clockrate); - - unsigned char id() const; - void setId(unsigned char id); - - unsigned int maxptime() const; - void setMaxptime(unsigned int maxptime); - - QString name() const; - void setName(const QString &name); - - unsigned int ptime() const; - void setPtime(unsigned int ptime); - - /// \cond - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - /// \endcond - - bool operator==(const QXmppJinglePayloadType &other) const; - -private: - unsigned char m_channels; - unsigned int m_clockrate; - unsigned char m_id; - unsigned int m_maxptime; - QString m_name; - unsigned int m_ptime; -}; - -/// \brief The QXmppJingleCandidate class represents a transport candidate -/// as specified by XEP-0176: Jingle ICE-UDP Transport Method. -/// - -class QXmppJingleCandidate -{ -public: - QXmppJingleCandidate(); - - int component() const; - void setComponent(int component); - - int foundation() const; - void setFoundation(int foundation); - - QHostAddress host() const; - void setHost(const QHostAddress &host); - - QString id() const; - void setId(const QString &id); - - int network() const; - void setNetwork(int network); - - quint16 port() const; - void setPort(quint16 port); - - int priority() const; - void setPriority(int priority); - - QString protocol() const; - void setProtocol(const QString &protocol); - - QString type() const; - void setType(const QString &type); - - bool isNull() const; - - /// \cond - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - /// \endcond - -private: - int m_component; - int m_foundation; - int m_generation; - QHostAddress m_host; - QString m_id; - int m_network; - quint16 m_port; - QString m_protocol; - int m_priority; - QString m_type; -}; - -/// \brief The QXmppJingleIq class represents an IQ used for initiating media -/// sessions as specified by XEP-0166: Jingle. -/// -/// \ingroup Stanzas - -class QXmppJingleIq : public QXmppIq -{ -public: - enum Action { - ContentAccept, - ContentAdd, - ContentModify, - ContentReject, - ContentRemove, - DescriptionInfo, - SecurityInfo, - SessionAccept, - SessionInfo, - SessionInitiate, - SessionTerminate, - TransportAccept, - TransportInfo, - TransportReject, - TransportReplace, - }; - - /// \internal - /// - /// The QXmppJingleIq::Content class represents the "content" element of a - /// QXmppJingleIq. - - class Content - { - public: - Content(); - - QString creator() const; - void setCreator(const QString &creator); - - QString name() const; - void setName(const QString &name); - - QString senders() const; - void setSenders(const QString &senders); - - // XEP-0167: Jingle RTP Sessions - QString descriptionMedia() const; - void setDescriptionMedia(const QString &media); - - void addPayloadType(const QXmppJinglePayloadType &payload); - QList<QXmppJinglePayloadType> payloadTypes() const; - void setPayloadTypes(const QList<QXmppJinglePayloadType> &payloadTypes); - - void addTransportCandidate(const QXmppJingleCandidate &candidate); - QList<QXmppJingleCandidate> transportCandidates() const; - - QString transportUser() const; - void setTransportUser(const QString &user); - - QString transportPassword() const; - void setTransportPassword(const QString &password); - - /// \cond - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - /// \endcond - - private: - QString m_creator; - QString m_disposition; - QString m_name; - QString m_senders; - - QString m_descriptionMedia; - QString m_descriptionType; - QString m_transportType; - QString m_transportUser; - QString m_transportPassword; - QList<QXmppJinglePayloadType> m_payloadTypes; - QList<QXmppJingleCandidate> m_transportCandidates; - }; - - /// \internal - /// - /// The QXmppJingleIq::Reason class represents the "reason" element of a - /// QXmppJingleIq. - - class Reason - { - public: - enum Type { - None, - AlternativeSession, - Busy, - Cancel, - ConnectivityError, - Decline, - Expired, - FailedApplication, - FailedTransport, - GeneralError, - Gone, - IncompatibleParameters, - MediaError, - SecurityError, - Success, - Timeout, - UnsupportedApplications, - UnsupportedTransports, - }; - - Reason(); - - QString text() const; - void setText(const QString &text); - - Type type() const; - void setType(Type type); - - /// \cond - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - /// \endcond - - private: - QString m_text; - Type m_type; - }; - - QXmppJingleIq(); - - Action action() const; - void setAction(Action action); - - QString initiator() const; - void setInitiator(const QString &initiator); - - QString responder() const; - void setResponder(const QString &responder); - - QString sid() const; - void setSid(const QString &sid); - - Content& content() { return m_content; }; - const Content& content() const { return m_content; }; - - Reason& reason() { return m_reason; }; - const Reason& reason() const { return m_reason; }; - - // XEP-0167: Jingle RTP Sessions - bool ringing() const; - void setRinging(bool ringing); - - static bool isJingleIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - Action m_action; - QString m_initiator; - QString m_responder; - QString m_sid; - - Content m_content; - Reason m_reason; - bool m_ringing; -}; - -#endif diff --git a/source/QXmppLogger.cpp b/source/QXmppLogger.cpp deleted file mode 100644 index ccff3fb5..00000000 --- a/source/QXmppLogger.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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 <iostream> - -#include <QTextStream> -#include <QFile> -#include <QTime> - -#include "QXmppLogger.h" - -QXmppLogger* QXmppLogger::m_logger = 0; - -static const char *typeName(QXmppLogger::MessageType type) -{ - switch (type) - { - case QXmppLogger::DebugMessage: - return "DEBUG"; - case QXmppLogger::InformationMessage: - return "INFO"; - case QXmppLogger::WarningMessage: - return "WARNING"; - case QXmppLogger::ReceivedMessage: - return "SERVER"; - case QXmppLogger::SentMessage: - return "CLIENT"; - default: - return ""; - } -} - -/// Constructs a new QXmppLogger. -/// -/// \param parent - -QXmppLogger::QXmppLogger(QObject *parent) - : QObject(parent), m_loggingType(QXmppLogger::NoLogging), - m_logFilePath("QXmppClientLog.log") -{ -} - -/// Returns the default logger. -/// - -QXmppLogger* QXmppLogger::getLogger() -{ - if(!m_logger) - { - m_logger = new QXmppLogger(); - m_logger->setLoggingType(FileLogging); - } - - return m_logger; -} - -/// Returns the handler for logging messages. -/// - -QXmppLogger::LoggingType QXmppLogger::loggingType() -{ - return m_loggingType; -} - -/// Sets the handler for logging messages. -/// -/// \param type - -void QXmppLogger::setLoggingType(QXmppLogger::LoggingType type) -{ - m_loggingType = type; -} - -/// Add a logging message. -/// -/// \param type -/// \param text - -void QXmppLogger::log(QXmppLogger::MessageType type, const QString& text) -{ - switch(m_loggingType) - { - case QXmppLogger::FileLogging: - { - QFile file(m_logFilePath); - file.open(QIODevice::Append); - QTextStream stream(&file); - stream << QTime::currentTime().toString("hh:mm:ss.zzz") << - " " << typeName(type) << " " << - text << "\n\n"; - } - break; - case QXmppLogger::StdoutLogging: - std::cout << typeName(type) << " " << qPrintable(text) << std::endl; - break; - case QXmppLogger::SignalLogging: - emit message(type, text); - break; - default: - break; - } -} - -/// Returns the path to which logging messages should be written. -/// -/// \sa loggingType() - -QString QXmppLogger::logFilePath() -{ - return m_logFilePath; -} - -/// Sets the path to which logging messages should be written. -/// -/// \param path -/// -/// \sa setLoggingType() - -void QXmppLogger::setLogFilePath(const QString &path) -{ - m_logFilePath = path; -} - diff --git a/source/QXmppLogger.h b/source/QXmppLogger.h deleted file mode 100644 index f0fee6df..00000000 --- a/source/QXmppLogger.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPLOGGER_H -#define QXMPPLOGGER_H - -#include <QObject> - -/// \brief The QXmppLogger class represents a sink for logging messages. -/// -/// \ingroup Core - -class QXmppLogger : public QObject -{ - Q_OBJECT - -public: - /// This enum describes how log message are handled. - enum LoggingType - { - NoLogging = 0, ///< Log messages are discarded - FileLogging = 1, ///< Log messages are written to a file - StdoutLogging = 2, ///< Log messages are written to the standard output - SignalLogging = 4, ///< Log messages are emitted as a signal - - // Deprecated - /// \cond - NONE = 0, ///< DEPRECATED Log messages are discarded - FILE = 1, ///< DEPRECATED Log messages are written to a file - STDOUT = 2 ///< DEPRECATED Log messages are written to the standard output - /// \endcond - }; - - /// This enum describes a type of log message. - enum MessageType - { - DebugMessage = 0, ///< Debugging message - InformationMessage, ///< Informational message - WarningMessage, ///< Warning message - ReceivedMessage, ///< Message received from server - SentMessage, ///< Message sent to server - }; - - QXmppLogger(QObject *parent = 0); - static QXmppLogger* getLogger(); - - QXmppLogger::LoggingType loggingType(); - void setLoggingType(QXmppLogger::LoggingType type); - - QString logFilePath(); - void setLogFilePath(const QString &path); - -public slots: - void log(QXmppLogger::MessageType type, const QString& text); - -signals: - /// This signal is emitted whenever a log message is received. - void message(QXmppLogger::MessageType type, const QString &text); - -private: - static QXmppLogger* m_logger; - QXmppLogger::LoggingType m_loggingType; - QString m_logFilePath; -}; - -#endif // QXMPPLOGGER_H diff --git a/source/QXmppMessage.cpp b/source/QXmppMessage.cpp deleted file mode 100644 index 8c626391..00000000 --- a/source/QXmppMessage.cpp +++ /dev/null @@ -1,346 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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 <QXmlStreamWriter> - -#include "QXmppConstants.h" -#include "QXmppMessage.h" -#include "QXmppUtils.h" - -static const char* chat_states[] = { - "", - "active", - "inactive", - "gone", - "composing", - "paused", -}; - -QXmppMessage::QXmppMessage(const QString& from, const QString& to, const - QString& body, const QString& thread) - : QXmppStanza(from, to), - m_type(Chat), - m_stampType(QXmppMessage::DelayedDelivery), - m_state(None), - m_body(body), - m_thread(thread) -{ -} - -QXmppMessage::~QXmppMessage() -{ - -} - -/// Returns the message's body. -/// - -QString QXmppMessage::body() const -{ - return m_body; -} - -/// Sets the message's body. -/// -/// \param body - -void QXmppMessage::setBody(const QString& body) -{ - m_body = body; -} - -/// Returns the message's type. -/// - -QXmppMessage::Type QXmppMessage::type() const -{ - return m_type; -} - -QString QXmppMessage::getTypeStr() const -{ - switch(m_type) - { - case QXmppMessage::Error: - return "error"; - case QXmppMessage::Normal: - return "normal"; - case QXmppMessage::Chat: - return "chat"; - case QXmppMessage::GroupChat: - return "groupchat"; - case QXmppMessage::Headline: - return "headline"; - default: - qWarning("QXmppMessage::getTypeStr() invalid type %d", (int)m_type); - return ""; - } -} - -/// Sets the message's type. -/// -/// \param type - -void QXmppMessage::setType(QXmppMessage::Type type) -{ - m_type = type; -} - -void QXmppMessage::setTypeFromStr(const QString& str) -{ - if(str == "error") - { - setType(QXmppMessage::Error); - return; - } - else if(str == "") // if no type is specified - { - setType(QXmppMessage::Normal); - return; - } - else if(str == "normal") - { - setType(QXmppMessage::Normal); - return; - } - else if(str == "chat") - { - setType(QXmppMessage::Chat); - return; - } - else if(str == "groupchat") - { - setType(QXmppMessage::GroupChat); - return; - } - else if(str == "headline") - { - setType(QXmppMessage::Headline); - return; - } - else - { - setType(static_cast<QXmppMessage::Type>(-1)); - qWarning("QXmppMessage::setTypeFromStr() invalid input string type: %s", - qPrintable(str)); - return; - } -} - -/// Returns the message's timestamp (if any). - -QDateTime QXmppMessage::stamp() const -{ - return m_stamp; -} - -/// Sets the message's timestamp. -/// -/// \param stamp - -void QXmppMessage::setStamp(const QDateTime &stamp) -{ - m_stamp = stamp; -} - -/// Returns the message's chat state. -/// - -QXmppMessage::State QXmppMessage::state() const -{ - return m_state; -} - -/// Sets the message's chat state. -/// -/// \param state - -void QXmppMessage::setState(QXmppMessage::State state) -{ - m_state = state; -} - -void QXmppMessage::parse(const QDomElement &element) -{ - QXmppStanza::parse(element); - - setTypeFromStr(element.attribute("type")); - setBody(unescapeString( - element.firstChildElement("body").text())); - setSubject(unescapeString( - element.firstChildElement("subject").text())); - setThread(element.firstChildElement("thread").text()); - - // chat states - for (int i = Active; i <= Paused; i++) - { - QDomElement stateElement = element.firstChildElement(chat_states[i]); - if (!stateElement.isNull() && - stateElement.namespaceURI() == ns_chat_states) - { - m_state = static_cast<QXmppMessage::State>(i); - break; - } - } - - // XEP-0203: Delayed Delivery - QDomElement delayElement = element.firstChildElement("delay"); - if (!delayElement.isNull() && delayElement.namespaceURI() == ns_delayed_delivery) - { - const QString str = delayElement.attribute("stamp"); - m_stamp = datetimeFromString(str); - m_stampType = QXmppMessage::DelayedDelivery; - } - - QXmppElementList extensions; - QDomElement xElement = element.firstChildElement("x"); - while (!xElement.isNull()) - { - if (xElement.namespaceURI() == ns_legacy_delayed_delivery) - { - // XEP-0091: Legacy Delayed Delivery - const QString str = xElement.attribute("stamp"); - m_stamp = QDateTime::fromString(str, "yyyyMMddThh:mm:ss"); - m_stamp.setTimeSpec(Qt::UTC); - m_stampType = QXmppMessage::LegacyDelayedDelivery; - } else { - // other extensions - extensions << QXmppElement(xElement); - } - xElement = xElement.nextSiblingElement("x"); - } - setExtensions(extensions); -} - -void QXmppMessage::toXml(QXmlStreamWriter *xmlWriter) const -{ - - xmlWriter->writeStartElement("message"); - helperToXmlAddAttribute(xmlWriter, "xml:lang", lang()); - helperToXmlAddAttribute(xmlWriter, "id", id()); - helperToXmlAddAttribute(xmlWriter, "to", to()); - helperToXmlAddAttribute(xmlWriter, "from", from()); - helperToXmlAddAttribute(xmlWriter, "type", getTypeStr()); - if (!m_subject.isEmpty()) - helperToXmlAddTextElement(xmlWriter, "subject", m_subject); - if (!m_body.isEmpty()) - helperToXmlAddTextElement(xmlWriter, "body", m_body); - if (!m_thread.isEmpty()) - helperToXmlAddTextElement(xmlWriter, "thread", m_thread); - error().toXml(xmlWriter); - - // chat states - if (m_state > None && m_state <= Paused) - { - xmlWriter->writeStartElement(chat_states[m_state]); - helperToXmlAddAttribute(xmlWriter, "xmlns", ns_chat_states); - xmlWriter->writeEndElement(); - } - - // time stamp - if (m_stamp.isValid()) - { - QDateTime utcStamp = m_stamp.toUTC(); - if (m_stampType == QXmppMessage::DelayedDelivery) - { - // XEP-0203: Delayed Delivery - xmlWriter->writeStartElement("delay"); - helperToXmlAddAttribute(xmlWriter, "xmlns", ns_delayed_delivery); - helperToXmlAddAttribute(xmlWriter, "stamp", datetimeToString(utcStamp)); - xmlWriter->writeEndElement(); - } else { - // XEP-0091: Legacy Delayed Delivery - xmlWriter->writeStartElement("x"); - helperToXmlAddAttribute(xmlWriter, "xmlns", ns_legacy_delayed_delivery); - helperToXmlAddAttribute(xmlWriter, "stamp", utcStamp.toString("yyyyMMddThh:mm:ss")); - xmlWriter->writeEndElement(); - } - } - - // other extensions - foreach (const QXmppElement &extension, extensions()) - extension.toXml(xmlWriter); - xmlWriter->writeEndElement(); -} - -/// Returns the message's subject. -/// - -QString QXmppMessage::subject() const -{ - return m_subject; -} - -/// Sets the message's subject. -/// -/// \param subject - -void QXmppMessage::setSubject(const QString& subject) -{ - m_subject = subject; -} - -/// Returns the message's thread. - -QString QXmppMessage::thread() const -{ - return m_thread; -} - -/// Sets the message's thread. -/// -/// \param thread - -void QXmppMessage::setThread(const QString& thread) -{ - m_thread = thread; -} - -// deprecated - -QXmppMessage::Type QXmppMessage::getType() const -{ - return m_type; -} - -QXmppMessage::State QXmppMessage::getState() const -{ - return m_state; -} - -QString QXmppMessage::getBody() const -{ - return m_body; -} - -QString QXmppMessage::getSubject() const -{ - return m_subject; -} - -QString QXmppMessage::getThread() const -{ - return m_thread; -} diff --git a/source/QXmppMessage.h b/source/QXmppMessage.h deleted file mode 100644 index e337dcb1..00000000 --- a/source/QXmppMessage.h +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPMESSAGE_H -#define QXMPPMESSAGE_H - -#include <QDateTime> -#include "QXmppStanza.h" - -/// \brief The QXmppMessage class represents an XMPP message. -/// -/// \ingroup Stanzas -/// - -class QXmppMessage : public QXmppStanza -{ -public: - /// This enum described a message type. - enum Type - { - Error = 0, - Normal, - Chat, - GroupChat, - Headline - }; - - /// This enum describes a chat state as defined by - /// XEP-0085 : Chat State Notifications. - enum State - { - None = 0, - Active, - Inactive, - Gone, - Composing, - Paused, - }; - - QXmppMessage(const QString& from = "", const QString& to = "", - const QString& body = "", const QString& thread = ""); - ~QXmppMessage(); - - QString body() const; - void setBody(const QString&); - - QDateTime stamp() const; - void setStamp(const QDateTime &stamp); - - QXmppMessage::State state() const; - void setState(QXmppMessage::State); - - QString subject() const; - void setSubject(const QString&); - - QString thread() const; - void setThread(const QString&); - - QXmppMessage::Type type() const; - void setType(QXmppMessage::Type); - - /// \cond - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - - // deprecated accessors, use the form without "get" instead - QXmppMessage::Type Q_DECL_DEPRECATED getType() const; - QXmppMessage::State Q_DECL_DEPRECATED getState() const; - QString Q_DECL_DEPRECATED getBody() const; - QString Q_DECL_DEPRECATED getSubject() const; - QString Q_DECL_DEPRECATED getThread() const; - /// \endcond - -private: - /// This enum describe a type of message timestamp. - enum StampType - { - LegacyDelayedDelivery, ///< XEP-0091: Legacy Delayed Delivery - DelayedDelivery, ///< XEP-0203: Delayed Delivery - }; - - QString getTypeStr() const; - void setTypeFromStr(const QString&); - - Type m_type; - QDateTime m_stamp; - StampType m_stampType; - State m_state; - - QString m_body; - QString m_subject; - QString m_thread; -}; - -#endif // QXMPPMESSAGE_H diff --git a/source/QXmppMucIq.cpp b/source/QXmppMucIq.cpp deleted file mode 100644 index 63af7567..00000000 --- a/source/QXmppMucIq.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* - * 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 "QXmppConstants.h" -#include "QXmppMucIq.h" -#include "QXmppUtils.h" - -QString QXmppMucAdminIq::Item::affiliation() const -{ - return m_affiliation; -} - -void QXmppMucAdminIq::Item::setAffiliation(const QString &affiliation) -{ - m_affiliation = affiliation; -} - -QString QXmppMucAdminIq::Item::jid() const -{ - return m_jid; -} - -void QXmppMucAdminIq::Item::setJid(const QString &jid) -{ - m_jid = jid; -} - -QString QXmppMucAdminIq::Item::nick() const -{ - return m_nick; -} - -void QXmppMucAdminIq::Item::setNick(const QString &nick) -{ - m_nick = nick; -} - -QString QXmppMucAdminIq::Item::reason() const -{ - return m_reason; -} - -void QXmppMucAdminIq::Item::setReason(const QString &reason) -{ - m_reason = reason; -} - -QString QXmppMucAdminIq::Item::role() const -{ - return m_role; -} - -void QXmppMucAdminIq::Item::setRole(const QString &role) -{ - m_role = role; -} - -QList<QXmppMucAdminIq::Item> QXmppMucAdminIq::items() const -{ - return m_items; -} - -void QXmppMucAdminIq::setItems(const QList<QXmppMucAdminIq::Item> &items) -{ - m_items = items; -} - -bool QXmppMucAdminIq::isMucAdminIq(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - return (queryElement.namespaceURI() == ns_muc_admin); -} - -void QXmppMucAdminIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - QDomElement child = queryElement.firstChildElement("item"); - while (!child.isNull()) - { - QXmppMucAdminIq::Item item; - item.setAffiliation(child.attribute("affiliation")); - item.setJid(child.attribute("jid")); - item.setNick(child.attribute("nick")); - item.setRole(child.attribute("role")); - item.setReason(child.firstChildElement("reason").text()); - m_items << item; - child = child.nextSiblingElement("item"); - } -} -void QXmppMucAdminIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("query"); - helperToXmlAddAttribute(writer, "xmlns", ns_muc_admin); - foreach (const QXmppMucAdminIq::Item &item, m_items) - { - writer->writeStartElement("item"); - helperToXmlAddAttribute(writer, "jid", item.jid()); - helperToXmlAddAttribute(writer, "affiliation", item.affiliation()); - helperToXmlAddAttribute(writer, "nick", item.nick()); - helperToXmlAddAttribute(writer, "role", item.role()); - if (!item.reason().isEmpty()) - helperToXmlAddTextElement(writer, "reason", item.reason()); - writer->writeEndElement(); - } - writer->writeEndElement(); -} - -QXmppDataForm QXmppMucOwnerIq::form() const -{ - return m_form; -} - -void QXmppMucOwnerIq::setForm(const QXmppDataForm &form) -{ - m_form = form; -} - -bool QXmppMucOwnerIq::isMucOwnerIq(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - return (queryElement.namespaceURI() == ns_muc_owner); -} - -void QXmppMucOwnerIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - m_form.parse(queryElement.firstChildElement("x")); -} - -void QXmppMucOwnerIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("query"); - helperToXmlAddAttribute(writer, "xmlns", ns_muc_owner); - m_form.toXml(writer); - writer->writeEndElement(); -} - diff --git a/source/QXmppMucIq.h b/source/QXmppMucIq.h deleted file mode 100644 index 3abcf5b4..00000000 --- a/source/QXmppMucIq.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPMUCIQ_H -#define QXMPPMUCIQ_H - -#include "QXmppDataForm.h" -#include "QXmppIq.h" - -/// \brief The QXmppMucAdminIq class represents a chat room administration IQ -/// as defined by XEP-0045: Multi-User Chat. -/// -/// It is used to get or modify room memberships. -/// -/// \ingroup Stanzas - -class QXmppMucAdminIq : public QXmppIq -{ -public: - class Item - { - public: - QString affiliation() const; - void setAffiliation(const QString &affiliation); - - QString jid() const; - void setJid(const QString &jid); - - QString nick() const; - void setNick(const QString &nick); - - QString reason() const; - void setReason(const QString &reason); - - QString role() const; - void setRole(const QString &role); - - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - - private: - QString m_affiliation; - QString m_jid; - QString m_nick; - QString m_reason; - QString m_role; - }; - - QList<QXmppMucAdminIq::Item> items() const; - void setItems(const QList<QXmppMucAdminIq::Item> &items); - - static bool isMucAdminIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QList<QXmppMucAdminIq::Item> m_items; -}; - -/// \brief The QXmppMucOwnerIq class represents a chat room configuration IQ as -/// defined by XEP-0045: Multi-User Chat. -/// -/// It is used to get or modify room configuration options. -/// -/// \sa QXmppDataForm -/// - -class QXmppMucOwnerIq : public QXmppIq -{ -public: - QXmppDataForm form() const; - void setForm(const QXmppDataForm &form); - - static bool isMucOwnerIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QXmppDataForm m_form; -}; - -#endif diff --git a/source/QXmppMucManager.cpp b/source/QXmppMucManager.cpp deleted file mode 100644 index bf6c3ed4..00000000 --- a/source/QXmppMucManager.cpp +++ /dev/null @@ -1,232 +0,0 @@ -/* - * 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 "QXmppConstants.h" -#include "QXmppMessage.h" -#include "QXmppMucIq.h" -#include "QXmppMucManager.h" -#include "QXmppStream.h" -#include "QXmppUtils.h" - -QXmppMucManager::QXmppMucManager(QXmppStream* stream, QObject *parent) - : QObject(parent), - m_stream(stream) -{ - bool check = connect(stream, SIGNAL(messageReceived(QXmppMessage)), - this, SLOT(messageReceived(QXmppMessage))); - Q_ASSERT(check); - - check = connect(stream, SIGNAL(mucAdminIqReceived(QXmppMucAdminIq)), - this, SLOT(mucAdminIqReceived(QXmppMucAdminIq))); - Q_ASSERT(check); - - check = connect(stream, SIGNAL(mucOwnerIqReceived(QXmppMucOwnerIq)), - this, SLOT(mucOwnerIqReceived(QXmppMucOwnerIq))); - Q_ASSERT(check); - - check = QObject::connect(m_stream, SIGNAL(presenceReceived(QXmppPresence)), - this, SLOT(presenceReceived(QXmppPresence))); - Q_ASSERT(check); -} - -/// Joins the given chat room with the requested nickname. -/// -/// \param roomJid -/// \param nickName -/// -/// \return true if the request was sent, false otherwise -/// - -bool QXmppMucManager::joinRoom(const QString &roomJid, const QString &nickName) -{ - QXmppPresence packet; - packet.setTo(roomJid + "/" + nickName); - packet.setType(QXmppPresence::Available); - QXmppElement x; - x.setTagName("x"); - x.setAttribute("xmlns", ns_muc); - packet.setExtensions(x); - if (m_stream->sendPacket(packet)) - { - m_nickNames[roomJid] = nickName; - return true; - } else { - return false; - } -} - -/// Leaves the given chat room. -/// -/// \param roomJid -/// -/// \return true if the request was sent, false otherwise -/// - -bool QXmppMucManager::leaveRoom(const QString &roomJid) -{ - if (!m_nickNames.contains(roomJid)) - return false; - QString nickName = m_nickNames.take(roomJid); - QXmppPresence packet; - packet.setTo(roomJid + "/" + nickName); - packet.setType(QXmppPresence::Unavailable); - return m_stream->sendPacket(packet); -} - -/// Retrieves the list of participants for the given room. -/// -/// \param roomJid -/// - -QMap<QString, QXmppPresence> QXmppMucManager::roomParticipants(const QString& roomJid) const -{ - return m_participants.value(roomJid); -} - -/// Request the configuration form for the given room. -/// -/// \param roomJid -/// -/// \return true if the request was sent, false otherwise -/// -/// \sa roomConfigurationReceived() -/// - -bool QXmppMucManager::requestRoomConfiguration(const QString &roomJid) -{ - QXmppMucOwnerIq iq; - iq.setTo(roomJid); - return m_stream->sendPacket(iq); -} - -/// Send the configuration form for the given room. -/// -/// \param roomJid -/// \param form -/// -/// \return true if the request was sent, false otherwise -/// - -bool QXmppMucManager::setRoomConfiguration(const QString &roomJid, const QXmppDataForm &form) -{ - QXmppMucOwnerIq iqPacket; - iqPacket.setType(QXmppIq::Set); - iqPacket.setTo(roomJid); - iqPacket.setForm(form); - return m_stream->sendPacket(iqPacket); -} - -/// Invite a user to a chat room. -/// -/// \param roomJid -/// \param jid -/// \param reason -/// -/// \return true if the message was sent, false otherwise -/// - -bool QXmppMucManager::sendInvitation(const QString &roomJid, const QString &jid, const QString &reason) -{ - QXmppElement x; - x.setTagName("x"); - x.setAttribute("xmlns", ns_conference); - x.setAttribute("jid", roomJid); - x.setAttribute("reason", reason); - - QXmppMessage message; - message.setTo(jid); - message.setType(QXmppMessage::Normal); - message.setExtensions(x); - return m_stream->sendPacket(message); -} - -/// Send a message to a chat room. -/// -/// \param roomJid -/// \param text -/// -/// \return true if the message was sent, false otherwise -/// - -bool QXmppMucManager::sendMessage(const QString &roomJid, const QString &text) -{ - if (!m_nickNames.contains(roomJid)) - { - qWarning("Cannot send message to unknown chat room"); - return false; - } - QXmppMessage msg; - msg.setBody(text); - msg.setFrom(roomJid + "/" + m_nickNames[roomJid]); - msg.setTo(roomJid); - msg.setType(QXmppMessage::GroupChat); - return m_stream->sendPacket(msg); -} - -void QXmppMucManager::messageReceived(const QXmppMessage &msg) -{ - if (msg.type() != QXmppMessage::Normal) - return; - - // process room invitations - foreach (const QXmppElement &extension, msg.extensions()) - { - if (extension.tagName() == "x" && extension.attribute("xmlns") == ns_conference) - { - const QString roomJid = extension.attribute("jid"); - if (!roomJid.isEmpty() && !m_nickNames.contains(roomJid)) - emit invitationReceived(roomJid, msg.from(), extension.attribute("reason")); - break; - } - } -} - -void QXmppMucManager::mucAdminIqReceived(const QXmppMucAdminIq &iq) -{ - Q_UNUSED(iq); -} - -void QXmppMucManager::mucOwnerIqReceived(const QXmppMucOwnerIq &iq) -{ - if (iq.type() == QXmppIq::Result && !iq.form().isNull()) - emit roomConfigurationReceived(iq.from(), iq.form()); -} - -void QXmppMucManager::presenceReceived(const QXmppPresence &presence) -{ - QString jid = presence.from(); - QString bareJid = jidToBareJid(jid); - QString resource = jidToResource(jid); - if (!m_nickNames.contains(bareJid)) - return; - - if (presence.type() == QXmppPresence::Available) - m_participants[bareJid][resource] = presence; - else if (presence.type() == QXmppPresence::Unavailable) - m_participants[bareJid].remove(resource); - else - return; - - emit roomParticipantChanged(bareJid, resource); -} - diff --git a/source/QXmppMucManager.h b/source/QXmppMucManager.h deleted file mode 100644 index 8e181789..00000000 --- a/source/QXmppMucManager.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPMUCMANAGER_H -#define QXMPPMUCMANAGER_H - -#include <QObject> -#include <QMap> - -#include "QXmppPresence.h" - -class QXmppDataForm; -class QXmppMessage; -class QXmppMucAdminIq; -class QXmppMucOwnerIq; -class QXmppStream; - -/// \brief The QXmppMucManager class makes it possible to interact with -/// multi-user chat rooms as defined by XEP-0045: Multi-User Chat. -/// -/// \ingroup Managers - -class QXmppMucManager : public QObject -{ - Q_OBJECT - -public: - QXmppMucManager(QXmppStream* stream, QObject *parent = 0); - - bool joinRoom(const QString &roomJid, const QString &nickName); - bool leaveRoom(const QString &roomJid); - - bool requestRoomConfiguration(const QString &roomJid); - bool setRoomConfiguration(const QString &roomJid, const QXmppDataForm &form); - - bool sendInvitation(const QString &roomJid, const QString &jid, const QString &reason); - bool sendMessage(const QString &roomJid, const QString &text); - - QMap<QString, QXmppPresence> roomParticipants(const QString& bareJid) const; - -signals: - /// This signal is emitted when an invitation to a chat room is received. - void invitationReceived(const QString &roomJid, const QString &inviter, const QString &reason); - - /// This signal is emitted when the configuration form for a chat room is received. - void roomConfigurationReceived(const QString &roomJid, const QXmppDataForm &configuration); - - void roomParticipantChanged(const QString &roomJid, const QString &nickName); - -private slots: - void messageReceived(const QXmppMessage &message); - void mucAdminIqReceived(const QXmppMucAdminIq &iq); - void mucOwnerIqReceived(const QXmppMucOwnerIq &iq); - void presenceReceived(const QXmppPresence &presence); - -private: - QXmppStream *m_stream; - QMap<QString, QString> m_nickNames; - QMap<QString, QMap<QString, QXmppPresence> > m_participants; -}; - -#endif diff --git a/source/QXmppNonSASLAuth.cpp b/source/QXmppNonSASLAuth.cpp deleted file mode 100644 index c17a1ba6..00000000 --- a/source/QXmppNonSASLAuth.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppNonSASLAuth.h" -#include "QXmppUtils.h" -#include <QCryptographicHash> -#include <QXmlStreamWriter> - -QXmppNonSASLAuthTypesRequestIq::QXmppNonSASLAuthTypesRequestIq() : QXmppIq(QXmppIq::Get) -{ - -} - -void QXmppNonSASLAuthTypesRequestIq::setUsername( const QString &username ) -{ - m_username = username; -} - -void QXmppNonSASLAuthTypesRequestIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("query"); - writer->writeAttribute( "xmlns","jabber:iq:auth"); - writer->writeTextElement("username", m_username ); - writer->writeEndElement(); -} - -QXmppNonSASLAuthIq::QXmppNonSASLAuthIq() : QXmppIq(QXmppIq::Set), m_useplaintext(false) -{ - -} - -void QXmppNonSASLAuthIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("query"); - writer->writeAttribute( "xmlns","jabber:iq:auth"); - writer->writeTextElement("username", m_username ); - if ( m_useplaintext ) - writer->writeTextElement("password", m_password ); - else - {//SHA1(concat(sid, password)). - QByteArray textSid = m_sid.toUtf8(); - QByteArray encodedPassword = m_password.toUtf8(); - QByteArray digest = QCryptographicHash::hash(textSid + encodedPassword, QCryptographicHash::Sha1 ).toHex(); - writer->writeTextElement("digest", digest ); - } - writer->writeTextElement("resource", m_resource ); - writer->writeEndElement(); -} - -void QXmppNonSASLAuthIq::setUsername( const QString &username ) -{ - m_username = username; -} - -void QXmppNonSASLAuthIq::setPassword( const QString &password ) -{ - m_password = password; -} - -void QXmppNonSASLAuthIq::setResource( const QString &resource ) -{ - m_resource = resource; -} - -void QXmppNonSASLAuthIq::setStreamId( const QString &sid ) -{ - m_sid = sid; -} - -void QXmppNonSASLAuthIq::setUsePlainText( bool use ) -{ - m_useplaintext = use; -} diff --git a/source/QXmppNonSASLAuth.h b/source/QXmppNonSASLAuth.h deleted file mode 100644 index 956814fa..00000000 --- a/source/QXmppNonSASLAuth.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - -#ifndef QXmppNonSASLAuth_H -#define QXmppNonSASLAuth_H - -#include "QXmppIq.h" - -class QXmppNonSASLAuthTypesRequestIq : public QXmppIq -{ -public: - QXmppNonSASLAuthTypesRequestIq(); - void setUsername( const QString &username ); - virtual void toXmlElementFromChild(QXmlStreamWriter *writer) const; -private: - QString m_username; -}; - -class QXmppNonSASLAuthIq : public QXmppIq -{ -public: - QXmppNonSASLAuthIq(); - virtual void toXmlElementFromChild(QXmlStreamWriter *writer) const; - void setUsername( const QString &username ); - void setPassword( const QString &password ); - void setResource( const QString &resource ); - void setStreamId( const QString &sid ); - void setUsePlainText( bool useplaintext ); - -private: - QString m_username; - QString m_password; - QString m_resource; - QString m_sid; - bool m_useplaintext; -}; - -#endif // QXmppNonSASLAuth_H diff --git a/source/QXmppPacket.cpp b/source/QXmppPacket.cpp deleted file mode 100644 index 63c29445..00000000 --- a/source/QXmppPacket.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppPacket.h" - -QXmppPacket::QXmppPacket() -{ -} - -QXmppPacket::~QXmppPacket() -{ -} - diff --git a/source/QXmppPacket.h b/source/QXmppPacket.h deleted file mode 100644 index be47ebb2..00000000 --- a/source/QXmppPacket.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPPACKET_H -#define QXMPPPACKET_H - -#include <QByteArray> - -// forward declarations of QXmlStream* classes will not work on Mac, we need to -// include the whole header. -// See http://lists.trolltech.com/qt-interest/2008-07/thread00798-0.html -// for an explanation. -#include <QXmlStreamWriter> - -class QDomElement; - -class QXmppPacket -{ -public: - QXmppPacket(); - virtual ~QXmppPacket(); - - virtual void parse(const QDomElement &element) = 0; - virtual void toXml( QXmlStreamWriter *writer ) const = 0; -}; - -#endif // QXMPPPACKET_H diff --git a/source/QXmppPingIq.cpp b/source/QXmppPingIq.cpp deleted file mode 100644 index 9e83912b..00000000 --- a/source/QXmppPingIq.cpp +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 "QXmppConstants.h" -#include "QXmppPingIq.h" -#include "QXmppUtils.h" - -#include <QDomElement> - -QXmppPingIq::QXmppPingIq() : QXmppIq(QXmppIq::Get) -{ -} - -bool QXmppPingIq::isPingIq(const QDomElement &element) -{ - QDomElement pingElement = element.firstChildElement("ping"); - return (element.attribute("type") == "get" && - pingElement.namespaceURI() == ns_ping); -} - -void QXmppPingIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("ping"); - helperToXmlAddAttribute(writer, "xmlns", ns_ping); - writer->writeEndElement(); -} - diff --git a/source/QXmppPingIq.h b/source/QXmppPingIq.h deleted file mode 100644 index 3e2ba4ca..00000000 --- a/source/QXmppPingIq.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPPINGIQ_H -#define QXMPPPINGIQ_H - -#include "QXmppIq.h" - -class QXmlStreamWriter; -class QDomElement; - -class QXmppPingIq : public QXmppIq -{ -public: - QXmppPingIq(); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - static bool isPingIq(const QDomElement &element); -}; - -#endif diff --git a/source/QXmppPresence.cpp b/source/QXmppPresence.cpp deleted file mode 100644 index 37fa494e..00000000 --- a/source/QXmppPresence.cpp +++ /dev/null @@ -1,358 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppPresence.h" -#include "QXmppUtils.h" -#include <QtDebug> -#include <QDomElement> -#include <QXmlStreamWriter> - -QXmppPresence::QXmppPresence(QXmppPresence::Type type, - const QXmppPresence::Status& status) - : QXmppStanza(), m_type(type), m_status(status) -{ - -} - -QXmppPresence::~QXmppPresence() -{ - -} - -QXmppPresence::Type QXmppPresence::type() const -{ - return m_type; -} - -void QXmppPresence::setType(QXmppPresence::Type type) -{ - m_type = type; -} - -const QXmppPresence::Status& QXmppPresence::status() const -{ - return m_status; -} - -QXmppPresence::Status& QXmppPresence::status() -{ - return m_status; -} - -void QXmppPresence::setStatus(const QXmppPresence::Status& status) -{ - m_status = status; -} - -void QXmppPresence::parse(const QDomElement &element) -{ - QXmppStanza::parse(element); - - setTypeFromStr(element.attribute("type")); - m_status.parse(element); - - QDomElement xElement = element.firstChildElement("x"); - if(!xElement.isNull()) - setExtensions(QXmppElement(xElement)); -} - -void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const -{ - xmlWriter->writeStartElement("presence"); - helperToXmlAddAttribute(xmlWriter,"xml:lang", lang()); - helperToXmlAddAttribute(xmlWriter,"id", id()); - helperToXmlAddAttribute(xmlWriter,"to", to()); - helperToXmlAddAttribute(xmlWriter,"from", from()); - helperToXmlAddAttribute(xmlWriter,"type", getTypeStr()); - m_status.toXml(xmlWriter); - - error().toXml(xmlWriter); - foreach (const QXmppElement &extension, extensions()) - extension.toXml(xmlWriter); - - xmlWriter->writeEndElement(); -} - -QString QXmppPresence::getTypeStr() const -{ - QString text; - switch(m_type) - { - case QXmppPresence::Error: - text = "error"; - break; - case QXmppPresence::Available: - // no type-attribute if available - text = ""; - break; - case QXmppPresence::Unavailable: - text = "unavailable"; - break; - case QXmppPresence::Subscribe: - text = "subscribe"; - break; - case QXmppPresence::Subscribed: - text = "subscribed"; - break; - case QXmppPresence::Unsubscribe: - text = "unsubscribe"; - break; - case QXmppPresence::Unsubscribed: - text = "unsubscribed"; - break; - case QXmppPresence::Probe: - text = "probe"; - break; - default: - qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type); - break; - } - return text; -} - -void QXmppPresence::setTypeFromStr(const QString& str) -{ - QXmppPresence::Type type; - if(str == "error") - { - type = QXmppPresence::Error; - setType(type); - return; - } - else if(str == "unavailable") - { - type = QXmppPresence::Unavailable; - setType(type); - return; - } - else if(str == "subscribe") - { - type = QXmppPresence::Subscribe; - setType(type); - return; - } - else if(str == "subscribed") - { - type = QXmppPresence::Subscribed; - setType(type); - return; - } - else if(str == "unsubscribe") - { - type = QXmppPresence::Unsubscribe; - setType(type); - return; - } - else if(str == "unsubscribed") - { - type = QXmppPresence::Unsubscribed; - setType(type); - return; - } - else if(str == "probe") - { - type = QXmppPresence::Probe; - setType(type); - return; - } - else if(str == "") - { - type = QXmppPresence::Available; - setType(type); - return; - } - else - { - type = static_cast<QXmppPresence::Type>(-1); - qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s", - qPrintable(str)); - setType(type); - return; - } -} - -QXmppPresence::Status::Status(QXmppPresence::Status::Type type, - const QString statusText, int priority) : - m_type(type), - m_statusText(statusText), m_priority(priority) -{ -} - -QXmppPresence::Status::Type QXmppPresence::Status::type() const -{ - return m_type; -} - -void QXmppPresence::Status::setType(QXmppPresence::Status::Type type) -{ - m_type = type; -} - -void QXmppPresence::Status::setTypeFromStr(const QString& str) -{ - // there is no keyword for Offline - - QXmppPresence::Status::Type type; - if(str == "") // not type-attribute means online - { - type = QXmppPresence::Status::Online; - setType(type); - return; - } - else if(str == "away") - { - type = QXmppPresence::Status::Away; - setType(type); - return; - } - else if(str == "xa") - { - type = QXmppPresence::Status::XA; - setType(type); - return; - } - else if(str == "dnd") - { - type = QXmppPresence::Status::DND; - setType(type); - return; - } - else if(str == "chat") - { - type = QXmppPresence::Status::Chat; - setType(type); - return; - } - else - { - type = static_cast<QXmppPresence::Status::Type>(-1); - qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s", - qPrintable(str)); - setType(type); - } -} - -QString QXmppPresence::Status::getTypeStr() const -{ - QString text; - switch(m_type) - { - case QXmppPresence::Status::Online: - // no type-attribute if available - text = ""; - break; - case QXmppPresence::Status::Offline: - text = ""; - break; - case QXmppPresence::Status::Away: - text = "away"; - break; - case QXmppPresence::Status::XA: - text = "xa"; - break; - case QXmppPresence::Status::DND: - text = "dnd"; - break; - case QXmppPresence::Status::Chat: - text = "chat"; - break; - default: - qWarning("QXmppPresence::Status::getTypeStr() invalid type %d", - (int)m_type); - break; - } - return text; -} - -QString QXmppPresence::Status::statusText() const -{ - return m_statusText; -} - -void QXmppPresence::Status::setStatusText(const QString& str) -{ - m_statusText = str; -} - -int QXmppPresence::Status::priority() const -{ - return m_priority; -} - -void QXmppPresence::Status::setPriority(int priority) -{ - m_priority = priority; -} - -void QXmppPresence::Status::parse(const QDomElement &element) -{ - setTypeFromStr(element.firstChildElement("show").text()); - m_statusText = element.firstChildElement("status").text(); - m_priority = element.firstChildElement("priority").text().toInt(); -} - -void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const -{ - const QString show = getTypeStr(); - if (!show.isEmpty()) - helperToXmlAddTextElement(xmlWriter, "show", getTypeStr()); - if (!m_statusText.isEmpty()) - helperToXmlAddTextElement(xmlWriter, "status", m_statusText); - if (m_priority != 0) - helperToXmlAddNumberElement(xmlWriter, "priority", m_priority); -} - -/// \cond - -QXmppPresence::Type QXmppPresence::getType() const -{ - return m_type; -} - -const QXmppPresence::Status& QXmppPresence::getStatus() const -{ - return m_status; -} - -QXmppPresence::Status& QXmppPresence::getStatus() -{ - return m_status; -} - -QXmppPresence::Status::Type QXmppPresence::Status::getType() const -{ - return m_type; -} - -QString QXmppPresence::Status::getStatusText() const -{ - return m_statusText; -} - -int QXmppPresence::Status::getPriority() const -{ - return m_priority; -} - -/// \endcond diff --git a/source/QXmppPresence.h b/source/QXmppPresence.h deleted file mode 100644 index 56272c1a..00000000 --- a/source/QXmppPresence.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPPRESENCE_H -#define QXMPPPRESENCE_H - -#include "QXmppStanza.h" - -/// \brief The QXmppPresence class represents an XMPP presence stanza. -/// -/// \ingroup Stanzas -class QXmppPresence : public QXmppStanza -{ -public: - enum Type - { - Error = 0, - Available, - Unavailable, - Subscribe, - Subscribed, - Unsubscribe, - Unsubscribed, - Probe - }; - - class Status - { - public: - enum Type - { - Offline = 0, - Online, - Away, - XA, - DND, - Chat, - Invisible - }; - - Status(QXmppPresence::Status::Type type = QXmppPresence::Status::Online, - const QString statusText = "", int priority = 0); - - QXmppPresence::Status::Type type() const; - void setType(QXmppPresence::Status::Type); - - QString statusText() const; - void setStatusText(const QString&); - - int priority() const; - void setPriority(int); - - /// \cond - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - - // deprecated accessors, use the form without "get" instead - int Q_DECL_DEPRECATED getPriority() const; - QString Q_DECL_DEPRECATED getStatusText() const; - QXmppPresence::Status::Type Q_DECL_DEPRECATED getType() const; - /// \endcond - - private: - QString getTypeStr() const; - void setTypeFromStr(const QString&); - - QXmppPresence::Status::Type m_type; - QString m_statusText; - int m_priority; - }; - - QXmppPresence(QXmppPresence::Type type = QXmppPresence::Available, - const QXmppPresence::Status& status = QXmppPresence::Status()); - ~QXmppPresence(); - - QXmppPresence::Type type() const; - void setType(QXmppPresence::Type); - - QXmppPresence::Status& status(); - const QXmppPresence::Status& status() const; - void setStatus(const QXmppPresence::Status&); - - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - - // deprecated accessors, use the form without "get" instead - /// \cond - QXmppPresence::Type Q_DECL_DEPRECATED getType() const; - QXmppPresence::Status Q_DECL_DEPRECATED & getStatus(); - const QXmppPresence::Status Q_DECL_DEPRECATED & getStatus() const; - /// \endcond - -private: - QString getTypeStr() const; - void setTypeFromStr(const QString&); - - Type m_type; - QXmppPresence::Status m_status; -}; - -#endif // QXMPPPRESENCE_H diff --git a/source/QXmppReconnectionManager.cpp b/source/QXmppReconnectionManager.cpp deleted file mode 100644 index 615d47a5..00000000 --- a/source/QXmppReconnectionManager.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppReconnectionManager.h" -#include "QXmppClient.h" -#include "QXmppLogger.h" -#include "QXmppUtils.h" - -QXmppReconnectionManager::QXmppReconnectionManager(QXmppClient* client) : - QObject(client), - m_receivedConflict(false), - m_reconnectionTries(0), - m_timer(this), - m_client(client) -{ - m_timer.setSingleShot(true); - bool check = connect(&m_timer, SIGNAL(timeout()), SLOT(reconnect())); - Q_ASSERT(check); - Q_UNUSED(check); -} - -void QXmppReconnectionManager::connected() -{ - m_receivedConflict = false; - m_reconnectionTries = 0; -} - -void QXmppReconnectionManager::error(QXmppClient::Error error) -{ - if(m_client && error == QXmppClient::XmppStreamError) - { - // if we receive a resource conflict, inhibit reconnection - if(m_client->xmppStreamError() == QXmppStanza::Error::Conflict) - m_receivedConflict = true; - } - else if(m_client && error == QXmppClient::SocketError && !m_receivedConflict) - { - int time = getNextReconnectingInTime(); - - // time is in sec - m_timer.start(time*1000); - emit reconnectingIn(time); - } - else if (m_client && error == QXmppClient::KeepAliveError) - { - // if we got a keepalive error, reconnect in one second - m_timer.start(1000); - } -} - -int QXmppReconnectionManager::getNextReconnectingInTime() -{ - int reconnectingIn; - if(m_reconnectionTries < 5) - reconnectingIn = 10; - else if(m_reconnectionTries < 10) - reconnectingIn = 20; - else if(m_reconnectionTries < 15) - reconnectingIn = 40; - else - reconnectingIn = 60; - - return reconnectingIn; -} - -void QXmppReconnectionManager::reconnect() -{ - if(m_client) - { - emit reconnectingNow(); - m_client->connectToServer(m_client->configuration(), m_client->clientPresence()); - } -} - -void QXmppReconnectionManager::cancelReconnection() -{ - m_timer.stop(); - m_receivedConflict = false; - m_reconnectionTries = 0; -} diff --git a/source/QXmppReconnectionManager.h b/source/QXmppReconnectionManager.h deleted file mode 100644 index 7240a7b9..00000000 --- a/source/QXmppReconnectionManager.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPRECONNECTIONMANAGER_H -#define QXMPPRECONNECTIONMANAGER_H - -#include <QObject> -#include <QTimer> -#include "QXmppClient.h" - -class QXmppReconnectionManager : public QObject -{ - Q_OBJECT - -public: - QXmppReconnectionManager(QXmppClient* client); - -signals: - void reconnectingIn(int); - void reconnectingNow(); - -public slots: - void cancelReconnection(); - -private slots: - void connected(); - void error(QXmppClient::Error); - void reconnect(); - -private: - int getNextReconnectingInTime(); - bool m_receivedConflict; - int m_reconnectionTries; - QTimer m_timer; - - // reference to to client object (no ownership) - QXmppClient* m_client; -}; - -#endif // QXMPPRECONNECTIONMANAGER_H diff --git a/source/QXmppRemoteMethod.cpp b/source/QXmppRemoteMethod.cpp deleted file mode 100644 index b92b2bdc..00000000 --- a/source/QXmppRemoteMethod.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Ian Reinhard Geiser - * - * 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 "QXmppRemoteMethod.h" -#include "QXmppClient.h" -#include "QXmppUtils.h" -#include "QXmppConfiguration.h" - -#include <QEventLoop> -#include <QTimer> -#include <qdebug.h> - -QXmppRemoteMethod::QXmppRemoteMethod(const QString &jid, const QString &method, const QVariantList &args, QXmppClient *client) : - QObject(client), m_client(client) -{ - m_payload.setTo( jid ); - m_payload.setFrom( client->configuration().jid() ); - m_payload.setMethod( method ); - m_payload.setArguments( args ); -} - -QXmppRemoteMethodResult QXmppRemoteMethod::call( ) -{ - QEventLoop loop(this); - connect( this, SIGNAL(callDone()), &loop, SLOT(quit())); - QTimer::singleShot(30000,&loop, SLOT(quit())); // Timeout incase the other end hangs... - - m_client->sendPacket( m_payload ); - - loop.exec( QEventLoop::ExcludeUserInputEvents | QEventLoop::WaitForMoreEvents ); - return m_result; -} - -void QXmppRemoteMethod::gotError( const QXmppRpcErrorIq &iq ) -{ - if ( iq.id() == m_payload.id() ) - { - m_result.hasError = true; - m_result.errorMessage = iq.error().text(); - m_result.code = iq.error().type(); - emit callDone(); - } -} - -void QXmppRemoteMethod::gotResult( const QXmppRpcResponseIq &iq ) -{ - if ( iq.id() == m_payload.id() ) - { - m_result.hasError = false; - // FIXME: we don't handle multiple responses - m_result.result = iq.values().first(); - emit callDone(); - } -} diff --git a/source/QXmppRemoteMethod.h b/source/QXmppRemoteMethod.h deleted file mode 100644 index aac8663c..00000000 --- a/source/QXmppRemoteMethod.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Ian Reinhard Geiser - * - * 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. - * - */ - -#ifndef QXMPPREMOTEMETHOD_H -#define QXMPPREMOTEMETHOD_H - -#include <QObject> -#include <QVariant> - -#include "QXmppRpcIq.h" - -class QXmppClient; -class QXmppStream; - -struct QXmppRemoteMethodResult { - QXmppRemoteMethodResult() : hasError(false), code(0) { } - bool hasError; - int code; - QString errorMessage; - QVariant result; -}; - -class QXmppRemoteMethod : public QObject -{ - Q_OBJECT -public: - QXmppRemoteMethod(const QString &jid, const QString &method, const QVariantList &args, QXmppClient *client); - QXmppRemoteMethodResult call( ); - -private slots: - void gotError( const QXmppRpcErrorIq &iq ); - void gotResult( const QXmppRpcResponseIq &iq ); - -signals: - void callDone(); - -private: - QXmppRpcInvokeIq m_payload; - QXmppClient *m_client; - QXmppRemoteMethodResult m_result; - -}; - -#endif // QXMPPREMOTEMETHOD_H diff --git a/source/QXmppRoster.h b/source/QXmppRoster.h deleted file mode 100644 index a6d9d388..00000000 --- a/source/QXmppRoster.h +++ /dev/null @@ -1,5 +0,0 @@ -#warning "QXmppRoster.h is deprecated, use QXmppRosterManager instead" - -#include "QXmppRosterManager.h" - -typedef QXmppRosterManager QXmppRoster; diff --git a/source/QXmppRosterIq.cpp b/source/QXmppRosterIq.cpp deleted file mode 100644 index 6456b4e0..00000000 --- a/source/QXmppRosterIq.cpp +++ /dev/null @@ -1,278 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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 <QXmlStreamWriter> - -#include "QXmppRosterIq.h" -#include "QXmppConstants.h" -#include "QXmppUtils.h" - -void QXmppRosterIq::addItem(const Item& item) -{ - m_items.append(item); -} - -QList<QXmppRosterIq::Item> QXmppRosterIq::items() const -{ - return m_items; -} - -bool QXmppRosterIq::isRosterIq(const QDomElement &element) -{ - return (element.firstChildElement("query").namespaceURI() == ns_roster); -} - -void QXmppRosterIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement itemElement = element. - firstChildElement("query"). - firstChildElement("item"); - while(!itemElement.isNull()) - { - QXmppRosterIq::Item item; - item.parse(itemElement); - m_items.append(item); - itemElement = itemElement.nextSiblingElement(); - } -} - -void QXmppRosterIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("query"); - writer->writeAttribute( "xmlns", ns_roster); - - for(int i = 0; i < m_items.count(); ++i) - m_items.at(i).toXml(writer); - writer->writeEndElement(); -} - -/// Returns the bareJid of the roster entry. -/// -/// \return bareJid as a QString -/// - -QString QXmppRosterIq::Item::bareJid() const -{ - return m_bareJid; -} - -/// Sets the bareJid of the roster entry. -/// -/// \param bareJid as a QString -/// - -void QXmppRosterIq::Item::setBareJid(const QString &bareJid) -{ - m_bareJid = bareJid; -} - -/// Returns the groups of the roster entry. -/// -/// \return QSet<QString> list of all the groups -/// - -QSet<QString> QXmppRosterIq::Item::groups() const -{ - return m_groups; -} - -/// Sets the groups of the roster entry. -/// -/// \param groups list of all the groups as a QSet<QString> -/// - -void QXmppRosterIq::Item::setGroups(const QSet<QString>& groups) -{ - m_groups = groups; -} - -/// Returns the name of the roster entry. -/// -/// \return name as a QString -/// - -QString QXmppRosterIq::Item::name() const -{ - return m_name; -} - -/// Sets the name of the roster entry. -/// -/// \param name as a QString -/// - -void QXmppRosterIq::Item::setName(const QString &name) -{ - m_name = name; -} - -/// Returns the subscription status of the roster entry. It is the "ask" -/// attribute in the Roster IQ stanza. Its value can be "subscribe" or "unsubscribe" -/// or empty. -/// -/// \return subscription status as a QString -/// -/// - -QString QXmppRosterIq::Item::subscriptionStatus() const -{ - return m_subscriptionStatus; -} - -/// Sets the subscription status of the roster entry. It is the "ask" -/// attribute in the Roster IQ stanza. Its value can be "subscribe" or "unsubscribe" -/// or empty. -/// -/// \param status as a QString -/// - -void QXmppRosterIq::Item::setSubscriptionStatus(const QString &status) -{ - m_subscriptionStatus = status; -} - -/// Returns the subscription type of the roster entry. -/// - -QXmppRosterIq::Item::SubscriptionType - QXmppRosterIq::Item::subscriptionType() const -{ - return m_type; -} - -/// Sets the subscription type of the roster entry. -/// -/// \param type -/// - -void QXmppRosterIq::Item::setSubscriptionType(SubscriptionType type) -{ - m_type = type; -} - -QString QXmppRosterIq::Item::getSubscriptionTypeStr() const -{ - switch(m_type) - { - case NotSet: - return ""; - case None: - return "none"; - case Both: - return "both"; - case From: - return "from"; - case To: - return "to"; - case Remove: - return "remove"; - default: - { - qWarning("QXmppRosterIq::Item::getTypeStr(): invalid type"); - return ""; - } - } -} - -void QXmppRosterIq::Item::setSubscriptionTypeFromStr(const QString& type) -{ - if(type == "") - setSubscriptionType(NotSet); - else if(type == "none") - setSubscriptionType(None); - else if(type == "both") - setSubscriptionType(Both); - else if(type == "from") - setSubscriptionType(From); - else if(type == "to") - setSubscriptionType(To); - else if(type == "remove") - setSubscriptionType(Remove); - else - qWarning("QXmppRosterIq::Item::setTypeFromStr(): invalid type"); -} - -void QXmppRosterIq::Item::parse(const QDomElement &element) -{ - m_name = element.attribute("name"); - m_bareJid = element.attribute("jid"); - setSubscriptionTypeFromStr(element.attribute("subscription")); - setSubscriptionStatus(element.attribute("ask")); - - QDomElement groupElement = element.firstChildElement("group"); - while(!groupElement.isNull()) - { - m_groups << groupElement.text(); - groupElement = groupElement.nextSiblingElement("group"); - } -} - -void QXmppRosterIq::Item::toXml(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("item"); - helperToXmlAddAttribute(writer,"jid", m_bareJid); - helperToXmlAddAttribute(writer,"name", m_name); - helperToXmlAddAttribute(writer,"subscription", getSubscriptionTypeStr()); - helperToXmlAddAttribute(writer, "ask", subscriptionStatus()); - - QSet<QString>::const_iterator i = m_groups.constBegin(); - while(i != m_groups.constEnd()) - { - helperToXmlAddTextElement(writer,"group", *i); - ++i; - } - writer->writeEndElement(); -} - -QList<QXmppRosterIq::Item> QXmppRosterIq::getItems() const -{ - return m_items; -} - -QXmppRosterIq::Item::SubscriptionType - QXmppRosterIq::Item::getSubscriptionType() const -{ - return m_type; -} - -QString QXmppRosterIq::Item::getName() const -{ - return m_name; -} - -QString QXmppRosterIq::Item::getSubscriptionStatus() const -{ - return m_subscriptionStatus; -} - -QString QXmppRosterIq::Item::getBareJid() const -{ - return m_bareJid; -} - -QSet<QString> QXmppRosterIq::Item::getGroups() const -{ - return m_groups; -} diff --git a/source/QXmppRosterIq.h b/source/QXmppRosterIq.h deleted file mode 100644 index 2057bf72..00000000 --- a/source/QXmppRosterIq.h +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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. - * - */ - - -#ifndef QXMPPROSTERIQ_H -#define QXMPPROSTERIQ_H - -#include "QXmppIq.h" -#include <QList> -#include <QSet> - -/// \brief The QXmppRosterIq class represents a roster IQ. -/// -/// \ingroup Stanzas - -class QXmppRosterIq : public QXmppIq -{ -public: - - /// \brief The QXmppRosterIq::Item class represents a roster entry. - class Item - { - public: - /// An enumeration for type of subscription with the bareJid in the roster. - enum SubscriptionType - { - NotSet = 0, - None, ///< the user does not have a subscription to the - ///< contact's presence information, and the contact does - ///< not have a subscription to the user's presence information - Both, ///< both the user and the contact have subscriptions to each - ///< other's presence information - From, ///< the contact has a subscription to the user's presence information, - ///< but the user does not have a subscription to the contact's presence information - To, ///< the user has a subscription to the contact's presence information, - ///< but the contact does not have a subscription to the user's presence information - Remove ///< to delete a roster item - }; - - QString bareJid() const; - QSet<QString> groups() const; - QString name() const; - QString subscriptionStatus() const; - SubscriptionType subscriptionType() const; - - void setBareJid(const QString&); - void setGroups(const QSet<QString>&); - void setName(const QString&); - void setSubscriptionStatus(const QString&); - void setSubscriptionType(SubscriptionType); - - /// \cond - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - - // deprecated accessors, use the form without "get" instead - SubscriptionType Q_DECL_DEPRECATED getSubscriptionType() const; - QString Q_DECL_DEPRECATED getName() const; - QString Q_DECL_DEPRECATED getSubscriptionStatus() const; - QString Q_DECL_DEPRECATED getBareJid() const; - QSet<QString> Q_DECL_DEPRECATED getGroups() const; - /// \endcond - - private: - QString getSubscriptionTypeStr() const; - void setSubscriptionTypeFromStr(const QString&); - - QString m_bareJid; - SubscriptionType m_type; - QString m_name; - // can be subscribe/unsubscribe (attribute "ask") - QString m_subscriptionStatus; - QSet<QString> m_groups; - }; - - void addItem(const Item&); - QList<Item> items() const; - - static bool isRosterIq(const QDomElement &element); - - // deprecated accessors, use the form without "get" instead - /// \cond - QList<Item> Q_DECL_DEPRECATED getItems() const; - /// \endcond - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QList<Item> m_items; -}; - -#endif // QXMPPROSTERIQ_H diff --git a/source/QXmppRosterManager.cpp b/source/QXmppRosterManager.cpp deleted file mode 100644 index 0da3475b..00000000 --- a/source/QXmppRosterManager.cpp +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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 "QXmppRosterManager.h" -#include "QXmppUtils.h" -#include "QXmppRosterIq.h" -#include "QXmppPresence.h" -#include "QXmppStream.h" - -QXmppRosterManager::QXmppRosterManager(QXmppStream* stream, QObject *parent) - : QObject(parent), - m_stream(stream), - m_isRosterReceived(false) -{ - bool check = QObject::connect(m_stream, SIGNAL(xmppConnected()), - this, SLOT(connected())); - Q_ASSERT(check); - - check = QObject::connect(m_stream, SIGNAL(disconnected()), - this, SLOT(disconnected())); - Q_ASSERT(check); - - check = QObject::connect(m_stream, SIGNAL(presenceReceived(const QXmppPresence&)), - this, SLOT(presenceReceived(const QXmppPresence&))); - Q_ASSERT(check); - - check = QObject::connect(m_stream, SIGNAL(rosterIqReceived(const QXmppRosterIq&)), - this, SLOT(rosterIqReceived(const QXmppRosterIq&))); - Q_ASSERT(check); -} - -QXmppRosterManager::~QXmppRosterManager() -{ - -} - -/// Upon XMPP connection, request the roster. -/// -void QXmppRosterManager::connected() -{ - QXmppRosterIq roster; - roster.setType(QXmppIq::Get); - roster.setFrom(m_stream->configuration().jid()); - m_rosterReqId = roster.id(); - m_stream->sendPacket(roster); -} - -void QXmppRosterManager::disconnected() -{ - m_entries = QMap<QString, QXmppRosterIq::Item>(); - m_presences = QMap<QString, QMap<QString, QXmppPresence> >(); - m_isRosterReceived = false; -} - -void QXmppRosterManager::presenceReceived(const QXmppPresence& presence) -{ - QString jid = presence.from(); - QString bareJid = jidToBareJid(jid); - QString resource = jidToResource(jid); - - if (bareJid.isEmpty()) - return; - - switch(presence.type()) - { - case QXmppPresence::Available: - m_presences[bareJid][resource] = presence; - emit presenceChanged(bareJid, resource); - break; - case QXmppPresence::Unavailable: - m_presences[bareJid].remove(resource); - emit presenceChanged(bareJid, resource); - break; - case QXmppPresence::Subscribe: - if (m_stream->configuration().autoAcceptSubscriptions()) - m_stream->acceptSubscriptionRequest(jid); - break; - default: - break; - } -} - -void QXmppRosterManager::rosterIqReceived(const QXmppRosterIq& rosterIq) -{ - bool isInitial = (m_rosterReqId == rosterIq.id()); - - switch(rosterIq.type()) - { - case QXmppIq::Set: - { - // send result iq - QXmppIq returnIq(QXmppIq::Result); - returnIq.setId(rosterIq.id()); - m_stream->sendPacket(returnIq); - - // store updated entries and notify changes - QList<QXmppRosterIq::Item> items = rosterIq.items(); - for (int i = 0; i < items.count(); i++) - { - QString bareJid = items.at(i).bareJid(); - m_entries[bareJid] = items.at(i); - emit rosterChanged(bareJid); - } - - // when contact subscribes user...user sends 'subscribed' presence - // then after recieving following iq user requests contact for subscription - - // check the "from" is newly added in the roster...and remove this ask thing...and do this for all items - if(rosterIq.items().at(0).subscriptionType() == - QXmppRosterIq::Item::From && rosterIq.items().at(0). - subscriptionStatus().isEmpty()) - m_stream->sendSubscriptionRequest(rosterIq.items().at(0).bareJid()); - } - break; - case QXmppIq::Result: - { - QList<QXmppRosterIq::Item> items = rosterIq.items(); - for(int i = 0; i < items.count(); ++i) - { - QString bareJid = items.at(i).bareJid(); - m_entries[bareJid] = items.at(i); - if (!isInitial) - emit rosterChanged(bareJid); - } - if (isInitial) - { - m_isRosterReceived = true; - emit rosterReceived(); - } - break; - } - default: - break; - } -} - -/// Function to get all the bareJids present in the roster. -/// -/// \return QStringList list of all the bareJids -/// - -QStringList QXmppRosterManager::getRosterBareJids() const -{ - return m_entries.keys(); -} - -/// Returns the roster entry of the given bareJid. If the bareJid is not in the -/// database and empty QXmppRosterIq::Item will be returned. -/// -/// \param bareJid as a QString -/// - -QXmppRosterIq::Item QXmppRosterManager::getRosterEntry( - const QString& bareJid) const -{ - // will return blank entry if bareJid does'nt exist - if(m_entries.contains(bareJid)) - return m_entries.value(bareJid); - else - return QXmppRosterIq::Item(); -} - -/// [OBSOLETE] Returns all the roster entries in the database. -/// -/// \return Map of bareJid and its respective QXmppRosterIq::Item -/// -/// \note This function is obsolete, use getRosterBareJids() and -/// getRosterEntry() to get all the roster entries. -/// - -QMap<QString, QXmppRosterIq::Item> - QXmppRosterManager::getRosterEntries() const -{ - return m_entries; -} - -/// Get all the associated resources with the given bareJid. -/// -/// \param bareJid as a QString -/// \return list of associated resources as a QStringList -/// - -QStringList QXmppRosterManager::getResources(const QString& bareJid) const -{ - if(m_presences.contains(bareJid)) - return m_presences[bareJid].keys(); - else - return QStringList(); -} - -/// Get all the presences of all the resources of the given bareJid. A bareJid -/// can have multiple resources and each resource will have a presence -/// associated with it. -/// -/// \param bareJid as a QString -/// \return Map of resource and its respective presence QMap<QString, QXmppPresence> -/// - -QMap<QString, QXmppPresence> QXmppRosterManager::getAllPresencesForBareJid( - const QString& bareJid) const -{ - if(m_presences.contains(bareJid)) - return m_presences[bareJid]; - else - return QMap<QString, QXmppPresence>(); -} - -/// Get the presence of the given resource of the given bareJid. -/// -/// \param bareJid as a QString -/// \param resource as a QString -/// \return QXmppPresence -/// - -QXmppPresence QXmppRosterManager::getPresence(const QString& bareJid, - const QString& resource) const -{ - if(m_presences.contains(bareJid) && m_presences[bareJid].contains(resource)) - return m_presences[bareJid][resource]; - else - return QXmppPresence(); -} - -/// [OBSOLETE] Returns all the presence entries in the database. -/// -/// \return Map of bareJid and map of resource and its presence that is -/// QMap<QString, QMap<QString, QXmppPresence> > -/// -/// \note This function is obsolete, use getRosterBareJids(), getResources() -/// and getPresence() or getAllPresencesForBareJid() -/// to get all the presence entries. - -QMap<QString, QMap<QString, QXmppPresence> > QXmppRosterManager::getAllPresences() const -{ - return m_presences; -} - -/// Function to check whether the roster has been received or not. -/// -/// \return true if roster received else false - -bool QXmppRosterManager::isRosterReceived() -{ - return m_isRosterReceived; -} - diff --git a/source/QXmppRosterManager.h b/source/QXmppRosterManager.h deleted file mode 100644 index 25d8ead8..00000000 --- a/source/QXmppRosterManager.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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. - * - */ - -#ifndef QXMPPROSTER_H -#define QXMPPROSTER_H - -#include <QObject> -#include <QMap> -#include <QSet> -#include <QStringList> - -#include "QXmppRosterIq.h" - -class QXmppRosterIq; -class QXmppPresence; -class QXmppStream; - -/// \brief The QXmppRosterManager class provides access to a connected client's roster. -/// -/// \note It's object should not be created using it's constructor. Instead -/// QXmppClient::rosterManager() should be used to get the reference of instantiated -/// object this class. -/// -/// It stores all the Roster and Presence details of all the roster entries (that -/// is all the bareJids) in the client's friend's list. It provides the -/// functionality to get all the bareJids in the client's roster and Roster and -/// Presence details of the same. -/// -/// After the sucessfull xmpp connection that after the signal QXmppClient::connected() -/// is emitted QXmpp requests for getting the roster. Once QXmpp receives the roster -/// the signal QXmppRosterManager::rosterReceived() is emitted and after that user can -/// use the functions of this class to get roster entries. -/// -/// Function QXmppRosterManager::isRosterReceived() tells whether the roster has been -/// received or not. -/// -/// Signals presenceChanged() or rosterChanged() are emitted whenever presence -/// or roster changes respectively. -/// -/// \ingroup Managers - -class QXmppRosterManager : public QObject -{ - Q_OBJECT - -public: - // FIXME : is this class really necessary? - typedef QXmppRosterIq::Item QXmppRosterEntry; - - QXmppRosterManager(QXmppStream* stream, QObject *parent = 0); - ~QXmppRosterManager(); - - bool isRosterReceived(); - QStringList getRosterBareJids() const; - QXmppRosterIq::Item getRosterEntry(const QString& bareJid) const; - - QStringList getResources(const QString& bareJid) const; - QMap<QString, QXmppPresence> getAllPresencesForBareJid( - const QString& bareJid) const; - QXmppPresence getPresence(const QString& bareJid, - const QString& resource) const; - - - /// \cond - QMap<QString, QXmppRosterIq::Item> Q_DECL_DEPRECATED getRosterEntries() const; - QMap<QString, QMap<QString, QXmppPresence> > Q_DECL_DEPRECATED getAllPresences() const; - /// \endcond - -signals: - /// This signal is emitted when the Roster IQ is received after a successful - /// connection. - void rosterReceived(); - - /// This signal is emitted when the presence of a particular bareJid and resource changes. - void presenceChanged(const QString& bareJid, const QString& resource); - - /// This signal is emitted when the roster entry of a particular bareJid changes. - void rosterChanged(const QString& bareJid); - -private: - //reverse pointer to stream - QXmppStream* m_stream; - //map of bareJid and its rosterEntry - QMap<QString, QXmppRosterIq::Item> m_entries; - // map of resources of the jid and map of resouces and presences - QMap<QString, QMap<QString, QXmppPresence> > m_presences; - // flag to store that the roster has been populated - bool m_isRosterReceived; - // id of the initial roster request - QString m_rosterReqId; - -private slots: - void connected(); - void disconnected(); - void presenceReceived(const QXmppPresence&); - void rosterIqReceived(const QXmppRosterIq&); -}; - -#endif // QXMPPROSTER_H diff --git a/source/QXmppRpcIq.cpp b/source/QXmppRpcIq.cpp deleted file mode 100644 index 2f641d1d..00000000 --- a/source/QXmppRpcIq.cpp +++ /dev/null @@ -1,443 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Ian Reinhard Geiser - * 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 <QMap> -#include <QVariant> -#include <QDateTime> -#include <QStringList> - -#include "QXmppConstants.h" -#include "QXmppRpcIq.h" -#include "QXmppUtils.h" - -void XMLRPC::marshall(QXmlStreamWriter *writer, const QVariant &value) -{ - writer->writeStartElement("value"); - switch( value.type() ) - { - case QVariant::Int: - case QVariant::UInt: - case QVariant::LongLong: - case QVariant::ULongLong: - writer->writeTextElement("i4", value.toString()); - break; - case QVariant::Double: - writer->writeTextElement("double", value.toString()); - break; - case QVariant::Bool: - writer->writeTextElement("boolean", value.toBool() ? "1" : "0"); - break; - case QVariant::Date: - writer->writeTextElement("dateTime.iso8601", value.toDate().toString( Qt::ISODate ) ); - break; - case QVariant::DateTime: - writer->writeTextElement("dateTime.iso8601", value.toDateTime().toString( Qt::ISODate ) ); - break; - case QVariant::Time: - writer->writeTextElement("dateTime.iso8601", value.toTime().toString( Qt::ISODate ) ); - break; - case QVariant::StringList: - case QVariant::List: - { - writer->writeStartElement("array"); - writer->writeStartElement("data"); - foreach(const QVariant &item, value.toList()) - marshall(writer, item); - writer->writeEndElement(); - writer->writeEndElement(); - break; - } - case QVariant::Map: - { - writer->writeStartElement("struct"); - QMap<QString, QVariant> map = value.toMap(); - QMap<QString, QVariant>::ConstIterator index = map.begin(); - while( index != map.end() ) - { - writer->writeStartElement("member"); - writer->writeTextElement("name", index.key()); - marshall( writer, *index ); - writer->writeEndElement(); - ++index; - } - writer->writeEndElement(); - break; - } - case QVariant::ByteArray: - { - writer->writeTextElement("base64", value.toByteArray().toBase64() ); - break; - } - default: - { - if (value.isNull()) - writer->writeEmptyElement("nil"); - else if( value.canConvert(QVariant::String) ) - { - writer->writeTextElement("string", value.toString() ); - } - break; - } - } - writer->writeEndElement(); -} - -QVariant XMLRPC::demarshall(const QDomElement &elem, QStringList &errors) -{ - if ( elem.tagName().toLower() != "value" ) - { - errors << "Bad param value"; - return QVariant(); - } - - if ( !elem.firstChild().isElement() ) - { - return QVariant( elem.text() ); - } - - const QDomElement typeData = elem.firstChild().toElement(); - const QString typeName = typeData.tagName().toLower(); - - if (typeName == "nil") - { - return QVariant(); - } - if ( typeName == "string" ) - { - return QVariant( typeData.text() ); - } - else if (typeName == "int" || typeName == "i4" ) - { - bool ok = false; - QVariant val( typeData.text().toInt( &ok ) ); - if (ok) - return val; - errors << "I was looking for an integer but data was courupt"; - return QVariant(); - } - else if( typeName == "double" ) - { - bool ok = false; - QVariant val( typeData.text().toDouble( &ok ) ); - if (ok) - return val; - errors << "I was looking for an double but data was corrupt"; - } - else if( typeName == "boolean" ) - return QVariant( typeData.text() == "1" || typeData.text().toLower() == "true" ); - else if( typeName == "datetime" || typeName == "datetime.iso8601" ) - return QVariant( QDateTime::fromString( typeData.text(), Qt::ISODate ) ); - else if( typeName == "array" ) - { - QVariantList arr; - QDomElement valueNode = typeData.firstChildElement("data").firstChildElement(); - while (!valueNode.isNull() && errors.isEmpty()) - { - arr.append(demarshall(valueNode, errors)); - valueNode = valueNode.nextSiblingElement(); - } - return QVariant( arr ); - } - else if( typeName == "struct" ) - { - QMap<QString,QVariant> stct; - QDomNode valueNode = typeData.firstChild(); - while(!valueNode.isNull() && errors.isEmpty()) - { - const QDomElement memberNode = valueNode.toElement().elementsByTagName("name").item(0).toElement(); - const QDomElement dataNode = valueNode.toElement().elementsByTagName("value").item(0).toElement(); - stct[ memberNode.text() ] = demarshall(dataNode, errors); - valueNode = valueNode.nextSibling(); - } - return QVariant(stct); - } - else if( typeName == "base64" ) - { - QVariant returnVariant; - QByteArray dest; - QByteArray src = typeData.text().toLatin1(); - return QVariant(QByteArray::fromBase64(src)); - } - - errors << QString( "Cannot handle type %1").arg(typeName); - return QVariant(); -} - -QXmppRpcErrorIq::QXmppRpcErrorIq() : QXmppIq( QXmppIq::Error ) -{ - -} - -QXmppRpcInvokeIq QXmppRpcErrorIq::query() const -{ - return m_query; -} - -void QXmppRpcErrorIq::setQuery(const QXmppRpcInvokeIq &query) -{ - m_query = query; -} - -bool QXmppRpcErrorIq::isRpcErrorIq(const QDomElement &element) -{ - QString type = element.attribute("type"); - QDomElement errorElement = element.firstChildElement("error"); - QDomElement queryElement = element.firstChildElement("query"); - return (type == "error") && - !errorElement.isNull() && - queryElement.namespaceURI() == ns_rpc; -} - -void QXmppRpcErrorIq::parseElementFromChild(const QDomElement &element) -{ - m_query.parseElementFromChild(element); -} - -void QXmppRpcErrorIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - m_query.toXmlElementFromChild(writer); -} - -QXmppRpcResponseIq::QXmppRpcResponseIq() - : QXmppIq(QXmppIq::Result), - m_faultCode(0) -{ -} - -/// Returns the fault code. -/// - -int QXmppRpcResponseIq::faultCode() const -{ - return m_faultCode; -} - -/// Sets the fault code. -/// -/// \param faultCode - -void QXmppRpcResponseIq::setFaultCode(int faultCode) -{ - m_faultCode = faultCode; -} - -/// Returns the fault string. -/// - -QString QXmppRpcResponseIq::faultString() const -{ - return m_faultString; -} - -/// Sets the fault string. -/// -/// \param faultString - -void QXmppRpcResponseIq::setFaultString(const QString& faultString) -{ - m_faultString = faultString; -} - -/// Returns the response values. -/// - -QVariantList QXmppRpcResponseIq::values() const -{ - return m_values; -} - -/// Sets the response values. -/// -/// \param values - -void QXmppRpcResponseIq::setValues(const QVariantList &values) -{ - m_values = values; -} - -bool QXmppRpcResponseIq::isRpcResponseIq(const QDomElement &element) -{ - QString type = element.attribute("type"); - QDomElement dataElement = element.firstChildElement("query"); - return dataElement.namespaceURI() == ns_rpc && - type == "result"; -} - -void QXmppRpcResponseIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - QDomElement methodElement = queryElement.firstChildElement("methodResponse"); - - const QDomElement contents = methodElement.firstChildElement(); - if( contents.tagName().toLower() == "params") - { - QDomNode param = contents.firstChildElement("param"); - while (!param.isNull()) - { - QStringList errors; - const QVariant value = XMLRPC::demarshall(param.firstChildElement("value"), errors); - if (!errors.isEmpty()) - break; - m_values << value; - param = param.nextSiblingElement("param"); - } - } - else if( contents.tagName().toLower() == "fault") - { - QStringList errors; - const QDomElement errElement = contents.firstChildElement("value"); - const QVariant error = XMLRPC::demarshall(errElement, errors); - if (!errors.isEmpty()) - return; - m_faultCode = error.toMap()["faultCode"].toInt(); - m_faultString = error.toMap()["faultString"].toString(); - } -} - -void QXmppRpcResponseIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("query"); - helperToXmlAddAttribute(writer, "xmlns", ns_rpc); - - writer->writeStartElement("methodResponse"); - if (m_faultCode) - { - writer->writeStartElement("fault"); - QMap<QString,QVariant> fault; - fault["faultCode"] = m_faultCode; - fault["faultString"] = m_faultString; - XMLRPC::marshall(writer, fault); - writer->writeEndElement(); - } - else if (!m_values.isEmpty()) - { - writer->writeStartElement("params"); - foreach (const QVariant &arg, m_values) - { - writer->writeStartElement("param"); - XMLRPC::marshall(writer, arg); - writer->writeEndElement(); - } - writer->writeEndElement(); - } - writer->writeEndElement(); - - writer->writeEndElement(); -} - -QXmppRpcInvokeIq::QXmppRpcInvokeIq() - : QXmppIq(QXmppIq::Set) -{ -} - -/// Returns the method arguments. -/// - -QVariantList QXmppRpcInvokeIq::arguments() const -{ - return m_arguments; -} - -/// Sets the method arguments. -/// -/// \param arguments - -void QXmppRpcInvokeIq::setArguments(const QVariantList &arguments) -{ - m_arguments = arguments; -} - -/// Returns the method name. -/// - -QString QXmppRpcInvokeIq::method() const -{ - return m_method; -} - -/// Sets the method name. -/// -/// \param method - -void QXmppRpcInvokeIq::setMethod(const QString &method) -{ - m_method = method; -} - -bool QXmppRpcInvokeIq::isRpcInvokeIq(const QDomElement &element) -{ - QString type = element.attribute("type"); - QDomElement dataElement = element.firstChildElement("query"); - return dataElement.namespaceURI() == ns_rpc && - type == "set"; -} - -void QXmppRpcInvokeIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - QDomElement methodElement = queryElement.firstChildElement("methodCall"); - - m_method = methodElement.firstChildElement("methodName").text(); - - const QDomElement methodParams = methodElement.firstChildElement("params"); - m_arguments.clear(); - if( !methodParams.isNull() ) - { - QDomNode param = methodParams.firstChildElement("param"); - while (!param.isNull()) - { - QStringList errors; - QVariant arg = XMLRPC::demarshall(param.firstChildElement("value"), errors); - if (!errors.isEmpty()) - break; - m_arguments << arg; - param = param.nextSiblingElement("param"); - } - } -} - -void QXmppRpcInvokeIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("query"); - helperToXmlAddAttribute(writer, "xmlns", ns_rpc); - - writer->writeStartElement("methodCall"); - writer->writeTextElement("methodName", m_method); - if (!m_arguments.isEmpty()) - { - writer->writeStartElement("params"); - foreach(const QVariant &arg, m_arguments) - { - writer->writeStartElement("param"); - XMLRPC::marshall(writer, arg); - writer->writeEndElement(); - } - writer->writeEndElement(); - } - writer->writeEndElement(); - - writer->writeEndElement(); -} - diff --git a/source/QXmppRpcIq.h b/source/QXmppRpcIq.h deleted file mode 100644 index 3693f133..00000000 --- a/source/QXmppRpcIq.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Ian Reinhard Geiser - * 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. - * - */ - -#ifndef QXMPPRPCIQ_H -#define QXMPPRPCIQ_H - -#include "QXmppIq.h" -#include <QVariant> - -class QXmlStreamWriter; -class QDomElement; - -namespace XMLRPC -{ - void marshall( QXmlStreamWriter *writer, const QVariant &value); - QVariant demarshall(const QDomElement &elem, QStringList &errors); -} - -/// \brief The QXmppRpcResponseIq class represents an IQ used to carry -/// an RPC response as specified by XEP-0009: Jabber-RPC. -/// -/// \ingroup Stanzas - -class QXmppRpcResponseIq : public QXmppIq -{ -public: - QXmppRpcResponseIq(); - - int faultCode() const; - void setFaultCode(int faultCode); - - QString faultString() const; - void setFaultString(const QString &faultString); - - QVariantList values() const; - void setValues(const QVariantList &values); - - static bool isRpcResponseIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - int m_faultCode; - QString m_faultString; - QVariantList m_values; -}; - -/// \brief The QXmppRpcInvokeIq class represents an IQ used to carry -/// an RPC invocation as specified by XEP-0009: Jabber-RPC. -/// -/// \ingroup Stanzas - -class QXmppRpcInvokeIq : public QXmppIq -{ -public: - QXmppRpcInvokeIq(); - - QString method() const; - void setMethod( const QString &method ); - - QVariantList arguments() const; - void setArguments(const QVariantList &arguments); - - static bool isRpcInvokeIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QVariantList m_arguments; - QString m_method; - - friend class QXmppRpcErrorIq; -}; - -class QXmppRpcErrorIq : public QXmppIq -{ -public: - QXmppRpcErrorIq(); - - QXmppRpcInvokeIq query() const; - void setQuery(const QXmppRpcInvokeIq &query); - - static bool isRpcErrorIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QXmppRpcInvokeIq m_query; -}; - -#endif // QXMPPRPCIQ_H diff --git a/source/QXmppSession.cpp b/source/QXmppSession.cpp deleted file mode 100644 index 8aaced7c..00000000 --- a/source/QXmppSession.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * 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 <QXmlStreamWriter> - -#include "QXmppSession.h" -#include "QXmppConstants.h" -#include "QXmppUtils.h" - -QXmppSession::QXmppSession() -{ -} - -QXmppSession::QXmppSession(QXmppIq::Type type) - : QXmppIq(type) -{ -} - -bool QXmppSession::isSession(const QDomElement &element) -{ - QDomElement sessionElement = element.firstChildElement("session"); - return (sessionElement.namespaceURI() == ns_session); -} - -void QXmppSession::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("session");; - writer->writeAttribute("xmlns", ns_session); - writer->writeEndElement(); -} - diff --git a/source/QXmppSession.h b/source/QXmppSession.h deleted file mode 100644 index 71688fbc..00000000 --- a/source/QXmppSession.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * 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. - * - */ - - -#ifndef QXMPPSESSION_H -#define QXMPPSESSION_H - -#include "QXmppIq.h" - -class QXmppSession : public QXmppIq -{ -public: - QXmppSession(); - QXmppSession(QXmppIq::Type type); - - static bool isSession(const QDomElement &element); - -private: - void toXmlElementFromChild(QXmlStreamWriter *writer) const; -}; - -#endif // QXMPPSESSION_H diff --git a/source/QXmppSocks.cpp b/source/QXmppSocks.cpp deleted file mode 100644 index 1cb1e84d..00000000 --- a/source/QXmppSocks.cpp +++ /dev/null @@ -1,345 +0,0 @@ -/* - * 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 <QDataStream> -#include <QEventLoop> -#include <QTcpServer> -#include <QTcpSocket> -#include <QTimer> - -#include "QXmppSocks.h" - -const static char SocksVersion = 5; - -enum AuthenticationMethod { - NoAuthentication = 0, - GSSAPI = 1, - UsernamePassword = 2, -}; - -enum Command { - ConnectCommand = 1, - BindCommand = 2, - AssociateCommand = 3, -}; - -enum AddressType { - IPv4Address = 1, - DomainName = 3, - IPv6Address = 4, -}; - -enum ReplyType { - Succeeded = 0, - SocksFailure = 1, - ConnectionNotAllowed = 2, - NetworkUnreachable = 3, - HostUnreachable = 4, - ConnectionRefused = 5, - TtlExpired = 6, - CommandNotSupported = 7, - AddressTypeNotSupported = 8, -}; - -enum State { - ConnectState = 0, - CommandState = 1, - ReadyState = 2, -}; - -static QByteArray encodeHostAndPort(quint8 type, const QByteArray &host, quint16 port) -{ - QByteArray buffer; - QDataStream stream(&buffer, QIODevice::WriteOnly); - // set host name - quint8 hostLength = host.size(); - stream << type; - stream << hostLength; - stream.writeRawData(host.constData(), hostLength); - // set port - stream << port; - return buffer; -} - -static bool parseHostAndPort(const QByteArray buffer, quint8 &type, QByteArray &host, quint16 &port) -{ - if (buffer.size() < 4) - return false; - - QDataStream stream(buffer); - // get host name - quint8 hostLength; - stream >> type; - stream >> hostLength; - if (buffer.size() < hostLength + 4) - { - qWarning("Invalid host length"); - return false; - } - host.resize(hostLength); - stream.readRawData(host.data(), hostLength); - // get port - stream >> port; - return true; -} - -QXmppSocksClient::QXmppSocksClient(const QHostAddress &proxyAddress, quint16 proxyPort, QObject *parent) - : QTcpSocket(parent), - m_proxyAddress(proxyAddress), - m_proxyPort(proxyPort), - m_step(ConnectState) -{ - connect(this, SIGNAL(connected()), this, SLOT(slotConnected())); - connect(this, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); -} - -void QXmppSocksClient::connectToHost(const QString &hostName, quint16 hostPort) -{ - m_hostName = hostName; - m_hostPort = hostPort; - QTcpSocket::connectToHost(m_proxyAddress, m_proxyPort); -} - -void QXmppSocksClient::slotConnected() -{ - m_step = ConnectState; - - // disconnect from signal - disconnect(this, SIGNAL(connected()), this, SLOT(slotConnected())); - - // send connect to server - QByteArray buffer; - buffer.resize(3); - buffer[0] = SocksVersion; - buffer[1] = 0x01; // number of methods - buffer[2] = NoAuthentication; - write(buffer); -} - -void QXmppSocksClient::slotReadyRead() -{ - if (m_step == ConnectState) - { - m_step++; - - // receive connect to server response - QByteArray buffer = readAll(); - if (buffer.size() != 2 || buffer.at(0) != SocksVersion || buffer.at(1) != NoAuthentication) - { - qWarning("QXmppSocksClient received an invalid response during handshake"); - close(); - return; - } - - // send CONNECT command - buffer.resize(3); - buffer[0] = SocksVersion; - buffer[1] = ConnectCommand; - buffer[2] = 0x00; // reserved - buffer.append(encodeHostAndPort( - DomainName, - m_hostName.toAscii(), - m_hostPort)); - write(buffer); - - } else if (m_step == CommandState) { - m_step++; - - // disconnect from signal - disconnect(this, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); - - // receive CONNECT response - QByteArray buffer = readAll(); - if (buffer.size() < 6 || - buffer.at(0) != SocksVersion || - buffer.at(1) != Succeeded || - buffer.at(2) != 0) - { - qWarning("QXmppSocksClient received an invalid response to CONNECT command"); - close(); - return; - } - - // parse host - quint8 hostType; - QByteArray hostName; - quint16 hostPort; - if (!parseHostAndPort(buffer.mid(3), hostType, hostName, hostPort)) - { - qWarning("QXmppSocksClient could not parse type/host/port"); - close(); - return; - } - // FIXME : what do we do with the resulting name / port? - - // notify of connection - emit ready(); - } -} - -bool QXmppSocksClient::waitForReady(int msecs) -{ - QEventLoop loop; - connect(this, SIGNAL(disconnected()), &loop, SLOT(quit())); - connect(this, SIGNAL(ready()), &loop, SLOT(quit())); - QTimer::singleShot(msecs, &loop, SLOT(quit())); - loop.exec(); - - if (m_step == ReadyState && isValid()) - return true; - else - return false; -} - -QXmppSocksServer::QXmppSocksServer(QObject *parent) - : QObject(parent) -{ - m_server = new QTcpServer(this); - connect(m_server, SIGNAL(newConnection()), this, SLOT(slotNewConnection())); -} - -void QXmppSocksServer::close() -{ - m_server->close(); -} - -bool QXmppSocksServer::listen(const QHostAddress &address, quint16 port) -{ - return m_server->listen(address, port); -} - -bool QXmppSocksServer::isListening() const -{ - return m_server->isListening(); -} - -QHostAddress QXmppSocksServer::serverAddress() const -{ - return m_server->serverAddress(); -} - -quint16 QXmppSocksServer::serverPort() const -{ - return m_server->serverPort(); -} - -void QXmppSocksServer::slotNewConnection() -{ - QTcpSocket *socket = m_server->nextPendingConnection(); - if (!socket) - return; - - // register socket - m_states.insert(socket, ConnectState); - connect(socket, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); -} - -void QXmppSocksServer::slotReadyRead() -{ - QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender()); - if (!socket || !m_states.contains(socket)) - return; - - if (m_states.value(socket) == ConnectState) - { - m_states.insert(socket, CommandState); - - // receive connect to server request - QByteArray buffer = socket->readAll(); - if (buffer.size() < 3 || - buffer.at(0) != SocksVersion || - buffer.at(1) + 2 != buffer.size()) - { - qWarning("QXmppSocksServer received invalid handshake"); - socket->close(); - return; - } - - // check authentication method - bool foundMethod = false; - for (int i = 2; i < buffer.size(); i++) - { - if (buffer.at(i) == NoAuthentication) - { - foundMethod = true; - break; - } - } - if (!foundMethod) - { - qWarning("QXmppSocksServer received bad authentication method"); - socket->close(); - return; - } - - // send connect to server response - buffer.resize(2); - buffer[0] = SocksVersion; - buffer[1] = NoAuthentication; - socket->write(buffer); - - } else if (m_states.value(socket) == CommandState) { - m_states.insert(socket, ReadyState); - - // disconnect from signals - disconnect(socket, SIGNAL(readyRead()), this, SLOT(slotReadyRead())); - - // receive command - QByteArray buffer = socket->readAll(); - if (buffer.size() < 4 || - buffer.at(0) != SocksVersion || - buffer.at(1) != ConnectCommand || - buffer.at(2) != 0x00) - { - qWarning("QXmppSocksServer received an invalid command"); - socket->close(); - return; - } - - // parse host - quint8 hostType; - QByteArray hostName; - quint16 hostPort; - if (!parseHostAndPort(buffer.mid(3), hostType, hostName, hostPort)) - { - qWarning("QXmppSocksServer could not parse type/host/port"); - socket->close(); - return; - } - - // notify of connection - emit newConnection(socket, hostName, hostPort); - - // send response - buffer.resize(3); - buffer[0] = SocksVersion; - buffer[1] = Succeeded; - buffer[2] = 0x00; - buffer.append(encodeHostAndPort( - DomainName, - hostName, - hostPort)); - socket->write(buffer); - } -} - diff --git a/source/QXmppSocks.h b/source/QXmppSocks.h deleted file mode 100644 index 68716ef7..00000000 --- a/source/QXmppSocks.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPSOCKS_H -#define QXMPPSOCKS_H - -#include <QHostAddress> -#include <QTcpSocket> - -class QTcpServer; - -class QXmppSocksClient : public QTcpSocket -{ - Q_OBJECT - -public: - QXmppSocksClient(const QHostAddress &proxyAddress, quint16 proxyPort, QObject *parent=0); - void connectToHost(const QString &hostName, quint16 hostPort); - bool waitForReady(int msecs = 30000); - -signals: - void ready(); - -private slots: - void slotConnected(); - void slotReadyRead(); - -private: - QHostAddress m_proxyAddress; - quint16 m_proxyPort; - QString m_hostName; - quint16 m_hostPort; - int m_step; -}; - -class QXmppSocksServer : public QObject -{ - Q_OBJECT - -public: - QXmppSocksServer(QObject *parent=0); - void close(); - bool isListening() const; - bool listen(const QHostAddress &address = QHostAddress::Any, quint16 port = 0); - - QHostAddress serverAddress() const; - quint16 serverPort() const; - -signals: - void newConnection(QTcpSocket *socket, QString hostName, quint16 port); - -private slots: - void slotNewConnection(); - void slotReadyRead(); - -private: - QTcpServer *m_server; - QMap<QTcpSocket*, int> m_states; -}; - -#endif diff --git a/source/QXmppStanza.cpp b/source/QXmppStanza.cpp deleted file mode 100644 index fb99e495..00000000 --- a/source/QXmppStanza.cpp +++ /dev/null @@ -1,456 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppStanza.h" -#include "QXmppUtils.h" -#include "QXmppConstants.h" - -#include <QDomElement> -#include <QXmlStreamWriter> - -uint QXmppStanza::s_uniqeIdNo = 0; - -QXmppStanza::Error::Error(): - m_code(0), - m_type(static_cast<QXmppStanza::Error::Type>(-1)), - m_condition(static_cast<QXmppStanza::Error::Condition>(-1)), - m_text("") -{ -} - -QXmppStanza::Error::Error(Type type, Condition cond, const QString& text): - m_code(0), - m_type(type), - m_condition(cond), - m_text(text) -{ -} - -QXmppStanza::Error::Error(const QString& type, const QString& cond, - const QString& text): - m_code(0), - m_text(text) -{ - setTypeFromStr(type); - setConditionFromStr(cond); -} - -QString QXmppStanza::Error::text() const -{ - return m_text; -} - -void QXmppStanza::Error::setText(const QString& text) -{ - m_text = text; -} - -int QXmppStanza::Error::code() const -{ - return m_code; -} - -void QXmppStanza::Error::setCode(int code) -{ - m_code = code; -} - -QXmppStanza::Error::Condition QXmppStanza::Error::condition() const -{ - return m_condition; -} - -void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond) -{ - m_condition = cond; -} - -QXmppStanza::Error::Type QXmppStanza::Error::type() const -{ - return m_type; -} - -void QXmppStanza::Error::setType(QXmppStanza::Error::Type type) -{ - m_type = type; -} - -QString QXmppStanza::Error::getTypeStr() const -{ - switch(m_type) - { - case Cancel: - return "cancel"; - case Continue: - return "continue"; - case Modify: - return "modify"; - case Auth: - return "auth"; - case Wait: - return "wait"; - default: - return ""; - } -} - -QString QXmppStanza::Error::getConditionStr() const -{ - switch(m_condition) - { - case BadRequest: - return "bad-request"; - case Conflict: - return "conflict"; - case FeatureNotImplemented: - return "feature-not-implemented"; - case Forbidden: - return "forbidden"; - case Gone: - return "gone"; - case InternalServerError: - return "internal-server-error"; - case ItemNotFound: - return "item-not-found"; - case JidMalformed: - return "jid-malformed"; - case NotAcceptable: - return "not-acceptable"; - case NotAllowed: - return "not-allowed"; - case NotAuthorized: - return "not-authorized"; - case PaymentRequired: - return "payment-required"; - case RecipientUnavailable: - return "recipient-unavailable"; - case Redirect: - return "redirect"; - case RegistrationRequired: - return "registration-required"; - case RemoteServerNotFound: - return "remote-server-not-found"; - case RemoteServerTimeout: - return "remote-server-timeout"; - case ResourceConstraint: - return "resource-constraint"; - case ServiceUnavailable: - return "service-unavailable"; - case SubscriptionRequired: - return "subscription-required"; - case UndefinedCondition: - return "undefined-condition"; - case UnexpectedRequest: - return "unexpected-request"; - default: - return ""; - } -} - -void QXmppStanza::Error::setTypeFromStr(const QString& type) -{ - if(type == "cancel") - setType(Cancel); - else if(type == "continue") - setType(Continue); - else if(type == "modify") - setType(Modify); - else if(type == "auth") - setType(Auth); - else if(type == "wait") - setType(Wait); - else - setType(static_cast<QXmppStanza::Error::Type>(-1)); -} - -void QXmppStanza::Error::setConditionFromStr(const QString& type) -{ - if(type == "bad-request") - setCondition(BadRequest); - else if(type == "conflict") - setCondition(Conflict); - else if(type == "feature-not-implemented") - setCondition(FeatureNotImplemented); - else if(type == "forbidden") - setCondition(Forbidden); - else if(type == "gone") - setCondition(Gone); - else if(type == "internal-server-error") - setCondition(InternalServerError); - else if(type == "item-not-found") - setCondition(ItemNotFound); - else if(type == "jid-malformed") - setCondition(JidMalformed); - else if(type == "not-acceptable") - setCondition(NotAcceptable); - else if(type == "not-allowed") - setCondition(NotAllowed); - else if(type == "not-authorized") - setCondition(NotAuthorized); - else if(type == "payment-required") - setCondition(PaymentRequired); - else if(type == "recipient-unavailable") - setCondition(RecipientUnavailable); - else if(type == "redirect") - setCondition(Redirect); - else if(type == "registration-required") - setCondition(RegistrationRequired); - else if(type == "remote-server-not-found") - setCondition(RemoteServerNotFound); - else if(type == "remote-server-timeout") - setCondition(RemoteServerTimeout); - else if(type == "resource-constraint") - setCondition(ResourceConstraint); - else if(type == "service-unavailable") - setCondition(ServiceUnavailable); - else if(type == "subscription-required") - setCondition(SubscriptionRequired); - else if(type == "undefined-condition") - setCondition(UndefinedCondition); - else if(type == "unexpected-request") - setCondition(UnexpectedRequest); - else - setCondition(static_cast<QXmppStanza::Error::Condition>(-1)); -} - -bool QXmppStanza::Error::isValid() -{ - return !(getTypeStr().isEmpty() && getConditionStr().isEmpty()); -} - -void QXmppStanza::Error::parse(const QDomElement &errorElement) -{ - setCode(errorElement.attribute("code").toInt()); - setTypeFromStr(errorElement.attribute("type")); - - QString text; - QString cond; - QDomElement element = errorElement.firstChildElement(); - while(!element.isNull()) - { - if(element.tagName() == "text") - text = element.text(); - else if(element.namespaceURI() == ns_stanza) - { - cond = element.tagName(); - } - element = element.nextSiblingElement(); - } - - setConditionFromStr(cond); - setText(text); -} - -void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const -{ - QString cond = getConditionStr(); - QString type = getTypeStr(); - - if(cond.isEmpty() && type.isEmpty()) - return; - - writer->writeStartElement("error"); - helperToXmlAddAttribute(writer, "type", type); - - if (m_code > 0) - helperToXmlAddAttribute(writer, "code", QString::number(m_code)); - - if(!cond.isEmpty()) - { - writer->writeStartElement(cond); - helperToXmlAddAttribute(writer,"xmlns", ns_stanza); - writer->writeEndElement(); - } - if(!m_text.isEmpty()) - { - writer->writeStartElement("text"); - helperToXmlAddAttribute(writer,"xml:lang", "en"); - helperToXmlAddAttribute(writer,"xmlns", ns_stanza); - writer->writeCharacters(m_text); - writer->writeEndElement(); - } - - writer->writeEndElement(); -} - - -QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(), -m_to(to), m_from(from) -{ -} - -QXmppStanza::~QXmppStanza() -{ -} - -/// Returns the stanza's recipient JID. -/// - -QString QXmppStanza::to() const -{ - return m_to; -} - -/// Sets the stanza's recipient JID. -/// -/// \param to - -void QXmppStanza::setTo(const QString& to) -{ - m_to = to; -} - -/// Returns the stanza's sender JID. - -QString QXmppStanza::from() const -{ - return m_from; -} - -/// Sets the stanza's sender JID. -/// -/// \param from - -void QXmppStanza::setFrom(const QString& from) -{ - m_from = from; -} - -/// Returns the stanza's identifier. - -QString QXmppStanza::id() const -{ - return m_id; -} - -/// Sets the stanza's identifier. -/// -/// \param id - -void QXmppStanza::setId(const QString& id) -{ - m_id = id; -} - -QString QXmppStanza::lang() const -{ - return m_lang; -} - -void QXmppStanza::setLang(const QString& lang) -{ - m_lang = lang; -} - -QXmppStanza::Error QXmppStanza::error() const -{ - return m_error; -} - -void QXmppStanza::setError(QXmppStanza::Error& error) -{ - m_error = error; -} - -QXmppElementList QXmppStanza::extensions() const -{ - return m_extensions; -} - -void QXmppStanza::setExtensions(const QXmppElementList &extensions) -{ - m_extensions = extensions; -} - -void QXmppStanza::generateAndSetNextId() -{ - // get back - ++s_uniqeIdNo; - m_id = "qxmpp" + QString::number(s_uniqeIdNo); -} - -bool QXmppStanza::isErrorStanza() -{ - return m_error.isValid(); -} - -void QXmppStanza::parse(const QDomElement &element) -{ - m_from = element.attribute("from"); - m_to = element.attribute("to"); - m_id = element.attribute("id"); - m_lang = element.attribute("lang"); - - QDomElement errorElement = element.firstChildElement("error"); - if(!errorElement.isNull()) - m_error.parse(errorElement); -} - -// deprecated - -QString QXmppStanza::Error::getText() const -{ - return m_text; -} - -int QXmppStanza::Error::getCode() const -{ - return m_code; -} - -QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const -{ - return m_condition; -} - -QXmppStanza::Error::Type QXmppStanza::Error::getType() const -{ - return m_type; -} - -QString QXmppStanza::getTo() const -{ - return m_to; -} - -QString QXmppStanza::getFrom() const -{ - return m_from; -} - -QString QXmppStanza::getId() const -{ - return m_id; -} - -QString QXmppStanza::getLang() const -{ - return m_lang; -} - -QXmppStanza::Error QXmppStanza::getError() const -{ - return m_error; -} - diff --git a/source/QXmppStanza.h b/source/QXmppStanza.h deleted file mode 100644 index c61acf69..00000000 --- a/source/QXmppStanza.h +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPSTANZA_H -#define QXMPPSTANZA_H - -#include "QXmppElement.h" -#include "QXmppPacket.h" -#include <QString> - -// forward declarations of QXmlStream* classes will not work on Mac, we need to -// include the whole header. -// See http://lists.trolltech.com/qt-interest/2008-07/thread00798-0.html -// for an explanation. -#include <QXmlStreamWriter> - -/// \defgroup Stanzas - -/// \brief The QXmppStanza class is the base class for all XMPP stanzas. -/// -/// \ingroup Stanzas - -class QXmppStanza : public QXmppPacket -{ -public: - class Error - { - public: - enum Type - { - Cancel, - Continue, - Modify, - Auth, - Wait - }; - - enum Condition - { - BadRequest, - Conflict, - FeatureNotImplemented, - Forbidden, - Gone, - InternalServerError, - ItemNotFound, - JidMalformed, - NotAcceptable, - NotAllowed, - NotAuthorized, - PaymentRequired, - RecipientUnavailable, - Redirect, - RegistrationRequired, - RemoteServerNotFound, - RemoteServerTimeout, - ResourceConstraint, - ServiceUnavailable, - SubscriptionRequired, - UndefinedCondition, - UnexpectedRequest - }; - - Error(); - Error(Type type, Condition cond, const QString& text=""); - Error(const QString& type, const QString& cond, const QString& text=""); - - int code() const; - void setCode(int code); - - QString text() const; - void setText(const QString& text); - - Condition condition() const; - void setCondition(Condition cond); - - void setType(Type type); - Type type() const; - - // FIXME : remove this once is gone - bool isValid(); - - /// \cond - void parse(const QDomElement &element); - void toXml(QXmlStreamWriter *writer) const; - - // deprecated accessors, use the form without "get" instead - int Q_DECL_DEPRECATED getCode() const; - QString Q_DECL_DEPRECATED getText() const; - Condition Q_DECL_DEPRECATED getCondition() const; - Type Q_DECL_DEPRECATED getType() const; - /// \endcond - - private: - QString getConditionStr() const; - void setConditionFromStr(const QString& cond); - - QString getTypeStr() const; - void setTypeFromStr(const QString& type); - - int m_code; - Type m_type; - Condition m_condition; - QString m_text; - }; - - QXmppStanza(const QString& from = "", const QString& to = ""); - ~QXmppStanza(); - - QString to() const; - void setTo(const QString&); - - QString from() const; - void setFrom(const QString&); - - QString id() const; - void setId(const QString&); - - QString lang() const; - void setLang(const QString&); - - QXmppStanza::Error error() const; - void setError(QXmppStanza::Error& error); - - QXmppElementList extensions() const; - void setExtensions(const QXmppElementList &elements); - - /// \cond - // FIXME : why is this needed? - bool isErrorStanza(); - - // deprecated accessors, use the form without "get" instead - QString Q_DECL_DEPRECATED getTo() const; - QString Q_DECL_DEPRECATED getFrom() const; - QString Q_DECL_DEPRECATED getId() const; - QString Q_DECL_DEPRECATED getLang() const; - QXmppStanza::Error Q_DECL_DEPRECATED getError() const; - -protected: - void generateAndSetNextId(); - void parse(const QDomElement &element); - /// \endcond - -private: - static uint s_uniqeIdNo; - QString m_to; - QString m_from; - QString m_id; - QString m_lang; - QXmppStanza::Error m_error; - QXmppElementList m_extensions; -}; - -#endif // QXMPPSTANZA_H diff --git a/source/QXmppStream.cpp b/source/QXmppStream.cpp deleted file mode 100644 index 95acb236..00000000 --- a/source/QXmppStream.cpp +++ /dev/null @@ -1,1120 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppUtils.h" -#include "QXmppBind.h" -#include "QXmppIq.h" -#include "QXmppLogger.h" -#include "QXmppMessage.h" -#include "QXmppPacket.h" -#include "QXmppPresence.h" -#include "QXmppSession.h" -#include "QXmppConstants.h" -#include "QXmppStream.h" -#include "QXmppNonSASLAuth.h" - -// IQ types -#include "QXmppArchiveIq.h" -#include "QXmppByteStreamIq.h" -#include "QXmppDiscoveryIq.h" -#include "QXmppIbbIq.h" -#include "QXmppJingleIq.h" -#include "QXmppMucIq.h" -#include "QXmppPingIq.h" -#include "QXmppRpcIq.h" -#include "QXmppRosterIq.h" -#include "QXmppStreamInitiationIq.h" -#include "QXmppVCard.h" -#include "QXmppVersionIq.h" - -#include <QCoreApplication> -#include <QDomDocument> -#include <QStringList> -#include <QRegExp> -#include <QHostAddress> -#include <QXmlStreamWriter> -#include <QTimer> - -static const QString capabilitiesNode = "http://code.google.com/p/qxmpp"; -static const QByteArray streamRootElementStart = "<?xml version=\"1.0\"?><stream:stream xmlns:stream=\"http://etherx.jabber.org/streams\" version=\"1.0\" xmlns=\"jabber:client\" xml:lang=\"en\" xmlns:xml=\"http://www.w3.org/XML/1998/namespace\">\n"; -static const QByteArray streamRootElementEnd = "</stream:stream>"; - -class QXmppStreamPrivate -{ -public: - QSslSocket socket; - QAbstractSocket::SocketError socketError; -}; - -QXmppStream::QXmppStream(QObject *parent) - : QObject(parent), - m_logger(0), - m_sessionAvailable(false), - m_authStep(0), - d(new QXmppStreamPrivate) -{ - // Make sure the random number generator is seeded - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); - - // initialise logger - setLogger(QXmppLogger::getLogger()); - - bool check = QObject::connect(&d->socket, SIGNAL(hostFound()), - this, SLOT(socketHostFound())); - Q_ASSERT(check); - check = QObject::connect(&d->socket, SIGNAL(connected()), - this, SLOT(socketConnected())); - Q_ASSERT(check); - check = QObject::connect(&d->socket, SIGNAL(disconnected()), - this, SLOT(socketDisconnected())); - Q_ASSERT(check); - check = QObject::connect(&d->socket, SIGNAL(readyRead()), - this, SLOT(socketReadReady())); - Q_ASSERT(check); - check = QObject::connect(&d->socket, SIGNAL(encrypted()), - this, SLOT(socketEncrypted())); - Q_ASSERT(check); - check = QObject::connect(&d->socket, - SIGNAL(sslErrors(const QList<QSslError>&)), this, - SLOT(socketSslErrors(const QList<QSslError>&))); - Q_ASSERT(check); - check = QObject::connect(&d->socket, - SIGNAL(error(QAbstractSocket::SocketError)), this, - SLOT(socketError(QAbstractSocket::SocketError))); - Q_ASSERT(check); - - // XEP-0199: XMPP Ping - m_pingTimer = new QTimer(this); - check = QObject::connect(m_pingTimer, SIGNAL(timeout()), this, SLOT(pingSend())); - Q_ASSERT(check); - - m_timeoutTimer = new QTimer(this); - m_timeoutTimer->setSingleShot(true); - check = QObject::connect(m_timeoutTimer, SIGNAL(timeout()), this, SLOT(pingTimeout())); - Q_ASSERT(check); - - check = QObject::connect(this, SIGNAL(xmppConnected()), this, SLOT(pingStart())); - Q_ASSERT(check); - - check = QObject::connect(this, SIGNAL(disconnected()), this, SLOT(pingStop())); - Q_ASSERT(check); -} - -QXmppStream::~QXmppStream() -{ - delete d; -} - -QXmppConfiguration& QXmppStream::configuration() -{ - return m_config; -} - -void QXmppStream::connect() -{ - info(QString("Connecting to: %1:%2").arg(configuration(). - host()).arg(configuration().port())); - - // prepare for connection - m_authStep = 0; - - d->socket.setProxy(configuration().networkProxy()); - d->socket.connectToHost(configuration(). - host(), configuration().port()); -} - -void QXmppStream::socketSslErrors(const QList<QSslError> & error) -{ - warning("SSL errors"); - for(int i = 0; i< error.count(); ++i) - warning(error.at(i).errorString()); - - if (configuration().ignoreSslErrors()) - d->socket.ignoreSslErrors(); -} - -void QXmppStream::socketHostFound() -{ - debug("Host found"); - emit hostFound(); -} - -void QXmppStream::socketConnected() -{ - flushDataBuffer(); - info("Connected"); - emit connected(); - sendStartStream(); -} - -void QXmppStream::socketDisconnected() -{ - flushDataBuffer(); - info("Disconnected"); - emit disconnected(); -} - -void QXmppStream::socketEncrypted() -{ - debug("Encrypted"); - sendStartStream(); -} - -void QXmppStream::socketError(QAbstractSocket::SocketError ee) -{ - d->socketError = ee; - emit error(QXmppClient::SocketError); - warning(QString("Socket error: " + d->socket.errorString())); -} - -void QXmppStream::socketReadReady() -{ - const QByteArray data = d->socket.readAll(); - //debug("SERVER [COULD BE PARTIAL DATA]:" + data.left(20)); - parser(data); -} - -void QXmppStream::sendNonSASLAuthQuery( const QString &to ) -{ - QXmppNonSASLAuthTypesRequestIq authQuery; - authQuery.setTo(to); - authQuery.setUsername(configuration().user()); - - sendPacket(authQuery); -} - -/// Returns the QXmppLogger associated with the current QXmppStream. - -QXmppLogger *QXmppStream::logger() -{ - return m_logger; -} - -/// Sets the QXmppLogger associated with the current QXmppStream. - -void QXmppStream::setLogger(QXmppLogger *logger) -{ - if (m_logger) - QObject::disconnect(this, SIGNAL(logMessage(QXmppLogger::MessageType, QString)), - m_logger, SLOT(log(QXmppLogger::MessageType, QString))); - m_logger = logger; - if (m_logger) - QObject::connect(this, SIGNAL(logMessage(QXmppLogger::MessageType, QString)), - m_logger, SLOT(log(QXmppLogger::MessageType, QString))); -} - -void QXmppStream::debug(const QString &data) -{ - emit logMessage(QXmppLogger::DebugMessage, data); -} - -void QXmppStream::info(const QString &data) -{ - emit logMessage(QXmppLogger::InformationMessage, data); -} - -void QXmppStream::warning(const QString &data) -{ - emit logMessage(QXmppLogger::WarningMessage, data); -} - -void QXmppStream::parser(const QByteArray& data) -{ - QDomDocument doc; - QByteArray completeXml; - - m_dataBuffer = m_dataBuffer + data; - - if(hasStartStreamElement(m_dataBuffer)) - { - completeXml = m_dataBuffer + streamRootElementEnd; - } - else if(hasEndStreamElement(data)) - { - completeXml = streamRootElementStart + m_dataBuffer; - } - else - { - completeXml = streamRootElementStart + m_dataBuffer + streamRootElementEnd; - } - - if(doc.setContent(completeXml, true)) - { - emit logMessage(QXmppLogger::ReceivedMessage, QString::fromUtf8(m_dataBuffer)); - flushDataBuffer(); - - QDomElement nodeRecv = doc.documentElement().firstChildElement(); - - if(nodeRecv.isNull()) - { - QDomElement streamElement = doc.documentElement(); - if(m_streamId.isEmpty()) - m_streamId = streamElement.attribute("id"); - if(m_XMPPVersion.isEmpty()) - { - m_XMPPVersion = streamElement.attribute("version"); - if(m_XMPPVersion.isEmpty()) - { - // no version specified, signals XMPP Version < 1.0. - // switch to old auth mechanism - sendNonSASLAuthQuery(doc.documentElement().attribute("from")); - } - } - } - else - { - //TODO: Make a login error here. - } - while(!nodeRecv.isNull()) - { - - QString ns = nodeRecv.namespaceURI(); - - // if we receive any kind of data, stop the timeout timer - m_timeoutTimer->stop(); - - bool handled = false; - emit elementReceived(nodeRecv, handled); - - if(handled) - { - // already handled by client, do nothing - } - else if(ns == ns_stream && nodeRecv.tagName() == "features") - { - bool nonSaslAvailable = nodeRecv.firstChildElement("auth"). - namespaceURI() == ns_authFeature; - bool saslAvailable = nodeRecv.firstChildElement("mechanisms"). - namespaceURI() == ns_sasl; - bool useSasl = configuration().useSASLAuthentication(); - - if (!d->socket.isEncrypted()) - { - // parse remote TLS mode - QXmppConfiguration::StreamSecurityMode remoteSecurity; - QDomElement tlsElement = nodeRecv.firstChildElement("starttls"); - if (tlsElement.namespaceURI() == ns_tls) - { - if (tlsElement.firstChildElement().tagName() == "required") - remoteSecurity = QXmppConfiguration::TLSRequired; - else - remoteSecurity = QXmppConfiguration::TLSEnabled; - } else { - remoteSecurity = QXmppConfiguration::TLSDisabled; - } - - // determine TLS mode to use - const QXmppConfiguration::StreamSecurityMode localSecurity = configuration().streamSecurityMode(); - if (!d->socket.supportsSsl() && - (localSecurity == QXmppConfiguration::TLSRequired || - remoteSecurity == QXmppConfiguration::TLSRequired)) - { - warning("Disconnecting as TLS is required, but SSL support is not available"); - disconnect(); - return; - } - if (localSecurity == QXmppConfiguration::TLSRequired && - remoteSecurity == QXmppConfiguration::TLSDisabled) - { - warning("Disconnecting as TLS is required, but not supported by the server"); - disconnect(); - return; - } - - if (d->socket.supportsSsl() && - (remoteSecurity == QXmppConfiguration::TLSRequired || - localSecurity != QXmppConfiguration::TLSDisabled)) - { - // enable TLS as it is required by the server - // or supported by the client - sendToServer("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"); - return; - } - } - - if((saslAvailable && nonSaslAvailable && !useSasl) || - (!saslAvailable && nonSaslAvailable)) - { - sendNonSASLAuthQuery(doc.documentElement().attribute("from")); - } - else if(saslAvailable) - { - // parse advertised SASL Authentication mechanisms - QList<QXmppConfiguration::SASLAuthMechanism> mechanisms; - QDomElement element = nodeRecv.firstChildElement("mechanisms"); - QDomElement subElement = element.firstChildElement("mechanism"); - debug("SASL Authentication mechanisms:"); - while(!subElement.isNull()) - { - debug(subElement.text()); - if (subElement.text() == QLatin1String("PLAIN")) - mechanisms << QXmppConfiguration::SASLPlain; - else if (subElement.text() == QLatin1String("DIGEST-MD5")) - mechanisms << QXmppConfiguration::SASLDigestMD5; - else if (subElement.text() == QLatin1String("ANONYMOUS")) - mechanisms << QXmppConfiguration::SASLAnonymous; - subElement = subElement.nextSiblingElement("mechanism"); - } - - // determine SASL Authentication mechanism to use - QXmppConfiguration::SASLAuthMechanism mechanism = configuration().sASLAuthMechanism(); - if (mechanisms.isEmpty()) - { - warning("No supported SASL Authentication mechanism available"); - disconnect(); - return; - } - else if (!mechanisms.contains(mechanism)) - { - info("Desired SASL Auth mechanism is not available, selecting first available one"); - mechanism = mechanisms.first(); - } - - // send SASL Authentication request - switch(mechanism) - { - case QXmppConfiguration::SASLPlain: - { - QString userPass('\0' + configuration().user() + - '\0' + configuration().passwd()); - QByteArray data = "<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>"; - data += userPass.toUtf8().toBase64(); - data += "</auth>"; - sendToServer(data); - } - break; - case QXmppConfiguration::SASLDigestMD5: - sendToServer("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>"); - break; - case QXmppConfiguration::SASLAnonymous: - sendToServer("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>"); - break; - } - } - - if(nodeRecv.firstChildElement("bind"). - namespaceURI() == ns_bind) - { - sendBindIQ(); - } - - if(nodeRecv.firstChildElement("session"). - namespaceURI() == ns_session) - { - m_sessionAvailable = true; - } - } - else if(ns == ns_stream && nodeRecv.tagName() == "error") - { - if (!nodeRecv.firstChildElement("conflict").isNull()) - m_xmppStreamError = QXmppStanza::Error::Conflict; - else - m_xmppStreamError = QXmppStanza::Error::UndefinedCondition; - emit error(QXmppClient::XmppStreamError); - } - else if(ns == ns_tls) - { - if(nodeRecv.tagName() == "proceed") - { - debug("Starting encryption"); - d->socket.startClientEncryption(); - return; - } - } - else if(ns == ns_sasl) - { - if(nodeRecv.tagName() == "success") - { - debug("Authenticated"); - sendStartStream(); - } - else if(nodeRecv.tagName() == "challenge") - { - // TODO: Track which mechanism was used for when other SASL protocols which use challenges are supported - m_authStep++; - switch (m_authStep) - { - case 1 : - sendAuthDigestMD5ResponseStep1(nodeRecv.text()); - break; - case 2 : - sendAuthDigestMD5ResponseStep2(); - break; - default : - warning("Too many authentication steps"); - disconnect(); - break; - } - } - else if(nodeRecv.tagName() == "failure") - { - if (!nodeRecv.firstChildElement("not-authorized").isNull()) - m_xmppStreamError = QXmppStanza::Error::NotAuthorized; - else - m_xmppStreamError = QXmppStanza::Error::UndefinedCondition; - emit error(QXmppClient::XmppStreamError); - - warning("Authentication failure"); - disconnect(); - } - } - else if(ns == ns_client) - { - - if(nodeRecv.tagName() == "iq") - { - QDomElement element = nodeRecv.firstChildElement(); - QString id = nodeRecv.attribute("id"); - QString type = nodeRecv.attribute("type"); - if(type.isEmpty()) - warning("QXmppStream: iq type can't be empty"); - - if(id == m_sessionId) - { - QXmppSession session; - session.parse(nodeRecv); - - // get back add configuration whether to send - // roster and intial presence in beginning - // process SessionIq - - // xmpp connection made - emit xmppConnected(); - } - else if(QXmppBind::isBind(nodeRecv) && id == m_bindId) - { - QXmppBind bind; - bind.parse(nodeRecv); - - // bind result - if (bind.type() == QXmppIq::Result) - { - if (!bind.jid().isEmpty()) - { - QRegExp jidRegex("^([^@/]+)@([^@/]+)/(.+)$"); - if (jidRegex.exactMatch(bind.jid())) - { - configuration().setUser(jidRegex.cap(1)); - configuration().setDomain(jidRegex.cap(2)); - configuration().setResource(jidRegex.cap(3)); - } else { - warning("Bind IQ received with invalid JID: " + bind.jid()); - } - } - if (m_sessionAvailable) - sendSessionIQ(); - } - } - else if(QXmppRosterIq::isRosterIq(nodeRecv)) - { - QXmppRosterIq rosterIq; - rosterIq.parse(nodeRecv); - emit rosterIqReceived(rosterIq); - } - // extensions - - // XEP-0009: Jabber-RPC - else if(QXmppRpcInvokeIq::isRpcInvokeIq(nodeRecv)) - { - QXmppRpcInvokeIq rpcIqPacket; - rpcIqPacket.parse(nodeRecv); - emit rpcCallInvoke(rpcIqPacket); - } - else if(QXmppRpcResponseIq::isRpcResponseIq(nodeRecv)) - { - QXmppRpcResponseIq rpcResponseIq; - rpcResponseIq.parse(nodeRecv); - emit rpcCallResponse(rpcResponseIq); - } - else if(QXmppRpcErrorIq::isRpcErrorIq(nodeRecv)) - { - QXmppRpcErrorIq rpcErrorIq; - rpcErrorIq.parse(nodeRecv); - emit rpcCallError(rpcErrorIq); - } - - // XEP-0030: Service Discovery - else if(QXmppDiscoveryIq::isDiscoveryIq(nodeRecv)) - { - QXmppDiscoveryIq discoIq; - discoIq.parse(nodeRecv); - - if (discoIq.type() == QXmppIq::Get && - discoIq.queryType() == QXmppDiscoveryIq::InfoQuery && - (discoIq.queryNode().isEmpty() || discoIq.queryNode().startsWith(capabilitiesNode))) - { - // respond to info query - QXmppDiscoveryIq qxmppFeatures = capabilities(); - qxmppFeatures.setId(discoIq.id()); - qxmppFeatures.setTo(discoIq.from()); - qxmppFeatures.setQueryNode(discoIq.queryNode()); - sendPacket(qxmppFeatures); - } else { - emit discoveryIqReceived(discoIq); - } - } - // XEP-0045: Multi-User Chat - else if (QXmppMucAdminIq::isMucAdminIq(nodeRecv)) - { - QXmppMucAdminIq mucIq; - mucIq.parse(nodeRecv); - emit mucAdminIqReceived(mucIq); - } - else if (QXmppMucOwnerIq::isMucOwnerIq(nodeRecv)) - { - QXmppMucOwnerIq mucIq; - mucIq.parse(nodeRecv); - emit mucOwnerIqReceived(mucIq); - } - // XEP-0047 In-Band Bytestreams - else if(QXmppIbbCloseIq::isIbbCloseIq(nodeRecv)) - { - QXmppIbbCloseIq ibbCloseIq; - ibbCloseIq.parse(nodeRecv); - emit ibbCloseIqReceived(ibbCloseIq); - } - else if(QXmppIbbDataIq::isIbbDataIq(nodeRecv)) - { - QXmppIbbDataIq ibbDataIq; - ibbDataIq.parse(nodeRecv); - emit ibbDataIqReceived(ibbDataIq); - } - else if(QXmppIbbOpenIq::isIbbOpenIq(nodeRecv)) - { - QXmppIbbOpenIq ibbOpenIq; - ibbOpenIq.parse(nodeRecv); - emit ibbOpenIqReceived(ibbOpenIq); - } - // XEP-0054: vcard-temp - else if(nodeRecv.firstChildElement("vCard"). - namespaceURI() == ns_vcard) - { - QXmppVCard vcardIq; - vcardIq.parse(nodeRecv); - emit vCardIqReceived(vcardIq); - } - // XEP-0065: SOCKS5 Bytestreams - else if(QXmppByteStreamIq::isByteStreamIq(nodeRecv)) - { - QXmppByteStreamIq byteStreamIq; - byteStreamIq.parse(nodeRecv); - emit byteStreamIqReceived(byteStreamIq); - } - // XEP-0078: Non-SASL Authentication - else if(id == m_nonSASLAuthId && type == "result") - { - // successful Non-SASL Authentication - debug("Authenticated (Non-SASL)"); - - // xmpp connection made - emit xmppConnected(); - } - else if(nodeRecv.firstChildElement("query"). - namespaceURI() == ns_auth) - { - if(type == "result") - { - bool digest = !nodeRecv.firstChildElement("query"). - firstChildElement("digest").isNull(); - bool plain = !nodeRecv.firstChildElement("query"). - firstChildElement("password").isNull(); - bool plainText = false; - - if(plain && digest) - { - if(configuration().nonSASLAuthMechanism() == - QXmppConfiguration::NonSASLDigest) - plainText = false; - else - plainText = true; - } - else if(plain) - plainText = true; - else if(digest) - plainText = false; - else - { - //TODO Login error - return; - } - sendNonSASLAuth(plainText); - } - } - // XEP-0092: Software Version - else if(QXmppVersionIq::isVersionIq(nodeRecv)) - { - QXmppVersionIq versionIq; - versionIq.parse(nodeRecv); - - if (versionIq.type() == QXmppIq::Get) - { - // respond to query - QXmppVersionIq responseIq; - responseIq.setType(QXmppIq::Result); - responseIq.setId(versionIq.id()); - responseIq.setTo(versionIq.from()); - responseIq.setName(qApp->applicationName()); - responseIq.setVersion(qApp->applicationVersion()); - sendPacket(responseIq); - } else { - emit iqReceived(versionIq); - } - - } - // XEP-0095: Stream Initiation - else if(QXmppStreamInitiationIq::isStreamInitiationIq(nodeRecv)) - { - QXmppStreamInitiationIq siIq; - siIq.parse(nodeRecv); - emit streamInitiationIqReceived(siIq); - } - // XEP-0136: Message Archiving - else if(QXmppArchiveChatIq::isArchiveChatIq(nodeRecv)) - { - QXmppArchiveChatIq archiveIq; - archiveIq.parse(nodeRecv); - emit archiveChatIqReceived(archiveIq); - } - else if(QXmppArchiveListIq::isArchiveListIq(nodeRecv)) - { - QXmppArchiveListIq archiveIq; - archiveIq.parse(nodeRecv); - emit archiveListIqReceived(archiveIq); - } - else if(QXmppArchivePrefIq::isArchivePrefIq(nodeRecv)) - { - QXmppArchivePrefIq archiveIq; - archiveIq.parse(nodeRecv); - emit archivePrefIqReceived(archiveIq); - } - // XEP-0166: Jingle - else if(QXmppJingleIq::isJingleIq(nodeRecv)) - { - QXmppJingleIq jingleIq; - jingleIq.parse(nodeRecv); - emit jingleIqReceived(jingleIq); - } - // XEP-0199: XMPP Ping - else if(QXmppPingIq::isPingIq(nodeRecv)) - { - QXmppPingIq req; - req.parse(nodeRecv); - - QXmppIq iq(QXmppIq::Result); - iq.setId(req.id()); - iq.setTo(req.from()); - iq.setFrom(req.to()); - sendPacket(iq); - } - else - { - QXmppIq iqPacket; - iqPacket.parse(nodeRecv); - - // if we didn't understant the iq, reply with error - // except for "result" and "error" iqs - if (type != "result" && type != "error") - { - QXmppIq iq(QXmppIq::Error); - iq.setId(iqPacket.id()); - iq.setTo(iqPacket.from()); - iq.setFrom(iqPacket.to()); - QXmppStanza::Error error(QXmppStanza::Error::Cancel, - QXmppStanza::Error::FeatureNotImplemented); - iq.setError(error); - sendPacket(iq); - } else { - emit iqReceived(iqPacket); - } - } - } - else if(nodeRecv.tagName() == "presence") - { - QXmppPresence presence; - presence.parse(nodeRecv); - - // emit presence - emit presenceReceived(presence); - } - else if(nodeRecv.tagName() == "message") - { - QXmppMessage message; - message.parse(nodeRecv); - - // emit message - emit messageReceived(message); - } - } - nodeRecv = nodeRecv.nextSiblingElement(); - } - } - else - { - //wait for complete packet - } -} - - -void QXmppStream::sendStartStream() -{ - QByteArray data = "<?xml version='1.0'?><stream:stream to='"; - data.append(configuration().domain()); - data.append("' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>"); - sendToServer(data); -} - -bool QXmppStream::sendToServer(const QByteArray& packet) -{ - emit logMessage(QXmppLogger::SentMessage, QString::fromUtf8(packet)); - if (!isConnected()) - return false; - return d->socket.write( packet ) == packet.size(); -} - -bool QXmppStream::hasStartStreamElement(const QByteArray& data) -{ - QString str(data); - QRegExp regex("^(<\\?xml.*\\?>)?\\s*<stream:stream.*>"); - regex.setMinimal(true); - return str.contains(regex); -} - -bool QXmppStream::hasEndStreamElement(const QByteArray& data) -{ - QString str(data); - QRegExp regex("</stream:stream>$"); - regex.setMinimal(true); - return str.contains(regex); -} - -void QXmppStream::sendNonSASLAuth(bool plainText) -{ - QXmppNonSASLAuthIq authQuery; - authQuery.setUsername(configuration().user()); - authQuery.setPassword(configuration().passwd()); - authQuery.setResource(configuration().resource()); - authQuery.setStreamId(m_streamId); - authQuery.setUsePlainText(plainText); - m_nonSASLAuthId = authQuery.id(); - sendPacket(authQuery); -} - -// challenge is BASE64 encoded string -void QXmppStream::sendAuthDigestMD5ResponseStep1(const QString& challenge) -{ - QByteArray ba = QByteArray::fromBase64(challenge.toUtf8()); - - QMap<QByteArray, QByteArray> map; - - QByteArray key; - QByteArray value; - bool parsingValue = false; - int startindex = 0; - for(int i = 0; i < ba.length(); i++) - { - char next = ba.at(i); - switch (next) { - case '=': - if (!parsingValue) - { - // Trim the key, but do not trim the value as it is in delimiters - key = ba.mid(startindex, i - startindex).trimmed(); - // Skip the equals and delimiter - startindex = i + 2; - } - break; - case '"': - // Ignore the opening delimiter - if (startindex != (i + 1)) - { - value = ba.mid(startindex, i - startindex); - map[key] = value; - debug(key + ":" + value); - // Skip the comma - i += 2; - startindex = i; - parsingValue = false; - } - else { - parsingValue = true; - } - - break; - - default: - break; - } - } - - if (!map.contains("nonce")) - { - warning("sendAuthDigestMD5ResponseStep1: Invalid input"); - disconnect(); - return; - } - - QByteArray user = configuration().user().toUtf8(); - QByteArray passwd = configuration().passwd().toUtf8(); - QByteArray domain = configuration().domain().toUtf8(); - QByteArray realm; - if(map.contains("realm")) - realm = map["realm"]; - - QByteArray response; - - QByteArray cnonce(32, 'm'); - for(int n = 0; n < cnonce.size(); ++n) - cnonce[n] = (char)(256.0*qrand()/(RAND_MAX+1.0)); - - // The random data can the '=' char is not valid as it is a delimiter, - // so to be safe, base64 the nonce - cnonce = cnonce.toBase64(); - - QByteArray nc = "00000001"; - QByteArray digest_uri = "xmpp/" + domain; - - QByteArray a1 = user + ':' + realm + ':' + passwd; - QByteArray ha1 = QCryptographicHash::hash(a1, QCryptographicHash::Md5); - ha1 += ':' + map["nonce"] + ':' + cnonce; - - if(map.contains("authzid")) - ha1 += ':' + map["authzid"]; - - QByteArray A1(ha1); - QByteArray A2 = "AUTHENTICATE:" + digest_uri; - QByteArray HA1 = QCryptographicHash::hash(A1, QCryptographicHash::Md5).toHex(); - QByteArray HA2 = QCryptographicHash::hash(A2, QCryptographicHash::Md5).toHex(); - QByteArray KD = HA1 + ':' + map["nonce"] + ':' + nc + ':' + cnonce + ':' - + "auth" + ':' + HA2; - QByteArray Z = QCryptographicHash::hash(KD, QCryptographicHash::Md5).toHex(); - - response += "username=\"" + user + "\","; - - if(!realm.isEmpty()) - response += "realm=\"" + realm + "\","; - - response += "nonce=\"" + map["nonce"] + "\","; - response += "cnonce=\"" + cnonce + "\","; - response += "nc=" + nc + ","; - response += "qop=auth,"; - response += "digest-uri=\"" + digest_uri + "\","; - response += "response=" + Z + ","; - if(map.contains("authzid")) - response += "authzid=\"" + map["authzid"] + "\","; - response += "charset=utf-8"; - - debug(response); - QByteArray packet = "<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>" - + response.toBase64() + "</response>"; - sendToServer(packet); -} - -void QXmppStream::sendAuthDigestMD5ResponseStep2() -{ - sendToServer("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>"); -} - -void QXmppStream::sendBindIQ() -{ - QXmppBind bind(QXmppIq::Set); - bind.setResource(configuration().resource()); - m_bindId = bind.id(); - sendPacket(bind); -} - -void QXmppStream::sendSessionIQ() -{ - QXmppSession session(QXmppIq::Set); - session.setTo(configuration().domain()); - m_sessionId = session.id(); - sendPacket(session); -} - -void QXmppStream::acceptSubscriptionRequest(const QString& from, bool accept) -{ - QXmppPresence presence; - presence.setTo(from); - if(accept) - presence.setType(QXmppPresence::Subscribed); - else - presence.setType(QXmppPresence::Unsubscribed); - - sendPacket(presence); -} - -void QXmppStream::sendSubscriptionRequest(const QString& to) -{ - if(to.isEmpty()) - return; - - QXmppPresence presence; - presence.setTo(to); - presence.setType(QXmppPresence::Subscribe); - sendPacket(presence); -} - -void QXmppStream::disconnect() -{ - m_authStep = 0; - sendEndStream(); - d->socket.flush(); - d->socket.disconnectFromHost(); -} - -bool QXmppStream::isConnected() const -{ - return d->socket.state() == QAbstractSocket::ConnectedState; -} - -bool QXmppStream::sendPacket(const QXmppPacket& packet) -{ - // prepare packet - QByteArray data; - QXmlStreamWriter xmlStream(&data); - packet.toXml(&xmlStream); - - // send packet - return sendToServer(data); -} - -void QXmppStream::sendEndStream() -{ - sendToServer(streamRootElementEnd); -} - -void QXmppStream::pingStart() -{ - const int interval = configuration().keepAliveInterval(); - // start ping timer - if (interval > 0) - { - m_pingTimer->setInterval(interval * 1000); - m_pingTimer->start(); - } -} - -void QXmppStream::pingStop() -{ - // stop all timers - m_pingTimer->stop(); - m_timeoutTimer->stop(); -} - -void QXmppStream::pingSend() -{ - // send ping packet - QXmppPingIq ping; - ping.setFrom(configuration().jid()); - ping.setTo(configuration().domain()); - sendPacket(ping); - - // start timeout timer - const int timeout = configuration().keepAliveTimeout(); - if (timeout > 0) - { - m_timeoutTimer->setInterval(timeout * 1000); - m_timeoutTimer->start(); - } -} - -void QXmppStream::pingTimeout() -{ - warning("Ping timeout"); - disconnect(); - emit error(QXmppClient::KeepAliveError); -} - -QAbstractSocket::SocketError QXmppStream::socketError() -{ - return d->socketError; -} - -QXmppStanza::Error::Condition QXmppStream::xmppStreamError() -{ - return m_xmppStreamError; -} - -void QXmppStream::flushDataBuffer() -{ - m_dataBuffer.clear(); -} - -QXmppDiscoveryIq QXmppStream::capabilities() const -{ - QXmppDiscoveryIq iq; - iq.setType(QXmppIq::Result); - iq.setQueryType(QXmppDiscoveryIq::InfoQuery); - - // features - QStringList features; - features - << ns_rpc // XEP-0009: Jabber-RPC - << ns_disco_info // XEP-0030: Service Discovery - << ns_ibb // XEP-0047: In-Band Bytestreams - << ns_vcard // XEP-0054: vcard-temp - << ns_bytestreams // XEP-0065: SOCKS5 Bytestreams - << ns_chat_states // XEP-0085: Chat State Notifications - << ns_version // XEP-0092: Software Version - << ns_stream_initiation // XEP-0095: Stream Initiation - << ns_stream_initiation_file_transfer // XEP-0096: SI File Transfer - << ns_capabilities // XEP-0115 : Entity Capabilities - << ns_jingle // XEP-0166 : Jingle - << ns_jingle_rtp // XEP-0167 : Jingle RTP Sessions - << ns_jingle_rtp_audio - << ns_jingle_ice_udp // XEP-0176 : Jingle ICE-UDP Transport Method - << ns_ping; // XEP-0199: XMPP Ping - iq.setFeatures(features); - - // identities - QList<QXmppDiscoveryIq::Identity> identities; - QXmppDiscoveryIq::Identity identity; - - identity.setCategory("automation"); - identity.setType("rpc"); - identities.append(identity); - - identity.setCategory("client"); - identity.setType("pc"); - identity.setName(QString("%1 %2").arg(qApp->applicationName(), qApp->applicationVersion())); - identities.append(identity); - - iq.setIdentities(identities); - return iq; -} - -QXmppElementList QXmppStream::presenceExtensions() const -{ - QXmppElementList extensions; - - QXmppElement caps; - caps.setTagName("c"); - caps.setAttribute("xmlns", ns_capabilities); - caps.setAttribute("hash", "sha-1"); - caps.setAttribute("node", capabilitiesNode); - caps.setAttribute("ver", capabilities().verificationString().toBase64()); - extensions << caps; - - return extensions; -} - diff --git a/source/QXmppStream.h b/source/QXmppStream.h deleted file mode 100644 index 139635e0..00000000 --- a/source/QXmppStream.h +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPSTREAM_H -#define QXMPPSTREAM_H - -#include <QObject> -#include <QSslSocket> -#include "QXmppClient.h" -#include "QXmppConfiguration.h" -#include "QXmppLogger.h" -#include "QXmppStanza.h" - -class QDomElement; -class QTimer; - -class QXmppClient; -class QXmppPacket; -class QXmppPresence; -class QXmppIq; -class QXmppBind; -class QXmppRosterIq; -class QXmppVCard; -class QXmppMessage; -class QXmppRpcResponseIq; -class QXmppRpcErrorIq; -class QXmppArchiveChatIq; -class QXmppArchiveListIq; -class QXmppArchivePrefIq; -class QXmppByteStreamIq; -class QXmppDiscoveryIq; -class QXmppIbbCloseIq; -class QXmppIbbDataIq; -class QXmppIbbOpenIq; -class QXmppJingleIq; -class QXmppMucAdminIq; -class QXmppMucOwnerIq; -class QXmppStreamInitiationIq; -class QXmppStreamPrivate; -class QXmppVersionIq; - -class QXmppStream : public QObject -{ - Q_OBJECT - -public: - QXmppStream(QObject *parent); - ~QXmppStream(); - void connect(); - void acceptSubscriptionRequest(const QString& from, bool accept = true); - void sendSubscriptionRequest(const QString& to); - void disconnect(); - bool isConnected() const; - bool sendPacket(const QXmppPacket&); - - QAbstractSocket::SocketError socketError(); - QXmppStanza::Error::Condition xmppStreamError(); - - QXmppConfiguration& configuration(); - - QXmppLogger *logger(); - void setLogger(QXmppLogger *logger); - - QXmppElementList presenceExtensions() const; - -signals: - // socket host found - void hostFound(); - - // socket connected - void connected(); - - // socket disconnected - void disconnected(); - - // xmpp connected - void xmppConnected(); - - /// This signal is emitted to send logging messages. - void logMessage(QXmppLogger::MessageType type, const QString &msg); - - void error(QXmppClient::Error); - void elementReceived(const QDomElement &element, bool &handled); - void presenceReceived(const QXmppPresence&); - void messageReceived(const QXmppMessage&); - void iqReceived(const QXmppIq&); - void rosterIqReceived(const QXmppRosterIq&); - void vCardIqReceived(const QXmppVCard&); - - void rpcCallInvoke(const QXmppRpcInvokeIq &invoke); - void rpcCallResponse(const QXmppRpcResponseIq& result); - void rpcCallError(const QXmppRpcErrorIq &err); - - void archiveChatIqReceived(const QXmppArchiveChatIq&); - void archiveListIqReceived(const QXmppArchiveListIq&); - void archivePrefIqReceived(const QXmppArchivePrefIq&); - - void discoveryIqReceived(const QXmppDiscoveryIq&); - - void byteStreamIqReceived(const QXmppByteStreamIq&); - void ibbCloseIqReceived(const QXmppIbbCloseIq&); - void ibbDataIqReceived(const QXmppIbbDataIq&); - void ibbOpenIqReceived(const QXmppIbbOpenIq&); - void streamInitiationIqReceived(const QXmppStreamInitiationIq&); - - // XEP-0045: Multi-User Chat - void mucAdminIqReceived(const QXmppMucAdminIq&); - void mucOwnerIqReceived(const QXmppMucOwnerIq&); - - // XEP-0166: Jingle - void jingleIqReceived(const QXmppJingleIq&); - -private slots: - void socketHostFound(); - void socketReadReady(); - void socketEncrypted(); - void socketConnected(); - void socketDisconnected(); - void socketError(QAbstractSocket::SocketError); - void socketSslErrors(const QList<QSslError>&); - - void pingStart(); - void pingStop(); - void pingSend(); - void pingTimeout(); - -private: - QXmppConfiguration m_config; ///< This object provides the configuration - ///< required for connecting to the XMPP server. - QXmppLogger* m_logger; - QString m_sessionId; - QString m_bindId; - QByteArray m_dataBuffer; - bool m_sessionAvailable; - QString m_streamId; - QString m_nonSASLAuthId; - QString m_XMPPVersion; - QXmppStanza::Error::Condition m_xmppStreamError; - QTimer *m_pingTimer; - QTimer *m_timeoutTimer; - - int m_authStep; - - QXmppDiscoveryIq capabilities() const; - void debug(const QString&); - void info(const QString&); - void warning(const QString&); - void parser(const QByteArray&); - void sendStartStream(); - void sendEndStream(); - void sendNonSASLAuth(bool); - void sendNonSASLAuthQuery( const QString &to ); - void sendAuthDigestMD5ResponseStep1(const QString& challenge); - void sendAuthDigestMD5ResponseStep2(); - void sendBindIQ(); - void sendSessionIQ(); - void sendRosterRequest(); - bool sendToServer(const QByteArray&); - bool hasStartStreamElement(const QByteArray&); - bool hasEndStreamElement(const QByteArray&); - - void flushDataBuffer(); - - QXmppStreamPrivate * const d; -}; - -#endif // QXMPPSTREAM_H diff --git a/source/QXmppStreamInitiationIq.cpp b/source/QXmppStreamInitiationIq.cpp deleted file mode 100644 index 4d062e59..00000000 --- a/source/QXmppStreamInitiationIq.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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 "QXmppConstants.h" -#include "QXmppStreamInitiationIq.h" -#include "QXmppUtils.h" - -QString QXmppStreamInitiationIq::mimeType() const -{ - return m_mimeType; -} - -void QXmppStreamInitiationIq::setMimeType(const QString &mimeType) -{ - m_mimeType = mimeType; -} - -QXmppStreamInitiationIq::Profile QXmppStreamInitiationIq::profile() const -{ - return m_profile; -} - -void QXmppStreamInitiationIq::setProfile(QXmppStreamInitiationIq::Profile profile) -{ - m_profile = profile; -} - -QXmppElementList QXmppStreamInitiationIq::siItems() const -{ - return m_siItems; -} - -QString QXmppStreamInitiationIq::siId() const -{ - return m_siId; -} - -void QXmppStreamInitiationIq::setSiId(const QString &id) -{ - m_siId = id; -} - -void QXmppStreamInitiationIq::setSiItems(const QXmppElementList &items) -{ - m_siItems = items; -} - -bool QXmppStreamInitiationIq::isStreamInitiationIq(const QDomElement &element) -{ - QDomElement siElement = element.firstChildElement("si"); - return (siElement.namespaceURI() == ns_stream_initiation); -} - -void QXmppStreamInitiationIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement siElement = element.firstChildElement("si"); - m_siId = siElement.attribute("id"); - m_mimeType = siElement.attribute("mime-type"); - if (siElement.attribute("profile") == ns_stream_initiation_file_transfer) - m_profile = FileTransfer; - else - m_profile = None; - - QDomElement itemElement = siElement.firstChildElement(); - while (!itemElement.isNull()) - { - m_siItems.append(QXmppElement(itemElement)); - itemElement = itemElement.nextSiblingElement(); - } -} - -void QXmppStreamInitiationIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("si"); - helperToXmlAddAttribute(writer, "xmlns", ns_stream_initiation); - helperToXmlAddAttribute(writer, "id", m_siId); - helperToXmlAddAttribute(writer, "mime-type", m_mimeType); - if (m_profile == FileTransfer) - helperToXmlAddAttribute(writer, "profile", ns_stream_initiation_file_transfer); - foreach (const QXmppElement &item, m_siItems) - item.toXml(writer); - writer->writeEndElement(); -} - diff --git a/source/QXmppStreamInitiationIq.h b/source/QXmppStreamInitiationIq.h deleted file mode 100644 index 81d31b77..00000000 --- a/source/QXmppStreamInitiationIq.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPSTREAMINITIATIONIQ_H -#define QXMPPSTREAMINITIATIONIQ_H - -#include <QDateTime> - -#include "QXmppIq.h" - -class QDomElement; -class QXmlStreamWriter; - -class QXmppStreamInitiationIq : public QXmppIq -{ -public: - enum Profile { - None = 0, - FileTransfer, - }; - - QString mimeType() const; - void setMimeType(const QString &mimeType); - - QXmppStreamInitiationIq::Profile profile() const; - void setProfile(QXmppStreamInitiationIq::Profile profile); - - QString siId() const; - void setSiId(const QString &id); - - QXmppElementList siItems() const; - void setSiItems(const QXmppElementList &items); - - static bool isStreamInitiationIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QString m_mimeType; - Profile m_profile; - QString m_siId; - QXmppElementList m_siItems; -}; - -#endif diff --git a/source/QXmppStun.cpp b/source/QXmppStun.cpp deleted file mode 100644 index 5bd3fd54..00000000 --- a/source/QXmppStun.cpp +++ /dev/null @@ -1,979 +0,0 @@ -/* - * 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. - * - */ - -#define QXMPP_DEBUG_STUN - -#include <QCryptographicHash> -#include <QDebug> -#include <QNetworkInterface> -#include <QUdpSocket> -#include <QTimer> - -#include "QXmppStun.h" -#include "QXmppUtils.h" - -#define ID_SIZE 12 - -static const quint32 STUN_MAGIC = 0x2112A442; -static const quint16 STUN_HEADER = 20; -static const quint8 STUN_IPV4 = 0x01; -static const quint8 STUN_IPV6 = 0x02; - -enum MessageType { - BindingRequest = 0x0001, - BindingIndication = 0x0011, - BindingResponse = 0x0101, - BindingError = 0x0111, - SharedSecretRequest = 0x0002, - SharedSecretResponse = 0x0102, - SharedSecretError = 0x0112, -}; - -enum AttributeType { - MappedAddress = 0x0001, - Username = 0x0006, - MessageIntegrity = 0x0008, - ErrorCode = 0x0009, - XorMappedAddress = 0x0020, - Priority = 0x0024, - UseCandidate = 0x0025, - Software = 0x8022, - Fingerprint = 0x8028, - IceControlled = 0x8029, - IceControlling = 0x802a, - OtherAddress = 0x802c, -}; - -static bool decodeAddress(QDataStream &stream, quint16 a_length, QHostAddress &address, quint16 &port) -{ - if (a_length < 4) - return false; - quint8 reserved, protocol; - stream >> reserved; - stream >> protocol; - stream >> port; - if (protocol == STUN_IPV4) - { - if (a_length != 8) - return false; - quint32 addr; - stream >> addr; - address = QHostAddress(addr); - } else if (protocol == STUN_IPV6) { - if (a_length != 20) - return false; - Q_IPV6ADDR addr; - stream.readRawData((char*)&addr, sizeof(addr)); - address = QHostAddress(addr); - } else { - return false; - } - return true; -} - -static void encodeAddress(QDataStream &stream, const QHostAddress &address, quint16 port) -{ - stream << quint16(8); - stream << quint8(0); - if (address.protocol() == QAbstractSocket::IPv4Protocol) - { - stream << quint8(STUN_IPV4); - stream << port; - stream << address.toIPv4Address(); - } else if (address.protocol() == QAbstractSocket::IPv6Protocol) { - stream << quint8(STUN_IPV6); - stream << port; - Q_IPV6ADDR addr = address.toIPv6Address(); - stream.writeRawData((char*)&addr, sizeof(addr)); - } -} - -static void encodeString(QDataStream &stream, const QString &string) -{ - const QByteArray utf8string = string.toUtf8(); - stream << quint16(utf8string.size()); - stream.writeRawData(utf8string.data(), utf8string.size()); - if (utf8string.size() % 4) - { - const QByteArray padding(4 - (utf8string.size() % 4), 0); - stream.writeRawData(padding.data(), padding.size()); - } -} - -static QByteArray randomByteArray(int length) -{ - QByteArray result(length, 0); - for (int i = 0; i < length; ++i) - result[i] = quint8(qrand() % 255); - return result; -} - -/// Constructs a new QXmppStunMessage. - -QXmppStunMessage::QXmppStunMessage() - : errorCode(0), - priority(0), - mappedPort(0), - otherPort(0), - xorMappedPort(0), - useCandidate(false) -{ - m_id = QByteArray(ID_SIZE, 0); -} - -QByteArray QXmppStunMessage::id() const -{ - return m_id; -} - -void QXmppStunMessage::setId(const QByteArray &id) -{ - Q_ASSERT(id.size() == ID_SIZE); - m_id = id; -} - -quint16 QXmppStunMessage::type() const -{ - return m_type; -} - -void QXmppStunMessage::setType(quint16 type) -{ - m_type = type; -} - -/// Decodes a QXmppStunMessage and checks its integrity using the given -/// password. -/// -/// \param buffer -/// \param password - -bool QXmppStunMessage::decode(const QByteArray &buffer, const QString &password, QStringList *errors) -{ - QStringList silent; - if (!errors) - errors = &silent; - - if (buffer.size() < STUN_HEADER) - { - *errors << QLatin1String("Received a truncated STUN packet"); - return false; - } - - // parse STUN header - QDataStream stream(buffer); - quint16 length; - quint32 cookie; - stream >> m_type; - stream >> length; - stream >> cookie; - stream.readRawData(m_id.data(), m_id.size()); - - if (cookie != STUN_MAGIC || length != buffer.size() - STUN_HEADER) - { - *errors << QLatin1String("Received an invalid STUN packet"); - return false; - } - - // parse STUN attributes - int done = 0; - bool after_integrity = false; - while (done < length) - { - quint16 a_type, a_length; - stream >> a_type; - stream >> a_length; - const int pad_length = 4 * ((a_length + 3) / 4) - a_length; - - // only FINGERPRINT is allowed after MESSAGE-INTEGRITY - if (after_integrity && a_type != Fingerprint) - { - *errors << QString("Skipping attribute %1 after MESSAGE-INTEGRITY").arg(QString::number(a_type)); - stream.skipRawData(a_length + pad_length); - done += 4 + a_length + pad_length; - continue; - } - - if (a_type == Priority) - { - // PRIORITY - if (a_length != sizeof(priority)) - return false; - stream >> priority; - - } else if (a_type == ErrorCode) { - - // ERROR-CODE - if (a_length < 4) - return false; - quint16 reserved; - quint8 errorCodeHigh, errorCodeLow; - stream >> reserved; - stream >> errorCodeHigh; - stream >> errorCodeLow; - errorCode = errorCodeHigh * 100 + errorCodeLow; - QByteArray phrase(a_length - 4, 0); - stream.readRawData(phrase.data(), phrase.size()); - errorPhrase = QString::fromUtf8(phrase); - - } else if (a_type == UseCandidate) { - - // USE-CANDIDATE - if (a_length != 0) - return false; - useCandidate = true; - - } else if (a_type == Software) { - - // SOFTWARE - QByteArray utf8Software(a_length, 0); - stream.readRawData(utf8Software.data(), utf8Software.size()); - software = QString::fromUtf8(utf8Software); - - } else if (a_type == MappedAddress) { - - // MAPPED-ADDRESS - if (!decodeAddress(stream, a_length, mappedHost, mappedPort)) - { - *errors << QLatin1String("Bad MAPPED-ADDRESS"); - return false; - } - - } else if (a_type == OtherAddress) { - - // OTHER-ADDRESS - if (!decodeAddress(stream, a_length, otherHost, otherPort)) - { - *errors << QLatin1String("Bad OTHER-ADDRESS"); - return false; - } - - } else if (a_type == XorMappedAddress) { - - // XOR-MAPPED-ADDRESS - if (a_length < 4) - return false; - quint8 reserved, protocol; - quint16 xport; - stream >> reserved; - stream >> protocol; - stream >> xport; - xorMappedPort = xport ^ (STUN_MAGIC >> 16); - if (protocol == STUN_IPV4) - { - if (a_length != 8) - return false; - quint32 xaddr; - stream >> xaddr; - xorMappedHost = QHostAddress(xaddr ^ STUN_MAGIC); - } else if (protocol == STUN_IPV6) { - if (a_length != 20) - return false; - QByteArray xaddr(16, 0); - stream.readRawData(xaddr.data(), xaddr.size()); - QByteArray xpad; - QDataStream(&xpad, QIODevice::WriteOnly) << STUN_MAGIC; - xpad += m_id; - Q_IPV6ADDR addr; - for (int i = 0; i < 16; i++) - addr[i] = xaddr[i] ^ xpad[i]; - xorMappedHost = QHostAddress(addr); - } else { - *errors << QString("Bad protocol %1").arg(QString::number(protocol)); - return false; - } - - } else if (a_type == MessageIntegrity) { - - // MESSAGE-INTEGRITY - if (a_length != 20) - return false; - QByteArray integrity(20, 0); - stream.readRawData(integrity.data(), integrity.size()); - - // check HMAC-SHA1 - if (!password.isEmpty()) - { - const QByteArray key = password.toUtf8(); - QByteArray copy = buffer.left(STUN_HEADER + done); - setBodyLength(copy, done + 24); - if (integrity != generateHmacSha1(key, copy)) - { - *errors << QLatin1String("Bad message integrity"); - return false; - } - } - - // from here onwards, only FINGERPRINT is allowed - after_integrity = true; - - } else if (a_type == Fingerprint) { - - // FINGERPRINT - if (a_length != 4) - return false; - quint32 fingerprint; - stream >> fingerprint; - - // check CRC32 - QByteArray copy = buffer.left(STUN_HEADER + done); - setBodyLength(copy, done + 8); - const quint32 expected = generateCrc32(copy) ^ 0x5354554eL; - if (fingerprint != expected) - { - *errors << QLatin1String("Bad fingerprint"); - return false; - } - - // stop parsing, no more attributes are allowed - return true; - - } else if (a_type == IceControlling) { - - /// ICE-CONTROLLING - if (a_length != 8) - return false; - iceControlling.resize(8); - stream.readRawData(iceControlling.data(), iceControlling.size()); - - } else if (a_type == IceControlled) { - - /// ICE-CONTROLLED - if (a_length != 8) - return false; - iceControlled.resize(8); - stream.readRawData(iceControlled.data(), iceControlled.size()); - - } else if (a_type == Username) { - - // USERNAME - QByteArray utf8Username(a_length, 0); - stream.readRawData(utf8Username.data(), utf8Username.size()); - username = QString::fromUtf8(utf8Username); - - } else { - - // Unknown attribute - stream.skipRawData(a_length); - *errors << QString("Skipping unknown attribute %1").arg(QString::number(a_type)); - - } - stream.skipRawData(pad_length); - done += 4 + a_length + pad_length; - } - return true; -} - -/// Encodes the current QXmppStunMessage, optionally calculating the -/// message integrity attribute using the given password. -/// -/// \param password - -QByteArray QXmppStunMessage::encode(const QString &password) const -{ - QByteArray buffer; - QDataStream stream(&buffer, QIODevice::WriteOnly); - - // encode STUN header - quint16 length = 0; - stream << m_type; - stream << length; - stream << STUN_MAGIC; - stream.writeRawData(m_id.data(), m_id.size()); - - // MAPPED-ADDRESS - if (mappedPort && !mappedHost.isNull() && - (mappedHost.protocol() == QAbstractSocket::IPv4Protocol || - mappedHost.protocol() == QAbstractSocket::IPv6Protocol)) - { - stream << quint16(MappedAddress); - encodeAddress(stream, mappedHost, mappedPort); - } - - // OTHER-ADDRESS - if (otherPort && !otherHost.isNull() && - (otherHost.protocol() == QAbstractSocket::IPv4Protocol || - otherHost.protocol() == QAbstractSocket::IPv6Protocol)) - { - stream << quint16(OtherAddress); - encodeAddress(stream, otherHost, otherPort); - } - - // XOR-MAPPED-ADDRESS - if (xorMappedPort && !xorMappedHost.isNull() && - (xorMappedHost.protocol() == QAbstractSocket::IPv4Protocol || - xorMappedHost.protocol() == QAbstractSocket::IPv6Protocol)) - { - stream << quint16(XorMappedAddress); - stream << quint16(8); - stream << quint8(0); - if (xorMappedHost.protocol() == QAbstractSocket::IPv4Protocol) - { - stream << quint8(STUN_IPV4); - stream << quint16(xorMappedPort ^ (STUN_MAGIC >> 16)); - stream << quint32(xorMappedHost.toIPv4Address() ^ STUN_MAGIC); - } else { - stream << quint8(STUN_IPV6); - stream << quint16(xorMappedPort ^ (STUN_MAGIC >> 16)); - Q_IPV6ADDR addr = xorMappedHost.toIPv6Address(); - QByteArray xaddr; - QDataStream(&xaddr, QIODevice::WriteOnly) << STUN_MAGIC; - xaddr += m_id; - for (int i = 0; i < 16; i++) - xaddr[i] = xaddr[i] ^ addr[i]; - stream.writeRawData(xaddr.data(), xaddr.size()); - } - } - - // ERROR-CODE - if (errorCode) - { - const quint16 reserved = 0; - const quint8 errorCodeHigh = errorCode / 100; - const quint8 errorCodeLow = errorCode % 100; - const QByteArray phrase = errorPhrase.toUtf8(); - stream << quint16(ErrorCode); - stream << quint16(phrase.size() + 4); - stream << reserved; - stream << errorCodeHigh; - stream << errorCodeLow; - stream.writeRawData(phrase.data(), phrase.size()); - if (phrase.size() % 4) - { - const QByteArray padding(4 - (phrase.size() % 4), 0); - stream.writeRawData(padding.data(), padding.size()); - } - } - - // PRIORITY - if (priority) - { - stream << quint16(Priority); - stream << quint16(sizeof(priority)); - stream << priority; - } - - // USE-CANDIDATE - if (useCandidate) - { - stream << quint16(UseCandidate); - stream << quint16(0); - } - - // SOFTWARE - if (!software.isEmpty()) - { - stream << quint16(Software); - encodeString(stream, software); - } - - // ICE-CONTROLLING or ICE-CONTROLLED - if (!iceControlling.isEmpty()) - { - stream << quint16(IceControlling); - stream << quint16(iceControlling.size()); - stream.writeRawData(iceControlling.data(), iceControlling.size()); - } else if (!iceControlled.isEmpty()) { - stream << quint16(IceControlled); - stream << quint16(iceControlled.size()); - stream.writeRawData(iceControlled.data(), iceControlled.size()); - } - - // USERNAME - if (!username.isEmpty()) - { - stream << quint16(Username); - encodeString(stream, username); - } - - // set body length - setBodyLength(buffer, buffer.size() - STUN_HEADER); - - // MESSAGE-INTEGRITY - if (!password.isEmpty()) - { - const QByteArray key = password.toUtf8(); - setBodyLength(buffer, buffer.size() - STUN_HEADER + 24); - QByteArray integrity = generateHmacSha1(key, buffer); - stream << quint16(MessageIntegrity); - stream << quint16(integrity.size()); - stream.writeRawData(integrity.data(), integrity.size()); - } - - // FINGERPRINT - setBodyLength(buffer, buffer.size() - STUN_HEADER + 8); - quint32 fingerprint = generateCrc32(buffer) ^ 0x5354554eL; - stream << quint16(Fingerprint); - stream << quint16(sizeof(fingerprint)); - stream << fingerprint; - - return buffer; -} - -/// If the given packet looks like a STUN message, returns the message -/// type, otherwise returns 0. -/// -/// \param buffer - -quint16 QXmppStunMessage::peekType(const QByteArray &buffer) -{ - if (buffer.size() < STUN_HEADER) - return 0; - - // parse STUN header - QDataStream stream(buffer); - quint16 type; - quint16 length; - quint32 cookie; - stream >> type; - stream >> length; - stream >> cookie; - - if (cookie != STUN_MAGIC || length != buffer.size() - STUN_HEADER) - return 0; - - return type; -} - -void QXmppStunMessage::setBodyLength(QByteArray &buffer, qint16 length) const -{ - QDataStream stream(&buffer, QIODevice::WriteOnly); - stream.device()->seek(2); - stream << length; -} - -QString QXmppStunMessage::toString() const -{ - QStringList dumpLines; - QString typeName; - switch (m_type & 0x000f) - { - case 1: typeName = "Binding"; break; - case 2: typeName = "Shared Secret"; break; - default: typeName = "Unknown"; break; - } - switch (m_type & 0x0ff0) - { - case 0x000: typeName += " Request"; break; - case 0x010: typeName += " Indication"; break; - case 0x100: typeName += " Response"; break; - case 0x110: typeName += " Error"; break; - default: break; - } - dumpLines << QString(" type %1 (%2)") - .arg(typeName) - .arg(QString::number(m_type)); - dumpLines << QString(" id %1").arg(QString::fromAscii(m_id.toHex())); - - // attributes - if (!username.isEmpty()) - dumpLines << QString(" * USERNAME %1").arg(username); - if (errorCode) - dumpLines << QString(" * ERROR-CODE %1 %2") - .arg(QString::number(errorCode)) - .arg(errorPhrase); - if (!software.isEmpty()) - dumpLines << QString(" * SOFTWARE %1").arg(software); - if (mappedPort) - dumpLines << QString(" * MAPPED-ADDRESS %1 %2") - .arg(mappedHost.toString()) - .arg(QString::number(mappedPort)); - if (otherPort) - dumpLines << QString(" * OTHER-ADDRESS %1 %2") - .arg(otherHost.toString()) - .arg(QString::number(otherPort)); - if (xorMappedPort) - dumpLines << QString(" * XOR-MAPPED-ADDRESS %1 %2") - .arg(xorMappedHost.toString()) - .arg(QString::number(xorMappedPort)); - if (!iceControlling.isEmpty()) - dumpLines << QString(" * ICE-CONTROLLING %1") - .arg(QString::fromAscii(iceControlling.toHex())); - if (!iceControlled.isEmpty()) - dumpLines << QString(" * ICE-CONTROLLED %1") - .arg(QString::fromAscii(iceControlled.toHex())); - - return dumpLines.join("\n"); -} - -QXmppStunSocket::Pair::Pair() - : checked(QIODevice::NotOpen) -{ - // FIXME : calculate priority - priority = 1862270975; - transaction = randomByteArray(ID_SIZE); -} - -QString QXmppStunSocket::Pair::toString() const -{ - QString str = QString("%1 %2").arg(remote.host().toString(), QString::number(remote.port())); - if (!reflexive.host().isNull() && reflexive.port()) - str += QString(" (reflexive %1 %2)").arg(reflexive.host().toString(), QString::number(reflexive.port())); - return str; -} - -/// Constructs a new QXmppStunSocket. -/// - -QXmppStunSocket::QXmppStunSocket(bool iceControlling, QObject *parent) - : QObject(parent), - m_activePair(0), - m_iceControlling(iceControlling) -{ - m_localUser = generateStanzaHash(4); - m_localPassword = generateStanzaHash(22); - - m_socket = new QUdpSocket(this); - connect(m_socket, SIGNAL(readyRead()), this, SLOT(readyRead())); - if (!m_socket->bind()) - qWarning("QXmppStunSocket could not start listening"); - - m_timer = new QTimer(this); - m_timer->setInterval(500); - connect(m_timer, SIGNAL(timeout()), this, SLOT(checkCandidates())); -} - -QXmppStunSocket::~QXmppStunSocket() -{ - foreach (Pair *pair, m_pairs) - delete pair; -} - -/// Returns the component id for the current socket, e.g. 1 for RTP -/// and 2 for RTCP. - -int QXmppStunSocket::component() const -{ - return m_component; -} - -/// Sets the component id for the current socket, e.g. 1 for RTP -/// and 2 for RTCP. -/// -/// \param component - -void QXmppStunSocket::setComponent(int component) -{ - m_component = component; -} - -void QXmppStunSocket::checkCandidates() -{ - debug("Checking remote candidates"); - foreach (Pair *pair, m_pairs) - { - // send a binding request - QXmppStunMessage message; - message.setId(pair->transaction); - message.setType(BindingRequest); - message.priority = pair->priority; - message.username = QString("%1:%2").arg(m_remoteUser, m_localUser); - if (m_iceControlling) - { - message.iceControlling = QByteArray(8, 0); - message.useCandidate = true; - } else { - message.iceControlled = QByteArray(8, 0); - } - writeStun(message, pair); - } -} - -/// Closes the socket. - -void QXmppStunSocket::close() -{ - m_socket->close(); - m_timer->stop(); -} - -/// Start ICE connectivity checks. - -void QXmppStunSocket::connectToHost() -{ - checkCandidates(); - m_timer->start(); -} - -/// Returns true if ICE negotiation completed, false otherwise. - -bool QXmppStunSocket::isConnected() const -{ - return m_activePair != 0; -} - -void QXmppStunSocket::debug(const QString &message, QXmppLogger::MessageType type) -{ - emit logMessage(type, QString("STUN(%1) %2").arg(QString::number(m_component)).arg(message)); -} - -/// Returns the list of local HOST CANDIDATES candidates by iterating -/// over the available network interfaces. - -QList<QXmppJingleCandidate> QXmppStunSocket::localCandidates() const -{ - QList<QXmppJingleCandidate> candidates; - foreach (const QNetworkInterface &interface, QNetworkInterface::allInterfaces()) - { - if (!(interface.flags() & QNetworkInterface::IsRunning) || - interface.flags() & QNetworkInterface::IsLoopBack) - continue; - - foreach (const QNetworkAddressEntry &entry, interface.addressEntries()) - { - if (entry.ip().protocol() != QAbstractSocket::IPv4Protocol || - entry.netmask().isNull() || - entry.netmask() == QHostAddress::Broadcast) - continue; - - QXmppJingleCandidate candidate; - candidate.setComponent(m_component); - candidate.setHost(entry.ip()); - candidate.setId(generateStanzaHash(10)); - candidate.setNetwork(interface.index()); - candidate.setPort(m_socket->localPort()); - candidate.setPriority(2130706432 - m_component); - candidate.setProtocol("udp"); - candidate.setType("host"); - candidates << candidate; - } - } - return candidates; -} - -QString QXmppStunSocket::localUser() const -{ - return m_localUser; -} - -void QXmppStunSocket::setLocalUser(const QString &user) -{ - m_localUser = user; -} - -QString QXmppStunSocket::localPassword() const -{ - return m_localPassword; -} - -void QXmppStunSocket::setLocalPassword(const QString &password) -{ - m_localPassword = password; -} - -/// Adds a remote STUN candidate. - -bool QXmppStunSocket::addRemoteCandidate(const QXmppJingleCandidate &candidate) -{ - if (candidate.component() != m_component || - candidate.type() != "host" || - candidate.protocol() != "udp") - return false; - - foreach (Pair *pair, m_pairs) - if (pair->remote.host() == candidate.host() && - pair->remote.port() == candidate.port()) - return false; - - Pair *pair = new Pair; - pair->remote = candidate; - m_pairs << pair; - return true; -} - -/// Adds a discovered STUN candidate. - -QXmppStunSocket::Pair *QXmppStunSocket::addRemoteCandidate(const QHostAddress &host, quint16 port) -{ - foreach (Pair *pair, m_pairs) - if (pair->remote.host() == host && - pair->remote.port() == port) - return pair; - - QXmppJingleCandidate candidate; - candidate.setHost(host); - candidate.setPort(port); - candidate.setProtocol("udp"); - candidate.setComponent(m_component); - - Pair *pair = new Pair; - pair->remote = candidate; - m_pairs << pair; - - debug(QString("Added candidate %1").arg(pair->toString())); - return pair; -} - -void QXmppStunSocket::setRemoteUser(const QString &user) -{ - m_remoteUser = user; -} - -void QXmppStunSocket::setRemotePassword(const QString &password) -{ - m_remotePassword = password; -} - -void QXmppStunSocket::readyRead() -{ - const qint64 size = m_socket->pendingDatagramSize(); - QHostAddress remoteHost; - quint16 remotePort; - QByteArray buffer(size, 0); - m_socket->readDatagram(buffer.data(), buffer.size(), &remoteHost, &remotePort); - - // if this is not a STUN message, emit it - quint16 messageType = QXmppStunMessage::peekType(buffer); - if (!messageType) - { - emit datagramReceived(buffer); - return; - } - - // parse STUN message - const QString messagePassword = (messageType & 0xFF00) ? m_remotePassword : m_localPassword; - if (messagePassword.isEmpty()) - return; - QXmppStunMessage message; - QStringList errors; - if (!message.decode(buffer, messagePassword, &errors)) - { - foreach (const QString &error, errors) - debug(error, QXmppLogger::WarningMessage); - return; - } -#ifdef QXMPP_DEBUG_STUN - debug(QString("Received from %1 port %2\n%3") - .arg(remoteHost.toString()) - .arg(QString::number(remotePort)) - .arg(message.toString()), - QXmppLogger::ReceivedMessage); -#endif - - if (m_activePair) - return; - - // process message - Pair *pair = 0; - if (message.type() == BindingRequest) - { - // add remote candidate - pair = addRemoteCandidate(remoteHost, remotePort); - - // send a binding response - QXmppStunMessage response; - response.setId(message.id()); - response.setType(BindingResponse); - response.username = message.username; - response.xorMappedHost = pair->remote.host(); - response.xorMappedPort = pair->remote.port(); - writeStun(response, pair); - - // update state - if (m_iceControlling || message.useCandidate) - { - debug(QString("ICE reverse check %1").arg(pair->toString())); - pair->checked |= QIODevice::ReadOnly; - } - - if (!m_iceControlling) - { - // send a triggered connectivity test - QXmppStunMessage message; - message.setId(pair->transaction); - message.setType(BindingRequest); - message.priority = pair->priority; - message.username = QString("%1:%2").arg(m_remoteUser, m_localUser); - message.iceControlled = QByteArray(8, 0); - writeStun(message, pair); - } - - } else if (message.type() == BindingResponse) { - - // find the pair for this transaction - foreach (Pair *ptr, m_pairs) - { - if (ptr->transaction == message.id()) - { - pair = ptr; - break; - } - } - if (!pair) - { - debug(QString("Unknown transaction %1").arg(QString::fromAscii(message.id().toHex()))); - return; - } - // store reflexive address - pair->reflexive.setHost(message.xorMappedHost); - pair->reflexive.setPort(message.xorMappedPort); - - // add the new remote candidate - addRemoteCandidate(remoteHost, remotePort); - -#if 0 - // send a binding indication - QXmppStunMessage indication; - indication.setId(randomByteArray(ID_SIZE)); - indication.setType(BindingIndication); - m_socket->writeStun(indication, pair); -#endif - // outgoing media can flow - debug(QString("ICE forward check %1").arg(pair->toString())); - pair->checked |= QIODevice::WriteOnly; - } - - // signal completion - if (pair && pair->checked == QIODevice::ReadWrite) - { - debug(QString("ICE completed %1").arg(pair->toString())); - m_activePair = pair; - m_timer->stop(); - emit connected(); - } -} - -/// Sends a data packet to the remote party. -/// -/// \param datagram - -qint64 QXmppStunSocket::writeDatagram(const QByteArray &datagram) -{ - if (!m_activePair) - return -1; - return m_socket->writeDatagram(datagram, m_activePair->remote.host(), m_activePair->remote.port()); -} - -/// Sends a STUN packet to the remote party. - -qint64 QXmppStunSocket::writeStun(const QXmppStunMessage &message, QXmppStunSocket::Pair *pair) -{ - const QString messagePassword = (message.type() & 0xFF00) ? m_localPassword : m_remotePassword; -#ifdef QXMPP_DEBUG_STUN - debug( - QString("Sent to %1\n%2").arg(pair->toString(), message.toString()), - QXmppLogger::SentMessage); -#endif - return m_socket->writeDatagram(message.encode(messagePassword), pair->remote.host(), pair->remote.port()); -} - diff --git a/source/QXmppStun.h b/source/QXmppStun.h deleted file mode 100644 index 5f9eed53..00000000 --- a/source/QXmppStun.h +++ /dev/null @@ -1,154 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPSTUN_H -#define QXMPPSTUN_H - -#include <QObject> - -#include "QXmppLogger.h" -#include "QXmppJingleIq.h" - -class QUdpSocket; -class QTimer; - -/// \brief The QXmppStunMessage class represents a STUN message. -/// - -class QXmppStunMessage -{ -public: - QXmppStunMessage(); - - QByteArray id() const; - void setId(const QByteArray &id); - - quint16 type() const; - void setType(quint16 type); - - QByteArray encode(const QString &password = QString()) const; - bool decode(const QByteArray &buffer, const QString &password = QString(), QStringList *errors = 0); - QString toString() const; - static quint16 peekType(const QByteArray &buffer); - - // attributes - int errorCode; - QString errorPhrase; - quint32 priority; - QByteArray iceControlling; - QByteArray iceControlled; - QHostAddress mappedHost; - quint16 mappedPort; - QHostAddress otherHost; - quint16 otherPort; - QHostAddress xorMappedHost; - quint16 xorMappedPort; - QString software; - QString username; - bool useCandidate; - -private: - void setBodyLength(QByteArray &buffer, qint16 length) const; - - QByteArray m_id; - quint16 m_type; -}; - - -/// \brief The QXmppStunSocket class represents an UDP socket capable -/// of performing Interactive Connectivity Establishment (RFC 5245). -/// - -class QXmppStunSocket : public QObject -{ - Q_OBJECT - -public: - QXmppStunSocket(bool iceControlling, QObject *parent=0); - ~QXmppStunSocket(); - - QList<QXmppJingleCandidate> localCandidates() const; - QString localUser() const; - void setLocalUser(const QString &user); - QString localPassword() const; - void setLocalPassword(const QString &password); - - int component() const; - void setComponent(int component); - - bool addRemoteCandidate(const QXmppJingleCandidate &candidate); - void setRemoteUser(const QString &user); - void setRemotePassword(const QString &password); - - void close(); - void connectToHost(); - bool isConnected() const; - qint64 writeDatagram(const QByteArray &datagram); - -private slots: - void checkCandidates(); - void readyRead(); - -signals: - // This signal is emitted once ICE negotiation succeeds. - void connected(); - - // This signal is emitted when a data packet is received. - void datagramReceived(const QByteArray &datagram); - - /// This signal is emitted to send logging messages. - void logMessage(QXmppLogger::MessageType type, const QString &msg); - -private: - class Pair { - public: - Pair(); - QString toString() const; - - QIODevice::OpenMode checked; - quint32 priority; - QXmppJingleCandidate remote; - QXmppJingleCandidate reflexive; - QByteArray transaction; - }; - - Pair *addRemoteCandidate(const QHostAddress &host, quint16 port); - void debug(const QString &message, QXmppLogger::MessageType = QXmppLogger::DebugMessage); - qint64 writeStun(const QXmppStunMessage &message, QXmppStunSocket::Pair *pair); - - int m_component; - - QString m_localUser; - QString m_localPassword; - - Pair *m_activePair; - bool m_iceControlling; - QList<Pair*> m_pairs; - QString m_remoteUser; - QString m_remotePassword; - - QUdpSocket *m_socket; - QTimer *m_timer; -}; - -#endif diff --git a/source/QXmppTransferManager.cpp b/source/QXmppTransferManager.cpp deleted file mode 100644 index b64d6285..00000000 --- a/source/QXmppTransferManager.cpp +++ /dev/null @@ -1,1358 +0,0 @@ -/* - * 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 <QFile> -#include <QFileInfo> -#include <QNetworkInterface> -#include <QTimer> - -#include "QXmppByteStreamIq.h" -#include "QXmppConstants.h" -#include "QXmppIbbIq.h" -#include "QXmppLogger.h" -#include "QXmppSocks.h" -#include "QXmppStream.h" -#include "QXmppStreamInitiationIq.h" -#include "QXmppTransferManager.h" -#include "QXmppUtils.h" - -// time to try to connect to a SOCKS host (7 seconds) -const int socksTimeout = 7000; - -static QString streamHash(const QString &sid, const QString &initiatorJid, const QString &targetJid) -{ - QCryptographicHash hash(QCryptographicHash::Sha1); - QString str = sid + initiatorJid + targetJid; - hash.addData(str.toAscii()); - return hash.result().toHex(); -} - -QXmppTransferFileInfo::QXmppTransferFileInfo() - : m_size(0) -{ -} - -QDateTime QXmppTransferFileInfo::date() const -{ - return m_date; -} - -void QXmppTransferFileInfo::setDate(const QDateTime &date) -{ - m_date = date; -} - -QByteArray QXmppTransferFileInfo::hash() const -{ - return m_hash; -} - -void QXmppTransferFileInfo::setHash(const QByteArray &hash) -{ - m_hash = hash; -} - -QString QXmppTransferFileInfo::name() const -{ - return m_name; -} - -void QXmppTransferFileInfo::setName(const QString &name) -{ - m_name = name; -} - -qint64 QXmppTransferFileInfo::size() const -{ - return m_size; -} - -void QXmppTransferFileInfo::setSize(qint64 size) -{ - m_size = size; -} - -bool QXmppTransferFileInfo::operator==(const QXmppTransferFileInfo &other) const -{ - return other.m_size == m_size && - other.m_hash == m_hash && - other.m_name == m_name; -} - -QXmppTransferJob::QXmppTransferJob(const QString &jid, QXmppTransferJob::Direction direction, QObject *parent) - : QObject(parent), - m_blockSize(16384), - m_direction(direction), - m_done(0), - m_error(NoError), - m_hash(QCryptographicHash::Md5), - m_iodevice(0), - m_jid(jid), - m_method(NoMethod), - m_state(OfferState), - m_ibbSequence(0), - m_socksSocket(0) -{ -} - -/// Call this method if you wish to abort on ongoing transfer job. -/// - -void QXmppTransferJob::abort() -{ - terminate(AbortError); -} - -/// Call this method if you wish to accept an incoming transfer job. -/// - -void QXmppTransferJob::accept(QIODevice *iodevice) -{ - if (m_direction == IncomingDirection && m_state == OfferState && !m_iodevice) - { - m_iodevice = iodevice; - setState(QXmppTransferJob::StartState); - } -} - -void QXmppTransferJob::checkData() -{ - if ((m_fileInfo.size() && m_done != m_fileInfo.size()) || - (!m_fileInfo.hash().isEmpty() && m_hash.result() != m_fileInfo.hash())) - terminate(QXmppTransferJob::FileCorruptError); - else - terminate(QXmppTransferJob::NoError); -} - -/// Returns the job's data for a given role. -/// -/// You can associate arbitrary data with the role using setData(). - -QVariant QXmppTransferJob::data(int role) const -{ - return m_data.value(role); -} - -/// Sets the data for a given role to the given value. -/// -/// You can set any data you want for use in your application, this -/// data will not be used internally by QXmppTransferManager. - -void QXmppTransferJob::setData(int role, const QVariant &value) -{ - m_data.insert(role, value); -} - -/// Returns the job's transfer direction. -/// - -QXmppTransferJob::Direction QXmppTransferJob::direction() const -{ - return m_direction; -} - -/// Returns the last error that was encountered. -/// - -QXmppTransferJob::Error QXmppTransferJob::error() const -{ - return m_error; -} - -/// Returns the remote party's JID. -/// - -QString QXmppTransferJob::jid() const -{ - return m_jid; -} - -/// Returns meta-data about the file being transfered. -/// - -QXmppTransferFileInfo QXmppTransferJob::fileInfo() const -{ - return m_fileInfo; -} - -QDateTime QXmppTransferJob::fileDate() const -{ - return m_fileInfo.date(); -} - -QByteArray QXmppTransferJob::fileHash() const -{ - return m_fileInfo.hash(); -} - -QString QXmppTransferJob::fileName() const -{ - return m_fileInfo.name(); -} - -qint64 QXmppTransferJob::fileSize() const -{ - return m_fileInfo.size(); -} - -/// Returns the job's transfer method. -/// - -QXmppTransferJob::Method QXmppTransferJob::method() const -{ - return m_method; -} - -/// Returns the job's session identifier. -/// - -QString QXmppTransferJob::sid() const -{ - return m_sid; -} - -/// Returns the job's state. -/// - -QXmppTransferJob::State QXmppTransferJob::state() const -{ - return m_state; -} - -void QXmppTransferJob::setState(QXmppTransferJob::State state) -{ - if (m_state != state) - { - m_state = state; - emit stateChanged(m_state); - } -} - -void QXmppTransferJob::disconnected() -{ - if (m_state == QXmppTransferJob::FinishedState) - return; - - // terminate transfer - if (m_direction == QXmppTransferJob::IncomingDirection) - { - checkData(); - } else { - if (fileSize() && m_done != fileSize()) - terminate(QXmppTransferJob::ProtocolError); - else - terminate(QXmppTransferJob::NoError); - } -} - -void QXmppTransferJob::receiveData() -{ - if (m_state != QXmppTransferJob::TransferState) - return; - - // receive data block - if (m_direction == QXmppTransferJob::IncomingDirection) - { - writeData(m_socksSocket->readAll()); - - // if we have received all the data, stop here - if (fileSize() && m_done >= fileSize()) - checkData(); - } -} - -void QXmppTransferJob::sendData() -{ - if (m_state != QXmppTransferJob::TransferState) - return; - - // don't saturate the outgoing socket - if (m_socksSocket->bytesToWrite() > 2 * m_blockSize) - return; - - // check whether we have written the whole file - if (m_fileInfo.size() && m_done >= m_fileInfo.size()) - { - if (!m_socksSocket->bytesToWrite()) - terminate(QXmppTransferJob::NoError); - return; - } - - char *buffer = new char[m_blockSize]; - qint64 length = m_iodevice->read(buffer, m_blockSize); - if (length < 0) - { - delete [] buffer; - terminate(QXmppTransferJob::FileAccessError); - return; - } - if (length > 0) - { - m_socksSocket->write(buffer, length); - delete [] buffer; - m_done += length; - emit progress(m_done, fileSize()); - } -} - -void QXmppTransferJob::slotTerminated() -{ - emit stateChanged(m_state); - if (m_error != NoError) - emit error(m_error); - emit finished(); -} - -void QXmppTransferJob::terminate(QXmppTransferJob::Error cause) -{ - if (m_state == FinishedState) - return; - - // change state - m_error = cause; - m_state = FinishedState; - - // close IO device - if (m_iodevice) - m_iodevice->close(); - - // close socket - if (m_socksSocket) - { - m_socksSocket->flush(); - m_socksSocket->close(); - } - - // emit signals later - QTimer::singleShot(0, this, SLOT(slotTerminated())); -} - -bool QXmppTransferJob::writeData(const QByteArray &data) -{ - const qint64 written = m_iodevice->write(data); - if (written < 0) - return false; - m_done += written; - if (!m_fileInfo.hash().isEmpty()) - m_hash.addData(data); - progress(m_done, m_fileInfo.size()); - return true; -} - -QXmppTransferManager::QXmppTransferManager(QXmppStream *stream, QObject *parent) - : QObject(parent), - m_stream(stream), - m_ibbBlockSize(4096), - m_proxyOnly(false), - m_socksServer(0), - m_supportedMethods(QXmppTransferJob::AnyMethod) -{ - // Logging - bool check = connect(this, SIGNAL(logMessage(QXmppLogger::MessageType, QString)), - m_stream, SIGNAL(logMessage(QXmppLogger::MessageType, QString))); - Q_ASSERT(check); - - // XEP-0047: In-Band Bytestreams - check = QObject::connect(m_stream, SIGNAL(iqReceived(const QXmppIq&)), - this, SLOT(iqReceived(const QXmppIq&))); - Q_ASSERT(check); - - check = QObject::connect(m_stream, SIGNAL(ibbCloseIqReceived(const QXmppIbbCloseIq&)), - this, SLOT(ibbCloseIqReceived(const QXmppIbbCloseIq&))); - Q_ASSERT(check); - - check = QObject::connect(m_stream, SIGNAL(ibbDataIqReceived(const QXmppIbbDataIq&)), - this, SLOT(ibbDataIqReceived(const QXmppIbbDataIq&))); - Q_ASSERT(check); - - check = QObject::connect(m_stream, SIGNAL(ibbOpenIqReceived(const QXmppIbbOpenIq&)), - this, SLOT(ibbOpenIqReceived(const QXmppIbbOpenIq&))); - Q_ASSERT(check); - - // XEP-0065: SOCKS5 Bytestreams - check = QObject::connect(m_stream, SIGNAL(byteStreamIqReceived(const QXmppByteStreamIq&)), - this, SLOT(byteStreamIqReceived(const QXmppByteStreamIq&))); - Q_ASSERT(check); - - // XEP-0095: Stream Initiation - check = QObject::connect(m_stream, SIGNAL(streamInitiationIqReceived(const QXmppStreamInitiationIq&)), - this, SLOT(streamInitiationIqReceived(const QXmppStreamInitiationIq&))); - Q_ASSERT(check); - - // start SOCKS server - m_socksServer = new QXmppSocksServer(this); - if (m_socksServer->listen()) - { - connect(m_socksServer, SIGNAL(newConnection(QTcpSocket*, const QString&, quint16)), - this, SLOT(socksServerConnected(QTcpSocket*, const QString&, quint16))); - } else { - emit logMessage(QXmppLogger::WarningMessage, "QXmppSocksServer could not start listening"); - } -} - -void QXmppTransferManager::byteStreamIqReceived(const QXmppByteStreamIq &iq) -{ - // handle IQ from proxy - foreach (QXmppTransferJob *job, m_jobs) - { - if (job->m_socksProxy.jid() == iq.from() && job->m_requestId == iq.id()) - { - if (iq.type() == QXmppIq::Result && iq.streamHosts().size() > 0) - { - job->m_socksProxy = iq.streamHosts().first(); - socksServerSendOffer(job); - return; - } - } - } - - if (iq.type() == QXmppIq::Result) - byteStreamResultReceived(iq); - else if (iq.type() == QXmppIq::Set) - byteStreamSetReceived(iq); -} - -/// Handle a response to a bystream set, i.e. after we informed the remote party -/// that we connected to a stream host. -void QXmppTransferManager::byteStreamResponseReceived(const QXmppIq &iq) -{ - QXmppTransferJob *job = getJobByRequestId(iq.from(), iq.id()); - if (!job || - job->direction() != QXmppTransferJob::IncomingDirection || - job->method() != QXmppTransferJob::SocksMethod || - job->state() != QXmppTransferJob::StartState) - return; - - if (iq.type() == QXmppIq::Error) - job->terminate(QXmppTransferJob::ProtocolError); -} - -/// Handle a bytestream result, i.e. after the remote party has connected to -/// a stream host. -void QXmppTransferManager::byteStreamResultReceived(const QXmppByteStreamIq &iq) -{ - QXmppTransferJob *job = getJobByRequestId(iq.from(), iq.id()); - if (!job || - job->direction() != QXmppTransferJob::OutgoingDirection || - job->method() != QXmppTransferJob::SocksMethod || - job->state() != QXmppTransferJob::StartState) - return; - - // check the stream host - if (iq.streamHostUsed() == job->m_socksProxy.jid()) - { - const QXmppByteStreamIq::StreamHost streamHost = job->m_socksProxy; - emit logMessage(QXmppLogger::InformationMessage, - QString("Connecting to proxy: %1 (%2:%3)").arg( - streamHost.jid(), - streamHost.host().toString(), - QString::number(streamHost.port()))); - - // connect to proxy - const QString hostName = streamHash(job->m_sid, - m_stream->configuration().jid(), - job->m_jid); - - QXmppSocksClient *socksClient = new QXmppSocksClient(streamHost.host(), streamHost.port(), job); - socksClient->connectToHost(hostName, 0); - // FIXME : this should probably be made asynchronous as it blocks XMPP packet handling - if (!socksClient->waitForReady(socksTimeout)) - { - emit logMessage(QXmppLogger::WarningMessage, - QString("Failed to connect to proxy: %1 (%2:%3)").arg( - streamHost.jid(), - streamHost.host().toString(), - QString::number(streamHost.port()))); - delete socksClient; - job->terminate(QXmppTransferJob::ProtocolError); - return; - } - job->m_socksSocket = socksClient; - connect(job->m_socksSocket, SIGNAL(disconnected()), job, SLOT(disconnected())); - - // activate stream - QXmppByteStreamIq streamIq; - streamIq.setType(QXmppIq::Set); - streamIq.setFrom(m_stream->configuration().jid()); - streamIq.setTo(streamHost.jid()); - streamIq.setSid(job->m_sid); - streamIq.setActivate(job->m_jid); - job->m_requestId = streamIq.id(); - m_stream->sendPacket(streamIq); - return; - } - - // direction connection, start sending data - if (!job->m_socksSocket) - { - emit logMessage(QXmppLogger::WarningMessage, "Client says they connected to our SOCKS server, but they did not"); - job->terminate(QXmppTransferJob::ProtocolError); - return; - } - job->setState(QXmppTransferJob::TransferState); - connect(job->m_socksSocket, SIGNAL(disconnected()), job, SLOT(disconnected())); - connect(job->m_socksSocket, SIGNAL(bytesWritten(qint64)), job, SLOT(sendData())); - connect(job->m_iodevice, SIGNAL(readyRead()), job, SLOT(sendData())); - job->sendData(); -} - -/// Handle a bytestream set, i.e. an invitation from the remote party to connect -/// to a stream host. -void QXmppTransferManager::byteStreamSetReceived(const QXmppByteStreamIq &iq) -{ - QXmppIq response; - response.setId(iq.id()); - response.setTo(iq.from()); - - QXmppTransferJob *job = getJobBySid(iq.from(), iq.sid()); - if (!job || - job->direction() != QXmppTransferJob::IncomingDirection || - job->method() != QXmppTransferJob::SocksMethod || - job->state() != QXmppTransferJob::StartState) - { - // the stream is unknown - QXmppStanza::Error error(QXmppStanza::Error::Auth, QXmppStanza::Error::NotAcceptable); - error.setCode(406); - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - return; - } - - // try connecting to the offered stream hosts - foreach (const QXmppByteStreamIq::StreamHost &streamHost, iq.streamHosts()) - { - emit logMessage(QXmppLogger::InformationMessage, - QString("Connecting to streamhost: %1 (%2:%3)").arg( - streamHost.jid(), - streamHost.host().toString(), - QString::number(streamHost.port()))); - - const QString hostName = streamHash(job->m_sid, - job->m_jid, - m_stream->configuration().jid()); - - // try to connect to stream host - QXmppSocksClient *socksClient = new QXmppSocksClient(streamHost.host(), streamHost.port(), job); - socksClient->connectToHost(hostName, 0); - // FIXME : this should probably be made asynchronous as it blocks XMPP packet handling - if (socksClient->waitForReady(socksTimeout)) - { - job->setState(QXmppTransferJob::TransferState); - job->m_socksSocket = socksClient; - connect(job->m_socksSocket, SIGNAL(readyRead()), job, SLOT(receiveData())); - connect(job->m_socksSocket, SIGNAL(disconnected()), job, SLOT(disconnected())); - - QXmppByteStreamIq ackIq; - ackIq.setId(iq.id()); - ackIq.setTo(iq.from()); - ackIq.setType(QXmppIq::Result); - ackIq.setSid(job->m_sid); - ackIq.setStreamHostUsed(streamHost.jid()); - m_stream->sendPacket(ackIq); - return; - } else { - emit logMessage(QXmppLogger::WarningMessage, - QString("Failed to connect to streamhost: %1 (%2:%3)").arg( - streamHost.jid(), - streamHost.host().toString(), - QString::number(streamHost.port()))); - delete socksClient; - } - } - - // could not connect to any stream host - QXmppStanza::Error error(QXmppStanza::Error::Cancel, QXmppStanza::Error::ItemNotFound); - error.setCode(404); - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - - job->terminate(QXmppTransferJob::ProtocolError); -} - -QXmppTransferJob* QXmppTransferManager::getJobByRequestId(const QString &jid, const QString &id) -{ - foreach (QXmppTransferJob *job, m_jobs) - if (job->m_jid == jid && job->m_requestId == id) - return job; - return 0; -} - -QXmppTransferJob* QXmppTransferManager::getJobBySid(const QString &jid, const QString &sid) -{ - foreach (QXmppTransferJob *job, m_jobs) - if (job->m_jid == jid && job->m_sid == sid) - return job; - return 0; -} - -void QXmppTransferManager::ibbCloseIqReceived(const QXmppIbbCloseIq &iq) -{ - QXmppIq response; - response.setTo(iq.from()); - response.setId(iq.id()); - - QXmppTransferJob *job = getJobBySid(iq.from(), iq.sid()); - if (!job || - job->direction() != QXmppTransferJob::IncomingDirection || - job->method() != QXmppTransferJob::InBandMethod) - { - // the job is unknown, cancel it - QXmppStanza::Error error(QXmppStanza::Error::Cancel, QXmppStanza::Error::ItemNotFound); - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - return; - } - - // acknowledge the packet - response.setType(QXmppIq::Result); - m_stream->sendPacket(response); - - // check received data - job->checkData(); -} - -void QXmppTransferManager::ibbDataIqReceived(const QXmppIbbDataIq &iq) -{ - QXmppIq response; - response.setTo(iq.from()); - response.setId(iq.id()); - - QXmppTransferJob *job = getJobBySid(iq.from(), iq.sid()); - if (!job || - job->direction() != QXmppTransferJob::IncomingDirection || - job->method() != QXmppTransferJob::InBandMethod || - job->state() != QXmppTransferJob::TransferState) - { - // the job is unknown, cancel it - QXmppStanza::Error error(QXmppStanza::Error::Cancel, QXmppStanza::Error::ItemNotFound); - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - return; - } - - if (iq.sequence() != job->m_ibbSequence) - { - // the packet is out of sequence - QXmppStanza::Error error(QXmppStanza::Error::Cancel, QXmppStanza::Error::UnexpectedRequest); - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - return; - } - - // write data - job->writeData(iq.payload()); - job->m_ibbSequence++; - - // acknowledge the packet - response.setType(QXmppIq::Result); - m_stream->sendPacket(response); -} - -void QXmppTransferManager::ibbOpenIqReceived(const QXmppIbbOpenIq &iq) -{ - QXmppIq response; - response.setTo(iq.from()); - response.setId(iq.id()); - - QXmppTransferJob *job = getJobBySid(iq.from(), iq.sid()); - if (!job || - job->direction() != QXmppTransferJob::IncomingDirection || - job->method() != QXmppTransferJob::InBandMethod) - { - // the job is unknown, cancel it - QXmppStanza::Error error(QXmppStanza::Error::Cancel, QXmppStanza::Error::ItemNotFound); - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - return; - } - - if (iq.blockSize() > m_ibbBlockSize) - { - // we prefer a smaller block size - QXmppStanza::Error error(QXmppStanza::Error::Modify, QXmppStanza::Error::ResourceConstraint); - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - return; - } - - job->m_blockSize = iq.blockSize(); - job->setState(QXmppTransferJob::TransferState); - - // accept transfer - response.setType(QXmppIq::Result); - m_stream->sendPacket(response); -} - -void QXmppTransferManager::ibbResponseReceived(const QXmppIq &iq) -{ - QXmppTransferJob *job = getJobByRequestId(iq.from(), iq.id()); - if (!job || - job->direction() != QXmppTransferJob::OutgoingDirection || - job->method() != QXmppTransferJob::InBandMethod || - job->state() == QXmppTransferJob::FinishedState) - return; - - // if the IO device is closed, do nothing - if (!job->m_iodevice->isOpen()) - return; - - if (iq.type() == QXmppIq::Result) - { - const QByteArray buffer = job->m_iodevice->read(job->m_blockSize); - job->setState(QXmppTransferJob::TransferState); - if (buffer.size()) - { - // send next data block - QXmppIbbDataIq dataIq; - dataIq.setTo(job->m_jid); - dataIq.setSid(job->m_sid); - dataIq.setSequence(job->m_ibbSequence++); - dataIq.setPayload(buffer); - job->m_requestId = dataIq.id(); - m_stream->sendPacket(dataIq); - - job->m_done += buffer.size(); - job->progress(job->m_done, job->fileSize()); - } else { - // close the bytestream - QXmppIbbCloseIq closeIq; - closeIq.setTo(job->m_jid); - closeIq.setSid(job->m_sid); - job->m_requestId = closeIq.id(); - m_stream->sendPacket(closeIq); - - job->terminate(QXmppTransferJob::NoError); - } - } - else if (iq.type() == QXmppIq::Error) - { - // close the bytestream - QXmppIbbCloseIq closeIq; - closeIq.setTo(job->m_jid); - closeIq.setSid(job->m_sid); - job->m_requestId = closeIq.id(); - m_stream->sendPacket(closeIq); - - job->terminate(QXmppTransferJob::ProtocolError); - } -} - -void QXmppTransferManager::iqReceived(const QXmppIq &iq) -{ - // handle IQ from proxy - foreach (QXmppTransferJob *job, m_jobs) - { - if (job->m_socksProxy.jid() == iq.from() && job->m_requestId == iq.id()) - { - if (job->m_socksSocket) - { - // proxy connection activation result - if (iq.type() == QXmppIq::Result) - { - // proxy stream activated, start sending data - job->setState(QXmppTransferJob::TransferState); - connect(job->m_socksSocket, SIGNAL(bytesWritten(qint64)), job, SLOT(sendData())); - connect(job->m_iodevice, SIGNAL(readyRead()), job, SLOT(sendData())); - job->sendData(); - } else if (iq.type() == QXmppIq::Error) { - // proxy stream not activated, terminate - emit logMessage(QXmppLogger::WarningMessage, "Could not activate SOCKS5 proxy bytestream"); - job->terminate(QXmppTransferJob::ProtocolError); - } - } else { - // we could not get host/port from proxy, procede without a proxy - if (iq.type() == QXmppIq::Error) - socksServerSendOffer(job); - } - return; - } - } - - QXmppTransferJob *job = getJobByRequestId(iq.from(), iq.id()); - if (!job) - return; - - if (job->method() == QXmppTransferJob::InBandMethod) - ibbResponseReceived(iq); - else if (job->method() == QXmppTransferJob::SocksMethod) - byteStreamResponseReceived(iq); - else if (iq.type() == QXmppIq::Error) { - // remote party cancelled stream initiation - job->terminate(QXmppTransferJob::AbortError); - } -} - -void QXmppTransferManager::jobDestroyed(QObject *object) -{ - m_jobs.removeAll(static_cast<QXmppTransferJob*>(object)); -} - -void QXmppTransferManager::jobError(QXmppTransferJob::Error error) -{ - QXmppTransferJob *job = qobject_cast<QXmppTransferJob *>(sender()); - if (!job || !m_jobs.contains(job)) - return; - - if (job->direction() == QXmppTransferJob::OutgoingDirection && - job->method() == QXmppTransferJob::InBandMethod && - error == QXmppTransferJob::AbortError) - { - // close the bytestream - QXmppIbbCloseIq closeIq; - closeIq.setTo(job->m_jid); - closeIq.setSid(job->m_sid); - job->m_requestId = closeIq.id(); - m_stream->sendPacket(closeIq); - } -} - -void QXmppTransferManager::jobFinished() -{ - QXmppTransferJob *job = qobject_cast<QXmppTransferJob *>(sender()); - if (!job || !m_jobs.contains(job)) - return; - - emit finished(job); -} - -void QXmppTransferManager::jobStateChanged(QXmppTransferJob::State state) -{ - QXmppTransferJob *job = qobject_cast<QXmppTransferJob *>(sender()); - if (!job || !m_jobs.contains(job)) - return; - - if (job->direction() != QXmppTransferJob::IncomingDirection) - return; - - // disconnect from the signal - disconnect(job, SIGNAL(stateChanged(QXmppTransferJob::State)), this, SLOT(jobStateChanged(QXmppTransferJob::State))); - - QXmppStreamInitiationIq response; - response.setTo(job->jid()); - response.setId(job->m_offerId); - - // the job was refused by the local party - if (state != QXmppTransferJob::StartState || !job->m_iodevice || !job->m_iodevice->isWritable()) - { - QXmppStanza::Error error(QXmppStanza::Error::Cancel, QXmppStanza::Error::Forbidden); - error.setCode(403); - - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - - job->terminate(QXmppTransferJob::AbortError); - return; - } - - // the job was accepted by the local party - connect(job, SIGNAL(error(QXmppTransferJob::Error)), this, SLOT(jobError(QXmppTransferJob::Error))); - - QXmppElement value; - value.setTagName("value"); - if (job->method() == QXmppTransferJob::InBandMethod) - value.setValue(ns_ibb); - else if (job->method() == QXmppTransferJob::SocksMethod) - value.setValue(ns_bytestreams); - - QXmppElement field; - field.setTagName("field"); - field.setAttribute("var", "stream-method"); - field.appendChild(value); - - QXmppElement x; - x.setTagName("x"); - x.setAttribute("xmlns", "jabber:x:data"); - x.setAttribute("type", "submit"); - x.appendChild(field); - - QXmppElement feature; - feature.setTagName("feature"); - feature.setAttribute("xmlns", ns_feature_negotiation); - feature.appendChild(x); - - response.setType(QXmppIq::Result); - response.setProfile(QXmppStreamInitiationIq::FileTransfer); - response.setSiItems(feature); - - m_stream->sendPacket(response); -} - -/// Send file to a remote party. -/// -/// The remote party will be given the choice to accept or refuse the transfer. -/// -QXmppTransferJob *QXmppTransferManager::sendFile(const QString &jid, const QString &fileName, const QString &sid) -{ - QFileInfo info(fileName); - - QXmppTransferFileInfo fileInfo; - fileInfo.setDate(info.lastModified()); - fileInfo.setName(info.fileName()); - fileInfo.setSize(info.size()); - - // open file - QIODevice *device = new QFile(fileName); - if (!device->open(QIODevice::ReadOnly)) - { - delete device; - device = 0; - } - - // hash file - if (device && !device->isSequential()) - { - QCryptographicHash hash(QCryptographicHash::Md5); - QByteArray buffer; - while (device->bytesAvailable()) - { - buffer = device->read(16384); - hash.addData(buffer); - } - device->reset(); - fileInfo.setHash(hash.result()); - } - - // create job - return sendFile(jid, device, fileInfo, sid); -} - -/// Send file to a remote party. -/// -/// The remote party will be given the choice to accept or refuse the transfer. -/// -QXmppTransferJob *QXmppTransferManager::sendFile(const QString &jid, QIODevice *device, const QXmppTransferFileInfo &fileInfo, const QString &sid) -{ - QXmppTransferJob *job = new QXmppTransferJob(jid, QXmppTransferJob::OutgoingDirection, this); - if (sid.isEmpty()) - job->m_sid = generateStanzaHash(); - else - job->m_sid = sid; - job->m_fileInfo = fileInfo; - job->m_iodevice = device; - if (device) - device->setParent(job); - - // check file is open - if (!device || !device->isReadable()) - { - job->terminate(QXmppTransferJob::FileAccessError); - return job; - } - - // check we support some methods - if (!m_supportedMethods) - { - job->terminate(QXmppTransferJob::ProtocolError); - return job; - } - - // prepare negotiation - QXmppElementList items; - - QXmppElement file; - file.setTagName("file"); - file.setAttribute("xmlns", ns_stream_initiation_file_transfer); - file.setAttribute("date", datetimeToString(job->fileDate())); - file.setAttribute("hash", job->fileHash().toHex()); - file.setAttribute("name", job->fileName()); - file.setAttribute("size", QString::number(job->fileSize())); - items.append(file); - - QXmppElement feature; - feature.setTagName("feature"); - feature.setAttribute("xmlns", ns_feature_negotiation); - - QXmppElement x; - x.setTagName("x"); - x.setAttribute("xmlns", "jabber:x:data"); - x.setAttribute("type", "form"); - feature.appendChild(x); - - QXmppElement field; - field.setTagName("field"); - field.setAttribute("var", "stream-method"); - field.setAttribute("type", "list-single"); - x.appendChild(field); - - // add supported stream methods - if (m_supportedMethods & QXmppTransferJob::InBandMethod) - { - QXmppElement option; - option.setTagName("option"); - field.appendChild(option); - - QXmppElement value; - value.setTagName("value"); - value.setValue(ns_ibb); - option.appendChild(value); - } - if (m_supportedMethods & QXmppTransferJob::SocksMethod) - { - QXmppElement option; - option.setTagName("option"); - field.appendChild(option); - - QXmppElement value; - value.setTagName("value"); - value.setValue(ns_bytestreams); - option.appendChild(value); - } - - items.append(feature); - - // start job - m_jobs.append(job); - connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(jobDestroyed(QObject*))); - connect(job, SIGNAL(error(QXmppTransferJob::Error)), this, SLOT(jobError(QXmppTransferJob::Error))); - connect(job, SIGNAL(finished()), this, SLOT(jobFinished())); - - QXmppStreamInitiationIq request; - request.setType(QXmppIq::Set); - request.setTo(jid); - request.setProfile(QXmppStreamInitiationIq::FileTransfer); - request.setSiItems(items); - request.setSiId(job->m_sid); - job->m_requestId = request.id(); - m_stream->sendPacket(request); - - return job; -} - -void QXmppTransferManager::socksServerConnected(QTcpSocket *socket, const QString &hostName, quint16 port) -{ - const QString ownJid = m_stream->configuration().jid(); - foreach (QXmppTransferJob *job, m_jobs) - { - if (hostName == streamHash(job->m_sid, ownJid, job->jid()) && port == 0) - { - job->m_socksSocket = socket; - return; - } - } - emit logMessage(QXmppLogger::WarningMessage, "QXmppSocksServer got a connection for a unknown stream"); - socket->close(); -} - -void QXmppTransferManager::socksServerSendOffer(QXmppTransferJob *job) -{ - const QString ownJid = m_stream->configuration().jid(); - QList<QXmppByteStreamIq::StreamHost> streamHosts; - - // discover local IPs - if (!m_proxyOnly) - { - foreach (const QNetworkInterface &interface, QNetworkInterface::allInterfaces()) - { - if (!(interface.flags() & QNetworkInterface::IsRunning) || - interface.flags() & QNetworkInterface::IsLoopBack) - continue; - - foreach (const QNetworkAddressEntry &entry, interface.addressEntries()) - { - if (entry.ip().protocol() != QAbstractSocket::IPv4Protocol || - entry.netmask().isNull() || - entry.netmask() == QHostAddress::Broadcast) - continue; - - QXmppByteStreamIq::StreamHost streamHost; - streamHost.setHost(entry.ip()); - streamHost.setPort(m_socksServer->serverPort()); - streamHost.setJid(ownJid); - streamHosts.append(streamHost); - } - } - } - - // add proxy - if (!job->m_socksProxy.jid().isEmpty()) - streamHosts.append(job->m_socksProxy); - - // check we have some stream hosts - if (!streamHosts.size()) - { - emit logMessage(QXmppLogger::WarningMessage, "Could not determine local stream hosts"); - job->terminate(QXmppTransferJob::ProtocolError); - return; - } - - // send offer - QXmppByteStreamIq streamIq; - streamIq.setType(QXmppIq::Set); - streamIq.setTo(job->m_jid); - streamIq.setSid(job->m_sid); - streamIq.setStreamHosts(streamHosts); - job->m_requestId = streamIq.id(); - m_stream->sendPacket(streamIq); -} - -void QXmppTransferManager::streamInitiationIqReceived(const QXmppStreamInitiationIq &iq) -{ - if (iq.type() == QXmppIq::Result) - streamInitiationResultReceived(iq); - else if (iq.type() == QXmppIq::Set) - streamInitiationSetReceived(iq); -} - -// The remote party has accepted an outgoing transfer. -void QXmppTransferManager::streamInitiationResultReceived(const QXmppStreamInitiationIq &iq) -{ - QXmppTransferJob *job = getJobByRequestId(iq.from(), iq.id()); - if (!job || - job->direction() != QXmppTransferJob::OutgoingDirection || - job->state() != QXmppTransferJob::OfferState) - return; - - foreach (const QXmppElement &item, iq.siItems()) - { - if (item.tagName() == "feature" && item.attribute("xmlns") == ns_feature_negotiation) - { - QXmppElement field = item.firstChildElement("x").firstChildElement("field"); - while (!field.isNull()) - { - if (field.attribute("var") == "stream-method") - { - if ((field.firstChildElement("value").value() == ns_ibb) && - (m_supportedMethods & QXmppTransferJob::InBandMethod)) - job->m_method = QXmppTransferJob::InBandMethod; - else if ((field.firstChildElement("value").value() == ns_bytestreams) && - (m_supportedMethods & QXmppTransferJob::SocksMethod)) - job->m_method = QXmppTransferJob::SocksMethod; - } - field = field.nextSiblingElement("field"); - } - } - } - - // remote party accepted stream initiation - job->setState(QXmppTransferJob::StartState); - if (job->method() == QXmppTransferJob::InBandMethod) - { - // lower block size for IBB - job->m_blockSize = m_ibbBlockSize; - - QXmppIbbOpenIq openIq; - openIq.setTo(job->m_jid); - openIq.setSid(job->m_sid); - openIq.setBlockSize(job->m_blockSize); - job->m_requestId = openIq.id(); - m_stream->sendPacket(openIq); - } else if (job->method() == QXmppTransferJob::SocksMethod) { - if (!m_socksServer->isListening()) - { - emit logMessage(QXmppLogger::WarningMessage, "QXmppSocksServer is not listening"); - job->terminate(QXmppTransferJob::ProtocolError); - return; - } - if (!m_proxy.isEmpty()) - { - job->m_socksProxy.setJid(m_proxy); - - // query proxy - QXmppByteStreamIq streamIq; - streamIq.setType(QXmppIq::Get); - streamIq.setTo(job->m_socksProxy.jid()); - streamIq.setSid(job->m_sid); - job->m_requestId = streamIq.id(); - m_stream->sendPacket(streamIq); - } else { - socksServerSendOffer(job); - } - } else { - emit logMessage(QXmppLogger::WarningMessage, "QXmppTransferManager received an unsupported method"); - job->terminate(QXmppTransferJob::ProtocolError); - } -} - -void QXmppTransferManager::streamInitiationSetReceived(const QXmppStreamInitiationIq &iq) -{ - QXmppStreamInitiationIq response; - response.setTo(iq.from()); - response.setId(iq.id()); - - // check we support the profile - if (iq.profile() != QXmppStreamInitiationIq::FileTransfer) - { - // FIXME : we should add: - // <bad-profile xmlns='http://jabber.org/protocol/si'/> - QXmppStanza::Error error(QXmppStanza::Error::Cancel, QXmppStanza::Error::BadRequest); - error.setCode(400); - - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - return; - } - - // check there is a receiver connected to the fileReceived() signal - if (!receivers(SIGNAL(fileReceived(QXmppTransferJob*)))) - { - QXmppStanza::Error error(QXmppStanza::Error::Cancel, QXmppStanza::Error::Forbidden); - error.setCode(403); - - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - return; - } - - // check the stream type - QXmppTransferJob *job = new QXmppTransferJob(iq.from(), QXmppTransferJob::IncomingDirection, this); - int offeredMethods = QXmppTransferJob::NoMethod; - job->m_offerId = iq.id(); - job->m_sid = iq.siId(); - job->m_mimeType = iq.mimeType(); - foreach (const QXmppElement &item, iq.siItems()) - { - if (item.tagName() == "feature" && item.attribute("xmlns") == ns_feature_negotiation) - { - QXmppElement field = item.firstChildElement("x").firstChildElement("field"); - while (!field.isNull()) - { - if (field.attribute("var") == "stream-method" && field.attribute("type") == "list-single") - { - QXmppElement option = field.firstChildElement("option"); - while (!option.isNull()) - { - if (option.firstChildElement("value").value() == ns_ibb) - offeredMethods = offeredMethods | QXmppTransferJob::InBandMethod; - else if (option.firstChildElement("value").value() == ns_bytestreams) - offeredMethods = offeredMethods | QXmppTransferJob::SocksMethod; - option = option.nextSiblingElement("option"); - } - } - field = field.nextSiblingElement("field"); - } - } - else if (item.tagName() == "file" && item.attribute("xmlns") == ns_stream_initiation_file_transfer) - { - job->m_fileInfo.setDate(datetimeFromString(item.attribute("date"))); - job->m_fileInfo.setHash(QByteArray::fromHex(item.attribute("hash").toAscii())); - job->m_fileInfo.setName(item.attribute("name")); - job->m_fileInfo.setSize(item.attribute("size").toLongLong()); - } - } - - // select a method supported by both parties - int sharedMethods = (offeredMethods & m_supportedMethods); - if (sharedMethods & QXmppTransferJob::SocksMethod) - job->m_method = QXmppTransferJob::SocksMethod; - else if (sharedMethods & QXmppTransferJob::InBandMethod) - job->m_method = QXmppTransferJob::InBandMethod; - else - { - // FIXME : we should add: - // <no-valid-streams xmlns='http://jabber.org/protocol/si'/> - QXmppStanza::Error error(QXmppStanza::Error::Cancel, QXmppStanza::Error::BadRequest); - error.setCode(400); - - response.setType(QXmppIq::Error); - response.setError(error); - m_stream->sendPacket(response); - - delete job; - return; - } - - // register job - m_jobs.append(job); - connect(job, SIGNAL(destroyed(QObject*)), this, SLOT(jobDestroyed(QObject*))); - connect(job, SIGNAL(finished()), this, SLOT(jobFinished())); - connect(job, SIGNAL(stateChanged(QXmppTransferJob::State)), this, SLOT(jobStateChanged(QXmppTransferJob::State))); - - // allow user to accept or decline the job - emit fileReceived(job); -} - -/// Return the JID of the bytestream proxy to use for -/// outgoing transfers. -/// - -QString QXmppTransferManager::proxy() const -{ - return m_proxy; -} - -/// Set the JID of the SOCKS5 bytestream proxy to use for -/// outgoing transfers. -/// -/// If you set a proxy, when you send a file the proxy will -/// be offered to the recipient in addition to your own IP -/// addresses. -/// - -void QXmppTransferManager::setProxy(const QString &proxyJid) -{ - m_proxy = proxyJid; -} - -/// Return whether the proxy will systematically be used for -/// outgoing SOCKS5 bytestream transfers. -/// - -bool QXmppTransferManager::proxyOnly() const -{ - return m_proxyOnly; -} - -/// Set whether the proxy should systematically be used for -/// outgoing SOCKS5 bytestream transfers. -/// -/// \note If you set this to true and do not provide a proxy -/// using setProxy(), your outgoing transfers will fail! -/// - -void QXmppTransferManager::setProxyOnly(bool proxyOnly) -{ - m_proxyOnly = proxyOnly; -} - -/// Return the supported stream methods. -/// -/// The methods are a combination of zero or more QXmppTransferJob::Method. -/// - -QXmppTransferJob::Methods QXmppTransferManager::supportedMethods() const -{ - return m_supportedMethods; -} - -/// Set the supported stream methods. This allows you to selectively -/// enable or disable stream methods (In-Band or SOCKS5 bytestreams). -/// -/// The methods argument is a combination of zero or more -/// QXmppTransferJob::Method. -/// - -void QXmppTransferManager::setSupportedMethods(QXmppTransferJob::Methods methods) -{ - m_supportedMethods = methods; -} diff --git a/source/QXmppTransferManager.h b/source/QXmppTransferManager.h deleted file mode 100644 index c3ef6d9a..00000000 --- a/source/QXmppTransferManager.h +++ /dev/null @@ -1,280 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPTRANSFERMANAGER_H -#define QXMPPTRANSFERMANAGER_H - -#include <QCryptographicHash> -#include <QDateTime> -#include <QHash> -#include <QHostAddress> -#include <QVariant> - -#include "QXmppIq.h" -#include "QXmppByteStreamIq.h" -#include "QXmppLogger.h" - -class QTcpSocket; -class QXmppByteStreamIq; -class QXmppStream; -class QXmppIbbCloseIq; -class QXmppIbbDataIq; -class QXmppIbbOpenIq; -class QXmppSocksClient; -class QXmppSocksServer; -class QXmppStreamInitiationIq; - -class QXmppTransferFileInfo -{ -public: - QXmppTransferFileInfo(); - - QDateTime date() const; - void setDate(const QDateTime &date); - - QByteArray hash() const; - void setHash(const QByteArray &hash); - - QString name() const; - void setName(const QString &name); - - qint64 size() const; - void setSize(qint64 size); - - bool operator==(const QXmppTransferFileInfo &other) const; - -private: - QDateTime m_date; - QByteArray m_hash; - QString m_name; - qint64 m_size; -}; - -/// \brief The QXmppTransferJob class represents a single file transfer job. -/// -/// \sa QXmppTransferManager -/// - -class QXmppTransferJob : public QObject -{ - Q_OBJECT - -public: - /// This enum is used to describe the direction of a transfer job. - enum Direction - { - IncomingDirection, ///< The file is being received. - OutgoingDirection, ///< The file is being sent. - }; - - /// This enum is used to describe the type of error encountered by a transfer job. - enum Error - { - NoError = 0, ///< No error occured. - AbortError, ///< The file transfer was aborted. - FileAccessError, ///< An error was encountered trying to access a local file. - FileCorruptError, ///< The file is corrupt: the file size or hash do not match. - ProtocolError, ///< An error was encountered in the file transfer protocol. - }; - - /// This enum is used to describe a transfer method. - enum Method - { - NoMethod = 0, ///< No transfer method. - InBandMethod = 1, ///< XEP-0047: In-Band Bytestreams - SocksMethod = 2, ///< XEP-0065: SOCKS5 Bytestreams - AnyMethod = 3, ///< Any supported transfer method. - }; - Q_DECLARE_FLAGS(Methods, Method) - - /// This enum is used to describe the state of a transfer job. - enum State - { - OfferState = 0, ///< The transfer is being offered to the remote party. - StartState = 1, ///< The transfer is being connected. - TransferState = 2, ///< The transfer is ongoing. - FinishedState = 3, ///< The transfer is finished. - }; - - void abort(); - void accept(QIODevice *output); - - QVariant data(int role) const; - void setData(int role, const QVariant &value); - - QXmppTransferJob::Direction direction() const; - QXmppTransferJob::Error error() const; - QString jid() const; - QXmppTransferJob::Method method() const; - QString sid() const; - QXmppTransferJob::State state() const; - - // XEP-0096 : File transfer - QXmppTransferFileInfo fileInfo() const; - QDateTime fileDate() const; - QByteArray fileHash() const; - QString fileName() const; - qint64 fileSize() const; - -signals: - /// This signal is emitted when an error is encountered while - /// processing the transfer job. - void error(QXmppTransferJob::Error error); - - /// This signal is emitted when the transfer job is finished. - /// - /// You can determine if the job completed successfully by testing whether - /// error() returns QXmppTransferJob::NoError. - /// - /// Note: Do not delete the job in the slot connected to this signal, - /// instead use deleteLater(). - void finished(); - - /// This signal is emitted to indicate the progress of this transfer job. - void progress(qint64 done, qint64 total); - - /// This signal is emitted when the transfer job changes state. - void stateChanged(QXmppTransferJob::State state); - -private slots: - void disconnected(); - void receiveData(); - void sendData(); - void slotTerminated(); - -private: - QXmppTransferJob(const QString &jid, QXmppTransferJob::Direction direction, QObject *parent); - void checkData(); - void setState(QXmppTransferJob::State state); - void terminate(QXmppTransferJob::Error error); - bool writeData(const QByteArray &data); - - int m_blockSize; - QXmppTransferJob::Direction m_direction; - qint64 m_done; - QXmppTransferJob::Error m_error; - QCryptographicHash m_hash; - QIODevice *m_iodevice; - QString m_offerId; - QString m_jid; - QString m_sid; - Method m_method; - QString m_mimeType; - QString m_requestId; - State m_state; - - // arbitrary data - QHash<int, QVariant> m_data; - - // file meta-data - QXmppTransferFileInfo m_fileInfo; - - // for in-band bytestreams - int m_ibbSequence; - - // for socks5 bytestreams - QTcpSocket *m_socksSocket; - QXmppByteStreamIq::StreamHost m_socksProxy; - - friend class QXmppTransferManager; -}; - -/// \brief The QXmppTransferManager class provides support for sending and -/// receiving files. -/// -/// Stream initiation is performed as described in XEP-0095: Stream Initiation -/// and XEP-0096: SI File Transfer. The actual file transfer is then performed -/// using either XEP-0065: SOCKS5 Bytestreams or XEP-0047: In-Band Bytestreams. -/// -/// \ingroup Managers - -class QXmppTransferManager : public QObject -{ - Q_OBJECT - -public: - QXmppTransferManager(QXmppStream *stream, QObject *parent = 0); - QXmppTransferJob *sendFile(const QString &jid, const QString &fileName, const QString &sid = QString()); - QXmppTransferJob *sendFile(const QString &jid, QIODevice *device, const QXmppTransferFileInfo &fileInfo, const QString &sid = QString()); - - QString proxy() const; - void setProxy(const QString &proxyJid); - - bool proxyOnly() const; - void setProxyOnly(bool proxyOnly); - - QXmppTransferJob::Methods supportedMethods() const; - void setSupportedMethods(QXmppTransferJob::Methods methods); - -signals: - /// This signal is emitted when a new file transfer offer is received. - /// - /// To accept the transfer job, call the job's QXmppTransferJob::accept() method. - /// To refuse the transfer job, call the job's QXmppTransferJob::abort() method. - void fileReceived(QXmppTransferJob *offer); - - /// This signal is emitted whenever a transfer job is finished. - /// - /// \sa QXmppTransferJob::finished() - void finished(QXmppTransferJob *job); - - /// This signal is emitted to send logging messages. - void logMessage(QXmppLogger::MessageType type, const QString &msg); - -private slots: - void byteStreamIqReceived(const QXmppByteStreamIq&); - void ibbCloseIqReceived(const QXmppIbbCloseIq&); - void ibbDataIqReceived(const QXmppIbbDataIq&); - void ibbOpenIqReceived(const QXmppIbbOpenIq&); - void iqReceived(const QXmppIq&); - void jobDestroyed(QObject *object); - void jobError(QXmppTransferJob::Error error); - void jobFinished(); - void jobStateChanged(QXmppTransferJob::State state); - void socksServerConnected(QTcpSocket *socket, const QString &hostName, quint16 port); - void streamInitiationIqReceived(const QXmppStreamInitiationIq&); - -private: - QXmppTransferJob *getJobByRequestId(const QString &jid, const QString &id); - QXmppTransferJob *getJobBySid(const QString &jid, const QString &sid); - void byteStreamResponseReceived(const QXmppIq&); - void byteStreamResultReceived(const QXmppByteStreamIq&); - void byteStreamSetReceived(const QXmppByteStreamIq&); - void ibbResponseReceived(const QXmppIq&); - void streamInitiationResultReceived(const QXmppStreamInitiationIq&); - void streamInitiationSetReceived(const QXmppStreamInitiationIq&); - void socksServerSendOffer(QXmppTransferJob *job); - - // reference to XMPP stream (no ownership) - QXmppStream* m_stream; - int m_ibbBlockSize; - QList<QXmppTransferJob*> m_jobs; - QString m_proxy; - bool m_proxyOnly; - QXmppSocksServer *m_socksServer; - QXmppTransferJob::Methods m_supportedMethods; -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(QXmppTransferJob::Methods) - -#endif diff --git a/source/QXmppUtils.cpp b/source/QXmppUtils.cpp deleted file mode 100644 index dc8f6a4b..00000000 --- a/source/QXmppUtils.cpp +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 <QBuffer> -#include <QByteArray> -#include <QCryptographicHash> -#include <QDateTime> -#include <QDebug> -#include <QRegExp> -#include <QString> -#include <QXmlStreamWriter> - -#include "QXmppUtils.h" -#include "QXmppLogger.h" - -// adapted from public domain source by Ross Williams and Eric Durbin -// FIXME : is this valid for big-endian machines? -static quint32 crctable[256] = -{ - 0x00000000L, 0x77073096L, 0xEE0E612CL, 0x990951BAL, - 0x076DC419L, 0x706AF48FL, 0xE963A535L, 0x9E6495A3L, - 0x0EDB8832L, 0x79DCB8A4L, 0xE0D5E91EL, 0x97D2D988L, - 0x09B64C2BL, 0x7EB17CBDL, 0xE7B82D07L, 0x90BF1D91L, - 0x1DB71064L, 0x6AB020F2L, 0xF3B97148L, 0x84BE41DEL, - 0x1ADAD47DL, 0x6DDDE4EBL, 0xF4D4B551L, 0x83D385C7L, - 0x136C9856L, 0x646BA8C0L, 0xFD62F97AL, 0x8A65C9ECL, - 0x14015C4FL, 0x63066CD9L, 0xFA0F3D63L, 0x8D080DF5L, - 0x3B6E20C8L, 0x4C69105EL, 0xD56041E4L, 0xA2677172L, - 0x3C03E4D1L, 0x4B04D447L, 0xD20D85FDL, 0xA50AB56BL, - 0x35B5A8FAL, 0x42B2986CL, 0xDBBBC9D6L, 0xACBCF940L, - 0x32D86CE3L, 0x45DF5C75L, 0xDCD60DCFL, 0xABD13D59L, - 0x26D930ACL, 0x51DE003AL, 0xC8D75180L, 0xBFD06116L, - 0x21B4F4B5L, 0x56B3C423L, 0xCFBA9599L, 0xB8BDA50FL, - 0x2802B89EL, 0x5F058808L, 0xC60CD9B2L, 0xB10BE924L, - 0x2F6F7C87L, 0x58684C11L, 0xC1611DABL, 0xB6662D3DL, - 0x76DC4190L, 0x01DB7106L, 0x98D220BCL, 0xEFD5102AL, - 0x71B18589L, 0x06B6B51FL, 0x9FBFE4A5L, 0xE8B8D433L, - 0x7807C9A2L, 0x0F00F934L, 0x9609A88EL, 0xE10E9818L, - 0x7F6A0DBBL, 0x086D3D2DL, 0x91646C97L, 0xE6635C01L, - 0x6B6B51F4L, 0x1C6C6162L, 0x856530D8L, 0xF262004EL, - 0x6C0695EDL, 0x1B01A57BL, 0x8208F4C1L, 0xF50FC457L, - 0x65B0D9C6L, 0x12B7E950L, 0x8BBEB8EAL, 0xFCB9887CL, - 0x62DD1DDFL, 0x15DA2D49L, 0x8CD37CF3L, 0xFBD44C65L, - 0x4DB26158L, 0x3AB551CEL, 0xA3BC0074L, 0xD4BB30E2L, - 0x4ADFA541L, 0x3DD895D7L, 0xA4D1C46DL, 0xD3D6F4FBL, - 0x4369E96AL, 0x346ED9FCL, 0xAD678846L, 0xDA60B8D0L, - 0x44042D73L, 0x33031DE5L, 0xAA0A4C5FL, 0xDD0D7CC9L, - 0x5005713CL, 0x270241AAL, 0xBE0B1010L, 0xC90C2086L, - 0x5768B525L, 0x206F85B3L, 0xB966D409L, 0xCE61E49FL, - 0x5EDEF90EL, 0x29D9C998L, 0xB0D09822L, 0xC7D7A8B4L, - 0x59B33D17L, 0x2EB40D81L, 0xB7BD5C3BL, 0xC0BA6CADL, - 0xEDB88320L, 0x9ABFB3B6L, 0x03B6E20CL, 0x74B1D29AL, - 0xEAD54739L, 0x9DD277AFL, 0x04DB2615L, 0x73DC1683L, - 0xE3630B12L, 0x94643B84L, 0x0D6D6A3EL, 0x7A6A5AA8L, - 0xE40ECF0BL, 0x9309FF9DL, 0x0A00AE27L, 0x7D079EB1L, - 0xF00F9344L, 0x8708A3D2L, 0x1E01F268L, 0x6906C2FEL, - 0xF762575DL, 0x806567CBL, 0x196C3671L, 0x6E6B06E7L, - 0xFED41B76L, 0x89D32BE0L, 0x10DA7A5AL, 0x67DD4ACCL, - 0xF9B9DF6FL, 0x8EBEEFF9L, 0x17B7BE43L, 0x60B08ED5L, - 0xD6D6A3E8L, 0xA1D1937EL, 0x38D8C2C4L, 0x4FDFF252L, - 0xD1BB67F1L, 0xA6BC5767L, 0x3FB506DDL, 0x48B2364BL, - 0xD80D2BDAL, 0xAF0A1B4CL, 0x36034AF6L, 0x41047A60L, - 0xDF60EFC3L, 0xA867DF55L, 0x316E8EEFL, 0x4669BE79L, - 0xCB61B38CL, 0xBC66831AL, 0x256FD2A0L, 0x5268E236L, - 0xCC0C7795L, 0xBB0B4703L, 0x220216B9L, 0x5505262FL, - 0xC5BA3BBEL, 0xB2BD0B28L, 0x2BB45A92L, 0x5CB36A04L, - 0xC2D7FFA7L, 0xB5D0CF31L, 0x2CD99E8BL, 0x5BDEAE1DL, - 0x9B64C2B0L, 0xEC63F226L, 0x756AA39CL, 0x026D930AL, - 0x9C0906A9L, 0xEB0E363FL, 0x72076785L, 0x05005713L, - 0x95BF4A82L, 0xE2B87A14L, 0x7BB12BAEL, 0x0CB61B38L, - 0x92D28E9BL, 0xE5D5BE0DL, 0x7CDCEFB7L, 0x0BDBDF21L, - 0x86D3D2D4L, 0xF1D4E242L, 0x68DDB3F8L, 0x1FDA836EL, - 0x81BE16CDL, 0xF6B9265BL, 0x6FB077E1L, 0x18B74777L, - 0x88085AE6L, 0xFF0F6A70L, 0x66063BCAL, 0x11010B5CL, - 0x8F659EFFL, 0xF862AE69L, 0x616BFFD3L, 0x166CCF45L, - 0xA00AE278L, 0xD70DD2EEL, 0x4E048354L, 0x3903B3C2L, - 0xA7672661L, 0xD06016F7L, 0x4969474DL, 0x3E6E77DBL, - 0xAED16A4AL, 0xD9D65ADCL, 0x40DF0B66L, 0x37D83BF0L, - 0xA9BCAE53L, 0xDEBB9EC5L, 0x47B2CF7FL, 0x30B5FFE9L, - 0xBDBDF21CL, 0xCABAC28AL, 0x53B39330L, 0x24B4A3A6L, - 0xBAD03605L, 0xCDD70693L, 0x54DE5729L, 0x23D967BFL, - 0xB3667A2EL, 0xC4614AB8L, 0x5D681B02L, 0x2A6F2B94L, - 0xB40BBE37L, 0xC30C8EA1L, 0x5A05DF1BL, 0x2D02EF8DL -}; - -QDateTime datetimeFromString(const QString &str) -{ - QRegExp tzRe("(Z|([+-])([0-9]{2}):([0-9]{2}))"); - int tzPos = tzRe.indexIn(str, 19); - if (str.size() < 20 || tzPos < 0) - return QDateTime(); - - // process date and time - QDateTime dt = QDateTime::fromString(str.left(19), "yyyy-MM-ddThh:mm:ss"); - dt.setTimeSpec(Qt::UTC); - - // process milliseconds - if (tzPos > 20 && str.at(19) == '.') - { - QString millis = (str.mid(20, tzPos - 20) + "000").left(3); - dt = dt.addMSecs(millis.toInt()); - } - - // process time zone - if (tzRe.cap(1) != "Z") - { - int offset = tzRe.cap(3).toInt() * 3600 + tzRe.cap(4).toInt() * 60; - if (tzRe.cap(2) == "+") - dt = dt.addSecs(-offset); - else - dt = dt.addSecs(offset); - } - return dt; -} - -QString datetimeToString(const QDateTime &dt) -{ - QDateTime utc = dt.toUTC(); - if (utc.time().msec()) - return utc.toString("yyyy-MM-ddThh:mm:ss.zzzZ"); - else - return utc.toString("yyyy-MM-ddThh:mm:ssZ"); -} - -QString jidToResource(const QString& jid) -{ - const int pos = jid.indexOf(QChar('/')); - if (pos < 0) - return QString(); - return jid.mid(pos+1); -} - -QString jidToBareJid(const QString& jid) -{ - const int pos = jid.indexOf(QChar('/')); - if (pos < 0) - return jid; - return jid.left(pos); -} - -quint32 generateCrc32(const QByteArray &in) -{ - quint32 result = 0xffffffff; - for(int n = 0; n < in.size(); ++n) - result = (result >> 8) ^ (crctable[(result & 0xff) ^ (quint8)in[n]]); - return result ^= 0xffffffff; -} - -static QByteArray generateHmac(QCryptographicHash::Algorithm algorithm, const QByteArray &key, const QByteArray &text) -{ - QCryptographicHash hasher(algorithm); - - const int B = 64; - QByteArray kpad = key + QByteArray(B - key.size(), 0); - - QByteArray ba; - for (int i = 0; i < B; ++i) - ba += kpad[i] ^ 0x5c; - - QByteArray tmp; - for (int i = 0; i < B; ++i) - tmp += kpad[i] ^ 0x36; - hasher.addData(tmp); - hasher.addData(text); - ba += hasher.result(); - - hasher.reset(); - hasher.addData(ba); - return hasher.result(); -} - -QByteArray generateHmacMd5(const QByteArray &key, const QByteArray &text) -{ - return generateHmac(QCryptographicHash::Md5, key, text); -} - -QByteArray generateHmacSha1(const QByteArray &key, const QByteArray &text) -{ - return generateHmac(QCryptographicHash::Sha1, key, text); -} - -QString generateStanzaHash(int length) -{ - QString somechars = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; - QString hashResult; - for ( int idx = 0; idx < length; ++idx ) - { - hashResult += somechars[(qrand() % 61)]; - } - return hashResult; -} - -void helperToXmlAddAttribute(QXmlStreamWriter* stream, const QString& name, - const QString& value) -{ - if(!value.isEmpty()) - stream->writeAttribute(name,value); -} - -void helperToXmlAddNumberElement(QXmlStreamWriter* stream, const QString& name, int value) -{ - stream->writeTextElement( name, QString::number(value)); -} - -void helperToXmlAddTextElement(QXmlStreamWriter* stream, const QString& name, - const QString& value) -{ - if(!value.isEmpty()) - stream->writeTextElement( name, value); - else - stream->writeEmptyElement(name); -} - -QString escapeString(const QString& str) -{ - QString strOut = str; - strOut.replace(QChar('&'), "&"); - strOut.replace(QChar('<'), "<"); - strOut.replace(QChar('>'), ">"); - strOut.replace(QChar('"'), """); - return strOut; -} - -QString unescapeString(const QString& str) -{ - QString strOut = str; - strOut.replace("<", QChar('<')); - strOut.replace(">", QChar('>')); - strOut.replace(""", QChar('"')); - strOut.replace("&", QChar('&')); - return strOut; -} - - diff --git a/source/QXmppUtils.h b/source/QXmppUtils.h deleted file mode 100644 index 9421787c..00000000 --- a/source/QXmppUtils.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPUTILS_H -#define QXMPPUTILS_H - - -// forward declarations of QXmlStream* classes will not work on Mac, we need to -// include the whole header. -// See http://lists.trolltech.com/qt-interest/2008-07/thread00798-0.html -// for an explanation. -#include <QXmlStreamWriter> - -class QByteArray; -class QDateTime; -class QString; - -// XEP-0082: XMPP Date and Time Profiles -QDateTime datetimeFromString(const QString &str); -QString datetimeToString(const QDateTime &dt); - -QString jidToResource(const QString& jid); -QString jidToBareJid(const QString& jid); - -quint32 generateCrc32(const QByteArray &input); -QByteArray generateHmacMd5(const QByteArray &key, const QByteArray &text); -QByteArray generateHmacSha1(const QByteArray &key, const QByteArray &text); -QString generateStanzaHash(int length=32); - -void helperToXmlAddAttribute(QXmlStreamWriter* stream, const QString& name, - const QString& value); -void helperToXmlAddTextElement(QXmlStreamWriter* stream, const QString& name, - const QString& value); -void helperToXmlAddNumberElement(QXmlStreamWriter* stream, const QString& name, - int value); - -QString escapeString(const QString& str); -QString unescapeString(const QString& str); - -#endif // QXMPPUTILS_H diff --git a/source/QXmppVCard.cpp b/source/QXmppVCard.cpp deleted file mode 100644 index 12cb6ed0..00000000 --- a/source/QXmppVCard.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 <QBuffer> -#include <QXmlStreamWriter> - -#ifndef QXMPP_NO_GUI -#include <QImage> -#include <QImageReader> -#endif - -#include "QXmppVCard.h" -#include "QXmppUtils.h" -#include "QXmppConstants.h" - -static QString getImageType(const QByteArray& image) -{ -#ifndef QXMPP_NO_GUI - QBuffer buffer; - buffer.setData(image); - buffer.open(QIODevice::ReadOnly); - QString format = QImageReader::imageFormat(&buffer); - - if(format.toUpper() == "PNG") - return "image/png"; - else if(format.toUpper() == "MNG") - return "video/x-mng"; - else if(format.toUpper() == "GIF") - return "image/gif"; - else if(format.toUpper() == "BMP") - return "image/bmp"; - else if(format.toUpper() == "XPM") - return "image/x-xpm"; - else if(format.toUpper() == "SVG") - return "image/svg+xml"; - else if(format.toUpper() == "JPEG") - return "image/jpeg"; -#endif - - return "image/unknown"; -} - -QXmppVCard::QXmppVCard(const QString& jid) : QXmppIq(QXmppIq::Get) -{ - // for self jid should be empty - setTo(jid); -} - -QString QXmppVCard::firstName() const -{ - return m_firstName; -} - -void QXmppVCard::setFirstName(const QString &firstName) -{ - m_firstName = firstName; -} - -QString QXmppVCard::fullName() const -{ - return m_fullName; -} - -void QXmppVCard::setFullName(const QString& str) -{ - m_fullName = str; -} - -QString QXmppVCard::lastName() const -{ - return m_lastName; -} - -void QXmppVCard::setLastName(const QString &lastName) -{ - m_lastName = lastName; -} - -QString QXmppVCard::middleName() const -{ - return m_middleName; -} - -void QXmppVCard::setMiddleName(const QString &middleName) -{ - m_middleName = middleName; -} - -QString QXmppVCard::nickName() const -{ - return m_nickName; -} - -void QXmppVCard::setNickName(const QString& str) -{ - m_nickName = str; -} - -QString QXmppVCard::url() const -{ - return m_url; -} - -void QXmppVCard::setUrl(const QString& url) -{ - m_url = url; -} - -const QByteArray& QXmppVCard::photo() const -{ - return m_photo; -} - -void QXmppVCard::setPhoto(const QByteArray& photo) -{ - m_photo = photo; -} - -#ifndef QXMPP_NO_GUI -void QXmppVCard::setPhoto(const QImage& image) -{ - QByteArray ba; - QBuffer buffer(&ba); - buffer.open(QIODevice::WriteOnly); - image.save(&buffer, "PNG"); - m_photo = ba; -} -#endif - -void QXmppVCard::parseElementFromChild(const QDomElement& nodeRecv) -{ - // vCard - QDomElement cardElement = nodeRecv.firstChildElement("vCard"); - m_fullName = cardElement.firstChildElement("FN").text(); - m_nickName = cardElement.firstChildElement("NICKNAME").text(); - QDomElement nameElement = cardElement.firstChildElement("N"); - m_firstName = nameElement.firstChildElement("GIVEN").text(); - m_lastName = nameElement.firstChildElement("FAMILY").text(); - m_middleName = nameElement.firstChildElement("MIDDLE").text(); - m_url = cardElement.firstChildElement("URL").text(); - QByteArray base64data = cardElement. - firstChildElement("PHOTO"). - firstChildElement("BINVAL").text().toAscii(); - setPhoto(QByteArray::fromBase64(base64data)); -} - -void QXmppVCard::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("vCard"); - helperToXmlAddAttribute(writer,"xmlns", ns_vcard); - if (!m_fullName.isEmpty()) - helperToXmlAddTextElement(writer, "FN", m_fullName); - if(!m_nickName.isEmpty()) - helperToXmlAddTextElement(writer, "NICKNAME", m_nickName); - if (!m_firstName.isEmpty() || - !m_lastName.isEmpty() || - !m_middleName.isEmpty()) - { - writer->writeStartElement("N"); - if (!m_firstName.isEmpty()) - helperToXmlAddTextElement(writer, "GIVEN", m_firstName); - if (!m_lastName.isEmpty()) - helperToXmlAddTextElement(writer, "FAMILY", m_lastName); - if (!m_middleName.isEmpty()) - helperToXmlAddTextElement(writer, "MIDDLE", m_middleName); - writer->writeEndElement(); - } - if (!m_url.isEmpty()) - helperToXmlAddTextElement(writer, "URL", m_url); - - if(!photo().isEmpty()) - { - writer->writeStartElement("PHOTO"); - helperToXmlAddTextElement(writer, "TYPE", getImageType(photo())); - helperToXmlAddTextElement(writer, "BINVAL", photo().toBase64()); - writer->writeEndElement(); - } - - writer->writeEndElement(); -} - -#ifndef QXMPP_NO_GUI -QImage QXmppVCard::photoAsImage() const -{ - QBuffer buffer; - buffer.setData(m_photo); - buffer.open(QIODevice::ReadOnly); - QImageReader imageReader(&buffer); - return imageReader.read(); -} -#endif - -QString QXmppVCard::getFullName() const -{ - return m_fullName; -} - -QString QXmppVCard::getNickName() const -{ - return m_nickName; -} - -const QByteArray& QXmppVCard::getPhoto() const -{ - return m_photo; -} - -#ifndef QXMPP_NO_GUI -QImage QXmppVCard::getPhotoAsImage() const -{ - return photoAsImage(); -} -#endif - diff --git a/source/QXmppVCard.h b/source/QXmppVCard.h deleted file mode 100644 index c551849f..00000000 --- a/source/QXmppVCard.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPVCARD_H -#define QXMPPVCARD_H - -#include "QXmppIq.h" -#include <QMap> -#include <QDomElement> - -class QImage; - -class QXmppVCard : public QXmppIq -{ -public: - QXmppVCard(const QString& bareJid = ""); - - void setFirstName(const QString&); - void setFullName(const QString&); - void setLastName(const QString&); - void setMiddleName(const QString&); - void setNickName(const QString&); - void setUrl(const QString&); - - void setPhoto(const QByteArray&); - void setPhoto(const QImage&); - - QString firstName() const; - QString fullName() const; - QString lastName() const; - QString middleName() const; - QString nickName() const; - QString url() const; - - QImage photoAsImage() const; - const QByteArray& photo() const; - - // deprecated accessors, use the form without "get" instead - /// \cond - QString Q_DECL_DEPRECATED getFullName() const; - QString Q_DECL_DEPRECATED getNickName() const; - QImage Q_DECL_DEPRECATED getPhotoAsImage() const; - const QByteArray Q_DECL_DEPRECATED & getPhoto() const; - /// \endcond - -protected: - /// \cond - void parseElementFromChild(const QDomElement&); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QString m_firstName; - QString m_fullName; - QString m_lastName; - QString m_middleName; - QString m_nickName; - QString m_url; - - // not as 64 base - QByteArray m_photo; -}; - -#endif // QXMPPVCARD_H diff --git a/source/QXmppVCardManager.cpp b/source/QXmppVCardManager.cpp deleted file mode 100644 index 59ac86ac..00000000 --- a/source/QXmppVCardManager.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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 "QXmppVCardManager.h" -#include "QXmppStream.h" -#include "QXmppUtils.h" - -QXmppVCardManager::QXmppVCardManager(QXmppStream* stream, QObject *parent) - : QObject(parent), - m_stream(stream), - m_isClientVCardReceived(false) -{ - bool check = QObject::connect(m_stream, SIGNAL(vCardIqReceived(const QXmppVCard&)), - this, SLOT(vCardIqReceived(const QXmppVCard&))); - Q_ASSERT(check); - Q_UNUSED(check); -} - -void QXmppVCardManager::requestVCard(const QString& jid) -{ - QXmppVCard vcardIq(jid); - m_stream->sendPacket(vcardIq); -} - -void QXmppVCardManager::vCardIqReceived(const QXmppVCard& vcard) -{ - // self vCard received - if(vcard.from().isEmpty()) - { - m_clientVCard = vcard; - m_isClientVCardReceived = true; - emit clientVCardReceived(); - } - - emit vCardReceived(vcard); -} - -const QXmppVCard& QXmppVCardManager::clientVCard() const -{ - return m_clientVCard; -} - -void QXmppVCardManager::setClientVCard(const QXmppVCard& clientVCard) -{ - m_clientVCard = clientVCard; - m_clientVCard.setTo(""); - m_clientVCard.setFrom(""); - m_clientVCard.setType(QXmppIq::Set); - m_stream->sendPacket(m_clientVCard); -} - -void QXmppVCardManager::requestClientVCard() -{ - requestVCard(); -} - -bool QXmppVCardManager::isClientVCardReceived() -{ - return m_isClientVCardReceived; -} - diff --git a/source/QXmppVCardManager.h b/source/QXmppVCardManager.h deleted file mode 100644 index bde01eec..00000000 --- a/source/QXmppVCardManager.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Manjeet Dahiya - * - * 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. - * - */ - - -#ifndef QXMPPVCARDMANAGER_H -#define QXMPPVCARDMANAGER_H - -#include <QObject> - -#include "QXmppVCard.h" - -class QXmppStream; - -/// \brief The QXmppVCardManager class makes it possible to interact -/// with XMPP vCards. -/// -/// \ingroup Managers - -class QXmppVCardManager : public QObject -{ - Q_OBJECT - -public: - QXmppVCardManager(QXmppStream* stream, QObject *parent = 0); - void requestVCard(const QString& bareJid = ""); - - const QXmppVCard& clientVCard() const; - void setClientVCard(const QXmppVCard&); - void requestClientVCard(); - bool isClientVCardReceived(); - -signals: - void vCardReceived(const QXmppVCard&); - void clientVCardReceived(); - -private slots: - void vCardIqReceived(const QXmppVCard&); - -private: - // reference to the xmpp stream (no ownership) - QXmppStream* m_stream; - - QXmppVCard m_clientVCard; ///< Stores the vCard of the connected client - bool m_isClientVCardReceived; -}; - -#endif // QXMPPVCARDMANAGER_H diff --git a/source/QXmppVersionIq.cpp b/source/QXmppVersionIq.cpp deleted file mode 100644 index 20364e8e..00000000 --- a/source/QXmppVersionIq.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* - * 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 "QXmppConstants.h" -#include "QXmppUtils.h" -#include "QXmppVersionIq.h" - -/// Returns the name of the software. -/// - -QString QXmppVersionIq::name() const -{ - return m_name; -} - -/// Sets the name of the software. -/// -/// \param name - -void QXmppVersionIq::setName(const QString &name) -{ - m_name = name; -} - -/// Returns the operating system. -/// - -QString QXmppVersionIq::os() const -{ - return m_os; -} - -/// Sets the operating system. -/// -/// \param os - -void QXmppVersionIq::setOs(const QString &os) -{ - m_os = os; -} - -/// Returns the software version. -/// - -QString QXmppVersionIq::version() const -{ - return m_version; -} - -/// Sets the software version. -/// -/// \param version - -void QXmppVersionIq::setVersion(const QString &version) -{ - m_version = version; -} - -bool QXmppVersionIq::isVersionIq(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - return queryElement.namespaceURI() == ns_version; -} - -void QXmppVersionIq::parseElementFromChild(const QDomElement &element) -{ - QDomElement queryElement = element.firstChildElement("query"); - m_name = element.firstChildElement("name").text(); - m_os = element.firstChildElement("os").text(); - m_version = element.firstChildElement("version").text(); -} - -void QXmppVersionIq::toXmlElementFromChild(QXmlStreamWriter *writer) const -{ - writer->writeStartElement("query"); - helperToXmlAddAttribute(writer, "xmlns", ns_version); - - if (!m_name.isEmpty()) - helperToXmlAddTextElement(writer, "name", m_name); - - if (!m_os.isEmpty()) - helperToXmlAddTextElement(writer, "os", m_os); - - if (!m_version.isEmpty()) - helperToXmlAddTextElement(writer, "version", m_version); - - writer->writeEndElement(); -} - diff --git a/source/QXmppVersionIq.h b/source/QXmppVersionIq.h deleted file mode 100644 index 134cf1d0..00000000 --- a/source/QXmppVersionIq.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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. - * - */ - -#ifndef QXMPPVERSIONIQ_H -#define QXMPPVERSIONIQ_H - -#include "QXmppIq.h" - -/// \brief The QXmppVersionIq class represents an IQ for conveying a software -/// version as defined by XEP-0092: Software Version. -/// -/// \ingroup Stanzas - -class QXmppVersionIq : public QXmppIq -{ -public: - QString name() const; - void setName(const QString &name); - - QString os() const; - void setOs(const QString &os); - - QString version() const; - void setVersion(const QString &version); - - static bool isVersionIq(const QDomElement &element); - -protected: - /// \cond - void parseElementFromChild(const QDomElement &element); - void toXmlElementFromChild(QXmlStreamWriter *writer) const; - /// \endcond - -private: - QString m_name; - QString m_os; - QString m_version; -}; - -#endif diff --git a/source/server/QXmppClientServer.cpp b/source/server/QXmppClientServer.cpp deleted file mode 100644 index 7e74f8d8..00000000 --- a/source/server/QXmppClientServer.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * Sjors Gielen - * - * 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 "QXmppClientServer.h" -#include "QXmppLogger.h" -#include "QXmppStream.h" -#include "QXmppMessage.h" -#include "QXmppUtils.h" - -#define QXMPPCLIENTSERVER_DEBUG - -#define ASSERT_CONNECT(a, b, c, d) \ - { bool check = connect(a, b, c, d); \ - Q_ASSERT( check ); } - -/** - * @brief Creates a QXmppClientServer object. - * - * This class is meant to service client connections as a server. This class - * is only directly used by QXmppServer. If you want to listen to clients, use - * that class, and not this one. - * - * @param socket Server socket (must be nonzero and connected) - * @param data Server data to start parsing - * @param parent QObject parent of this object - */ -QXmppClientServer::QXmppClientServer(QSslSocket *socket, - const QByteArray &data, QObject *parent) -: QObject(parent) -, m_stream(0) -{ - Q_ASSERT( socket->state() == QAbstractSocket::ConnectedState ); - - //m_stream = new QXmppStream(this); - //m_stream->setSocket( socket ); - - ASSERT_CONNECT(m_stream, SIGNAL(messageReceived(const QXmppMessage&)), - this, SIGNAL(messageReceived(const QXmppMessage&))); - - ASSERT_CONNECT(m_stream, SIGNAL(disconnected()), - this, SIGNAL(disconnected())); - - ASSERT_CONNECT(m_stream, SIGNAL(xmppConnected()), - this, SIGNAL(connected())); - - ASSERT_CONNECT(m_stream, SIGNAL(error(QXmppClientServer::Error)), - this, SIGNAL(error(QXmppClientServer::Error))); -} - -/// Destructor, destroys the QXmppClientServer object. -/// - -QXmppClientServer::~QXmppClientServer() -{ -} - -/// 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. QXmppPacket is a parent class of all the stanzas -/// QXmppMessage, QXmppPresence, QXmppIq, QXmppBind, QXmppRosterIq, QXmppSession -/// and QXmppVCard. -/// -/// 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. -/// - -void QXmppClientServer::sendPacket(const QXmppPacket& packet) -{ - Q_ASSERT( m_stream != 0 ); - m_stream->sendPacket(packet); -} - -/// Disconnects the client and the current presence of client changes to -/// QXmppPresence::Unavailable and statatus 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 disconnect() function. -/// - -void QXmppClientServer::disconnect() -{ - Q_ASSERT( m_stream != 0 ); - m_stream->disconnect(); -} - -/// Returns the socket error if QXmppClientServer::Error is QXmppClientServer::SocketError. -/// -/// \return QAbstractSocket::SocketError -/// - -QAbstractSocket::SocketError QXmppClientServer::socketError() -{ - return m_stream->socketError(); -} - -/// Returns the XMPP stream error if QXmppClientServer::Error is QXmppClientServer::XmppStreamError. -/// -/// \return QXmppClientServer::Error::Condition -/// - -QXmppStanza::Error::Condition QXmppClientServer::xmppStreamError() -{ - return m_stream->xmppStreamError(); -} - -/// Return the QXmppLogger associated with the client. - -QXmppLogger *QXmppClientServer::logger() -{ - return m_stream->logger(); -} - -void QXmppClientServer::setLogger(QXmppLogger *logger) -{ - m_stream->setLogger(logger); -} - diff --git a/source/server/QXmppClientServer.h b/source/server/QXmppClientServer.h deleted file mode 100644 index 4f7e4c66..00000000 --- a/source/server/QXmppClientServer.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * Sjors Gielen - * - * 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. - * - */ - -#ifndef QXMPPCLIENTSERVER_H -#define QXMPPCLIENTSERVER_H - -#include <QObject> -#include <QSslSocket> - -#include "QXmppClient.h" - -/** - * @brief The QXmppClientServer receives connections from clients. - */ - -class QXmppClientServer : public QObject -{ - Q_OBJECT - -public: - QXmppClientServer(QSslSocket *serverSocket, - const QByteArray &parseData = QByteArray(), QObject *parent = 0); - ~QXmppClientServer(); - - void disconnect(); - -signals: - - /// This signal is emitted when the XMPP connection disconnects. - /// - void disconnected(); - - /// This signal is emitted when the XMPP connection encounters any error. - /// The QXmppClient::Error parameter specifies the type of error occured. - /// It could be due to TCP socket or the xml stream or the stanza. - /// Depending upon the type of error occured use the respective get function to - /// know the error. - void error(QXmppClient::Error); - - /// Notifies that an XMPP message stanza is received. The QXmppMessage - /// parameter contains the details of the message sent to this client. - /// In other words whenever someone sends you a message this signal is - /// emitted. - void messageReceived(const QXmppMessage&); - -public: - QAbstractSocket::SocketError socketError(); - QXmppStanza::Error::Condition xmppStreamError(); - - QXmppLogger *logger(); - void setLogger(QXmppLogger *logger); - -public slots: - void sendPacket(const QXmppPacket&); - -private: - QXmppStream* m_stream; ///< Pointer to QXmppStream object, a wrapper over - ///< TCP socket and XMPP protocol -}; - -#endif // QXMPPCLIENT_H diff --git a/source/server/QXmppServer.cpp b/source/server/QXmppServer.cpp deleted file mode 100644 index b402a3cc..00000000 --- a/source/server/QXmppServer.cpp +++ /dev/null @@ -1,418 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Author: - * Sjors Gielen - * - * 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 <QSslSocket> - -#include "QXmppServer.h" -#include "QXmppServerConnection.h" -#include "QXmppClientServer.h" - -#define QXMPPSERVER_DEBUG - -#define ASSERT_CONNECT(a, b, c, d) \ - { bool check = connect(a, b, c, d); \ - Q_ASSERT( check ); } - -const QByteArray XMPP_STANDARD_SERVER_STREAM_START = "<stream:stream " - "xmlns=\"jabber:server\" xmlns:stream=\"http://etherx.jabber.org/streams\"" - " version=\"1.0\">"; -const QByteArray XMPP_STANDARD_CLIENT_STREAM_START = "<stream:stream " - "xmlns=\"jabber:client\" xmlns:stream=\"http://etherx.jabber.org/streams\"" - " version=\"1.0\">"; -const QByteArray XMPP_STANDARD_POLICY_STREAM_ERROR = "<stream:error " - "xmlns:stream=\"http://etherx.jabber.org/streams\">" - "<policy-violation xmlns=\"urn:ietf:params:xml:ns:xmpp-streams\"/>" - "<text xmlns=\"urn:ietf:params:xml:ns:xmpp-streams'\" xml:lang=\"en\">" - "Clients of your type are not allowed to connect to this port." - "</text>" - "</stream:error>"; -const QByteArray XMPP_STANDARD_INVALIDNS_STREAM_ERROR = "<stream:error " - "xmlns:stream=\"http://etherx.jabber.org/streams\">" - "<invalid-namespace xmlns=\"urn:ietf:params:xml:ns:xmpp-streams\"/>" - "</stream:error>"; -const QByteArray XMPP_STANDARD_NOTWELLFORMED_STREAM_ERROR = "<stream:error " - "xmlns:stream=\"http://etherx.jabber.org/streams\">" - "<invalid-xml xmlns=\"urn:ietf:params:xml:ns:xmpp-streams\"/>" - "</stream:error>"; -const QByteArray XMPP_STANDARD_END_STREAM = "</stream:stream>"; - -QXmppServer::QXmppServer(bool acceptsServers, bool acceptsClients, QObject *parent) -: QTcpServer(parent) -, m_logger(0) -, m_localCertificate(QByteArray()) -, m_privateKey(QSslKey()) -, m_acceptsClients(acceptsClients) -, m_acceptsServers(acceptsServers) -{ - m_logger = QXmppLogger::getLogger(); -} - -QXmppServer::~QXmppServer() -{ - for( int i = 0; i < m_unknownClients.size(); ++i ) - { - closeSocket( m_unknownClients[i] ); - } - m_unknownClients.clear(); - Q_ASSERT( m_streamReaders.isEmpty() ); - Q_ASSERT( m_cache.isEmpty() ); - - for( int i = 0; i < m_clientConnections.size(); ++i ) - { - delete m_clientConnections[i]; - } - - for( int i = 0; i < m_serverConnections.size(); ++i ) - { - delete m_serverConnections[i]; - } -} - -bool QXmppServer::acceptsClients() const -{ - return m_acceptsClients; -} - -bool QXmppServer::acceptsServers() const -{ - return m_acceptsServers; -} - -void QXmppServer::addCaCertificates( const QList<QSslCertificate> &certificates ) -{ - m_certificates.append( certificates ); -} - -void QXmppServer::addCaCertificates( const QSslCertificate &certificate ) -{ - m_certificates.append( certificate ); -} - -void QXmppServer::closeSocket( QSslSocket *socket ) -{ - forgetSocket( socket ); - delete socket; -} - -/** - * @brief Determine the socket type of this socket. - * - * This method determines whether the connecting peer is a client on the network, or - * another server. To do this, it analyses the 'xmlns' attribute to the - * <stream:stream> start tag. - */ -void QXmppServer::determineSocketType() -{ - QSslSocket *socket = static_cast<QSslSocket*>(sender()); - Q_ASSERT( socket != 0 ); - - Q_ASSERT( m_unknownClients.contains( socket ) ); - Q_ASSERT( m_streamReaders. contains( socket ) ); - Q_ASSERT( m_cache. contains( socket ) ); - QXmlStreamReader *reader = m_streamReaders.value( socket ); - - // Previous errors should already be handled here - Q_ASSERT( !reader->hasError() ); - - QByteArray data = socket->readAll(); - m_cache[socket].append( data ); - reader->addData( data ); - - bool isStartStream = false; - QXmlStreamNamespaceDeclarations xmlns; - while( !reader->atEnd() ) - { - QXmlStreamReader::TokenType type = reader->readNext(); - if( type == QXmlStreamReader::StartElement ) - { - xmlns = reader->namespaceDeclarations(); - if( reader->qualifiedName() == "stream:stream" ) - { - // Got the start of a stream! -#ifdef QXMPPSERVER_DEBUG - qDebug() << "Got the start of a stream."; -#endif - isStartStream = true; - } - else - { - qWarning() << "Received another start element than stream:stream" - << reader->qualifiedName(); - socket->write( XMPP_STANDARD_SERVER_STREAM_START ); - socket->write( XMPP_STANDARD_NOTWELLFORMED_STREAM_ERROR ); - socket->write( XMPP_STANDARD_END_STREAM ); - socket->flush(); - closeSocket( socket ); - return; - } - } - else if( !isStartStream && type != QXmlStreamReader::StartDocument ) - { - qWarning() << "Received XML data before start of stream: " - << reader->qualifiedName() - << "type: " << type - << "error: " << reader->errorString(); - if( type == 1 && tryOtherProtocol( socket ) ) - { - // Apparantly, the socket wasn't speaking XMPP. - // tryOtherProtocol() has returned another message, now close - socket->flush(); - closeSocket( socket ); - return; - } - else if( reader->hasError() && reader->error() != - QXmlStreamReader::PrematureEndOfDocumentError ) - { - socket->write( XMPP_STANDARD_SERVER_STREAM_START ); - if( reader->qualifiedName() == "stream:stream" ) - { - socket->write( XMPP_STANDARD_INVALIDNS_STREAM_ERROR ); - } - else - { - socket->write( XMPP_STANDARD_NOTWELLFORMED_STREAM_ERROR ); - } - socket->write( XMPP_STANDARD_END_STREAM ); - socket->flush(); - closeSocket( socket ); - return; - } - } - } - - if( !isStartStream ) - { - // Didn't find a stream:stream yet, return immediately. - return; - } - - bool containsServerXmlns; - bool containsClientXmlns; - for(int i = 0; i < xmlns.size(); ++i ) - { -#ifdef QXMPPSERVER_DEBUG - qDebug() << "XMLNS prefix=" << xmlns.at(i).prefix() << "; namespaceUri=" - << xmlns.at(i).namespaceUri(); -#endif - if( xmlns.at(i).prefix().isEmpty() ) - { - if( xmlns.at(i).namespaceUri() == "jabber:client" ) - { - containsClientXmlns = true; - } - else if( xmlns.at(i).namespaceUri() == "jabber:server" ) - { - containsServerXmlns = true; - } - else - { - qWarning() << "Didn't find proper XML namespace in stream."; - socket->write( XMPP_STANDARD_SERVER_STREAM_START ); - socket->write( XMPP_STANDARD_INVALIDNS_STREAM_ERROR ); - socket->write( XMPP_STANDARD_END_STREAM ); - socket->flush(); - closeSocket( socket ); - return; - } - } - } - - Q_ASSERT( containsServerXmlns || containsClientXmlns ); - - if( containsServerXmlns ) - { -#ifdef QXMPPSERVER_DEBUG - qDebug() << "It's a server socket!"; -#endif - - if( !m_acceptsServers ) - { - // send a stream error - socket->write( XMPP_STANDARD_SERVER_STREAM_START ); - socket->write( XMPP_STANDARD_POLICY_STREAM_ERROR ); - socket->write( XMPP_STANDARD_END_STREAM ); - socket->flush(); - closeSocket( socket ); - return; - } - - QByteArray pastData = m_cache[socket]; - forgetSocket( socket ); - - socket->addCaCertificates( m_certificates ); - socket->setLocalCertificate( m_localCertificate ); - socket->setPrivateKey( m_privateKey ); - socket->setProtocol( QSsl::AnyProtocol ); - - QXmppServerConnection *sc = new QXmppServerConnection( socket, pastData ); - sc->setLogger( m_logger ); - m_serverConnections.append( sc ); - } - else if( containsClientXmlns ) - { -#ifdef QXMPPSERVER_DEBUG - qDebug() << "It's a client socket!"; -#endif - - if( !m_acceptsClients ) - { - // send a stream error - socket->write( XMPP_STANDARD_CLIENT_STREAM_START ); - socket->write( XMPP_STANDARD_POLICY_STREAM_ERROR ); - socket->write( XMPP_STANDARD_END_STREAM ); - socket->flush(); - closeSocket( socket ); - return; - } - - QByteArray pastData = m_cache[socket]; - forgetSocket( socket ); - - QXmppClientServer *cs = new QXmppClientServer( socket, pastData ); - cs->setLogger( m_logger ); - m_clientConnections.append( cs ); - } -} - -void QXmppServer::forgetSocket( QSslSocket *socket ) -{ - Q_ASSERT( m_unknownClients.contains( socket ) ); - Q_ASSERT( m_streamReaders. contains( socket ) ); - Q_ASSERT( m_cache. contains( socket ) ); - - socket->disconnect( this, 0 ); - - QXmlStreamReader *reader = m_streamReaders.value( socket ); - m_unknownClients.removeAll( socket ); - m_streamReaders.remove( socket ); - m_cache.remove( socket ); - delete reader; -} - -void QXmppServer::incomingConnection( int socketDescriptor ) -{ - QSslSocket *socket = new QSslSocket; - if( socket->setSocketDescriptor( socketDescriptor ) ) - { - ASSERT_CONNECT( socket, SIGNAL( readyRead() ), - this, SLOT( determineSocketType() ) ); - - m_unknownClients.append( socket ); - m_streamReaders.insert( socket, new QXmlStreamReader() ); - m_cache.insert( socket, "" ); - emit unknownClientConnected( socket ); - return; - } - - delete socket; - qWarning() << "setSocketDescriptor failed"; -} - -QXmppLogger *QXmppServer::logger() -{ - return m_logger; -} - -void QXmppServer::setAcceptsClients( bool acceptsClients ) -{ - m_acceptsClients = acceptsClients; -} - -void QXmppServer::setAcceptsServers( bool acceptsServers ) -{ - m_acceptsServers = acceptsServers; -} - -void QXmppServer::setLocalCertificate( const QSslCertificate &localCertificate ) -{ - m_localCertificate = localCertificate; -} - -void QXmppServer::setLogger(QXmppLogger *logger) -{ - m_logger = logger; -} - -void QXmppServer::setPrivateKey( const QSslKey &privateKey ) -{ - m_privateKey = privateKey; -} - -/** - * @brief Try to detect another protocol on our server line - * - * Sometimes, a client erroneously connects to the wrong port. For example, a - * browser or IRC client might end up on our socket. The XML parser will - * likely give an error then - here we check if the other side is speaking the - * incorrect protocol. This will, of course, never work in protocols where the - * server starts sending and the client waits indefinitely. - * - * This method should only write a message to the socket and return true if - * a protocol was recognised; the socket will be flushed and closed elsewhere. - * - * Recognised protocols: http (first line ends with HTTP/x.y), irc (first line - * starts with NICK) - */ -bool QXmppServer::tryOtherProtocol( QSslSocket *socket ) -{ - Q_ASSERT( m_cache. contains( socket ) ); - QByteArray &cache = m_cache[socket]; - - int newline = cache.indexOf( "\n" ); - int carrret = cache.indexOf( "\r" ); - newline = ( carrret < newline && carrret != -1 ) ? carrret : newline; - QByteArray firstLine = cache.mid( 0, newline ); - - // Discover IRC - if( firstLine.startsWith( "NICK " ) ) - { - QByteArray nick = firstLine.mid( 5, newline - 5 ); - socket->write( ":xmppd 001 " + nick + " :Welcome to XMPP IRC\r\n" ); - socket->write( ":xmppd 002 " + nick + " :Your host is an XMPP IRC daemon\r\n" ); - socket->write( ":xmppd 375 " + nick + " :- XMPP IRC Daemon Message of the Day -\r\n" ); - socket->write( ":xmppd 372 " + nick + " :- This server is not an IRC server! It is\r\n" ); - socket->write( ":xmppd 372 " + nick + " :- an XMPP server. Please use an XMPP client\r\n" ); - socket->write( ":xmppd 372 " + nick + " :- to connect to it.\r\n" ); - socket->write( ":xmppd 376 " + nick + " :End of /MOTD command.\r\n" ); - socket->write( ":" + nick + " QUIT :Not an XMPP client.\r\n" ); - socket->write( "ERROR :Closing Link: Not an XMPP client.\r\n" ); - return true; - } - - // Discover HTTP - QByteArray httpVer = firstLine.right(8); - if( httpVer.startsWith( "HTTP/" ) ) - { - socket->write( "HTTP/1.0 200 OK\r\n" ); - socket->write( "Content-Type: text/html; charset=UTF-8\r\n" ); - socket->write( "Server: xmppd\r\n" ); - socket->write( "\r\n" ); - socket->write( "<html><head><title>Not a webserver</title></head>\r\n" ); - socket->write( "<body>You are connecting to an XMPP server as if it were" ); - socket->write( " a webserver. Please use an XMPP client to connect to " ); - socket->write( "it.</body></html>\r\n" ); - return true; - } - - return false; -} diff --git a/source/server/QXmppServer.h b/source/server/QXmppServer.h deleted file mode 100644 index 6cc6597b..00000000 --- a/source/server/QXmppServer.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Sjors Gielen - * Rob ten Berge - * - * 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. - * - */ - -#ifndef QXMPPSERVER_H -#define QXMPPSERVER_H - -#include <QObject> -#include <QTcpServer> -#include <QSslKey> -#include <QSslCertificate> -#include <QSslSocket> - -#include "QXmppConfiguration.h" -#include "QXmppPresence.h" -#include "QXmppClient.h" -#include "QXmppLogger.h" - -class QXmppServerConnection; -class QXmppClientServer; - -/** @brief The QXmppServer class is the server class of QXmpp. - * - * This class listens on a TCP port and accepts clients and/or servers (depending on - * its configuration). It proceeds to create a QXmppServerConnection class if the - * other peer is a server, or a QXmppClientServer class if the other peer is a client. - */ - -class QXmppServer : public QTcpServer -{ - Q_OBJECT - -public: - QXmppServer(bool acceptsClients, bool acceptsServers, QObject *parent = 0); - ~QXmppServer(); - - QXmppLogger *logger(); - void setLogger(QXmppLogger *logger); - - void setAcceptsClients( bool acceptsClients ); - void setAcceptsServers( bool acceptsServers ); - bool acceptsClients() const; - bool acceptsServers() const; - - void addCaCertificates( const QList<QSslCertificate> &certificates ); - void addCaCertificates( const QSslCertificate &certificate ); - void setLocalCertificate( const QSslCertificate &localCertificate ); - void setPrivateKey( const QSslKey &privateKey ); - -signals: - void unknownClientConnected( QSslSocket *client ); - void serverConnected( QXmppServerConnection *server ); - void clientConnected( QXmppClientServer *client ); - -private slots: - void determineSocketType(); - void forgetSocket( QSslSocket *socket ); - void closeSocket( QSslSocket *socket ); - bool tryOtherProtocol( QSslSocket *socket ); - -private: - QList<QXmppServerConnection*> m_serverConnections; - QList<QXmppClientServer*> m_clientConnections; - QList<QSslSocket*> m_unknownClients; - QHash<QSslSocket*, QXmlStreamReader*> m_streamReaders; - QHash<QSslSocket*, QByteArray> m_cache; - - QXmppLogger* m_logger; - QList<QSslCertificate> m_certificates; - QSslCertificate m_localCertificate; - QSslKey m_privateKey; - bool m_acceptsClients; - bool m_acceptsServers; - - void incomingConnection(int socketDescriptor); -}; - -#endif // QXMPPCLIENT_H diff --git a/source/server/QXmppServerConnection.cpp b/source/server/QXmppServerConnection.cpp deleted file mode 100644 index 09993e2c..00000000 --- a/source/server/QXmppServerConnection.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * Sjors Gielen - * - * 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 "QXmppServerConnection.h" -#include "QXmppLogger.h" -#include "QXmppStream.h" -#include "QXmppMessage.h" -#include "QXmppUtils.h" - -#define QXMPPSERVERCONNECTION_DEBUG - -#define ASSERT_CONNECT(a, b, c, d) \ - { bool check = connect(a, b, c, d); \ - Q_ASSERT( check ); } - -/** - * @brief Creates a QXmppServerConnection object. - * - * This class is meant for server to server connections, both initiated by this - * server (in which case the connectToHost method should be used), and - * initiated by other servers (in which case a QSslSocket should be given to - * this class). To listen to incoming connections, use QXmppServer. - * - * @param socket Server socket if nonzero, ignored if zero - * @param data Server data to start parsing, only if server socket nonzero - * @param parent QObject parent of this object - */ -QXmppServerConnection::QXmppServerConnection(QSslSocket *socket, - const QByteArray &data, QObject *parent) -: QObject(parent) -, m_stream(0) -{ - Q_ASSERT( socket == 0 || socket->state() == QAbstractSocket::ConnectedState ); - - //m_stream = new QXmppStream(this); - //m_stream->setSocket( socket ); - - ASSERT_CONNECT(m_stream, SIGNAL(messageReceived(const QXmppMessage&)), - this, SIGNAL(messageReceived(const QXmppMessage&))); - - ASSERT_CONNECT(m_stream, SIGNAL(disconnected()), - this, SIGNAL(disconnected())); - - ASSERT_CONNECT(m_stream, SIGNAL(xmppConnected()), - this, SIGNAL(connected())); - - ASSERT_CONNECT(m_stream, SIGNAL(error(QXmppServerConnection::Error)), - this, SIGNAL(error(QXmppServerConnection::Error))); -} - -/// Destructor, destroys the QXmppServerConnection object. -/// - -QXmppServerConnection::~QXmppServerConnection() -{ -} - -/** - * @brief Attempts to connect to another XMPP server. - * - * @param host Hostname of the XMPP server where connection has to be made - * (e.g. "jabber.org" and "talk.google.com"). It can also be an IP address in - * the form of a string (e.g. "192.168.1.25"). - * @param domain Domain name of the other side e.g. "gmail.com", "jabber.org". - * @param port Port number at which the XMPP server is listening. The default - * value is 5269. - */ -void QXmppServerConnection::connectToServer(const QString& host, const QString& domain, - int port) -{ - disconnect(); - //m_stream->connect( host, domain, port ); -} - -/// 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. QXmppPacket is a parent class of all the stanzas -/// QXmppMessage, QXmppPresence, QXmppIq, QXmppBind, QXmppRosterIq, QXmppSession -/// and QXmppVCard. -/// -/// 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. -/// - -void QXmppServerConnection::sendPacket(const QXmppPacket& packet) -{ - Q_ASSERT( m_stream != 0 ); - m_stream->sendPacket(packet); -} - -/// Disconnects the client and the current presence of client changes to -/// QXmppPresence::Unavailable and statatus 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 disconnect() function. -/// - -void QXmppServerConnection::disconnect() -{ - Q_ASSERT( m_stream != 0 ); - m_stream->disconnect(); -} - -/// Returns the socket error if QXmppServerConnection::Error is QXmppServerConnection::SocketError. -/// -/// \return QAbstractSocket::SocketError -/// - -QAbstractSocket::SocketError QXmppServerConnection::socketError() -{ - return m_stream->socketError(); -} - -/// Returns the XMPP stream error if QXmppServerConnection::Error is QXmppServerConnection::XmppStreamError. -/// -/// \return QXmppServerConnection::Error::Condition -/// - -QXmppStanza::Error::Condition QXmppServerConnection::xmppStreamError() -{ - return m_stream->xmppStreamError(); -} - -/// Return the QXmppLogger associated with the client. - -QXmppLogger *QXmppServerConnection::logger() -{ - return m_stream->logger(); -} - -void QXmppServerConnection::setLogger(QXmppLogger *logger) -{ - m_stream->setLogger(logger); -} - diff --git a/source/server/QXmppServerConnection.h b/source/server/QXmppServerConnection.h deleted file mode 100644 index aa685dc8..00000000 --- a/source/server/QXmppServerConnection.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2008-2010 The QXmpp developers - * - * Authors: - * Manjeet Dahiya - * Sjors Gielen - * - * 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. - * - */ - -#ifndef QXMPPSERVERCONNECTION_H -#define QXMPPSERVERCONNECTION_H - -#include <QObject> -#include <QSslSocket> - -#include "QXmppClient.h" - -/** - * @brief The QXmppServerConnection class handles connections to other servers. - */ - -class QXmppServerConnection : public QObject -{ - Q_OBJECT - -public: - // should probably be moved to QXmppStream - enum Error - { - SocketError, ///< Error due to TCP socket - KeepAliveError, ///< Error due to no response to a keep alive - XmppStreamError, ///< Error due to XML stream - }; - - QXmppServerConnection(QSslSocket *serverSocket = 0, - const QByteArray &parseData = QByteArray(), QObject *parent = 0); - ~QXmppServerConnection(); - void connectToServer(const QString& host, - const QString& domain, - int port = 5269); - void disconnect(); - -signals: - - /// This signal is emitted when the client connects sucessfully to the XMPP - /// server i.e. when a successful XMPP connection is established. - /// XMPP Connection involves following sequential steps: - /// - TCP socket connection - /// - Client sends start stream - /// - Server sends start stream - /// - TLS negotiation (encryption) - /// - Authentication - /// - Resource binding - /// - Session establishment - /// - /// After all these steps a successful XMPP connection is established and - /// connected() signal is emitted. - /// - /// After the connected() signal is emitted QXmpp will send the roster request - /// to the server. On receiving the roster, QXmpp will emit - /// QXmppRoster::rosterReceived(). After this signal, QXmppRoster object gets - /// populated and you can use getRoster() to get the handle of QXmppRoster object. - /// - void connected(); - - /// This signal is emitted when the XMPP connection disconnects. - /// - void disconnected(); - - /// This signal is emitted when the XMPP connection encounters any error. - /// The QXmppClient::Error parameter specifies the type of error occured. - /// It could be due to TCP socket or the xml stream or the stanza. - /// Depending upon the type of error occured use the respective get function to - /// know the error. - void error(QXmppClient::Error); - - /// Notifies that an XMPP message stanza is received. The QXmppMessage - /// parameter contains the details of the message sent to this client. - /// In other words whenever someone sends you a message this signal is - /// emitted. - void messageReceived(const QXmppMessage&); - -public: - QAbstractSocket::SocketError socketError(); - QXmppStanza::Error::Condition xmppStreamError(); - - QXmppLogger *logger(); - void setLogger(QXmppLogger *logger); - -public slots: - void sendPacket(const QXmppPacket&); - -private: - QXmppStream* m_stream; ///< Pointer to QXmppStream object, a wrapper over - ///< TCP socket and XMPP protocol -}; - -#endif // QXMPPCLIENT_H diff --git a/source/server/README b/source/server/README deleted file mode 100644 index 5ef2b3d5..00000000 --- a/source/server/README +++ /dev/null @@ -1 +0,0 @@ -This directory contains server specific files.
diff --git a/source/server/server.pro b/source/server/server.pro deleted file mode 100644 index 55a06ac5..00000000 --- a/source/server/server.pro +++ /dev/null @@ -1,107 +0,0 @@ -TEMPLATE = lib
-QT += network \
- xml
-CONFIG += staticlib \
- debug_and_release
-
-INCLUDEPATH += ../
-
-# Make sure the library gets built in the same location
-# regardless of the platform. On win32 the library is
-# automagically put in debug/release folders, so do the
-# same for other platforms.
-CONFIG(debug, debug|release) {
- win32:TARGET = QXmppServer_d
- !win32:TARGET = debug/QXmppServer_d
-} else {
- win32:TARGET = QXmppServer
- !win32:TARGET = release/QXmppServer
-}
-
-# Header files
-HEADERS += QXmppClientServer.h \
- QXmppServer.h \
- QXmppServerConnection.h
-
-# Source files
-SOURCES += QXmppClientServer.cpp \
- QXmppServer.cpp \
- QXmppServerConnection.cpp
-
-# Header files of the client
-HEADERS += ../QXmppUtils.h \
- ../QXmppArchiveIq.h \
- ../QXmppArchiveManager.h \
- ../QXmppBind.h \
- ../QXmppByteStreamIq.h \
- ../QXmppClient.h \
- ../QXmppConfiguration.h \
- ../QXmppConstants.h \
- ../QXmppDataForm.h \
- ../QXmppDiscoveryIq.h \
- ../QXmppElement.h \
- ../QXmppIbbIq.h \
- ../QXmppInformationRequestResult.h \
- ../QXmppInvokable.h \
- ../QXmppIq.h \
- ../QXmppLogger.h \
- ../QXmppMessage.h \
- ../QXmppNonSASLAuth.h \
- ../QXmppPacket.h \
- ../QXmppPingIq.h \
- ../QXmppPresence.h \
- ../QXmppRoster.h \
- ../QXmppRosterIq.h \
- ../QXmppSession.h \
- ../QXmppSocks.h \
- ../QXmppStanza.h \
- ../QXmppStream.h \
- ../QXmppStreamInitiationIq.h \
- ../QXmppTransferManager.h \
- ../QXmppReconnectionManager.h \
- ../QXmppRemoteMethod.h \
- ../QXmppRpcIq.h \
- ../QXmppVCardManager.h \
- ../QXmppVCard.h \
- ../QXmppVersionIq.h \
- ../xmlrpc.h
-
-# Source files of the client
-SOURCES += ../QXmppUtils.cpp \
- ../QXmppArchiveIq.cpp \
- ../QXmppArchiveManager.cpp \
- ../QXmppBind.cpp \
- ../QXmppByteStreamIq.cpp \
- ../QXmppClient.cpp \
- ../QXmppConfiguration.cpp \
- ../QXmppConstants.cpp \
- ../QXmppDataForm.cpp \
- ../QXmppDiscoveryIq.cpp \
- ../QXmppElement.cpp \
- ../QXmppIbbIq.cpp \
- ../QXmppInformationRequestResult.cpp \
- ../QXmppInvokable.cpp \
- ../QXmppIq.cpp \
- ../QXmppLogger.cpp \
- ../QXmppMessage.cpp \
- ../QXmppNonSASLAuth.cpp \
- ../QXmppPacket.cpp \
- ../QXmppPingIq.cpp \
- ../QXmppPresence.cpp \
- ../QXmppRoster.cpp \
- ../QXmppRosterIq.cpp \
- ../QXmppSession.cpp \
- ../QXmppSocks.cpp \
- ../QXmppStanza.cpp \
- ../QXmppStream.cpp \
- ../QXmppStreamInitiationIq.cpp \
- ../QXmppTransferManager.cpp \
- ../QXmppReconnectionManager.cpp \
- ../QXmppRemoteMethod.cpp \
- ../QXmppRpcIq.cpp \
- ../QXmppVCardManager.cpp \
- ../QXmppVCard.cpp \
- ../QXmppVersionIq.cpp \
- ../xmlrpc.cpp
-
-
diff --git a/source/source.pro b/source/source.pro deleted file mode 100644 index 7e421632..00000000 --- a/source/source.pro +++ /dev/null @@ -1,113 +0,0 @@ -include(../qxmpp.pri) - -TEMPLATE = lib - -QT += network xml - -CONFIG += staticlib - -# To disable the dependency on QtGui, uncomment the following: -# DEFINES += QXMPP_NO_GUI - -# To enable support for the Speex codec, uncomment the following: -# DEFINES += QXMPP_USE_SPEEX - -# Target definition -TARGET = $$QXMPP_LIBRARY_NAME -VERSION = $$QXMPP_VERSION -DESTDIR = $$QXMPP_LIBRARY_DIR - -# Header files -HEADERS += QXmppUtils.h \ - QXmppArchiveIq.h \ - QXmppArchiveManager.h \ - QXmppBind.h \ - QXmppByteStreamIq.h \ - QXmppCallManager.h \ - QXmppClient.h \ - QXmppCodec.h \ - QXmppConfiguration.h \ - QXmppConstants.h \ - QXmppDataForm.h \ - QXmppDiscoveryIq.h \ - QXmppElement.h \ - QXmppIbbIq.h \ - QXmppInvokable.h \ - QXmppIq.h \ - QXmppJingleIq.h \ - QXmppLogger.h \ - QXmppMessage.h \ - QXmppMucIq.h \ - QXmppMucManager.h \ - QXmppNonSASLAuth.h \ - QXmppPacket.h \ - QXmppPingIq.h \ - QXmppPresence.h \ - QXmppRoster.h \ - QXmppRosterIq.h \ - QXmppRosterManager.h \ - QXmppSession.h \ - QXmppSocks.h \ - QXmppStanza.h \ - QXmppStream.h \ - QXmppStreamInitiationIq.h \ - QXmppStun.h \ - QXmppTransferManager.h \ - QXmppReconnectionManager.h \ - QXmppRemoteMethod.h \ - QXmppRpcIq.h \ - QXmppVCardManager.h \ - QXmppVCard.h \ - QXmppVersionIq.h - -# Source files -SOURCES += QXmppUtils.cpp \ - QXmppArchiveIq.cpp \ - QXmppArchiveManager.cpp \ - QXmppBind.cpp \ - QXmppByteStreamIq.cpp \ - QXmppCallManager.cpp \ - QXmppClient.cpp \ - QXmppCodec.cpp \ - QXmppConfiguration.cpp \ - QXmppConstants.cpp \ - QXmppDataForm.cpp \ - QXmppDiscoveryIq.cpp \ - QXmppElement.cpp \ - QXmppIbbIq.cpp \ - QXmppInvokable.cpp \ - QXmppIq.cpp \ - QXmppJingleIq.cpp \ - QXmppLogger.cpp \ - QXmppMessage.cpp \ - QXmppMucIq.cpp \ - QXmppMucManager.cpp \ - QXmppNonSASLAuth.cpp \ - QXmppPacket.cpp \ - QXmppPingIq.cpp \ - QXmppPresence.cpp \ - QXmppRosterIq.cpp \ - QXmppRosterManager.cpp \ - QXmppSession.cpp \ - QXmppSocks.cpp \ - QXmppStanza.cpp \ - QXmppStream.cpp \ - QXmppStreamInitiationIq.cpp \ - QXmppStun.cpp \ - QXmppTransferManager.cpp \ - QXmppReconnectionManager.cpp \ - QXmppRemoteMethod.cpp \ - QXmppRpcIq.cpp \ - QXmppVCardManager.cpp \ - QXmppVCard.cpp \ - QXmppVersionIq.cpp - -# pkg-config support -CONFIG += create_pc create_prl no_install_prl -QMAKE_PKGCONFIG_DESTDIR = $$QXMPP_LIBRARY_DIR/pkgconfig - -# Installation -headers.files = $$HEADERS -headers.path = $$[QT_INSTALL_PREFIX]/include/qxmpp -target.path = $$[QT_INSTALL_PREFIX]/lib -INSTALLS += headers target |
