summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTobias Markmann <tm@ayena.de>2011-05-26 18:46:49 (GMT)
committerRemko Tronçon <git@el-tramo.be>2011-09-25 17:42:32 (GMT)
commit4f62e5ec4b42929fe3c1a68667e63cb1b7a35509 (patch)
tree0d19fac3f578dec00ccf3e58930312951e38de89 /Swiften
parentde660b763459cdd707876ec244b6866abca07fa2 (diff)
downloadswift-4f62e5ec4b42929fe3c1a68667e63cb1b7a35509.zip
swift-4f62e5ec4b42929fe3c1a68667e63cb1b7a35509.tar.bz2
Google Summer of Code 2011 Project: Adding support for Jingle File Transfers (XEP-0234), Jingle SOCKS5 Bytestreams Transport Method (XEP-0260), Jingle In-Band Bytestreams Transport Method (XEP-0261) and SOCKS5 Bytestreams (XEP-0065).
License: This patch is BSD-licensed, see http://www.opensource.org/licenses/bsd-license.php
Diffstat (limited to 'Swiften')
-rw-r--r--Swiften/Client/Client.cpp17
-rw-r--r--Swiften/Client/Client.h13
-rw-r--r--Swiften/Client/ClientXMLTracer.cpp11
-rw-r--r--Swiften/Client/ClientXMLTracer.h8
-rw-r--r--Swiften/Client/CoreClient.cpp1
-rw-r--r--Swiften/Client/CoreClient.h9
-rw-r--r--Swiften/Client/XMLBeautifier.cpp126
-rw-r--r--Swiften/Client/XMLBeautifier.h53
-rw-r--r--Swiften/Elements/DiscoInfo.cpp6
-rw-r--r--Swiften/Elements/DiscoInfo.h5
-rw-r--r--Swiften/Elements/JingleContentPayload.h1
-rw-r--r--Swiften/Elements/JingleFileTransferDescription.h22
-rw-r--r--Swiften/Elements/JingleFileTransferHash.h35
-rw-r--r--Swiften/Elements/JingleFileTransferReceived.h33
-rw-r--r--Swiften/Elements/JingleIBBTransportPayload.h9
-rw-r--r--Swiften/Elements/JinglePayload.h57
-rw-r--r--Swiften/Elements/JingleS5BTransportPayload.h96
-rw-r--r--Swiften/Elements/JingleTransportPayload.h12
-rw-r--r--Swiften/Elements/Payload.h4
-rw-r--r--Swiften/Elements/S5BProxyRequest.h61
-rw-r--r--Swiften/Elements/StreamInitiationFileInfo.h95
-rw-r--r--Swiften/Examples/SendFile/ReceiveFile.cpp37
-rw-r--r--Swiften/Examples/SendFile/SendFile.cpp78
-rw-r--r--Swiften/FileTransfer/ByteArrayReadBytestream.h2
-rw-r--r--Swiften/FileTransfer/ByteArrayWriteBytestream.h1
-rw-r--r--Swiften/FileTransfer/ConnectivityManager.cpp101
-rw-r--r--Swiften/FileTransfer/ConnectivityManager.h43
-rw-r--r--Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGenerator.cpp97
-rw-r--r--Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGenerator.h39
-rw-r--r--Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.cpp25
-rw-r--r--Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.h33
-rw-r--r--Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.cpp121
-rw-r--r--Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.h58
-rw-r--r--Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.cpp25
-rw-r--r--Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.h28
-rw-r--r--Swiften/FileTransfer/FileReadBytestream.cpp1
-rw-r--r--Swiften/FileTransfer/FileTransfer.h58
-rw-r--r--Swiften/FileTransfer/FileTransferManager.cpp14
-rw-r--r--Swiften/FileTransfer/FileTransferManager.h34
-rw-r--r--Swiften/FileTransfer/FileTransferManagerImpl.cpp123
-rw-r--r--Swiften/FileTransfer/FileTransferManagerImpl.h80
-rw-r--r--Swiften/FileTransfer/FileWriteBytestream.cpp8
-rw-r--r--Swiften/FileTransfer/FileWriteBytestream.h1
-rw-r--r--Swiften/FileTransfer/IBBReceiveSession.cpp9
-rw-r--r--Swiften/FileTransfer/IBBSendSession.cpp3
-rw-r--r--Swiften/FileTransfer/IBBSendSession.h2
-rw-r--r--Swiften/FileTransfer/IncomingFileTransfer.h5
-rw-r--r--Swiften/FileTransfer/IncomingFileTransferManager.cpp20
-rw-r--r--Swiften/FileTransfer/IncomingFileTransferManager.h11
-rw-r--r--Swiften/FileTransfer/IncomingJingleFileTransfer.cpp408
-rw-r--r--Swiften/FileTransfer/IncomingJingleFileTransfer.h60
-rw-r--r--Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp61
-rw-r--r--Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h33
-rw-r--r--Swiften/FileTransfer/JingleIncomingIBBTransport.cpp3
-rw-r--r--Swiften/FileTransfer/JingleTransport.h2
-rw-r--r--Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h6
-rw-r--r--Swiften/FileTransfer/OutgoingFileTransfer.h8
-rw-r--r--Swiften/FileTransfer/OutgoingFileTransferManager.cpp46
-rw-r--r--Swiften/FileTransfer/OutgoingFileTransferManager.h47
-rw-r--r--Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp401
-rw-r--r--Swiften/FileTransfer/OutgoingJingleFileTransfer.h115
-rw-r--r--Swiften/FileTransfer/OutgoingSIFileTransfer.cpp4
-rw-r--r--Swiften/FileTransfer/ReadBytestream.h5
-rw-r--r--Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h4
-rw-r--r--Swiften/FileTransfer/SConscript16
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp235
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamClientSession.h94
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxy.cpp72
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxy.h46
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp54
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamRegistry.h49
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServer.cpp14
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServer.h8
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp86
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerSession.h20
-rw-r--r--Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h36
-rw-r--r--Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp282
-rw-r--r--Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp283
-rw-r--r--Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp306
-rw-r--r--Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp16
-rw-r--r--Swiften/FileTransfer/WriteBytestream.h4
-rw-r--r--Swiften/Jingle/FakeJingleSession.cpp52
-rw-r--r--Swiften/Jingle/FakeJingleSession.h93
-rw-r--r--Swiften/Jingle/JingleContentID.h8
-rw-r--r--Swiften/Jingle/JingleResponder.cpp25
-rw-r--r--Swiften/Jingle/JingleResponder.h3
-rw-r--r--Swiften/Jingle/JingleSession.cpp4
-rw-r--r--Swiften/Jingle/JingleSession.h20
-rw-r--r--Swiften/Jingle/JingleSessionImpl.cpp159
-rw-r--r--Swiften/Jingle/JingleSessionImpl.h22
-rw-r--r--Swiften/Jingle/JingleSessionManager.cpp15
-rw-r--r--Swiften/Jingle/JingleSessionManager.h11
-rw-r--r--Swiften/Jingle/SConscript1
-rw-r--r--Swiften/Network/BoostNetworkFactories.cpp3
-rw-r--r--Swiften/Network/BoostNetworkFactories.h5
-rw-r--r--Swiften/Network/DummyConnectionFactory.h29
-rw-r--r--Swiften/Network/NATPMPNATTraversalForwardPortRequest.cpp62
-rw-r--r--Swiften/Network/NATPMPNATTraversalForwardPortRequest.h24
-rw-r--r--Swiften/Network/NATPMPNATTraversalGetPublicIPRequest.cpp64
-rw-r--r--Swiften/Network/NATPMPNATTraversalGetPublicIPRequest.h22
-rw-r--r--Swiften/Network/NATPMPNATTraversalRemovePortForwardingRequest.cpp83
-rw-r--r--Swiften/Network/NATPMPNATTraversalRemovePortForwardingRequest.h27
-rw-r--r--Swiften/Network/NetworkEnvironment.h24
-rw-r--r--Swiften/Network/NetworkFactories.h2
-rw-r--r--Swiften/Network/NetworkInterface.h35
-rw-r--r--Swiften/Network/PlatformNATTraversalForwardPortRequest.cpp18
-rw-r--r--Swiften/Network/PlatformNATTraversalForwardPortRequest.h38
-rw-r--r--Swiften/Network/PlatformNATTraversalGetPublicIPRequest.cpp18
-rw-r--r--Swiften/Network/PlatformNATTraversalGetPublicIPRequest.h25
-rw-r--r--Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.cpp18
-rw-r--r--Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.h38
-rw-r--r--Swiften/Network/PlatformNATTraversalRequest.cpp25
-rw-r--r--Swiften/Network/PlatformNATTraversalRequest.h31
-rw-r--r--Swiften/Network/PlatformNATTraversalWorker.cpp140
-rw-r--r--Swiften/Network/PlatformNATTraversalWorker.h60
-rw-r--r--Swiften/Network/PlatformNetworkEnvironment.h26
-rw-r--r--Swiften/Network/SConscript16
-rw-r--r--Swiften/Network/UPnPNATTraversalForwardPortRequest.cpp86
-rw-r--r--Swiften/Network/UPnPNATTraversalForwardPortRequest.h27
-rw-r--r--Swiften/Network/UPnPNATTraversalGetPublicIPRequest.cpp57
-rw-r--r--Swiften/Network/UPnPNATTraversalGetPublicIPRequest.h21
-rw-r--r--Swiften/Network/UPnPNATTraversalRemovePortForwardingRequest.cpp92
-rw-r--r--Swiften/Network/UPnPNATTraversalRemovePortForwardingRequest.h27
-rw-r--r--Swiften/Network/UnixNetworkEnvironment.cpp74
-rw-r--r--Swiften/Network/UnixNetworkEnvironment.h59
-rw-r--r--Swiften/Network/WindowsNetworkEnvironment.cpp97
-rw-r--r--Swiften/Network/WindowsNetworkEnvironment.h56
-rw-r--r--Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp23
-rw-r--r--Swiften/Parser/PayloadParsers/IBBParser.cpp2
-rw-r--r--Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp74
-rw-r--r--Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h30
-rw-r--r--Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h35
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp75
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h38
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h35
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp43
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h27
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferReceivedParser.cpp49
-rw-r--r--Swiften/Parser/PayloadParsers/JingleFileTransferReceivedParser.h27
-rw-r--r--Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp38
-rw-r--r--Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h26
-rw-r--r--Swiften/Parser/PayloadParsers/JingleParser.cpp119
-rw-r--r--Swiften/Parser/PayloadParsers/JingleParser.h32
-rw-r--r--Swiften/Parser/PayloadParsers/JingleParserFactory.h35
-rw-r--r--Swiften/Parser/PayloadParsers/JingleReasonParser.cpp81
-rw-r--r--Swiften/Parser/PayloadParsers/JingleReasonParser.h30
-rw-r--r--Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp88
-rw-r--r--Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h29
-rw-r--r--Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp64
-rw-r--r--Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h30
-rw-r--r--Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp69
-rw-r--r--Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h28
-rw-r--r--Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp6
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp709
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp6
-rw-r--r--Swiften/Parser/SConscript10
-rw-r--r--Swiften/SConscript17
-rw-r--r--Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp21
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp79
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h25
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp46
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h25
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp45
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h23
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.cpp35
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.h23
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp31
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h25
-rw-r--r--Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp144
-rw-r--r--Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h30
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp85
-rw-r--r--Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h27
-rw-r--r--Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h38
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp56
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h24
-rw-r--r--Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp10
-rw-r--r--Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp512
-rw-r--r--Swiften/StringCodecs/Hexify.cpp18
-rw-r--r--Swiften/StringCodecs/Hexify.h1
-rw-r--r--Swiften/StringCodecs/MD5.cpp21
-rw-r--r--Swiften/StringCodecs/MD5.h11
-rw-r--r--Swiften/StringCodecs/UnitTest/HexifyTest.cpp6
-rw-r--r--Swiften/StringCodecs/UnitTest/MD5Test.cpp11
183 files changed, 9426 insertions, 218 deletions
diff --git a/Swiften/Client/Client.cpp b/Swiften/Client/Client.cpp
index c53bcaf..e95e704 100644
--- a/Swiften/Client/Client.cpp
+++ b/Swiften/Client/Client.cpp
@@ -26,6 +26,9 @@
#include <Swiften/TLS/BlindCertificateTrustChecker.h>
#include <Swiften/Client/NickManagerImpl.h>
#include <Swiften/Client/ClientSession.h>
+#include <Swiften/Jingle/JingleSessionManager.h>
+#include <Swiften/Network/NetworkFactories.h>
+#include <Swiften/FileTransfer/FileTransferManagerImpl.h>
namespace Swift {
@@ -59,9 +62,15 @@ Client::Client(const JID& jid, const SafeString& password, NetworkFactories* net
nickResolver = new NickResolver(jid.toBare(), roster, vcardManager, mucRegistry);
blindCertificateTrustChecker = new BlindCertificateTrustChecker();
+
+ jingleSessionManager = new JingleSessionManager(getIQRouter());
+ fileTransferManager = NULL;
}
Client::~Client() {
+ delete fileTransferManager;
+ delete jingleSessionManager;
+
delete blindCertificateTrustChecker;
delete nickResolver;
@@ -98,6 +107,10 @@ void Client::setSoftwareVersion(const std::string& name, const std::string& vers
softwareVersionResponder->setVersion(name, version, os);
}
+void Client::handleConnected() {
+ fileTransferManager = new FileTransferManagerImpl(getJID(), jingleSessionManager, getIQRouter(), getEntityCapsProvider(), presenceOracle, getNetworkFactories()->getConnectionFactory(), getNetworkFactories()->getConnectionServerFactory(), getNetworkFactories()->getTimerFactory(), getNetworkFactories()->getPlatformNATTraversalWorker());
+}
+
void Client::requestRoster() {
// FIXME: We should set this once when the session is finished, but there
// is currently no callback for this
@@ -139,4 +152,8 @@ NickManager* Client::getNickManager() const {
return nickManager;
}
+FileTransferManager* Client::getFileTransferManager() const {
+ return fileTransferManager;
+}
+
}
diff --git a/Swiften/Client/Client.h b/Swiften/Client/Client.h
index 08289a5..7269f10 100644
--- a/Swiften/Client/Client.h
+++ b/Swiften/Client/Client.h
@@ -33,6 +33,9 @@ namespace Swift {
class SubscriptionManager;
class ClientDiscoManager;
class NickManager;
+ class FileTransferManager;
+ class JingleSessionManager;
+ class FileTransferManagerImpl;
/**
* Provides the core functionality for writing XMPP client software.
@@ -131,6 +134,11 @@ namespace Swift {
ClientDiscoManager* getDiscoManager() const {
return discoManager;
}
+
+ /**
+ * Returns a FileTransferManager for the client. This is only available after the onConnected signal has been fired.
+ */
+ FileTransferManager* getFileTransferManager() const;
/**
* Configures the client to always trust a non-validating
@@ -149,6 +157,9 @@ namespace Swift {
private:
Storages* getStorages() const;
+ protected:
+ void handleConnected();
+
private:
Storages* storages;
MemoryStorages* memoryStorages;
@@ -168,6 +179,8 @@ namespace Swift {
SubscriptionManager* subscriptionManager;
MUCManager* mucManager;
ClientDiscoManager* discoManager;
+ JingleSessionManager* jingleSessionManager;
+ FileTransferManagerImpl* fileTransferManager;
BlindCertificateTrustChecker* blindCertificateTrustChecker;
};
}
diff --git a/Swiften/Client/ClientXMLTracer.cpp b/Swiften/Client/ClientXMLTracer.cpp
index c1e398d..c1093eb 100644
--- a/Swiften/Client/ClientXMLTracer.cpp
+++ b/Swiften/Client/ClientXMLTracer.cpp
@@ -12,13 +12,18 @@
namespace Swift {
ClientXMLTracer::ClientXMLTracer(CoreClient* client) {
- client->onDataRead.connect(boost::bind(&ClientXMLTracer::printData, '<', _1));
- client->onDataWritten.connect(boost::bind(&ClientXMLTracer::printData, '>', _1));
+ beautifier = new XMLBeautifier(true, true);
+ client->onDataRead.connect(boost::bind(&ClientXMLTracer::printData, this, '<', _1));
+ client->onDataWritten.connect(boost::bind(&ClientXMLTracer::printData, this, '>', _1));
+}
+
+ClientXMLTracer::~ClientXMLTracer() {
+ delete beautifier;
}
void ClientXMLTracer::printData(char direction, const SafeByteArray& data) {
printLine(direction);
- std::cerr << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl;
+ std::cerr << beautifier->beautify(byteArrayToString(ByteArray(data.begin(), data.end()))) << std::endl;
}
void ClientXMLTracer::printLine(char c) {
diff --git a/Swiften/Client/ClientXMLTracer.h b/Swiften/Client/ClientXMLTracer.h
index dd94e0e..0752faa 100644
--- a/Swiften/Client/ClientXMLTracer.h
+++ b/Swiften/Client/ClientXMLTracer.h
@@ -7,15 +7,19 @@
#pragma once
#include <Swiften/Client/CoreClient.h>
+#include <Swiften/Client/XMLBeautifier.h>
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
class ClientXMLTracer {
public:
ClientXMLTracer(CoreClient* client);
+ ~ClientXMLTracer();
+ private:
+ void printData(char direction, const SafeByteArray& data);
+ void printLine(char c);
private:
- static void printData(char direction, const SafeByteArray& data);
- static void printLine(char c);
+ XMLBeautifier *beautifier;
};
}
diff --git a/Swiften/Client/CoreClient.cpp b/Swiften/Client/CoreClient.cpp
index cceec74..37055e4 100644
--- a/Swiften/Client/CoreClient.cpp
+++ b/Swiften/Client/CoreClient.cpp
@@ -276,6 +276,7 @@ void CoreClient::handleDataWritten(const SafeByteArray& data) {
void CoreClient::handleStanzaChannelAvailableChanged(bool available) {
if (available) {
+ handleConnected();
onConnected();
}
}
diff --git a/Swiften/Client/CoreClient.h b/Swiften/Client/CoreClient.h
index 16813de..3472e76 100644
--- a/Swiften/Client/CoreClient.h
+++ b/Swiften/Client/CoreClient.h
@@ -188,6 +188,15 @@ namespace Swift {
return session_;
}
+ NetworkFactories* getNetworkFactories() const {
+ return networkFactories;
+ }
+
+ /**
+ * Called before onConnected signal is emmitted.
+ */
+ virtual void handleConnected() {};
+
private:
void handleConnectorFinished(boost::shared_ptr<Connection>);
void handleStanzaChannelAvailableChanged(bool available);
diff --git a/Swiften/Client/XMLBeautifier.cpp b/Swiften/Client/XMLBeautifier.cpp
new file mode 100644
index 0000000..b70fc48
--- /dev/null
+++ b/Swiften/Client/XMLBeautifier.cpp
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <sstream>
+#include <stack>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Client/XMLBeautifier.h>
+#include <Swiften/Parser/PlatformXMLParserFactory.h>
+
+namespace Swift {
+
+XMLBeautifier::XMLBeautifier(bool indention, bool coloring) : doIndention(indention), doColoring(coloring), intLevel(0), parser(NULL), lastWasStepDown(false) {
+ factory = new PlatformXMLParserFactory();
+}
+
+XMLBeautifier::~XMLBeautifier() {
+ delete factory;
+}
+
+std::string XMLBeautifier::beautify(const std::string &text) {
+ parser = factory->createXMLParser(this);
+ intLevel = 0;
+ buffer.str(std::string());
+ parser->parse(text);
+ delete parser;
+ return buffer.str();
+}
+
+void XMLBeautifier::indent() {
+ for (int i = 0; i < intLevel; ++i) {
+ buffer << " ";
+ }
+}
+
+// all bold but reset
+const char colorBlue[] = "\x1b[01;34m";
+const char colorCyan[] = "\x1b[01;36m";
+const char colorGreen[] = "\x1b[01;32m";
+const char colorMagenta[] = "\x1b[01;35m";
+const char colorRed[] = "\x1b[01;31m";
+const char colorReset[] = "\x1b[0m";
+const char colorYellow[] = "\x1b[01;33m";
+
+
+
+std::string XMLBeautifier::styleTag(const std::string& text) const {
+ std::string result;
+ result += colorYellow;
+ result += text;
+ result += colorReset;
+ return result;
+}
+
+std::string XMLBeautifier::styleNamespace(const std::string& text) const {
+ std::string result;
+ result += colorRed;
+ result += text;
+ result += colorReset;
+ return result;
+}
+
+std::string XMLBeautifier::styleAttribute(const std::string& text) const {
+ std::string result;
+ result += colorGreen;
+ result += text;
+ result += colorReset;
+ return result;
+}
+std::string XMLBeautifier::styleValue(const std::string& text) const {
+ std::string result;
+ result += colorCyan;
+ result += text;
+ result += colorReset;
+ return result;
+}
+
+void XMLBeautifier::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
+ if (doIndention) {
+ if (intLevel) buffer << std::endl;
+ }
+ indent();
+ buffer << "<" << (doColoring ? styleTag(element) : element);
+ if (!ns.empty() && (!parentNSs.empty() && parentNSs.top() != ns)) {
+ buffer << " ";
+ buffer << (doColoring ? styleAttribute("xmlns") : "xmlns");
+ buffer << "=";
+ buffer << "\"" << (doColoring ? styleNamespace(ns) : ns) << "\"";
+ }
+ if (!attributes.getEntries().empty()) {
+ foreach(AttributeMap::Entry entry, attributes.getEntries()) {
+ buffer << " ";
+ buffer << (doColoring ? styleAttribute(entry.getAttribute().getName()) : entry.getAttribute().getName());
+ buffer << "=";
+ buffer << "\"" << (doColoring ? styleValue(entry.getValue()) : entry.getValue()) << "\"";
+ }
+ }
+ buffer << ">";
+ ++intLevel;
+ lastWasStepDown = false;
+ parentNSs.push(ns);
+}
+
+void XMLBeautifier::handleEndElement(const std::string& element, const std::string& /* ns */) {
+ --intLevel;
+ parentNSs.pop();
+ if (/*hadCDATA.top() ||*/ lastWasStepDown) {
+ if (doIndention) {
+ buffer << std::endl;
+ }
+ indent();
+ }
+ buffer << "</" << (doColoring ? styleTag(element) : element) << ">";
+ lastWasStepDown = true;
+}
+
+void XMLBeautifier::handleCharacterData(const std::string& data) {
+ buffer << data;
+ lastWasStepDown = false;
+}
+
+}
diff --git a/Swiften/Client/XMLBeautifier.h b/Swiften/Client/XMLBeautifier.h
new file mode 100644
index 0000000..44dfd20
--- /dev/null
+++ b/Swiften/Client/XMLBeautifier.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <string>
+#include <stack>
+
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/Parser/XMLParserFactory.h>
+#include <Swiften/Parser/XMLParserClient.h>
+#include <Swiften/Parser/XMLParser.h>
+
+namespace Swift {
+
+class XMLBeautifier : public XMLParserClient {
+public:
+ XMLBeautifier(bool indention, bool coloring);
+ virtual ~XMLBeautifier();
+
+ std::string beautify(const std::string&);
+
+private:
+ void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
+ void handleEndElement(const std::string& element, const std::string& ns);
+ void handleCharacterData(const std::string& data);
+
+private:
+ void indent();
+
+private:
+ std::string styleTag(const std::string& text) const;
+ std::string styleNamespace(const std::string& text) const;
+ std::string styleAttribute(const std::string& text) const;
+ std::string styleValue(const std::string& text) const;
+
+private:
+ bool doIndention;
+ bool doColoring;
+
+ int intLevel;
+ std::string inputBuffer;
+ std::stringstream buffer;
+ XMLParserFactory* factory;
+ XMLParser* parser;
+
+ bool lastWasStepDown;
+ std::stack<std::string> parentNSs;
+};
+}
diff --git a/Swiften/Elements/DiscoInfo.cpp b/Swiften/Elements/DiscoInfo.cpp
index f54b6bf..35d4d04 100644
--- a/Swiften/Elements/DiscoInfo.cpp
+++ b/Swiften/Elements/DiscoInfo.cpp
@@ -16,7 +16,11 @@ const std::string DiscoInfo::SecurityLabelsCatalogFeature = std::string("urn:xmp
const std::string DiscoInfo::JabberSearchFeature = std::string("jabber:iq:search");
const std::string DiscoInfo::CommandsFeature = std::string("http://jabber.org/protocol/commands");
const std::string DiscoInfo::MessageCorrectionFeature = std::string("urn:xmpp:message-correct:0");
-
+const std::string DiscoInfo::JingleFeature = std::string("urn:xmpp:jingle:1");
+const std::string DiscoInfo::JingleFTFeature = std::string("urn:xmpp:jingle:apps:file-transfer:3");
+const std::string DiscoInfo::JingleTransportsIBBFeature = std::string("urn:xmpp:jingle:transports:ibb:1");
+const std::string DiscoInfo::JingleTransportsS5BFeature = std::string("urn:xmpp:jingle:transports:s5b:1");
+const std::string DiscoInfo::Bytestream = std::string("http://jabber.org/protocol/bytestreams");
bool DiscoInfo::Identity::operator<(const Identity& other) const {
diff --git a/Swiften/Elements/DiscoInfo.h b/Swiften/Elements/DiscoInfo.h
index c5c9e1c..6d6e722 100644
--- a/Swiften/Elements/DiscoInfo.h
+++ b/Swiften/Elements/DiscoInfo.h
@@ -23,6 +23,11 @@ namespace Swift {
static const std::string JabberSearchFeature;
static const std::string CommandsFeature;
static const std::string MessageCorrectionFeature;
+ static const std::string JingleFeature;
+ static const std::string JingleFTFeature;
+ static const std::string JingleTransportsIBBFeature;
+ static const std::string JingleTransportsS5BFeature;
+ static const std::string Bytestream;
class Identity {
public:
diff --git a/Swiften/Elements/JingleContentPayload.h b/Swiften/Elements/JingleContentPayload.h
index c44a806..183b8eb 100644
--- a/Swiften/Elements/JingleContentPayload.h
+++ b/Swiften/Elements/JingleContentPayload.h
@@ -21,6 +21,7 @@ namespace Swift {
typedef boost::shared_ptr<JingleContentPayload> ref;
enum Creator {
+ UnknownCreator,
InitiatorCreator,
ResponderCreator,
};
diff --git a/Swiften/Elements/JingleFileTransferDescription.h b/Swiften/Elements/JingleFileTransferDescription.h
index 19644bd..04f3f1f 100644
--- a/Swiften/Elements/JingleFileTransferDescription.h
+++ b/Swiften/Elements/JingleFileTransferDescription.h
@@ -7,7 +7,7 @@
#pragma once
#include <boost/shared_ptr.hpp>
-#include <boost/optional.hpp>
+#include <vector>
#include <Swiften/Elements/JingleDescription.h>
#include <Swiften/Elements/StreamInitiationFileInfo.h>
@@ -17,15 +17,25 @@ namespace Swift {
public:
typedef boost::shared_ptr<JingleFileTransferDescription> ref;
- void setOffer(const StreamInitiationFileInfo& offer) {
- this->offer = offer;
+ void addOffer(const StreamInitiationFileInfo& offer) {
+ offers.push_back(offer);
}
+
- const boost::optional<StreamInitiationFileInfo>& getOffer() const {
- return offer;
+ const std::vector<StreamInitiationFileInfo>& getOffers() const {
+ return offers;
+ }
+
+ void addRequest(const StreamInitiationFileInfo& request) {
+ reqeusts.push_back(request);
+ }
+
+ const std::vector<StreamInitiationFileInfo>& getRequests() const {
+ return reqeusts;
}
private:
- boost::optional<StreamInitiationFileInfo> offer;
+ std::vector<StreamInitiationFileInfo> offers;
+ std::vector<StreamInitiationFileInfo> reqeusts;
};
}
diff --git a/Swiften/Elements/JingleFileTransferHash.h b/Swiften/Elements/JingleFileTransferHash.h
new file mode 100644
index 0000000..5603531
--- /dev/null
+++ b/Swiften/Elements/JingleFileTransferHash.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <boost/shared_ptr.hpp>
+#include <map>
+#include <string>
+
+#include <Swiften/Elements/JingleDescription.h>
+
+namespace Swift {
+
+class JingleFileTransferHash : public Payload {
+public:
+ typedef std::map<std::string, std::string> HashesMap;
+public:
+ typedef boost::shared_ptr<JingleFileTransferHash> ref;
+
+ void setHash(const std::string& algo, const std::string& hash) {
+ hashes[algo] = hash;
+ }
+
+ const HashesMap& getHashes() const {
+ return hashes;
+ }
+
+private:
+ HashesMap hashes;
+};
+
+}
diff --git a/Swiften/Elements/JingleFileTransferReceived.h b/Swiften/Elements/JingleFileTransferReceived.h
new file mode 100644
index 0000000..75c95d9
--- /dev/null
+++ b/Swiften/Elements/JingleFileTransferReceived.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <boost/shared_ptr.hpp>
+#include <vector>
+
+#include <Swiften/Elements/StreamInitiationFileInfo.h>
+#include <Swiften/Elements/Payload.h>
+
+namespace Swift {
+
+class JingleFileTransferReceived : public Payload {
+ public:
+ typedef boost::shared_ptr<JingleFileTransferReceived> ref;
+
+ void setFileInfo(const StreamInitiationFileInfo& fileInfo) {
+ this->fileInfo = fileInfo;
+ }
+
+ const StreamInitiationFileInfo& getFileInfo() const {
+ return this->fileInfo;
+ }
+ private:
+ StreamInitiationFileInfo fileInfo;
+
+};
+
+}
diff --git a/Swiften/Elements/JingleIBBTransportPayload.h b/Swiften/Elements/JingleIBBTransportPayload.h
index 67aab09..8c174f0 100644
--- a/Swiften/Elements/JingleIBBTransportPayload.h
+++ b/Swiften/Elements/JingleIBBTransportPayload.h
@@ -29,14 +29,6 @@ namespace Swift {
return stanzaType;
}
- void setSessionID(const std::string& id) {
- sessionID = id;
- }
-
- const std::string& getSessionID() const {
- return sessionID;
- }
-
int getBlockSize() const {
return blockSize;
}
@@ -46,7 +38,6 @@ namespace Swift {
}
private:
- std::string sessionID;
int blockSize;
StanzaType stanzaType;
};
diff --git a/Swiften/Elements/JinglePayload.h b/Swiften/Elements/JinglePayload.h
index 5c766b8..31d4448 100644
--- a/Swiften/Elements/JinglePayload.h
+++ b/Swiften/Elements/JinglePayload.h
@@ -7,6 +7,7 @@
#pragma once
#include <vector>
+#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>
#include <string>
@@ -14,13 +15,15 @@
#include <Swiften/Elements/Payload.h>
#include <Swiften/Elements/JingleContentPayload.h>
+#include <Swiften/Base/Log.h>
namespace Swift {
class JinglePayload : public Payload {
public:
typedef boost::shared_ptr<JinglePayload> ref;
- struct Reason {
+ struct Reason : public Payload {
enum Type {
+ UnknownType,
AlternativeSession,
Busy,
Cancel,
@@ -39,13 +42,15 @@ namespace Swift {
UnsupportedApplications,
UnsupportedTransports
};
-
+ Reason() : type(UnknownType), text("") {}
Reason(Type type, const std::string& text = "") : type(type), text(text) {}
+ ~Reason() {}
Type type;
std::string text;
};
enum Action {
+ UnknownAction,
ContentAccept,
ContentAdd,
ContentModify,
@@ -62,8 +67,11 @@ namespace Swift {
TransportReject,
TransportReplace
};
-
+ JinglePayload() : action(SessionTerminate), sessionID("") {
+ }
+
JinglePayload(Action action, const std::string& sessionID) : action(action), sessionID(sessionID) {
+
}
void setAction(Action action) {
@@ -99,11 +107,46 @@ namespace Swift {
}
void addContent(JingleContentPayload::ref content) {
- this->contents.push_back(content);
+ this->payloads.push_back(content);
+ }
+
+ void addPayload(boost::shared_ptr<Payload> payload) {
+ this->payloads.push_back(payload);
+ }
+
+ const std::vector<JingleContentPayload::ref> getContents() const {
+ return getPayloads<JingleContentPayload>();
+ }
+
+ const std::vector<boost::shared_ptr<Payload> > getPayloads() const {
+ return payloads;
+ }
+
+ template<typename T>
+ const std::vector<boost::shared_ptr<T> > getPayloads() const {
+ std::vector<boost::shared_ptr<T> > matched_payloads;
+ for (std::vector<boost::shared_ptr<Payload> >::const_iterator i = payloads.begin(); i != payloads.end(); ++i) {
+ boost::shared_ptr<T> result = boost::dynamic_pointer_cast<T>(*i);
+ if (result) {
+ matched_payloads.push_back(result);
+ }
+ }
+
+ return matched_payloads;
+
}
- const std::vector<JingleContentPayload::ref>& getContents() const {
- return contents;
+ template<typename T>
+ const boost::shared_ptr<T> getPayload() const {
+ boost::shared_ptr<T> result;
+ for (std::vector<boost::shared_ptr<Payload> >::const_iterator i = payloads.begin(); i != payloads.end(); ++i) {
+ result = boost::dynamic_pointer_cast<T>(*i);
+ if (result) {
+ return result;
+ }
+ }
+
+ return result;
}
void setReason(const Reason& reason) {
@@ -119,7 +162,7 @@ namespace Swift {
JID initiator;
JID responder;
std::string sessionID;
- std::vector<JingleContentPayload::ref> contents;
+ std::vector<boost::shared_ptr<Payload> > payloads;
boost::optional<Reason> reason;
};
}
diff --git a/Swiften/Elements/JingleS5BTransportPayload.h b/Swiften/Elements/JingleS5BTransportPayload.h
index 7b3089f..980af27 100644
--- a/Swiften/Elements/JingleS5BTransportPayload.h
+++ b/Swiften/Elements/JingleS5BTransportPayload.h
@@ -6,23 +6,107 @@
#pragma once
+#include <vector>
+
+#include <boost/shared_ptr.hpp>
+
#include <Swiften/Elements/JingleTransportPayload.h>
#include <Swiften/Elements/Bytestreams.h>
+#include <Swiften/Network/HostAddressPort.h>
-// FIXME: Remove Bytestreams, and replace by our own candidate
namespace Swift {
class JingleS5BTransportPayload : public JingleTransportPayload {
public:
- const Bytestreams& getInfo() const {
- return info;
+ enum Mode {
+ TCPMode, // default case
+ UDPMode,
+ };
+
+ struct Candidate {
+ enum Type {
+ DirectType, // default case
+ AssistedType,
+ TunnelType,
+ ProxyType,
+ };
+
+ Candidate() : priority(0), type(DirectType) {}
+
+ std::string cid;
+ JID jid;
+ HostAddressPort hostPort;
+ int priority;
+ Type type;
+ };
+
+ struct CompareCandidate {
+ bool operator() (const JingleS5BTransportPayload::Candidate& c1, const JingleS5BTransportPayload::Candidate& c2) const {
+ if (c1.priority < c2.priority) return true;
+ return false;
+ }
+ };
+
+ public:
+ JingleS5BTransportPayload() : mode(TCPMode), candidateError(false), proxyError(false) {}
+
+ Mode getMode() const {
+ return mode;
+ }
+
+ void setMode(Mode mode) {
+ this->mode = mode;
+ }
+
+ const std::vector<Candidate>& getCandidates() {
+ return candidates;
+ }
+
+ void addCandidate(const Candidate& candidate) {
+ candidates.push_back(candidate);
+ }
+
+ void setCandidateUsed(const std::string& cid) {
+ candidateUsedCID = cid;
+ }
+
+ const std::string& getCandidateUsed() const {
+ return candidateUsedCID;
+ }
+
+ void setActivated(const std::string& cid) {
+ activatedCID = cid;
}
- void setInfo(const Bytestreams& info) {
- this->info = info;
+ const std::string& getActivated() const {
+ return activatedCID;
}
+ void setCandidateError(bool hasError) {
+ candidateError = hasError;
+ }
+
+ bool hasCandidateError() const {
+ return candidateError;
+ }
+
+ void setProxyError(bool hasError) {
+ proxyError = hasError;
+ }
+
+ bool hasProxyError() const {
+ return proxyError;
+ }
+ public:
+ typedef boost::shared_ptr<JingleS5BTransportPayload> ref;
+
private:
- Bytestreams info;
+ Mode mode;
+ std::vector<Candidate> candidates;
+
+ std::string candidateUsedCID;
+ std::string activatedCID;
+ bool candidateError;
+ bool proxyError;
};
}
diff --git a/Swiften/Elements/JingleTransportPayload.h b/Swiften/Elements/JingleTransportPayload.h
index 7a9ea29..b870be9 100644
--- a/Swiften/Elements/JingleTransportPayload.h
+++ b/Swiften/Elements/JingleTransportPayload.h
@@ -13,6 +13,18 @@
namespace Swift {
class JingleTransportPayload : public Payload {
public:
+ void setSessionID(const std::string& id) {
+ sessionID = id;
+ }
+
+ const std::string& getSessionID() const {
+ return sessionID;
+ }
+
+ public:
typedef boost::shared_ptr<JingleTransportPayload> ref;
+
+ private:
+ std::string sessionID;
};
}
diff --git a/Swiften/Elements/Payload.h b/Swiften/Elements/Payload.h
index 8b6d44a..f994ebc 100644
--- a/Swiften/Elements/Payload.h
+++ b/Swiften/Elements/Payload.h
@@ -6,9 +6,13 @@
#pragma once
+#include <boost/shared_ptr.hpp>
+
namespace Swift {
class Payload {
public:
+ typedef boost::shared_ptr<Payload> ref;
+ public:
virtual ~Payload();
};
}
diff --git a/Swiften/Elements/S5BProxyRequest.h b/Swiften/Elements/S5BProxyRequest.h
new file mode 100644
index 0000000..fcd0cb2
--- /dev/null
+++ b/Swiften/Elements/S5BProxyRequest.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <string>
+
+#include <boost/optional.hpp>
+
+#include <Swiften/Elements/Payload.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Network/HostAddressPort.h>
+
+namespace Swift {
+
+class S5BProxyRequest : public Payload {
+public:
+ typedef boost::shared_ptr<S5BProxyRequest> ref;
+
+public:
+ struct StreamHost {
+ HostAddressPort addressPort;
+ JID jid;
+ };
+
+public:
+ const boost::optional<StreamHost>& getStreamHost() const {
+ return streamHost;
+ }
+
+ void setStreamHost(const StreamHost& streamHost) {
+ this->streamHost = boost::optional<StreamHost>(streamHost);
+ }
+
+ const std::string& getSID() const {
+ return sid;
+ }
+
+ void setSID(const std::string& sid) {
+ this->sid = sid;
+ }
+
+ const boost::optional<JID>& getActivate() const {
+ return activate;
+ }
+
+ void setActivate(const JID& activate) {
+ this->activate = activate;
+ }
+
+private:
+ boost::optional<StreamHost> streamHost;
+
+ std::string sid;
+ boost::optional<JID> activate;
+};
+
+}
diff --git a/Swiften/Elements/StreamInitiationFileInfo.h b/Swiften/Elements/StreamInitiationFileInfo.h
index 92b9824..9484bc0 100644
--- a/Swiften/Elements/StreamInitiationFileInfo.h
+++ b/Swiften/Elements/StreamInitiationFileInfo.h
@@ -6,14 +6,97 @@
#pragma once
+#include <Swiften/Elements/Payload.h>
+#include <boost/shared_ptr.hpp>
+#include <boost/date_time/posix_time/posix_time_types.hpp>
+
#include <string>
namespace Swift {
- struct StreamInitiationFileInfo {
- StreamInitiationFileInfo(const std::string& name = "", const std::string& description = "", int size = -1) : name(name), description(description), size(size) {}
- std::string name;
- std::string description;
- int size;
- };
+class StreamInitiationFileInfo : public Payload {
+public:
+ typedef boost::shared_ptr<StreamInitiationFileInfo> ref;
+
+public:
+ StreamInitiationFileInfo(const std::string& name = "", const std::string& description = "", int size = 0,
+ const std::string& hash = "", const boost::posix_time::ptime &date = boost::posix_time::ptime(), const std::string& algo="md5") :
+ name(name), description(description), size(size), hash(hash), date(date), algo(algo), supportsRangeRequests(false), rangeOffset(0) {}
+
+ void setName(const std::string& name) {
+ this->name = name;;
+ }
+
+ const std::string& getName() const {
+ return this->name;
+ }
+
+ void setDescription(const std::string& description) {
+ this->description = description;
+ }
+
+ const std::string& getDescription() const {
+ return this->description;
+ }
+
+ void setSize(const boost::uintmax_t size) {
+ this->size = size;
+ }
+
+ boost::uintmax_t getSize() const {
+ return this->size;
+ }
+
+ void setHash(const std::string& hash) {
+ this->hash = hash;
+ }
+
+ const std::string& getHash() const {
+ return this->hash;
+ }
+
+ void setDate(const boost::posix_time::ptime& date) {
+ this->date = date;
+ }
+
+ const boost::posix_time::ptime& getDate() const {
+ return this->date;
+ }
+
+ void setAlgo(const std::string& algo) {
+ this->algo = algo;
+ }
+
+ const std::string& getAlgo() const {
+ return this->algo;
+ }
+
+ void setSupportsRangeRequests(const bool supportsIt) {
+ supportsRangeRequests = supportsIt;
+ }
+
+ bool getSupportsRangeRequests() const {
+ return supportsRangeRequests;
+ }
+
+ void setRangeOffset(const int offset) {
+ supportsRangeRequests = offset >= 0 ? true : false;
+ rangeOffset = offset;
+ }
+
+ int getRangeOffset() const {
+ return rangeOffset;
+ }
+
+private:
+ std::string name;
+ std::string description;
+ boost::uintmax_t size;
+ std::string hash;
+ boost::posix_time::ptime date;
+ std::string algo;
+ bool supportsRangeRequests;
+ boost::uintmax_t rangeOffset;
+};
+
}
diff --git a/Swiften/Examples/SendFile/ReceiveFile.cpp b/Swiften/Examples/SendFile/ReceiveFile.cpp
index effa1b7..f80f03a 100644
--- a/Swiften/Examples/SendFile/ReceiveFile.cpp
+++ b/Swiften/Examples/SendFile/ReceiveFile.cpp
@@ -12,12 +12,18 @@
#include <Swiften/Elements/Presence.h>
#include <Swiften/Base/foreach.h>
#include <Swiften/Client/Client.h>
+#include <Swiften/Elements/DiscoInfo.h>
#include <Swiften/Network/BoostNetworkFactories.h>
#include <Swiften/EventLoop/SimpleEventLoop.h>
#include <Swiften/Client/ClientXMLTracer.h>
+#include <Swiften/Disco/ClientDiscoManager.h>
#include <Swiften/FileTransfer/IncomingFileTransferManager.h>
#include <Swiften/FileTransfer/FileWriteBytestream.h>
#include <Swiften/Jingle/JingleSessionManager.h>
+#include <Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.h>
+#include <Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/FileTransfer/FileTransferManager.h>
using namespace Swift;
@@ -26,19 +32,20 @@ BoostNetworkFactories networkFactories(&eventLoop);
int exitCode = 2;
+static const std::string CLIENT_NAME = "Swiften FT Test";
+static const std::string CLIENT_NODE = "http://swift.im";
+
class FileReceiver {
public:
FileReceiver(const JID& jid, const std::string& password) : jid(jid), password(password), jingleSessionManager(NULL), incomingFileTransferManager(NULL) {
client = new Swift::Client(jid, password, &networkFactories);
client->onConnected.connect(boost::bind(&FileReceiver::handleConnected, this));
client->onDisconnected.connect(boost::bind(&FileReceiver::handleDisconnected, this, _1));
- //tracer = new ClientXMLTracer(client);
+ tracer = new ClientXMLTracer(client);
}
~FileReceiver() {
- delete incomingFileTransferManager;
- delete jingleSessionManager;
- //delete tracer;
+ delete tracer;
client->onDisconnected.disconnect(boost::bind(&FileReceiver::handleDisconnected, this, _1));
client->onConnected.disconnect(boost::bind(&FileReceiver::handleConnected, this));
delete client;
@@ -57,13 +64,24 @@ class FileReceiver {
private:
void handleConnected() {
- client->sendPresence(Presence::create());
- jingleSessionManager = new JingleSessionManager(client->getIQRouter());
- incomingFileTransferManager = new IncomingFileTransferManager(jingleSessionManager, client->getIQRouter());
- incomingFileTransferManager->onIncomingFileTransfer.connect(boost::bind(&FileReceiver::handleIncomingFileTransfer, this, _1));
+ Swift::logging = true;
+ client->getFileTransferManager()->startListeningOnPort(9999);
+ client->getFileTransferManager()->onIncomingFileTransfer.connect(boost::bind(&FileReceiver::handleIncomingFileTransfer, this, _1));
+
+ DiscoInfo discoInfo;
+ discoInfo.addIdentity(DiscoInfo::Identity(CLIENT_NAME, "client", "pc"));
+ discoInfo.addFeature(DiscoInfo::JingleFeature);
+ discoInfo.addFeature(DiscoInfo::JingleFTFeature);
+ discoInfo.addFeature(DiscoInfo::Bytestream);
+ discoInfo.addFeature(DiscoInfo::JingleTransportsIBBFeature);
+ discoInfo.addFeature(DiscoInfo::JingleTransportsS5BFeature);
+ client->getDiscoManager()->setCapsNode(CLIENT_NODE);
+ client->getDiscoManager()->setDiscoInfo(discoInfo);
+ client->getPresenceSender()->sendPresence(Presence::create());
}
void handleIncomingFileTransfer(IncomingFileTransfer::ref transfer) {
+ SWIFT_LOG(debug) << "foo" << std::endl;
incomingFileTransfers.push_back(transfer);
transfer->accept(boost::make_shared<FileWriteBytestream>("out"));
//transfer->onFinished.connect(boost::bind(&FileReceiver::handleFileTransferFinished, this, _1));
@@ -100,6 +118,9 @@ class FileReceiver {
JingleSessionManager* jingleSessionManager;
IncomingFileTransferManager* incomingFileTransferManager;
std::vector<IncomingFileTransfer::ref> incomingFileTransfers;
+ DefaultLocalJingleTransportCandidateGeneratorFactory *localFactory;
+ DefaultRemoteJingleTransportCandidateSelectorFactory *remoteFactory;
+ SOCKS5BytestreamRegistry* bytestreamRegistry;
};
diff --git a/Swiften/Examples/SendFile/SendFile.cpp b/Swiften/Examples/SendFile/SendFile.cpp
index 205b442..9b2105b 100644
--- a/Swiften/Examples/SendFile/SendFile.cpp
+++ b/Swiften/Examples/SendFile/SendFile.cpp
@@ -4,6 +4,7 @@
* See Documentation/Licenses/GPLv3.txt for more information.
*/
+#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <iostream>
@@ -20,6 +21,17 @@
#include <Swiften/FileTransfer/FileReadBytestream.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServer.h>
#include <Swiften/Network/BoostConnectionServer.h>
+#include <Swiften/FileTransfer/OutgoingFileTransferManager.h>
+#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
+#include <Swiften/Jingle/JingleSessionManager.h>
+#include <Swiften/Disco/EntityCapsManager.h>
+#include <Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.h>
+#include <Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.h>
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/StringCodecs/MD5.h>
+#include <Swiften/StringCodecs/SHA1.h>
+#include <Swiften/StringCodecs/Hexify.h>
+#include <Swiften/FileTransfer/FileTransferManager.h>
using namespace Swift;
@@ -30,45 +42,65 @@ int exitCode = 2;
class FileSender {
public:
- FileSender(const JID& jid, const std::string& password, const JID& recipient, const boost::filesystem::path& file, int port) : jid(jid), password(password), recipient(recipient), file(file), transfer(NULL) {
- connectionServer = BoostConnectionServer::create(port, networkFactories.getIOServiceThread()->getIOService(), &eventLoop);
- socksBytestreamServer = new SOCKS5BytestreamServer(connectionServer);
+ FileSender(const JID& jid, const std::string& password, const JID& recipient, const boost::filesystem::path& file) : jid(jid), password(password), recipient(recipient), file(file) {
client = new Swift::Client(jid, password, &networkFactories);
client->onConnected.connect(boost::bind(&FileSender::handleConnected, this));
client->onDisconnected.connect(boost::bind(&FileSender::handleDisconnected, this, _1));
- //tracer = new ClientXMLTracer(client);
+ tracer = new ClientXMLTracer(client);
+ client->getEntityCapsProvider()->onCapsChanged.connect(boost::bind(&FileSender::handleCapsChanged, this, _1));
}
~FileSender() {
- //delete tracer;
+ delete tracer;
client->onDisconnected.disconnect(boost::bind(&FileSender::handleDisconnected, this, _1));
client->onConnected.disconnect(boost::bind(&FileSender::handleConnected, this));
delete client;
- delete socksBytestreamServer;
}
-
+
void start() {
- connectionServer->start();
- socksBytestreamServer->start();
client->connect();
}
- void stop() {
- if (transfer) {
- transfer->stop();
- }
- client->disconnect();
- socksBytestreamServer->stop();
- connectionServer->stop();
- }
-
private:
void handleConnected() {
client->sendPresence(Presence::create());
+
+ client->getFileTransferManager()->startListeningOnPort(19999);
+ //ByteArray fileData;
+ //readByteArrayFromFile(fileData, file.string());
+
+ // gather file information
+ /*StreamInitiationFileInfo fileInfo;
+
+ fileInfo.setName(file.filename());
+ fileInfo.setSize(boost::filesystem::file_size(file));
+ fileInfo.setDescription("Some file!");
+ fileInfo.setDate(boost::posix_time::from_time_t(boost::filesystem::last_write_time(file)));*/
+ //fileInfo.setHash(Hexify::hexify(MD5::getHash(fileData)));
+ /*
transfer = new OutgoingSIFileTransfer("myid", client->getJID(), recipient, file.filename(), boost::filesystem::file_size(file), "A file", boost::shared_ptr<FileReadBytestream>(new FileReadBytestream(file)), client->getIQRouter(), socksBytestreamServer);
transfer->onFinished.connect(boost::bind(&FileSender::handleFileTransferFinished, this, _1));
transfer->start();
+ */
+ }
+
+ void handleCapsChanged(JID jid) {
+ if (jid.toBare() == recipient) {
+ // create ReadBytestream from file
+ boost::shared_ptr<FileReadBytestream> fileStream = boost::make_shared<FileReadBytestream>(file);
+
+ outgoingFileTransfer = client->getFileTransferManager()->createOutgoingFileTransfer(recipient, file, "Some File!", fileStream);
+
+ if (outgoingFileTransfer) {
+ std::cout << "started FT" << std::endl;
+ outgoingFileTransfer->start();
+ // TODO: getting notified about FT status and end
+ } else {
+ std::cout << "[ ERROR ] " << recipient << " doesn't support any kind of file transfer!" << std::endl;
+ //client->disconnect();
+ }
+ }
}
void handleDisconnected(const boost::optional<ClientError>&) {
@@ -85,23 +117,23 @@ class FileSender {
exit(0);
}
}
-
+
void exit(int code) {
exitCode = code;
- stop();
eventLoop.stop();
}
private:
BoostConnectionServer::ref connectionServer;
SOCKS5BytestreamServer* socksBytestreamServer;
+ SOCKS5BytestreamRegistry* registry;
+ OutgoingFileTransfer::ref outgoingFileTransfer;
JID jid;
std::string password;
JID recipient;
boost::filesystem::path file;
Client* client;
ClientXMLTracer* tracer;
- OutgoingSIFileTransfer* transfer;
};
@@ -113,9 +145,9 @@ int main(int argc, char* argv[]) {
JID sender(argv[1]);
JID recipient(argv[3]);
- FileSender fileSender(sender, std::string(argv[2]), recipient, boost::filesystem::path(argv[4]), 8888);
+ Swift::logging = true;
+ FileSender fileSender(sender, std::string(argv[2]), recipient, boost::filesystem::path(argv[4]));
fileSender.start();
-
{
/*BoostTimer::ref timer(BoostTimer::create(30000, &MainBoostIOServiceThread::getInstance().getIOService()));
timer->onTick.connect(boost::bind(&SimpleEventLoop::stop, &eventLoop));
diff --git a/Swiften/FileTransfer/ByteArrayReadBytestream.h b/Swiften/FileTransfer/ByteArrayReadBytestream.h
index 4704db6..a6945c3 100644
--- a/Swiften/FileTransfer/ByteArrayReadBytestream.h
+++ b/Swiften/FileTransfer/ByteArrayReadBytestream.h
@@ -22,6 +22,8 @@ namespace Swift {
readSize = data.size() - position;
}
std::vector<unsigned char> result(data.begin() + position, data.begin() + position + readSize);
+
+ onRead(result);
position += readSize;
return result;
}
diff --git a/Swiften/FileTransfer/ByteArrayWriteBytestream.h b/Swiften/FileTransfer/ByteArrayWriteBytestream.h
index 6c360e6..ef97ed9 100644
--- a/Swiften/FileTransfer/ByteArrayWriteBytestream.h
+++ b/Swiften/FileTransfer/ByteArrayWriteBytestream.h
@@ -16,6 +16,7 @@ namespace Swift {
virtual void write(const std::vector<unsigned char>& bytes) {
data.insert(data.end(), bytes.begin(), bytes.end());
+ onWrite(bytes);
}
const std::vector<unsigned char>& getData() const {
diff --git a/Swiften/FileTransfer/ConnectivityManager.cpp b/Swiften/FileTransfer/ConnectivityManager.cpp
new file mode 100644
index 0000000..174d6ab
--- /dev/null
+++ b/Swiften/FileTransfer/ConnectivityManager.cpp
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "ConnectivityManager.h"
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Network/NetworkInterface.h>
+#include <Swiften/Network/PlatformNATTraversalGetPublicIPRequest.h>
+#include <Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.h>
+#include <Swiften/Network/PlatformNATTraversalWorker.h>
+#include <Swiften/Network/PlatformNetworkEnvironment.h>
+
+namespace Swift {
+
+ConnectivityManager::ConnectivityManager(PlatformNATTraversalWorker* worker) : natTraversalWorker(worker) {
+
+}
+
+ConnectivityManager::~ConnectivityManager() {
+ std::set<int> leftOpenPorts = ports;
+ foreach(int port, leftOpenPorts) {
+ removeListeningPort(port);
+ }
+}
+
+void ConnectivityManager::addListeningPort(int port) {
+ ports.insert(port);
+ boost::shared_ptr<PlatformNATTraversalGetPublicIPRequest> getIPRequest = natTraversalWorker->createGetPublicIPRequest();
+ if (getIPRequest) {
+ getIPRequest->onResult.connect(boost::bind(&ConnectivityManager::natTraversalGetPublicIPResult, this, _1));
+ getIPRequest->run();
+ }
+
+ boost::shared_ptr<PlatformNATTraversalForwardPortRequest> forwardPortRequest = natTraversalWorker->createForwardPortRequest(port, port);
+ if (forwardPortRequest) {
+ forwardPortRequest->onResult.connect(boost::bind(&ConnectivityManager::natTraversalForwardPortResult, this, _1));
+ forwardPortRequest->run();
+ }
+}
+
+void ConnectivityManager::removeListeningPort(int port) {
+ SWIFT_LOG(debug) << "remove listening port " << port << std::endl;
+ ports.erase(port);
+ boost::shared_ptr<PlatformNATTraversalRemovePortForwardingRequest> removePortForwardingRequest = natTraversalWorker->createRemovePortForwardingRequest(port, port);
+ if (removePortForwardingRequest) {
+ removePortForwardingRequest->run();
+ }
+}
+
+std::vector<HostAddressPort> ConnectivityManager::getHostAddressPorts() const {
+ PlatformNetworkEnvironment env;
+ std::vector<HostAddressPort> results;
+
+ std::vector<HostAddress> addresses;
+
+ foreach (NetworkInterface::ref iface, env.getNetworkInterfaces()) {
+ foreach (HostAddress address, iface->getAddresses()) {
+ foreach (int port, ports) {
+ results.push_back(HostAddressPort(address, port));
+ }
+ }
+ }
+
+ return results;
+}
+
+std::vector<HostAddressPort> ConnectivityManager::getAssistedHostAddressPorts() const {
+ std::vector<HostAddressPort> results;
+
+ if (publicAddress) {
+ foreach (int port, ports) {
+ results.push_back(HostAddressPort(publicAddress.get(), port));
+ }
+ }
+
+ return results;
+}
+
+void ConnectivityManager::natTraversalGetPublicIPResult(boost::optional<HostAddress> address) {
+ if (address) {
+ publicAddress = address;
+ SWIFT_LOG(debug) << "Public IP discovered as " << publicAddress.get().toString() << "." << std::endl;
+ } else {
+ SWIFT_LOG(debug) << "No public IP discoverable." << std::endl;
+ }
+}
+
+void ConnectivityManager::natTraversalForwardPortResult(boost::optional<PlatformNATTraversalForwardPortRequest::PortMapping> mapping) {
+ if (mapping) {
+ SWIFT_LOG(debug) << "Mapping port was successful." << std::endl;
+ } else {
+ SWIFT_LOG(debug) << "Mapping port has failed." << std::endl;
+ }
+}
+
+
+}
diff --git a/Swiften/FileTransfer/ConnectivityManager.h b/Swiften/FileTransfer/ConnectivityManager.h
new file mode 100644
index 0000000..87041b2
--- /dev/null
+++ b/Swiften/FileTransfer/ConnectivityManager.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <vector>
+#include <set>
+
+#include <boost/optional.hpp>
+
+#include <Swiften/Network/HostAddressPort.h>
+#include <Swiften/Network/PlatformNATTraversalForwardPortRequest.h>
+
+namespace Swift {
+
+class PlatformNATTraversalWorker;
+
+class ConnectivityManager {
+public:
+ ConnectivityManager(PlatformNATTraversalWorker*);
+ ~ConnectivityManager();
+public:
+ void addListeningPort(int port);
+ void removeListeningPort(int port);
+
+ std::vector<HostAddressPort> getHostAddressPorts() const;
+ std::vector<HostAddressPort> getAssistedHostAddressPorts() const;
+
+private:
+ void natTraversalGetPublicIPResult(boost::optional<HostAddress> address);
+ void natTraversalForwardPortResult(boost::optional<PlatformNATTraversalForwardPortRequest::PortMapping> mapping);
+
+private:
+ PlatformNATTraversalWorker* natTraversalWorker;
+
+ std::set<int> ports;
+ boost::optional<HostAddress> publicAddress;
+};
+
+}
diff --git a/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGenerator.cpp b/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGenerator.cpp
new file mode 100644
index 0000000..5b6da4c
--- /dev/null
+++ b/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGenerator.cpp
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "DefaultLocalJingleTransportCandidateGenerator.h"
+
+#include <vector>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/FileTransfer/ConnectivityManager.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamProxy.h>
+
+namespace Swift {
+
+DefaultLocalJingleTransportCandidateGenerator::DefaultLocalJingleTransportCandidateGenerator(ConnectivityManager* connectivityManager, SOCKS5BytestreamRegistry* s5bRegistry, SOCKS5BytestreamProxy* s5bProxy, JID& ownJID) : connectivityManager(connectivityManager), s5bRegistry(s5bRegistry), s5bProxy(s5bProxy), ownJID(ownJID) {
+}
+
+DefaultLocalJingleTransportCandidateGenerator::~DefaultLocalJingleTransportCandidateGenerator() {
+}
+
+void DefaultLocalJingleTransportCandidateGenerator::generateLocalTransportCandidates(JingleTransportPayload::ref transportPayload) {
+ if (boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transportPayload)) {
+ JingleTransportPayload::ref payL = boost::make_shared<JingleTransportPayload>();
+ payL->setSessionID(transportPayload->getSessionID());
+ onLocalTransportCandidatesGenerated(payL);
+ }
+ if (boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transportPayload)) {
+ JingleS5BTransportPayload::ref payL = boost::make_shared<JingleS5BTransportPayload>();
+ payL->setSessionID(transportPayload->getSessionID());
+ payL->setMode(JingleS5BTransportPayload::TCPMode);
+
+ const unsigned long localPreference = 0;
+
+ // get direct candidates
+ std::vector<HostAddressPort> directCandidates = connectivityManager->getHostAddressPorts();
+ foreach(HostAddressPort addressPort, directCandidates) {
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate.type = JingleS5BTransportPayload::Candidate::DirectType;
+ candidate.jid = ownJID;
+ candidate.hostPort = addressPort;
+ candidate.priority = 65536 * 126 + localPreference;
+ candidate.cid = idGenerator.generateID();
+ payL->addCandidate(candidate);
+ }
+
+ // get assissted candidates
+ std::vector<HostAddressPort> assisstedCandidates = connectivityManager->getAssistedHostAddressPorts();
+ foreach(HostAddressPort addressPort, assisstedCandidates) {
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate.type = JingleS5BTransportPayload::Candidate::AssistedType;
+ candidate.jid = ownJID;
+ candidate.hostPort = addressPort;
+ candidate.priority = 65536 * 120 + localPreference;
+ candidate.cid = idGenerator.generateID();
+ payL->addCandidate(candidate);
+ }
+
+ // get proxy candidates
+ std::vector<S5BProxyRequest::ref> proxyCandidates = s5bProxy->getS5BProxies();
+ foreach(S5BProxyRequest::ref proxy, proxyCandidates) {
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate.type = JingleS5BTransportPayload::Candidate::ProxyType;
+ candidate.jid = proxy->getStreamHost().get().jid;
+ candidate.hostPort = proxy->getStreamHost().get().addressPort;
+ candidate.priority = 65536 * 10 + localPreference;
+ candidate.cid = idGenerator.generateID();
+ payL->addCandidate(candidate);
+ }
+
+ onLocalTransportCandidatesGenerated(payL);
+ }
+
+}
+
+bool DefaultLocalJingleTransportCandidateGenerator::isActualCandidate(JingleTransportPayload::ref transportPayload) {
+ if (!transportPayload.get()) return false;
+ return false;
+}
+
+int DefaultLocalJingleTransportCandidateGenerator::getPriority(JingleTransportPayload::ref /* transportPayload */) {
+ return 0;
+}
+
+JingleTransport::ref DefaultLocalJingleTransportCandidateGenerator::selectTransport(JingleTransportPayload::ref /* transportPayload */) {
+ return JingleTransport::ref();
+}
+
+}
diff --git a/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGenerator.h b/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGenerator.h
new file mode 100644
index 0000000..7d45491
--- /dev/null
+++ b/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGenerator.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h>
+
+#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/JID/JID.h>
+
+namespace Swift {
+
+class SOCKS5BytestreamRegistry;
+class SOCKS5BytestreamProxy;
+class ConnectivityManager;
+
+class DefaultLocalJingleTransportCandidateGenerator : public LocalJingleTransportCandidateGenerator {
+public:
+ DefaultLocalJingleTransportCandidateGenerator(ConnectivityManager* connectivityManager, SOCKS5BytestreamRegistry* s5bRegistry, SOCKS5BytestreamProxy* s5bProxy, JID& ownJID);
+ virtual ~DefaultLocalJingleTransportCandidateGenerator();
+
+ virtual void generateLocalTransportCandidates(JingleTransportPayload::ref);
+
+ virtual bool isActualCandidate(JingleTransportPayload::ref);
+ virtual int getPriority(JingleTransportPayload::ref);
+ virtual JingleTransport::ref selectTransport(JingleTransportPayload::ref);
+
+private:
+ IDGenerator idGenerator;
+ ConnectivityManager* connectivityManager;
+ SOCKS5BytestreamRegistry* s5bRegistry;
+ SOCKS5BytestreamProxy* s5bProxy;
+ JID ownJID;
+};
+
+}
diff --git a/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.cpp b/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.cpp
new file mode 100644
index 0000000..ed0386e
--- /dev/null
+++ b/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "DefaultLocalJingleTransportCandidateGeneratorFactory.h"
+
+#include <Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGenerator.h>
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+
+DefaultLocalJingleTransportCandidateGeneratorFactory::DefaultLocalJingleTransportCandidateGeneratorFactory(ConnectivityManager* connectivityManager, SOCKS5BytestreamRegistry* s5bRegistry, SOCKS5BytestreamProxy* s5bProxy, const JID& ownJID) : connectivityManager(connectivityManager), s5bRegistry(s5bRegistry), s5bProxy(s5bProxy), ownJID(ownJID) {
+}
+
+DefaultLocalJingleTransportCandidateGeneratorFactory::~DefaultLocalJingleTransportCandidateGeneratorFactory() {
+}
+
+LocalJingleTransportCandidateGenerator* DefaultLocalJingleTransportCandidateGeneratorFactory::createCandidateGenerator() {
+ return new DefaultLocalJingleTransportCandidateGenerator(connectivityManager, s5bRegistry, s5bProxy, ownJID);
+}
+
+
+}
diff --git a/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.h b/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.h
new file mode 100644
index 0000000..511d0a1
--- /dev/null
+++ b/Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/FileTransfer/LocalJingleTransportCandidateGeneratorFactory.h>
+
+#include <Swiften/JID/JID.h>
+
+namespace Swift {
+
+class ConnectivityManager;
+class SOCKS5BytestreamRegistry;
+class SOCKS5BytestreamProxy;
+
+class DefaultLocalJingleTransportCandidateGeneratorFactory : public LocalJingleTransportCandidateGeneratorFactory{
+public:
+ DefaultLocalJingleTransportCandidateGeneratorFactory(ConnectivityManager* connectivityManager, SOCKS5BytestreamRegistry* s5bRegistry, SOCKS5BytestreamProxy* s5bProxy, const JID& ownJID);
+ virtual ~DefaultLocalJingleTransportCandidateGeneratorFactory();
+
+ LocalJingleTransportCandidateGenerator* createCandidateGenerator();
+
+private:
+ ConnectivityManager* connectivityManager;
+ SOCKS5BytestreamRegistry* s5bRegistry;
+ SOCKS5BytestreamProxy* s5bProxy;
+ JID ownJID;
+};
+
+}
diff --git a/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.cpp b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.cpp
new file mode 100644
index 0000000..32b4df8
--- /dev/null
+++ b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.cpp
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "DefaultRemoteJingleTransportCandidateSelector.h"
+
+#include <boost/smart_ptr/make_shared.hpp>
+#include <boost/bind.hpp>
+
+#include <Swiften/Base/Log.h>
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/Network/ConnectionFactory.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+
+namespace Swift {
+
+DefaultRemoteJingleTransportCandidateSelector::DefaultRemoteJingleTransportCandidateSelector(ConnectionFactory* connectionFactory, TimerFactory* timerFactory) : connectionFactory(connectionFactory), timerFactory(timerFactory) {
+}
+
+DefaultRemoteJingleTransportCandidateSelector::~DefaultRemoteJingleTransportCandidateSelector() {
+}
+
+void DefaultRemoteJingleTransportCandidateSelector::addRemoteTransportCandidates(JingleTransportPayload::ref transportPayload) {
+ JingleS5BTransportPayload::ref s5bPayload;
+ transportSID = transportPayload->getSessionID();
+ if ((s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transportPayload))) {
+ foreach(JingleS5BTransportPayload::Candidate c, s5bPayload->getCandidates()) {
+ candidates.push(c);
+ }
+ }
+}
+
+void DefaultRemoteJingleTransportCandidateSelector::selectCandidate() {
+ tryNextCandidate(true);
+}
+
+void DefaultRemoteJingleTransportCandidateSelector::tryNextCandidate(bool error) {
+ if (error) {
+ if (s5bSession) {
+ SWIFT_LOG(debug) << "failed to connect" << std::endl;
+ }
+ if (candidates.empty()) {
+ // failed to connect to any of the candidates
+ // issue an error
+ SWIFT_LOG(debug) << "out of candidates )=" << std::endl;
+ JingleS5BTransportPayload::ref failed = boost::make_shared<JingleS5BTransportPayload>();
+ failed->setCandidateError(true);
+ failed->setSessionID(transportSID);
+ onRemoteTransportCandidateSelectFinished(failed);
+ } else {
+ lastCandidate = candidates.top();
+ // only try direct or assisted for now
+ if (lastCandidate.type == JingleS5BTransportPayload::Candidate::DirectType ||
+ lastCandidate.type == JingleS5BTransportPayload::Candidate::AssistedType || lastCandidate.type == JingleS5BTransportPayload::Candidate::ProxyType ) {
+ // create connection
+ connection = connectionFactory->createConnection();
+ s5bSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, lastCandidate.hostPort, SOCKS5BytestreamRegistry::getHostname(transportSID, requester, target), timerFactory);
+
+ // bind onReady to this method
+ s5bSession->onSessionReady.connect(boost::bind(&DefaultRemoteJingleTransportCandidateSelector::tryNextCandidate, this, _1));
+
+ std::string candidateType;
+ if (lastCandidate.type == JingleS5BTransportPayload::Candidate::DirectType) {
+ candidateType = "direct";
+ } else if (lastCandidate.type == JingleS5BTransportPayload::Candidate::AssistedType) {
+ candidateType = "assisted";
+ } else if (lastCandidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ candidateType = "proxy";
+ }
+
+ // initiate connect
+ SWIFT_LOG(debug) << "try to connect to candidate of type " << candidateType << " : " << lastCandidate.hostPort.toString() << std::endl;
+ s5bSession->start();
+
+ // that's it. we're gonna be called back
+ candidates.pop();
+ } else {
+ s5bSession.reset();
+ candidates.pop();
+ tryNextCandidate(true);
+ }
+ }
+ } else {
+ // we have a working connection, hooray
+ JingleS5BTransportPayload::ref success = boost::make_shared<JingleS5BTransportPayload>();
+ success->setCandidateUsed(lastCandidate.cid);
+ success->setSessionID(transportSID);
+ onRemoteTransportCandidateSelectFinished(success);
+ }
+}
+
+void DefaultRemoteJingleTransportCandidateSelector::setMinimumPriority(int priority) {
+ SWIFT_LOG(debug) << "priority: " << priority << std::endl;
+}
+
+void DefaultRemoteJingleTransportCandidateSelector::setRequesterTargtet(const JID& requester, const JID& target) {
+ this->requester = requester;
+ this->target = target;
+}
+
+SOCKS5BytestreamClientSession::ref DefaultRemoteJingleTransportCandidateSelector::getS5BSession() {
+ return s5bSession;
+}
+
+bool DefaultRemoteJingleTransportCandidateSelector::isActualCandidate(JingleTransportPayload::ref /* transportPayload */) {
+ return false;
+}
+
+int DefaultRemoteJingleTransportCandidateSelector::getPriority(JingleTransportPayload::ref /* transportPayload */) {
+ return 0;
+}
+
+JingleTransport::ref DefaultRemoteJingleTransportCandidateSelector::selectTransport(JingleTransportPayload::ref /* transportPayload */) {
+ return JingleTransport::ref();
+}
+
+}
diff --git a/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.h b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.h
new file mode 100644
index 0000000..255acd9
--- /dev/null
+++ b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <queue>
+#include <vector>
+
+#include <boost/shared_ptr.hpp>
+
+#include <Swiften/JID/JID.h>
+#include <Swiften/Network/Connection.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+
+
+namespace Swift {
+
+class ConnectionFactory;
+class TimerFactory;
+
+class DefaultRemoteJingleTransportCandidateSelector : public RemoteJingleTransportCandidateSelector {
+public:
+ DefaultRemoteJingleTransportCandidateSelector(ConnectionFactory*, TimerFactory*);
+ virtual ~DefaultRemoteJingleTransportCandidateSelector();
+
+ virtual void addRemoteTransportCandidates(JingleTransportPayload::ref);
+ virtual void selectCandidate();
+ virtual void setMinimumPriority(int);
+ void setRequesterTargtet(const JID& requester, const JID& target);
+ virtual SOCKS5BytestreamClientSession::ref getS5BSession();
+
+ virtual bool isActualCandidate(JingleTransportPayload::ref);
+ virtual int getPriority(JingleTransportPayload::ref);
+ virtual JingleTransport::ref selectTransport(JingleTransportPayload::ref);
+
+private:
+ void tryNextCandidate(bool error);
+
+private:
+ ConnectionFactory* connectionFactory;
+ TimerFactory* timerFactory;
+
+ std::priority_queue<JingleS5BTransportPayload::Candidate, std::vector<JingleS5BTransportPayload::Candidate>, JingleS5BTransportPayload::CompareCandidate> candidates;
+
+ std::string transportSID;
+ boost::shared_ptr<Connection> connection;
+ boost::shared_ptr<SOCKS5BytestreamClientSession> s5bSession;
+ JingleS5BTransportPayload::Candidate lastCandidate;
+ JID requester;
+ JID target;
+};
+
+}
diff --git a/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.cpp b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.cpp
new file mode 100644
index 0000000..8ebbf46
--- /dev/null
+++ b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "DefaultRemoteJingleTransportCandidateSelectorFactory.h"
+
+#include <Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelector.h>
+
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+
+DefaultRemoteJingleTransportCandidateSelectorFactory::DefaultRemoteJingleTransportCandidateSelectorFactory(ConnectionFactory* connectionFactory, TimerFactory* timerFactory) : connectionFactory(connectionFactory), timerFactory(timerFactory) {
+}
+
+DefaultRemoteJingleTransportCandidateSelectorFactory::~DefaultRemoteJingleTransportCandidateSelectorFactory() {
+}
+
+RemoteJingleTransportCandidateSelector* DefaultRemoteJingleTransportCandidateSelectorFactory::createCandidateSelector() {
+ return new DefaultRemoteJingleTransportCandidateSelector(connectionFactory, timerFactory);
+}
+
+}
diff --git a/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.h b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.h
new file mode 100644
index 0000000..ca29e1f
--- /dev/null
+++ b/Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelectorFactory.h>
+
+namespace Swift {
+
+class ConnectionFactory;
+class TimerFactory;
+
+class DefaultRemoteJingleTransportCandidateSelectorFactory : public RemoteJingleTransportCandidateSelectorFactory {
+public:
+ DefaultRemoteJingleTransportCandidateSelectorFactory(ConnectionFactory*, TimerFactory*);
+ virtual ~DefaultRemoteJingleTransportCandidateSelectorFactory();
+
+ RemoteJingleTransportCandidateSelector* createCandidateSelector();
+
+private:
+ ConnectionFactory* connectionFactory;
+ TimerFactory* timerFactory;
+};
+
+}
diff --git a/Swiften/FileTransfer/FileReadBytestream.cpp b/Swiften/FileTransfer/FileReadBytestream.cpp
index 84d6490..f0139b8 100644
--- a/Swiften/FileTransfer/FileReadBytestream.cpp
+++ b/Swiften/FileTransfer/FileReadBytestream.cpp
@@ -30,6 +30,7 @@ std::vector<unsigned char> FileReadBytestream::read(size_t size) {
assert(stream->good());
stream->read(reinterpret_cast<char*>(&result[0]), size);
result.resize(stream->gcount());
+ onRead(result);
return result;
}
diff --git a/Swiften/FileTransfer/FileTransfer.h b/Swiften/FileTransfer/FileTransfer.h
new file mode 100644
index 0000000..6c37d8d
--- /dev/null
+++ b/Swiften/FileTransfer/FileTransfer.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <boost/optional.hpp>
+#include <boost/shared_ptr.hpp>
+
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/FileTransfer/FileTransferError.h>
+
+namespace Swift {
+
+class FileTransfer {
+public:
+ struct State {
+ enum FTState {
+ Canceled,
+ Failed,
+ Finished,
+ Negotiating,
+ Transferring,
+ WaitingForStart,
+ WaitingForAccept,
+ };
+
+ FTState state;
+ std::string message;
+
+ State(FTState state) : state(state), message("") {}
+ State(FTState state, std::string message) : state(state), message(message) {}
+ };
+
+public:
+ typedef boost::shared_ptr<FileTransfer> ref;
+
+public:
+ uintmax_t fileSizeInBytes;
+ std::string filename;
+ std::string algo;
+ std::string hash;
+
+public:
+ virtual void cancel() = 0;
+
+public:
+ boost::signal<void (int /* proccessedBytes */)> onProcessedBytes;
+ boost::signal<void (State)> onStateChange;
+ boost::signal<void (boost::optional<FileTransferError>)> onFinished;
+
+public:
+ virtual ~FileTransfer() {}
+};
+
+}
diff --git a/Swiften/FileTransfer/FileTransferManager.cpp b/Swiften/FileTransfer/FileTransferManager.cpp
new file mode 100644
index 0000000..69be852
--- /dev/null
+++ b/Swiften/FileTransfer/FileTransferManager.cpp
@@ -0,0 +1,14 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/FileTransfer/FileTransferManager.h>
+
+namespace Swift {
+
+FileTransferManager::~FileTransferManager() {
+}
+
+}
diff --git a/Swiften/FileTransfer/FileTransferManager.h b/Swiften/FileTransfer/FileTransferManager.h
new file mode 100644
index 0000000..3a1628f
--- /dev/null
+++ b/Swiften/FileTransfer/FileTransferManager.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <string>
+#include <boost/filesystem.hpp>
+#include <boost/date_time/posix_time/posix_time.hpp>
+
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
+#include <Swiften/FileTransfer/IncomingFileTransfer.h>
+
+namespace Swift {
+ class ReadBytestream;
+ class S5BProxyRequest;
+
+ class FileTransferManager {
+ public:
+ virtual ~FileTransferManager();
+
+ virtual void startListeningOnPort(int port) = 0;
+ virtual void addS5BProxy(boost::shared_ptr<S5BProxyRequest> proxy) = 0;
+
+ virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(const JID& to, const boost::filesystem::path& filepath, const std::string& description, boost::shared_ptr<ReadBytestream> bytestream) = 0;
+ virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(const JID& to, const std::string& filename, const std::string& description, const boost::uintmax_t sizeInBytes, const boost::posix_time::ptime& lastModified, boost::shared_ptr<ReadBytestream> bytestream) = 0;
+
+ boost::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer;
+ };
+}
diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.cpp b/Swiften/FileTransfer/FileTransferManagerImpl.cpp
new file mode 100644
index 0000000..f89a3e9
--- /dev/null
+++ b/Swiften/FileTransfer/FileTransferManagerImpl.cpp
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/FileTransfer/FileTransferManagerImpl.h>
+
+#include <boost/bind.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include "Swiften/Disco/EntityCapsProvider.h"
+#include <Swiften/JID/JID.h>
+#include <Swiften/Elements/StreamInitiationFileInfo.h>
+#include <Swiften/FileTransfer/ConnectivityManager.h>
+#include <Swiften/FileTransfer/OutgoingFileTransferManager.h>
+#include <Swiften/FileTransfer/IncomingFileTransferManager.h>
+#include <Swiften/FileTransfer/DefaultLocalJingleTransportCandidateGeneratorFactory.h>
+#include <Swiften/FileTransfer/DefaultRemoteJingleTransportCandidateSelectorFactory.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamServer.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamProxy.h>
+#include <Swiften/Presence/PresenceOracle.h>
+#include <Swiften/Elements/Presence.h>
+#include <Swiften/Network/ConnectionFactory.h>
+#include <Swiften/Network/ConnectionServerFactory.h>
+#include <Swiften/Network/HostAddress.h>
+#include <Swiften/Network/PlatformNATTraversalWorker.h>
+
+namespace Swift {
+
+FileTransferManagerImpl::FileTransferManagerImpl(const JID& ownFullJID, JingleSessionManager* jingleSessionManager, IQRouter* router, EntityCapsProvider* capsProvider, PresenceOracle* presOracle, ConnectionFactory* connectionFactory, ConnectionServerFactory* connectionServerFactory, TimerFactory* timerFactory, PlatformNATTraversalWorker* natTraversalWorker) : ownJID(ownFullJID), jingleSM(jingleSessionManager), iqRouter(router), capsProvider(capsProvider), presenceOracle(presOracle), timerFactory(timerFactory), connectionFactory(connectionFactory), connectionServerFactory(connectionServerFactory), natTraversalWorker(natTraversalWorker), bytestreamServer(NULL) {
+ assert(!ownFullJID.isBare());
+
+ connectivityManager = new ConnectivityManager(natTraversalWorker);
+ bytestreamRegistry = new SOCKS5BytestreamRegistry();
+ bytestreamProxy = new SOCKS5BytestreamProxy(connectionFactory, timerFactory);
+
+ localCandidateGeneratorFactory = new DefaultLocalJingleTransportCandidateGeneratorFactory(connectivityManager, bytestreamRegistry, bytestreamProxy, ownFullJID);
+ remoteCandidateSelectorFactory = new DefaultRemoteJingleTransportCandidateSelectorFactory(connectionFactory, timerFactory);
+ outgoingFTManager = new OutgoingFileTransferManager(ownJID, jingleSM, iqRouter, capsProvider, remoteCandidateSelectorFactory, localCandidateGeneratorFactory, bytestreamRegistry, bytestreamProxy);
+ incomingFTManager = new IncomingFileTransferManager(ownJID, jingleSM, iqRouter, remoteCandidateSelectorFactory, localCandidateGeneratorFactory, bytestreamRegistry, bytestreamProxy, timerFactory);
+ incomingFTManager->onIncomingFileTransfer.connect(onIncomingFileTransfer);
+}
+
+FileTransferManagerImpl::~FileTransferManagerImpl() {
+ if (bytestreamServer) {
+ bytestreamServer->stop();
+ }
+ delete incomingFTManager;
+ delete outgoingFTManager;
+ delete remoteCandidateSelectorFactory;
+ delete localCandidateGeneratorFactory;
+ delete connectivityManager;
+}
+
+void FileTransferManagerImpl::startListeningOnPort(int port) {
+ // TODO: create a server for each interface we're on
+ SWIFT_LOG(debug) << "Start listening on port " << port << " and hope it's not in use." << std::endl;
+ boost::shared_ptr<ConnectionServer> server = connectionServerFactory->createConnectionServer(HostAddress("0.0.0.0"), port);
+ server->start();
+ bytestreamServer = new SOCKS5BytestreamServer(server, bytestreamRegistry);
+ bytestreamServer->start();
+ connectivityManager->addListeningPort(port);
+}
+
+void FileTransferManagerImpl::addS5BProxy(S5BProxyRequest::ref proxy) {
+ bytestreamProxy->addS5BProxy(proxy);
+}
+
+boost::optional<JID> FileTransferManagerImpl::highestPriorityJIDSupportingFileTransfer(const JID& bareJID) {
+ JID fullReceipientJID;
+ int priority = INT_MIN;
+
+ //getAllPresence(bareJID) gives you all presences for the bare JID (i.e. all resources) Remko Tronçon @ 11:11
+ std::vector<Presence::ref> presences = presenceOracle->getAllPresence(bareJID);
+
+ //iterate over them
+ foreach(Presence::ref pres, presences) {
+ if (pres->getPriority() > priority) {
+ // look up caps from the jid
+ DiscoInfo::ref info = capsProvider->getCaps(pres->getFrom());
+ if (info && info->hasFeature(DiscoInfo::JingleFeature) && info->hasFeature(DiscoInfo::JingleFTFeature) &&
+ info->hasFeature(DiscoInfo::JingleTransportsIBBFeature)) {
+
+ priority = pres->getPriority();
+ fullReceipientJID = pres->getFrom();
+ }
+ }
+ }
+
+ return fullReceipientJID.isValid() ? boost::optional<JID>(fullReceipientJID) : boost::optional<JID>();
+}
+
+OutgoingFileTransfer::ref FileTransferManagerImpl::createOutgoingFileTransfer(const JID& to, const boost::filesystem::path& filepath, const std::string& description, boost::shared_ptr<ReadBytestream> bytestream) {
+ std::string filename = filepath.filename();
+ uintmax_t sizeInBytes = boost::filesystem::file_size(filepath);
+ boost::posix_time::ptime lastModified = boost::posix_time::from_time_t(boost::filesystem::last_write_time(filepath));
+ return createOutgoingFileTransfer(to, filename, description, sizeInBytes, lastModified, bytestream);
+}
+
+OutgoingFileTransfer::ref FileTransferManagerImpl::createOutgoingFileTransfer(const JID& to, const std::string& filename, const std::string& description, const uintmax_t sizeInBytes, const boost::posix_time::ptime& lastModified, boost::shared_ptr<ReadBytestream> bytestream) {
+ StreamInitiationFileInfo fileInfo;
+ fileInfo.setDate(lastModified);
+ fileInfo.setSize(sizeInBytes);
+ fileInfo.setName(filename);
+ fileInfo.setDescription(description);
+
+ JID receipient = to;
+
+ if(receipient.isBare()) {
+ boost::optional<JID> fullJID = highestPriorityJIDSupportingFileTransfer(receipient);
+ if (fullJID.is_initialized()) {
+ receipient = fullJID.get();
+ } else {
+ return OutgoingFileTransfer::ref();
+ }
+ }
+
+ return outgoingFTManager->createOutgoingFileTransfer(receipient, bytestream, fileInfo);
+}
+
+}
diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.h b/Swiften/FileTransfer/FileTransferManagerImpl.h
new file mode 100644
index 0000000..b38eaea
--- /dev/null
+++ b/Swiften/FileTransfer/FileTransferManagerImpl.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <vector>
+#include <string>
+
+#include <boost/filesystem.hpp>
+#include <boost/date_time/posix_time/posix_time.hpp>
+#include <boost/optional.hpp>
+
+#include <Swiften/FileTransfer/FileTransferManager.h>
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
+#include <Swiften/FileTransfer/IncomingFileTransfer.h>
+#include <Swiften/Elements/S5BProxyRequest.h>
+
+namespace Swift {
+
+class Client;
+class ConnectionFactory;
+class ConnectionServerFactory;
+class ConnectivityManager;
+class EntityCapsProvider;
+class IQRouter;
+class IncomingFileTransferManager;
+class JingleSessionManager;
+class LocalJingleTransportCandidateGeneratorFactory;
+class OutgoingFileTransferManager;
+class PlatformNATTraversalWorker;
+class PresenceOracle;
+class ReadBytestream;
+class RemoteJingleTransportCandidateSelectorFactory;
+class SOCKS5BytestreamRegistry;
+class SOCKS5BytestreamServer;
+class SOCKS5BytestreamProxy;
+class TimerFactory;
+
+class FileTransferManagerImpl : public FileTransferManager {
+public:
+ FileTransferManagerImpl(const JID& ownFullJID, JingleSessionManager* jingleSessionManager, IQRouter* router, EntityCapsProvider* capsProvider, PresenceOracle* presOracle, ConnectionFactory* connectionFactory, ConnectionServerFactory* connectionServerFactory, TimerFactory* timerFactory, PlatformNATTraversalWorker* natTraversalWorker);
+ ~FileTransferManagerImpl();
+
+ void startListeningOnPort(int port);
+ void addS5BProxy(S5BProxyRequest::ref proxy);
+
+ OutgoingFileTransfer::ref createOutgoingFileTransfer(const JID& to, const boost::filesystem::path& filepath, const std::string& description, boost::shared_ptr<ReadBytestream> bytestream);
+ OutgoingFileTransfer::ref createOutgoingFileTransfer(const JID& to, const std::string& filename, const std::string& description, const boost::uintmax_t sizeInBytes, const boost::posix_time::ptime& lastModified, boost::shared_ptr<ReadBytestream> bytestream);
+
+ private:
+ boost::optional<JID> highestPriorityJIDSupportingFileTransfer(const JID& bareJID);
+
+private:
+ JID ownJID;
+
+ OutgoingFileTransferManager* outgoingFTManager;
+ IncomingFileTransferManager* incomingFTManager;
+ RemoteJingleTransportCandidateSelectorFactory* remoteCandidateSelectorFactory;
+ LocalJingleTransportCandidateGeneratorFactory* localCandidateGeneratorFactory;
+ JingleSessionManager* jingleSM;
+ IQRouter* iqRouter;
+ EntityCapsProvider* capsProvider;
+ PresenceOracle* presenceOracle;
+
+ TimerFactory* timerFactory;
+ ConnectionFactory* connectionFactory;
+ ConnectionServerFactory* connectionServerFactory;
+ PlatformNATTraversalWorker* natTraversalWorker;
+ SOCKS5BytestreamRegistry* bytestreamRegistry;
+ SOCKS5BytestreamServer* bytestreamServer;
+ SOCKS5BytestreamProxy* bytestreamProxy;
+ ConnectivityManager* connectivityManager;
+};
+
+}
diff --git a/Swiften/FileTransfer/FileWriteBytestream.cpp b/Swiften/FileTransfer/FileWriteBytestream.cpp
index c38338a..6a22c6a 100644
--- a/Swiften/FileTransfer/FileWriteBytestream.cpp
+++ b/Swiften/FileTransfer/FileWriteBytestream.cpp
@@ -27,6 +27,14 @@ void FileWriteBytestream::write(const std::vector<unsigned char>& data) {
}
assert(stream->good());
stream->write(reinterpret_cast<const char*>(&data[0]), data.size());
+ onWrite(data);
+}
+
+void FileWriteBytestream::close() {
+ if (stream) {
+ stream->close();
+ stream = NULL;
+ }
}
}
diff --git a/Swiften/FileTransfer/FileWriteBytestream.h b/Swiften/FileTransfer/FileWriteBytestream.h
index 8cfa718..82c4a65 100644
--- a/Swiften/FileTransfer/FileWriteBytestream.h
+++ b/Swiften/FileTransfer/FileWriteBytestream.h
@@ -18,6 +18,7 @@ namespace Swift {
~FileWriteBytestream();
virtual void write(const std::vector<unsigned char>&);
+ void close();
private:
boost::filesystem::path file;
diff --git a/Swiften/FileTransfer/IBBReceiveSession.cpp b/Swiften/FileTransfer/IBBReceiveSession.cpp
index 566dcca..43c26be 100644
--- a/Swiften/FileTransfer/IBBReceiveSession.cpp
+++ b/Swiften/FileTransfer/IBBReceiveSession.cpp
@@ -14,6 +14,8 @@
#include <Swiften/FileTransfer/BytestreamException.h>
#include <Swiften/Queries/SetResponder.h>
+#include <cassert>
+
namespace Swift {
class IBBReceiveSession::IBBResponder : public SetResponder<IBB> {
@@ -43,14 +45,17 @@ class IBBReceiveSession::IBBResponder : public SetResponder<IBB> {
}
}
else if (ibb->getAction() == IBB::Open) {
+ SWIFT_LOG(debug) << "IBB open received" << std::endl;
sendResponse(from, id, IBB::ref());
}
else if (ibb->getAction() == IBB::Close) {
+ SWIFT_LOG(debug) << "IBB close received" << std::endl;
sendResponse(from, id, IBB::ref());
session->finish(FileTransferError(FileTransferError::ClosedError));
}
return true;
}
+ SWIFT_LOG(debug) << "wrong from/sessionID: " << from << " == " << session->from << " / " <<ibb->getStreamID() << " == " << session->id << std::endl;
return false;
}
@@ -71,6 +76,8 @@ IBBReceiveSession::IBBReceiveSession(
size(size),
router(router),
active(false) {
+ assert(!id.empty());
+ assert(from.isValid());
responder = new IBBResponder(this, router);
}
@@ -82,11 +89,13 @@ IBBReceiveSession::~IBBReceiveSession() {
}
void IBBReceiveSession::start() {
+ SWIFT_LOG(debug) << "receive session started" << std::endl;
active = true;
responder->start();
}
void IBBReceiveSession::stop() {
+ SWIFT_LOG(debug) << "receive session stopped" << std::endl;
responder->stop();
if (active) {
if (router->isAvailable()) {
diff --git a/Swiften/FileTransfer/IBBSendSession.cpp b/Swiften/FileTransfer/IBBSendSession.cpp
index 5376276..a434cfb 100644
--- a/Swiften/FileTransfer/IBBSendSession.cpp
+++ b/Swiften/FileTransfer/IBBSendSession.cpp
@@ -35,7 +35,7 @@ void IBBSendSession::stop() {
}
void IBBSendSession::handleIBBResponse(IBB::ref, ErrorPayload::ref error) {
- if (!error) {
+ if (!error && active) {
if (!bytestream->isFinished()) {
try {
std::vector<unsigned char> data = bytestream->read(blockSize);
@@ -43,6 +43,7 @@ void IBBSendSession::handleIBBResponse(IBB::ref, ErrorPayload::ref error) {
sequenceNumber++;
request->onResponse.connect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2));
request->send();
+ onBytesSent(data.size());
}
catch (const BytestreamException&) {
finish(FileTransferError(FileTransferError::ReadError));
diff --git a/Swiften/FileTransfer/IBBSendSession.h b/Swiften/FileTransfer/IBBSendSession.h
index 6c741cf..325f66c 100644
--- a/Swiften/FileTransfer/IBBSendSession.h
+++ b/Swiften/FileTransfer/IBBSendSession.h
@@ -32,7 +32,7 @@ namespace Swift {
}
boost::signal<void (boost::optional<FileTransferError>)> onFinished;
-
+ boost::signal<void (int)> onBytesSent;
private:
void handleIBBResponse(IBB::ref, ErrorPayload::ref);
void finish(boost::optional<FileTransferError>);
diff --git a/Swiften/FileTransfer/IncomingFileTransfer.h b/Swiften/FileTransfer/IncomingFileTransfer.h
index 1ccd76c..a6cf05e 100644
--- a/Swiften/FileTransfer/IncomingFileTransfer.h
+++ b/Swiften/FileTransfer/IncomingFileTransfer.h
@@ -9,15 +9,18 @@
#include <boost/shared_ptr.hpp>
#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/FileTransfer/FileTransfer.h>
#include <Swiften/FileTransfer/WriteBytestream.h>
namespace Swift {
- class IncomingFileTransfer {
+ class IncomingFileTransfer : public FileTransfer {
public:
typedef boost::shared_ptr<IncomingFileTransfer> ref;
virtual ~IncomingFileTransfer();
virtual void accept(WriteBytestream::ref) = 0;
+ virtual const JID& getSender() const = 0;
};
}
diff --git a/Swiften/FileTransfer/IncomingFileTransferManager.cpp b/Swiften/FileTransfer/IncomingFileTransferManager.cpp
index 79d2391..c01c906 100644
--- a/Swiften/FileTransfer/IncomingFileTransferManager.cpp
+++ b/Swiften/FileTransfer/IncomingFileTransferManager.cpp
@@ -18,7 +18,9 @@
namespace Swift {
-IncomingFileTransferManager::IncomingFileTransferManager(JingleSessionManager* jingleSessionManager, IQRouter* router) : jingleSessionManager(jingleSessionManager), router(router) {
+IncomingFileTransferManager::IncomingFileTransferManager(const JID& ourFullJID, JingleSessionManager* jingleSessionManager, IQRouter* router,
+ RemoteJingleTransportCandidateSelectorFactory* remoteFactory,
+ LocalJingleTransportCandidateGeneratorFactory* localFactory, SOCKS5BytestreamRegistry* bytestreamRegistry, SOCKS5BytestreamProxy* bytestreamProxy, TimerFactory* timerFactory) : ourJID(ourFullJID), jingleSessionManager(jingleSessionManager), router(router), remoteFactory(remoteFactory), localFactory(localFactory), bytestreamRegistry(bytestreamRegistry), bytestreamProxy(bytestreamProxy), timerFactory(timerFactory) {
jingleSessionManager->addIncomingSessionHandler(this);
}
@@ -29,13 +31,19 @@ IncomingFileTransferManager::~IncomingFileTransferManager() {
bool IncomingFileTransferManager::handleIncomingJingleSession(JingleSession::ref session, const std::vector<JingleContentPayload::ref>& contents) {
if (JingleContentPayload::ref content = Jingle::getContentWithDescription<JingleFileTransferDescription>(contents)) {
if (content->getTransport<JingleIBBTransportPayload>() || content->getTransport<JingleS5BTransportPayload>()) {
- RemoteJingleTransportCandidateSelectorFactory* a;
- LocalJingleTransportCandidateGeneratorFactory* b;
- IncomingJingleFileTransfer::ref transfer = boost::make_shared<IncomingJingleFileTransfer>(session, content, a, b, router);
- onIncomingFileTransfer(transfer);
+
+ JingleFileTransferDescription::ref description = content->getDescription<JingleFileTransferDescription>();
+
+ if (description && description->getOffers().size() == 1) {
+ IncomingJingleFileTransfer::ref transfer = boost::make_shared<IncomingJingleFileTransfer>(ourJID, session, content, remoteFactory, localFactory, router, bytestreamRegistry, bytestreamProxy, timerFactory);
+ onIncomingFileTransfer(transfer);
+ } else {
+ std::cerr << "Received a file-transfer request with no description or more than one file!" << std::endl;
+ session->sendTerminate(JinglePayload::Reason::FailedApplication);
+ }
}
else {
- session->terminate(JinglePayload::Reason::UnsupportedTransports);
+ session->sendTerminate(JinglePayload::Reason::UnsupportedTransports);
}
return true;
}
diff --git a/Swiften/FileTransfer/IncomingFileTransferManager.h b/Swiften/FileTransfer/IncomingFileTransferManager.h
index 428a838..d1573f6 100644
--- a/Swiften/FileTransfer/IncomingFileTransferManager.h
+++ b/Swiften/FileTransfer/IncomingFileTransferManager.h
@@ -17,10 +17,13 @@ namespace Swift {
class JingleSessionManager;
class RemoteJingleTransportCandidateSelectorFactory;
class LocalJingleTransportCandidateGeneratorFactory;
+ class SOCKS5BytestreamRegistry;
+ class SOCKS5BytestreamProxy;
+ class TimerFactory;
class IncomingFileTransferManager : public IncomingJingleSessionHandler {
public:
- IncomingFileTransferManager(JingleSessionManager* jingleSessionManager, IQRouter* router);
+ IncomingFileTransferManager(const JID& ourFullJID, JingleSessionManager* jingleSessionManager, IQRouter* router, RemoteJingleTransportCandidateSelectorFactory* remoteFactory, LocalJingleTransportCandidateGeneratorFactory* localFactory, SOCKS5BytestreamRegistry* bytestreamRegistry, SOCKS5BytestreamProxy* bytestreamProxy, TimerFactory* timerFactory);
~IncomingFileTransferManager();
boost::signal<void (IncomingFileTransfer::ref)> onIncomingFileTransfer;
@@ -29,7 +32,13 @@ namespace Swift {
bool handleIncomingJingleSession(JingleSession::ref session, const std::vector<JingleContentPayload::ref>& contents);
private:
+ JID ourJID;
JingleSessionManager* jingleSessionManager;
IQRouter* router;
+ RemoteJingleTransportCandidateSelectorFactory* remoteFactory;
+ LocalJingleTransportCandidateGeneratorFactory* localFactory;
+ SOCKS5BytestreamRegistry* bytestreamRegistry;
+ SOCKS5BytestreamProxy* bytestreamProxy;
+ TimerFactory* timerFactory;
};
}
diff --git a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
index 904b53e..1189830 100644
--- a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
@@ -9,29 +9,47 @@
#include <boost/bind.hpp>
#include <boost/smart_ptr/make_shared.hpp>
-#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelectorFactory.h>
-#include <Swiften/FileTransfer/LocalJingleTransportCandidateGeneratorFactory.h>
-#include <Swiften/FileTransfer/JingleIncomingIBBTransport.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Base/foreach.h>
#include <Swiften/Elements/JingleIBBTransportPayload.h>
#include <Swiften/Elements/JingleS5BTransportPayload.h>
-#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
+#include <Swiften/Elements/JingleFileTransferHash.h>
+#include <Swiften/Elements/S5BProxyRequest.h>
+#include <Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h>
+#include <Swiften/FileTransfer/JingleIncomingIBBTransport.h>
#include <Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h>
+#include <Swiften/FileTransfer/LocalJingleTransportCandidateGeneratorFactory.h>
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelectorFactory.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamProxy.h>
+#include <Swiften/Network/TimerFactory.h>
+#include <Swiften/Queries/GenericRequest.h>
namespace Swift {
IncomingJingleFileTransfer::IncomingJingleFileTransfer(
+ const JID& ourJID,
JingleSession::ref session,
JingleContentPayload::ref content,
RemoteJingleTransportCandidateSelectorFactory* candidateSelectorFactory,
LocalJingleTransportCandidateGeneratorFactory* candidateGeneratorFactory,
- IQRouter* router) :
+ IQRouter* router,
+ SOCKS5BytestreamRegistry* registry,
+ SOCKS5BytestreamProxy* proxy,
+ TimerFactory* timerFactory) :
+ ourJID(ourJID),
session(session),
router(router),
+ timerFactory(timerFactory),
initialContent(content),
- contentID(content->getName(), content->getCreator()),
state(Initial),
+ receivedBytes(0),
+ s5bRegistry(registry),
+ s5bProxy(proxy),
remoteTransportCandidateSelectFinished(false),
- localTransportCandidateSelectFinished(false) {
+ localTransportCandidateSelectFinished(false),
+ serverSession(0) {
candidateSelector = candidateSelectorFactory->createCandidateSelector();
candidateSelector->onRemoteTransportCandidateSelectFinished.connect(boost::bind(&IncomingJingleFileTransfer::handleRemoteTransportCandidateSelectFinished, this, _1));
@@ -41,13 +59,26 @@ IncomingJingleFileTransfer::IncomingJingleFileTransfer(
session->onTransportInfoReceived.connect(boost::bind(&IncomingJingleFileTransfer::handleTransportInfoReceived, this, _1, _2));
session->onTransportReplaceReceived.connect(boost::bind(&IncomingJingleFileTransfer::handleTransportReplaceReceived, this, _1, _2));
- session->onSessionTerminateReceived.connect(boost::bind(&IncomingJingleFileTransfer::handleSessionTerminateReceived, this));
+ session->onSessionTerminateReceived.connect(boost::bind(&IncomingJingleFileTransfer::handleSessionTerminateReceived, this, _1));
+ session->onSessionInfoReceived.connect(boost::bind(&IncomingJingleFileTransfer::handleSessionInfoReceived, this, _1));
description = initialContent->getDescription<JingleFileTransferDescription>();
assert(description);
+ assert(description->getOffers().size() == 1);
+ StreamInitiationFileInfo fileInfo = description->getOffers().front();
+ fileSizeInBytes = fileInfo.getSize();
+ filename = fileInfo.getName();
+ hash = fileInfo.getHash();
+ algo = fileInfo.getAlgo();
+
+ waitOnHashTimer = timerFactory->createTimer(5000);
+ waitOnHashTimer->onTick.connect(boost::bind(&IncomingJingleFileTransfer::finishOffTransfer, this));
}
IncomingJingleFileTransfer::~IncomingJingleFileTransfer() {
+ stream->onWrite.disconnect(boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1));
+ delete hashCalculator;
+
session->onSessionTerminateReceived.disconnect(boost::bind(&IncomingJingleFileTransfer::handleSessionTerminateReceived, this));
session->onTransportReplaceReceived.disconnect(boost::bind(&IncomingJingleFileTransfer::handleTransportReplaceReceived, this, _1, _2));
session->onTransportInfoReceived.disconnect(boost::bind(&IncomingJingleFileTransfer::handleTransportInfoReceived, this, _1, _2));
@@ -60,44 +91,87 @@ IncomingJingleFileTransfer::~IncomingJingleFileTransfer() {
}
void IncomingJingleFileTransfer::accept(WriteBytestream::ref stream) {
- assert(!stream);
+ assert(!this->stream);
this->stream = stream;
+ hashCalculator = new IncrementalBytestreamHashCalculator( algo == "md5" || hash.empty() , algo == "sha-1" || hash.empty() );
+ stream->onWrite.connect(boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1));
+ stream->onWrite.connect(boost::bind(&IncomingJingleFileTransfer::handleWriteStreamDataReceived, this, _1));
+ onStateChange(FileTransfer::State(FileTransfer::State::Negotiating));
if (JingleIBBTransportPayload::ref ibbTransport = initialContent->getTransport<JingleIBBTransportPayload>()) {
+ SWIFT_LOG(debug) << "Got IBB transport payload!" << std::endl;
setActiveTransport(createIBBTransport(ibbTransport));
- session->accept();
+ session->sendAccept(getContentID(), initialContent->getDescriptions()[0], ibbTransport);
}
else if (JingleS5BTransportPayload::ref s5bTransport = initialContent->getTransport<JingleS5BTransportPayload>()) {
+ SWIFT_LOG(debug) << "Got S5B transport payload!" << std::endl;
state = CreatingInitialTransports;
+ s5bSessionID = s5bTransport->getSessionID().empty() ? idGenerator.generateID() : s5bTransport->getSessionID();
+ s5bDestination = SOCKS5BytestreamRegistry::getHostname(s5bSessionID, ourJID, session->getInitiator());
+ s5bRegistry->addWriteBytestream(s5bDestination, stream);
+ fillCandidateMap(theirCandidates, s5bTransport);
candidateSelector->addRemoteTransportCandidates(s5bTransport);
- candidateGenerator->generateLocalTransportCandidates();
+ candidateSelector->setRequesterTargtet(session->getInitiator(), ourJID);
+ s5bTransport->setSessionID(s5bSessionID);
+ candidateGenerator->generateLocalTransportCandidates(s5bTransport);
}
else {
assert(false);
}
}
+const JID& IncomingJingleFileTransfer::getSender() const {
+ return session->getInitiator();
+}
+
+void IncomingJingleFileTransfer::cancel() {
+ session->sendTerminate(JinglePayload::Reason::Cancel);
+
+ if (activeTransport) activeTransport->stop();
+ if (serverSession) serverSession->stop();
+ if (clientSession) clientSession->stop();
+ onStateChange(FileTransfer::State(FileTransfer::State::Canceled));
+}
void IncomingJingleFileTransfer::handleLocalTransportCandidatesGenerated(JingleTransportPayload::ref candidates) {
if (state == CreatingInitialTransports) {
- if (!candidates) {
- localTransportCandidateSelectFinished = true;
+ if (JingleS5BTransportPayload::ref s5bCandidates = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(candidates)) {
+ //localTransportCandidateSelectFinished = true;
+ //JingleS5BTransportPayload::ref emptyCandidates = boost::make_shared<JingleS5BTransportPayload>();
+ //emptyCandidates->setSessionID(s5bCandidates->getSessionID());
+ fillCandidateMap(ourCandidates, s5bCandidates);
+ session->sendAccept(getContentID(), initialContent->getDescriptions()[0], s5bCandidates);
+
+ state = NegotiatingTransport;
+ candidateSelector->selectCandidate();
}
- session->accept(candidates);
- state = NegotiatingTransport;
- candidateSelector->selectCandidate();
+ }
+ else {
+ SWIFT_LOG(debug) << "Unhandled state!" << std::endl;
}
}
void IncomingJingleFileTransfer::handleRemoteTransportCandidateSelectFinished(JingleTransportPayload::ref transport) {
- remoteTransportCandidateSelectFinished = true;
- selectedRemoteTransportCandidate = transport;
- session->sendTransportInfo(contentID, transport);
- checkCandidateSelected();
+ SWIFT_LOG(debug) << std::endl;
+ if (state == Terminated) {
+ return;
+ }
+ if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport)) {
+ //remoteTransportCandidateSelectFinished = true;
+ //selectedRemoteTransportCandidate = transport;
+ ourCandidate = s5bPayload;
+ //checkCandidateSelected();
+ decideOnUsedTransport();
+ session->sendTransportInfo(getContentID(), s5bPayload);
+ }
+ else {
+ SWIFT_LOG(debug) << "Expected something different here." << std::endl;
+ }
}
void IncomingJingleFileTransfer::checkCandidateSelected() {
+ assert(false);
if (localTransportCandidateSelectFinished && remoteTransportCandidateSelectFinished) {
if (candidateGenerator->isActualCandidate(selectedLocalTransportCandidate) && candidateSelector->isActualCandidate(selectedRemoteTransportCandidate)) {
if (candidateGenerator->getPriority(selectedLocalTransportCandidate) > candidateSelector->getPriority(selectedRemoteTransportCandidate)) {
@@ -121,37 +195,293 @@ void IncomingJingleFileTransfer::checkCandidateSelected() {
void IncomingJingleFileTransfer::setActiveTransport(JingleTransport::ref transport) {
state = Transferring;
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
activeTransport = transport;
activeTransport->onDataReceived.connect(boost::bind(&IncomingJingleFileTransfer::handleTransportDataReceived, this, _1));
+ activeTransport->onFinished.connect(boost::bind(&IncomingJingleFileTransfer::handleTransferFinished, this, _1));
activeTransport->start();
}
-void IncomingJingleFileTransfer::handleSessionTerminateReceived() {
- // TODO
+bool IncomingJingleFileTransfer::verifyReceviedData() {
+ if (algo.empty() || hash.empty()) {
+ SWIFT_LOG(debug) << "no verification possible, skipping" << std::endl;
+ return true;
+ } else {
+ if (algo == "sha-1") {
+ SWIFT_LOG(debug) << "verify data via SHA-1 hash: " << (hash == hashCalculator->getSHA1String()) << std::endl;
+ return hash == hashCalculator->getSHA1String();
+ }
+ else if (algo == "md5") {
+ SWIFT_LOG(debug) << "verify data via MD5 hash: " << (hash == hashCalculator->getMD5String()) << std::endl;
+ return hash == hashCalculator->getMD5String();
+ }
+ else {
+ SWIFT_LOG(debug) << "no verification possible, skipping" << std::endl;
+ return true;
+ }
+ }
+}
+
+void IncomingJingleFileTransfer::finishOffTransfer() {
+ if (verifyReceviedData()) {
+ onStateChange(FileTransfer::State(FileTransfer::State::Finished));
+ session->sendTerminate(JinglePayload::Reason::Success);
+ } else {
+ onStateChange(FileTransfer::State(FileTransfer::State::Failed, "Verification failed."));
+ session->sendTerminate(JinglePayload::Reason::MediaError);
+ }
+ state = Terminated;
+ waitOnHashTimer->stop();
+}
+
+void IncomingJingleFileTransfer::handleSessionInfoReceived(JinglePayload::ref jinglePayload) {
+ if (state == Terminated) {
+ return;
+ }
+ JingleFileTransferHash::ref transferHash = jinglePayload->getPayload<JingleFileTransferHash>();
+ if (transferHash) {
+ SWIFT_LOG(debug) << "Recevied hash information." << std::endl;
+ if (transferHash->getHashes().find("sha-1") != transferHash->getHashes().end()) {
+ algo = "sha-1";
+ hash = transferHash->getHashes().at("sha-1");
+ }
+ else if (transferHash->getHashes().find("md5") != transferHash->getHashes().end()) {
+ algo = "md5";
+ hash = transferHash->getHashes().at("md5");
+ }
+ checkIfAllDataReceived();
+ }
+}
+
+void IncomingJingleFileTransfer::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) {
+ SWIFT_LOG(debug) << "session terminate received" << std::endl;
+ if (activeTransport) activeTransport->stop();
+ if (reason && reason.get().type == JinglePayload::Reason::Cancel) {
+ onStateChange(FileTransfer::State(FileTransfer::State::Canceled, "Other user canceled the transfer."));
+ }
+ else if (reason && reason.get().type == JinglePayload::Reason::Success) {
+ /*if (verifyReceviedData()) {
+ onStateChange(FileTransfer::State(FileTransfer::State::Finished));
+ } else {
+ onStateChange(FileTransfer::State(FileTransfer::State::Failed, "Verification failed."));
+ }*/
+ }
state = Terminated;
}
+void IncomingJingleFileTransfer::checkIfAllDataReceived() {
+ if (receivedBytes == fileSizeInBytes) {
+ SWIFT_LOG(debug) << "All data received." << std::endl;
+ if (hash.empty()) {
+ SWIFT_LOG(debug) << "No hash information yet. Waiting 5 seconds on hash info." << std::endl;
+ waitOnHashTimer->start();
+ } else {
+ SWIFT_LOG(debug) << "We already have hash info using " << algo << " algorithm. Finishing off transfer." << std::endl;
+ finishOffTransfer();
+ }
+ }
+ else if (receivedBytes > fileSizeInBytes) {
+ SWIFT_LOG(debug) << "We got more than we could handle!" << std::endl;
+ }
+}
+
void IncomingJingleFileTransfer::handleTransportDataReceived(const std::vector<unsigned char>& data) {
+ SWIFT_LOG(debug) << data.size() << " bytes received" << std::endl;
+ onProcessedBytes(data.size());
stream->write(data);
+ receivedBytes += data.size();
+ checkIfAllDataReceived();
+}
+
+void IncomingJingleFileTransfer::handleWriteStreamDataReceived(const std::vector<unsigned char>& data) {
+ receivedBytes += data.size();
+ checkIfAllDataReceived();
+}
+
+void IncomingJingleFileTransfer::useOurCandidateChoiceForTransfer(JingleS5BTransportPayload::Candidate candidate) {
+ SWIFT_LOG(debug) << std::endl;
+ if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ // get proxy client session from remoteCandidateSelector
+ clientSession = candidateSelector->getS5BSession();
+
+ // wait on <activated/> transport-info
+ } else {
+ // ask s5b client
+ clientSession = candidateSelector->getS5BSession();
+ if (clientSession) {
+ state = Transferring;
+ SWIFT_LOG(debug) << clientSession->getAddressPort().toString() << std::endl;
+ clientSession->onBytesReceived.connect(boost::bind(boost::ref(onProcessedBytes), _1));
+ clientSession->onFinished.connect(boost::bind(&IncomingJingleFileTransfer::handleTransferFinished, this, _1));
+ clientSession->startReceiving(stream);
+ } else {
+ SWIFT_LOG(debug) << "No S5B client session found!!!" << std::endl;
+ }
+ }
}
+void IncomingJingleFileTransfer::useTheirCandidateChoiceForTransfer(JingleS5BTransportPayload::Candidate candidate) {
+ SWIFT_LOG(debug) << std::endl;
+
+ if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ // get proxy client session from s5bRegistry
+ clientSession = s5bProxy->createSOCKS5BytestreamClientSession(candidate.hostPort, SOCKS5BytestreamRegistry::getHostname(s5bSessionID, ourJID, session->getInitiator()));
+ clientSession->onSessionReady.connect(boost::bind(&IncomingJingleFileTransfer::proxySessionReady, this, candidate.jid, _1));
+ clientSession->start();
+
+ // on reply send activate
+ } else {
+ // ask s5b server
+ serverSession = s5bRegistry->getConnectedSession(s5bDestination);
+ if (serverSession) {
+ state = Transferring;
+ serverSession->onBytesReceived.connect(boost::bind(boost::ref(onProcessedBytes), _1));
+ serverSession->onFinished.connect(boost::bind(&IncomingJingleFileTransfer::handleTransferFinished, this, _1));
+ serverSession->startTransfer();
+ } else {
+ SWIFT_LOG(debug) << "No S5B server session found!!!" << std::endl;
+ }
+ }
+}
+
+void IncomingJingleFileTransfer::fillCandidateMap(CandidateMap& map, JingleS5BTransportPayload::ref s5bPayload) {
+ map.clear();
+ foreach (JingleS5BTransportPayload::Candidate candidate, s5bPayload->getCandidates()) {
+ map[candidate.cid] = candidate;
+ }
+}
+
+
+void IncomingJingleFileTransfer::decideOnUsedTransport() {
+ if (ourCandidate && theirCandidate) {
+ if (ourCandidate->hasCandidateError() && theirCandidate->hasCandidateError()) {
+ state = WaitingForFallbackOrTerminate;
+ return;
+ }
+ std::string our_cid = ourCandidate->getCandidateUsed();
+ std::string their_cid = theirCandidate->getCandidateUsed();
+ if (ourCandidate->hasCandidateError() && !their_cid.empty()) {
+ useTheirCandidateChoiceForTransfer(ourCandidates[their_cid]);
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+ }
+ else if (theirCandidate->hasCandidateError() && !our_cid.empty()) {
+ useOurCandidateChoiceForTransfer(theirCandidates[our_cid]);
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+ }
+ else if (!our_cid.empty() && !their_cid.empty()) {
+ // compare priorites, if same they win
+ if (ourCandidates.find(their_cid) == ourCandidates.end() || theirCandidates.find(our_cid) == theirCandidates.end()) {
+ SWIFT_LOG(debug) << "Didn't recognize candidate IDs!" << std::endl;
+ session->sendTerminate(JinglePayload::Reason::FailedTransport);
+ onStateChange(FileTransfer::State(FileTransfer::State::Canceled, "Failed to negotiate candidate."));
+ onFinished(FileTransferError(FileTransferError::PeerError));
+ return;
+ }
+
+ JingleS5BTransportPayload::Candidate our_candidate = theirCandidates[our_cid];
+ JingleS5BTransportPayload::Candidate their_candidate = ourCandidates[their_cid];
+ if (our_candidate.priority > their_candidate.priority) {
+ useOurCandidateChoiceForTransfer(our_candidate);
+ }
+ else if (our_candidate.priority < their_candidate.priority) {
+ useTheirCandidateChoiceForTransfer(their_candidate);
+ }
+ else {
+ useTheirCandidateChoiceForTransfer(their_candidate);
+ }
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+ }
+ else {
+ assert(false);
+ }
+ } else {
+ SWIFT_LOG(debug) << "Can't make a transport decision yet." << std::endl;
+ }
+}
+
+void IncomingJingleFileTransfer::proxySessionReady(const JID& proxy, bool error) {
+ if (error) {
+ // indicate proxy error
+ } else {
+ // activate proxy
+ activateProxySession(proxy);
+ }
+}
+
+void IncomingJingleFileTransfer::activateProxySession(const JID &proxy) {
+ S5BProxyRequest::ref proxyRequest = boost::make_shared<S5BProxyRequest>();
+ proxyRequest->setSID(s5bSessionID);
+ proxyRequest->setActivate(session->getInitiator());
+
+ boost::shared_ptr<GenericRequest<S5BProxyRequest> > request = boost::make_shared<GenericRequest<S5BProxyRequest> >(IQ::Set, proxy, proxyRequest, router);
+ request->onResponse.connect(boost::bind(&IncomingJingleFileTransfer::handleActivateProxySessionResult, this, _1, _2));
+ request->send();
+}
+
+void IncomingJingleFileTransfer::handleActivateProxySessionResult(boost::shared_ptr<S5BProxyRequest> /*request*/, ErrorPayload::ref error) {
+ SWIFT_LOG(debug) << std::endl;
+ if (error) {
+ SWIFT_LOG(debug) << "ERROR" << std::endl;
+ } else {
+ // send activated to other jingle party
+ JingleS5BTransportPayload::ref proxyActivate = boost::make_shared<JingleS5BTransportPayload>();
+ proxyActivate->setActivated(theirCandidate->getCandidateUsed());
+ session->sendTransportInfo(getContentID(), proxyActivate);
+
+ // start transferring
+ clientSession->onBytesReceived.connect(boost::bind(boost::ref(onProcessedBytes), _1));
+ clientSession->onFinished.connect(boost::bind(&IncomingJingleFileTransfer::handleTransferFinished, this, _1));
+ clientSession->startReceiving(stream);
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+ }
+}
void IncomingJingleFileTransfer::handleTransportInfoReceived(const JingleContentID&, JingleTransportPayload::ref transport) {
- localTransportCandidateSelectFinished = true;
+ SWIFT_LOG(debug) << "transport info received" << std::endl;
+ if (state == Terminated) {
+ return;
+ }
+ if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport)) {
+ if (!s5bPayload->getActivated().empty()) {
+ if (ourCandidate->getCandidateUsed() == s5bPayload->getActivated()) {
+ clientSession->onBytesReceived.connect(boost::bind(boost::ref(onProcessedBytes), _1));
+ clientSession->onFinished.connect(boost::bind(&IncomingJingleFileTransfer::handleTransferFinished, this, _1));
+ clientSession->startReceiving(stream);
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+ } else {
+ SWIFT_LOG(debug) << "ourCandidateChoice doesn't match activated proxy candidate!" << std::endl;
+ JingleS5BTransportPayload::ref proxyError = boost::make_shared<JingleS5BTransportPayload>();
+ proxyError->setProxyError(true);
+ proxyError->setSessionID(s5bSessionID);
+ session->sendTransportInfo(getContentID(), proxyError);
+ }
+ } else {
+ theirCandidate = s5bPayload;
+ decideOnUsedTransport();
+ }
+ }
+ else {
+ SWIFT_LOG(debug) << "Expected something different here." << std::endl;
+ }
+ /*localTransportCandidateSelectFinished = true;
selectedLocalTransportCandidate = transport;
if (candidateGenerator->isActualCandidate(transport)) {
candidateSelector->setMinimumPriority(candidateGenerator->getPriority(transport));
- }
- checkCandidateSelected();
+ }*/
+ //checkCandidateSelected();
}
void IncomingJingleFileTransfer::handleTransportReplaceReceived(const JingleContentID& content, JingleTransportPayload::ref transport) {
+ if (state == Terminated) {
+ return;
+ }
if (JingleIBBTransportPayload::ref ibbTransport = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport)) {
+ SWIFT_LOG(debug) << "transport replaced with IBB" << std::endl;
setActiveTransport(createIBBTransport(ibbTransport));
- session->acceptTransport(content, transport);
- }
- else {
- session->rejectTransport(content, transport);
+ session->sendTransportAccept(content, ibbTransport);
+ } else {
+ SWIFT_LOG(debug) << "transport replaced failed" << std::endl;
+ session->sendTransportReject(content, transport);
}
}
@@ -163,7 +493,25 @@ void IncomingJingleFileTransfer::stopActiveTransport() {
}
JingleIncomingIBBTransport::ref IncomingJingleFileTransfer::createIBBTransport(JingleIBBTransportPayload::ref ibbTransport) {
- return boost::make_shared<JingleIncomingIBBTransport>(session->getInitiator(), ibbTransport->getSessionID(), description->getOffer()->size, router);
+ // TODO: getOffer() -> getOffers correction
+ return boost::make_shared<JingleIncomingIBBTransport>(session->getInitiator(), ibbTransport->getSessionID(), description->getOffers()[0].getSize(), router);
+}
+
+JingleContentID IncomingJingleFileTransfer::getContentID() const {
+ return JingleContentID(initialContent->getName(), initialContent->getCreator());
+}
+
+void IncomingJingleFileTransfer::handleTransferFinished(boost::optional<FileTransferError> error) {
+ if (state == Terminated) {
+ return;
+ }
+
+ if (error) {
+ session->sendTerminate(JinglePayload::Reason::ConnectivityError);
+ onStateChange(FileTransfer::State(FileTransfer::State::Failed));
+ onFinished(error);
+ }
+ //
}
}
diff --git a/Swiften/FileTransfer/IncomingJingleFileTransfer.h b/Swiften/FileTransfer/IncomingJingleFileTransfer.h
index 164d868..4ae0d1d 100644
--- a/Swiften/FileTransfer/IncomingJingleFileTransfer.h
+++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.h
@@ -8,14 +8,21 @@
#include <boost/shared_ptr.hpp>
+#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/Network/Timer.h>
#include <Swiften/Jingle/JingleSession.h>
#include <Swiften/Jingle/JingleContentID.h>
#include <Swiften/FileTransfer/IncomingFileTransfer.h>
#include <Swiften/FileTransfer/JingleTransport.h>
#include <Swiften/FileTransfer/JingleIncomingIBBTransport.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
#include <Swiften/Elements/JingleContentPayload.h>
#include <Swiften/Elements/JingleFileTransferDescription.h>
#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/Elements/S5BProxyRequest.h>
+#include <Swiften/Elements/ErrorPayload.h>
namespace Swift {
class IQRouter;
@@ -23,6 +30,9 @@ namespace Swift {
class LocalJingleTransportCandidateGeneratorFactory;
class RemoteJingleTransportCandidateSelector;
class LocalJingleTransportCandidateGenerator;
+ class SOCKS5BytestreamRegistry;
+ class SOCKS5BytestreamProxy;
+ class IncrementalBytestreamHashCalculator;
class IncomingJingleFileTransfer : public IncomingFileTransfer {
public:
@@ -37,42 +47,86 @@ namespace Swift {
};
IncomingJingleFileTransfer(
+ const JID& ourJID,
JingleSession::ref,
JingleContentPayload::ref content,
RemoteJingleTransportCandidateSelectorFactory*,
LocalJingleTransportCandidateGeneratorFactory*,
- IQRouter* router);
+ IQRouter* router,
+ SOCKS5BytestreamRegistry* bytestreamRegistry,
+ SOCKS5BytestreamProxy* bytestreamProxy,
+ TimerFactory*);
~IncomingJingleFileTransfer();
virtual void accept(WriteBytestream::ref);
+ virtual const JID& getSender() const;
+ void cancel();
private:
- void handleSessionTerminateReceived();
+ void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>);
+ void handleSessionInfoReceived(JinglePayload::ref);
void handleTransportReplaceReceived(const JingleContentID&, JingleTransportPayload::ref);
void handleTransportInfoReceived(const JingleContentID&, JingleTransportPayload::ref);
void handleLocalTransportCandidatesGenerated(JingleTransportPayload::ref candidates);
void handleRemoteTransportCandidateSelectFinished(JingleTransportPayload::ref candidate);
void setActiveTransport(JingleTransport::ref transport);
void handleTransportDataReceived(const std::vector<unsigned char>& data);
+ void handleWriteStreamDataReceived(const std::vector<unsigned char>& data);
void stopActiveTransport();
void checkCandidateSelected();
JingleIncomingIBBTransport::ref createIBBTransport(JingleIBBTransportPayload::ref ibbTransport);
+ JingleContentID getContentID() const;
+ void checkIfAllDataReceived();
+ bool verifyReceviedData();
+ void finishOffTransfer();
+ void handleTransferFinished(boost::optional<FileTransferError>);
private:
+ typedef std::map<std::string, JingleS5BTransportPayload::Candidate> CandidateMap;
+
+ private:
+ void activateProxySession(const JID &proxy);
+ void handleActivateProxySessionResult(boost::shared_ptr<S5BProxyRequest> request, ErrorPayload::ref error);
+ void proxySessionReady(const JID& proxy, bool error);
+
+ private:
+ void useOurCandidateChoiceForTransfer(JingleS5BTransportPayload::Candidate candidate);
+ void useTheirCandidateChoiceForTransfer(JingleS5BTransportPayload::Candidate candidate);
+ void decideOnUsedTransport();
+ void fillCandidateMap(CandidateMap& map, JingleS5BTransportPayload::ref s5bPayload);
+
+ private:
+ JID ourJID;
JingleSession::ref session;
IQRouter* router;
+ TimerFactory* timerFactory;
JingleContentPayload::ref initialContent;
- JingleContentID contentID;
State state;
JingleFileTransferDescription::ref description;
WriteBytestream::ref stream;
+ uintmax_t receivedBytes;
+ IncrementalBytestreamHashCalculator* hashCalculator;
+ Timer::ref waitOnHashTimer;
+ IDGenerator idGenerator;
+
RemoteJingleTransportCandidateSelector* candidateSelector;
LocalJingleTransportCandidateGenerator* candidateGenerator;
+ SOCKS5BytestreamRegistry* s5bRegistry;
+ SOCKS5BytestreamProxy* s5bProxy;
bool remoteTransportCandidateSelectFinished;
JingleTransportPayload::ref selectedRemoteTransportCandidate;
bool localTransportCandidateSelectFinished;
JingleTransportPayload::ref selectedLocalTransportCandidate;
+ JingleS5BTransportPayload::ref ourCandidate;
+ JingleS5BTransportPayload::ref theirCandidate;
+ CandidateMap ourCandidates;
+ CandidateMap theirCandidates;
+ SOCKS5BytestreamClientSession::ref clientSession;
+ std::string s5bDestination;
+ std::string s5bSessionID;
+ SOCKS5BytestreamServerSession* serverSession;
+
JingleTransport::ref activeTransport;
};
}
diff --git a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
new file mode 100644
index 0000000..6b53a1b
--- /dev/null
+++ b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h>
+
+#include <Swiften/StringCodecs/Hexify.h>
+#include <Swiften/StringCodecs/MD5.h>
+#include <Swiften/StringCodecs/SHA1.h>
+
+namespace Swift {
+
+IncrementalBytestreamHashCalculator::IncrementalBytestreamHashCalculator(bool doMD5, bool doSHA1) {
+ md5Hasher = doMD5 ? new MD5() : NULL;
+ sha1Hasher = doSHA1 ? new SHA1() : NULL;
+}
+
+IncrementalBytestreamHashCalculator::~IncrementalBytestreamHashCalculator() {
+ delete md5Hasher;
+ delete sha1Hasher;
+}
+
+void IncrementalBytestreamHashCalculator::feedData(const ByteArray& data) {
+ if (md5Hasher) {
+ md5Hasher->update(data);
+ }
+ if (sha1Hasher) {
+ sha1Hasher->update(data);
+ }
+}
+/*
+void IncrementalBytestreamHashCalculator::feedData(const SafeByteArray& data) {
+ if (md5Hasher) {
+ md5Hasher->update(createByteArray(data.data(), data.size()));
+ }
+ if (sha1Hasher) {
+ sha1Hasher->update(createByteArray(data.data(), data.size()));
+ }
+}*/
+
+std::string IncrementalBytestreamHashCalculator::getSHA1String() {
+ if (sha1Hasher) {
+ ByteArray result = sha1Hasher->getHash();
+ return Hexify::hexify(result);
+ } else {
+ return std::string();
+ }
+}
+
+std::string IncrementalBytestreamHashCalculator::getMD5String() {
+ if (md5Hasher) {
+ ByteArray result = md5Hasher->getHash();
+ return Hexify::hexify(result);
+ } else {
+ return std::string();
+ }
+}
+
+}
diff --git a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h
new file mode 100644
index 0000000..64f4b5f
--- /dev/null
+++ b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/SafeByteArray.h>
+
+namespace Swift {
+
+class MD5;
+class SHA1;
+
+class IncrementalBytestreamHashCalculator {
+public:
+ IncrementalBytestreamHashCalculator(bool doMD5, bool doSHA1);
+ ~IncrementalBytestreamHashCalculator();
+
+ void feedData(const ByteArray& data);
+ //void feedData(const SafeByteArray& data);
+
+ std::string getSHA1String();
+ std::string getMD5String();
+
+private:
+ MD5* md5Hasher;
+ SHA1* sha1Hasher;
+};
+
+}
diff --git a/Swiften/FileTransfer/JingleIncomingIBBTransport.cpp b/Swiften/FileTransfer/JingleIncomingIBBTransport.cpp
index 0ca899f..9b5c354 100644
--- a/Swiften/FileTransfer/JingleIncomingIBBTransport.cpp
+++ b/Swiften/FileTransfer/JingleIncomingIBBTransport.cpp
@@ -8,8 +8,9 @@
namespace Swift {
-JingleIncomingIBBTransport::JingleIncomingIBBTransport(const JID& from, const std::string& id, size_t size, IQRouter* router) : ibbSession(from, id, size, router) {
+JingleIncomingIBBTransport::JingleIncomingIBBTransport(const JID& from, const std::string& id, size_t size, IQRouter* router) : ibbSession(id, from, size, router) {
ibbSession.onDataReceived.connect(boost::ref(onDataReceived));
+ ibbSession.onFinished.connect(boost::ref(onFinished));
}
void JingleIncomingIBBTransport::start() {
diff --git a/Swiften/FileTransfer/JingleTransport.h b/Swiften/FileTransfer/JingleTransport.h
index 1d163d0..fa296e8 100644
--- a/Swiften/FileTransfer/JingleTransport.h
+++ b/Swiften/FileTransfer/JingleTransport.h
@@ -9,6 +9,7 @@
#include <boost/shared_ptr.hpp>
#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/FileTransfer/FileTransfer.h>
namespace Swift {
class JingleTransport {
@@ -21,5 +22,6 @@ namespace Swift {
virtual void stop() = 0;
boost::signal<void (const std::vector<unsigned char>&)> onDataReceived;
+ boost::signal<void (boost::optional<FileTransferError>)> onFinished;
};
}
diff --git a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h
index c111005..041afe3 100644
--- a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h
+++ b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h
@@ -15,8 +15,10 @@ namespace Swift {
class LocalJingleTransportCandidateGenerator {
public:
virtual ~LocalJingleTransportCandidateGenerator();
-
- virtual void generateLocalTransportCandidates() = 0;
+ /**
+ * Should call onLocalTransportCandidatesGenerated if it has finished discovering local candidates.
+ */
+ virtual void generateLocalTransportCandidates(JingleTransportPayload::ref) = 0;
virtual bool isActualCandidate(JingleTransportPayload::ref) = 0;
virtual int getPriority(JingleTransportPayload::ref) = 0;
diff --git a/Swiften/FileTransfer/OutgoingFileTransfer.h b/Swiften/FileTransfer/OutgoingFileTransfer.h
index a8c1e81..1ec1ae3 100644
--- a/Swiften/FileTransfer/OutgoingFileTransfer.h
+++ b/Swiften/FileTransfer/OutgoingFileTransfer.h
@@ -6,8 +6,14 @@
#pragma once
+#include <boost/shared_ptr.hpp>
+
+#include <Swiften/FileTransfer/FileTransfer.h>
+
namespace Swift {
- class OutgoingFileTransfer {
+ class OutgoingFileTransfer : public FileTransfer {
+ public:
+ typedef boost::shared_ptr<OutgoingFileTransfer> ref;
public:
virtual ~OutgoingFileTransfer();
diff --git a/Swiften/FileTransfer/OutgoingFileTransferManager.cpp b/Swiften/FileTransfer/OutgoingFileTransferManager.cpp
new file mode 100644
index 0000000..321a57a
--- /dev/null
+++ b/Swiften/FileTransfer/OutgoingFileTransferManager.cpp
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "OutgoingFileTransferManager.h"
+
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/JID/JID.h>
+#include <Swiften/Jingle/JingleSessionManager.h>
+#include <Swiften/Jingle/JingleSessionImpl.h>
+#include <Swiften/Jingle/JingleContentID.h>
+#include <Swiften/FileTransfer/OutgoingJingleFileTransfer.h>
+#include <Swiften/Base/IDGenerator.h>
+
+namespace Swift {
+
+OutgoingFileTransferManager::OutgoingFileTransferManager(const JID& ownFullJID, JingleSessionManager* jingleSessionManager, IQRouter* router, EntityCapsProvider* capsProvider, RemoteJingleTransportCandidateSelectorFactory* remoteFactory, LocalJingleTransportCandidateGeneratorFactory* localFactory, SOCKS5BytestreamRegistry* bytestreamRegistry, SOCKS5BytestreamProxy* bytestreamProxy) : ownJID(ownFullJID), jsManager(jingleSessionManager), iqRouter(router), capsProvider(capsProvider), remoteFactory(remoteFactory), localFactory(localFactory), bytestreamRegistry(bytestreamRegistry), bytestreamProxy(bytestreamProxy) {
+ idGenerator = new IDGenerator();
+}
+
+OutgoingFileTransferManager::~OutgoingFileTransferManager() {
+ delete idGenerator;
+}
+
+boost::shared_ptr<OutgoingFileTransfer> OutgoingFileTransferManager::createOutgoingFileTransfer(const JID& receipient, boost::shared_ptr<ReadBytestream> readBytestream, const StreamInitiationFileInfo& fileInfo) {
+ // check if receipient support Jingle FT
+
+
+ JingleSessionImpl::ref jingleSession = boost::make_shared<JingleSessionImpl>(ownJID, receipient, idGenerator->generateID(), iqRouter);
+
+ //jsManager->getSession(receipient, idGenerator->generateID());
+ assert(jingleSession);
+ jsManager->registerOutgoingSession(ownJID, jingleSession);
+ boost::shared_ptr<OutgoingJingleFileTransfer> jingleFT = boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer(jingleSession, remoteFactory, localFactory, iqRouter, idGenerator, receipient, readBytestream, fileInfo, bytestreamRegistry, bytestreamProxy));
+
+ // otherwise try SI
+
+ // else fail
+
+ return jingleFT;
+}
+
+}
diff --git a/Swiften/FileTransfer/OutgoingFileTransferManager.h b/Swiften/FileTransfer/OutgoingFileTransferManager.h
new file mode 100644
index 0000000..d57c14d
--- /dev/null
+++ b/Swiften/FileTransfer/OutgoingFileTransferManager.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <boost/shared_ptr.hpp>
+
+#include <Swiften/JID/JID.h>
+
+namespace Swift {
+
+class JingleSessionManager;
+class IQRouter;
+class EntityCapsProvider;
+class RemoteJingleTransportCandidateSelectorFactory;
+class LocalJingleTransportCandidateGeneratorFactory;
+class OutgoingFileTransfer;
+class JID;
+class IDGenerator;
+class ReadBytestream;
+class StreamInitiationFileInfo;
+class SOCKS5BytestreamRegistry;
+class SOCKS5BytestreamProxy;
+
+class OutgoingFileTransferManager {
+public:
+ OutgoingFileTransferManager(const JID& ownFullJID, JingleSessionManager* jingleSessionManager, IQRouter* router, EntityCapsProvider* capsProvider, RemoteJingleTransportCandidateSelectorFactory* remoteFactory, LocalJingleTransportCandidateGeneratorFactory* localFactory, SOCKS5BytestreamRegistry* bytestreamRegistry, SOCKS5BytestreamProxy* bytestreamProxy);
+ ~OutgoingFileTransferManager();
+
+ boost::shared_ptr<OutgoingFileTransfer> createOutgoingFileTransfer(const JID&, boost::shared_ptr<ReadBytestream>, const StreamInitiationFileInfo&);
+
+private:
+ JID ownJID;
+ JingleSessionManager* jsManager;
+ IQRouter* iqRouter;
+ EntityCapsProvider* capsProvider;
+ RemoteJingleTransportCandidateSelectorFactory* remoteFactory;
+ LocalJingleTransportCandidateGeneratorFactory* localFactory;
+ IDGenerator *idGenerator;
+ SOCKS5BytestreamRegistry* bytestreamRegistry;
+ SOCKS5BytestreamProxy* bytestreamProxy;
+};
+
+}
diff --git a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
new file mode 100644
index 0000000..9b71165
--- /dev/null
+++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
@@ -0,0 +1,401 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "OutgoingJingleFileTransfer.h"
+
+#include <boost/bind.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/Jingle/JingleContentID.h>
+#include <Swiften/Elements/JingleFileTransferDescription.h>
+#include <Swiften/Elements/JingleFileTransferHash.h>
+#include <Swiften/Elements/JingleTransportPayload.h>
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/Queries/GenericRequest.h>
+#include <Swiften/FileTransfer/IBBSendSession.h>
+#include <Swiften/FileTransfer/IncrementalBytestreamHashCalculator.h>
+#include <Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h>
+#include <Swiften/FileTransfer/LocalJingleTransportCandidateGeneratorFactory.h>
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelectorFactory.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamProxy.h>
+#include <Swiften/StringCodecs/Hexify.h>
+#include <Swiften/StringCodecs/SHA1.h>
+
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+
+OutgoingJingleFileTransfer::OutgoingJingleFileTransfer(JingleSession::ref session,
+ RemoteJingleTransportCandidateSelectorFactory* remoteFactory,
+ LocalJingleTransportCandidateGeneratorFactory* localFactory,
+ IQRouter* router,
+ IDGenerator *idGenerator,
+ const JID& toJID,
+ boost::shared_ptr<ReadBytestream> readStream,
+ const StreamInitiationFileInfo &fileInfo,
+ SOCKS5BytestreamRegistry* bytestreamRegistry,
+ SOCKS5BytestreamProxy* bytestreamProxy) :
+ session(session), remoteFactory(remoteFactory), localFactory(localFactory), router(router), idGenerator(idGenerator), toJID(toJID), readStream(readStream), fileInfo(fileInfo), s5bRegistry(bytestreamRegistry), s5bProxy(bytestreamProxy), serverSession(NULL), contentID(JingleContentID(idGenerator->generateID(), JingleContentPayload::InitiatorCreator)), canceled(false) {
+ session->onSessionAcceptReceived.connect(boost::bind(&OutgoingJingleFileTransfer::handleSessionAcceptReceived, this, _1, _2, _3));
+ session->onSessionTerminateReceived.connect(boost::bind(&OutgoingJingleFileTransfer::handleSessionTerminateReceived, this, _1));
+ session->onTransportInfoReceived.connect(boost::bind(&OutgoingJingleFileTransfer::handleTransportInfoReceived, this, _1, _2));
+ session->onTransportAcceptReceived.connect(boost::bind(&OutgoingJingleFileTransfer::handleTransportAcceptReceived, this, _1, _2));
+ fileSizeInBytes = fileInfo.getSize();
+ filename = fileInfo.getName();
+
+ localCandidateGenerator = localFactory->createCandidateGenerator();
+ localCandidateGenerator->onLocalTransportCandidatesGenerated.connect(boost::bind(&OutgoingJingleFileTransfer::handleLocalTransportCandidatesGenerated, this, _1));
+
+ remoteCandidateSelector = remoteFactory->createCandidateSelector();
+ remoteCandidateSelector->onRemoteTransportCandidateSelectFinished.connect(boost::bind(&OutgoingJingleFileTransfer::handleRemoteTransportCandidateSelectFinished, this, _1));
+ // calculate both, MD5 and SHA-1 since we don't know which one the other side supports
+ hashCalculator = new IncrementalBytestreamHashCalculator(true, true);
+ this->readStream->onRead.connect(boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1));
+}
+
+OutgoingJingleFileTransfer::~OutgoingJingleFileTransfer() {
+ readStream->onRead.disconnect(boost::bind(&IncrementalBytestreamHashCalculator::feedData, hashCalculator, _1));
+ delete hashCalculator;
+}
+
+void OutgoingJingleFileTransfer::start() {
+ onStateChange(FileTransfer::State(FileTransfer::State::WaitingForStart));
+
+ s5bSessionID = s5bRegistry->generateSessionID();
+ SWIFT_LOG(debug) << "S5B SessionID: " << s5bSessionID << std::endl;
+
+ //s5bProxy->connectToProxies(s5bSessionID);
+
+ JingleS5BTransportPayload::ref transport = boost::make_shared<JingleS5BTransportPayload>();
+ localCandidateGenerator->generateLocalTransportCandidates(transport);
+}
+
+void OutgoingJingleFileTransfer::stop() {
+
+}
+
+void OutgoingJingleFileTransfer::cancel() {
+ canceled = true;
+ session->sendTerminate(JinglePayload::Reason::Cancel);
+
+ if (ibbSession) {
+ ibbSession->stop();
+ }
+ SOCKS5BytestreamServerSession *serverSession = s5bRegistry->getConnectedSession(SOCKS5BytestreamRegistry::getHostname(s5bSessionID, session->getInitiator(), toJID));
+ if (serverSession) {
+ serverSession->stop();
+ }
+ if (clientSession) {
+ clientSession->stop();
+ }
+ onStateChange(FileTransfer::State(FileTransfer::State::Canceled));
+}
+
+void OutgoingJingleFileTransfer::handleSessionAcceptReceived(const JingleContentID& id, JingleDescription::ref /* decription */, JingleTransportPayload::ref transportPayload) {
+ if (canceled) {
+ return;
+ }
+ onStateChange(FileTransfer::State(FileTransfer::State::Negotiating));
+
+ JingleIBBTransportPayload::ref ibbPayload;
+ JingleS5BTransportPayload::ref s5bPayload;
+ if ((ibbPayload = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transportPayload))) {
+ ibbSession = boost::make_shared<IBBSendSession>(ibbPayload->getSessionID(), toJID, readStream, router);
+ ibbSession->setBlockSize(ibbPayload->getBlockSize());
+ ibbSession->onBytesSent.connect(boost::bind(boost::ref(onProcessedBytes), _1));
+ ibbSession->onFinished.connect(boost::bind(&OutgoingJingleFileTransfer::handleTransferFinished, this, _1));
+ ibbSession->start();
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+ }
+ else if ((s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transportPayload))) {
+ fillCandidateMap(theirCandidates, s5bPayload);
+ remoteCandidateSelector->setRequesterTargtet(toJID, session->getInitiator());
+ remoteCandidateSelector->addRemoteTransportCandidates(s5bPayload);
+ remoteCandidateSelector->selectCandidate();
+ }
+ else {
+ // TODO: error handling
+ SWIFT_LOG(debug) << "Unknown transport payload! Try replaceing with IBB." << std::endl;
+ replaceTransportWithIBB(id);
+ }
+}
+
+void OutgoingJingleFileTransfer::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) {
+ if (canceled) {
+ return;
+ }
+
+ if (ibbSession) {
+ ibbSession->stop();
+ }
+ if (clientSession) {
+ clientSession->stop();
+ }
+ if (serverSession) {
+ serverSession->stop();
+ }
+
+ if (reason.is_initialized() && reason.get().type == JinglePayload::Reason::Cancel) {
+ onStateChange(FileTransfer::State(FileTransfer::State::Canceled));
+ onFinished(FileTransferError(FileTransferError::PeerError));
+ } else if (reason.is_initialized() && reason.get().type == JinglePayload::Reason::Success) {
+ onStateChange(FileTransfer::State(FileTransfer::State::Finished));
+ onFinished(boost::optional<FileTransferError>());
+ } else {
+ onStateChange(FileTransfer::State(FileTransfer::State::Failed));
+ onFinished(FileTransferError(FileTransferError::PeerError));
+ }
+ canceled = true;
+}
+
+void OutgoingJingleFileTransfer::handleTransportAcceptReceived(const JingleContentID& /* contentID */, JingleTransportPayload::ref transport) {
+ if (canceled) {
+ return;
+ }
+
+ if (JingleIBBTransportPayload::ref ibbPayload = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport)) {
+ ibbSession = boost::make_shared<IBBSendSession>(ibbPayload->getSessionID(), toJID, readStream, router);
+ ibbSession->setBlockSize(ibbPayload->getBlockSize());
+ ibbSession->onBytesSent.connect(boost::bind(boost::ref(onProcessedBytes), _1));
+ ibbSession->onFinished.connect(boost::bind(&OutgoingJingleFileTransfer::handleTransferFinished, this, _1));
+ ibbSession->start();
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+ } else {
+ // error handling
+ SWIFT_LOG(debug) << "Replacing with anything other than IBB isn't supported yet." << std::endl;
+ session->sendTerminate(JinglePayload::Reason::FailedTransport);
+ onStateChange(FileTransfer::State(FileTransfer::State::Failed));
+ }
+}
+
+void OutgoingJingleFileTransfer::startTransferViaOurCandidateChoice(JingleS5BTransportPayload::Candidate candidate) {
+ SWIFT_LOG(debug) << "Transferring data using our candidate." << std::endl;
+ if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ // get proxy client session from remoteCandidateSelector
+ clientSession = remoteCandidateSelector->getS5BSession();
+
+ // wait on <activated/> transport-info
+ } else {
+ clientSession = remoteCandidateSelector->getS5BSession();
+ clientSession->onBytesSent.connect(boost::bind(boost::ref(onProcessedBytes), _1));
+ clientSession->onFinished.connect(boost::bind(&OutgoingJingleFileTransfer::handleTransferFinished, this, _1));
+ clientSession->startSending(readStream);
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+ }
+ assert(clientSession);
+}
+
+void OutgoingJingleFileTransfer::startTransferViaTheirCandidateChoice(JingleS5BTransportPayload::Candidate candidate) {
+ SWIFT_LOG(debug) << "Transferring data using their candidate." << std::endl;
+ if (candidate.type == JingleS5BTransportPayload::Candidate::ProxyType) {
+ // connect to proxy
+ clientSession = s5bProxy->createSOCKS5BytestreamClientSession(candidate.hostPort, SOCKS5BytestreamRegistry::getHostname(s5bSessionID, session->getInitiator(), toJID));
+ clientSession->onSessionReady.connect(boost::bind(&OutgoingJingleFileTransfer::proxySessionReady, this, candidate.jid, _1));
+ clientSession->start();
+
+ // on reply send activate
+
+ } else {
+ serverSession = s5bRegistry->getConnectedSession(SOCKS5BytestreamRegistry::getHostname(s5bSessionID, session->getInitiator(), toJID));
+ serverSession->onBytesSent.connect(boost::bind(boost::ref(onProcessedBytes), _1));
+ serverSession->onFinished.connect(boost::bind(&OutgoingJingleFileTransfer::handleTransferFinished, this, _1));
+ serverSession->startTransfer();
+ }
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+}
+
+// decide on candidates according to http://xmpp.org/extensions/xep-0260.html#complete
+void OutgoingJingleFileTransfer::decideOnCandidates() {
+ if (ourCandidateChoice && theirCandidateChoice) {
+ std::string our_cid = ourCandidateChoice->getCandidateUsed();
+ std::string their_cid = theirCandidateChoice->getCandidateUsed();
+ if (ourCandidateChoice->hasCandidateError() && theirCandidateChoice->hasCandidateError()) {
+ replaceTransportWithIBB(contentID);
+ }
+ else if (!our_cid.empty() && theirCandidateChoice->hasCandidateError()) {
+ // use our candidate
+ startTransferViaOurCandidateChoice(theirCandidates[our_cid]);
+ }
+ else if (!their_cid.empty() && ourCandidateChoice->hasCandidateError()) {
+ // use their candidate
+ startTransferViaTheirCandidateChoice(ourCandidates[their_cid]);
+ }
+ else if (!our_cid.empty() && !their_cid.empty()) {
+ // compare priorites, if same we win
+ if (ourCandidates.find(their_cid) == ourCandidates.end() || theirCandidates.find(our_cid) == theirCandidates.end()) {
+ SWIFT_LOG(debug) << "Didn't recognize candidate IDs!" << std::endl;
+ session->sendTerminate(JinglePayload::Reason::FailedTransport);
+ onStateChange(FileTransfer::State(FileTransfer::State::Failed));
+ onFinished(FileTransferError(FileTransferError::PeerError));
+ return;
+ }
+
+ JingleS5BTransportPayload::Candidate ourCandidate = theirCandidates[our_cid];
+ JingleS5BTransportPayload::Candidate theirCandidate = ourCandidates[their_cid];
+ if (ourCandidate.priority > theirCandidate.priority) {
+ startTransferViaOurCandidateChoice(ourCandidate);
+ }
+ else if (ourCandidate.priority < theirCandidate.priority) {
+ startTransferViaTheirCandidateChoice(theirCandidate);
+ }
+ else {
+ startTransferViaOurCandidateChoice(ourCandidate);
+ }
+ }
+ } else {
+ SWIFT_LOG(debug) << "Can't make a decision yet!" << std::endl;
+ }
+}
+
+void OutgoingJingleFileTransfer::fillCandidateMap(CandidateMap& map, JingleS5BTransportPayload::ref s5bPayload) {
+ map.clear();
+ foreach (JingleS5BTransportPayload::Candidate candidate, s5bPayload->getCandidates()) {
+ map[candidate.cid] = candidate;
+ }
+}
+
+void OutgoingJingleFileTransfer::proxySessionReady(const JID& proxy, bool error) {
+ if (error) {
+ // indicate proxy error
+ } else {
+ // activate proxy
+ activateProxySession(proxy);
+ }
+}
+
+void OutgoingJingleFileTransfer::activateProxySession(const JID& proxy) {
+ S5BProxyRequest::ref proxyRequest = boost::make_shared<S5BProxyRequest>();
+ proxyRequest->setSID(s5bSessionID);
+ proxyRequest->setActivate(toJID);
+
+ boost::shared_ptr<GenericRequest<S5BProxyRequest> > request = boost::make_shared<GenericRequest<S5BProxyRequest> >(IQ::Set, proxy, proxyRequest, router);
+ request->onResponse.connect(boost::bind(&OutgoingJingleFileTransfer::handleActivateProxySessionResult, this, _1, _2));
+ request->send();
+}
+
+void OutgoingJingleFileTransfer::handleActivateProxySessionResult(boost::shared_ptr<S5BProxyRequest> /*request*/, ErrorPayload::ref error) {
+ if (error) {
+ SWIFT_LOG(debug) << "ERROR" << std::endl;
+ } else {
+ // send activated to other jingle party
+ JingleS5BTransportPayload::ref proxyActivate = boost::make_shared<JingleS5BTransportPayload>();
+ proxyActivate->setActivated(theirCandidateChoice->getCandidateUsed());
+ session->sendTransportInfo(contentID, proxyActivate);
+
+ // start transferring
+ clientSession->onBytesSent.connect(boost::bind(boost::ref(onProcessedBytes), _1));
+ clientSession->onFinished.connect(boost::bind(&OutgoingJingleFileTransfer::handleTransferFinished, this, _1));
+ clientSession->startSending(readStream);
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+ }
+}
+
+void OutgoingJingleFileTransfer::sendSessionInfoHash() {
+ SWIFT_LOG(debug) << std::endl;
+ JingleFileTransferHash::ref hashElement = boost::make_shared<JingleFileTransferHash>();
+ hashElement->setHash("sha-1", hashCalculator->getSHA1String());
+ hashElement->setHash("md5", hashCalculator->getMD5String());
+ session->sendInfo(hashElement);
+}
+
+void OutgoingJingleFileTransfer::handleTransportInfoReceived(const JingleContentID& /* contentID */, JingleTransportPayload::ref transport) {
+ if (canceled) {
+ return;
+ }
+ if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport)) {
+ if (s5bPayload->hasCandidateError() || !s5bPayload->getCandidateUsed().empty()) {
+ theirCandidateChoice = s5bPayload;
+ decideOnCandidates();
+ } else if(!s5bPayload->getActivated().empty()) {
+ if (ourCandidateChoice->getCandidateUsed() == s5bPayload->getActivated()) {
+ clientSession->onBytesSent.connect(boost::bind(boost::ref(onProcessedBytes), _1));
+ clientSession->onFinished.connect(boost::bind(&OutgoingJingleFileTransfer::handleTransferFinished, this, _1));
+ clientSession->startSending(readStream);
+ onStateChange(FileTransfer::State(FileTransfer::State::Transferring));
+ } else {
+ SWIFT_LOG(debug) << "ourCandidateChoice doesn't match activated proxy candidate!" << std::endl;
+ JingleS5BTransportPayload::ref proxyError = boost::make_shared<JingleS5BTransportPayload>();
+ proxyError->setProxyError(true);
+ proxyError->setSessionID(s5bSessionID);
+ session->sendTransportInfo(contentID, proxyError);
+ }
+ }
+ }
+}
+
+void OutgoingJingleFileTransfer::handleLocalTransportCandidatesGenerated(JingleTransportPayload::ref payload) {
+ if (canceled) {
+ return;
+ }
+ JingleFileTransferDescription::ref description = boost::make_shared<JingleFileTransferDescription>();
+ description->addOffer(fileInfo);
+
+ JingleTransportPayload::ref transport;
+ if (JingleIBBTransportPayload::ref ibbTransport = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(payload)) {
+ ibbTransport->setBlockSize(4096);
+ ibbTransport->setSessionID(idGenerator->generateID());
+ transport = ibbTransport;
+ }
+ else if (JingleS5BTransportPayload::ref s5bTransport = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(payload)) {
+ //fillCandidateMap(ourCandidates, s5bTransport);
+ //s5bTransport->setSessionID(s5bSessionID);
+
+ JingleS5BTransportPayload::ref emptyCandidates = boost::make_shared<JingleS5BTransportPayload>();
+ emptyCandidates->setSessionID(s5bTransport->getSessionID());
+ fillCandidateMap(ourCandidates, emptyCandidates);
+
+ transport = emptyCandidates;
+ s5bRegistry->addReadBytestream(SOCKS5BytestreamRegistry::getHostname(s5bSessionID, session->getInitiator(), toJID), readStream);
+ }
+ else {
+ SWIFT_LOG(debug) << "Unknown tranport payload: " << typeid(*payload).name() << std::endl;
+ return;
+ }
+ session->sendInitiate(contentID, description, transport);
+ onStateChange(FileTransfer::State(FileTransfer::State::WaitingForAccept));
+}
+
+void OutgoingJingleFileTransfer::handleRemoteTransportCandidateSelectFinished(JingleTransportPayload::ref payload) {
+ if (canceled) {
+ return;
+ }
+ if (JingleS5BTransportPayload::ref s5bPayload = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(payload)) {
+ ourCandidateChoice = s5bPayload;
+ session->sendTransportInfo(contentID, s5bPayload);
+ decideOnCandidates();
+ }
+}
+
+void OutgoingJingleFileTransfer::replaceTransportWithIBB(const JingleContentID& id) {
+ SWIFT_LOG(debug) << "Both parties failed. Replace transport with IBB." << std::endl;
+ JingleIBBTransportPayload::ref ibbTransport = boost::make_shared<JingleIBBTransportPayload>();
+ ibbTransport->setBlockSize(4096);
+ ibbTransport->setSessionID(idGenerator->generateID());
+ session->sendTransportReplace(id, ibbTransport);
+}
+
+void OutgoingJingleFileTransfer::handleTransferFinished(boost::optional<FileTransferError> error) {
+ if (error) {
+ session->sendTerminate(JinglePayload::Reason::ConnectivityError);
+ onStateChange(FileTransfer::State(FileTransfer::State::Failed));
+ onFinished(error);
+ } else {
+ sendSessionInfoHash();
+ /*
+ session->terminate(JinglePayload::Reason::Success);
+ onStateChange(FileTransfer::State(FileTransfer::State::Finished));
+ */
+ }
+ //
+}
+
+}
diff --git a/Swiften/FileTransfer/OutgoingJingleFileTransfer.h b/Swiften/FileTransfer/OutgoingJingleFileTransfer.h
new file mode 100644
index 0000000..fecfbdb
--- /dev/null
+++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.h
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <boost/shared_ptr.hpp>
+
+#include <Swiften/Elements/JingleContentPayload.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/Elements/StreamInitiationFileInfo.h>
+#include <Swiften/Elements/S5BProxyRequest.h>
+#include <Swiften/Elements/ErrorPayload.h>
+#include <Swiften/FileTransfer/OutgoingFileTransfer.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
+#include <Swiften/Jingle/JingleContentID.h>
+#include <Swiften/Jingle/JingleSession.h>
+#include <Swiften/StringCodecs/SHA1.h>
+
+namespace Swift {
+
+class RemoteJingleTransportCandidateSelectorFactory;
+class RemoteJingleTransportCandidateSelector;
+class LocalJingleTransportCandidateGeneratorFactory;
+class LocalJingleTransportCandidateGenerator;
+class IQRouter;
+class ReadBytestream;
+class IBBSendSession;
+class IDGenerator;
+class IncrementalBytestreamHashCalculator;
+class SOCKS5BytestreamRegistry;
+class SOCKS5BytestreamProxy;
+
+class OutgoingJingleFileTransfer : public OutgoingFileTransfer {
+public:
+ OutgoingJingleFileTransfer(JingleSession::ref,
+ RemoteJingleTransportCandidateSelectorFactory*,
+ LocalJingleTransportCandidateGeneratorFactory*,
+ IQRouter*,
+ IDGenerator*,
+ const JID&,
+ boost::shared_ptr<ReadBytestream>,
+ const StreamInitiationFileInfo&,
+ SOCKS5BytestreamRegistry*,
+ SOCKS5BytestreamProxy*);
+ virtual ~OutgoingJingleFileTransfer();
+
+ void start();
+ void stop();
+
+ void cancel();
+
+private:
+ void handleSessionAcceptReceived(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref);
+ void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason);
+ void handleTransportAcceptReceived(const JingleContentID&, JingleTransportPayload::ref);
+ void handleTransportInfoReceived(const JingleContentID&, JingleTransportPayload::ref);
+
+ void handleLocalTransportCandidatesGenerated(JingleTransportPayload::ref);
+ void handleRemoteTransportCandidateSelectFinished(JingleTransportPayload::ref);
+
+private:
+ void replaceTransportWithIBB(const JingleContentID&);
+ void handleTransferFinished(boost::optional<FileTransferError>);
+ void activateProxySession(const JID &proxy);
+ void handleActivateProxySessionResult(boost::shared_ptr<S5BProxyRequest> request, ErrorPayload::ref error);
+ void proxySessionReady(const JID& proxy, bool error);
+
+private:
+ typedef std::map<std::string, JingleS5BTransportPayload::Candidate> CandidateMap;
+
+private:
+ void startTransferViaOurCandidateChoice(JingleS5BTransportPayload::Candidate);
+ void startTransferViaTheirCandidateChoice(JingleS5BTransportPayload::Candidate);
+ void decideOnCandidates();
+ void fillCandidateMap(CandidateMap& map, JingleS5BTransportPayload::ref s5bPayload);
+
+private:
+ void sendSessionInfoHash();
+
+private:
+ JingleSession::ref session;
+ RemoteJingleTransportCandidateSelector* remoteCandidateSelector;
+ RemoteJingleTransportCandidateSelectorFactory* remoteFactory;
+ LocalJingleTransportCandidateGenerator* localCandidateGenerator;
+ LocalJingleTransportCandidateGeneratorFactory* localFactory;
+
+ IQRouter* router;
+ IDGenerator* idGenerator;
+ JID toJID;
+ boost::shared_ptr<ReadBytestream> readStream;
+ StreamInitiationFileInfo fileInfo;
+ IncrementalBytestreamHashCalculator *hashCalculator;
+
+ boost::shared_ptr<IBBSendSession> ibbSession;
+
+ JingleS5BTransportPayload::ref ourCandidateChoice;
+ JingleS5BTransportPayload::ref theirCandidateChoice;
+ CandidateMap ourCandidates;
+ CandidateMap theirCandidates;
+
+ SOCKS5BytestreamRegistry* s5bRegistry;
+ SOCKS5BytestreamProxy* s5bProxy;
+ SOCKS5BytestreamClientSession::ref clientSession;
+ SOCKS5BytestreamServerSession* serverSession;
+ JingleContentID contentID;
+ std::string s5bSessionID;
+
+ bool canceled;
+};
+
+}
diff --git a/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp b/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp
index 85ac505..dfcf028 100644
--- a/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp
+++ b/Swiften/FileTransfer/OutgoingSIFileTransfer.cpp
@@ -38,7 +38,7 @@ void OutgoingSIFileTransfer::handleStreamInitiationRequestResponse(StreamInitiat
}
else {
if (response->getRequestedMethod() == "http://jabber.org/protocol/bytestreams") {
- socksServer->addBytestream(id, from, to, bytestream);
+ socksServer->addReadBytestream(id, from, to, bytestream);
Bytestreams::ref bytestreams(new Bytestreams());
bytestreams->setStreamID(id);
HostAddressPort addressPort = socksServer->getAddressPort();
@@ -67,7 +67,7 @@ void OutgoingSIFileTransfer::finish(boost::optional<FileTransferError> error) {
ibbSession->onFinished.disconnect(boost::bind(&OutgoingSIFileTransfer::handleIBBSessionFinished, this, _1));
ibbSession.reset();
}
- socksServer->removeBytestream(id, from, to);
+ socksServer->removeReadBytestream(id, from, to);
onFinished(error);
}
diff --git a/Swiften/FileTransfer/ReadBytestream.h b/Swiften/FileTransfer/ReadBytestream.h
index 2601192..9e070f7 100644
--- a/Swiften/FileTransfer/ReadBytestream.h
+++ b/Swiften/FileTransfer/ReadBytestream.h
@@ -9,11 +9,16 @@
#include <vector>
#include <cstring>
+#include <Swiften/Base/boost_bsignals.h>
+
namespace Swift {
class ReadBytestream {
public:
virtual ~ReadBytestream();
virtual std::vector<unsigned char> read(size_t size) = 0;
virtual bool isFinished() const = 0;
+
+ public:
+ boost::signal<void (std::vector<unsigned char>)> onRead;
};
}
diff --git a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h
index b12b06b..f8df8f9 100644
--- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h
+++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h
@@ -8,8 +8,10 @@
#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/JID/JID.h>
#include <Swiften/Elements/JingleTransportPayload.h>
#include <Swiften/FileTransfer/JingleTransport.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
namespace Swift {
class RemoteJingleTransportCandidateSelector {
@@ -19,6 +21,8 @@ namespace Swift {
virtual void addRemoteTransportCandidates(JingleTransportPayload::ref) = 0;
virtual void selectCandidate() = 0;
virtual void setMinimumPriority(int) = 0;
+ virtual void setRequesterTargtet(const JID&, const JID&) {}
+ virtual SOCKS5BytestreamClientSession::ref getS5BSession() { return SOCKS5BytestreamClientSession::ref(); }
virtual bool isActualCandidate(JingleTransportPayload::ref) = 0;
virtual int getPriority(JingleTransportPayload::ref) = 0;
diff --git a/Swiften/FileTransfer/SConscript b/Swiften/FileTransfer/SConscript
index 24fc9e8..ef02557 100644
--- a/Swiften/FileTransfer/SConscript
+++ b/Swiften/FileTransfer/SConscript
@@ -3,6 +3,9 @@ Import("swiften_env", "env")
sources = [
"OutgoingFileTransfer.cpp",
"OutgoingSIFileTransfer.cpp",
+ "OutgoingJingleFileTransfer.cpp",
+ "OutgoingFileTransferManager.cpp",
+ "OutgoingFileTransferManager.cpp",
"IncomingFileTransfer.cpp",
"IncomingJingleFileTransfer.cpp",
"IncomingFileTransferManager.cpp",
@@ -10,23 +13,36 @@ sources = [
"RemoteJingleTransportCandidateSelectorFactory.cpp",
"LocalJingleTransportCandidateGenerator.cpp",
"LocalJingleTransportCandidateGeneratorFactory.cpp",
+ "DefaultRemoteJingleTransportCandidateSelectorFactory.cpp",
+ "DefaultLocalJingleTransportCandidateGeneratorFactory.cpp",
+ "DefaultRemoteJingleTransportCandidateSelector.cpp",
+ "DefaultLocalJingleTransportCandidateGenerator.cpp",
"JingleTransport.cpp",
"JingleIncomingIBBTransport.cpp",
"ReadBytestream.cpp",
"WriteBytestream.cpp",
"FileReadBytestream.cpp",
"FileWriteBytestream.cpp",
+ "SOCKS5BytestreamClientSession.cpp",
"SOCKS5BytestreamServer.cpp",
"SOCKS5BytestreamServerSession.cpp",
"SOCKS5BytestreamRegistry.cpp",
+ "SOCKS5BytestreamProxy.cpp",
"IBBSendSession.cpp",
"IBBReceiveSession.cpp",
+ "FileTransferManager.cpp",
+ "FileTransferManagerImpl.cpp",
+ "IncrementalBytestreamHashCalculator.cpp",
+ "ConnectivityManager.cpp",
]
swiften_env.Append(SWIFTEN_OBJECTS = swiften_env.SwiftenObject(sources))
env.Append(UNITTEST_SOURCES = [
File("UnitTest/SOCKS5BytestreamServerSessionTest.cpp"),
+ File("UnitTest/SOCKS5BytestreamClientSessionTest.cpp"),
File("UnitTest/IBBSendSessionTest.cpp"),
File("UnitTest/IBBReceiveSessionTest.cpp"),
+ File("UnitTest/IncomingJingleFileTransferTest.cpp"),
+ File("UnitTest/OutgoingJingleFileTransferTest.cpp"),
])
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
new file mode 100644
index 0000000..f90b73b
--- /dev/null
+++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
@@ -0,0 +1,235 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "SOCKS5BytestreamClientSession.h"
+
+#include <boost/bind.hpp>
+
+#include <Swiften/Base/Algorithm.h>
+#include <Swiften/Base/SafeByteArray.h>
+#include <Swiften/Base/Concat.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/StringCodecs/SHA1.h>
+#include <Swiften/StringCodecs/Hexify.h>
+#include <Swiften/FileTransfer/BytestreamException.h>
+#include <Swiften/Network/TimerFactory.h>
+
+namespace Swift {
+
+SOCKS5BytestreamClientSession::SOCKS5BytestreamClientSession(boost::shared_ptr<Connection> connection, const HostAddressPort& addressPort, const std::string& destination, TimerFactory* timerFactory) :
+ connection(connection), addressPort(addressPort), destination(destination), state(Initial), chunkSize(131072) {
+ connection->onConnectFinished.connect(boost::bind(&SOCKS5BytestreamClientSession::handleConnectFinished, this, _1));
+ connection->onDisconnected.connect(boost::bind(&SOCKS5BytestreamClientSession::handleDisconnected, this, _1));
+ weFailedTimeout = timerFactory->createTimer(2000);
+ weFailedTimeout->onTick.connect(boost::bind(&SOCKS5BytestreamClientSession::handleWeFailedTimeout, this));
+}
+
+void SOCKS5BytestreamClientSession::start() {
+ assert(state == Initial);
+ SWIFT_LOG(debug) << "Trying to connect via TCP to " << addressPort.toString() << "." << std::endl;
+ weFailedTimeout->start();
+ connection->connect(addressPort);
+}
+
+void SOCKS5BytestreamClientSession::stop() {
+ connection->disconnect();
+ connection->onDataWritten.disconnect(boost::bind(&SOCKS5BytestreamClientSession::sendData, this));
+ connection->onDataRead.disconnect(boost::bind(&SOCKS5BytestreamClientSession::handleDataRead, this, _1));
+ readBytestream.reset();
+ state = Finished;
+}
+
+void SOCKS5BytestreamClientSession::process() {
+ SWIFT_LOG(debug) << "unprocessedData.size(): " << unprocessedData.size() << std::endl;
+ ByteArray bndAddress;
+ switch(state) {
+ case Initial:
+ hello();
+ break;
+ case Hello:
+ if (unprocessedData.size() > 1) {
+ unsigned char version = unprocessedData[0];
+ unsigned char authMethod = unprocessedData[1];
+ if (version != 5 || authMethod != 0) {
+ // signal failure to upper level
+ finish(true);
+ return;
+ }
+ unprocessedData.clear();
+ authenticate();
+ }
+ break;
+ case Authenticating:
+ if (unprocessedData.size() < 5) {
+ // need more data to start progressing
+ break;
+ }
+ if (unprocessedData[0] != '\x05') {
+ // wrong version
+ // disconnect & signal failure
+ finish(true);
+ break;
+ }
+ if (unprocessedData[1] != '\x00') {
+ // no success
+ // disconnect & signal failure
+ finish(true);
+ break;
+ }
+ if (unprocessedData[3] != '\x03') {
+ // we expect x'03' = DOMAINNAME here
+ // discconect & signal failure
+ finish(true);
+ break;
+ }
+ if (static_cast<size_t>(unprocessedData[4]) + 1 > unprocessedData.size() + 5) {
+ // complete domainname and port not available yet
+ break;
+ }
+ bndAddress = createByteArray(&(unprocessedData.data()[5]), unprocessedData[4]);
+ if (unprocessedData[unprocessedData[4] + 5] != 0 && bndAddress == createByteArray(destination)) {
+ // we expect a 0 as port
+ // disconnect and fail
+ finish(true);
+ }
+ unprocessedData.clear();
+ state = Ready;
+ SWIFT_LOG(debug) << "session ready" << std::endl;
+ // issue ready signal so the bytestream can be used for reading or writing
+ weFailedTimeout->stop();
+ onSessionReady(false);
+ break;
+ case Ready:
+ SWIFT_LOG(debug) << "Received further data in Ready state." << std::endl;
+ break;
+ case Reading:
+ case Writing:
+ case Finished:
+ SWIFT_LOG(debug) << "Unexpected receive of data. Current state: " << state << std::endl;
+ SWIFT_LOG(debug) << "Data: " << Hexify::hexify(unprocessedData) << std::endl;
+ unprocessedData.clear();
+ //assert(false);
+ }
+}
+
+void SOCKS5BytestreamClientSession::hello() {
+ // Version 5, 1 auth method, No authentication
+ const SafeByteArray hello = createSafeByteArray("\x05\x01\x00", 3);
+ connection->write(hello);
+ state = Hello;
+}
+
+void SOCKS5BytestreamClientSession::authenticate() {
+ SWIFT_LOG(debug) << std::endl;
+ SafeByteArray header = createSafeByteArray("\x05\x01\x00\x03", 4);
+ SafeByteArray message = header;
+ append(message, createSafeByteArray(destination.size()));
+ authenticateAddress = createByteArray(destination);
+ append(message, authenticateAddress);
+ append(message, createSafeByteArray("\x00\x00", 2)); // 2 byte for port
+ connection->write(message);
+ state = Authenticating;
+}
+
+void SOCKS5BytestreamClientSession::startReceiving(boost::shared_ptr<WriteBytestream> writeStream) {
+ if (state == Ready) {
+ state = Reading;
+ writeBytestream = writeStream;
+ writeBytestream->write(unprocessedData);
+ onBytesReceived(unprocessedData.size());
+ unprocessedData.clear();
+ } else {
+ SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl;
+ }
+}
+
+void SOCKS5BytestreamClientSession::startSending(boost::shared_ptr<ReadBytestream> readStream) {
+ if (state == Ready) {
+ state = Writing;
+ readBytestream = readStream;
+ connection->onDataWritten.connect(boost::bind(&SOCKS5BytestreamClientSession::sendData, this));
+ sendData();
+ } else {
+ SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl;
+ }
+}
+
+HostAddressPort SOCKS5BytestreamClientSession::getAddressPort() const {
+ return addressPort;
+}
+
+void SOCKS5BytestreamClientSession::sendData() {
+ if (!readBytestream->isFinished()) {
+ try {
+ SafeByteArray dataToSend = createSafeByteArray(readBytestream->read(chunkSize));
+ connection->write(dataToSend);
+ onBytesSent(dataToSend.size());
+ }
+ catch (const BytestreamException&) {
+ finish(true);
+ }
+ }
+ else {
+ finish(false);
+ }
+}
+
+void SOCKS5BytestreamClientSession::finish(bool error) {
+ weFailedTimeout->stop();
+ connection->disconnect();
+ connection->onDataWritten.disconnect(boost::bind(&SOCKS5BytestreamClientSession::sendData, this));
+ connection->onDataRead.disconnect(boost::bind(&SOCKS5BytestreamClientSession::handleDataRead, this, _1));
+ readBytestream.reset();
+ if (state == Initial || state == Hello || state == Authenticating) {
+ onSessionReady(true);
+ }
+ else {
+ state = Finished;
+ if (error) {
+ onFinished(boost::optional<FileTransferError>(FileTransferError::ReadError));
+ } else {
+ onFinished(boost::optional<FileTransferError>());
+ }
+ }
+}
+
+void SOCKS5BytestreamClientSession::handleConnectFinished(bool error) {
+ if (error) {
+ SWIFT_LOG(debug) << "Failed to connect via TCP to " << addressPort.toString() << "." << std::endl;
+ finish(true);
+ } else {
+ SWIFT_LOG(debug) << "Successfully connected via TCP" << addressPort.toString() << "." << std::endl;
+ weFailedTimeout->start();
+ connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSession::handleDataRead, this, _1));
+ process();
+ }
+}
+
+void SOCKS5BytestreamClientSession::handleDataRead(const SafeByteArray& data) {
+ SWIFT_LOG(debug) << "state: " << state << " data.size() = " << data.size() << std::endl;
+ if (state != Reading) {
+ append(unprocessedData, data);
+ process();
+ }
+ else {
+ writeBytestream->write(createByteArray(data.data(), data.size()));
+ onBytesReceived(data.size());
+ }
+}
+
+void SOCKS5BytestreamClientSession::handleDisconnected(const boost::optional<Connection::Error>& error) {
+ SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl;
+ if (error) {
+ finish(true);
+ }
+}
+
+void SOCKS5BytestreamClientSession::handleWeFailedTimeout() {
+ SWIFT_LOG(debug) << "Failed due to timeout!" << std::endl;
+ finish(true);
+}
+
+}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h
new file mode 100644
index 0000000..894e977
--- /dev/null
+++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.h
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <boost/shared_ptr.hpp>
+#include <boost/optional.hpp>
+
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/FileTransfer/FileTransferError.h>
+#include <Swiften/FileTransfer/WriteBytestream.h>
+#include <Swiften/FileTransfer/ReadBytestream.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Network/Connection.h>
+#include <Swiften/Network/HostAddressPort.h>
+#include <Swiften/Network/Timer.h>
+
+namespace Swift {
+
+class SOCKS5BytestreamRegistry;
+class Connection;
+class TimerFactory;
+
+/**
+ * A session which has been connected to a SOCKS5 server (requester).
+ *
+ */
+class SOCKS5BytestreamClientSession {
+public:
+ enum State {
+ Initial,
+ Hello,
+ Authenticating,
+ Ready,
+ Writing,
+ Reading,
+ Finished,
+ };
+
+public:
+ typedef boost::shared_ptr<SOCKS5BytestreamClientSession> ref;
+
+public:
+ SOCKS5BytestreamClientSession(boost::shared_ptr<Connection> connection, const HostAddressPort&, const std::string&, TimerFactory*);
+
+ void start();
+ void stop();
+
+ void startReceiving(boost::shared_ptr<WriteBytestream>);
+ void startSending(boost::shared_ptr<ReadBytestream>);
+
+ HostAddressPort getAddressPort() const;
+
+ boost::signal<void (bool /*error*/)> onSessionReady;
+
+ boost::signal<void (boost::optional<FileTransferError>)> onFinished;
+ boost::signal<void (int)> onBytesSent;
+ boost::signal<void (int)> onBytesReceived;
+
+private:
+ void process();
+ void hello();
+ void authenticate();
+
+ void handleConnectFinished(bool error);
+ void handleDataRead(const SafeByteArray&);
+ void handleDisconnected(const boost::optional<Connection::Error>&);
+ void handleWeFailedTimeout();
+
+ void finish(bool error);
+ void sendData();
+
+private:
+ boost::shared_ptr<Connection> connection;
+ HostAddressPort addressPort;
+ std::string destination; // hexify(SHA1(sessionID + requester + target))
+
+ State state;
+ int destinationPort;
+
+ ByteArray unprocessedData;
+ ByteArray authenticateAddress;
+
+ int chunkSize;
+ boost::shared_ptr<WriteBytestream> writeBytestream;
+ boost::shared_ptr<ReadBytestream> readBytestream;
+
+ Timer::ref weFailedTimeout;
+};
+
+}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxy.cpp b/Swiften/FileTransfer/SOCKS5BytestreamProxy.cpp
new file mode 100644
index 0000000..9599fd1
--- /dev/null
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxy.cpp
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "SOCKS5BytestreamProxy.h"
+
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+
+SOCKS5BytestreamProxy::SOCKS5BytestreamProxy(ConnectionFactory *connFactory, TimerFactory *timeFactory) : connectionFactory(connFactory), timerFactory(timeFactory) {
+
+}
+
+void SOCKS5BytestreamProxy::addS5BProxy(S5BProxyRequest::ref proxy) {
+ localS5BProxies.push_back(proxy);
+}
+
+const std::vector<S5BProxyRequest::ref>& SOCKS5BytestreamProxy::getS5BProxies() const {
+ return localS5BProxies;
+}
+
+void SOCKS5BytestreamProxy::connectToProxies(const std::string& sessionID) {
+ SWIFT_LOG(debug) << "session ID: " << sessionID << std::endl;
+ ProxyJIDClientSessionMap clientSessions;
+
+ foreach(S5BProxyRequest::ref proxy, localS5BProxies) {
+ boost::shared_ptr<Connection> conn = connectionFactory->createConnection();
+
+ boost::shared_ptr<SOCKS5BytestreamClientSession> session = boost::make_shared<SOCKS5BytestreamClientSession>(conn, proxy->getStreamHost().get().addressPort, sessionID, timerFactory);
+ clientSessions[proxy->getStreamHost().get().jid] = session;
+ session->start();
+ }
+
+ proxySessions[sessionID] = clientSessions;
+}
+
+boost::shared_ptr<SOCKS5BytestreamClientSession> SOCKS5BytestreamProxy::getProxySessionAndCloseOthers(const JID& proxyJID, const std::string& sessionID) {
+ // checking parameters
+ if (proxySessions.find(sessionID) == proxySessions.end()) {
+ return boost::shared_ptr<SOCKS5BytestreamClientSession>();
+ }
+ if (proxySessions[sessionID].find(proxyJID) == proxySessions[sessionID].end()) {
+ return boost::shared_ptr<SOCKS5BytestreamClientSession>();
+ }
+
+ // get active session
+ boost::shared_ptr<SOCKS5BytestreamClientSession> activeSession = proxySessions[sessionID][proxyJID];
+ proxySessions[sessionID].erase(proxyJID);
+
+ // close other sessions
+ foreach(const ProxyJIDClientSessionMap::value_type& myPair, proxySessions[sessionID]) {
+ myPair.second->stop();
+ }
+
+ proxySessions.erase(sessionID);
+
+ return activeSession;
+}
+
+boost::shared_ptr<SOCKS5BytestreamClientSession> SOCKS5BytestreamProxy::createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr) {
+ SOCKS5BytestreamClientSession::ref connection = boost::make_shared<SOCKS5BytestreamClientSession>(connectionFactory->createConnection(), addressPort, destAddr, timerFactory);
+ return connection;
+}
+
+}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxy.h b/Swiften/FileTransfer/SOCKS5BytestreamProxy.h
new file mode 100644
index 0000000..8f80cea
--- /dev/null
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxy.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <string>
+#include <vector>
+
+#include <Swiften/Elements/S5BProxyRequest.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Network/ConnectionFactory.h>
+#include <Swiften/Network/TimerFactory.h>
+
+namespace Swift {
+
+/**
+ * - manages list of working S5B proxies
+ * - creates initial connections (for the candidates you provide)
+ */
+class SOCKS5BytestreamProxy {
+public:
+ SOCKS5BytestreamProxy(ConnectionFactory*, TimerFactory*);
+
+ void addS5BProxy(S5BProxyRequest::ref);
+ const std::vector<S5BProxyRequest::ref>& getS5BProxies() const;
+
+ void connectToProxies(const std::string& sessionID);
+ boost::shared_ptr<SOCKS5BytestreamClientSession> getProxySessionAndCloseOthers(const JID& proxyJID, const std::string& sessionID);
+
+ boost::shared_ptr<SOCKS5BytestreamClientSession> createSOCKS5BytestreamClientSession(HostAddressPort addressPort, const std::string& destAddr);
+
+private:
+ ConnectionFactory* connectionFactory;
+ TimerFactory* timerFactory;
+
+ typedef std::map<JID, boost::shared_ptr<SOCKS5BytestreamClientSession> > ProxyJIDClientSessionMap;
+ std::map<std::string, ProxyJIDClientSessionMap> proxySessions;
+
+ std::vector<S5BProxyRequest::ref> localS5BProxies;
+};
+
+}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
index 429c7f2..ffc4298 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.cpp
@@ -6,27 +6,67 @@
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Base/Algorithm.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Base/foreach.h>
+#include <Swiften/StringCodecs/SHA1.h>
+#include <Swiften/StringCodecs/Hexify.h>
+
namespace Swift {
SOCKS5BytestreamRegistry::SOCKS5BytestreamRegistry() {
}
-void SOCKS5BytestreamRegistry::addBytestream(const std::string& destination, boost::shared_ptr<ReadBytestream> byteStream) {
- byteStreams[destination] = byteStream;
+void SOCKS5BytestreamRegistry::addReadBytestream(const std::string& destination, boost::shared_ptr<ReadBytestream> byteStream) {
+ readBytestreams[destination] = byteStream;
}
-void SOCKS5BytestreamRegistry::removeBytestream(const std::string& destination) {
- byteStreams.erase(destination);
+void SOCKS5BytestreamRegistry::removeReadBytestream(const std::string& destination) {
+ readBytestreams.erase(destination);
}
-boost::shared_ptr<ReadBytestream> SOCKS5BytestreamRegistry::getBytestream(const std::string& destination) const {
- BytestreamMap::const_iterator i = byteStreams.find(destination);
- if (i != byteStreams.end()) {
+boost::shared_ptr<ReadBytestream> SOCKS5BytestreamRegistry::getReadBytestream(const std::string& destination) const {
+ ReadBytestreamMap::const_iterator i = readBytestreams.find(destination);
+ if (i != readBytestreams.end()) {
return i->second;
}
return boost::shared_ptr<ReadBytestream>();
}
+void SOCKS5BytestreamRegistry::addWriteBytestream(const std::string& destination, boost::shared_ptr<WriteBytestream> byteStream) {
+ writeBytestreams[destination] = byteStream;
+}
+
+void SOCKS5BytestreamRegistry::removeWriteBytestream(const std::string& destination) {
+ writeBytestreams.erase(destination);
+}
+
+boost::shared_ptr<WriteBytestream> SOCKS5BytestreamRegistry::getWriteBytestream(const std::string& destination) const {
+ WriteBytestreamMap::const_iterator i = writeBytestreams.find(destination);
+ if (i != writeBytestreams.end()) {
+ return i->second;
+ }
+ return boost::shared_ptr<WriteBytestream>();
+}
+
+std::string SOCKS5BytestreamRegistry::generateSessionID() {
+ return idGenerator.generateID();
+}
+
+SOCKS5BytestreamServerSession* SOCKS5BytestreamRegistry::getConnectedSession(const std::string& destination) {
+ if (serverSessions.find(destination) != serverSessions.end()) {
+ return serverSessions[destination];
+ } else {
+ SWIFT_LOG(debug) << "No active connction for stream ID " << destination << " found!" << std::endl;
+ return NULL;
+ }
+}
+
+std::string SOCKS5BytestreamRegistry::getHostname(const std::string& sessionID, const JID& requester, const JID& target) {
+ return Hexify::hexify(SHA1::getHash(createSafeByteArray(sessionID + requester.toString() + target.toString())));
+}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h
index 955b900..779aabb 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamRegistry.h
@@ -7,23 +7,58 @@
#pragma once
#include <boost/shared_ptr.hpp>
-#include <map>
+#include <map>
#include <string>
+#include <vector>
+#include <set>
+
+#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Elements/S5BProxyRequest.h>
#include <Swiften/FileTransfer/ReadBytestream.h>
+#include <Swiften/FileTransfer/WriteBytestream.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
+#include <Swiften/Network/HostAddressPort.h>
namespace Swift {
class SOCKS5BytestreamRegistry {
public:
SOCKS5BytestreamRegistry();
- boost::shared_ptr<ReadBytestream> getBytestream(const std::string& destination) const;
- void addBytestream(const std::string& destination, boost::shared_ptr<ReadBytestream> byteStream);
- void removeBytestream(const std::string& destination);
+ boost::shared_ptr<ReadBytestream> getReadBytestream(const std::string& destination) const;
+ void addReadBytestream(const std::string& destination, boost::shared_ptr<ReadBytestream> byteStream);
+ void removeReadBytestream(const std::string& destination);
+
+ boost::shared_ptr<WriteBytestream> getWriteBytestream(const std::string& destination) const;
+ void addWriteBytestream(const std::string& destination, boost::shared_ptr<WriteBytestream> byteStream);
+ void removeWriteBytestream(const std::string& destination);
+
+ /**
+ * Generate a new session ID to use for new S5B streams.
+ */
+ std::string generateSessionID();
+
+ /**
+ * Start an actual transfer.
+ */
+ SOCKS5BytestreamServerSession* getConnectedSession(const std::string& destination);
+
+ public:
+ static std::string getHostname(const std::string& sessionID, const JID& requester, const JID& target);
private:
- typedef std::map<std::string, boost::shared_ptr<ReadBytestream> > BytestreamMap;
- BytestreamMap byteStreams;
+ friend class SOCKS5BytestreamServerSession;
+
+ typedef std::map<std::string, boost::shared_ptr<ReadBytestream> > ReadBytestreamMap;
+ ReadBytestreamMap readBytestreams;
+
+ typedef std::map<std::string, boost::shared_ptr<WriteBytestream> > WriteBytestreamMap;
+ WriteBytestreamMap writeBytestreams;
+
+ std::map<std::string, SOCKS5BytestreamServerSession*> serverSessions;
+
+ IDGenerator idGenerator;
};
}
-
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
index 9731d2d..90fed7a 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServer.cpp
@@ -8,13 +8,15 @@
#include <boost/bind.hpp>
+#include <Swiften/Base/Log.h>
#include <Swiften/StringCodecs/Hexify.h>
#include <Swiften/StringCodecs/SHA1.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
namespace Swift {
-SOCKS5BytestreamServer::SOCKS5BytestreamServer(boost::shared_ptr<ConnectionServer> connectionServer) : connectionServer(connectionServer) {
+SOCKS5BytestreamServer::SOCKS5BytestreamServer(boost::shared_ptr<ConnectionServer> connectionServer, SOCKS5BytestreamRegistry* registry) : connectionServer(connectionServer), registry(registry) {
}
void SOCKS5BytestreamServer::start() {
@@ -25,12 +27,12 @@ void SOCKS5BytestreamServer::stop() {
connectionServer->onNewConnection.disconnect(boost::bind(&SOCKS5BytestreamServer::handleNewConnection, this, _1));
}
-void SOCKS5BytestreamServer::addBytestream(const std::string& id, const JID& from, const JID& to, boost::shared_ptr<ReadBytestream> byteStream) {
- bytestreams.addBytestream(getSOCKSDestinationAddress(id, from, to), byteStream);
+void SOCKS5BytestreamServer::addReadBytestream(const std::string& id, const JID& from, const JID& to, boost::shared_ptr<ReadBytestream> byteStream) {
+ registry->addReadBytestream(getSOCKSDestinationAddress(id, from, to), byteStream);
}
-void SOCKS5BytestreamServer::removeBytestream(const std::string& id, const JID& from, const JID& to) {
- bytestreams.removeBytestream(getSOCKSDestinationAddress(id, from, to));
+void SOCKS5BytestreamServer::removeReadBytestream(const std::string& id, const JID& from, const JID& to) {
+ registry->removeReadBytestream(getSOCKSDestinationAddress(id, from, to));
}
std::string SOCKS5BytestreamServer::getSOCKSDestinationAddress(const std::string& id, const JID& from, const JID& to) {
@@ -38,7 +40,7 @@ std::string SOCKS5BytestreamServer::getSOCKSDestinationAddress(const std::string
}
void SOCKS5BytestreamServer::handleNewConnection(boost::shared_ptr<Connection> connection) {
- boost::shared_ptr<SOCKS5BytestreamServerSession> session(new SOCKS5BytestreamServerSession(connection, &bytestreams));
+ boost::shared_ptr<SOCKS5BytestreamServerSession> session(new SOCKS5BytestreamServerSession(connection, registry));
sessions.push_back(session);
session->start();
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServer.h b/Swiften/FileTransfer/SOCKS5BytestreamServer.h
index 7fa709e..6bb598e 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServer.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServer.h
@@ -20,15 +20,15 @@ namespace Swift {
class SOCKS5BytestreamServer {
public:
- SOCKS5BytestreamServer(boost::shared_ptr<ConnectionServer> connectionServer);
+ SOCKS5BytestreamServer(boost::shared_ptr<ConnectionServer> connectionServer, SOCKS5BytestreamRegistry* registry);
HostAddressPort getAddressPort() const;
void start();
void stop();
- void addBytestream(const std::string& id, const JID& from, const JID& to, boost::shared_ptr<ReadBytestream> byteStream);
- void removeBytestream(const std::string& id, const JID& from, const JID& to);
+ void addReadBytestream(const std::string& id, const JID& from, const JID& to, boost::shared_ptr<ReadBytestream> byteStream);
+ void removeReadBytestream(const std::string& id, const JID& from, const JID& to);
/*protected:
boost::shared_ptr<ReadBytestream> getBytestream(const std::string& dest);*/
@@ -42,7 +42,7 @@ namespace Swift {
friend class SOCKS5BytestreamServerSession;
boost::shared_ptr<ConnectionServer> connectionServer;
- SOCKS5BytestreamRegistry bytestreams;
+ SOCKS5BytestreamRegistry* registry;
std::vector<boost::shared_ptr<SOCKS5BytestreamServerSession> > sessions;
};
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
index 477af4b..6f33862 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
@@ -13,12 +13,14 @@
#include <Swiften/Base/SafeByteArray.h>
#include <Swiften/Base/Algorithm.h>
#include <Swiften/Base/Concat.h>
+#include <Swiften/Base/Log.h>
#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
#include <Swiften/FileTransfer/BytestreamException.h>
namespace Swift {
-SOCKS5BytestreamServerSession::SOCKS5BytestreamServerSession(boost::shared_ptr<Connection> connection, SOCKS5BytestreamRegistry* bytestreams) : connection(connection), bytestreams(bytestreams), state(Initial), chunkSize(4096) {
+SOCKS5BytestreamServerSession::SOCKS5BytestreamServerSession(boost::shared_ptr<Connection> connection, SOCKS5BytestreamRegistry* bytestreams) : connection(connection), bytestreams(bytestreams), state(Initial), chunkSize(131072) {
+ connection->onDisconnected.connect(boost::bind(&SOCKS5BytestreamServerSession::handleDisconnected, this, _1));
}
SOCKS5BytestreamServerSession::~SOCKS5BytestreamServerSession() {
@@ -29,17 +31,55 @@ SOCKS5BytestreamServerSession::~SOCKS5BytestreamServerSession() {
}
void SOCKS5BytestreamServerSession::start() {
+ SWIFT_LOG(debug) << std::endl;
connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamServerSession::handleDataRead, this, _1));
state = WaitingForAuthentication;
}
void SOCKS5BytestreamServerSession::stop() {
- finish(false);
+ connection->onDataWritten.disconnect(boost::bind(&SOCKS5BytestreamServerSession::sendData, this));
+ connection->onDataRead.disconnect(boost::bind(&SOCKS5BytestreamServerSession::handleDataRead, this, _1));
+ connection->disconnect();
+ state = Finished;
+}
+
+void SOCKS5BytestreamServerSession::startTransfer() {
+ if (state == ReadyForTransfer) {
+ if (readBytestream) {
+ state = WritingData;
+ connection->onDataWritten.connect(boost::bind(&SOCKS5BytestreamServerSession::sendData, this));
+ sendData();
+ }
+ else if(writeBytestream) {
+ state = ReadingData;
+ writeBytestream->write(unprocessedData);
+ onBytesReceived(unprocessedData.size());
+ unprocessedData.clear();
+ }
+ } else {
+ SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl;
+ }
+}
+
+HostAddressPort SOCKS5BytestreamServerSession::getAddressPort() const {
+ return connection->getLocalAddress();
}
void SOCKS5BytestreamServerSession::handleDataRead(const SafeByteArray& data) {
- append(unprocessedData, data);
- process();
+ if (state != ReadingData) {
+ append(unprocessedData, data);
+ process();
+ } else {
+ writeBytestream->write(createByteArray(data.data(), data.size()));
+ onBytesReceived(data.size());
+ }
+}
+
+void SOCKS5BytestreamServerSession::handleDisconnected(const boost::optional<Connection::Error>& error) {
+ SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl;
+ if (error) {
+ finish(true);
+ }
}
void SOCKS5BytestreamServerSession::process() {
@@ -54,7 +94,7 @@ void SOCKS5BytestreamServerSession::process() {
if (i == 2 + authCount) {
// Authentication message is complete
if (i != unprocessedData.size()) {
- std::cerr << "SOCKS5BytestreamServerSession: Junk after authentication mechanism";
+ SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl;
}
unprocessedData.clear();
connection->write(createSafeByteArray("\x05\x00", 2));
@@ -71,26 +111,31 @@ void SOCKS5BytestreamServerSession::process() {
requestID.push_back(unprocessedData[i]);
++i;
}
- // Skip the port:
+ // Skip the port: 2 byte large, one already skipped. Add one for comparison with size
i += 2;
- if (i >= unprocessedData.size()) {
+ if (i <= unprocessedData.size()) {
if (i != unprocessedData.size()) {
- std::cerr << "SOCKS5BytestreamServerSession: Junk after authentication mechanism";
+ SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl;
}
- bytestream = bytestreams->getBytestream(byteArrayToString(requestID));
+ unprocessedData.clear();
+ std::string streamID = byteArrayToString(requestID);
+ readBytestream = bytestreams->getReadBytestream(streamID);
+ writeBytestream = bytestreams->getWriteBytestream(streamID);
SafeByteArray result = createSafeByteArray("\x05", 1);
- result.push_back(bytestream ? 0x0 : 0x4);
+ result.push_back((readBytestream || writeBytestream) ? 0x0 : 0x4);
append(result, createByteArray("\x00\x03", 2));
result.push_back(static_cast<char>(requestID.size()));
append(result, concat(requestID, createByteArray("\x00\x00", 2)));
- if (!bytestream) {
+ if (!readBytestream && !writeBytestream) {
+ SWIFT_LOG(debug) << "Readstream or Wrtiestream with ID " << streamID << " not found!" << std::endl;
connection->write(result);
finish(true);
}
else {
- state = SendingData;
- connection->onDataWritten.connect(boost::bind(&SOCKS5BytestreamServerSession::sendData, this));
+ SWIFT_LOG(deubg) << "Found " << (readBytestream ? "Readstream" : "Writestream") << ". Sent OK." << std::endl;
connection->write(result);
+ bytestreams->serverSessions[streamID] = this;
+ state = ReadyForTransfer;
}
}
}
@@ -98,9 +143,11 @@ void SOCKS5BytestreamServerSession::process() {
}
void SOCKS5BytestreamServerSession::sendData() {
- if (!bytestream->isFinished()) {
+ if (!readBytestream->isFinished()) {
try {
- connection->write(createSafeByteArray(bytestream->read(chunkSize)));
+ SafeByteArray dataToSend = createSafeByteArray(readBytestream->read(chunkSize));
+ connection->write(dataToSend);
+ onBytesSent(dataToSend.size());
}
catch (const BytestreamException&) {
finish(true);
@@ -114,9 +161,14 @@ void SOCKS5BytestreamServerSession::sendData() {
void SOCKS5BytestreamServerSession::finish(bool error) {
connection->onDataWritten.disconnect(boost::bind(&SOCKS5BytestreamServerSession::sendData, this));
connection->onDataRead.disconnect(boost::bind(&SOCKS5BytestreamServerSession::handleDataRead, this, _1));
- bytestream.reset();
+ connection->onDisconnected.disconnect(boost::bind(&SOCKS5BytestreamServerSession::handleDisconnected, this, _1));
+ readBytestream.reset();
state = Finished;
- onFinished(error);
+ if (error) {
+ onFinished(boost::optional<FileTransferError>(FileTransferError::PeerError));
+ } else {
+ onFinished(boost::optional<FileTransferError>());
+ }
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
index 761a365..3e1018f 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.h
@@ -11,17 +11,24 @@
#include <Swiften/Base/boost_bsignals.h>
#include <Swiften/Network/Connection.h>
#include <Swiften/FileTransfer/ReadBytestream.h>
+#include <Swiften/FileTransfer/WriteBytestream.h>
+#include <Swiften/FileTransfer/FileTransferError.h>
namespace Swift {
class SOCKS5BytestreamRegistry;
class SOCKS5BytestreamServerSession {
public:
+ typedef boost::shared_ptr<SOCKS5BytestreamServerSession> ref;
+
+ public:
enum State {
Initial,
WaitingForAuthentication,
WaitingForRequest,
- SendingData,
+ ReadyForTransfer,
+ ReadingData,
+ WritingData,
Finished,
};
@@ -35,12 +42,18 @@ namespace Swift {
void start();
void stop();
- boost::signal<void (bool /* error */)> onFinished;
+ void startTransfer();
+ HostAddressPort getAddressPort() const;
+
+ boost::signal<void (boost::optional<FileTransferError>)> onFinished;
+ boost::signal<void (int)> onBytesSent;
+ boost::signal<void (int)> onBytesReceived;
private:
void finish(bool error);
void process();
void handleDataRead(const SafeByteArray&);
+ void handleDisconnected(const boost::optional<Connection::Error>&);
void sendData();
private:
@@ -49,6 +62,7 @@ namespace Swift {
ByteArray unprocessedData;
State state;
int chunkSize;
- boost::shared_ptr<ReadBytestream> bytestream;
+ boost::shared_ptr<ReadBytestream> readBytestream;
+ boost::shared_ptr<WriteBytestream> writeBytestream;
};
}
diff --git a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h
new file mode 100644
index 0000000..ae06cd3
--- /dev/null
+++ b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <string>
+#include <boost/filesystem.hpp>
+#include <boost/date_time/posix_time/posix_time.hpp>
+
+#include <Swiften/FileTransfer/FileTransferManager.h>
+
+namespace Swift {
+ class DummyFileTransferManager : public FileTransferManager {
+ public:
+ DummyFileTransferManager() : FileTransferManager() {
+ }
+
+ virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(const JID&, const boost::filesystem::path&, const std::string&, boost::shared_ptr<ReadBytestream>) {
+ return OutgoingFileTransfer::ref();
+ }
+
+ virtual OutgoingFileTransfer::ref createOutgoingFileTransfer(const JID&, const std::string&, const std::string&, const boost::uintmax_t, const boost::posix_time::ptime&, boost::shared_ptr<ReadBytestream>) {
+ return OutgoingFileTransfer::ref();
+ }
+
+ virtual void startListeningOnPort(int) {
+ }
+
+ virtual void addS5BProxy(boost::shared_ptr<S5BProxyRequest>) {
+ }
+
+ };
+}
diff --git a/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp b/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp
new file mode 100644
index 0000000..7407f44
--- /dev/null
+++ b/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp
@@ -0,0 +1,282 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Client/DummyStanzaChannel.h>
+#include <Swiften/Elements/IBB.h>
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/FileTransfer/ByteArrayWriteBytestream.h>
+#include <Swiften/FileTransfer/IncomingJingleFileTransfer.h>
+#include <Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h>
+#include <Swiften/FileTransfer/LocalJingleTransportCandidateGeneratorFactory.h>
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelectorFactory.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamProxy.h>
+#include <Swiften/Jingle/FakeJingleSession.h>
+#include <Swiften/Network/DummyTimerFactory.h>
+#include <Swiften/EventLoop/DummyEventLoop.h>
+#include <Swiften/Network/DummyConnectionFactory.h>
+#include <Swiften/Network/PlatformNATTraversalWorker.h>
+#include <Swiften/Queries/IQRouter.h>
+
+#include <iostream>
+
+using namespace Swift;
+using namespace boost;
+
+class FakeRemoteJingleTransportCandidateSelector : public RemoteJingleTransportCandidateSelector {
+ void addRemoteTransportCandidates(JingleTransportPayload::ref cand) {
+ candidate = cand;
+ }
+
+ void selectCandidate() {
+ boost::shared_ptr<JingleS5BTransportPayload> payload = make_shared<JingleS5BTransportPayload>();
+ payload->setCandidateError(true);
+ payload->setSessionID(candidate->getSessionID());
+ onRemoteTransportCandidateSelectFinished(payload);
+ }
+
+ void setMinimumPriority(int) {
+
+ }
+
+ bool isActualCandidate(JingleTransportPayload::ref) {
+ return false;
+ }
+
+ int getPriority(JingleTransportPayload::ref) {
+ return 0;
+ }
+
+ JingleTransport::ref selectTransport(JingleTransportPayload::ref) {
+ return JingleTransport::ref();
+ }
+
+private:
+ JingleTransportPayload::ref candidate;
+};
+
+class FakeRemoteJingleTransportCandidateSelectorFactory : public RemoteJingleTransportCandidateSelectorFactory {
+public:
+ virtual ~FakeRemoteJingleTransportCandidateSelectorFactory() {
+
+ }
+
+ virtual RemoteJingleTransportCandidateSelector* createCandidateSelector() {
+ return new FakeRemoteJingleTransportCandidateSelector();
+ }
+};
+
+class FakeLocalJingleTransportCandidateGenerator : public LocalJingleTransportCandidateGenerator {
+public:
+ virtual void generateLocalTransportCandidates(JingleTransportPayload::ref payload) {
+ JingleS5BTransportPayload::ref payL = make_shared<JingleS5BTransportPayload>();
+ payL->setSessionID(payload->getSessionID());
+ onLocalTransportCandidatesGenerated(payL);
+ }
+
+ void emitonLocalTransportCandidatesGenerated(JingleTransportPayload::ref payload) {
+ onLocalTransportCandidatesGenerated(payload);
+ }
+
+ virtual bool isActualCandidate(JingleTransportPayload::ref) {
+ return false;
+ }
+
+ virtual int getPriority(JingleTransportPayload::ref) {
+ return 0;
+ }
+
+ virtual JingleTransport::ref selectTransport(JingleTransportPayload::ref) {
+ return JingleTransport::ref();
+ }
+};
+
+class FakeLocalJingleTransportCandidateGeneratorFactory : public LocalJingleTransportCandidateGeneratorFactory {
+public:
+ virtual LocalJingleTransportCandidateGenerator* createCandidateGenerator() {
+ return new FakeLocalJingleTransportCandidateGenerator();
+ }
+};
+
+class IncomingJingleFileTransferTest : public CppUnit::TestFixture {
+ CPPUNIT_TEST_SUITE(IncomingJingleFileTransferTest);
+ CPPUNIT_TEST(test_AcceptOnyIBBSendsSessionAccept);
+ CPPUNIT_TEST(test_OnlyIBBTransferReceiveWorks);
+ CPPUNIT_TEST(test_AcceptFailingS5BFallsBackToIBB);
+ CPPUNIT_TEST_SUITE_END();
+public:
+ shared_ptr<IncomingJingleFileTransfer> createTestling() {
+ JID ourJID("our@jid.org/full");
+ return make_shared<IncomingJingleFileTransfer>(ourJID, shared_ptr<JingleSession>(fakeJingleSession), jingleContentPayload, fakeRJTCSF.get(), fakeLJTCF.get(), iqRouter, bytestreamRegistry, bytestreamProxy, timerFactory);
+ }
+
+ IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) {
+ IQ::ref request = IQ::createRequest(IQ::Set, JID("foo@bar.com/baz"), id, ibb);
+ request->setFrom(from);
+ return request;
+ }
+
+ void setUp() {
+ eventLoop = new DummyEventLoop();
+ fakeJingleSession = new FakeJingleSession("foo@bar.com/baz", "mysession");
+ jingleContentPayload = make_shared<JingleContentPayload>();
+ fakeRJTCSF = make_shared<FakeRemoteJingleTransportCandidateSelectorFactory>();
+ fakeLJTCF = make_shared<FakeLocalJingleTransportCandidateGeneratorFactory>();
+ stanzaChannel = new DummyStanzaChannel();
+ iqRouter = new IQRouter(stanzaChannel);
+ bytestreamRegistry = new SOCKS5BytestreamRegistry();
+ timerFactory = new DummyTimerFactory();
+ connectionFactory = new DummyConnectionFactory(eventLoop);
+ bytestreamProxy = new SOCKS5BytestreamProxy(connectionFactory, timerFactory);
+ }
+
+ void tearDown() {
+ delete bytestreamProxy;
+ delete connectionFactory;
+ delete timerFactory;
+ delete bytestreamRegistry;
+ delete iqRouter;
+ delete stanzaChannel;
+ delete eventLoop;
+ }
+
+ // Tests whether IncomingJingleFileTransfer would accept a IBB only file transfer.
+ void test_AcceptOnyIBBSendsSessionAccept() {
+ //1. create your test incoming file transfer
+ shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>();
+ desc->addOffer(StreamInitiationFileInfo());
+ jingleContentPayload->addDescription(desc);
+ JingleIBBTransportPayload::ref tpRef = make_shared<JingleIBBTransportPayload>();
+ tpRef->setSessionID("mysession");
+ jingleContentPayload->addTransport(tpRef);
+
+ shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
+
+ //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
+ shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>();
+ fileTransfer->accept(byteStream);
+
+ // check whether accept has been called
+ getCall<FakeJingleSession::AcceptCall>(0);
+ }
+
+ void test_OnlyIBBTransferReceiveWorks() {
+ //1. create your test incoming file transfer
+ shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>();
+ desc->addOffer(StreamInitiationFileInfo());
+ jingleContentPayload->addDescription(desc);
+ JingleIBBTransportPayload::ref tpRef = make_shared<JingleIBBTransportPayload>();
+ tpRef->setSessionID("mysession");
+ jingleContentPayload->addTransport(tpRef);
+
+ shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
+
+ //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
+ shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>();
+ fileTransfer->accept(byteStream);
+
+ // check whether accept has been called
+ getCall<FakeJingleSession::AcceptCall>(0);
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
+ CPPUNIT_ASSERT(createByteArray("abc") == byteStream->getData());
+ }
+
+ void test_AcceptFailingS5BFallsBackToIBB() {
+ //1. create your test incoming file transfer
+ addFileTransferDescription();
+
+ // add SOCKS5BytestreamTransportPayload
+ JingleS5BTransportPayload::ref payLoad = addJingleS5BPayload();
+
+ shared_ptr<IncomingJingleFileTransfer> fileTransfer = createTestling();
+
+ //2. do 'accept' on a dummy writebytestream (you'll have to look if there already is one)
+ shared_ptr<ByteArrayWriteBytestream> byteStream = make_shared<ByteArrayWriteBytestream>();
+ fileTransfer->accept(byteStream);
+
+ // check whether accept has been called
+ FakeJingleSession::AcceptCall acceptCall = getCall<FakeJingleSession::AcceptCall>(0);
+ CPPUNIT_ASSERT_EQUAL(payLoad->getSessionID(), acceptCall.payload->getSessionID());
+
+ // check for candidate error
+ FakeJingleSession::InfoTransportCall infoTransportCall = getCall<FakeJingleSession::InfoTransportCall>(1);
+ JingleS5BTransportPayload::ref s5bPayload = dynamic_pointer_cast<JingleS5BTransportPayload>(infoTransportCall.payload);
+ CPPUNIT_ASSERT(s5bPayload->hasCandidateError());
+
+ // indicate transport replace (Romeo)
+ fakeJingleSession->onTransportReplaceReceived(getContentID(), addJingleIBBPayload());
+
+ FakeJingleSession::AcceptTransportCall acceptTransportCall = getCall<FakeJingleSession::AcceptTransportCall>(2);
+
+ // send a bit of data
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBOpen("mysession", 0x10), "foo@bar.com/baz", "id-open"));
+ stanzaChannel->onIQReceived(createIBBRequest(IBB::createIBBData("mysession", 0, createByteArray("abc")), "foo@bar.com/baz", "id-a"));
+ CPPUNIT_ASSERT(createByteArray("abc") == byteStream->getData());
+ }
+
+ void test_S5BTransferReceiveTest() {
+ addFileTransferDescription();
+ JingleS5BTransportPayload::ref payLoad = addJingleS5BPayload();
+ }
+
+private:
+ void addFileTransferDescription() {
+ shared_ptr<JingleFileTransferDescription> desc = make_shared<JingleFileTransferDescription>();
+ desc->addOffer(StreamInitiationFileInfo());
+ jingleContentPayload->addDescription(desc);
+ }
+
+ shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() {
+ JingleS5BTransportPayload::ref payLoad = make_shared<JingleS5BTransportPayload>();
+ payLoad->setSessionID("mysession");
+ jingleContentPayload->addTransport(payLoad);
+ return payLoad;
+ }
+
+ shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() {
+ JingleIBBTransportPayload::ref payLoad = make_shared<JingleIBBTransportPayload>();
+ payLoad->setSessionID("mysession");
+ jingleContentPayload->addTransport(payLoad);
+ return payLoad;
+ }
+
+ JingleContentID getContentID() const {
+ return JingleContentID(jingleContentPayload->getName(), jingleContentPayload->getCreator());
+ }
+
+ template <typename T> T getCall(int i) const {
+ size_t index = static_cast<size_t>(i);
+ CPPUNIT_ASSERT(index < fakeJingleSession->calledCommands.size());
+ T* cmd = boost::get<T>(&fakeJingleSession->calledCommands[index]);
+ CPPUNIT_ASSERT(cmd);
+ return *cmd;
+ }
+
+private:
+ EventLoop* eventLoop;
+ FakeJingleSession* fakeJingleSession;
+ shared_ptr<JingleContentPayload> jingleContentPayload;
+ shared_ptr<FakeRemoteJingleTransportCandidateSelectorFactory> fakeRJTCSF;
+ shared_ptr<FakeLocalJingleTransportCandidateGeneratorFactory> fakeLJTCF;
+ DummyStanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ SOCKS5BytestreamRegistry* bytestreamRegistry;
+ DummyConnectionFactory* connectionFactory;
+ SOCKS5BytestreamProxy* bytestreamProxy;
+ DummyTimerFactory* timerFactory;
+};
+
+CPPUNIT_TEST_SUITE_REGISTRATION(IncomingJingleFileTransferTest);
diff --git a/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp b/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp
new file mode 100644
index 0000000..582c3e5
--- /dev/null
+++ b/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp
@@ -0,0 +1,283 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <boost/bind.hpp>
+#include <boost/optional.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/FileTransfer/OutgoingJingleFileTransfer.h>
+#include <Swiften/Jingle/FakeJingleSession.h>
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelectorFactory.h>
+#include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h>
+#include <Swiften/FileTransfer/LocalJingleTransportCandidateGeneratorFactory.h>
+#include <Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h>
+#include <Swiften/Queries/IQRouter.h>
+#include <Swiften/Client/DummyStanzaChannel.h>
+#include <Swiften/FileTransfer/ByteArrayReadBytestream.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamProxy.h>
+
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/Elements/JingleFileTransferDescription.h>
+#include <Swiften/Elements/IBB.h>
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/IDGenerator.h>
+#include <Swiften/EventLoop/DummyEventLoop.h>
+#include <Swiften/Network/PlatformNATTraversalWorker.h>
+#include <Swiften/Network/DummyTimerFactory.h>
+#include <Swiften/Network/DummyConnection.h>
+#include <Swiften/Network/ConnectionFactory.h>
+#include <Swiften/Network/DummyConnectionFactory.h>
+
+#include <Swiften/Base/Log.h>
+
+#include <iostream>
+
+using namespace Swift;
+
+class OFakeRemoteJingleTransportCandidateSelector : public RemoteJingleTransportCandidateSelector {
+ void addRemoteTransportCandidates(JingleTransportPayload::ref cand) {
+ candidate = cand;
+ }
+
+ void selectCandidate() {
+ JingleS5BTransportPayload::ref payload = boost::make_shared<JingleS5BTransportPayload>();
+ payload->setCandidateError(true);
+ payload->setSessionID(candidate->getSessionID());
+ onRemoteTransportCandidateSelectFinished(payload);
+ }
+
+ void setMinimumPriority(int) {
+
+ }
+
+ bool isActualCandidate(JingleTransportPayload::ref) {
+ return false;
+ }
+
+ int getPriority(JingleTransportPayload::ref) {
+ return 0;
+ }
+
+ JingleTransport::ref selectTransport(JingleTransportPayload::ref) {
+ return JingleTransport::ref();
+ }
+
+private:
+ JingleTransportPayload::ref candidate;
+};
+
+class OFakeRemoteJingleTransportCandidateSelectorFactory : public RemoteJingleTransportCandidateSelectorFactory {
+public:
+ virtual ~OFakeRemoteJingleTransportCandidateSelectorFactory() {
+
+ }
+
+ virtual RemoteJingleTransportCandidateSelector* createCandidateSelector() {
+ return new OFakeRemoteJingleTransportCandidateSelector();
+ }
+};
+
+class OFakeLocalJingleTransportCandidateGenerator : public LocalJingleTransportCandidateGenerator {
+public:
+ virtual void generateLocalTransportCandidates(JingleTransportPayload::ref /* payload */) {
+ //JingleTransportPayload::ref payL = make_shared<JingleTransportPayload>();
+ //payL->setSessionID(payload->getSessionID());
+ JingleS5BTransportPayload::ref payL = boost::make_shared<JingleS5BTransportPayload>();
+
+ onLocalTransportCandidatesGenerated(payL);
+ }
+
+ void emitonLocalTransportCandidatesGenerated(JingleTransportPayload::ref payload) {
+ onLocalTransportCandidatesGenerated(payload);
+ }
+
+ virtual bool isActualCandidate(JingleTransportPayload::ref) {
+ return false;
+ }
+
+ virtual int getPriority(JingleTransportPayload::ref) {
+ return 0;
+ }
+
+ virtual JingleTransport::ref selectTransport(JingleTransportPayload::ref) {
+ return JingleTransport::ref();
+ }
+};
+
+class OFakeLocalJingleTransportCandidateGeneratorFactory : public LocalJingleTransportCandidateGeneratorFactory {
+public:
+ virtual LocalJingleTransportCandidateGenerator* createCandidateGenerator() {
+ return new OFakeLocalJingleTransportCandidateGenerator();
+ }
+};
+
+class OutgoingJingleFileTransferTest : public CppUnit::TestFixture {
+ CPPUNIT_TEST_SUITE(OutgoingJingleFileTransferTest);
+ CPPUNIT_TEST(test_SendSessionInitiateOnStart);
+ CPPUNIT_TEST(test_IBBStartsAfterSendingSessionAccept);
+ CPPUNIT_TEST(test_ReceiveSessionTerminateAfterSessionInitiate);
+ CPPUNIT_TEST_SUITE_END();
+
+ class FTStatusHelper {
+ public:
+ bool finishedCalled;
+ FileTransferError::Type error;
+ void handleFileTransferFinished(boost::optional<FileTransferError> error) {
+ finishedCalled = true;
+ if (error.is_initialized()) this->error = error.get().getType();
+ }
+ };
+public:
+
+ boost::shared_ptr<OutgoingJingleFileTransfer> createTestling() {
+ JID to("test@foo.com/bla");
+ StreamInitiationFileInfo fileInfo;
+ fileInfo.setDescription("some file");
+ fileInfo.setName("test.bin");
+ fileInfo.setHash("asdjasdas");
+ fileInfo.setSize(1024 * 1024);
+ return boost::shared_ptr<OutgoingJingleFileTransfer>(new OutgoingJingleFileTransfer(boost::shared_ptr<JingleSession>(fakeJingleSession), fakeRJTCSF.get(), fakeLJTCF.get(), iqRouter, idGen, to, stream, fileInfo, s5bRegistry, s5bProxy));
+ }
+
+ IQ::ref createIBBRequest(IBB::ref ibb, const JID& from, const std::string& id) {
+ IQ::ref request = IQ::createRequest(IQ::Set, JID("foo@bar.com/baz"), id, ibb);
+ request->setFrom(from);
+ return request;
+ }
+
+ void setUp() {
+ fakeJingleSession = new FakeJingleSession("foo@bar.com/baz", "mysession");
+ jingleContentPayload = boost::make_shared<JingleContentPayload>();
+ fakeRJTCSF = boost::make_shared<OFakeRemoteJingleTransportCandidateSelectorFactory>();
+ fakeLJTCF = boost::make_shared<OFakeLocalJingleTransportCandidateGeneratorFactory>();
+ stanzaChannel = new DummyStanzaChannel();
+ iqRouter = new IQRouter(stanzaChannel);
+ eventLoop = new DummyEventLoop();
+ timerFactory = new DummyTimerFactory();
+ connectionFactory = new DummyConnectionFactory(eventLoop);
+ s5bRegistry = new SOCKS5BytestreamRegistry();
+ s5bProxy = new SOCKS5BytestreamProxy(connectionFactory, timerFactory);
+
+ data.clear();
+ for (int n=0; n < 1024 * 1024; ++n) {
+ data.push_back(34);
+ }
+
+ stream = boost::make_shared<ByteArrayReadBytestream>(data);
+
+ idGen = new IDGenerator();
+ }
+
+ void tearDown() {
+ delete idGen;
+ delete s5bRegistry;
+ delete connectionFactory;
+ delete timerFactory;
+ delete eventLoop;
+ delete iqRouter;
+ delete stanzaChannel;
+ }
+
+
+ void test_SendSessionInitiateOnStart() {
+ boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling();
+ transfer->start();
+ FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0);
+ JingleFileTransferDescription::ref description = boost::dynamic_pointer_cast<JingleFileTransferDescription>(call.description);
+ CPPUNIT_ASSERT(description);
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), description->getOffers().size());
+ CPPUNIT_ASSERT(static_cast<size_t>(1048576) == description->getOffers()[0].getSize());
+
+ JingleS5BTransportPayload::ref transport = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(call.payload);
+ CPPUNIT_ASSERT(transport);
+ }
+
+ void test_IBBStartsAfterSendingSessionAccept() {
+ boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling();
+ transfer->start();
+
+ FakeJingleSession::InitiateCall call = getCall<FakeJingleSession::InitiateCall>(0);
+ // FIXME: we initiate with SOCSK5 now and not IBB, needs to be fixed.
+ /*
+ fakeJingleSession->onSessionAcceptReceived(call.id, call.description, call.payload);
+ IQ::ref iqOpenStanza = stanzaChannel->getStanzaAtIndex<IQ>(0);
+ CPPUNIT_ASSERT(iqOpenStanza);
+ */
+ }
+
+ void test_ReceiveSessionTerminateAfterSessionInitiate() {
+ boost::shared_ptr<OutgoingJingleFileTransfer> transfer = createTestling();
+ transfer->start();
+
+ getCall<FakeJingleSession::InitiateCall>(0);
+
+ FTStatusHelper helper;
+ helper.finishedCalled = false;
+ transfer->onFinished.connect(bind(&FTStatusHelper::handleFileTransferFinished, &helper, _1));
+ fakeJingleSession->onSessionTerminateReceived(JinglePayload::Reason(JinglePayload::Reason::Busy));
+ CPPUNIT_ASSERT_EQUAL(true, helper.finishedCalled);
+ CPPUNIT_ASSERT(FileTransferError::PeerError == helper.error);
+ }
+
+
+//TODO: some more testcases
+
+private:
+ void addFileTransferDescription() {
+ boost::shared_ptr<JingleFileTransferDescription> desc = boost::make_shared<JingleFileTransferDescription>();
+ desc->addOffer(StreamInitiationFileInfo());
+ jingleContentPayload->addDescription(desc);
+ }
+
+ boost::shared_ptr<JingleS5BTransportPayload> addJingleS5BPayload() {
+ JingleS5BTransportPayload::ref payLoad = boost::make_shared<JingleS5BTransportPayload>();
+ payLoad->setSessionID("mysession");
+ jingleContentPayload->addTransport(payLoad);
+ return payLoad;
+ }
+
+ boost::shared_ptr<JingleIBBTransportPayload> addJingleIBBPayload() {
+ JingleIBBTransportPayload::ref payLoad = boost::make_shared<JingleIBBTransportPayload>();
+ payLoad->setSessionID("mysession");
+ jingleContentPayload->addTransport(payLoad);
+ return payLoad;
+ }
+
+ JingleContentID getContentID() const {
+ return JingleContentID(jingleContentPayload->getName(), jingleContentPayload->getCreator());
+ }
+
+ template <typename T> T getCall(int i) const {
+ size_t index = static_cast<size_t>(i);
+ CPPUNIT_ASSERT(index < fakeJingleSession->calledCommands.size());
+ T* cmd = boost::get<T>(&fakeJingleSession->calledCommands[index]);
+ CPPUNIT_ASSERT(cmd);
+ return *cmd;
+ }
+
+private:
+ std::vector<unsigned char> data;
+ boost::shared_ptr<ByteArrayReadBytestream> stream;
+ FakeJingleSession* fakeJingleSession;
+ boost::shared_ptr<JingleContentPayload> jingleContentPayload;
+ boost::shared_ptr<OFakeRemoteJingleTransportCandidateSelectorFactory> fakeRJTCSF;
+ boost::shared_ptr<OFakeLocalJingleTransportCandidateGeneratorFactory> fakeLJTCF;
+ DummyStanzaChannel* stanzaChannel;
+ IQRouter* iqRouter;
+ IDGenerator* idGen;
+ EventLoop *eventLoop;
+ SOCKS5BytestreamRegistry* s5bRegistry;
+ SOCKS5BytestreamProxy* s5bProxy;
+ DummyTimerFactory* timerFactory;
+ DummyConnectionFactory* connectionFactory;
+};
+
+CPPUNIT_TEST_SUITE_REGISTRATION(OutgoingJingleFileTransferTest);
diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
new file mode 100644
index 0000000..35580bf
--- /dev/null
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
@@ -0,0 +1,306 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Base/ByteArray.h>
+#include <QA/Checker/IO.h>
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <boost/bind.hpp>
+#include <boost/random/mersenne_twister.hpp>
+#include <boost/random/uniform_int.hpp>
+#include <boost/random/variate_generator.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Base/Algorithm.h>
+#include <Swiften/Base/ByteArray.h>
+#include <Swiften/Base/Concat.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Base/StartStopper.h>
+#include <Swiften/EventLoop/DummyEventLoop.h>
+#include <Swiften/FileTransfer/ByteArrayReadBytestream.h>
+#include <Swiften/FileTransfer/ByteArrayWriteBytestream.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h>
+#include <Swiften/FileTransfer/SOCKS5BytestreamRegistry.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Network/DummyConnection.h>
+#include <Swiften/Network/DummyTimerFactory.h>
+#include <Swiften/StringCodecs/Hexify.h>
+
+using namespace Swift;
+
+boost::mt19937 randomGen;
+
+class SOCKS5BytestreamClientSessionTest : public CppUnit::TestFixture {
+ CPPUNIT_TEST_SUITE(SOCKS5BytestreamClientSessionTest);
+ CPPUNIT_TEST(testForSessionReady);
+ CPPUNIT_TEST(testErrorHandlingHello);
+ CPPUNIT_TEST(testErrorHandlingRequest);
+ CPPUNIT_TEST(testWriteBytestream);
+ CPPUNIT_TEST(testReadBytestream);
+ CPPUNIT_TEST_SUITE_END();
+
+ const HostAddressPort destinationAddressPort;
+ const std::string destination;
+
+public:
+ SOCKS5BytestreamClientSessionTest() : destinationAddressPort(HostAddressPort(HostAddress("127.0.0.1"), 8888)),
+ destination(SOCKS5BytestreamRegistry::getHostname("foo", JID("requester@example.com/test"), JID("target@example.com/test"))), eventLoop(NULL), timerFactory(NULL) { }
+
+ void setUp() {
+ randomGen.seed(time(NULL));
+ eventLoop = new DummyEventLoop();
+ timerFactory = new DummyTimerFactory();
+ connection = boost::make_shared<MockeryConnection>(failingPorts, true, eventLoop);
+ //connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
+ //stream1 = boost::shared_ptr<ByteArrayReadBytestream>(new ByteArrayReadBytestream(createByteArray("abcdefg")));
+// connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSessionTest::handleDataRead, this, _1));
+ }
+
+ void tearDown() {
+ //connection.reset();
+ delete timerFactory;
+ delete eventLoop;
+ }
+
+ void testForSessionReady() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
+ clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
+
+ clientSession->start();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT(createByteArray("\x05\x01\x00", 3) == helper.unprocessedInput);
+
+ helper.unprocessedInput.clear();
+ serverRespondHelloOK();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4));
+ CPPUNIT_ASSERT_EQUAL(createByteArray(destination.size()), createByteArray(helper.unprocessedInput[4]));
+ CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size()));
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1));
+
+ helper.unprocessedInput.clear();
+ serverRespondRequestOK();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
+ CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError);
+ }
+
+ void testErrorHandlingHello() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
+ clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
+
+ clientSession->start();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00", 3), helper.unprocessedInput);
+
+ helper.unprocessedInput.clear();
+ serverRespondHelloAuthFail();
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyError);
+ CPPUNIT_ASSERT_EQUAL(true, connection->disconnectCalled);
+ }
+
+ void testErrorHandlingRequest() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
+ clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
+
+ clientSession->start();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00", 3), helper.unprocessedInput);
+
+ helper.unprocessedInput.clear();
+ serverRespondHelloOK();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x05\x01\x00\x03", 4), createByteArray(&helper.unprocessedInput[0], 4));
+ CPPUNIT_ASSERT_EQUAL(createByteArray(destination.size()), createByteArray(helper.unprocessedInput[4]));
+ CPPUNIT_ASSERT_EQUAL(createByteArray(destination), createByteArray(&helper.unprocessedInput[5], destination.size()));
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\x00", 1), createByteArray(&helper.unprocessedInput[5 + destination.size()], 1));
+
+ helper.unprocessedInput.clear();
+ serverRespondRequestFail();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyError);
+ CPPUNIT_ASSERT_EQUAL(true, connection->disconnectCalled);
+ }
+
+ void testWriteBytestream() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
+ clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
+
+ clientSession->start();
+ eventLoop->processEvents();
+
+ helper.unprocessedInput.clear();
+ serverRespondHelloOK();
+ eventLoop->processEvents();
+
+ helper.unprocessedInput.clear();
+ serverRespondRequestOK();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
+ CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError);
+
+ boost::shared_ptr<ByteArrayWriteBytestream> output = boost::make_shared<ByteArrayWriteBytestream>();
+ clientSession->startReceiving(output);
+
+ ByteArray transferData = generateRandomByteArray(1024);
+ connection->onDataRead(createSafeByteArray(transferData.data(), transferData.size()));
+ CPPUNIT_ASSERT_EQUAL(transferData, output->getData());
+ }
+
+ void testReadBytestream() {
+ TestHelper helper;
+ connection->onDataSent.connect(boost::bind(&TestHelper::handleConnectionDataWritten, &helper, _1));
+
+ SOCKS5BytestreamClientSession::ref clientSession = boost::make_shared<SOCKS5BytestreamClientSession>(connection, destinationAddressPort, destination, timerFactory);
+ clientSession->onSessionReady.connect(boost::bind(&TestHelper::handleSessionReady, &helper, _1));
+
+ clientSession->start();
+ eventLoop->processEvents();
+
+ helper.unprocessedInput.clear();
+ serverRespondHelloOK();
+ eventLoop->processEvents();
+
+ helper.unprocessedInput.clear();
+ serverRespondRequestOK();
+ eventLoop->processEvents();
+ CPPUNIT_ASSERT_EQUAL(true, helper.sessionReadyCalled);
+ CPPUNIT_ASSERT_EQUAL(false, helper.sessionReadyError);
+
+ helper.unprocessedInput.clear();
+ ByteArray transferData = generateRandomByteArray(1024 * 1024);
+ boost::shared_ptr<ByteArrayReadBytestream> input = boost::make_shared<ByteArrayReadBytestream>(transferData);
+ clientSession->startSending(input);
+ eventLoop->processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(createByteArray(transferData.data(), transferData.size()), helper.unprocessedInput);
+ }
+
+
+
+private:
+ static ByteArray generateRandomByteArray(size_t len) {
+ boost::uniform_int<> dist(0, 255);
+ boost::variate_generator<boost::mt19937&, boost::uniform_int<> > randomByte(randomGen, dist);
+ ByteArray result(len);
+ for (size_t i=0; i < len; ++i ) {
+ result[i] = randomByte();
+ }
+ return result;
+ }
+
+ // Server responses
+ void serverRespondHelloOK() {
+ connection->onDataRead(createSafeByteArray("\x05\00", 2));
+ }
+
+ void serverRespondHelloAuthFail() {
+ connection->onDataRead(createSafeByteArray("\x05\xFF", 2));
+ }
+
+ void serverRespondRequestOK() {
+ SafeByteArray dataToSend = createSafeByteArray("\x05\x00\x00\x03", 4);
+ append(dataToSend, createSafeByteArray(destination.size()));
+ append(dataToSend, createSafeByteArray(destination));
+ append(dataToSend, createSafeByteArray("\x00", 1));
+ connection->onDataRead(dataToSend);
+ }
+
+ void serverRespondRequestFail() {
+ SafeByteArray correctData = createSafeByteArray("\x05\x00\x00\x03", 4);
+ append(correctData, createSafeByteArray(destination.size()));
+ append(correctData, createSafeByteArray(destination));
+ append(correctData, createSafeByteArray("\x00", 1));
+
+ SafeByteArray dataToSend;
+ //ByteArray failingData = Hexify::unhexify("8417947d1d305c72c11520ea7d2c6e787396705e72c312c6ccc3f66613d7cae1b91b7ab48e8b59a17d559c15fb51");
+ //append(dataToSend, failingData);
+ //SWIFT_LOG(debug) << "hexed: " << Hexify::hexify(failingData) << std::endl;
+ do {
+ ByteArray rndArray = generateRandomByteArray(correctData.size());
+ dataToSend = createSafeByteArray(rndArray.data(), rndArray.size());
+ } while (dataToSend == correctData);
+ connection->onDataRead(dataToSend);
+ }
+
+private:
+ struct TestHelper {
+ TestHelper() : sessionReadyCalled(false), sessionReadyError(false) {}
+ ByteArray unprocessedInput;
+ bool sessionReadyCalled;
+ bool sessionReadyError;
+
+ void handleConnectionDataWritten(const SafeByteArray& data) {
+ append(unprocessedInput, data);
+ //SWIFT_LOG(debug) << "unprocessedInput (" << unprocessedInput.size() << "): " << Hexify::hexify(unprocessedInput) << std::endl;
+ }
+
+ void handleSessionReady(bool error) {
+ sessionReadyCalled = true;
+ sessionReadyError = error;
+ }
+ };
+
+
+private:
+ struct MockeryConnection : public Connection, public EventOwner, public boost::enable_shared_from_this<MockeryConnection> {
+ public:
+ MockeryConnection(const std::vector<HostAddressPort>& failingPorts, bool isResponsive, EventLoop* eventLoop) : eventLoop(eventLoop), failingPorts(failingPorts), isResponsive(isResponsive), disconnectCalled(false) {}
+
+ void listen() { assert(false); }
+ void connect(const HostAddressPort& address) {
+ hostAddressPort = address;
+ if (isResponsive) {
+ bool fail = std::find(failingPorts.begin(), failingPorts.end(), address) != failingPorts.end();
+ eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), fail));
+ }
+ }
+
+ HostAddressPort getLocalAddress() const { return HostAddressPort(); }
+ void disconnect() {
+ disconnectCalled = true;
+ }
+
+ void write(const SafeByteArray& data) {
+ eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this());
+ onDataSent(data);
+ }
+
+ boost::signal<void (const SafeByteArray&)> onDataSent;
+
+ EventLoop* eventLoop;
+ boost::optional<HostAddressPort> hostAddressPort;
+ std::vector<HostAddressPort> failingPorts;
+ bool isResponsive;
+ bool disconnectCalled;
+ };
+
+private:
+ DummyEventLoop* eventLoop;
+ DummyTimerFactory* timerFactory;
+ boost::shared_ptr<MockeryConnection> connection;
+ const std::vector<HostAddressPort> failingPorts;
+};
+
+CPPUNIT_TEST_SUITE_REGISTRATION(SOCKS5BytestreamClientSessionTest);
diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
index 06bc98f..cd480f0 100644
--- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamServerSessionTest.cpp
@@ -34,6 +34,7 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
void setUp() {
receivedDataChunks = 0;
eventLoop = new DummyEventLoop();
+ bytestreams = new SOCKS5BytestreamRegistry();
connection = boost::shared_ptr<DummyConnection>(new DummyConnection(eventLoop));
connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1));
stream1 = boost::shared_ptr<ByteArrayReadBytestream>(new ByteArrayReadBytestream(createByteArray("abcdefg")));
@@ -41,6 +42,7 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
void tearDown() {
connection.reset();
+ delete bytestreams;
delete eventLoop;
}
@@ -67,7 +69,7 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
void testRequest() {
boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
- bytestreams.addBytestream("abcdef", stream1);
+ bytestreams->addReadBytestream("abcdef", stream1);
authenticate();
ByteArray hostname(createByteArray("abcdef"));
@@ -88,10 +90,11 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
void testReceiveData() {
boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
- bytestreams.addBytestream("abcdef", stream1);
+ bytestreams->addReadBytestream("abcdef", stream1);
authenticate();
request("abcdef");
eventLoop->processEvents();
+ testling->startTransfer();
skipHeader("abcdef");
CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData);
@@ -102,11 +105,12 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
boost::shared_ptr<SOCKS5BytestreamServerSession> testling(createSession());
testling->setChunkSize(3);
StartStopper<SOCKS5BytestreamServerSession> stopper(testling.get());
- bytestreams.addBytestream("abcdef", stream1);
+ bytestreams->addReadBytestream("abcdef", stream1);
authenticate();
request("abcdef");
eventLoop->processEvents();
-
+ testling->startTransfer();
+ eventLoop->processEvents();
skipHeader("abcdef");
CPPUNIT_ASSERT(createByteArray("abcdefg") == receivedData);
CPPUNIT_ASSERT_EQUAL(4, receivedDataChunks);
@@ -141,13 +145,13 @@ class SOCKS5BytestreamServerSessionTest : public CppUnit::TestFixture {
private:
SOCKS5BytestreamServerSession* createSession() {
- SOCKS5BytestreamServerSession* session = new SOCKS5BytestreamServerSession(connection, &bytestreams);
+ SOCKS5BytestreamServerSession* session = new SOCKS5BytestreamServerSession(connection, bytestreams);
return session;
}
private:
DummyEventLoop* eventLoop;
- SOCKS5BytestreamRegistry bytestreams;
+ SOCKS5BytestreamRegistry* bytestreams;
boost::shared_ptr<DummyConnection> connection;
std::vector<unsigned char> receivedData;
int receivedDataChunks;
diff --git a/Swiften/FileTransfer/WriteBytestream.h b/Swiften/FileTransfer/WriteBytestream.h
index c27aeff..fb6f2f1 100644
--- a/Swiften/FileTransfer/WriteBytestream.h
+++ b/Swiften/FileTransfer/WriteBytestream.h
@@ -9,6 +9,8 @@
#include <boost/shared_ptr.hpp>
#include <vector>
+#include <Swiften/Base/boost_bsignals.h>
+
namespace Swift {
class WriteBytestream {
public:
@@ -17,5 +19,7 @@ namespace Swift {
virtual ~WriteBytestream();
virtual void write(const std::vector<unsigned char>&) = 0;
+
+ boost::signal<void (const std::vector<unsigned char>&)> onWrite;
};
}
diff --git a/Swiften/Jingle/FakeJingleSession.cpp b/Swiften/Jingle/FakeJingleSession.cpp
new file mode 100644
index 0000000..82ec631
--- /dev/null
+++ b/Swiften/Jingle/FakeJingleSession.cpp
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Jingle/FakeJingleSession.h>
+
+#include <boost/smart_ptr/make_shared.hpp>
+
+namespace Swift {
+
+FakeJingleSession::FakeJingleSession(const JID& initiator, const std::string& id) : JingleSession(initiator, id) {
+
+}
+
+FakeJingleSession::~FakeJingleSession() {
+}
+
+void FakeJingleSession::sendInitiate(const JingleContentID& id, JingleDescription::ref desc, JingleTransportPayload::ref payload) {
+ calledCommands.push_back(InitiateCall(id, desc, payload));
+}
+
+void FakeJingleSession::sendTerminate(JinglePayload::Reason::Type reason) {
+ calledCommands.push_back(TerminateCall(reason));
+}
+
+void FakeJingleSession::sendInfo(boost::shared_ptr<Payload> payload) {
+ calledCommands.push_back(InfoCall(payload));
+}
+
+void FakeJingleSession::sendAccept(const JingleContentID& id, JingleDescription::ref desc, JingleTransportPayload::ref payload) {
+ calledCommands.push_back(AcceptCall(id, desc, payload));
+}
+
+void FakeJingleSession::sendTransportInfo(const JingleContentID& id, JingleTransportPayload::ref payload) {
+ calledCommands.push_back(InfoTransportCall(id, payload));
+}
+
+void FakeJingleSession::sendTransportAccept(const JingleContentID& id, JingleTransportPayload::ref payload) {
+ calledCommands.push_back(AcceptTransportCall(id, payload));
+}
+
+void FakeJingleSession::sendTransportReject(const JingleContentID& id, JingleTransportPayload::ref payload) {
+ calledCommands.push_back(RejectTransportCall(id, payload));
+}
+
+void FakeJingleSession::sendTransportReplace(const JingleContentID& id, JingleTransportPayload::ref payload) {
+ calledCommands.push_back(ReplaceTransportCall(id, payload));
+}
+
+}
diff --git a/Swiften/Jingle/FakeJingleSession.h b/Swiften/Jingle/FakeJingleSession.h
new file mode 100644
index 0000000..fd3d7b7
--- /dev/null
+++ b/Swiften/Jingle/FakeJingleSession.h
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <boost/shared_ptr.hpp>
+#include <string>
+#include <vector>
+#include <boost/variant.hpp>
+
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/JID/JID.h>
+#include <Swiften/Elements/JinglePayload.h>
+#include <Swiften/Jingle/JingleSession.h>
+#include <Swiften/Jingle/JingleContentID.h>
+
+namespace Swift {
+ class JingleContentID;
+
+ class FakeJingleSession : public JingleSession {
+ public:
+ struct InitiateCall {
+ InitiateCall(JingleContentID contentId, JingleDescription::ref desc, JingleTransportPayload::ref payL) : id(contentId), description(desc), payload(payL) {}
+ JingleContentID id;
+ JingleDescription::ref description;
+ JingleTransportPayload::ref payload;
+ };
+
+ struct TerminateCall {
+ TerminateCall(JinglePayload::Reason::Type r) : reason(r) {}
+ JinglePayload::Reason::Type reason;
+ };
+
+ struct InfoCall {
+ InfoCall(boost::shared_ptr<Payload> info) : payload(info) {}
+ boost::shared_ptr<Payload> payload;
+ };
+
+ struct AcceptCall {
+ AcceptCall(JingleContentID contentId, JingleDescription::ref desc, JingleTransportPayload::ref payL) : id(contentId), description(desc), payload(payL) {}
+ JingleContentID id;
+ JingleDescription::ref description;
+ JingleTransportPayload::ref payload;
+ };
+
+ struct InfoTransportCall {
+ InfoTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
+ JingleContentID id;
+ JingleTransportPayload::ref payload;
+ };
+
+ struct AcceptTransportCall {
+ AcceptTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
+ JingleContentID id;
+ JingleTransportPayload::ref payload;
+ };
+
+ struct RejectTransportCall {
+ RejectTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
+ JingleContentID id;
+ JingleTransportPayload::ref payload;
+ };
+
+ struct ReplaceTransportCall {
+ ReplaceTransportCall(JingleContentID contentId, JingleTransportPayload::ref payL) : id(contentId), payload(payL) {}
+ JingleContentID id;
+ JingleTransportPayload::ref payload;
+ };
+
+ typedef boost::variant<InitiateCall, TerminateCall, AcceptCall, InfoCall, InfoTransportCall, AcceptTransportCall, RejectTransportCall, ReplaceTransportCall> Command;
+
+ public:
+ typedef boost::shared_ptr<FakeJingleSession> ref;
+
+ FakeJingleSession(const JID& initiator, const std::string& id);
+ virtual ~FakeJingleSession();
+
+ virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref);
+ virtual void sendTerminate(JinglePayload::Reason::Type reason);
+ virtual void sendInfo(boost::shared_ptr<Payload>);
+ virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref());
+ virtual void sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref);
+ virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref);
+ virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref);
+ virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref);
+
+ public:
+ std::vector<Command> calledCommands;
+ };
+}
diff --git a/Swiften/Jingle/JingleContentID.h b/Swiften/Jingle/JingleContentID.h
index 8d75581..fc0cc8f 100644
--- a/Swiften/Jingle/JingleContentID.h
+++ b/Swiften/Jingle/JingleContentID.h
@@ -15,6 +15,14 @@ namespace Swift {
public:
JingleContentID(const std::string& name, JingleContentPayload::Creator creator) : name(name), creator(creator) {
}
+
+ const std::string getName() const {
+ return this->name;
+ }
+
+ JingleContentPayload::Creator getCreator() const {
+ return this->creator;
+ }
private:
std::string name;
diff --git a/Swiften/Jingle/JingleResponder.cpp b/Swiften/Jingle/JingleResponder.cpp
index 198f9a2..63f108e 100644
--- a/Swiften/Jingle/JingleResponder.cpp
+++ b/Swiften/Jingle/JingleResponder.cpp
@@ -11,9 +11,14 @@
#include <Swiften/Jingle/JingleSessionManager.h>
#include <Swiften/Jingle/JingleSessionImpl.h>
+#include <Swiften/Base/Log.h>
+
namespace Swift {
-JingleResponder::JingleResponder(JingleSessionManager* sessionManager, IQRouter* router) : SetResponder<JinglePayload>(router), sessionManager(sessionManager) {
+JingleResponder::JingleResponder(JingleSessionManager* sessionManager, IQRouter* router) : SetResponder<JinglePayload>(router), sessionManager(sessionManager), router(router) {
+}
+
+JingleResponder::~JingleResponder() {
}
bool JingleResponder::handleSetRequest(const JID& from, const JID&, const std::string& id, boost::shared_ptr<JinglePayload> payload) {
@@ -24,17 +29,29 @@ bool JingleResponder::handleSetRequest(const JID& from, const JID&, const std::s
}
else {
sendResponse(from, id, boost::shared_ptr<JinglePayload>());
- JingleSessionImpl::ref session = boost::make_shared<JingleSessionImpl>(payload->getInitiator(), payload->getSessionID());
- sessionManager->handleIncomingSession(from, session, payload->getContents());
+ if (!payload->getInitiator().isBare()) {
+ JingleSessionImpl::ref session = boost::make_shared<JingleSessionImpl>(payload->getInitiator(), from, payload->getSessionID(), router);
+ sessionManager->handleIncomingSession(from, session, payload->getContents());
+ } else {
+ SWIFT_LOG(debug) << "Unable to create Jingle session due to initiator not being a full JID." << std::endl;
+ }
}
}
else {
- JingleSessionImpl::ref session = sessionManager->getSession(from, payload->getSessionID());
+ JingleSessionImpl::ref session;
+ if (payload->getInitiator().isValid()) {
+ SWIFT_LOG(debug) << "Lookup session by initiator." << std::endl;
+ session = sessionManager->getSession(payload->getInitiator(), payload->getSessionID());
+ } else {
+ SWIFT_LOG(debug) << "Lookup session by from attribute." << std::endl;
+ session = sessionManager->getSession(from, payload->getSessionID());
+ }
if (session) {
session->handleIncomingAction(payload);
sendResponse(from, id, boost::shared_ptr<JinglePayload>());
}
else {
+ std::cerr << "WARN: Didn't find jingle session!" << std::endl;
// TODO: Add jingle-specific error
sendError(from, id, ErrorPayload::ItemNotFound, ErrorPayload::Cancel);
}
diff --git a/Swiften/Jingle/JingleResponder.h b/Swiften/Jingle/JingleResponder.h
index 6e1965c..6f4d688 100644
--- a/Swiften/Jingle/JingleResponder.h
+++ b/Swiften/Jingle/JingleResponder.h
@@ -16,11 +16,12 @@ namespace Swift {
class JingleResponder : public SetResponder<JinglePayload> {
public:
JingleResponder(JingleSessionManager* sessionManager, IQRouter* router);
-
+ virtual ~JingleResponder();
private:
virtual bool handleSetRequest(const JID& from, const JID& to, const std::string& id, boost::shared_ptr<JinglePayload> payload);
private:
JingleSessionManager* sessionManager;
+ IQRouter* router;
};
}
diff --git a/Swiften/Jingle/JingleSession.cpp b/Swiften/Jingle/JingleSession.cpp
index 1366191..eb649f3 100644
--- a/Swiften/Jingle/JingleSession.cpp
+++ b/Swiften/Jingle/JingleSession.cpp
@@ -11,7 +11,9 @@
namespace Swift {
JingleSession::JingleSession(const JID& initiator, const std::string& id) : initiator(initiator), id(id) {
-
+ // initiator must always be a full JID; session lookup based on it wouldn't work otherwise
+ // this is checked on an upper level so that the assert never fails
+ assert(!initiator.isBare());
}
JingleSession::~JingleSession() {
diff --git a/Swiften/Jingle/JingleSession.h b/Swiften/Jingle/JingleSession.h
index b8117bb..150ad79 100644
--- a/Swiften/Jingle/JingleSession.h
+++ b/Swiften/Jingle/JingleSession.h
@@ -7,6 +7,8 @@
#pragma once
#include <boost/shared_ptr.hpp>
+#include <boost/optional.hpp>
+
#include <string>
#include <Swiften/Base/boost_bsignals.h>
@@ -30,16 +32,22 @@ namespace Swift {
const std::string& getID() const {
return id;
}
-
- virtual void terminate(JinglePayload::Reason::Type reason) = 0;
- virtual void accept(JingleTransportPayload::ref = JingleTransportPayload::ref()) = 0;
+ virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) = 0;
+ virtual void sendTerminate(JinglePayload::Reason::Type reason) = 0;
+ virtual void sendInfo(boost::shared_ptr<Payload>) = 0;
+ virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) = 0;
virtual void sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) = 0;
- virtual void acceptTransport(const JingleContentID&, JingleTransportPayload::ref) = 0;
- virtual void rejectTransport(const JingleContentID&, JingleTransportPayload::ref) = 0;
+ virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) = 0;
+ virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) = 0;
+ virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) = 0;
public:
- boost::signal<void ()> onSessionTerminateReceived;
+ boost::signal<void (const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref)> onSessionAcceptReceived;
+ boost::signal<void (JinglePayload::ref)> onSessionInfoReceived;
+ boost::signal<void (boost::optional<JinglePayload::Reason>)> onSessionTerminateReceived;
+ boost::signal<void (const JingleContentID&, JingleTransportPayload::ref)> onTransportAcceptReceived;
boost::signal<void (const JingleContentID&, JingleTransportPayload::ref)> onTransportInfoReceived;
+ boost::signal<void (const JingleContentID&, JingleTransportPayload::ref)> onTransportRejectReceived;
boost::signal<void (const JingleContentID&, JingleTransportPayload::ref)> onTransportReplaceReceived;
private:
diff --git a/Swiften/Jingle/JingleSessionImpl.cpp b/Swiften/Jingle/JingleSessionImpl.cpp
index cbb2b42..98c5196 100644
--- a/Swiften/Jingle/JingleSessionImpl.cpp
+++ b/Swiften/Jingle/JingleSessionImpl.cpp
@@ -8,33 +8,176 @@
#include <boost/smart_ptr/make_shared.hpp>
+#include <Swiften/Parser/PayloadParsers/JingleParser.h>
+#include <Swiften/Jingle/JingleContentID.h>
+#include <Swiften/Elements/JingleContentPayload.h>
+#include <Swiften/Queries/Request.h>
+#include <Swiften/Queries/GenericRequest.h>
+
+#include <Swiften/Base/Log.h>
+
+#include "Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h"
+#include "Swiften/FileTransfer/JingleTransport.h"
+
namespace Swift {
-JingleSessionImpl::JingleSessionImpl(const JID& initiator, const std::string& id) : JingleSession(initiator, id) {
+JingleSessionImpl::JingleSessionImpl(const JID& initiator, const JID& peerJID, const std::string& id, IQRouter* router) : JingleSession(initiator, id), iqRouter(router), peerJID(peerJID) {
+ SWIFT_LOG(debug) << "initiator: " << initiator << ", peerJID: " << peerJID << std::endl;
+}
+
+void JingleSessionImpl::handleIncomingAction(JinglePayload::ref action) {
+ if (action->getAction() == JinglePayload::SessionTerminate) {
+ onSessionTerminateReceived(action->getReason());
+ return;
+ }
+ if (action->getAction() == JinglePayload::SessionInfo) {
+ onSessionInfoReceived(action);
+ return;
+ }
+
+ JingleContentPayload::ref content = action->getPayload<JingleContentPayload>();
+ if (!content) {
+ SWIFT_LOG(debug) << "no content payload!" << std::endl;
+ return;
+ }
+ JingleContentID contentID(content->getName(), content->getCreator());
+ JingleDescription::ref description = content->getDescriptions().empty() ? JingleDescription::ref() : content->getDescriptions()[0];
+ JingleTransportPayload::ref transport = content->getTransports().empty() ? JingleTransportPayload::ref() : content->getTransports()[0];
+ switch(action->getAction()) {
+ case JinglePayload::SessionAccept:
+ onSessionAcceptReceived(contentID, description, transport);
+ return;
+ case JinglePayload::TransportAccept:
+ onTransportAcceptReceived(contentID, transport);
+ return;
+ case JinglePayload::TransportInfo:
+ onTransportInfoReceived(contentID, transport);
+ return;
+ case JinglePayload::TransportReject:
+ onTransportRejectReceived(contentID, transport);
+ return;
+ case JinglePayload::TransportReplace:
+ onTransportReplaceReceived(contentID, transport);
+ return;
+ // following unused Jingle actions
+ case JinglePayload::ContentAccept:
+ case JinglePayload::ContentAdd:
+ case JinglePayload::ContentModify:
+ case JinglePayload::ContentReject:
+ case JinglePayload::ContentRemove:
+ case JinglePayload::DescriptionInfo:
+ case JinglePayload::SecurityInfo:
+
+ // handled elsewhere
+ case JinglePayload::SessionInitiate:
+ case JinglePayload::SessionInfo:
+ case JinglePayload::SessionTerminate:
+
+ case JinglePayload::UnknownAction:
+ return;
+ }
+ std::cerr << "Unhandled Jingle action!!! ACTION: " << action->getAction() << std::endl;
}
-void JingleSessionImpl::handleIncomingAction(JinglePayload::ref) {
+void JingleSessionImpl::sendInitiate(const JingleContentID& id, JingleDescription::ref description, JingleTransportPayload::ref transport) {
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionInitiate, getID());
+ payload->setInitiator(getInitiator());
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addDescription(description);
+ content->addTransport(transport);
+ payload->addPayload(content);
+
+ sendSetRequest(payload);
}
-void JingleSessionImpl::terminate(JinglePayload::Reason::Type reason) {
+void JingleSessionImpl::sendTerminate(JinglePayload::Reason::Type reason) {
JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionTerminate, getID());
payload->setReason(JinglePayload::Reason(reason));
- //onAction(payload)
+ payload->setInitiator(getInitiator());
+ sendSetRequest(payload);
+}
+
+void JingleSessionImpl::sendInfo(boost::shared_ptr<Payload> info) {
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>(JinglePayload::SessionInfo, getID());
+ payload->addPayload(info);
+
+ sendSetRequest(payload);
+}
+
+void JingleSessionImpl::sendAccept(const JingleContentID& id, JingleDescription::ref description, JingleTransportPayload::ref transPayload) {
+ JinglePayload::ref payload = createPayload();
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addTransport(transPayload);
+ content->addDescription(description);
+ payload->setAction(JinglePayload::SessionAccept);
+ payload->addPayload(content);
+
+ // put into IQ:set and send it away
+ sendSetRequest(payload);
}
-void JingleSessionImpl::acceptTransport(const JingleContentID&, JingleTransportPayload::ref) {
+void JingleSessionImpl::sendTransportAccept(const JingleContentID& id, JingleTransportPayload::ref transPayload) {
+ JinglePayload::ref payload = createPayload();
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addTransport(transPayload);
+ payload->setAction(JinglePayload::TransportAccept);
+ payload->addPayload(content);
+
+ // put into IQ:set and send it away
+ sendSetRequest(payload);
+}
+
+void JingleSessionImpl::sendTransportInfo(const JingleContentID& id, JingleTransportPayload::ref transPayload) {
+ JinglePayload::ref payload = createPayload();
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addTransport(transPayload);
+ payload->setAction(JinglePayload::TransportInfo);
+ payload->addPayload(content);
+
+ sendSetRequest(payload);
+}
+
+void JingleSessionImpl::sendTransportReject(const JingleContentID& /* id */, JingleTransportPayload::ref /* transPayload */) {
+ SWIFT_LOG(debug) << "NOT IMPLEMENTED YET!!!!" << std::endl;
}
-void JingleSessionImpl::rejectTransport(const JingleContentID&, JingleTransportPayload::ref) {
+void JingleSessionImpl::sendTransportReplace(const JingleContentID& id, JingleTransportPayload::ref transPayload) {
+ JinglePayload::ref payload = createPayload();
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(id.getCreator());
+ content->setName(id.getName());
+ content->addTransport(transPayload);
+ payload->setAction(JinglePayload::TransportReplace);
+ payload->addContent(content);
+
+ sendSetRequest(payload);
}
-void JingleSessionImpl::accept(JingleTransportPayload::ref) {
+
+void JingleSessionImpl::sendSetRequest(JinglePayload::ref payload) {
+ boost::shared_ptr<GenericRequest<JinglePayload> > request = boost::make_shared<GenericRequest<JinglePayload> >(IQ::Set, peerJID, payload, iqRouter);
+ request->send();
}
-void JingleSessionImpl::sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) {
+JinglePayload::ref JingleSessionImpl::createPayload() const {
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setSessionID(getID());
+ payload->setInitiator(getInitiator());
+ return payload;
}
diff --git a/Swiften/Jingle/JingleSessionImpl.h b/Swiften/Jingle/JingleSessionImpl.h
index a254ead..3c1559a 100644
--- a/Swiften/Jingle/JingleSessionImpl.h
+++ b/Swiften/Jingle/JingleSessionImpl.h
@@ -11,20 +11,32 @@
#include <Swiften/Jingle/JingleSession.h>
namespace Swift {
+ class IQRouter;
+
class JingleSessionImpl : public JingleSession {
friend class JingleResponder;
public:
typedef boost::shared_ptr<JingleSessionImpl> ref;
- JingleSessionImpl(const JID& initiator, const std::string& id);
+ JingleSessionImpl(const JID& initiator, const JID&, const std::string& id, IQRouter* router);
- virtual void terminate(JinglePayload::Reason::Type reason);
- virtual void accept(JingleTransportPayload::ref);
+ virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref);
+ virtual void sendTerminate(JinglePayload::Reason::Type reason);
+ virtual void sendInfo(boost::shared_ptr<Payload>);
+ virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref);
virtual void sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref);
- virtual void acceptTransport(const JingleContentID&, JingleTransportPayload::ref);
- virtual void rejectTransport(const JingleContentID&, JingleTransportPayload::ref);
+ virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref);
+ virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref);
+ virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref);
private:
void handleIncomingAction(JinglePayload::ref);
+
+ void sendSetRequest(JinglePayload::ref payload);
+ JinglePayload::ref createPayload() const;
+
+ private:
+ IQRouter *iqRouter;
+ JID peerJID;
};
}
diff --git a/Swiften/Jingle/JingleSessionManager.cpp b/Swiften/Jingle/JingleSessionManager.cpp
index f9a94f3..4299a1e 100644
--- a/Swiften/Jingle/JingleSessionManager.cpp
+++ b/Swiften/Jingle/JingleSessionManager.cpp
@@ -14,15 +14,17 @@ namespace Swift {
JingleSessionManager::JingleSessionManager(IQRouter* router) : router(router) {
responder = new JingleResponder(this, router);
+ responder->start();
}
JingleSessionManager::~JingleSessionManager() {
+ responder->stop();
delete responder;
}
JingleSessionImpl::ref JingleSessionManager::getSession(const JID& jid, const std::string& id) const {
- SessionMap::const_iterator i = incomingSessions.find(JIDSession(jid, id));
- return i != incomingSessions.end() ? i->second : JingleSessionImpl::ref();
+ SessionMap::const_iterator i = sessions.find(JIDSession(jid, id));
+ return i != sessions.end() ? i->second : JingleSessionImpl::ref();
}
void JingleSessionManager::addIncomingSessionHandler(IncomingJingleSessionHandler* handler) {
@@ -33,8 +35,13 @@ void JingleSessionManager::removeIncomingSessionHandler(IncomingJingleSessionHan
erase(incomingSessionHandlers, handler);
}
-void JingleSessionManager::handleIncomingSession(const JID& from, JingleSessionImpl::ref session, const std::vector<JingleContentPayload::ref>& contents) {
- incomingSessions.insert(std::make_pair(JIDSession(from, session->getID()), session));
+void JingleSessionManager::registerOutgoingSession(const JID& initiator, JingleSessionImpl::ref session) {
+ sessions.insert(std::make_pair(JIDSession(initiator, session->getID()), session));
+ SWIFT_LOG(debug) << "Added session " << session->getID() << " for initiator " << initiator.toString() << std::endl;
+}
+
+void JingleSessionManager::handleIncomingSession(const JID& initiator, JingleSessionImpl::ref session, const std::vector<JingleContentPayload::ref>& contents) {
+ sessions.insert(std::make_pair(JIDSession(initiator, session->getID()), session));
foreach (IncomingJingleSessionHandler* handler, incomingSessionHandlers) {
if (handler->handleIncomingJingleSession(session, contents)) {
return;
diff --git a/Swiften/Jingle/JingleSessionManager.h b/Swiften/Jingle/JingleSessionManager.h
index 3b23fb0..50c429b 100644
--- a/Swiften/Jingle/JingleSessionManager.h
+++ b/Swiften/Jingle/JingleSessionManager.h
@@ -28,22 +28,23 @@ namespace Swift {
void addIncomingSessionHandler(IncomingJingleSessionHandler* handler);
void removeIncomingSessionHandler(IncomingJingleSessionHandler* handler);
+ void registerOutgoingSession(const JID& initiator, JingleSessionImpl::ref);
protected:
- void handleIncomingSession(const JID& from, JingleSessionImpl::ref, const std::vector<JingleContentPayload::ref>& contents);
+ void handleIncomingSession(const JID& initiator, JingleSessionImpl::ref, const std::vector<JingleContentPayload::ref>& contents);
private:
IQRouter* router;
JingleResponder* responder;
std::vector<IncomingJingleSessionHandler*> incomingSessionHandlers;
struct JIDSession {
- JIDSession(const JID& jid, const std::string& session) : jid(jid), session(session) {}
+ JIDSession(const JID& initiator, const std::string& session) : initiator(initiator), session(session) {}
bool operator<(const JIDSession& o) const {
- return jid == o.jid ? session < o.session : jid < o.jid;
+ return initiator == o.initiator ? session < o.session : initiator < o.initiator;
}
- JID jid;
+ JID initiator;
std::string session;
};
typedef std::map<JIDSession, JingleSessionImpl::ref> SessionMap;
- SessionMap incomingSessions;
+ SessionMap sessions;
};
}
diff --git a/Swiften/Jingle/SConscript b/Swiften/Jingle/SConscript
index 6b3cfd3..5dcf293 100644
--- a/Swiften/Jingle/SConscript
+++ b/Swiften/Jingle/SConscript
@@ -6,6 +6,7 @@ sources = [
"IncomingJingleSessionHandler.cpp",
"JingleSessionManager.cpp",
"JingleResponder.cpp",
+ "FakeJingleSession.cpp",
]
swiften_env.Append(SWIFTEN_OBJECTS = swiften_env.SwiftenObject(sources))
diff --git a/Swiften/Network/BoostNetworkFactories.cpp b/Swiften/Network/BoostNetworkFactories.cpp
index cc80197..c13270f 100644
--- a/Swiften/Network/BoostNetworkFactories.cpp
+++ b/Swiften/Network/BoostNetworkFactories.cpp
@@ -9,6 +9,7 @@
#include <Swiften/Network/BoostConnectionFactory.h>
#include <Swiften/Network/PlatformDomainNameResolver.h>
#include <Swiften/Network/BoostConnectionServerFactory.h>
+#include <Swiften/Network/PlatformNATTraversalWorker.h>
namespace Swift {
@@ -17,9 +18,11 @@ BoostNetworkFactories::BoostNetworkFactories(EventLoop* eventLoop) {
connectionFactory = new BoostConnectionFactory(ioServiceThread.getIOService(), eventLoop);
domainNameResolver = new PlatformDomainNameResolver(eventLoop);
connectionServerFactory = new BoostConnectionServerFactory(ioServiceThread.getIOService(), eventLoop);
+ platformNATTraversalWorker = new PlatformNATTraversalWorker(eventLoop);
}
BoostNetworkFactories::~BoostNetworkFactories() {
+ delete platformNATTraversalWorker;
delete connectionServerFactory;
delete domainNameResolver;
delete connectionFactory;
diff --git a/Swiften/Network/BoostNetworkFactories.h b/Swiften/Network/BoostNetworkFactories.h
index 96bcc6c..a1cf9ae 100644
--- a/Swiften/Network/BoostNetworkFactories.h
+++ b/Swiften/Network/BoostNetworkFactories.h
@@ -37,11 +37,16 @@ namespace Swift {
return connectionServerFactory;
}
+ PlatformNATTraversalWorker* getPlatformNATTraversalWorker() const {
+ return platformNATTraversalWorker;
+ }
+
private:
BoostIOServiceThread ioServiceThread;
TimerFactory* timerFactory;
ConnectionFactory* connectionFactory;
DomainNameResolver* domainNameResolver;
ConnectionServerFactory* connectionServerFactory;
+ PlatformNATTraversalWorker* platformNATTraversalWorker;
};
}
diff --git a/Swiften/Network/DummyConnectionFactory.h b/Swiften/Network/DummyConnectionFactory.h
new file mode 100644
index 0000000..e8a294e
--- /dev/null
+++ b/Swiften/Network/DummyConnectionFactory.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Network/ConnectionFactory.h>
+#include <Swiften/Network/DummyConnection.h>
+
+namespace Swift {
+
+class EventLoop;
+
+class DummyConnectionFactory : public ConnectionFactory {
+public:
+ DummyConnectionFactory(EventLoop *eventLoop) : eventLoop(eventLoop) {}
+ virtual ~DummyConnectionFactory() {}
+ virtual boost::shared_ptr<Connection> createConnection() {
+ return boost::make_shared<DummyConnection>(eventLoop);
+ }
+private:
+ EventLoop* eventLoop;
+};
+
+}
diff --git a/Swiften/Network/NATPMPNATTraversalForwardPortRequest.cpp b/Swiften/Network/NATPMPNATTraversalForwardPortRequest.cpp
new file mode 100644
index 0000000..69b325c
--- /dev/null
+++ b/Swiften/Network/NATPMPNATTraversalForwardPortRequest.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "NATPMPNATTraversalForwardPortRequest.h"
+
+#include <natpmp.h>
+
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+
+NATPMPNATTraversalForwardPortRequest::NATPMPNATTraversalForwardPortRequest(PlatformNATTraversalForwardPortRequest::PortMapping mapping, PlatformNATTraversalWorker* worker) : PlatformNATTraversalForwardPortRequest(worker), mapping(mapping) {
+
+}
+
+NATPMPNATTraversalForwardPortRequest::~NATPMPNATTraversalForwardPortRequest() {
+
+}
+
+void NATPMPNATTraversalForwardPortRequest::runBlocking() {
+ boost::optional<PortMapping> result;
+
+ natpmp_t natpmp;
+ natpmpresp_t response;
+ initnatpmp(&natpmp, 0, 0);
+
+ do {
+ if (sendnewportmappingrequest(&natpmp, mapping.protocol == PortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, mapping.leaseInSeconds, mapping.publicPort, mapping.localPort) != 2) {
+ SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl;
+ break;
+ }
+ int r = 0;
+
+ do {
+ fd_set fds;
+ struct timeval timeout;
+ FD_ZERO(&fds);
+ FD_SET(natpmp.s, &fds);
+ getnatpmprequesttimeout(&natpmp, &timeout);
+ select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
+ r = readnatpmpresponseorretry(&natpmp, &response);
+ } while(r == NATPMP_TRYAGAIN);
+
+ if (r == 0) {
+ if (response.pnu.newportmapping.privateport == mapping.localPort &&
+ response.pnu.newportmapping.mappedpublicport == mapping.publicPort) {
+ mapping.leaseInSeconds = response.pnu.newportmapping.lifetime;
+ result = boost::optional<PortMapping>(mapping);
+ }
+ } else {
+ SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl;
+ }
+ } while(false);
+ closenatpmp(&natpmp);
+
+ onResult(result);
+}
+
+}
diff --git a/Swiften/Network/NATPMPNATTraversalForwardPortRequest.h b/Swiften/Network/NATPMPNATTraversalForwardPortRequest.h
new file mode 100644
index 0000000..71d8621
--- /dev/null
+++ b/Swiften/Network/NATPMPNATTraversalForwardPortRequest.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Network/PlatformNATTraversalForwardPortRequest.h>
+
+namespace Swift {
+
+class NATPMPNATTraversalForwardPortRequest : public PlatformNATTraversalForwardPortRequest {
+public:
+ NATPMPNATTraversalForwardPortRequest(PlatformNATTraversalForwardPortRequest::PortMapping, PlatformNATTraversalWorker*);
+ virtual ~NATPMPNATTraversalForwardPortRequest();
+
+ virtual void runBlocking();
+
+private:
+ PlatformNATTraversalForwardPortRequest::PortMapping mapping;
+};
+
+}
diff --git a/Swiften/Network/NATPMPNATTraversalGetPublicIPRequest.cpp b/Swiften/Network/NATPMPNATTraversalGetPublicIPRequest.cpp
new file mode 100644
index 0000000..06a21a3
--- /dev/null
+++ b/Swiften/Network/NATPMPNATTraversalGetPublicIPRequest.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "NATPMPNATTraversalGetPublicIPRequest.h"
+
+#include <natpmp.h>
+
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+
+NATPMPNATTraversalGetPublicIPRequest::NATPMPNATTraversalGetPublicIPRequest(PlatformNATTraversalWorker* worker) : PlatformNATTraversalGetPublicIPRequest(worker) {
+
+}
+
+NATPMPNATTraversalGetPublicIPRequest::~NATPMPNATTraversalGetPublicIPRequest() {
+
+}
+
+/*
+TODO: a non-blocking solution should be possible too here
+void NATPMPNATTraversalGetPublicIPRequest::run() {
+ // we can run directly since libnatpmp's API is asynchronous
+ runBlocking();
+}*/
+
+void NATPMPNATTraversalGetPublicIPRequest::runBlocking() {
+ boost::optional<HostAddress> result;
+
+ natpmp_t natpmp;
+ natpmpresp_t response;
+ initnatpmp(&natpmp, 0, 0);
+
+ do {
+ if (sendpublicaddressrequest(&natpmp) != 2) {
+ SWIFT_LOG(debug) << "Failed to send NAT-PMP public address request!" << std::endl;
+ break;
+ }
+ int r = 0;
+
+ do {
+ fd_set fds;
+ struct timeval timeout;
+ FD_ZERO(&fds);
+ FD_SET(natpmp.s, &fds);
+ getnatpmprequesttimeout(&natpmp, &timeout);
+ select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
+ r = readnatpmpresponseorretry(&natpmp, &response);
+ } while(r == NATPMP_TRYAGAIN);
+
+ if (r == 0) {
+ result = boost::optional<HostAddress>(HostAddress(reinterpret_cast<const unsigned char*>(&(response.pnu.publicaddress.addr)), 4));
+ } else {
+ SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl;
+ }
+ } while(false);
+ closenatpmp(&natpmp);
+ onResult(result);
+}
+
+}
diff --git a/Swiften/Network/NATPMPNATTraversalGetPublicIPRequest.h b/Swiften/Network/NATPMPNATTraversalGetPublicIPRequest.h
new file mode 100644
index 0000000..6112091
--- /dev/null
+++ b/Swiften/Network/NATPMPNATTraversalGetPublicIPRequest.h
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Network/PlatformNATTraversalGetPublicIPRequest.h>
+
+namespace Swift {
+
+class NATPMPNATTraversalGetPublicIPRequest : public PlatformNATTraversalGetPublicIPRequest {
+public:
+ NATPMPNATTraversalGetPublicIPRequest(PlatformNATTraversalWorker*);
+ virtual ~NATPMPNATTraversalGetPublicIPRequest();
+
+ //virtual void run();
+ virtual void runBlocking();
+};
+
+}
diff --git a/Swiften/Network/NATPMPNATTraversalRemovePortForwardingRequest.cpp b/Swiften/Network/NATPMPNATTraversalRemovePortForwardingRequest.cpp
new file mode 100644
index 0000000..c99ac92
--- /dev/null
+++ b/Swiften/Network/NATPMPNATTraversalRemovePortForwardingRequest.cpp
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "NATPMPNATTraversalRemovePortForwardingRequest.h"
+
+#include <boost/format.hpp>
+
+#include <natpmp.h>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Network/NetworkInterface.h>
+#include <Swiften/Network/PlatformNetworkEnvironment.h>
+
+namespace Swift {
+
+NATPMPNATTraversalRemovePortForwardingRequest::NATPMPNATTraversalRemovePortForwardingRequest(PlatformNATTraversalRemovePortForwardingRequest::PortMapping mapping, PlatformNATTraversalWorker* worker) : PlatformNATTraversalRemovePortForwardingRequest(worker), mapping(mapping) {
+
+}
+
+NATPMPNATTraversalRemovePortForwardingRequest::~NATPMPNATTraversalRemovePortForwardingRequest() {
+
+}
+
+void NATPMPNATTraversalRemovePortForwardingRequest::runBlocking() {
+ boost::optional<bool> result;
+
+ natpmp_t natpmp;
+ natpmpresp_t response;
+ initnatpmp(&natpmp, 0, 0);
+
+ do {
+ if (sendnewportmappingrequest(&natpmp, mapping.protocol == PortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, 0, 0, mapping.localPort) != 2) {
+ SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!" << std::endl;
+ break;
+ }
+ int r = 0;
+
+ do {
+ fd_set fds;
+ struct timeval timeout;
+ FD_ZERO(&fds);
+ FD_SET(natpmp.s, &fds);
+ getnatpmprequesttimeout(&natpmp, &timeout);
+ select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
+ r = readnatpmpresponseorretry(&natpmp, &response);
+ } while(r == NATPMP_TRYAGAIN);
+
+ if (r == 0) {
+ if (response.pnu.newportmapping.privateport == mapping.localPort &&
+ response.pnu.newportmapping.mappedpublicport == mapping.publicPort) {
+ mapping.leaseInSeconds = response.pnu.newportmapping.lifetime;
+ result = boost::optional<bool>(true);
+ }
+ } else {
+ result = boost::optional<bool>(false);
+ SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl;
+ }
+ } while(false);
+ closenatpmp(&natpmp);
+
+ onResult(result);
+}
+
+HostAddress NATPMPNATTraversalRemovePortForwardingRequest::getLocalClient() {
+ PlatformNetworkEnvironment env;
+
+ foreach (NetworkInterface::ref iface, env.getNetworkInterfaces()) {
+ if (!iface->isLoopback()) {
+ foreach (HostAddress address, iface->getAddresses()) {
+ if (address.getRawAddress().is_v4()) {
+ return address;
+ }
+ }
+ }
+ }
+ return HostAddress();
+}
+
+}
diff --git a/Swiften/Network/NATPMPNATTraversalRemovePortForwardingRequest.h b/Swiften/Network/NATPMPNATTraversalRemovePortForwardingRequest.h
new file mode 100644
index 0000000..c4ffcf3
--- /dev/null
+++ b/Swiften/Network/NATPMPNATTraversalRemovePortForwardingRequest.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.h>
+
+namespace Swift {
+
+class NATPMPNATTraversalRemovePortForwardingRequest : public PlatformNATTraversalRemovePortForwardingRequest {
+public:
+ NATPMPNATTraversalRemovePortForwardingRequest(PlatformNATTraversalRemovePortForwardingRequest::PortMapping, PlatformNATTraversalWorker*);
+ virtual ~NATPMPNATTraversalRemovePortForwardingRequest();
+
+ virtual void runBlocking();
+
+private:
+ HostAddress getLocalClient();
+
+private:
+ PlatformNATTraversalRemovePortForwardingRequest::PortMapping mapping;
+};
+
+}
diff --git a/Swiften/Network/NetworkEnvironment.h b/Swiften/Network/NetworkEnvironment.h
new file mode 100644
index 0000000..348bdb9
--- /dev/null
+++ b/Swiften/Network/NetworkEnvironment.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <vector>
+
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/Network/NetworkInterface.h>
+
+namespace Swift {
+
+class NetworkEnvironment {
+public:
+ virtual ~NetworkEnvironment() {};
+ virtual std::vector<NetworkInterface::ref> getNetworkInterfaces() = 0;
+
+ boost::signal <void (NetworkInterface::ref)> onNetworkInterfaceChange;
+};
+
+}
diff --git a/Swiften/Network/NetworkFactories.h b/Swiften/Network/NetworkFactories.h
index d0d2299..e7d2ff0 100644
--- a/Swiften/Network/NetworkFactories.h
+++ b/Swiften/Network/NetworkFactories.h
@@ -11,6 +11,7 @@ namespace Swift {
class ConnectionFactory;
class DomainNameResolver;
class ConnectionServerFactory;
+ class PlatformNATTraversalWorker;
/**
* An interface collecting network factories.
@@ -23,5 +24,6 @@ namespace Swift {
virtual ConnectionFactory* getConnectionFactory() const = 0;
virtual DomainNameResolver* getDomainNameResolver() const = 0;
virtual ConnectionServerFactory* getConnectionServerFactory() const = 0;
+ virtual PlatformNATTraversalWorker* getPlatformNATTraversalWorker() const = 0;
};
}
diff --git a/Swiften/Network/NetworkInterface.h b/Swiften/Network/NetworkInterface.h
new file mode 100644
index 0000000..062e1f9
--- /dev/null
+++ b/Swiften/Network/NetworkInterface.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <vector>
+#include <boost/shared_ptr.hpp>
+
+#include <Swiften/Network/HostAddress.h>
+
+namespace Swift {
+
+class NetworkInterface {
+public:
+ typedef boost::shared_ptr<NetworkInterface> ref;
+
+public:
+ enum InterfaceType {
+ WLAN,
+ Ethernet,
+ Mobile,
+ VPN,
+ };
+
+public:
+ virtual ~NetworkInterface() {};
+ virtual std::vector<HostAddress> getAddresses() = 0;
+ virtual std::string getName() = 0;
+ virtual bool isLoopback() = 0;
+};
+
+}
diff --git a/Swiften/Network/PlatformNATTraversalForwardPortRequest.cpp b/Swiften/Network/PlatformNATTraversalForwardPortRequest.cpp
new file mode 100644
index 0000000..b28024a
--- /dev/null
+++ b/Swiften/Network/PlatformNATTraversalForwardPortRequest.cpp
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "PlatformNATTraversalForwardPortRequest.h"
+
+namespace Swift {
+
+PlatformNATTraversalForwardPortRequest::PlatformNATTraversalForwardPortRequest(PlatformNATTraversalWorker* worker) : PlatformNATTraversalRequest(worker) {
+}
+
+PlatformNATTraversalForwardPortRequest::~PlatformNATTraversalForwardPortRequest() {
+
+}
+
+}
diff --git a/Swiften/Network/PlatformNATTraversalForwardPortRequest.h b/Swiften/Network/PlatformNATTraversalForwardPortRequest.h
new file mode 100644
index 0000000..cb1750c
--- /dev/null
+++ b/Swiften/Network/PlatformNATTraversalForwardPortRequest.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/Network/HostAddress.h>
+#include <Swiften/Network/PlatformNATTraversalRequest.h>
+
+namespace Swift {
+
+class PlatformNATTraversalWorker;
+
+class PlatformNATTraversalForwardPortRequest : public PlatformNATTraversalRequest {
+public:
+ struct PortMapping {
+ enum Protocol {
+ TCP,
+ UDP,
+ };
+
+ unsigned int publicPort;
+ unsigned int localPort;
+ Protocol protocol;
+ unsigned long leaseInSeconds;
+ };
+
+public:
+ PlatformNATTraversalForwardPortRequest(PlatformNATTraversalWorker* worker);
+ virtual ~PlatformNATTraversalForwardPortRequest();
+
+ boost::signal<void (boost::optional<PortMapping>)> onResult;
+};
+
+}
diff --git a/Swiften/Network/PlatformNATTraversalGetPublicIPRequest.cpp b/Swiften/Network/PlatformNATTraversalGetPublicIPRequest.cpp
new file mode 100644
index 0000000..7a57e30
--- /dev/null
+++ b/Swiften/Network/PlatformNATTraversalGetPublicIPRequest.cpp
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "PlatformNATTraversalGetPublicIPRequest.h"
+
+namespace Swift {
+
+PlatformNATTraversalGetPublicIPRequest::PlatformNATTraversalGetPublicIPRequest(PlatformNATTraversalWorker* worker) : PlatformNATTraversalRequest(worker) {
+}
+
+PlatformNATTraversalGetPublicIPRequest::~PlatformNATTraversalGetPublicIPRequest() {
+
+}
+
+}
diff --git a/Swiften/Network/PlatformNATTraversalGetPublicIPRequest.h b/Swiften/Network/PlatformNATTraversalGetPublicIPRequest.h
new file mode 100644
index 0000000..1cb37fe
--- /dev/null
+++ b/Swiften/Network/PlatformNATTraversalGetPublicIPRequest.h
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/Network/HostAddress.h>
+#include <Swiften/Network/PlatformNATTraversalRequest.h>
+
+namespace Swift {
+
+class PlatformNATTraversalWorker;
+
+class PlatformNATTraversalGetPublicIPRequest : public PlatformNATTraversalRequest {
+public:
+ PlatformNATTraversalGetPublicIPRequest(PlatformNATTraversalWorker* worker);
+ virtual ~PlatformNATTraversalGetPublicIPRequest();
+
+ boost::signal<void (boost::optional<HostAddress>)> onResult;
+};
+
+}
diff --git a/Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.cpp b/Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.cpp
new file mode 100644
index 0000000..514988e
--- /dev/null
+++ b/Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.cpp
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "PlatformNATTraversalRemovePortForwardingRequest.h"
+
+namespace Swift {
+
+PlatformNATTraversalRemovePortForwardingRequest::PlatformNATTraversalRemovePortForwardingRequest(PlatformNATTraversalWorker* worker) : PlatformNATTraversalRequest(worker) {
+}
+
+PlatformNATTraversalRemovePortForwardingRequest::~PlatformNATTraversalRemovePortForwardingRequest() {
+
+}
+
+}
diff --git a/Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.h b/Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.h
new file mode 100644
index 0000000..03427ad
--- /dev/null
+++ b/Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/Network/HostAddress.h>
+#include <Swiften/Network/PlatformNATTraversalRequest.h>
+
+namespace Swift {
+
+class PlatformNATTraversalWorker;
+
+class PlatformNATTraversalRemovePortForwardingRequest : public PlatformNATTraversalRequest {
+public:
+ struct PortMapping {
+ enum Protocol {
+ TCP,
+ UDP,
+ };
+
+ unsigned int publicPort;
+ unsigned int localPort;
+ Protocol protocol;
+ unsigned long leaseInSeconds;
+ };
+
+public:
+ PlatformNATTraversalRemovePortForwardingRequest(PlatformNATTraversalWorker* worker);
+ virtual ~PlatformNATTraversalRemovePortForwardingRequest();
+
+ boost::signal<void (boost::optional<bool> /* failure */)> onResult;
+};
+
+}
diff --git a/Swiften/Network/PlatformNATTraversalRequest.cpp b/Swiften/Network/PlatformNATTraversalRequest.cpp
new file mode 100644
index 0000000..25e8a32
--- /dev/null
+++ b/Swiften/Network/PlatformNATTraversalRequest.cpp
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "PlatformNATTraversalRequest.h"
+
+#include <Swiften/Network/PlatformNATTraversalWorker.h>
+
+namespace Swift {
+
+PlatformNATTraversalRequest::PlatformNATTraversalRequest(PlatformNATTraversalWorker* worker) : worker(worker) {
+
+}
+
+PlatformNATTraversalRequest::~PlatformNATTraversalRequest() {
+
+}
+
+void PlatformNATTraversalRequest::run() {
+ worker->addRequestToQueue(shared_from_this());
+}
+
+}
diff --git a/Swiften/Network/PlatformNATTraversalRequest.h b/Swiften/Network/PlatformNATTraversalRequest.h
new file mode 100644
index 0000000..4b760ad
--- /dev/null
+++ b/Swiften/Network/PlatformNATTraversalRequest.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <boost/enable_shared_from_this.hpp>
+#include <boost/shared_ptr.hpp>
+
+namespace Swift {
+
+class PlatformNATTraversalWorker;
+
+class PlatformNATTraversalRequest : public boost::enable_shared_from_this<PlatformNATTraversalRequest> {
+public:
+ typedef boost::shared_ptr<PlatformNATTraversalRequest> ref;
+
+public:
+ PlatformNATTraversalRequest(PlatformNATTraversalWorker* worker);
+ virtual ~PlatformNATTraversalRequest();
+
+ virtual void run();
+ virtual void runBlocking() = 0;
+
+private:
+ PlatformNATTraversalWorker* worker;
+};
+
+}
diff --git a/Swiften/Network/PlatformNATTraversalWorker.cpp b/Swiften/Network/PlatformNATTraversalWorker.cpp
new file mode 100644
index 0000000..a4efedd
--- /dev/null
+++ b/Swiften/Network/PlatformNATTraversalWorker.cpp
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "PlatformNATTraversalWorker.h"
+
+#include <boost/smart_ptr/make_shared.hpp>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Network/UPnPNATTraversalGetPublicIPRequest.h>
+#include <Swiften/Network/UPnPNATTraversalForwardPortRequest.h>
+#include <Swiften/Network/UPnPNATTraversalRemovePortForwardingRequest.h>
+#include <Swiften/Network/NATPMPNATTraversalGetPublicIPRequest.h>
+#include <Swiften/Network/NATPMPNATTraversalForwardPortRequest.h>
+#include <Swiften/Network/NATPMPNATTraversalRemovePortForwardingRequest.h>
+#include <Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.h>
+
+namespace Swift {
+
+PlatformNATTraversalWorker::PlatformNATTraversalWorker(EventLoop* eventLoop) : backendType(NotYetDecided), eventLoop(eventLoop), stopRequested(false) {
+ checkAvailableNATTraversalProtocols();
+ thread = new boost::thread(boost::bind(&PlatformNATTraversalWorker::run, this));
+}
+
+PlatformNATTraversalWorker::~PlatformNATTraversalWorker() {
+ stopRequested = true;
+ addRequestToQueue(boost::shared_ptr<PlatformNATTraversalRequest>());
+ thread->join();
+ delete thread;
+}
+
+boost::shared_ptr<PlatformNATTraversalGetPublicIPRequest> PlatformNATTraversalWorker::createGetPublicIPRequest() {
+ switch(backendType) {
+ case UPnP:
+ return boost::make_shared<UPnPNATTraversalGetPublicIPRequest>(this);
+ case NATPMP:
+ return boost::make_shared<NATPMPNATTraversalGetPublicIPRequest>(this);
+ case NotYetDecided:
+ case None:
+ break;
+ }
+ return boost::shared_ptr<PlatformNATTraversalGetPublicIPRequest>();
+}
+
+boost::shared_ptr<PlatformNATTraversalForwardPortRequest> PlatformNATTraversalWorker::createForwardPortRequest(unsigned int localPort, unsigned int publicPort) {
+ PlatformNATTraversalForwardPortRequest::PortMapping mapping;
+ mapping.protocol = PlatformNATTraversalForwardPortRequest::PortMapping::TCP;
+ mapping.leaseInSeconds = 60 * 60 * 24;
+ mapping.localPort = localPort;
+ mapping.publicPort = publicPort;
+
+ switch(backendType) {
+ case UPnP:
+ return boost::make_shared<UPnPNATTraversalForwardPortRequest>(mapping, this);
+ case NATPMP:
+ return boost::make_shared<NATPMPNATTraversalForwardPortRequest>(mapping, this);
+ case NotYetDecided:
+ case None:
+ break;
+ }
+ return boost::shared_ptr<PlatformNATTraversalForwardPortRequest>();
+}
+
+boost::shared_ptr<PlatformNATTraversalRemovePortForwardingRequest> PlatformNATTraversalWorker::createRemovePortForwardingRequest(unsigned int localPort, unsigned int publicPort) {
+ PlatformNATTraversalRemovePortForwardingRequest::PortMapping mapping;
+ mapping.protocol = PlatformNATTraversalRemovePortForwardingRequest::PortMapping::TCP;
+ mapping.leaseInSeconds = 60 * 60 * 24;
+ mapping.localPort = localPort;
+ mapping.publicPort = publicPort;
+
+ switch(backendType) {
+ case UPnP:
+ return boost::make_shared<UPnPNATTraversalRemovePortForwardingRequest>(mapping, this);
+ case NATPMP:
+ return boost::make_shared<NATPMPNATTraversalRemovePortForwardingRequest>(mapping, this);
+ case NotYetDecided:
+ case None:
+ break;
+ }
+ return boost::shared_ptr<PlatformNATTraversalRemovePortForwardingRequest>();
+}
+
+void PlatformNATTraversalWorker::run() {
+ while (!stopRequested) {
+ PlatformNATTraversalRequest::ref request;
+ {
+ boost::unique_lock<boost::mutex> lock(queueMutex);
+ while (queue.empty()) {
+ queueNonEmpty.wait(lock);
+ }
+ request = queue.front();
+ queue.pop_front();
+ }
+ // Check whether we don't have a non-null request (used to stop the
+ // worker)
+ if (request) {
+ request->runBlocking();
+ }
+ }
+}
+
+void PlatformNATTraversalWorker::addRequestToQueue(PlatformNATTraversalRequest::ref request) {
+ {
+ boost::lock_guard<boost::mutex> lock(queueMutex);
+ queue.push_back(request);
+ }
+ queueNonEmpty.notify_one();
+}
+
+void PlatformNATTraversalWorker::checkAvailableNATTraversalProtocols() {
+ boost::shared_ptr<UPnPNATTraversalGetPublicIPRequest> upnpRequest = boost::make_shared<UPnPNATTraversalGetPublicIPRequest>(this);
+ upnpRequest->onResult.connect(boost::bind(&PlatformNATTraversalWorker::handleUPnPGetPublicIPResult, this, _1));
+
+ boost::shared_ptr<NATPMPNATTraversalGetPublicIPRequest> natpmpRequest = boost::make_shared<NATPMPNATTraversalGetPublicIPRequest>(this);
+ natpmpRequest->onResult.connect(boost::bind(&PlatformNATTraversalWorker::handleNATPMPGetPublicIPResult, this, _1));
+
+ upnpRequest->run();
+ natpmpRequest->run();
+}
+
+void PlatformNATTraversalWorker::handleUPnPGetPublicIPResult(boost::optional<HostAddress> address) {
+ if (backendType == NotYetDecided || backendType == None) {
+ if (address) {
+ SWIFT_LOG(debug) << "Found UPnP IGD in the local network." << std::endl;
+ backendType = UPnP;
+ }
+ }
+}
+
+void PlatformNATTraversalWorker::handleNATPMPGetPublicIPResult(boost::optional<HostAddress> address) {
+ if (backendType == NotYetDecided || backendType == None) {
+ if (address) {
+ SWIFT_LOG(debug) << "Found NAT-PMP device in the local network." << std::endl;
+ backendType = NATPMP;
+ }
+ }
+}
+
+}
diff --git a/Swiften/Network/PlatformNATTraversalWorker.h b/Swiften/Network/PlatformNATTraversalWorker.h
new file mode 100644
index 0000000..7c249cc
--- /dev/null
+++ b/Swiften/Network/PlatformNATTraversalWorker.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <deque>
+#include <boost/optional.hpp>
+#include <boost/thread/thread.hpp>
+#include <boost/thread/mutex.hpp>
+#include <boost/thread/condition_variable.hpp>
+
+#include <Swiften/Network/HostAddressPort.h>
+#include <Swiften/Network/PlatformNATTraversalRequest.h>
+
+namespace Swift {
+
+class EventLoop;
+class PlatformNATTraversalGetPublicIPRequest;
+class PlatformNATTraversalForwardPortRequest;
+class PlatformNATTraversalRemovePortForwardingRequest;
+
+class PlatformNATTraversalWorker {
+private:
+ enum BackendType {
+ NotYetDecided,
+ UPnP,
+ NATPMP,
+ None,
+ };
+
+public:
+ PlatformNATTraversalWorker(EventLoop* eventLoop);
+ ~PlatformNATTraversalWorker();
+
+ boost::shared_ptr<PlatformNATTraversalGetPublicIPRequest> createGetPublicIPRequest();
+ boost::shared_ptr<PlatformNATTraversalForwardPortRequest> createForwardPortRequest(unsigned int localPort, unsigned int publicPort);
+ boost::shared_ptr<PlatformNATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(unsigned int localPort, unsigned int publicPort);
+
+ void run();
+ void addRequestToQueue(PlatformNATTraversalRequest::ref);
+
+private:
+ void checkAvailableNATTraversalProtocols();
+ void handleUPnPGetPublicIPResult(boost::optional<HostAddress> address);
+ void handleNATPMPGetPublicIPResult(boost::optional<HostAddress> address);
+
+private:
+ BackendType backendType;
+ EventLoop* eventLoop;
+ bool stopRequested;
+ boost::thread* thread;
+ std::deque<PlatformNATTraversalRequest::ref> queue;
+ boost::mutex queueMutex;
+ boost::condition_variable queueNonEmpty;
+};
+
+}
diff --git a/Swiften/Network/PlatformNetworkEnvironment.h b/Swiften/Network/PlatformNetworkEnvironment.h
new file mode 100644
index 0000000..c6b945e
--- /dev/null
+++ b/Swiften/Network/PlatformNetworkEnvironment.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Base/Platform.h>
+
+#if defined(SWIFTEN_PLATFORM_MACOSX)
+#include <Swiften/Network/UnixNetworkEnvironment.h>
+namespace Swift {
+ typedef UnixNetworkEnvironment PlatformNetworkEnvironment;
+}
+#elif defined(SWIFTEN_PLATFORM_WIN32)
+#include <Swiften/Network/WindowsNetworkEnvironment.h>
+namespace Swift {
+ typedef WindowsNetworkEnvironment PlatformNetworkEnvironment;
+}
+#else
+#include <Swiften/Network/UnixNetworkEnvironment.h>
+namespace Swift {
+ typedef UnixNetworkEnvironment PlatformNetworkEnvironment;
+}
+#endif
diff --git a/Swiften/Network/SConscript b/Swiften/Network/SConscript
index 965361b..e9853dd 100644
--- a/Swiften/Network/SConscript
+++ b/Swiften/Network/SConscript
@@ -40,7 +40,18 @@ sourceList = [
"Timer.cpp",
"BoostTimer.cpp",
"ProxyProvider.cpp",
- "NullProxyProvider.cpp"
+ "NullProxyProvider.cpp",
+ "PlatformNATTraversalWorker.cpp",
+ "PlatformNATTraversalGetPublicIPRequest.cpp",
+ "PlatformNATTraversalForwardPortRequest.cpp",
+ "PlatformNATTraversalRemovePortForwardingRequest.cpp",
+ "PlatformNATTraversalRequest.cpp",
+ "UPnPNATTraversalGetPublicIPRequest.cpp",
+ "UPnPNATTraversalForwardPortRequest.cpp",
+ "UPnPNATTraversalRemovePortForwardingRequest.cpp",
+ "NATPMPNATTraversalGetPublicIPRequest.cpp",
+ "NATPMPNATTraversalForwardPortRequest.cpp",
+ "NATPMPNATTraversalRemovePortForwardingRequest.cpp",
]
if myenv.get("HAVE_CARES", False) :
@@ -49,9 +60,12 @@ if myenv.get("HAVE_CARES", False) :
if myenv["PLATFORM"] == "darwin" :
myenv.Append(FRAMEWORKS = ["CoreServices", "SystemConfiguration"])
sourceList += [ "MacOSXProxyProvider.cpp" ]
+ sourceList += [ "UnixNetworkEnvironment.cpp" ]
elif myenv["PLATFORM"] == "win32" :
sourceList += [ "WindowsProxyProvider.cpp" ]
+ sourceList += [ "WindowsNetworkEnvironment.cpp" ]
else :
+ sourceList += [ "UnixNetworkEnvironment.cpp" ]
sourceList += [ "UnixProxyProvider.cpp" ]
sourceList += [ "EnvironmentProxyProvider.cpp" ]
if myenv.get("HAVE_GCONF", 0) :
diff --git a/Swiften/Network/UPnPNATTraversalForwardPortRequest.cpp b/Swiften/Network/UPnPNATTraversalForwardPortRequest.cpp
new file mode 100644
index 0000000..c95066e
--- /dev/null
+++ b/Swiften/Network/UPnPNATTraversalForwardPortRequest.cpp
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "UPnPNATTraversalForwardPortRequest.h"
+
+#include <boost/format.hpp>
+
+#include <miniupnpc.h>
+#include <upnpcommands.h>
+#include <upnperrors.h>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Network/NetworkInterface.h>
+#include <Swiften/Network/PlatformNetworkEnvironment.h>
+
+namespace Swift {
+
+UPnPNATTraversalForwardPortRequest::UPnPNATTraversalForwardPortRequest(PlatformNATTraversalForwardPortRequest::PortMapping mapping, PlatformNATTraversalWorker* worker) : PlatformNATTraversalForwardPortRequest(worker), mapping(mapping) {
+
+}
+
+UPnPNATTraversalForwardPortRequest::~UPnPNATTraversalForwardPortRequest() {
+
+}
+
+void UPnPNATTraversalForwardPortRequest::runBlocking() {
+ boost::optional<PortMapping> result;
+
+ UPNPDev* deviceList = 0;
+ int error = 0;
+ char lanAddrress[64];
+
+ std::string publicPort = str(boost::format("%d") % mapping.publicPort);
+ std::string localPort = str(boost::format("%d") % mapping.localPort);
+ std::string internalClient = getLocalClient().toString();
+ std::string leaseSeconds = str(boost::format("%d") % mapping.leaseInSeconds);
+ UPNPUrls urls;
+ IGDdatas data;
+
+ do {
+ // find valid IGD
+ deviceList = upnpDiscover(1500 /* timeout in ms */, 0, 0, 0, 0 /* do IPv6? */, &error);
+ if (!deviceList) {
+ break;
+ }
+
+ if (!UPNP_GetValidIGD(deviceList, &urls, &data, lanAddrress, sizeof(lanAddrress))) {
+ break;
+ }
+
+ /*
+ int ret = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
+ if (ret != UPNPCOMMAND_SUCCESS) {
+ break;
+ }*/
+
+ int ret = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, publicPort.c_str(), localPort.c_str(), internalClient.c_str(), 0, mapping.protocol == PlatformNATTraversalForwardPortRequest::PortMapping::TCP ? "TCP" : "UDP", 0, leaseSeconds.c_str());
+ if (ret == UPNPCOMMAND_SUCCESS) {
+ result = boost::optional<PlatformNATTraversalForwardPortRequest::PortMapping>(mapping);
+ }
+ } while(false);
+
+ freeUPNPDevlist(deviceList); deviceList = 0;
+
+ onResult(result);
+}
+
+HostAddress UPnPNATTraversalForwardPortRequest::getLocalClient() {
+ PlatformNetworkEnvironment env;
+
+ foreach (NetworkInterface::ref iface, env.getNetworkInterfaces()) {
+ if (!iface->isLoopback()) {
+ foreach (HostAddress address, iface->getAddresses()) {
+ if (address.getRawAddress().is_v4()) {
+ return address;
+ }
+ }
+ }
+ }
+ return HostAddress();
+}
+
+}
diff --git a/Swiften/Network/UPnPNATTraversalForwardPortRequest.h b/Swiften/Network/UPnPNATTraversalForwardPortRequest.h
new file mode 100644
index 0000000..931efee
--- /dev/null
+++ b/Swiften/Network/UPnPNATTraversalForwardPortRequest.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Network/PlatformNATTraversalForwardPortRequest.h>
+
+namespace Swift {
+
+class UPnPNATTraversalForwardPortRequest : public PlatformNATTraversalForwardPortRequest {
+public:
+ UPnPNATTraversalForwardPortRequest(PlatformNATTraversalForwardPortRequest::PortMapping, PlatformNATTraversalWorker*);
+ virtual ~UPnPNATTraversalForwardPortRequest();
+
+ virtual void runBlocking();
+
+private:
+ HostAddress getLocalClient();
+
+private:
+ PlatformNATTraversalForwardPortRequest::PortMapping mapping;
+};
+
+}
diff --git a/Swiften/Network/UPnPNATTraversalGetPublicIPRequest.cpp b/Swiften/Network/UPnPNATTraversalGetPublicIPRequest.cpp
new file mode 100644
index 0000000..4a7c247
--- /dev/null
+++ b/Swiften/Network/UPnPNATTraversalGetPublicIPRequest.cpp
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "UPnPNATTraversalGetPublicIPRequest.h"
+
+#include <miniupnpc.h>
+#include <upnpcommands.h>
+#include <upnperrors.h>
+
+namespace Swift {
+
+UPnPNATTraversalGetPublicIPRequest::UPnPNATTraversalGetPublicIPRequest(PlatformNATTraversalWorker* worker) : PlatformNATTraversalGetPublicIPRequest(worker) {
+
+}
+
+UPnPNATTraversalGetPublicIPRequest::~UPnPNATTraversalGetPublicIPRequest() {
+
+}
+
+void UPnPNATTraversalGetPublicIPRequest::runBlocking() {
+ boost::optional<HostAddress> result;
+
+ UPNPDev* deviceList = 0;
+ int error = 0;
+ char lanAddrress[64];
+ char externalIPAddress[40];
+ UPNPUrls urls;
+ IGDdatas data;
+
+ do {
+ // find valid IGD
+ deviceList = upnpDiscover(1500 /* timeout in ms */, 0, 0, 0, 0 /* do IPv6? */, &error);
+ if (!deviceList) {
+ break;
+ }
+
+ if (!UPNP_GetValidIGD(deviceList, &urls, &data, lanAddrress, sizeof(lanAddrress))) {
+ break;
+ }
+
+ int ret = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
+ if (ret != UPNPCOMMAND_SUCCESS) {
+ break;
+ } else {
+ result = HostAddress(std::string(externalIPAddress));
+ }
+ } while(false);
+
+ freeUPNPDevlist(deviceList); deviceList = 0;
+
+ onResult(result);
+}
+
+}
diff --git a/Swiften/Network/UPnPNATTraversalGetPublicIPRequest.h b/Swiften/Network/UPnPNATTraversalGetPublicIPRequest.h
new file mode 100644
index 0000000..9d50001
--- /dev/null
+++ b/Swiften/Network/UPnPNATTraversalGetPublicIPRequest.h
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Network/PlatformNATTraversalGetPublicIPRequest.h>
+
+namespace Swift {
+
+class UPnPNATTraversalGetPublicIPRequest : public PlatformNATTraversalGetPublicIPRequest {
+public:
+ UPnPNATTraversalGetPublicIPRequest(PlatformNATTraversalWorker*);
+ virtual ~UPnPNATTraversalGetPublicIPRequest();
+
+ virtual void runBlocking();
+};
+
+}
diff --git a/Swiften/Network/UPnPNATTraversalRemovePortForwardingRequest.cpp b/Swiften/Network/UPnPNATTraversalRemovePortForwardingRequest.cpp
new file mode 100644
index 0000000..2026880
--- /dev/null
+++ b/Swiften/Network/UPnPNATTraversalRemovePortForwardingRequest.cpp
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "UPnPNATTraversalRemovePortForwardingRequest.h"
+
+#include <boost/format.hpp>
+
+#include <miniupnpc.h>
+#include <upnpcommands.h>
+#include <upnperrors.h>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/Log.h>
+#include <Swiften/Network/NetworkInterface.h>
+#include <Swiften/Network/PlatformNetworkEnvironment.h>
+
+namespace Swift {
+
+UPnPNATTraversalRemovePortForwardingRequest::UPnPNATTraversalRemovePortForwardingRequest(PlatformNATTraversalRemovePortForwardingRequest::PortMapping mapping, PlatformNATTraversalWorker* worker) : PlatformNATTraversalRemovePortForwardingRequest(worker), mapping(mapping) {
+
+}
+
+UPnPNATTraversalRemovePortForwardingRequest::~UPnPNATTraversalRemovePortForwardingRequest() {
+
+}
+
+void UPnPNATTraversalRemovePortForwardingRequest::runBlocking() {
+ boost::optional<bool> result;
+
+ UPNPDev* deviceList = 0;
+ int error = 0;
+ char lanAddrress[64];
+
+ std::string publicPort = str(boost::format("%d") % mapping.publicPort);
+ std::string localPort = str(boost::format("%d") % mapping.localPort);
+ std::string internalClient = getLocalClient().toString();
+ std::string leaseSeconds = str(boost::format("%d") % mapping.leaseInSeconds);
+ UPNPUrls urls;
+ IGDdatas data;
+
+ do {
+ // find valid IGD
+ deviceList = upnpDiscover(1500 /* timeout in ms */, 0, 0, 0, 0 /* do IPv6? */, &error);
+ if (!deviceList) {
+ break;
+ }
+
+ if (!UPNP_GetValidIGD(deviceList, &urls, &data, lanAddrress, sizeof(lanAddrress))) {
+ break;
+ }
+
+ /*
+ int ret = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
+ if (ret != UPNPCOMMAND_SUCCESS) {
+ break;
+ }*/
+ SWIFT_LOG(debug) << "Start removing port forwarding..." << std::endl;
+ int ret = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, publicPort.c_str(), mapping.protocol == PlatformNATTraversalRemovePortForwardingRequest::PortMapping::TCP ? "TCP" : "UDP", 0);
+
+ if (ret == UPNPCOMMAND_SUCCESS) {
+ SWIFT_LOG(debug) << "Removing port " << publicPort << " successfull." << std::endl;
+ result = true;
+ } else {
+ SWIFT_LOG(debug) << "Removing port " << publicPort << " failed." << std::endl;
+ result = false;
+ }
+ } while(false);
+
+ freeUPNPDevlist(deviceList); deviceList = 0;
+
+ onResult(result);
+}
+
+HostAddress UPnPNATTraversalRemovePortForwardingRequest::getLocalClient() {
+ PlatformNetworkEnvironment env;
+
+ foreach (NetworkInterface::ref iface, env.getNetworkInterfaces()) {
+ if (!iface->isLoopback()) {
+ foreach (HostAddress address, iface->getAddresses()) {
+ if (address.getRawAddress().is_v4()) {
+ return address;
+ }
+ }
+ }
+ }
+ return HostAddress();
+}
+
+}
diff --git a/Swiften/Network/UPnPNATTraversalRemovePortForwardingRequest.h b/Swiften/Network/UPnPNATTraversalRemovePortForwardingRequest.h
new file mode 100644
index 0000000..ad1e019
--- /dev/null
+++ b/Swiften/Network/UPnPNATTraversalRemovePortForwardingRequest.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Network/PlatformNATTraversalRemovePortForwardingRequest.h>
+
+namespace Swift {
+
+class UPnPNATTraversalRemovePortForwardingRequest : public PlatformNATTraversalRemovePortForwardingRequest {
+public:
+ UPnPNATTraversalRemovePortForwardingRequest(PlatformNATTraversalRemovePortForwardingRequest::PortMapping, PlatformNATTraversalWorker*);
+ virtual ~UPnPNATTraversalRemovePortForwardingRequest();
+
+ virtual void runBlocking();
+
+private:
+ HostAddress getLocalClient();
+
+private:
+ PlatformNATTraversalRemovePortForwardingRequest::PortMapping mapping;
+};
+
+}
diff --git a/Swiften/Network/UnixNetworkEnvironment.cpp b/Swiften/Network/UnixNetworkEnvironment.cpp
new file mode 100644
index 0000000..649855d
--- /dev/null
+++ b/Swiften/Network/UnixNetworkEnvironment.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "UnixNetworkEnvironment.h"
+
+#include <string>
+#include <vector>
+#include <map>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/Network/HostAddress.h>
+#include <Swiften/Network/NetworkInterface.h>
+
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <net/if.h>
+#include <ifaddrs.h>
+
+namespace Swift {
+
+std::vector<NetworkInterface::ref> UnixNetworkEnvironment::getNetworkInterfaces() {
+ std::map<std::string, UnixNetworkInterface::ref> interfaces;
+ std::vector<NetworkInterface::ref> result;
+
+ ifaddrs *addrs = 0;
+ int ret = getifaddrs(&addrs);
+ if (ret != 0) {
+ return result;
+ }
+
+ for (ifaddrs *a = addrs; a != 0; a = a->ifa_next) {
+ std::string name(a->ifa_name);
+ std::string ip;
+ if (a->ifa_addr->sa_family == PF_INET) {
+ sockaddr_in* sa = reinterpret_cast<sockaddr_in*>(a->ifa_addr);
+ char str[INET_ADDRSTRLEN];
+ inet_ntop(AF_INET, &(sa->sin_addr), str, INET_ADDRSTRLEN);
+ ip.assign(str);
+ }
+ else if (a->ifa_addr->sa_family == PF_INET6) {
+ sockaddr_in6* sa = reinterpret_cast<sockaddr_in6*>(a->ifa_addr);
+ char str[INET6_ADDRSTRLEN];
+ /*if (IN6_IS_ADDR_LINKLOCAL(sa)) {
+ continue;
+ }*/
+ inet_ntop(AF_INET6, &(sa->sin6_addr), str, INET6_ADDRSTRLEN);
+ ip.assign(str);
+ }
+ if (!ip.empty()) {
+ if (interfaces.find(name) == interfaces.end()) {
+ interfaces[name] = boost::make_shared<UnixNetworkInterface>(name);
+ if (a->ifa_flags & IFF_LOOPBACK) {
+ interfaces[name]->setLoopback(true);
+ }
+ }
+ interfaces[name]->addHostAddress(HostAddress(ip));
+ }
+ }
+
+ freeifaddrs(addrs);
+
+ for(std::map<std::string, UnixNetworkInterface::ref>::iterator i = interfaces.begin(); i != interfaces.end(); ++i) {
+ result.push_back(i->second);
+ }
+ return result;
+}
+
+}
diff --git a/Swiften/Network/UnixNetworkEnvironment.h b/Swiften/Network/UnixNetworkEnvironment.h
new file mode 100644
index 0000000..e4b2f37
--- /dev/null
+++ b/Swiften/Network/UnixNetworkEnvironment.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <vector>
+
+#include <Swiften/Base/boost_bsignals.h>
+
+#include <Swiften/Network/NetworkEnvironment.h>
+#include <Swiften/Network/NetworkInterface.h>
+
+namespace Swift {
+
+class UnixNetworkEnvironment : public NetworkEnvironment {
+ class UnixNetworkInterface : public NetworkInterface {
+ public:
+ typedef boost::shared_ptr<UnixNetworkInterface> ref;
+
+ public:
+ UnixNetworkInterface(std::string name) : name(name), loopback(false) { }
+
+ std::vector<HostAddress> getAddresses() {
+ return addresses;
+ }
+
+ std::string getName() {
+ return name;
+ }
+
+ bool isLoopback() {
+ return loopback;
+ }
+
+ private:
+ void addHostAddress(HostAddress address) {
+ addresses.push_back(address);
+ }
+
+ void setLoopback(bool loopback) {
+ this->loopback = loopback;
+ }
+
+ private:
+ friend class UnixNetworkEnvironment;
+ std::vector<HostAddress> addresses;
+ std::string name;
+ InterfaceType type;
+ bool loopback;
+ };
+
+public:
+ std::vector<NetworkInterface::ref> getNetworkInterfaces();
+};
+
+}
diff --git a/Swiften/Network/WindowsNetworkEnvironment.cpp b/Swiften/Network/WindowsNetworkEnvironment.cpp
new file mode 100644
index 0000000..5163f43
--- /dev/null
+++ b/Swiften/Network/WindowsNetworkEnvironment.cpp
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "WindowsNetworkEnvironment.h"
+
+#include <string>
+#include <vector>
+#include <map>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+#include <Swiften/Base/boost_bsignals.h>
+#include <Swiften/Network/HostAddress.h>
+#include <Swiften/Network/NetworkInterface.h>
+
+#include <winsock2.h>
+#include <iphlpapi.h>
+
+namespace Swift {
+
+std::string winSocketAddressToStdString(const SOCKET_ADDRESS& socketAddress) {
+ char text[46];
+ ULONG bufferSize = sizeof(text);
+ std::string result;
+
+ int ret = WSAAddressToString(socketAddress.lpSockaddr, socketAddress.iSockaddrLength, NULL, text, &bufferSize);
+ if (ret == 0) {
+ result.assign(text, sizeof(text));
+ }
+ return result;
+}
+
+std::vector<NetworkInterface::ref> WindowsNetworkEnvironment::getNetworkInterfaces() {
+ std::map<std::string, WindowsNetworkInterface::ref> interfaces;
+ std::vector<NetworkInterface::ref> result;
+
+ IP_ADAPTER_ADDRESSES preBuffer[5];
+ PIP_ADAPTER_ADDRESSES adapterStart = preBuffer;
+
+ ULONG bufferSize = sizeof(preBuffer);
+
+ ULONG flags = GAA_FLAG_INCLUDE_ALL_INTERFACES | GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER;
+
+ ULONG ret = GetAdaptersAddresses( AF_UNSPEC, flags, NULL, adapterStart, &bufferSize);
+ if (ret == ERROR_BUFFER_OVERFLOW) {
+ adapterStart = new IP_ADAPTER_ADDRESSES[bufferSize / sizeof(IP_ADAPTER_ADDRESSES)];
+ if (!adapterStart) {
+ return result;
+ }
+ ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterStart, &bufferSize);
+ }
+ if (ret != ERROR_SUCCESS) {
+ if (adapterStart != preBuffer) {
+ delete adapterStart;
+ }
+ return result;
+ }
+
+ for (PIP_ADAPTER_ADDRESSES adapter = adapterStart; adapter; adapter = adapter->Next) {
+ std::string name(adapter->AdapterName);
+
+ if (adapter->OperStatus != IfOperStatusUp) {
+ continue;
+ }
+
+ // iterate over addresses
+ for (PIP_ADAPTER_UNICAST_ADDRESS address = adapter->FirstUnicastAddress; address; address = address->Next) {
+ std::string ip;
+
+ if (address->Address.lpSockaddr->sa_family == PF_INET ||
+ address->Address.lpSockaddr->sa_family == PF_INET6) {
+ ip = winSocketAddressToStdString(address->Address);
+ if (!ip.empty()) {
+ if (interfaces.find(name) == interfaces.end()) {
+ interfaces[name] = boost::make_shared<WindowsNetworkInterface>();
+ interfaces[name]->setName(name);
+ }
+ interfaces[name]->addHostAddress(HostAddress(ip));
+ }
+ }
+ }
+ }
+
+ if (adapterStart != preBuffer) {
+ //delete adapterStart;
+ }
+
+ for(std::map<std::string, WindowsNetworkInterface::ref>::iterator i = interfaces.begin(); i != interfaces.end(); ++i) {
+ result.push_back(i->second);
+ }
+ return result;
+}
+
+}
diff --git a/Swiften/Network/WindowsNetworkEnvironment.h b/Swiften/Network/WindowsNetworkEnvironment.h
new file mode 100644
index 0000000..2b79504
--- /dev/null
+++ b/Swiften/Network/WindowsNetworkEnvironment.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <vector>
+
+#include <Swiften/Base/boost_bsignals.h>
+
+#include <Swiften/Network/NetworkEnvironment.h>
+#include <Swiften/Network/NetworkInterface.h>
+
+namespace Swift {
+
+class WindowsNetworkEnvironment : public NetworkEnvironment {
+ class WindowsNetworkInterface : public NetworkInterface {
+ public:
+ typedef boost::shared_ptr<WindowsNetworkInterface> ref;
+
+ public:
+ virtual ~WindowsNetworkInterface() { }
+ virtual std::vector<HostAddress> getAddresses() {
+ return addresses;
+ }
+
+ virtual std::string getName() {
+ return name;
+ }
+
+ virtual bool isLoopback() {
+ return false;
+ }
+
+ public:
+ void addHostAddress(HostAddress address) {
+ addresses.push_back(address);
+ }
+
+ void setName(const std::string& name) {
+ this->name = name;
+ }
+
+ private:
+ std::vector<HostAddress> addresses;
+ InterfaceType type;
+ std::string name;
+ };
+
+public:
+ std::vector<NetworkInterface::ref> getNetworkInterfaces();
+};
+
+}
diff --git a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
index 1b59f6f..9eafcba 100644
--- a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
+++ b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp
@@ -48,6 +48,19 @@
#include <Swiften/Parser/PayloadParsers/NicknameParserFactory.h>
#include <Swiften/Parser/PayloadParsers/ReplaceParser.h>
#include <Swiften/Parser/PayloadParsers/LastParser.h>
+#include <Swiften/Parser/PayloadParsers/JingleParserFactory.h>
+#include <Swiften/Parser/PayloadParsers/JingleReasonParser.h>
+#include <Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h>
+#include <Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h>
+#include <Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h>
+#include <Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h>
+#include <Swiften/Parser/PayloadParsers/JingleFileTransferReceivedParser.h>
+#include <Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h>
+#include <Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h>
+
+#include "JingleIBBTransportMethodPayloadParser.h"
+#include "JingleFileTransferDescriptionParser.h"
using namespace boost;
@@ -91,6 +104,16 @@ FullPayloadParserFactoryCollection::FullPayloadParserFactoryCollection() {
factories_.push_back(shared_ptr<PayloadParserFactory>(new MUCUserPayloadParserFactory()));
factories_.push_back(shared_ptr<PayloadParserFactory>(new GenericPayloadParserFactory<MUCAdminPayloadParser>("query", "http://jabber.org/protocol/muc#admin")));
factories_.push_back(shared_ptr<PayloadParserFactory>(new NicknameParserFactory()));
+ factories_.push_back(shared_ptr<PayloadParserFactory>(new JingleParserFactory(this)));
+ factories_.push_back(shared_ptr<PayloadParserFactory>(new GenericPayloadParserFactory<JingleReasonParser>("reason", "urn:xmpp:jingle:1")));
+ factories_.push_back(shared_ptr<PayloadParserFactory>(new JingleContentPayloadParserFactory(this)));
+ factories_.push_back(shared_ptr<PayloadParserFactory>(new GenericPayloadParserFactory<JingleIBBTransportMethodPayloadParser>("transport", "urn:xmpp:jingle:transports:ibb:1")));
+ factories_.push_back(shared_ptr<PayloadParserFactory>(new GenericPayloadParserFactory<JingleS5BTransportMethodPayloadParser>("transport", "urn:xmpp:jingle:transports:s5b:1")));
+ factories_.push_back(shared_ptr<PayloadParserFactory>(new JingleFileTransferDescriptionParserFactory(this)));
+ factories_.push_back(shared_ptr<PayloadParserFactory>(new GenericPayloadParserFactory<StreamInitiationFileInfoParser>("file", "http://jabber.org/protocol/si/profile/file-transfer")));
+ factories_.push_back(shared_ptr<PayloadParserFactory>(new GenericPayloadParserFactory<JingleFileTransferReceivedParser>("received", "urn:xmpp:jingle:apps:file-transfer:3")));
+ factories_.push_back(shared_ptr<PayloadParserFactory>(new GenericPayloadParserFactory<JingleFileTransferHashParser>("checksum")));
+ factories_.push_back(shared_ptr<PayloadParserFactory>(new GenericPayloadParserFactory<S5BProxyRequestParser>("query", "http://jabber.org/protocol/bytestreams")));
foreach(shared_ptr<PayloadParserFactory> factory, factories_) {
addFactory(factory.get());
}
diff --git a/Swiften/Parser/PayloadParsers/IBBParser.cpp b/Swiften/Parser/PayloadParsers/IBBParser.cpp
index 2705c75..20a1ce9 100644
--- a/Swiften/Parser/PayloadParsers/IBBParser.cpp
+++ b/Swiften/Parser/PayloadParsers/IBBParser.cpp
@@ -60,7 +60,7 @@ void IBBParser::handleEndElement(const std::string& element, const std::string&)
std::vector<char> data;
for (size_t i = 0; i < currentText.size(); ++i) {
char c = currentText[i];
- if (c >= 48 && c <= 122) {
+ if ((c >= 48 && c <= 122) || c == 47 || c == 43) {
data.push_back(c);
}
}
diff --git a/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp
new file mode 100644
index 0000000..1431b9e
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "JingleContentPayloadParser.h"
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Elements/JinglePayload.h>
+
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+ JingleContentPayloadParser::JingleContentPayloadParser(PayloadParserFactoryCollection* factories) : factories(factories), level(0) {
+
+ }
+
+ void JingleContentPayloadParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
+ if (level == 0) {
+ std::string creator = attributes.getAttributeValue("creator").get_value_or("");
+ if (creator == "initiator") {
+ getPayloadInternal()->setCreator(JingleContentPayload::InitiatorCreator);
+ } else if (creator == "responder") {
+ getPayloadInternal()->setCreator(JingleContentPayload::ResponderCreator);
+ } else {
+ getPayloadInternal()->setCreator(JingleContentPayload::UnknownCreator);
+ }
+
+ getPayloadInternal()->setName(attributes.getAttributeValue("name").get_value_or(""));
+ }
+
+ if (level == 1) {
+ PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
+ if (payloadParserFactory) {
+ currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+
+ ++level;
+ }
+
+ void JingleContentPayloadParser::handleEndElement(const std::string& element, const std::string& ns) {
+ --level;
+
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ boost::shared_ptr<JingleTransportPayload> transport = boost::dynamic_pointer_cast<JingleTransportPayload>(currentPayloadParser->getPayload());
+ if (transport) {
+ getPayloadInternal()->addTransport(transport);
+ }
+
+ boost::shared_ptr<JingleDescription> description = boost::dynamic_pointer_cast<JingleDescription>(currentPayloadParser->getPayload());
+ if (description) {
+ getPayloadInternal()->addDescription(description);
+ }
+ }
+ }
+ }
+
+ void JingleContentPayloadParser::handleCharacterData(const std::string& data) {
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
+ }
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h
new file mode 100644
index 0000000..a871cc4
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Elements/JingleContentPayload.h>
+#include <Swiften/Parser/GenericPayloadParser.h>
+
+namespace Swift {
+
+class PayloadParserFactoryCollection;
+
+class JingleContentPayloadParser : public GenericPayloadParser<JingleContentPayload> {
+ public:
+ JingleContentPayloadParser(PayloadParserFactoryCollection* factories);
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+ private:
+ PayloadParserFactoryCollection* factories;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+};
+
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h b/Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h
new file mode 100644
index 0000000..6d66e74
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleContentPayloadParserFactory.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Parser/GenericPayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParsers/JingleContentPayloadParser.h>
+
+namespace Swift {
+
+ class PayloadParserFactoryCollection;
+
+ class JingleContentPayloadParserFactory : public PayloadParserFactory {
+ public:
+ JingleContentPayloadParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
+ }
+
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return element == "content" && ns == "urn:xmpp:jingle:1";
+ }
+
+ virtual PayloadParser* createPayloadParser() {
+ return new JingleContentPayloadParser(factories);
+ }
+
+ private:
+ PayloadParserFactoryCollection* factories;
+
+ };
+}
+
+
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp
new file mode 100644
index 0000000..b394115
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.cpp
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "JingleFileTransferDescriptionParser.h"
+
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+
+JingleFileTransferDescriptionParser::JingleFileTransferDescriptionParser(PayloadParserFactoryCollection* factories) : factories(factories), level(0),
+ currentElement(UnknownElement) {
+
+}
+
+void JingleFileTransferDescriptionParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
+ if (level == 0) {
+
+ }
+
+ if (level == 1) {
+ if (element == "offer") {
+ currentElement = OfferElement;
+ } else if (element == "request") {
+ currentElement = RequestElement;
+ } else {
+ currentElement = UnknownElement;
+ }
+ }
+
+ if (level == 2) {
+ PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
+ if (payloadParserFactory) {
+ currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
+ }
+ }
+
+ if (level >= 2 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+
+ ++level;
+}
+
+void JingleFileTransferDescriptionParser::handleEndElement(const std::string& element, const std::string& ns) {
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 2) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 2) {
+ boost::shared_ptr<StreamInitiationFileInfo> info = boost::dynamic_pointer_cast<StreamInitiationFileInfo>(currentPayloadParser->getPayload());
+ if (info) {
+ if (currentElement == OfferElement) {
+ getPayloadInternal()->addOffer(*info);
+ } else if (currentElement == RequestElement) {
+ getPayloadInternal()->addRequest(*info);
+ }
+ }
+ }
+ }
+}
+
+void JingleFileTransferDescriptionParser::handleCharacterData(const std::string& data) {
+ if (level >= 2 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
+}
+
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h
new file mode 100644
index 0000000..93560c6
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Elements/JingleFileTransferDescription.h>
+#include <Swiften/Parser/GenericPayloadParser.h>
+#include <Swiften/Parser/PayloadParser.h>
+
+namespace Swift {
+
+class PayloadParserFactoryCollection;
+
+class JingleFileTransferDescriptionParser : public GenericPayloadParser<JingleFileTransferDescription> {
+ public:
+ JingleFileTransferDescriptionParser(PayloadParserFactoryCollection* factories);
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+ private:
+ enum CurrentParseElement {
+ UnknownElement,
+ RequestElement,
+ OfferElement,
+ };
+
+ PayloadParserFactoryCollection* factories;
+ int level;
+ CurrentParseElement currentElement;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+};
+
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h
new file mode 100644
index 0000000..b997c1d
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParserFactory.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Parser/GenericPayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParsers/JingleFileTransferDescriptionParser.h>
+
+namespace Swift {
+
+ class PayloadParserFactoryCollection;
+
+ class JingleFileTransferDescriptionParserFactory : public PayloadParserFactory {
+ public:
+ JingleFileTransferDescriptionParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
+ }
+
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return element == "description" && ns == "urn:xmpp:jingle:apps:file-transfer:3";
+ }
+
+ virtual PayloadParser* createPayloadParser() {
+ return new JingleFileTransferDescriptionParser(factories);
+ }
+
+ private:
+ PayloadParserFactoryCollection* factories;
+
+ };
+}
+
+
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp b/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp
new file mode 100644
index 0000000..87f8317
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.cpp
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "JingleFileTransferHashParser.h"
+
+#include <boost/shared_ptr.hpp>
+#include <boost/algorithm/string.hpp>
+
+#include <Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h>
+#include <Swiften/Parser/GenericPayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+
+namespace Swift {
+
+JingleFileTransferHashParser::JingleFileTransferHashParser() {
+}
+
+void JingleFileTransferHashParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
+ if (element == "hash") {
+ algo = attributes.getAttribute("algo");
+ }
+}
+
+void JingleFileTransferHashParser::handleEndElement(const std::string& element, const std::string& ) {
+ if (element == "hash" && !algo.empty() && !hash.empty()) {
+ getPayloadInternal()->setHash(algo, hash);
+ algo.clear();
+ hash.clear();
+ }
+}
+
+void JingleFileTransferHashParser::handleCharacterData(const std::string& data) {
+ if (!algo.empty()) {
+ std::string new_data(data);
+ boost::trim(new_data);
+ hash += new_data;
+ }
+}
+
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h b/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h
new file mode 100644
index 0000000..35e4a05
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferHashParser.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Elements/JingleFileTransferHash.h>
+#include <Swiften/Parser/GenericPayloadParser.h>
+
+namespace Swift {
+
+class JingleFileTransferHashParser : public GenericPayloadParser<JingleFileTransferHash> {
+public:
+ JingleFileTransferHashParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+private:
+ std::string algo;
+ std::string hash;
+};
+
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferReceivedParser.cpp b/Swiften/Parser/PayloadParsers/JingleFileTransferReceivedParser.cpp
new file mode 100644
index 0000000..20ad73e
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferReceivedParser.cpp
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "JingleFileTransferReceivedParser.h"
+#include "StreamInitiationFileInfoParser.h"
+
+#include <boost/shared_ptr.hpp>
+#include <Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h>
+#include <Swiften/Parser/GenericPayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+
+namespace Swift {
+
+JingleFileTransferReceivedParser::JingleFileTransferReceivedParser() : level(0) {
+}
+
+void JingleFileTransferReceivedParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
+ if (level == 1 && element == "file") {
+ PayloadParserFactory* payloadParserFactory = new GenericPayloadParserFactory<StreamInitiationFileInfoParser>("file", "http://jabber.org/protocol/si/profile/file-transfer");
+ if (payloadParserFactory) {
+ currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
+ }
+ }
+
+ if (currentPayloadParser && level >= 1) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+
+ ++level;
+}
+
+void JingleFileTransferReceivedParser::handleEndElement(const std::string& element, const std::string& ) {
+ --level;
+ if (element == "file") {
+ boost::shared_ptr<StreamInitiationFileInfo> fileInfo = boost::dynamic_pointer_cast<StreamInitiationFileInfo>(currentPayloadParser->getPayload());
+ if (fileInfo) {
+ getPayloadInternal()->setFileInfo(*fileInfo);
+ }
+ }
+}
+
+void JingleFileTransferReceivedParser::handleCharacterData(const std::string& ) {
+
+}
+
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleFileTransferReceivedParser.h b/Swiften/Parser/PayloadParsers/JingleFileTransferReceivedParser.h
new file mode 100644
index 0000000..824b06d
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleFileTransferReceivedParser.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Elements/JingleFileTransferReceived.h>
+#include <Swiften/Parser/GenericPayloadParser.h>
+
+namespace Swift {
+
+class JingleFileTransferReceivedParser : public GenericPayloadParser<JingleFileTransferReceived> {
+public:
+ JingleFileTransferReceivedParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+private:
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+ int level;
+};
+
+} \ No newline at end of file
diff --git a/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp
new file mode 100644
index 0000000..a3dfd12
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <boost/lexical_cast.hpp>
+#include <boost/optional.hpp>
+
+#include "JingleIBBTransportMethodPayloadParser.h"
+
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+ JingleIBBTransportMethodPayloadParser::JingleIBBTransportMethodPayloadParser() : level(0) {
+
+ }
+
+ void JingleIBBTransportMethodPayloadParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) {
+ try {
+ getPayloadInternal()->setBlockSize(boost::lexical_cast<int>(attributes.getAttributeValue("block-size").get_value_or("0")));
+ } catch (boost::bad_lexical_cast &) {
+ getPayloadInternal()->setBlockSize(0);
+ }
+ getPayloadInternal()->setSessionID(attributes.getAttributeValue("sid").get_value_or(""));
+ ++level;
+ }
+
+ void JingleIBBTransportMethodPayloadParser::handleEndElement(const std::string&, const std::string&) {
+ --level;
+
+
+ }
+
+ void JingleIBBTransportMethodPayloadParser::handleCharacterData(const std::string&) {
+
+ }
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h
new file mode 100644
index 0000000..311cc5b
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleIBBTransportMethodPayloadParser.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#include <Swiften/Parser/GenericPayloadParser.h>
+
+namespace Swift {
+
+class JingleIBBTransportMethodPayloadParser : public GenericPayloadParser<JingleIBBTransportPayload> {
+ public:
+ JingleIBBTransportMethodPayloadParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+ private:
+ int level;
+};
+
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleParser.cpp b/Swiften/Parser/PayloadParsers/JingleParser.cpp
new file mode 100644
index 0000000..dd34458
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleParser.cpp
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Parser/PayloadParsers/JingleParser.h>
+#include <Swiften/Parser/PayloadParserFactory.h>
+#include <Swiften/Elements/JingleContentPayload.h>
+#include <Swiften/Elements/JingleFileTransferReceived.h>
+#include <Swiften/Elements/JingleFileTransferHash.h>
+#include <Swiften/Base/Log.h>
+
+#include <boost/intrusive_ptr.hpp>
+
+namespace Swift {
+
+ JingleParser::JingleParser(PayloadParserFactoryCollection* factories) : factories(factories), level(0) {
+
+ }
+
+ void JingleParser::handleStartElement(const std::string& element, const std::string &ns, const AttributeMap& attributes) {
+ if (level == 0) {
+ // <jingle > tag
+ JinglePayload::ref payload = getPayloadInternal();
+ payload->setAction(stringToAction(attributes.getAttributeValue("action").get_value_or("")));
+ payload->setInitiator(JID(attributes.getAttributeValue("initiator").get_value_or("")));
+ payload->setResponder(JID(attributes.getAttributeValue("responder").get_value_or("")));
+ payload->setSessionID(attributes.getAttributeValue("sid").get_value_or(""));
+ }
+
+ if (level == 1) {
+ PayloadParserFactory* payloadParserFactory = factories->getPayloadParserFactory(element, ns, attributes);
+ if (payloadParserFactory) {
+ currentPayloadParser.reset(payloadParserFactory->createPayloadParser());
+ }
+ }
+
+ if (level >= 1 && currentPayloadParser) {
+ currentPayloadParser->handleStartElement(element, ns, attributes);
+ }
+
+ ++level;
+ }
+
+ void JingleParser::handleEndElement(const std::string& element, const std::string &ns) {
+ --level;
+ if (currentPayloadParser) {
+ if (level >= 1) {
+ currentPayloadParser->handleEndElement(element, ns);
+ }
+
+ if (level == 1) {
+ boost::shared_ptr<JinglePayload::Reason> reason = boost::dynamic_pointer_cast<JinglePayload::Reason>(currentPayloadParser->getPayload());
+ if (reason) {
+ getPayloadInternal()->setReason(*reason);
+ }
+
+ boost::shared_ptr<JingleContentPayload> payload = boost::dynamic_pointer_cast<JingleContentPayload>(currentPayloadParser->getPayload());
+ if (payload) {
+ getPayloadInternal()->addContent(payload);
+ }
+
+ boost::shared_ptr<JingleFileTransferReceived> received = boost::dynamic_pointer_cast<JingleFileTransferReceived>(currentPayloadParser->getPayload());
+ if (received) {
+ getPayloadInternal()->addPayload(received);
+ }
+
+ boost::shared_ptr<JingleFileTransferHash> hash = boost::dynamic_pointer_cast<JingleFileTransferHash>(currentPayloadParser->getPayload());
+ if (hash) {
+ getPayloadInternal()->addPayload(hash);
+ }
+ }
+ }
+ }
+
+ void JingleParser::handleCharacterData(const std::string& data) {
+ if (level > 1 && currentPayloadParser) {
+ currentPayloadParser->handleCharacterData(data);
+ }
+ }
+
+ JinglePayload::Action JingleParser::stringToAction(const std::string &str) const {
+ if (str == "content-accept") {
+ return JinglePayload::ContentAccept;
+ } else if (str == "content-add") {
+ return JinglePayload::ContentAdd;
+ } else if (str == "content-modify") {
+ return JinglePayload::ContentModify;
+ } else if (str == "content-reject") {
+ return JinglePayload::ContentReject;
+ } else if (str == "content-remove") {
+ return JinglePayload::ContentRemove;
+ } else if (str == "description-info") {
+ return JinglePayload::DescriptionInfo;
+ } else if (str == "security-info") {
+ return JinglePayload::SecurityInfo;
+ } else if (str == "session-accept") {
+ return JinglePayload::SessionAccept;
+ } else if (str == "session-info") {
+ return JinglePayload::SessionInfo;
+ } else if (str == "session-initiate") {
+ return JinglePayload::SessionInitiate;
+ } else if (str == "session-terminate") {
+ return JinglePayload::SessionTerminate;
+ } else if (str == "transport-accept") {
+ return JinglePayload::TransportAccept;
+ } else if (str == "transport-info") {
+ return JinglePayload::TransportInfo;
+ } else if (str == "transport-reject") {
+ return JinglePayload::TransportReject;
+ } else if (str == "transport-replace") {
+ return JinglePayload::TransportReplace;
+ } else {
+ return JinglePayload::UnknownAction;
+ }
+
+ }
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleParser.h b/Swiften/Parser/PayloadParsers/JingleParser.h
new file mode 100644
index 0000000..ecaca3c
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleParser.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Elements/JinglePayload.h>
+#include <Swiften/Parser/GenericPayloadParser.h>
+#include <Swiften/Parser/PayloadParserFactoryCollection.h>
+
+namespace Swift {
+
+class JingleParser : public GenericPayloadParser<JinglePayload> {
+ public:
+ JingleParser(PayloadParserFactoryCollection* factories);
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+ private:
+ JinglePayload::Action stringToAction(const std::string &str) const;
+
+ private:
+ PayloadParserFactoryCollection* factories;
+ int level;
+ boost::shared_ptr<PayloadParser> currentPayloadParser;
+};
+
+}; \ No newline at end of file
diff --git a/Swiften/Parser/PayloadParsers/JingleParserFactory.h b/Swiften/Parser/PayloadParsers/JingleParserFactory.h
new file mode 100644
index 0000000..fa25aeb
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleParserFactory.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Parser/GenericPayloadParserFactory.h>
+#include <Swiften/Parser/PayloadParsers/JingleParser.h>
+
+namespace Swift {
+
+ class PayloadParserFactoryCollection;
+
+ class JingleParserFactory : public PayloadParserFactory {
+ public:
+ JingleParserFactory(PayloadParserFactoryCollection* factories) : factories(factories) {
+ }
+
+ virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const {
+ return element == "jingle" && ns == "urn:xmpp:jingle:1";
+ }
+
+ virtual PayloadParser* createPayloadParser() {
+ return new JingleParser(factories);
+ }
+
+ private:
+ PayloadParserFactoryCollection* factories;
+
+ };
+}
+
+
diff --git a/Swiften/Parser/PayloadParsers/JingleReasonParser.cpp b/Swiften/Parser/PayloadParsers/JingleReasonParser.cpp
new file mode 100644
index 0000000..3df82ae
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleReasonParser.cpp
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "JingleReasonParser.h"
+
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+ JingleReasonParser::JingleReasonParser() : level(0), parseText(false) {
+
+ }
+
+ void JingleReasonParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap&) {
+ if (level == 1) {
+ if (element == "text") {
+ parseText = true;
+ } else {
+ // reason type
+ getPayloadInternal()->type = stringToReasonType(element);
+ }
+ }
+ ++level;
+ }
+
+ void JingleReasonParser::handleEndElement(const std::string& element, const std::string&) {
+ --level;
+ if (element == "text") {
+ parseText = false;
+ getPayloadInternal()->text = text;
+ }
+ }
+
+ void JingleReasonParser::handleCharacterData(const std::string& data) {
+ if (parseText) {
+ text += data;
+ }
+ }
+
+ JinglePayload::Reason::Type JingleReasonParser::stringToReasonType(const std::string& type) const {
+ if (type == "alternative-session") {
+ return JinglePayload::Reason::AlternativeSession;
+ } else if (type == "busy") {
+ return JinglePayload::Reason::Busy;
+ } else if (type == "cancel") {
+ return JinglePayload::Reason::Cancel;
+ } else if (type == "connectivity-error") {
+ return JinglePayload::Reason::ConnectivityError;
+ } else if (type == "decline") {
+ return JinglePayload::Reason::Decline;
+ } else if (type == "expired") {
+ return JinglePayload::Reason::Expired;
+ } else if (type == "failed-application") {
+ return JinglePayload::Reason::FailedApplication;
+ } else if (type == "failed-transport") {
+ return JinglePayload::Reason::FailedTransport;
+ } else if (type == "general-error") {
+ return JinglePayload::Reason::GeneralError;
+ } else if (type == "gone") {
+ return JinglePayload::Reason::Gone;
+ } else if (type == "incompatible-parameters") {
+ return JinglePayload::Reason::IncompatibleParameters;
+ } else if (type == "media-error") {
+ return JinglePayload::Reason::MediaError;
+ } else if (type == "security-error") {
+ return JinglePayload::Reason::SecurityError;
+ } else if (type == "success") {
+ return JinglePayload::Reason::Success;
+ } else if (type == "timeout") {
+ return JinglePayload::Reason::Timeout;
+ } else if (type == "unsupported-applications") {
+ return JinglePayload::Reason::UnsupportedApplications;
+ } else if (type == "unsupported-transports") {
+ return JinglePayload::Reason::UnsupportedTransports;
+ } else {
+ return JinglePayload::Reason::UnknownType;
+ }
+ }
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleReasonParser.h b/Swiften/Parser/PayloadParsers/JingleReasonParser.h
new file mode 100644
index 0000000..08af31a
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleReasonParser.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Elements/JinglePayload.h>
+#include <Swiften/Parser/GenericPayloadParser.h>
+
+namespace Swift {
+
+class JingleReasonParser : public GenericPayloadParser<JinglePayload::Reason> {
+ public:
+ JingleReasonParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+ private:
+ JinglePayload::Reason::Type stringToReasonType(const std::string& type) const;
+
+ private:
+ int level;
+ bool parseText;
+ std::string text;
+};
+
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp
new file mode 100644
index 0000000..14a80e6
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <boost/lexical_cast.hpp>
+#include <boost/optional.hpp>
+
+#include "JingleS5BTransportMethodPayloadParser.h"
+
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+ JingleS5BTransportMethodPayloadParser::JingleS5BTransportMethodPayloadParser() : level(0) {
+
+ }
+
+ void JingleS5BTransportMethodPayloadParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
+ if (level == 0) {
+ getPayloadInternal()->setSessionID(attributes.getAttributeValue("sid").get_value_or(""));
+ std::string mode = attributes.getAttributeValue("mode").get_value_or("tcp");
+ if (mode == "tcp") {
+ getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode);
+ } else if(mode == "udp") {
+ getPayloadInternal()->setMode(JingleS5BTransportPayload::UDPMode);
+ } else {
+ std::cerr << "Unknown S5B mode; falling back to defaul!" << std::endl;
+ getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode);
+ }
+ } else if (level == 1) {
+ if (element == "candidate") {
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate.cid = attributes.getAttributeValue("cid").get_value_or("");
+
+ int port = -1;
+ try {
+ port = boost::lexical_cast<int>(attributes.getAttributeValue("port").get_value_or("-1"));
+ } catch(boost::bad_lexical_cast &) { }
+ candidate.hostPort = HostAddressPort(HostAddress(attributes.getAttributeValue("host").get_value_or("")), port);
+ candidate.jid = JID(attributes.getAttributeValue("jid").get_value_or(""));
+ int priority = -1;
+ try {
+ priority = boost::lexical_cast<int>(attributes.getAttributeValue("priority").get_value_or("-1"));
+ } catch(boost::bad_lexical_cast &) { }
+ candidate.priority = priority;
+ candidate.type = stringToType(attributes.getAttributeValue("type").get_value_or("direct"));
+
+ getPayloadInternal()->addCandidate(candidate);
+ } else if (element == "candidate-used") {
+ getPayloadInternal()->setCandidateUsed(attributes.getAttributeValue("cid").get_value_or(""));
+ } else if (element == "candidate-error") {
+ getPayloadInternal()->setCandidateError(true);
+ } else if (element == "activated") {
+ getPayloadInternal()->setActivated(attributes.getAttributeValue("cid").get_value_or(""));
+ } else if (element == "proxy-error") {
+ getPayloadInternal()->setProxyError(true);
+ }
+ }
+
+ ++level;
+ }
+
+ void JingleS5BTransportMethodPayloadParser::handleEndElement(const std::string&, const std::string&) {
+ --level;
+
+
+ }
+
+ void JingleS5BTransportMethodPayloadParser::handleCharacterData(const std::string&) {
+
+ }
+
+ JingleS5BTransportPayload::Candidate::Type JingleS5BTransportMethodPayloadParser::stringToType(const std::string &str) const {
+ if (str == "direct") {
+ return JingleS5BTransportPayload::Candidate::DirectType;
+ } else if (str == "assisted") {
+ return JingleS5BTransportPayload::Candidate::AssistedType;
+ } else if (str == "tunnel") {
+ return JingleS5BTransportPayload::Candidate::TunnelType;
+ } else if (str == "proxy") {
+ return JingleS5BTransportPayload::Candidate::ProxyType;
+ } else {
+ std::cerr << "Unknown candidate type; falling back to default!" << std::endl;
+ return JingleS5BTransportPayload::Candidate::DirectType;
+ }
+ }
+}
diff --git a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h
new file mode 100644
index 0000000..1987d3f
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/Parser/GenericPayloadParser.h>
+
+namespace Swift {
+
+class JingleS5BTransportMethodPayloadParser : public GenericPayloadParser<JingleS5BTransportPayload> {
+ public:
+ JingleS5BTransportMethodPayloadParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+ private:
+ JingleS5BTransportPayload::Candidate::Type stringToType(const std::string &str) const;
+
+ private:
+ int level;
+};
+
+}
diff --git a/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp
new file mode 100644
index 0000000..6e33f16
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "S5BProxyRequestParser.h"
+
+#include <boost/lexical_cast.hpp>
+#include <boost/optional.hpp>
+
+namespace Swift {
+
+S5BProxyRequestParser::S5BProxyRequestParser() : parseActivate(false) {
+}
+
+S5BProxyRequestParser::~S5BProxyRequestParser() {
+}
+
+void S5BProxyRequestParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
+ if (element == "streamhost") {
+ if (attributes.getAttributeValue("host") && attributes.getAttributeValue("jid") && attributes.getAttributeValue("port")) {
+ HostAddress address = attributes.getAttributeValue("host").get_value_or("");
+ int port = -1;
+ JID jid = attributes.getAttributeValue("jid").get_value_or("");
+
+ try {
+ port = boost::lexical_cast<int>(attributes.getAttributeValue("port").get());
+ } catch (boost::bad_lexical_cast &) {
+ port = -1;
+ }
+ if (address.isValid() && port != -1 && jid.isValid()) {
+ S5BProxyRequest::StreamHost streamHost;
+ streamHost.addressPort = HostAddressPort(address, port);
+ streamHost.jid = jid;
+ getPayloadInternal()->setStreamHost(streamHost);
+ }
+ }
+ } else if (element == "activate") {
+ parseActivate = true;
+ } else if (element == "query") {
+ if (attributes.getAttributeValue("sid")) {
+ getPayloadInternal()->setSID(attributes.getAttributeValue("sid").get());
+ }
+ }
+}
+
+void S5BProxyRequestParser::handleEndElement(const std::string& element, const std::string&) {
+ if (element == "activate") {
+ JID activate = JID(activateJID);
+ if (activate.isValid()) {
+ getPayloadInternal()->setActivate(activate);
+ }
+ parseActivate = false;
+ }
+}
+
+void S5BProxyRequestParser::handleCharacterData(const std::string& data) {
+ if (parseActivate) {
+ activateJID = activateJID + data;
+ }
+}
+
+}
diff --git a/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h
new file mode 100644
index 0000000..0bf1a26
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <string>
+
+#include <Swiften/Elements/S5BProxyRequest.h>
+#include <Swiften/Parser/GenericPayloadParser.h>
+
+namespace Swift {
+
+class S5BProxyRequestParser : public GenericPayloadParser<S5BProxyRequest> {
+public:
+ S5BProxyRequestParser();
+ virtual ~S5BProxyRequestParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+private:
+ bool parseActivate;
+ std::string activateJID;
+};
+
+}
diff --git a/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp
new file mode 100644
index 0000000..0a13844
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include "StreamInitiationFileInfoParser.h"
+
+#include <boost/optional.hpp>
+#include <boost/lexical_cast.hpp>
+
+#include <Swiften/Base/DateTime.h>
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+
+StreamInitiationFileInfoParser::StreamInitiationFileInfoParser() : level(0), parseDescription(false) {
+
+}
+
+void StreamInitiationFileInfoParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) {
+ if (level == 0) {
+ getPayloadInternal()->setName(attributes.getAttributeValue("name").get_value_or(""));
+ getPayloadInternal()->setHash(attributes.getAttributeValue("hash").get_value_or(""));
+ getPayloadInternal()->setAlgo(attributes.getAttributeValue("algo").get_value_or("md5"));
+ try {
+ getPayloadInternal()->setSize(boost::lexical_cast<boost::uintmax_t>(attributes.getAttributeValue("size").get_value_or("0")));
+ } catch (boost::bad_lexical_cast &) {
+ getPayloadInternal()->setSize(0);
+ }
+ getPayloadInternal()->setDate(stringToDateTime(attributes.getAttributeValue("date").get_value_or("")));
+ } else if (level == 1) {
+ if (element == "desc") {
+ parseDescription = true;
+ } else {
+ parseDescription = false;
+ if (element == "range") {
+ int offset = 0;
+ try {
+ offset = boost::lexical_cast<boost::uintmax_t>(attributes.getAttributeValue("offset").get_value_or("0"));
+ } catch (boost::bad_lexical_cast &) {
+ offset = 0;
+ }
+ if (offset == 0) {
+ getPayloadInternal()->setSupportsRangeRequests(true);
+ } else {
+ getPayloadInternal()->setRangeOffset(offset);
+ }
+ }
+ }
+ }
+ ++level;
+}
+
+void StreamInitiationFileInfoParser::handleEndElement(const std::string& element, const std::string&) {
+ --level;
+ if (parseDescription && element == "desc") {
+ parseDescription = false;
+ getPayloadInternal()->setDescription(desc);
+ }
+}
+
+void StreamInitiationFileInfoParser::handleCharacterData(const std::string& data) {
+ if (parseDescription) {
+ desc += data;
+ }
+}
+
+}
diff --git a/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h
new file mode 100644
index 0000000..6d3591d
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/StreamInitiationFileInfoParser.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#pragma once
+
+#include <Swiften/Elements/StreamInitiationFileInfo.h>
+#include <Swiften/Parser/GenericPayloadParser.h>
+
+namespace Swift {
+
+class StreamInitiationFileInfoParser : public GenericPayloadParser<StreamInitiationFileInfo> {
+ public:
+ StreamInitiationFileInfoParser();
+
+ virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes);
+ virtual void handleEndElement(const std::string& element, const std::string&);
+ virtual void handleCharacterData(const std::string& data);
+
+ private:
+ int level;
+ bool parseDescription;
+ std::string desc;
+};
+
+}
diff --git a/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp b/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
index 9ea8089..fd3d019 100644
--- a/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
+++ b/Swiften/Parser/PayloadParsers/StreamInitiationParser.cpp
@@ -38,9 +38,9 @@ void StreamInitiationParser::handleStartElement(const std::string& element, cons
if (element == "file") {
inFile = true;
currentFile = StreamInitiationFileInfo();
- currentFile.name = attributes.getAttribute("name");
+ currentFile.setName(attributes.getAttribute("name"));
try {
- currentFile.size = boost::lexical_cast<int>(attributes.getAttribute("size"));
+ currentFile.setSize(boost::lexical_cast<int>(attributes.getAttribute("size")));
}
catch (boost::bad_lexical_cast&) {
}
@@ -83,7 +83,7 @@ void StreamInitiationParser::handleEndElement(const std::string& element, const
}
else if (level == FileOrFeatureLevel) {
if (inFile && element == "desc") {
- currentFile.description = currentText;
+ currentFile.setDescription(currentText);
}
else if (formParser) {
Form::ref form = formParser->getPayloadInternal();
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp
new file mode 100644
index 0000000..d03ba8b
--- /dev/null
+++ b/Swiften/Parser/PayloadParsers/UnitTest/JingleParserTest.cpp
@@ -0,0 +1,709 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h>
+#include <Swiften/Elements/JinglePayload.h>
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/Elements/JingleFileTransferDescription.h>
+#include <Swiften/Elements/StreamInitiationFileInfo.h>
+#include <Swiften/Elements/JingleFileTransferReceived.h>
+#include <Swiften/Elements/JingleFileTransferHash.h>
+#include <Swiften/Base/DateTime.h>
+
+#include <Swiften/Base/Log.h>
+
+using namespace Swift;
+
+class JingleParserTest : public CppUnit::TestFixture {
+ CPPUNIT_TEST_SUITE(JingleParserTest);
+ CPPUNIT_TEST(testParse_Xep0166_Example3);
+ CPPUNIT_TEST(testParse_Xep0166_Example8);
+
+ CPPUNIT_TEST(testParse_Xep0261_Example1);
+ CPPUNIT_TEST(testParse_Xep0261_Example3);
+ CPPUNIT_TEST(testParse_Xep0261_Example9);
+ CPPUNIT_TEST(testParse_Xep0261_Example13);
+
+ CPPUNIT_TEST(testParse_Xep0234_Example1);
+ CPPUNIT_TEST(testParse_Xep0234_Example3);
+ CPPUNIT_TEST(testParse_Xep0234_Example5);
+ CPPUNIT_TEST(testParse_Xep0234_Example8);
+ CPPUNIT_TEST(testParse_Xep0234_Example10);
+ CPPUNIT_TEST(testParse_Xep0234_Example11);
+ CPPUNIT_TEST(testParse_Xep0234_Example12);
+
+ CPPUNIT_TEST(testParse_Xep0260_Example1);
+ CPPUNIT_TEST(testParse_Xep0260_Example3);
+ CPPUNIT_TEST_SUITE_END();
+
+ public:
+ //http://xmpp.org/extensions/xep-0166.html#example-3
+ void testParse_Xep0166_Example3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-terminate'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <reason>\n"
+ " <success/>\n"
+ " </reason>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionTerminate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::Reason::Success,
+ jingle->getReason().get_value_or(JinglePayload::Reason(JinglePayload::Reason::UnknownType, "")).type);
+ }
+
+ //http://xmpp.org/extensions/xep-0166.html#example-8
+ void testParse_Xep0166_Example8() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-terminate'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <reason>\n"
+ " <success/>\n"
+ " <text>Sorry, gotta go!</text>\n"
+ " </reason>\n"
+ "</jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionTerminate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::Reason::Success,
+ jingle->getReason().get_value_or(JinglePayload::Reason(JinglePayload::Reason::UnknownType, "")).type);
+ CPPUNIT_ASSERT_EQUAL(std::string("Sorry, gotta go!"),
+ jingle->getReason().get_value_or(JinglePayload::Reason(JinglePayload::Reason::UnknownType, "")).text);
+ }
+
+ // IBB Transport Method Examples
+
+ // http://xmpp.org/extensions/xep-0261.html#example-1
+ void testParse_Xep0261_Example1() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-initiate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <description xmlns='urn:xmpp:example'/>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:ibb:1'\n"
+ " block-size='4096'\n"
+ " sid='ch3d9s71'/>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> payloads = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payloads.size());
+ JingleContentPayload::ref payload = payloads[0];
+ CPPUNIT_ASSERT_EQUAL(JingleContentPayload::InitiatorCreator, payload->getCreator());
+ CPPUNIT_ASSERT_EQUAL(std::string("ex"), payload->getName());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payload->getTransports().size());
+
+ JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>();
+ CPPUNIT_ASSERT(transportPaylod);
+ CPPUNIT_ASSERT_EQUAL(4096, transportPaylod->getBlockSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("ch3d9s71"), transportPaylod->getSessionID());
+ }
+
+ // http://xmpp.org/extensions/xep-0261.html#example-1
+ void testParse_Xep0261_Example3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-accept'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " responder='juliet@capulet.lit/balcony'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <description xmlns='urn:xmpp:example'/>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:ibb:1'\n"
+ " block-size='2048'\n"
+ " sid='ch3d9s71'/>\n"
+ " </content>\n"
+ " </jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionAccept, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), jingle->getResponder());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> payloads = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payloads.size());
+ JingleContentPayload::ref payload = payloads[0];
+ CPPUNIT_ASSERT_EQUAL(JingleContentPayload::InitiatorCreator, payload->getCreator());
+ CPPUNIT_ASSERT_EQUAL(std::string("ex"), payload->getName());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payload->getTransports().size());
+
+ JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>();
+ CPPUNIT_ASSERT(transportPaylod);
+ CPPUNIT_ASSERT_EQUAL(2048, transportPaylod->getBlockSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("ch3d9s71"), transportPaylod->getSessionID());
+ }
+
+ // http://xmpp.org/extensions/xep-0261.html#example-9
+ void testParse_Xep0261_Example9() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='transport-info'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:ibb:1'\n"
+ " block-size='2048'\n"
+ " sid='bt8a71h6'/>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::TransportInfo, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> payloads = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), payloads.size());
+ JingleContentPayload::ref payload = payloads[0];
+ CPPUNIT_ASSERT_EQUAL(JingleContentPayload::InitiatorCreator, payload->getCreator());
+ CPPUNIT_ASSERT_EQUAL(std::string("ex"), payload->getName());
+
+ JingleIBBTransportPayload::ref transportPaylod = payload->getTransport<JingleIBBTransportPayload>();
+ CPPUNIT_ASSERT(transportPaylod);
+ CPPUNIT_ASSERT_EQUAL(2048, transportPaylod->getBlockSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("bt8a71h6"), transportPaylod->getSessionID());
+ }
+
+ // http://xmpp.org/extensions/xep-0261.html#example-13
+ void testParse_Xep0261_Example13() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-terminate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <reason><success/></reason>\n"
+ " </jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionTerminate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::Reason::Success, jingle->getReason().get_value_or(JinglePayload::Reason()).type);
+
+ }
+
+ // Jingle File Transfer Examples
+
+ // http://xmpp.org/extensions/xep-0234.html#example-1
+ void testParse_Xep0234_Example1() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-initiate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='851ba2'>\n"
+ " <content creator='initiator' name='a-file-offer'>\n"
+ " <description xmlns='urn:xmpp:jingle:apps:file-transfer:3'>\n"
+ " <offer>\n"
+ " <file xmlns='http://jabber.org/protocol/si/profile/file-transfer'\n"
+ " date='1969-07-21T02:56:15Z'\n"
+ " hash='552da749930852c69ae5d2141d3766b1'\n"
+ " name='test.txt'\n"
+ " size='1022'>\n"
+ " <desc>This is a test. If this were a real file...</desc>\n"
+ " <range/>\n"
+ " </file>\n"
+ " </offer>\n"
+ " </description>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " mode='tcp'\n"
+ " sid='vj3hs98y'>\n"
+ " <candidate cid='hft54dqy'\n"
+ " host='192.168.4.1'\n"
+ " jid='romeo@montague.lit/orchard'\n"
+ " port='5086'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ " <candidate cid='hutr46fe'\n"
+ " host='24.24.24.1'\n"
+ " jid='romeo@montague.lit/orchard'\n"
+ " port='5087'\n"
+ " priority='8258636'\n"
+ " type='direct'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ " </jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("851ba2"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> contents = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), contents.size());
+
+ JingleFileTransferDescription::ref description = contents[0]->getDescription<JingleFileTransferDescription>();
+
+
+ std::vector<StreamInitiationFileInfo> offers = description->getOffers();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), offers.size());
+ CPPUNIT_ASSERT_EQUAL(std::string("test.txt"), offers[0].getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("552da749930852c69ae5d2141d3766b1"), offers[0].getHash());
+ CPPUNIT_ASSERT(1022 == offers[0].getSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("This is a test. If this were a real file..."), offers[0].getDescription());
+ CPPUNIT_ASSERT_EQUAL(true, offers[0].getSupportsRangeRequests());
+ CPPUNIT_ASSERT(stringToDateTime("1969-07-21T02:56:15Z") == offers[0].getDate());
+ CPPUNIT_ASSERT_EQUAL(std::string("md5"), offers[0].getAlgo());
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-3
+ void testParse_Xep0234_Example3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-accept'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='851ba2'>\n"
+ " <content creator='initiator' name='a-file-offer'>\n"
+ " <description xmlns='urn:xmpp:jingle:apps:file-transfer:3'>\n"
+ " <offer>\n"
+ " <file xmlns='http://jabber.org/protocol/si/profile/file-transfer'\n"
+ " name='test.txt'\n"
+ " size='1022'\n"
+ " hash='552da749930852c69ae5d2141d3766b1'\n"
+ " date='1969-07-21T02:56:15Z'>\n"
+ " <desc>This is a test. If this were a real file...</desc>\n"
+ " <range/>\n"
+ " </file>\n"
+ " </offer>\n"
+ " </description>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " mode='tcp'\n"
+ " sid='vj3hs98y'>\n"
+ " <candidate cid='ht567dq'\n"
+ " host='192.169.1.10'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ " <candidate cid='hr65dqyd'\n"
+ " host='134.102.201.180'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='16453'\n"
+ " priority='7929856'\n"
+ " type='assisted'/>\n"
+ " <candidate cid='grt654q2'\n"
+ " host='2001:638:708:30c9:219:d1ff:fea4:a17d'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257606'\n"
+ " type='direct'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionAccept, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("851ba2"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> contents = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), contents.size());
+
+ JingleFileTransferDescription::ref description = contents[0]->getDescription<JingleFileTransferDescription>();
+
+
+ std::vector<StreamInitiationFileInfo> offers = description->getOffers();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), offers.size());
+ CPPUNIT_ASSERT_EQUAL(std::string("test.txt"), offers[0].getName());
+ CPPUNIT_ASSERT_EQUAL(std::string("552da749930852c69ae5d2141d3766b1"), offers[0].getHash());
+ CPPUNIT_ASSERT(1022 == offers[0].getSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("This is a test. If this were a real file..."), offers[0].getDescription());
+ CPPUNIT_ASSERT_EQUAL(true, offers[0].getSupportsRangeRequests());
+ CPPUNIT_ASSERT(stringToDateTime("1969-07-21T02:56:15Z") == offers[0].getDate());
+ CPPUNIT_ASSERT_EQUAL(std::string("md5"), offers[0].getAlgo());
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-5
+ void testParse_Xep0234_Example5() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='transport-info'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " sid='vj3hs98y'>\n"
+ " <candidate-used cid='hr65dqyd'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::TransportInfo, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ std::vector<JingleContentPayload::ref> contents = jingle->getContents();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), contents.size());
+
+ JingleS5BTransportPayload::ref transport = contents[0]->getTransport<JingleS5BTransportPayload>();
+ CPPUNIT_ASSERT(transport);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("vj3hs98y"), transport->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(std::string("hr65dqyd"), transport->getCandidateUsed());
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-8
+ void testParse_Xep0234_Example8() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-info'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <checksum xmlns='urn:xmpp:jingle:apps:file-transfer:3'>\n"
+ " <file>\n"
+ " <hashes xmlns='urn:xmpp:hashes:0'>\n"
+ " <hash algo='sha-1'>552da749930852c69ae5d2141d3766b1</hash>\n"
+ " </hashes>\n"
+ " </file>\n"
+ " </checksum>\n"
+ "</jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInfo, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ JingleFileTransferHash::ref hash = jingle->getPayload<JingleFileTransferHash>();
+ CPPUNIT_ASSERT(hash);
+ CPPUNIT_ASSERT_EQUAL(std::string("552da749930852c69ae5d2141d3766b1"), hash->getHashes().at("sha-1"));
+
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-10
+ void testParse_Xep0234_Example10() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-initiate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='uj3b2'>\n"
+ " <content creator='initiator' name='a-file-request'>\n"
+ " <description xmlns='urn:xmpp:jingle:apps:file-transfer:3'>\n"
+ " <request>\n"
+ " <file xmlns='http://jabber.org/protocol/si/profile/file-transfer'\n"
+ " hash='552da749930852c69ae5d2141d3766b1'>\n"
+ " <range offset='270336'/>\n"
+ " </file>\n"
+ " </request>\n"
+ " </description>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " mode='tcp'\n"
+ " sid='xig361fj'>\n"
+ " <candidate cid='ht567dq'\n"
+ " host='192.169.1.10'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ " <candidate cid='hr65dqyd'\n"
+ " host='134.102.201.180'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='16453'\n"
+ " priority='7929856'\n"
+ " type='assisted'/>\n"
+ " <candidate cid='grt654q2'\n"
+ " host='2001:638:708:30c9:219:d1ff:fea4:a17d'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257606'\n"
+ " type='direct'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("uj3b2"), jingle->getSessionID());
+
+ JingleContentPayload::ref content = jingle->getPayload<JingleContentPayload>();
+ CPPUNIT_ASSERT(content);
+
+ StreamInitiationFileInfo file = content->getDescription<JingleFileTransferDescription>()->getRequests()[0];
+ CPPUNIT_ASSERT_EQUAL(std::string("552da749930852c69ae5d2141d3766b1"), file.getHash());
+ CPPUNIT_ASSERT_EQUAL(270336, file.getRangeOffset());
+ CPPUNIT_ASSERT_EQUAL(true, file.getSupportsRangeRequests());
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-11
+ void testParse_Xep0234_Example11() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-initiate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='h2va419i'>\n"
+ " <content creator='initiator' name='a-file-offer'>\n"
+ " <description xmlns='urn:xmpp:jingle:apps:file-transfer:3'>\n"
+ " <offer>\n"
+ " <file xmlns='http://jabber.org/protocol/si/profile/file-transfer'\n"
+ " date='2011-06-01T15:58:15Z'\n"
+ " hash='a749930852c69ae5d2141d3766b1552d'\n"
+ " name='somefile.txt'\n"
+ " size='1234'/>\n"
+ " <file xmlns='http://jabber.org/protocol/si/profile/file-transfer'\n"
+ " date='2011-06-01T15:58:15Z'\n"
+ " hash='930852c69ae5d2141d3766b1552da749'\n"
+ " name='anotherfile.txt'\n"
+ " size='2345'/>\n"
+ " <file xmlns='http://jabber.org/protocol/si/profile/file-transfer'\n"
+ " date='2011-06-01T15:58:15Z'\n"
+ " hash='52c69ae5d2141d3766b1552da7499308'\n"
+ " name='yetanotherfile.txt'\n"
+ " size='3456'/>\n"
+ " </offer>\n"
+ " </description>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " mode='tcp'\n"
+ " sid='vj3hs98y'>\n"
+ " <candidate cid='hft54dqy'\n"
+ " host='192.168.4.1'\n"
+ " jid='romeo@montague.lit/orchard'\n"
+ " port='5086'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ " <candidate cid='hutr46fe'\n"
+ " host='24.24.24.1'\n"
+ " jid='romeo@montague.lit/orchard'\n"
+ " port='5087'\n"
+ " priority='8258636'\n"
+ " type='direct'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("h2va419i"), jingle->getSessionID());
+
+ JingleContentPayload::ref content = jingle->getPayload<JingleContentPayload>();
+ CPPUNIT_ASSERT(content);
+ CPPUNIT_ASSERT_EQUAL(JingleContentPayload::InitiatorCreator, content->getCreator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a-file-offer"), content->getName());
+
+ std::vector<StreamInitiationFileInfo> offers = content->getDescription<JingleFileTransferDescription>()->getOffers();
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), offers.size());
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-12
+ void testParse_Xep0234_Example12() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-info'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <received xmlns='urn:xmpp:jingle:apps:file-transfer:3'>\n"
+ " <file xmlns='http://jabber.org/protocol/si/profile/file-transfer'\n"
+ " hash='a749930852c69ae5d2141d3766b1552d'/>\n"
+ " </received>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInfo, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ boost::shared_ptr<JingleFileTransferReceived> received = jingle->getPayload<JingleFileTransferReceived>();
+ CPPUNIT_ASSERT(received);
+ CPPUNIT_ASSERT_EQUAL(std::string("a749930852c69ae5d2141d3766b1552d"), received->getFileInfo().getHash());
+ }
+
+ // http://xmpp.org/extensions/xep-0260.html#example-1
+ void testParse_Xep0260_Example1() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-initiate'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <description xmlns='urn:xmpp:example'/>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " mode='tcp'\n"
+ " sid='vj3hs98y'>\n"
+ " <candidate cid='hft54dqy'\n"
+ " host='192.168.4.1'\n"
+ " jid='romeo@montague.lit/orchard'\n"
+ " port='5086'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ " <candidate cid='hutr46fe'\n"
+ " host='24.24.24.1'\n"
+ " jid='romeo@montague.lit/orchard'\n"
+ " port='5087'\n"
+ " priority='8258636'\n"
+ " type='direct'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionInitiate, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ JingleContentPayload::ref content = jingle->getPayload<JingleContentPayload>();
+ CPPUNIT_ASSERT(content);
+
+ JingleS5BTransportPayload::ref s5bPayload = content->getTransport<JingleS5BTransportPayload>();
+ CPPUNIT_ASSERT(s5bPayload);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("vj3hs98y"), s5bPayload->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::TCPMode, s5bPayload->getMode());
+ CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasCandidateError());
+ CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasProxyError());
+ CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getActivated());
+ CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getCandidateUsed());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), s5bPayload->getCandidates().size());
+
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate = s5bPayload->getCandidates()[0];
+ CPPUNIT_ASSERT_EQUAL(std::string("hft54dqy"), candidate.cid);
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), candidate.jid);
+ CPPUNIT_ASSERT(HostAddressPort(HostAddress("192.168.4.1"), 5086) == candidate.hostPort);
+ CPPUNIT_ASSERT_EQUAL(8257636, candidate.priority);
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
+
+ candidate = s5bPayload->getCandidates()[1];
+ CPPUNIT_ASSERT_EQUAL(std::string("hutr46fe"), candidate.cid);
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), candidate.jid);
+ CPPUNIT_ASSERT(HostAddressPort(HostAddress("24.24.24.1"), 5087) == candidate.hostPort);
+ CPPUNIT_ASSERT_EQUAL(8258636, candidate.priority);
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
+ }
+
+ // http://xmpp.org/extensions/xep-0260.html#example-3
+ void testParse_Xep0260_Example3() {
+ PayloadsParserTester parser;
+ CPPUNIT_ASSERT(parser.parse(
+ "<jingle xmlns='urn:xmpp:jingle:1'\n"
+ " action='session-accept'\n"
+ " initiator='romeo@montague.lit/orchard'\n"
+ " sid='a73sjjvkla37jfea'>\n"
+ " <content creator='initiator' name='ex'>\n"
+ " <description xmlns='urn:xmpp:example'/>\n"
+ " <transport xmlns='urn:xmpp:jingle:transports:s5b:1'\n"
+ " mode='tcp'\n"
+ " sid='vj3hs98y'>\n"
+ " <candidate cid='ht567dq'\n"
+ " host='192.169.1.10'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257636'\n"
+ " type='direct'/>\n"
+ " <candidate cid='hr65dqyd'\n"
+ " host='134.102.201.180'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='16453'\n"
+ " priority='7929856'\n"
+ " type='assisted'/>\n"
+ " <candidate cid='grt654q2'\n"
+ " host='2001:638:708:30c9:219:d1ff:fea4:a17d'\n"
+ " jid='juliet@capulet.lit/balcony'\n"
+ " port='6539'\n"
+ " priority='8257606'\n"
+ " type='direct'/>\n"
+ " </transport>\n"
+ " </content>\n"
+ "</jingle>\n"
+ ));
+
+ JinglePayload::ref jingle = parser.getPayload<JinglePayload>();
+ CPPUNIT_ASSERT(jingle);
+ CPPUNIT_ASSERT_EQUAL(JinglePayload::SessionAccept, jingle->getAction());
+ CPPUNIT_ASSERT_EQUAL(JID("romeo@montague.lit/orchard"), jingle->getInitiator());
+ CPPUNIT_ASSERT_EQUAL(std::string("a73sjjvkla37jfea"), jingle->getSessionID());
+
+ JingleContentPayload::ref content = jingle->getPayload<JingleContentPayload>();
+ CPPUNIT_ASSERT(content);
+
+ JingleS5BTransportPayload::ref s5bPayload = content->getTransport<JingleS5BTransportPayload>();
+ CPPUNIT_ASSERT(s5bPayload);
+
+ CPPUNIT_ASSERT_EQUAL(std::string("vj3hs98y"), s5bPayload->getSessionID());
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::TCPMode, s5bPayload->getMode());
+ CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasCandidateError());
+ CPPUNIT_ASSERT_EQUAL(false, s5bPayload->hasProxyError());
+ CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getActivated());
+ CPPUNIT_ASSERT_EQUAL(std::string(), s5bPayload->getCandidateUsed());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3), s5bPayload->getCandidates().size());
+
+ JingleS5BTransportPayload::Candidate candidate;
+ candidate = s5bPayload->getCandidates()[0];
+ CPPUNIT_ASSERT_EQUAL(std::string("ht567dq"), candidate.cid);
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
+ CPPUNIT_ASSERT(HostAddressPort(HostAddress("192.169.1.10"), 6539) == candidate.hostPort);
+ CPPUNIT_ASSERT_EQUAL(8257636, candidate.priority);
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
+
+ candidate = s5bPayload->getCandidates()[1];
+ CPPUNIT_ASSERT_EQUAL(std::string("hr65dqyd"), candidate.cid);
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
+ CPPUNIT_ASSERT(HostAddressPort(HostAddress("134.102.201.180"), 16453) == candidate.hostPort);
+ CPPUNIT_ASSERT_EQUAL(7929856, candidate.priority);
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::AssistedType, candidate.type);
+
+ candidate = s5bPayload->getCandidates()[2];
+ CPPUNIT_ASSERT_EQUAL(std::string("grt654q2"), candidate.cid);
+ CPPUNIT_ASSERT_EQUAL(JID("juliet@capulet.lit/balcony"), candidate.jid);
+ CPPUNIT_ASSERT(HostAddressPort(HostAddress("2001:638:708:30c9:219:d1ff:fea4:a17d"), 6539) == candidate.hostPort);
+ CPPUNIT_ASSERT_EQUAL(8257606, candidate.priority);
+ CPPUNIT_ASSERT_EQUAL(JingleS5BTransportPayload::Candidate::DirectType, candidate.type);
+ }
+};
+
+CPPUNIT_TEST_SUITE_REGISTRATION(JingleParserTest);
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp
index 47b2816..63a6c9b 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp
+++ b/Swiften/Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp
@@ -42,9 +42,9 @@ class StreamInitiationParserTest : public CppUnit::TestFixture {
StreamInitiation::ref si = parser.getPayload<StreamInitiation>();
CPPUNIT_ASSERT(si->getIsFileTransfer());
CPPUNIT_ASSERT(si->getFileInfo());
- CPPUNIT_ASSERT_EQUAL(std::string("test.txt"), si->getFileInfo()->name);
- CPPUNIT_ASSERT_EQUAL(1022, si->getFileInfo()->size);
- CPPUNIT_ASSERT_EQUAL(std::string("This is info about the file."), si->getFileInfo()->description);
+ CPPUNIT_ASSERT_EQUAL(std::string("test.txt"), si->getFileInfo()->getName());
+ CPPUNIT_ASSERT(1022 == si->getFileInfo()->getSize());
+ CPPUNIT_ASSERT_EQUAL(std::string("This is info about the file."), si->getFileInfo()->getDescription());
CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(si->getProvidedMethods().size()));
CPPUNIT_ASSERT_EQUAL(std::string("http://jabber.org/protocol/bytestreams"), si->getProvidedMethods()[0]);
CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:oob"), si->getProvidedMethods()[1]);
diff --git a/Swiften/Parser/SConscript b/Swiften/Parser/SConscript
index e6c16d1..3dbfbee 100644
--- a/Swiften/Parser/SConscript
+++ b/Swiften/Parser/SConscript
@@ -29,6 +29,15 @@ sources = [
"PayloadParsers/ErrorParser.cpp",
"PayloadParsers/FormParser.cpp",
"PayloadParsers/IBBParser.cpp",
+ "PayloadParsers/JingleParser.cpp",
+ "PayloadParsers/JingleReasonParser.cpp",
+ "PayloadParsers/JingleContentPayloadParser.cpp",
+ "PayloadParsers/JingleIBBTransportMethodPayloadParser.cpp",
+ "PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp",
+ "PayloadParsers/JingleFileTransferDescriptionParser.cpp",
+ "PayloadParsers/JingleFileTransferReceivedParser.cpp",
+ "PayloadParsers/JingleFileTransferHashParser.cpp",
+ "PayloadParsers/StreamInitiationFileInfoParser.cpp",
"PayloadParsers/CommandParser.cpp",
"PayloadParsers/InBandRegistrationPayloadParser.cpp",
"PayloadParsers/SearchPayloadParser.cpp",
@@ -56,6 +65,7 @@ sources = [
"PayloadParsers/NicknameParser.cpp",
"PayloadParsers/ReplaceParser.cpp",
"PayloadParsers/LastParser.cpp",
+ "PayloadParsers/S5BProxyRequestParser.cpp",
"PlatformXMLParserFactory.cpp",
"PresenceParser.cpp",
"SerializingParser.cpp",
diff --git a/Swiften/SConscript b/Swiften/SConscript
index e20e5e6..ca8dee5 100644
--- a/Swiften/SConscript
+++ b/Swiften/SConscript
@@ -6,7 +6,7 @@ Import("env")
# Flags
################################################################################
-swiften_dep_modules = ["BOOST", "GCONF", "LIBIDN", "ZLIB", "OPENSSL", "LIBXML", "EXPAT", "AVAHI"]
+swiften_dep_modules = ["BOOST", "GCONF", "LIBIDN", "ZLIB", "OPENSSL", "LIBXML", "EXPAT", "AVAHI", "LIBMINIUPNPC", "LIBNATPMP"]
if env["SCONS_STAGE"] == "flags" :
env["SWIFTEN_VERSION"] = Version.getBuildVersion(env.Dir("#").abspath, "swift")
@@ -21,6 +21,10 @@ if env["SCONS_STAGE"] == "flags" :
env["SWIFTEN_LIBRARY"] = "Swiften"
env["SWIFTEN_LIBRARY_FILE"] = "Swiften"
env["SWIFTEN_LIBRARY_ALIASES"] = []
+
+ if env["PLATFORM"] == "win32" :
+ env.Append(CCFLAGS = ["-DSTATICLIB"])
+
if ARGUMENTS.get("swiften_dll", False) :
if env["PLATFORM"] == "win32" :
pass
@@ -87,6 +91,7 @@ if env["SCONS_STAGE"] == "build" :
"Client/NickManager.cpp",
"Client/NickManagerImpl.cpp",
"Client/Storages.cpp",
+ "Client/XMLBeautifier.cpp",
"Compress/ZLibCodecompressor.cpp",
"Compress/ZLibDecompressor.cpp",
"Compress/ZLibCompressor.cpp",
@@ -166,6 +171,14 @@ if env["SCONS_STAGE"] == "build" :
"Serializer/PayloadSerializers/SearchPayloadSerializer.cpp",
"Serializer/PayloadSerializers/FormSerializer.cpp",
"Serializer/PayloadSerializers/NicknameSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp",
+ "Serializer/PayloadSerializers/JinglePayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp",
+ "Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp",
"Serializer/PresenceSerializer.cpp",
"Serializer/StanzaSerializer.cpp",
"Serializer/StreamErrorSerializer.cpp",
@@ -281,6 +294,7 @@ if env["SCONS_STAGE"] == "build" :
File("Parser/PayloadParsers/UnitTest/RosterItemExchangeParserTest.cpp"),
File("Parser/PayloadParsers/UnitTest/RosterParserTest.cpp"),
File("Parser/PayloadParsers/UnitTest/IBBParserTest.cpp"),
+ File("Parser/PayloadParsers/UnitTest/JingleParserTest.cpp"),
File("Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp"),
File("Parser/PayloadParsers/UnitTest/SecurityLabelParserTest.cpp"),
File("Parser/PayloadParsers/UnitTest/SecurityLabelsCatalogParserTest.cpp"),
@@ -340,6 +354,7 @@ if env["SCONS_STAGE"] == "build" :
File("Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp"),
File("Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp"),
File("Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp"),
+ File("Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp"),
File("Serializer/UnitTest/StreamFeaturesSerializerTest.cpp"),
File("Serializer/UnitTest/AuthSuccessSerializerTest.cpp"),
File("Serializer/UnitTest/AuthChallengeSerializerTest.cpp"),
diff --git a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
index 0ddd445..55c39c7 100644
--- a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
+++ b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp
@@ -49,6 +49,16 @@
#include <Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h>
#include <Swiften/Serializer/PayloadSerializers/LastSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h>
+
namespace Swift {
FullPayloadSerializerCollection::FullPayloadSerializerCollection() {
@@ -92,6 +102,17 @@ FullPayloadSerializerCollection::FullPayloadSerializerCollection() {
serializers_.push_back(new SearchPayloadSerializer());
serializers_.push_back(new ReplaceSerializer());
serializers_.push_back(new LastSerializer());
+
+ serializers_.push_back(new StreamInitiationFileInfoSerializer());
+ serializers_.push_back(new JingleContentPayloadSerializer());
+ serializers_.push_back(new JingleFileTransferDescriptionSerializer());
+ serializers_.push_back(new JingleFileTransferHashSerializer());
+ serializers_.push_back(new JingleFileTransferReceivedSerializer());
+ serializers_.push_back(new JingleIBBTransportPayloadSerializer());
+ serializers_.push_back(new JingleS5BTransportPayloadSerializer());
+ serializers_.push_back(new JinglePayloadSerializer(this));
+ serializers_.push_back(new S5BProxyRequestSerializer());
+
foreach(PayloadSerializer* serializer, serializers_) {
addSerializer(serializer);
}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp
new file mode 100644
index 0000000..90bd940
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+#include <boost/smart_ptr/intrusive_ptr.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
+
+#include <Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h>
+
+#include "Swiften/FileTransfer/JingleTransport.h"
+
+namespace Swift {
+
+JingleContentPayloadSerializer::JingleContentPayloadSerializer() {
+}
+
+std::string JingleContentPayloadSerializer::serializePayload(boost::shared_ptr<JingleContentPayload> payload) const {
+ XMLElement payloadXML("content");
+ payloadXML.setAttribute("creator", creatorToString(payload->getCreator()));
+ payloadXML.setAttribute("name", payload->getName());
+
+ if (!payload->getDescriptions().empty()) {
+ // JingleFileTransferDescription
+ JingleFileTransferDescriptionSerializer ftSerializer;
+ JingleFileTransferDescription::ref filetransfer;
+
+ foreach(JingleDescription::ref desc, payload->getDescriptions()) {
+ if ((filetransfer = boost::dynamic_pointer_cast<JingleFileTransferDescription>(desc))) {
+ payloadXML.addNode(boost::make_shared<XMLRawTextNode>(ftSerializer.serializePayload(filetransfer)));
+ }
+ }
+ }
+
+ if (!payload->getTransports().empty()) {
+ // JingleIBBTransportPayload
+ JingleIBBTransportPayloadSerializer ibbSerializer;
+ JingleIBBTransportPayload::ref ibb;
+
+ // JingleS5BTransportPayload
+ JingleS5BTransportPayloadSerializer s5bSerializer;
+ JingleS5BTransportPayload::ref s5b;
+
+ foreach(JingleTransportPayload::ref transport, payload->getTransports()) {
+ if ((ibb = boost::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) {
+ payloadXML.addNode(boost::make_shared<XMLRawTextNode>(ibbSerializer.serializePayload(ibb)));
+ } else if ((s5b = boost::dynamic_pointer_cast<JingleS5BTransportPayload>(transport))) {
+ payloadXML.addNode(boost::make_shared<XMLRawTextNode>(s5bSerializer.serializePayload(s5b)));
+ }
+ }
+ }
+ return payloadXML.serialize();
+}
+
+std::string JingleContentPayloadSerializer::creatorToString(JingleContentPayload::Creator creator) const {
+ switch(creator) {
+ case JingleContentPayload::InitiatorCreator:
+ return "initiator";
+ case JingleContentPayload::ResponderCreator:
+ return "responder";
+ case JingleContentPayload::UnknownCreator:
+ std::cerr << "Serializing unknown creator value." << std::endl;
+ return "ERROR ERROR ERROR";
+ }
+ assert(false);
+}
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h
new file mode 100644
index 0000000..2de0064
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+
+#pragma once
+
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Elements/JingleContentPayload.h>
+
+namespace Swift {
+ class PayloadSerializerCollection;
+
+ class JingleContentPayloadSerializer : public GenericPayloadSerializer<JingleContentPayload> {
+ public:
+ JingleContentPayloadSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleContentPayload>) const;
+
+ private:
+ std::string creatorToString(JingleContentPayload::Creator creator) const;
+ };
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp
new file mode 100644
index 0000000..16337ff
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.cpp
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+
+#include <Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h>
+
+namespace Swift {
+
+JingleFileTransferDescriptionSerializer::JingleFileTransferDescriptionSerializer() {
+}
+
+std::string JingleFileTransferDescriptionSerializer::serializePayload(boost::shared_ptr<JingleFileTransferDescription> payload) const {
+ XMLElement description("description", "urn:xmpp:jingle:apps:file-transfer:3");
+ StreamInitiationFileInfoSerializer fileInfoSerializer;
+ if (!payload->getOffers().empty()) {
+ boost::shared_ptr<XMLElement> offers = boost::make_shared<XMLElement>("offer");
+ foreach(const StreamInitiationFileInfo &fileInfo, payload->getOffers()) {
+ boost::shared_ptr<XMLRawTextNode> fileInfoXML = boost::make_shared<XMLRawTextNode>(fileInfoSerializer.serialize(boost::make_shared<StreamInitiationFileInfo>(fileInfo)));
+ offers->addNode(fileInfoXML);
+ }
+ description.addNode(offers);
+ }
+ if (!payload->getRequests().empty()) {
+ boost::shared_ptr<XMLElement> requests = boost::make_shared<XMLElement>("request");
+ foreach(const StreamInitiationFileInfo &fileInfo, payload->getRequests()) {
+ boost::shared_ptr<XMLRawTextNode> fileInfoXML = boost::make_shared<XMLRawTextNode>(fileInfoSerializer.serialize(boost::make_shared<StreamInitiationFileInfo>(fileInfo)));
+ requests->addNode(fileInfoXML);
+ }
+ description.addNode(requests);
+ }
+ return description.serialize();
+}
+
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h
new file mode 100644
index 0000000..5131435
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+
+#pragma once
+
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Elements/JingleFileTransferDescription.h>
+
+
+
+namespace Swift {
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class JingleFileTransferDescriptionSerializer : public GenericPayloadSerializer<JingleFileTransferDescription> {
+ public:
+ JingleFileTransferDescriptionSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleFileTransferDescription>) const;
+ };
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
new file mode 100644
index 0000000..2bd3afa
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.cpp
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h>
+
+#include <string>
+#include <map>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+
+
+namespace Swift {
+
+JingleFileTransferHashSerializer::JingleFileTransferHashSerializer() {
+}
+
+std::string JingleFileTransferHashSerializer::serializePayload(boost::shared_ptr<JingleFileTransferHash> payload) const {
+ // code for version urn:xmpp:jingle:apps:file-transfer:2
+ //XMLElement hash("hash", "urn:xmpp:jingle:apps:file-transfer:info:2", payload->getHash());
+
+ // code for version urn:xmpp:jingle:apps:file-transfer:3
+ XMLElement checksum("checksum", "urn:xmpp:jingle:apps:file-transfer:3");
+ boost::shared_ptr<XMLElement> file = boost::make_shared<XMLElement>("file");
+ checksum.addNode(file);
+ boost::shared_ptr<XMLElement> hashes = boost::make_shared<XMLElement>("hashes", "urn:xmpp:hashes:0");
+ file->addNode(hashes);
+ foreach(const JingleFileTransferHash::HashesMap::value_type& pair, payload->getHashes()) {
+ boost::shared_ptr<XMLElement> hash = boost::make_shared<XMLElement>("hash", "", pair.second);
+ hash->setAttribute("algo", pair.first);
+ hashes->addNode(hash);
+ }
+
+ return checksum.serialize();
+}
+
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h
new file mode 100644
index 0000000..7fa6ac5
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+
+#pragma once
+
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Elements/JingleFileTransferHash.h>
+
+namespace Swift {
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class JingleFileTransferHashSerializer : public GenericPayloadSerializer<JingleFileTransferHash> {
+ public:
+ JingleFileTransferHashSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleFileTransferHash>) const;
+ };
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.cpp
new file mode 100644
index 0000000..40be70e
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.cpp
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.h>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+
+namespace Swift {
+
+JingleFileTransferReceivedSerializer::JingleFileTransferReceivedSerializer() {
+}
+
+std::string JingleFileTransferReceivedSerializer::serializePayload(boost::shared_ptr<JingleFileTransferReceived> payload) const {
+ XMLElement receivedElement("received", "urn:xmpp:jingle:apps:file-transfer:3");
+ XMLElement::ref fileElement = boost::make_shared<XMLElement>("file", "http://jabber.org/protocol/si/profile/file-transfer");
+ fileElement->setAttribute("hash", payload->getFileInfo().getHash());
+ if (payload->getFileInfo().getAlgo() != "md5") {
+ fileElement->setAttribute("algo", payload->getFileInfo().getAlgo());
+ }
+ receivedElement.addNode(fileElement);
+ return receivedElement.serialize();
+}
+
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.h
new file mode 100644
index 0000000..4151dd0
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+
+#pragma once
+
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Elements/JingleFileTransferReceived.h>
+
+namespace Swift {
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class JingleFileTransferReceivedSerializer : public GenericPayloadSerializer<JingleFileTransferReceived> {
+ public:
+ JingleFileTransferReceivedSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleFileTransferReceived>) const;
+ };
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
new file mode 100644
index 0000000..029a5b4
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+#include <boost/lexical_cast.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+
+namespace Swift {
+
+JingleIBBTransportPayloadSerializer::JingleIBBTransportPayloadSerializer() {
+}
+
+std::string JingleIBBTransportPayloadSerializer::serializePayload(boost::shared_ptr<JingleIBBTransportPayload> payload) const {
+ XMLElement payloadXML("transport", "urn:xmpp:jingle:transports:ibb:1");
+ payloadXML.setAttribute("block-size", boost::lexical_cast<std::string>(payload->getBlockSize()));
+ payloadXML.setAttribute("sid", payload->getSessionID());
+
+ return payloadXML.serialize();
+}
+
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h
new file mode 100644
index 0000000..ac9cba9
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+
+#pragma once
+
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
+
+
+
+namespace Swift {
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class JingleIBBTransportPayloadSerializer : public GenericPayloadSerializer<JingleIBBTransportPayload> {
+ public:
+ JingleIBBTransportPayloadSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleIBBTransportPayload>) const;
+ };
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
new file mode 100644
index 0000000..25d35ff
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+#include <boost/smart_ptr/intrusive_ptr.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleContentPayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferHashSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferReceivedSerializer.h>
+
+#include <Swiften/Serializer/PayloadSerializerCollection.h>
+
+#include <Swiften/Elements/JinglePayload.h>
+#include <Swiften/Elements/JingleContentPayload.h>
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#include <Swiften/Elements/JingleFileTransferDescription.h>
+#include <Swiften/Elements/JingleFileTransferHash.h>
+#include <Swiften/Elements/JingleFileTransferReceived.h>
+
+namespace Swift {
+
+JinglePayloadSerializer::JinglePayloadSerializer(PayloadSerializerCollection* serializers) : serializers(serializers) {
+}
+
+std::string JinglePayloadSerializer::serializePayload(boost::shared_ptr<JinglePayload> payload) const {
+ XMLElement jinglePayload("jingle", "urn:xmpp:jingle:1");
+ jinglePayload.setAttribute("action", actionToString(payload->getAction()));
+ jinglePayload.setAttribute("initiator", payload->getInitiator());
+ jinglePayload.setAttribute("sid", payload->getSessionID());
+
+ if (!payload->getPayloads().empty()) {
+ foreach(boost::shared_ptr<Payload> subPayload, payload->getPayloads()) {
+ PayloadSerializer* serializer = serializers->getPayloadSerializer(subPayload);
+ if (serializer) {
+ jinglePayload.addNode(boost::shared_ptr<XMLRawTextNode>(new XMLRawTextNode(serializer->serialize(subPayload))));
+ }
+ }
+ }
+
+ if (payload->getReason().is_initialized()) {
+ boost::shared_ptr<XMLElement> reason = boost::make_shared<XMLElement>("reason");
+ reason->addNode(boost::make_shared<XMLElement>(reasonTypeToString(payload->getReason()->type)));
+ if (!payload->getReason()->text.empty()) {
+ reason->addNode(boost::make_shared<XMLElement>("desc", "", payload->getReason()->text));
+ }
+ jinglePayload.addNode(reason);
+ }
+
+ return jinglePayload.serialize();
+}
+
+std::string JinglePayloadSerializer::actionToString(JinglePayload::Action action) const {
+ switch(action) {
+ case JinglePayload::ContentAccept:
+ return "content-accept";
+ case JinglePayload::ContentAdd:
+ return "content-add";
+ case JinglePayload::ContentModify:
+ return "content-modify";
+ case JinglePayload::ContentReject:
+ return "content-reject";
+ case JinglePayload::ContentRemove:
+ return "content-remove";
+ case JinglePayload::DescriptionInfo:
+ return "description-info";
+ case JinglePayload::SecurityInfo:
+ return "security-info";
+ case JinglePayload::SessionAccept:
+ return "session-accept";
+ case JinglePayload::SessionInfo:
+ return "session-info";
+ case JinglePayload::SessionInitiate:
+ return "session-initiate";
+ case JinglePayload::SessionTerminate:
+ return "session-terminate";
+ case JinglePayload::TransportAccept:
+ return "transport-accept";
+ case JinglePayload::TransportInfo:
+ return "transport-info";
+ case JinglePayload::TransportReject:
+ return "transport-reject";
+ case JinglePayload::TransportReplace:
+ return "transport-replace";
+ case JinglePayload::UnknownAction:
+ std::cerr << "Serializing unknown action value." << std::endl;
+ return "";
+ }
+ assert(false);
+}
+
+std::string JinglePayloadSerializer::reasonTypeToString(JinglePayload::Reason::Type type) const {
+ switch(type) {
+ case JinglePayload::Reason::UnknownType:
+ std::cerr << "Unknown jingle reason type!" << std::endl;
+ return "";
+ case JinglePayload::Reason::AlternativeSession:
+ return "alternative-session";
+ case JinglePayload::Reason::Busy:
+ return "busy";
+ case JinglePayload::Reason::Cancel:
+ return "cancel";
+ case JinglePayload::Reason::ConnectivityError:
+ return "connectivity-error";
+ case JinglePayload::Reason::Decline:
+ return "decline";
+ case JinglePayload::Reason::Expired:
+ return "expired";
+ case JinglePayload::Reason::FailedApplication:
+ return "failed-application";
+ case JinglePayload::Reason::FailedTransport:
+ return "failed-transport";
+ case JinglePayload::Reason::GeneralError:
+ return "general-error";
+ case JinglePayload::Reason::Gone:
+ return "gone";
+ case JinglePayload::Reason::IncompatibleParameters:
+ return "incompatible-parameters";
+ case JinglePayload::Reason::MediaError:
+ return "media-error";
+ case JinglePayload::Reason::SecurityError:
+ return "security-error";
+ case JinglePayload::Reason::Success:
+ return "success";
+ case JinglePayload::Reason::Timeout:
+ return "timeout";
+ case JinglePayload::Reason::UnsupportedApplications:
+ return "unsupported-applications";
+ case JinglePayload::Reason::UnsupportedTransports:
+ return "unsupported-transports";
+ }
+ assert(false);
+}
+
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h
new file mode 100644
index 0000000..ccdb6d0
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+
+#pragma once
+
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Elements/JinglePayload.h>
+
+namespace Swift {
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class JinglePayloadSerializer : public GenericPayloadSerializer<JinglePayload> {
+ public:
+ JinglePayloadSerializer(PayloadSerializerCollection*);
+
+ virtual std::string serializePayload(boost::shared_ptr<JinglePayload>) const;
+
+ private:
+ std::string actionToString(JinglePayload::Action action) const;
+ std::string reasonTypeToString(JinglePayload::Reason::Type type) const;
+
+ private:
+ PayloadSerializerCollection* serializers;
+ };
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp
new file mode 100644
index 0000000..c5b40d5
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+#include <boost/lexical_cast.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Serializer/XML/XMLNode.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+#include <Swiften/Base/Log.h>
+
+namespace Swift {
+
+JingleS5BTransportPayloadSerializer::JingleS5BTransportPayloadSerializer() {
+}
+
+std::string JingleS5BTransportPayloadSerializer::serializePayload(boost::shared_ptr<JingleS5BTransportPayload> payload) const {
+ XMLElement payloadXML("transport", "urn:xmpp:jingle:transports:s5b:1");
+ payloadXML.setAttribute("sid", payload->getSessionID());
+ payloadXML.setAttribute("mode", modeToString(payload->getMode()));
+
+ foreach(JingleS5BTransportPayload::Candidate candidate, payload->getCandidates()) {
+ boost::shared_ptr<XMLElement> candidateXML = boost::make_shared<XMLElement>("candidate");
+ candidateXML->setAttribute("cid", candidate.cid);
+ candidateXML->setAttribute("host", candidate.hostPort.getAddress().toString());
+ candidateXML->setAttribute("jid", candidate.jid.toString());
+ candidateXML->setAttribute("port", boost::lexical_cast<std::string>(candidate.hostPort.getPort()));
+ candidateXML->setAttribute("priority", boost::lexical_cast<std::string>(candidate.priority));
+ candidateXML->setAttribute("type", typeToString(candidate.type));
+ payloadXML.addNode(candidateXML);
+ }
+
+ if (payload->hasCandidateError()) {
+ payloadXML.addNode(boost::make_shared<XMLElement>("candidate-error"));
+ }
+ if (payload->hasProxyError()) {
+ payloadXML.addNode(boost::make_shared<XMLElement>("proxy-error"));
+ }
+
+ if (!payload->getActivated().empty()) {
+ boost::shared_ptr<XMLElement> activatedXML = boost::make_shared<XMLElement>("activated");
+ activatedXML->setAttribute("cid", payload->getActivated());
+ payloadXML.addNode(activatedXML);
+ }
+ if (!payload->getCandidateUsed().empty()) {
+ boost::shared_ptr<XMLElement> candusedXML = boost::make_shared<XMLElement>("candidate-used");
+ candusedXML->setAttribute("cid", payload->getCandidateUsed());
+ payloadXML.addNode(candusedXML);
+ }
+
+ return payloadXML.serialize();
+}
+
+std::string JingleS5BTransportPayloadSerializer::modeToString(JingleS5BTransportPayload::Mode mode) const {
+ switch(mode) {
+ case JingleS5BTransportPayload::TCPMode:
+ return "tcp";
+ case JingleS5BTransportPayload::UDPMode:
+ return "udp";
+ }
+ assert(false);
+}
+
+std::string JingleS5BTransportPayloadSerializer::typeToString(JingleS5BTransportPayload::Candidate::Type type) const {
+ switch(type) {
+ case JingleS5BTransportPayload::Candidate::AssistedType:
+ return "assisted";
+ case JingleS5BTransportPayload::Candidate::DirectType:
+ return "direct";
+ case JingleS5BTransportPayload::Candidate::ProxyType:
+ return "proxy";
+ case JingleS5BTransportPayload::Candidate::TunnelType:
+ return "tunnel";
+ }
+ assert(false);
+}
+
+}
diff --git a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h
new file mode 100644
index 0000000..210688d
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+
+#pragma once
+
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+
+namespace Swift {
+ class PayloadSerializerCollection;
+ class XMLElement;
+
+ class JingleS5BTransportPayloadSerializer : public GenericPayloadSerializer<JingleS5BTransportPayload> {
+ public:
+ JingleS5BTransportPayloadSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<JingleS5BTransportPayload>) const;
+
+ private:
+ std::string modeToString(JingleS5BTransportPayload::Mode) const;
+ std::string typeToString(JingleS5BTransportPayload::Candidate::Type) const;
+ };
+}
diff --git a/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h b/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h
new file mode 100644
index 0000000..b523588
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+
+#pragma once
+
+#include <boost/lexical_cast.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <Swiften/Elements/S5BProxyRequest.h>
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+
+namespace Swift {
+ class PayloadSerializerCollection;
+
+ class S5BProxyRequestSerializer : public GenericPayloadSerializer<S5BProxyRequest> {
+ public:
+ virtual std::string serializePayload(boost::shared_ptr<S5BProxyRequest> s5bProxyRequest) const {
+ XMLElement queryElement("query", "http://jabber.org/protocol/bytestreams");
+ if (s5bProxyRequest && s5bProxyRequest->getStreamHost()) {
+ boost::shared_ptr<XMLElement> streamHost = boost::make_shared<XMLElement>("streamhost");
+ streamHost->setAttribute("host", s5bProxyRequest->getStreamHost().get().addressPort.getAddress().toString());
+ streamHost->setAttribute("port", boost::lexical_cast<std::string>(s5bProxyRequest->getStreamHost().get().addressPort.getPort()));
+ streamHost->setAttribute("jid", s5bProxyRequest->getStreamHost().get().jid.toString());
+ queryElement.addNode(streamHost);
+ } else if (s5bProxyRequest && s5bProxyRequest->getActivate()) {
+ queryElement.setAttribute("sid", s5bProxyRequest->getSID());
+ boost::shared_ptr<XMLElement> activate = boost::make_shared<XMLElement>("activate", "", s5bProxyRequest->getActivate().get().toString());
+ queryElement.addNode(activate);
+ }
+ return queryElement.serialize();
+ }
+ };
+}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
new file mode 100644
index 0000000..7b0cad8
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h>
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+#include <boost/lexical_cast.hpp>
+
+#include <Swiften/Base/foreach.h>
+#include <Swiften/Base/DateTime.h>
+#include <Swiften/Serializer/XML/XMLElement.h>
+#include <Swiften/Serializer/XML/XMLRawTextNode.h>
+#include <Swiften/Serializer/XML/XMLTextNode.h>
+
+
+
+namespace Swift {
+
+StreamInitiationFileInfoSerializer::StreamInitiationFileInfoSerializer() {
+}
+
+std::string StreamInitiationFileInfoSerializer::serializePayload(boost::shared_ptr<StreamInitiationFileInfo> fileInfo) const {
+ XMLElement fileElement("file", "http://jabber.org/protocol/si/profile/file-transfer");
+
+ if (fileInfo->getDate() != stringToDateTime("")) {
+ fileElement.setAttribute("date", dateTimeToString(fileInfo->getDate()));
+ }
+ fileElement.setAttribute("hash", fileInfo->getHash());
+ if (fileInfo->getAlgo() != "md5") {
+ fileElement.setAttribute("algo", fileInfo->getAlgo());
+ }
+ if (!fileInfo->getName().empty()) {
+ fileElement.setAttribute("name", fileInfo->getName());
+ }
+ if (fileInfo->getSize() != 0) {
+ fileElement.setAttribute("size", boost::lexical_cast<std::string>(fileInfo->getSize()));
+ }
+ if (!fileInfo->getDescription().empty()) {
+ boost::shared_ptr<XMLElement> desc = boost::make_shared<XMLElement>("desc", "", fileInfo->getDescription());
+ fileElement.addNode(desc);
+ }
+ if (fileInfo->getSupportsRangeRequests()) {
+ boost::shared_ptr<XMLElement> range = boost::make_shared<XMLElement>("range");
+ if (fileInfo->getRangeOffset() != 0) {
+ range->setAttribute("offset", boost::lexical_cast<std::string>(fileInfo->getRangeOffset()));
+ }
+ fileElement.addNode(range);
+ }
+ return fileElement.serialize();
+}
+
+}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h
new file mode 100644
index 0000000..4ac0a0d
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+
+#pragma once
+
+#include <Swiften/Serializer/GenericPayloadSerializer.h>
+#include <Swiften/Elements/StreamInitiationFileInfo.h>
+
+#include <Swiften/Serializer/XML/XMLElement.h>
+
+namespace Swift {
+ class PayloadSerializerCollection;
+
+ class StreamInitiationFileInfoSerializer : public GenericPayloadSerializer<StreamInitiationFileInfo> {
+ public:
+ StreamInitiationFileInfoSerializer();
+
+ virtual std::string serializePayload(boost::shared_ptr<StreamInitiationFileInfo>) const;
+ };
+}
diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
index 3b71bfb..9ccfab2 100644
--- a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp
@@ -36,13 +36,13 @@ std::string StreamInitiationSerializer::serializePayload(boost::shared_ptr<Strea
if (streamInitiation->getFileInfo()) {
StreamInitiationFileInfo file = *streamInitiation->getFileInfo();
boost::shared_ptr<XMLElement> fileElement(new XMLElement("file", "http://jabber.org/protocol/si/profile/file-transfer"));
- fileElement->setAttribute("name", file.name);
- if (file.size != -1) {
- fileElement->setAttribute("size", boost::lexical_cast<std::string>(file.size));
+ fileElement->setAttribute("name", file.getName());
+ if (file.getSize() != 0) {
+ fileElement->setAttribute("size", boost::lexical_cast<std::string>(file.getSize()));
}
- if (!file.description.empty()) {
+ if (!file.getDescription().empty()) {
boost::shared_ptr<XMLElement> descElement(new XMLElement("desc"));
- descElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(file.description)));
+ descElement->addNode(boost::shared_ptr<XMLTextNode>(new XMLTextNode(file.getDescription())));
fileElement->addNode(descElement);
}
siElement.addNode(fileElement);
diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp
new file mode 100644
index 0000000..e3ec8fc
--- /dev/null
+++ b/Swiften/Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp
@@ -0,0 +1,512 @@
+/*
+ * Copyright (c) 2011 Tobias Markmann
+ * Licensed under the simplified BSD license.
+ * See Documentation/Licenses/BSD-simplified.txt for more information.
+ */
+
+#include <boost/shared_ptr.hpp>
+#include <boost/smart_ptr/make_shared.hpp>
+
+#include <cppunit/extensions/HelperMacros.h>
+#include <cppunit/extensions/TestFactoryRegistry.h>
+
+#include <Swiften/Serializer/PayloadSerializers/JingleFileTransferDescriptionSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h>
+#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h>
+#include <Swiften/Elements/JingleFileTransferDescription.h>
+#include <Swiften/Elements/StreamInitiationFileInfo.h>
+#include <Swiften/Elements/JingleIBBTransportPayload.h>
+#include <Swiften/Elements/JingleS5BTransportPayload.h>
+#include <Swiften/Elements/JingleFileTransferHash.h>
+#include <Swiften/Elements/JinglePayload.h>
+#include <Swiften/Elements/JingleFileTransferReceived.h>
+#include <Swiften/Base/DateTime.h>
+
+using namespace Swift;
+
+class JingleSerializersTest : public CppUnit::TestFixture {
+ CPPUNIT_TEST_SUITE(JingleSerializersTest);
+ CPPUNIT_TEST(testSerialize_StreamInitiationFileInfo);
+ CPPUNIT_TEST(testSerialize_StreamInitiationFileInfoRange);
+
+ CPPUNIT_TEST(testSerialize_Xep0261_Example1);
+ CPPUNIT_TEST(testSerialize_Xep0261_Example9);
+ CPPUNIT_TEST(testSerialize_Xep0261_Example13);
+
+ CPPUNIT_TEST(testSerialize_Xep0234_Example1);
+ CPPUNIT_TEST(testSerialize_Xep0234_Example3);
+ CPPUNIT_TEST(testSerialize_Xep0234_Example5);
+ CPPUNIT_TEST(testSerialize_Xep0234_Example8);
+ CPPUNIT_TEST(testSerialize_Xep0234_Example10);
+ CPPUNIT_TEST(testSerialize_Xep0234_Example13);
+
+ CPPUNIT_TEST(testSerialize_Xep0260_Example1);
+
+ CPPUNIT_TEST_SUITE_END();
+
+ boost::shared_ptr<JinglePayloadSerializer> createTestling() {
+ return boost::make_shared<JinglePayloadSerializer>(&collection);
+ }
+
+
+ public:
+ void testSerialize_StreamInitiationFileInfo() {
+ std::string expected = "<file"
+ " date=\"1969-07-21T02:56:15Z\""
+ " hash=\"552da749930852c69ae5d2141d3766b1\""
+ " name=\"test.txt\""
+ " size=\"1022\""
+ " xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
+ "<desc>This is a test. If this were a real file...</desc>"
+ "<range/>"
+ "</file>";
+
+ StreamInitiationFileInfo::ref fileInfo = boost::make_shared<StreamInitiationFileInfo>();
+ fileInfo->setDate(stringToDateTime("1969-07-21T02:56:15Z"));
+ fileInfo->setHash("552da749930852c69ae5d2141d3766b1");
+ fileInfo->setSize(1022);
+ fileInfo->setName("test.txt");
+ fileInfo->setDescription("This is a test. If this were a real file...");
+ fileInfo->setSupportsRangeRequests(true);
+
+ boost::shared_ptr<StreamInitiationFileInfoSerializer> serializer = boost::make_shared<StreamInitiationFileInfoSerializer>();
+ CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(fileInfo));
+ }
+
+ void testSerialize_StreamInitiationFileInfoRange() {
+ std::string expected = "<file hash=\"552da749930852c69ae5d2141d3766b1\""
+ " xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
+ "<range offset=\"270336\"/>"
+ "</file>";
+
+ StreamInitiationFileInfo::ref fileInfo = boost::make_shared<StreamInitiationFileInfo>();
+ fileInfo->setHash("552da749930852c69ae5d2141d3766b1");
+ fileInfo->setSupportsRangeRequests(true);
+ fileInfo->setRangeOffset(270336);
+
+ boost::shared_ptr<StreamInitiationFileInfoSerializer> serializer = boost::make_shared<StreamInitiationFileInfoSerializer>();
+ CPPUNIT_ASSERT_EQUAL(expected, serializer->serializePayload(fileInfo));
+ }
+
+
+ // IBB Transport Method Examples
+
+ // http://xmpp.org/extensions/xep-0261.html#example-1
+ void testSerialize_Xep0261_Example1() {
+ std::string expected =
+ "<jingle action=\"session-initiate\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"ex\">"
+ "<transport block-size=\"4096\""
+ " sid=\"ch3d9s71\""
+ " xmlns=\"urn:xmpp:jingle:transports:ibb:1\"/>"
+ "</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInitiate);
+ payload->setSessionID("a73sjjvkla37jfea");
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+
+ JingleIBBTransportPayload::ref transport = boost::make_shared<JingleIBBTransportPayload>();
+ transport->setBlockSize(4096);
+ transport->setSessionID("ch3d9s71");
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("ex");
+ content->addTransport(transport);
+
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0261.html#example-9
+ void testSerialize_Xep0261_Example9() {
+ std::string expected =
+ "<jingle action=\"transport-info\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"ex\">"
+ "<transport block-size=\"2048\""
+ " sid=\"bt8a71h6\""
+ " xmlns=\"urn:xmpp:jingle:transports:ibb:1\"/>"
+ "</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::TransportInfo);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("ex");
+
+ JingleIBBTransportPayload::ref transport = boost::make_shared<JingleIBBTransportPayload>();
+ transport->setBlockSize(2048);
+ transport->setSessionID("bt8a71h6");
+
+ content->addTransport(transport);
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0261.html#example-13
+ void testSerialize_Xep0261_Example13() {
+ std::string expected =
+ "<jingle action=\"session-terminate\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<reason><success/></reason>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionTerminate);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+ payload->setReason(JinglePayload::Reason(JinglePayload::Reason::Success));
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-1
+ void testSerialize_Xep0234_Example1() {
+ std::string expected = "<description xmlns=\"urn:xmpp:jingle:apps:file-transfer:3\">"
+ "<offer>"
+ "<file"
+ " date=\"1969-07-21T02:56:15Z\""
+ " hash=\"552da749930852c69ae5d2141d3766b1\""
+ " name=\"test.txt\""
+ " size=\"1022\""
+ " xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
+ "<desc>This is a test. If this were a real file...</desc>"
+ "<range/>"
+ "</file>"
+ "</offer>"
+ "</description>";
+ JingleFileTransferDescription::ref desc = boost::make_shared<JingleFileTransferDescription>();
+ StreamInitiationFileInfo fileInfo;
+
+ fileInfo.setDate(stringToDateTime("1969-07-21T02:56:15Z"));
+ fileInfo.setHash("552da749930852c69ae5d2141d3766b1");
+ fileInfo.setSize(1022);
+ fileInfo.setName("test.txt");
+ fileInfo.setDescription("This is a test. If this were a real file...");
+ fileInfo.setSupportsRangeRequests(true);
+
+ desc->addOffer(fileInfo);
+
+ CPPUNIT_ASSERT_EQUAL(expected, boost::make_shared<JingleFileTransferDescriptionSerializer>()->serialize(desc));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-3
+ void testSerialize_Xep0234_Example3() {
+ std::string expected =
+ "<jingle action=\"session-accept\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"851ba2\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"a-file-offer\">"
+ "<description xmlns=\"urn:xmpp:jingle:apps:file-transfer:3\">"
+ "<offer>"
+ "<file"
+ " date=\"1969-07-21T02:56:15Z\""
+ " hash=\"552da749930852c69ae5d2141d3766b1\""
+ " name=\"test.txt\""
+ " size=\"1022\""
+ " xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
+ "<desc>This is a test. If this were a real file...</desc>"
+ "<range/>"
+ "</file>"
+ "</offer>"
+ "</description>"
+ /*"<transport xmlns=\"urn:xmpp:jingle:transports:s5b:1\""
+ " mode=\"tcp\""
+ " sid=\"vj3hs98y\">"
+ "<candidate cid=\"ht567dq\""
+ " host=\"192.169.1.10\""
+ " jid=\"juliet@capulet.lit/balcony\""
+ " port=\"6539\""
+ " priority=\"8257636\""
+ " type=\"direct\"/>"
+ "<candidate cid=\"hr65dqyd\""
+ " host=\"134.102.201.180\""
+ " jid=\"juliet@capulet.lit/balcony\""
+ " port=\"16453\""
+ " priority=\"7929856\""
+ " type=\"assisted\"/>"
+ "<candidate cid=\"grt654q2\""
+ " host=\"2001:638:708:30c9:219:d1ff:fea4:a17d\""
+ " jid=\"juliet@capulet.lit/balcony\""
+ " port=\"6539\""
+ " priority=\"8257606\""
+ " type=\"direct\"/>"
+ "</transport>"*/
+ "</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionAccept);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("851ba2");
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("a-file-offer");
+
+ JingleFileTransferDescription::ref description = boost::make_shared<JingleFileTransferDescription>();
+ StreamInitiationFileInfo fileInfo;
+ fileInfo.setName("test.txt");
+ fileInfo.setSize(1022);
+ fileInfo.setHash("552da749930852c69ae5d2141d3766b1");
+ fileInfo.setDate(stringToDateTime("1969-07-21T02:56:15Z"));
+ fileInfo.setDescription("This is a test. If this were a real file...");
+ fileInfo.setSupportsRangeRequests(true);
+
+ description->addOffer(fileInfo);
+ content->addDescription(description);
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-5
+ void testSerialize_Xep0234_Example5() {
+ std::string expected =
+ "<jingle"
+ " action=\"transport-info\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"ex\"/>"
+ /*"<transport"
+ " sid=\"vj3hs98y\""
+ " xmlns=\"urn:xmpp:jingle:transports:s5b:1\">"
+ "<candidate-used cid=\"hr65dqyd\"/>"
+ "</transport>"*/
+ //"</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::TransportInfo);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("ex");
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-8
+ void testSerialize_Xep0234_Example8() {
+ std::string expected =
+ "<jingle"
+ " action=\"session-info\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<checksum xmlns=\"urn:xmpp:jingle:apps:file-transfer:3\">"
+ "<file>"
+ "<hashes xmlns=\"urn:xmpp:hashes:0\">"
+ "<hash algo=\"sha-1\">552da749930852c69ae5d2141d3766b1</hash>"
+ "</hashes>"
+ "</file>"
+ "</checksum>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInfo);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleFileTransferHash::ref hash = boost::make_shared<JingleFileTransferHash>();
+ hash->setHash("sha-1", "552da749930852c69ae5d2141d3766b1");
+
+ payload->addPayload(hash);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-10
+ void testSerialize_Xep0234_Example10() {
+ std::string expected =
+ "<jingle"
+ " action=\"session-initiate\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"uj3b2\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"a-file-request\">"
+ "<description"
+ " xmlns=\"urn:xmpp:jingle:apps:file-transfer:3\">"
+ "<request>"
+ "<file"
+ " hash=\"552da749930852c69ae5d2141d3766b1\""
+ " xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\">"
+ "<range offset=\"270336\"/>"
+ "</file>"
+ "</request>"
+ "</description>"
+ /*"<transport"
+ " mode=\"tcp\""
+ " sid=\"xig361fj\""
+ " xmlns=\"urn:xmpp:jingle:transports:s5b:1\">"
+ "<candidate"
+ " cid=\"ht567dq\""
+ " host=\"192.169.1.10\""
+ " jid=\"juliet@capulet.lit/balcony\""
+ " port=\"6539\""
+ " priority=\"8257636\""
+ " type=\"direct\"/>"
+ "<candidate"
+ " cid=\"hr65dqyd\""
+ " host=\"134.102.201.180\""
+ " jid=\"juliet@capulet.lit/balcony\""
+ " port=\"16453\""
+ " priority=\"7929856\""
+ " type=\"assisted\"/>"
+ "<candidate"
+ " cid=\"grt654q2\""
+ " host=\"2001:638:708:30c9:219:d1ff:fea4:a17d\""
+ " jid=\"juliet@capulet.lit/balcony\""
+ " port=\"6539\""
+ " priority=\"8257606\""
+ " type=\"direct\"/>"
+ "</transport>"*/
+ "</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInitiate);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("uj3b2");
+
+ StreamInitiationFileInfo fileInfo;
+ fileInfo.setHash("552da749930852c69ae5d2141d3766b1");
+ fileInfo.setRangeOffset(270336);
+
+ JingleFileTransferDescription::ref desc = boost::make_shared<JingleFileTransferDescription>();
+ desc->addRequest(fileInfo);
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("a-file-request");
+ content->addDescription(desc);
+
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0234.html#example-10
+ void testSerialize_Xep0234_Example13() {
+ std::string expected =
+ "<jingle"
+ " action=\"session-info\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<received xmlns=\"urn:xmpp:jingle:apps:file-transfer:3\">"
+ "<file"
+ " hash=\"a749930852c69ae5d2141d3766b1552d\""
+ " xmlns=\"http://jabber.org/protocol/si/profile/file-transfer\"/>"
+ "</received>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInfo);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleFileTransferReceived::ref received = boost::make_shared<JingleFileTransferReceived>();
+
+ StreamInitiationFileInfo fileInfo;
+ fileInfo.setHash("a749930852c69ae5d2141d3766b1552d");
+
+ received->setFileInfo(fileInfo);
+ payload->addPayload(received);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ // http://xmpp.org/extensions/xep-0260.html#example-1
+ void testSerialize_Xep0260_Example1() {
+ std::string expected =
+ "<jingle"
+ " action=\"session-initiate\""
+ " initiator=\"romeo@montague.lit/orchard\""
+ " sid=\"a73sjjvkla37jfea\""
+ " xmlns=\"urn:xmpp:jingle:1\">"
+ "<content creator=\"initiator\" name=\"ex\">"
+ "<transport"
+ " mode=\"tcp\""
+ " sid=\"vj3hs98y\""
+ " xmlns=\"urn:xmpp:jingle:transports:s5b:1\">"
+ "<candidate cid=\"hft54dqy\""
+ " host=\"192.168.4.1\""
+ " jid=\"romeo@montague.lit/orchard\""
+ " port=\"5086\""
+ " priority=\"8257636\""
+ " type=\"direct\"/>"
+ "<candidate cid=\"hutr46fe\""
+ " host=\"24.24.24.1\""
+ " jid=\"romeo@montague.lit/orchard\""
+ " port=\"5087\""
+ " priority=\"8258636\""
+ " type=\"direct\"/>"
+ "</transport>"
+ "</content>"
+ "</jingle>";
+
+ JinglePayload::ref payload = boost::make_shared<JinglePayload>();
+ payload->setAction(JinglePayload::SessionInitiate);
+ payload->setInitiator(JID("romeo@montague.lit/orchard"));
+ payload->setSessionID("a73sjjvkla37jfea");
+
+ JingleContentPayload::ref content = boost::make_shared<JingleContentPayload>();
+ content->setCreator(JingleContentPayload::InitiatorCreator);
+ content->setName("ex");
+
+ JingleS5BTransportPayload::ref transport = boost::make_shared<JingleS5BTransportPayload>();
+ transport->setMode(JingleS5BTransportPayload::TCPMode);
+ transport->setSessionID("vj3hs98y");
+
+ JingleS5BTransportPayload::Candidate candidate1;
+ candidate1.cid = "hft54dqy";
+ candidate1.hostPort = HostAddressPort(HostAddress("192.168.4.1"), 5086);
+ candidate1.jid = JID("romeo@montague.lit/orchard");
+ candidate1.priority = 8257636;
+ candidate1.type = JingleS5BTransportPayload::Candidate::DirectType;
+ transport->addCandidate(candidate1);
+
+ JingleS5BTransportPayload::Candidate candidate2;
+ candidate2.cid = "hutr46fe";
+ candidate2.hostPort = HostAddressPort(HostAddress("24.24.24.1"), 5087);
+ candidate2.jid = JID("romeo@montague.lit/orchard");
+ candidate2.priority = 8258636;
+ candidate2.type = JingleS5BTransportPayload::Candidate::DirectType;
+ transport->addCandidate(candidate2);
+
+ content->addTransport(transport);
+
+ payload->addPayload(content);
+
+ CPPUNIT_ASSERT_EQUAL(expected, createTestling()->serialize(payload));
+ }
+
+ private:
+ FullPayloadSerializerCollection collection;
+};
+
+CPPUNIT_TEST_SUITE_REGISTRATION(JingleSerializersTest);
+
diff --git a/Swiften/StringCodecs/Hexify.cpp b/Swiften/StringCodecs/Hexify.cpp
index 367743c..668079b 100644
--- a/Swiften/StringCodecs/Hexify.cpp
+++ b/Swiften/StringCodecs/Hexify.cpp
@@ -31,4 +31,22 @@ std::string Hexify::hexify(const ByteArray& data) {
return std::string(result.str());
}
+ByteArray Hexify::unhexify(const std::string& hexstring) {
+ if (hexstring.size() % 2) {
+ return ByteArray();
+ }
+ ByteArray result = ByteArray(hexstring.size() / 2);
+ for (size_t pos = 0; pos < hexstring.size() - 1; pos += 2) {
+ char c;
+ c = hexstring[pos];
+ int a = (c>='0'&&c<='9') ? c-'0' : (c>='A'&&c<='Z') ? c-'A' + 10 : (c>='a'&&c<='z') ? c-'a' + 10 : -1;
+ c = hexstring[pos+1];
+ int b = (c>='0'&&c<='9') ? c-'0' : (c>='A'&&c<='Z') ? c-'A' + 10 : (c>='a'&&c<='z') ? c-'a' + 10 : -1;
+ if (a == -1 || b == -1) return ByteArray(); // fail
+ result[pos/2] = (a<<4) | b;
+
+ }
+ return result;
+}
+
}
diff --git a/Swiften/StringCodecs/Hexify.h b/Swiften/StringCodecs/Hexify.h
index 9815e21..c016448 100644
--- a/Swiften/StringCodecs/Hexify.h
+++ b/Swiften/StringCodecs/Hexify.h
@@ -13,5 +13,6 @@ namespace Swift {
public:
static std::string hexify(unsigned char byte);
static std::string hexify(const ByteArray& data);
+ static ByteArray unhexify(const std::string& hexstring);
};
}
diff --git a/Swiften/StringCodecs/MD5.cpp b/Swiften/StringCodecs/MD5.cpp
index 0d36254..6871f79 100644
--- a/Swiften/StringCodecs/MD5.cpp
+++ b/Swiften/StringCodecs/MD5.cpp
@@ -366,6 +366,27 @@ namespace {
}
}
+MD5::MD5() {
+ state = new md5_state_t;
+ md5_init(state);
+}
+
+MD5::~MD5() {
+ delete state;
+}
+
+MD5& MD5::update(const std::vector<unsigned char>& input) {
+ md5_append(state, reinterpret_cast<const md5_byte_t*>(vecptr(input)), input.size());
+ return *this;
+}
+
+std::vector<unsigned char> MD5::getHash() {
+ ByteArray digest;
+ digest.resize(16);
+ md5_finish(state, reinterpret_cast<md5_byte_t*>(vecptr(digest)));
+ return digest;
+}
+
ByteArray MD5::getHash(const ByteArray& data) {
return getMD5Hash(data);
}
diff --git a/Swiften/StringCodecs/MD5.h b/Swiften/StringCodecs/MD5.h
index b1d610c..09473c2 100644
--- a/Swiften/StringCodecs/MD5.h
+++ b/Swiften/StringCodecs/MD5.h
@@ -10,9 +10,20 @@
#include <Swiften/Base/SafeByteArray.h>
namespace Swift {
+ struct md5_state_s;
+
class MD5 {
public:
+ MD5();
+ ~MD5();
+
+ MD5& update(const std::vector<unsigned char>& data);
+ std::vector<unsigned char> getHash();
+
static ByteArray getHash(const ByteArray& data);
static ByteArray getHash(const SafeByteArray& data);
+
+ private:
+ md5_state_s* state;
};
}
diff --git a/Swiften/StringCodecs/UnitTest/HexifyTest.cpp b/Swiften/StringCodecs/UnitTest/HexifyTest.cpp
index 9cbd0d4..38233f9 100644
--- a/Swiften/StringCodecs/UnitTest/HexifyTest.cpp
+++ b/Swiften/StringCodecs/UnitTest/HexifyTest.cpp
@@ -17,6 +17,7 @@ class HexifyTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(HexifyTest);
CPPUNIT_TEST(testHexify);
CPPUNIT_TEST(testHexify_Byte);
+ CPPUNIT_TEST(testUnhexify);
CPPUNIT_TEST_SUITE_END();
public:
@@ -27,6 +28,11 @@ class HexifyTest : public CppUnit::TestFixture {
void testHexify_Byte() {
CPPUNIT_ASSERT_EQUAL(std::string("b2"), Hexify::hexify(0xb2));
}
+
+ void testUnhexify() {
+ CPPUNIT_ASSERT_EQUAL(std::string("ffaf02"), Hexify::hexify(Hexify::unhexify("ffaf02")));
+ CPPUNIT_ASSERT(createByteArray("\x01\x23\xf2", 3) == Hexify::unhexify("0123f2"));
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(HexifyTest);
diff --git a/Swiften/StringCodecs/UnitTest/MD5Test.cpp b/Swiften/StringCodecs/UnitTest/MD5Test.cpp
index ce7e422..c62c46a 100644
--- a/Swiften/StringCodecs/UnitTest/MD5Test.cpp
+++ b/Swiften/StringCodecs/UnitTest/MD5Test.cpp
@@ -19,6 +19,7 @@ class MD5Test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(MD5Test);
CPPUNIT_TEST(testGetHash_Empty);
CPPUNIT_TEST(testGetHash_Alphabet);
+ CPPUNIT_TEST(testIncrementalTest);
CPPUNIT_TEST_SUITE_END();
public:
@@ -33,6 +34,16 @@ class MD5Test : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(createByteArray("\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f", 16), result);
}
+
+ void testIncrementalTest() {
+ MD5 testling;
+ testling.update(createByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZ"));
+ testling.update(createByteArray("abcdefghijklmnopqrstuvwxyz0123456789"));
+
+ ByteArray result = testling.getHash();
+
+ CPPUNIT_ASSERT_EQUAL(createByteArray("\xd1\x74\xab\x98\xd2\x77\xd9\xf5\xa5\x61\x1c\x2c\x9f\x41\x9d\x9f", 16), result);
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(MD5Test);