diff options
Diffstat (limited to 'Swiften')
460 files changed, 6002 insertions, 2107 deletions
diff --git a/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp b/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp index 8aca98e..3e5e9e6 100644 --- a/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp +++ b/Swiften/Avatars/UnitTest/CombinedAvatarProviderTest.cpp @@ -42,20 +42,20 @@ class CombinedAvatarProviderTest : public CppUnit::TestFixture { CPPUNIT_TEST(testProviderUpdateAfterAvatarDisappearedTriggersChange); CPPUNIT_TEST(testProviderUpdateAfterGetDoesNotTriggerChange); CPPUNIT_TEST(testProviderUpdateBareJIDAfterGetFullJID); CPPUNIT_TEST(testRemoveProviderDisconnectsUpdates); CPPUNIT_TEST(testAddRemoveFallthrough); CPPUNIT_TEST_SUITE_END(); public: void setUp() { - avatarProvider1 = std::unique_ptr<DummyAvatarProvider>(new DummyAvatarProvider()); - avatarProvider2 = std::unique_ptr<DummyAvatarProvider>(new DummyAvatarProvider()); + avatarProvider1 = std::make_unique<DummyAvatarProvider>(); + avatarProvider2 = std::make_unique<DummyAvatarProvider>(); user1 = JID("user1@bar.com/bla"); user2 = JID("user2@foo.com/baz"); avatarHash1 = "ABCDEFG"; avatarHash2 = "XYZU"; avatarHash3 = "IDGH"; } void testGetAvatarWithNoAvatarProviderReturnsEmpty() { std::shared_ptr<CombinedAvatarProvider> testling(createProvider()); diff --git a/Swiften/Base/Algorithm.h b/Swiften/Base/Algorithm.h index 108dbe3..ee761b7 100644 --- a/Swiften/Base/Algorithm.h +++ b/Swiften/Base/Algorithm.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2014 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <algorithm> #include <list> #include <map> @@ -154,10 +154,34 @@ namespace Swift { }; template <typename Map> bool key_compare(Map const& lhs, Map const& rhs) { auto pred = [](decltype(*lhs.begin()) a, decltype(a) b) { return a.first == b.first; }; return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin(), pred); } + + /** + * Ranges + */ + template <typename T> + class range_t { + public: + range_t(T b, T e) : b_(b), e_(e) {} + + T begin() { + return b_; + } + T end() { + return e_; + } + private: + T b_; + T e_; + }; + + template <typename T> + range_t<T> range(T b, T e) { + return range_t<T>(b, e); + } } diff --git a/Swiften/Base/LRUCache.h b/Swiften/Base/LRUCache.h index e4e652f..1f92612 100644 --- a/Swiften/Base/LRUCache.h +++ b/Swiften/Base/LRUCache.h @@ -13,52 +13,52 @@ #include <boost/multi_index/member.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/optional.hpp> namespace Swift { /** - * The \ref LRUCache templaged class implements a lookup cache which removes + * The \ref LRUCache template class implements a lookup cache which removes * the least recently used cached item from the cache, if the cache size hits - * the \ref MAX_SIZE limit. + * the \p MAX_SIZE limit. * * An example use is a cache for entity capabilities hash to DiscoInfo. */ template <typename KEY_TYPE, typename VALUE_TYPE, size_t MAX_SIZE> class LRUCache { public: using cacheMissFunction = std::function<boost::optional<VALUE_TYPE>(const KEY_TYPE& )>; public: /** - * Inserts the key/value pair in the front of the cache. If the \ref key + * Inserts the key/value pair in the front of the cache. If the \p key * already exists in the cache, it is moved to the front instead. If - * afterwards, the cahe size exceeds the \ref MAX_SIZE limit, the least + * afterwards, the cahe size exceeds the \p MAX_SIZE limit, the least * recently item is removed from the cache. */ void insert(const KEY_TYPE& key, VALUE_TYPE value) { auto pushResult = cache.push_front(entry_t(key, value)); if (!pushResult.second) { cache.relocate(cache.begin(), pushResult.first); } else if (cache.size() > MAX_SIZE) { cache.pop_back(); } } /** - * Looks up a cache entry based on the provided \ref key and moves it back + * Looks up a cache entry based on the provided \p key and moves it back * to the front of the cache. If there is no cache entry for the provided - * \ref key, an uninitialized \ref boost::optional is returned. - * If the optional \ref missFunction is provided, it is called on a cache miss. - * If the \ref missFunction returns an initialized \ref boost::optional, the + * \p key, an uninitialized \p boost::optional is returned. + * If the optional \p missFunction is provided, it is called on a cache miss. + * If the \p missFunction returns an initialized \p boost::optional, the * value is inserted in the cache. */ boost::optional<VALUE_TYPE> get(const KEY_TYPE& key, cacheMissFunction missFunction = cacheMissFunction()) { boost::optional<VALUE_TYPE> cachedValue; auto cacheItemIterator = boost::multi_index::get<1>(cache).find(key); if (cacheItemIterator != boost::multi_index::get<1>(cache).end()) { cachedValue = cacheItemIterator->second; cache.relocate(cache.begin(), cache.iterator_to(*cacheItemIterator)); } diff --git a/Swiften/Base/Override.h b/Swiften/Base/Override.h deleted file mode 100644 index 2806aae..0000000 --- a/Swiften/Base/Override.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) 2012 Isode Limited. - * All rights reserved. - * See the COPYING file for more information. - */ - -#pragma once - -#if defined(__clang__) -# if __has_feature(cxx_override_control) || __has_extension(cxx_override_control) -# define SWIFTEN_OVERRIDE override -# else -# define SWIFTEN_OVERRIDE -# endif - -#elif defined(__GNUC__) -# if ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ >= 7))) && defined(__GXX_EXPERIMENTAL_CXX0X__) -# define SWIFTEN_OVERRIDE override -# else -# define SWIFTEN_OVERRIDE -# endif - -#elif defined(_MSC_VER) -// Actually, 1700 is the first version that supports the C++11 override, but -// older versions apparently support a similar keyword. -# if _MSC_VER >= 1400 -# define SWIFTEN_OVERRIDE override -# else -# define SWIFTEN_OVERRIDE -# endif - -#else -# define SWIFTEN_OVERRIDE -#endif diff --git a/Swiften/Base/SimpleIDGenerator.h b/Swiften/Base/SimpleIDGenerator.h index ff645b1..09e01de 100644 --- a/Swiften/Base/SimpleIDGenerator.h +++ b/Swiften/Base/SimpleIDGenerator.h @@ -1,32 +1,31 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> #include <Swiften/Base/IDGenerator.h> -#include <Swiften/Base/Override.h> namespace Swift { /** * @brief The SimpleIDGenerator class implements a IDGenerator generating consecutive ID strings from * the lower case latin alphabet. */ class SWIFTEN_API SimpleIDGenerator : public IDGenerator { public: SimpleIDGenerator(); - ~SimpleIDGenerator(); + ~SimpleIDGenerator() override; - std::string generateID() SWIFTEN_OVERRIDE; + std::string generateID() override; private: std::string currentID; }; } diff --git a/Swiften/Base/StdRandomGenerator.h b/Swiften/Base/StdRandomGenerator.h index 4cc5e95..159d361 100644 --- a/Swiften/Base/StdRandomGenerator.h +++ b/Swiften/Base/StdRandomGenerator.h @@ -3,23 +3,22 @@ * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <random> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Base/RandomGenerator.h> namespace Swift { class SWIFTEN_API StdRandomGenerator : public RandomGenerator { public: StdRandomGenerator(); - int generateRandomInteger(int max) SWIFTEN_OVERRIDE; + int generateRandomInteger(int max) override; private: std::mt19937 generator; }; } diff --git a/Swiften/Base/URL.cpp b/Swiften/Base/URL.cpp index 4a47a11..5c0f0d7 100644 --- a/Swiften/Base/URL.cpp +++ b/Swiften/Base/URL.cpp @@ -1,23 +1,23 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Base/URL.h> #include <algorithm> #include <iostream> namespace Swift { -int URL::getPortOrDefaultPort(const URL& url) { +unsigned short URL::getPortOrDefaultPort(const URL& url) { if (url.getPort()) { return *url.getPort(); } else if (url.getScheme() == "http") { return 80; } else if (url.getScheme() == "https") { return 443; } @@ -56,44 +56,44 @@ URL URL::fromString(const std::string& urlString) { userInfo = authority.substr(0, atIndex); hostAndPort = authority.substr(atIndex + 1); } else { userInfo = ""; hostAndPort = authority; } std::string host; - boost::optional<int> port; + boost::optional<unsigned short> port; if (hostAndPort[0] == '[') { // handle IPv6 address literals size_t addressEndIndex = hostAndPort.find(']'); if (addressEndIndex != std::string::npos) { host = hostAndPort.substr(1, addressEndIndex - 1); colonIndex = hostAndPort.find(':', addressEndIndex); if (colonIndex != std::string::npos) { try { - port = boost::lexical_cast<int>(hostAndPort.substr(colonIndex + 1)); + port = boost::numeric_cast<unsigned short>(boost::lexical_cast<int>(hostAndPort.substr(colonIndex + 1))); } - catch (const boost::bad_lexical_cast&) { + catch (...) { return URL(); } } } else { return URL(); } } else { colonIndex = hostAndPort.find(':'); if (colonIndex != std::string::npos) { host = unescape(hostAndPort.substr(0, colonIndex)); try { - port = boost::lexical_cast<int>(hostAndPort.substr(colonIndex + 1)); + port = boost::numeric_cast<unsigned short>(boost::lexical_cast<int>(hostAndPort.substr(colonIndex + 1))); } catch (const boost::bad_lexical_cast&) { return URL(); } } else { host = unescape(hostAndPort); } } @@ -126,19 +126,19 @@ std::string URL::toString() const { } if (host.find(':') != std::string::npos) { result += "[" + host + "]"; } else { result += host; } if (port) { result += ":"; - result += boost::lexical_cast<std::string>(*port); + result += std::to_string(*port); } result += path; return result; } // Disabling this code for now, since GCC4.5+boost1.42 (on ubuntu) seems to // result in a bug. Replacing it with naive code. #if 0 // Should be in anonymous namespace, but older GCCs complain if we do that diff --git a/Swiften/Base/URL.h b/Swiften/Base/URL.h index 1a03efe..8fdb018 100644 --- a/Swiften/Base/URL.h +++ b/Swiften/Base/URL.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <boost/lexical_cast.hpp> @@ -15,19 +15,19 @@ namespace Swift { class SWIFTEN_API URL { public: URL() : scheme(""), user(""), password(""), host(""), path(""), empty(true) { } - URL(const std::string& scheme, const std::string& host, int port, const std::string& path) : scheme(scheme), user(), password(), host(host), port(port), path(path), empty(false) { + URL(const std::string& scheme, const std::string& host, unsigned short port, const std::string& path) : scheme(scheme), user(), password(), host(host), port(port), path(path), empty(false) { } URL(const std::string& scheme, const std::string& host, const std::string& path) : scheme(scheme), user(), password(), host(host), path(path), empty(false) { } /** * Whether the URL is empty. */ bool isEmpty() const { @@ -45,37 +45,37 @@ class SWIFTEN_API URL { * Hostname */ const std::string& getHost() const { return host; } /** * Port number */ - boost::optional<int> getPort() const { + boost::optional<unsigned short> getPort() const { return port; } /** * Path */ const std::string& getPath() const { return path; } std::string toString() const; - static int getPortOrDefaultPort(const URL& url); + static unsigned short getPortOrDefaultPort(const URL& url); static URL fromString(const std::string&); static std::string unescape(const std::string&); private: std::string scheme; std::string user; std::string password; std::string host; - boost::optional<int> port; + boost::optional<unsigned short> port; std::string path; bool empty; }; } diff --git a/Swiften/Base/UnitTest/URLTest.cpp b/Swiften/Base/UnitTest/URLTest.cpp index c38398a..da9f15c 100644 --- a/Swiften/Base/UnitTest/URLTest.cpp +++ b/Swiften/Base/UnitTest/URLTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <boost/lexical_cast.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> @@ -60,37 +60,37 @@ class URLTest : public CppUnit::TestFixture { CPPUNIT_ASSERT(!url.getPort()); CPPUNIT_ASSERT_EQUAL(std::string("/"), url.getPath()); } void testFromString_WithPort() { URL url = URL::fromString("http://foo.bar:1234/baz/bam"); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(1234, *url.getPort()); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(1234), *url.getPort()); CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath()); } void testFromString_WithPortOnePartPath() { URL url = URL::fromString("http://foo.bar:11440/http-bind/"); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(11440, *url.getPort()); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(11440), *url.getPort()); CPPUNIT_ASSERT_EQUAL(std::string("/http-bind/"), url.getPath()); } void testFromString_WithPortWithoutPath() { URL url = URL::fromString("http://foo.bar:1234"); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(1234, *url.getPort()); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(1234), *url.getPort()); CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath()); } void testFromString_WithUserInfo() { URL url = URL::fromString("http://user:pass@foo.bar/baz/bam"); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("foo.bar"), url.getHost()); CPPUNIT_ASSERT_EQUAL(std::string("/baz/bam"), url.getPath()); @@ -115,117 +115,117 @@ class URLTest : public CppUnit::TestFixture { CPPUNIT_ASSERT_EQUAL(std::string("127.0.0.1"), url.getHost()); CPPUNIT_ASSERT_EQUAL(std::string("/foobar"), url.getPath()); } void testFromString_IPv4AddressWithPort() { URL url = URL::fromString("http://127.0.0.1:12345/foobar"); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("127.0.0.1"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(12345, url.getPort().get_value_or(0)); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(12345), url.getPort().get_value_or(0)); CPPUNIT_ASSERT_EQUAL(std::string("/foobar"), url.getPath()); } void testFromString_IPv6Address() { URL url = URL::fromString("http://[fdf8:f53b:82e4::53]/foobar"); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("fdf8:f53b:82e4::53"), url.getHost()); } void testFromString_IPv6AddressWithPort() { URL url = URL::fromString("http://[fdf8:f53b:82e4::53]:12435/foobar"); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("fdf8:f53b:82e4::53"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(12435, url.getPort().get_value_or(0)); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(12435), url.getPort().get_value_or(0)); } void test_FromString_ToString_IPv6RFC2732() { { const char* testVector = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html"; URL url = URL::fromString(testVector); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("FEDC:BA98:7654:3210:FEDC:BA98:7654:3210"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(80, url.getPort().get_value_or(2)); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(80), url.getPort().get_value_or(2)); CPPUNIT_ASSERT_EQUAL(std::string("/index.html"), url.getPath()); CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString()); } { const char* testVector = "http://[1080:0:0:0:8:800:200C:417A]/index.html"; URL url = URL::fromString(testVector); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("1080:0:0:0:8:800:200C:417A"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(2, url.getPort().get_value_or(2)); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(2), url.getPort().get_value_or(2)); CPPUNIT_ASSERT_EQUAL(std::string("/index.html"), url.getPath()); CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString()); } { const char* testVector = "http://[3ffe:2a00:100:7031::1]"; URL url = URL::fromString(testVector); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("3ffe:2a00:100:7031::1"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(2, url.getPort().get_value_or(2)); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(2), url.getPort().get_value_or(2)); CPPUNIT_ASSERT_EQUAL(std::string(""), url.getPath()); CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString()); } { const char* testVector = "http://[1080::8:800:200C:417A]/foo"; URL url = URL::fromString(testVector); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("1080::8:800:200C:417A"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(2, url.getPort().get_value_or(2)); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(2), url.getPort().get_value_or(2)); CPPUNIT_ASSERT_EQUAL(std::string("/foo"), url.getPath()); CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString()); } { const char* testVector = "http://[::192.9.5.5]/ipng"; URL url = URL::fromString(testVector); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("::192.9.5.5"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(2, url.getPort().get_value_or(2)); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(2), url.getPort().get_value_or(2)); CPPUNIT_ASSERT_EQUAL(std::string("/ipng"), url.getPath()); CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString()); } { const char* testVector = "http://[::FFFF:129.144.52.38]:80/index.html"; URL url = URL::fromString(testVector); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("::FFFF:129.144.52.38"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(80, url.getPort().get_value_or(2)); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(80), url.getPort().get_value_or(2)); CPPUNIT_ASSERT_EQUAL(std::string("/index.html"), url.getPath()); CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString()); } { const char* testVector = "http://[2010:836B:4179::836B:4179]"; URL url = URL::fromString(testVector); CPPUNIT_ASSERT_EQUAL(std::string("http"), url.getScheme()); CPPUNIT_ASSERT_EQUAL(std::string("2010:836B:4179::836B:4179"), url.getHost()); - CPPUNIT_ASSERT_EQUAL(2, url.getPort().get_value_or(2)); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(2), url.getPort().get_value_or(2)); CPPUNIT_ASSERT_EQUAL(std::string(), url.getPath()); CPPUNIT_ASSERT_EQUAL(std::string(testVector), url.toString()); } } void testToString() { CPPUNIT_ASSERT_EQUAL(std::string("http://foo.bar/baz/bam"), URL("http", "foo.bar", "/baz/bam").toString()); } diff --git a/Swiften/ChangeLog.md b/Swiften/ChangeLog.md index 23d5185..60355b4 100644 --- a/Swiften/ChangeLog.md +++ b/Swiften/ChangeLog.md @@ -1,9 +1,13 @@ +5-in-progress +------------- +- Update build system from scons 2.4.0 to 3.0.1 + 4.0.1 (2018-03-28) ------------------ - Fix handling errors when fetching own vCard 4.0 (2018-03-20) ---------------- - Moved code-base to C++11 - Use C++11 threading instead of Boost.Thread library - Use C++11 smart pointers instead of Boost's diff --git a/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp b/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp index efd37d9..b6c909a 100644 --- a/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp +++ b/Swiften/Chat/UnitTest/ChatStateNotifierTest.cpp @@ -1,24 +1,27 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <boost/bind.hpp> #include <gtest/gtest.h> #include <Swiften/Chat/ChatStateNotifier.h> #include <Swiften/Client/DummyStanzaChannel.h> #include <Swiften/Disco/DummyEntityCapsProvider.h> #include <Swiften/Network/DummyTimerFactory.h> +// Clang wrongly things that tests for 0 are using 0 as null. +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" + using namespace Swift; class ChatStateNotifierTest : public ::testing::Test { protected: virtual void SetUp() { stanzaChannel = new DummyStanzaChannel(); stanzaChannel->setAvailable(true); entityCapsProvider = new DummyEntityCapsProvider(); diff --git a/Swiften/Client/ClientXMLTracer.cpp b/Swiften/Client/ClientXMLTracer.cpp index e205f41..e1b9e0c 100644 --- a/Swiften/Client/ClientXMLTracer.cpp +++ b/Swiften/Client/ClientXMLTracer.cpp @@ -10,21 +10,21 @@ #include <boost/bind.hpp> #include <Swiften/Base/Platform.h> namespace Swift { ClientXMLTracer::ClientXMLTracer(CoreClient* client, bool bosh) : bosh_(bosh) { #ifdef SWIFTEN_PLATFORM_WIN32 - beautifier_ = std::unique_ptr<XMLBeautifier>(new XMLBeautifier(true, false)); + beautifier_ = std::make_unique<XMLBeautifier>(true, false); #else - beautifier_ = std::unique_ptr<XMLBeautifier>(new XMLBeautifier(true, true)); + beautifier_ = std::make_unique<XMLBeautifier>(true, true); #endif onDataReadConnection_ = client->onDataRead.connect(boost::bind(&ClientXMLTracer::printData, this, '<', _1)); onDataWrittenConnection_ = client->onDataWritten.connect(boost::bind(&ClientXMLTracer::printData, this, '>', _1)); } void ClientXMLTracer::printData(char direction, const SafeByteArray& data) { if (bosh_) { printLine(direction); std::string line = byteArrayToString(ByteArray(data.begin(), data.end())); diff --git a/Swiften/Client/CoreClient.cpp b/Swiften/Client/CoreClient.cpp index 1de1d61..ccde0c2 100644 --- a/Swiften/Client/CoreClient.cpp +++ b/Swiften/Client/CoreClient.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Client/CoreClient.h> #include <memory> #include <boost/bind.hpp> @@ -79,42 +79,72 @@ void CoreClient::connect(const ClientOptions& o) { } if (systemHTTPConnectProxy.isValid()) { SWIFT_LOG(debug) << "Found HTTPConnect Proxy: " << systemHTTPConnectProxy.getAddress().toString() << ":" << systemHTTPConnectProxy.getPort() << std::endl; proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemHTTPConnectProxy.getAddress().toString(), systemHTTPConnectProxy.getPort())); } break; case ClientOptions::SOCKS5Proxy: { SWIFT_LOG(debug) << " with manual configured SOCKS5 proxy" << std::endl; std::string proxyHostname = o.manualProxyHostname.empty() ? systemSOCKS5Proxy.getAddress().toString() : o.manualProxyHostname; - int proxyPort = o.manualProxyPort == -1 ? systemSOCKS5Proxy.getPort() : o.manualProxyPort; + auto proxyPort = systemSOCKS5Proxy.getPort(); + if (o.manualProxyPort != -1) { + try { + proxyPort = boost::numeric_cast<unsigned short>(o.manualProxyPort); + } + catch (const boost::numeric::bad_numeric_cast& e) { + SWIFT_LOG(warning) << "Manual proxy port " << o.manualProxyPort << " is invalid: " << e.what() << std::endl; + onDisconnected(boost::optional<ClientError>(ClientError::ConnectionError)); + return; + } + } SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl; proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort)); useDirectConnection = false; break; } case ClientOptions::HTTPConnectProxy: { SWIFT_LOG(debug) << " with manual configured HTTPConnect proxy" << std::endl; std::string proxyHostname = o.manualProxyHostname.empty() ? systemHTTPConnectProxy.getAddress().toString() : o.manualProxyHostname; - int proxyPort = o.manualProxyPort == -1 ? systemHTTPConnectProxy.getPort() : o.manualProxyPort; + unsigned short proxyPort = systemHTTPConnectProxy.getPort(); + if (o.manualProxyPort != -1) { + try { + proxyPort = boost::numeric_cast<unsigned short>(o.manualProxyPort); + } + catch (const boost::numeric::bad_numeric_cast& e) { + SWIFT_LOG(warning) << "Manual proxy port " << o.manualProxyPort << " is invalid: " << e.what() << std::endl; + onDisconnected(boost::optional<ClientError>(ClientError::ConnectionError)); + return; + } + } SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl; proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort, o.httpTrafficFilter)); useDirectConnection = false; break; } } std::vector<ConnectionFactory*> connectionFactories(proxyConnectionFactories); if (useDirectConnection) { connectionFactories.push_back(networkFactories->getConnectionFactory()); } // Create connector std::string host = o.manualHostname.empty() ? jid_.getDomain() : o.manualHostname; - int port = o.manualPort; + unsigned short port = 0; + if (o.manualPort != -1) { + try { + port = boost::numeric_cast<unsigned short>(o.manualPort); + } + catch (const boost::numeric::bad_numeric_cast& e) { + SWIFT_LOG(warning) << "Invalid manual port " << o.manualPort << ": " << e.what() << std::endl; + onDisconnected(boost::optional<ClientError>(ClientError::ConnectionError)); + return; + } + } boost::optional<std::string> serviceLookupPrefix; if (o.manualHostname.empty()) { serviceLookupPrefix = "_xmpp-client._tcp."; } assert(!connector_); if (options.boshURL.isEmpty()) { connector_ = std::make_shared<ChainedConnector>(host, port, serviceLookupPrefix, networkFactories->getDomainNameResolver(), connectionFactories, networkFactories->getTimerFactory()); connector_->onConnectFinished.connect(boost::bind(&CoreClient::handleConnectorFinished, this, _1, _2)); connector_->setTimeoutMilliseconds(2*60*1000); @@ -280,18 +310,20 @@ void CoreClient::handleSessionFinished(std::shared_ptr<Error> error) { } clientError.setErrorCode(actualError->errorCode); } else if (std::shared_ptr<TLSError> actualError = std::dynamic_pointer_cast<TLSError>(error)) { switch(actualError->getType()) { case TLSError::CertificateCardRemoved: clientError = ClientError(ClientError::CertificateCardRemoved); break; case TLSError::UnknownError: + case TLSError::AcceptFailed: + case TLSError::ConnectFailed: clientError = ClientError(ClientError::TLSError); break; } } else if (std::shared_ptr<SessionStream::SessionStreamError> actualError = std::dynamic_pointer_cast<SessionStream::SessionStreamError>(error)) { switch(actualError->type) { case SessionStream::SessionStreamError::ParseError: clientError = ClientError(ClientError::XMLError); break; diff --git a/Swiften/Client/DummyStanzaChannel.h b/Swiften/Client/DummyStanzaChannel.h index 4cc0f7e..1ba70ad 100644 --- a/Swiften/Client/DummyStanzaChannel.h +++ b/Swiften/Client/DummyStanzaChannel.h @@ -42,20 +42,24 @@ namespace Swift { id += "-" + std::to_string(idCounter_++); } return id; } virtual bool isAvailable() const { return available_; } + virtual void setStreamManagementEnabled(bool enable) { + streamManagement_ = enable; + } + virtual bool getStreamManagementEnabled() const { - return false; + return streamManagement_; } template<typename T> bool isRequestAtIndex(size_t index, const JID& jid, IQ::Type type) { if (index >= sentStanzas.size()) { return false; } std::shared_ptr<IQ> iqStanza = std::dynamic_pointer_cast<IQ>(sentStanzas[index]); return iqStanza && iqStanza->getType() == type && iqStanza->getTo() == jid && iqStanza->getPayload<T>(); } @@ -95,11 +99,12 @@ namespace Swift { std::vector<Certificate::ref> getPeerCertificateChain() const { return std::vector<Certificate::ref>(); } std::vector<std::shared_ptr<Stanza> > sentStanzas; bool available_ = true; bool uniqueIDs_ = false; unsigned int idCounter_ = 0; + bool streamManagement_ = false; }; } diff --git a/Swiften/Client/UnitTest/XMLBeautifierTest.cpp b/Swiften/Client/UnitTest/XMLBeautifierTest.cpp index 0188634..2a639ea 100644 --- a/Swiften/Client/UnitTest/XMLBeautifierTest.cpp +++ b/Swiften/Client/UnitTest/XMLBeautifierTest.cpp @@ -1,66 +1,69 @@ /* - * Copyright (c) 2010-2017 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include "gtest/gtest.h" #include <Swiften/Client/XMLBeautifier.h> #include <iostream> +// Clang wrongly things that tests for 0 are using 0 as null. +#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" + using namespace Swift; namespace { const static std::string FULL_FORMATTED_OUTPUT("<list>\n <el>aqq</el>\n <el>bzz</el>\n</list>"); } TEST(XMLBeautifierTest, testBeautify) { - auto beautifier = std::unique_ptr<XMLBeautifier>(new XMLBeautifier(true, false)); + auto beautifier = std::make_unique<XMLBeautifier>(true, false); ASSERT_EQ(FULL_FORMATTED_OUTPUT, beautifier->beautify("<list><el>aqq</el><el>bzz</el></list>")); ASSERT_TRUE(beautifier->wasReset()); ASSERT_EQ(0, beautifier->getLevel()); ASSERT_EQ(FULL_FORMATTED_OUTPUT, beautifier->beautify("<list><el>aqq</el><el>bzz</el></list>")); ASSERT_TRUE(beautifier->wasReset()); ASSERT_EQ(0, beautifier->getLevel()); } TEST(XMLBeautifierTest, testBeautifyMultipleChunks) { - auto beautifier = std::unique_ptr<XMLBeautifier>(new XMLBeautifier(true, false)); + auto beautifier = std::make_unique<XMLBeautifier>(true, false); auto result = beautifier->beautify("<list><el>aqq</el>"); ASSERT_TRUE(beautifier->wasReset()); ASSERT_EQ(1, beautifier->getLevel()); result += beautifier->beautify("<el>bzz</el></list>"); ASSERT_FALSE(beautifier->wasReset()); ASSERT_EQ(0, beautifier->getLevel()); ASSERT_EQ(FULL_FORMATTED_OUTPUT, result); } TEST(XMLBeautifierTest, testBeautifyMultipleChunksMiddleElement) { - auto beautifier = std::unique_ptr<XMLBeautifier>(new XMLBeautifier(true, false)); + auto beautifier = std::make_unique<XMLBeautifier>(true, false); auto result = beautifier->beautify("<l"); ASSERT_TRUE(beautifier->wasReset()); ASSERT_EQ(0, beautifier->getLevel()); result += beautifier->beautify("ist><el>aqq</el><el>bzz</el></list>"); ASSERT_FALSE(beautifier->wasReset()); ASSERT_EQ(0, beautifier->getLevel()); ASSERT_EQ(FULL_FORMATTED_OUTPUT, result); } TEST(XMLBeautifierTest, testBeautifyInvalidMultipleChunks) { - auto beautifier = std::unique_ptr<XMLBeautifier>(new XMLBeautifier(true, false)); + auto beautifier = std::make_unique<XMLBeautifier>(true, false); ASSERT_EQ(std::string("<list>\n <el>aqq"), beautifier->beautify("<list><el>aqq<")); ASSERT_TRUE(beautifier->wasReset()); ASSERT_EQ(2, beautifier->getLevel()); ASSERT_EQ(FULL_FORMATTED_OUTPUT, beautifier->beautify("<list><el>aqq</el><el>bzz</el></list>")); ASSERT_TRUE(beautifier->wasReset()); ASSERT_EQ(0, beautifier->getLevel()); } diff --git a/Swiften/Component/ComponentConnector.cpp b/Swiften/Component/ComponentConnector.cpp index a7375a7..7789c4c 100644 --- a/Swiften/Component/ComponentConnector.cpp +++ b/Swiften/Component/ComponentConnector.cpp @@ -1,27 +1,27 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Component/ComponentConnector.h> #include <boost/bind.hpp> #include <Swiften/Network/ConnectionFactory.h> #include <Swiften/Network/DomainNameAddressQuery.h> #include <Swiften/Network/DomainNameResolver.h> #include <Swiften/Network/TimerFactory.h> namespace Swift { -ComponentConnector::ComponentConnector(const std::string& hostname, int port, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) : hostname(hostname), port(port), resolver(resolver), connectionFactory(connectionFactory), timerFactory(timerFactory), timeoutMilliseconds(0) { +ComponentConnector::ComponentConnector(const std::string& hostname, unsigned short port, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) : hostname(hostname), port(port), resolver(resolver), connectionFactory(connectionFactory), timerFactory(timerFactory), timeoutMilliseconds(0) { } void ComponentConnector::setTimeoutMilliseconds(int milliseconds) { timeoutMilliseconds = milliseconds; } void ComponentConnector::start() { assert(!currentConnection); assert(!timer); diff --git a/Swiften/Component/ComponentConnector.h b/Swiften/Component/ComponentConnector.h index ab36901..cfd49fe 100644 --- a/Swiften/Component/ComponentConnector.h +++ b/Swiften/Component/ComponentConnector.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <deque> #include <memory> #include <string> @@ -22,44 +22,44 @@ namespace Swift { class DomainNameAddressQuery; class DomainNameResolver; class ConnectionFactory; class TimerFactory; class SWIFTEN_API ComponentConnector : public boost::signals2::trackable, public std::enable_shared_from_this<ComponentConnector> { public: typedef std::shared_ptr<ComponentConnector> ref; - static ComponentConnector::ref create(const std::string& hostname, int port, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) { + static ComponentConnector::ref create(const std::string& hostname, unsigned short port, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) { return ref(new ComponentConnector(hostname, port, resolver, connectionFactory, timerFactory)); } void setTimeoutMilliseconds(int milliseconds); void start(); void stop(); boost::signals2::signal<void (std::shared_ptr<Connection>)> onConnectFinished; private: - ComponentConnector(const std::string& hostname, int port, DomainNameResolver*, ConnectionFactory*, TimerFactory*); + ComponentConnector(const std::string& hostname, unsigned short port, DomainNameResolver*, ConnectionFactory*, TimerFactory*); void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> error); void tryNextAddress(); void tryConnect(const HostAddressPort& target); void handleConnectionConnectFinished(bool error); void finish(std::shared_ptr<Connection>); void handleTimeout(); private: std::string hostname; - int port; + unsigned short port; DomainNameResolver* resolver; ConnectionFactory* connectionFactory; TimerFactory* timerFactory; int timeoutMilliseconds; std::shared_ptr<Timer> timer; std::shared_ptr<DomainNameAddressQuery> addressQuery; std::deque<HostAddress> addressQueryResults; std::shared_ptr<Connection> currentConnection; }; diff --git a/Swiften/Component/CoreComponent.cpp b/Swiften/Component/CoreComponent.cpp index 3896bdd..2d91c9c 100644 --- a/Swiften/Component/CoreComponent.cpp +++ b/Swiften/Component/CoreComponent.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Component/CoreComponent.h> #include <boost/bind.hpp> #include <Swiften/Base/IDGenerator.h> @@ -37,19 +37,19 @@ CoreComponent::~CoreComponent() { } delete iqRouter_; stanzaChannel_->onAvailableChanged.disconnect(boost::bind(&CoreComponent::handleStanzaChannelAvailableChanged, this, _1)); stanzaChannel_->onMessageReceived.disconnect(boost::ref(onMessageReceived)); stanzaChannel_->onPresenceReceived.disconnect(boost::ref(onPresenceReceived)); delete stanzaChannel_; } -void CoreComponent::connect(const std::string& host, int port) { +void CoreComponent::connect(const std::string& host, unsigned short port) { assert(!connector_); connector_ = ComponentConnector::create(host, port, networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory()); connector_->onConnectFinished.connect(boost::bind(&CoreComponent::handleConnectorFinished, this, _1)); connector_->setTimeoutMilliseconds(60*1000); connector_->start(); } void CoreComponent::handleConnectorFinished(std::shared_ptr<Connection> connection) { connector_->onConnectFinished.disconnect(boost::bind(&CoreComponent::handleConnectorFinished, this, _1)); @@ -160,10 +160,18 @@ void CoreComponent::sendMessage(std::shared_ptr<Message> message) { void CoreComponent::sendPresence(std::shared_ptr<Presence> presence) { stanzaChannel_->sendPresence(presence); } void CoreComponent::sendData(const std::string& data) { sessionStream_->writeData(data); } +bool CoreComponent::isActive() const { + return session_ || connector_; +} + +bool CoreComponent::isAvailable() const { + return stanzaChannel_->isAvailable(); +} + } diff --git a/Swiften/Component/CoreComponent.h b/Swiften/Component/CoreComponent.h index f673643..7565d00 100644 --- a/Swiften/Component/CoreComponent.h +++ b/Swiften/Component/CoreComponent.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2017 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> @@ -40,36 +40,45 @@ namespace Swift { * This class can be used directly in your application, although the Component * subclass provides more functionality and interfaces, and is better suited * for most needs. */ class SWIFTEN_API CoreComponent : public Entity { public: CoreComponent(const JID& jid, const std::string& secret, NetworkFactories* networkFactories); virtual ~CoreComponent(); - void connect(const std::string& host, int port); + void connect(const std::string& host, unsigned short port); void disconnect(); void sendMessage(std::shared_ptr<Message>); void sendPresence(std::shared_ptr<Presence>); void sendData(const std::string& data); IQRouter* getIQRouter() const { return iqRouter_; } StanzaChannel* getStanzaChannel() const { return stanzaChannel_; } - bool isAvailable() const { - return stanzaChannel_->isAvailable(); - } + /** + * Checks whether the component is connected to the server, + * and stanzas can be sent. + */ + bool isAvailable() const; + + /** + * Checks whether the component is active. + * + * A component is active when it is connected or connecting to the server. + */ + bool isActive() const; /** * Returns the JID of the component */ const JID& getJID() const { return jid_; } public: diff --git a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp index 3b4fa83..bd26989 100644 --- a/Swiften/Component/UnitTest/ComponentConnectorTest.cpp +++ b/Swiften/Component/UnitTest/ComponentConnectorTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <boost/bind.hpp> #include <boost/optional.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> @@ -140,19 +140,19 @@ class ComponentConnectorTest : public CppUnit::TestFixture { eventLoop->processEvents(); timerFactory->setTime(10); eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); CPPUNIT_ASSERT(!connections[0]); } private: - ComponentConnector::ref createConnector(const std::string& hostname, int port) { + ComponentConnector::ref createConnector(const std::string& hostname, unsigned short port) { ComponentConnector::ref connector = ComponentConnector::create(hostname, port, resolver, connectionFactory, timerFactory); connector->onConnectFinished.connect(boost::bind(&ComponentConnectorTest::handleConnectorFinished, this, _1)); return connector; } void handleConnectorFinished(std::shared_ptr<Connection> connection) { std::shared_ptr<MockConnection> c(std::dynamic_pointer_cast<MockConnection>(connection)); if (connection) { assert(c); diff --git a/Swiften/Config/SConscript b/Swiften/Config/SConscript index dd06d61..ae0d37a 100644 --- a/Swiften/Config/SConscript +++ b/Swiften/Config/SConscript @@ -4,39 +4,39 @@ Import("env") def replaceSwiftenPath(input) : return input.replace(env.Dir("#").abspath, "#") def cStringVariable(env, cVar, sconsVar) : result = "static const char* " + cVar + "[] = {\n" # FIXME: Probably not very robust for var in sconsVar.split(" ") : result += "\t\"" + env.subst(var).replace("\\", "\\\\") + "\",\n" - result += "\t0\n" + result += "\tnullptr\n" result += "};\n" return result config_flags = "" swiften_env = env.Clone() swiften_env.UseFlags(swiften_env["SWIFTEN_FLAGS"]) swiften_env.UseFlags(swiften_env["SWIFTEN_DEP_FLAGS"]) cppflags = replaceSwiftenPath(" ".join([ swiften_env.subst("$CPPFLAGS").replace("-isystem ","-I"), - swiften_env.subst("$_CPPDEFFLAGS"), + swiften_env.subst("$_CPPDEFFLAGS"), swiften_env.subst("$_CPPINCFLAGS")])) config_flags += cStringVariable(swiften_env, "CPPFLAGS", cppflags) libflags = replaceSwiftenPath(" ".join([ - swiften_env.subst("$_LIBDIRFLAGS"), - swiften_env.subst("$_LIBFLAGS"), - swiften_env.subst("$_FRAMEWORKPATH"), - swiften_env.subst("$_FRAMEWORKS"), + swiften_env.subst("$_LIBDIRFLAGS"), + swiften_env.subst("$_LIBFLAGS"), + swiften_env.subst("$_FRAMEWORKPATH"), + swiften_env.subst("$_FRAMEWORKS"), swiften_env.subst("$_FRAMEWORKSFLAGS") ])) config_flags += cStringVariable(swiften_env, "LIBFLAGS", libflags) config_env = env.Clone() config_env.Append(CPPDEFINES = ["SWIFTEN_STATIC"]) # Create a local copy of Paths.cpp to avoid a Swiften dependency config_env.Install(".", [ diff --git a/Swiften/Crypto/CommonCryptoCryptoProvider.cpp b/Swiften/Crypto/CommonCryptoCryptoProvider.cpp index 9fbdb2a..3cc69b0 100644 --- a/Swiften/Crypto/CommonCryptoCryptoProvider.cpp +++ b/Swiften/Crypto/CommonCryptoCryptoProvider.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Crypto/CommonCryptoCryptoProvider.h> #include <cassert> #include <boost/numeric/conversion/cast.hpp> @@ -21,96 +21,111 @@ using namespace Swift; namespace { class SHA1Hash : public Hash { public: SHA1Hash() : finalized(false) { if (!CC_SHA1_Init(&context)) { assert(false); } } - ~SHA1Hash() { + virtual ~SHA1Hash() override { } - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const ByteArray& data) override { return updateInternal(data); } - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const SafeByteArray& data) override { return updateInternal(data); } - virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { + virtual std::vector<unsigned char> getHash() override { assert(!finalized); std::vector<unsigned char> result(CC_SHA1_DIGEST_LENGTH); CC_SHA1_Final(vecptr(result), &context); return result; } private: template<typename ContainerType> Hash& updateInternal(const ContainerType& data) { assert(!finalized); - if (!CC_SHA1_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) { + try { + if (!CC_SHA1_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) { + assert(false); + } + } + catch (const boost::numeric::bad_numeric_cast&) { assert(false); } return *this; } private: CC_SHA1_CTX context; bool finalized; }; class MD5Hash : public Hash { public: MD5Hash() : finalized(false) { if (!CC_MD5_Init(&context)) { assert(false); } } - ~MD5Hash() { + virtual ~MD5Hash() override { } - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const ByteArray& data) override { return updateInternal(data); } - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const SafeByteArray& data) override { return updateInternal(data); } - virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { + virtual std::vector<unsigned char> getHash() override { assert(!finalized); std::vector<unsigned char> result(CC_MD5_DIGEST_LENGTH); CC_MD5_Final(vecptr(result), &context); return result; } private: template<typename ContainerType> Hash& updateInternal(const ContainerType& data) { assert(!finalized); - if (!CC_MD5_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) { + try { + if (!CC_MD5_Update(&context, vecptr(data), boost::numeric_cast<CC_LONG>(data.size()))) { + assert(false); + } + } + catch (const boost::numeric::bad_numeric_cast&) { assert(false); } return *this; } private: CC_MD5_CTX context; bool finalized; }; template<typename T> ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data) { std::vector<unsigned char> result(CC_SHA1_DIGEST_LENGTH); - CCHmac(kCCHmacAlgSHA1, vecptr(key), key.size(), vecptr(data), boost::numeric_cast<CC_LONG>(data.size()), vecptr(result)); + try { + CCHmac(kCCHmacAlgSHA1, vecptr(key), key.size(), vecptr(data), boost::numeric_cast<CC_LONG>(data.size()), vecptr(result)); + } + catch (const boost::numeric::bad_numeric_cast&) { + assert(false); + } return result; } } CommonCryptoCryptoProvider::CommonCryptoCryptoProvider() { } CommonCryptoCryptoProvider::~CommonCryptoCryptoProvider() { } diff --git a/Swiften/Crypto/CommonCryptoCryptoProvider.h b/Swiften/Crypto/CommonCryptoCryptoProvider.h index 8fa7fa6..7d1675f 100644 --- a/Swiften/Crypto/CommonCryptoCryptoProvider.h +++ b/Swiften/Crypto/CommonCryptoCryptoProvider.h @@ -1,25 +1,24 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Crypto/CryptoProvider.h> namespace Swift { class SWIFTEN_API CommonCryptoCryptoProvider : public CryptoProvider { public: CommonCryptoCryptoProvider(); - ~CommonCryptoCryptoProvider(); + virtual ~CommonCryptoCryptoProvider() override; - virtual Hash* createSHA1() SWIFTEN_OVERRIDE; - virtual Hash* createMD5() SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE; + virtual Hash* createSHA1() override; + virtual Hash* createMD5() override; + virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) override; + virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) override; + virtual bool isMD5AllowedForCrypto() const override; }; } diff --git a/Swiften/Crypto/OpenSSLCryptoProvider.cpp b/Swiften/Crypto/OpenSSLCryptoProvider.cpp index c785041..5245bd8 100644 --- a/Swiften/Crypto/OpenSSLCryptoProvider.cpp +++ b/Swiften/Crypto/OpenSSLCryptoProvider.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2013 Isode Limited. + * Copyright (c) 2013-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Crypto/OpenSSLCryptoProvider.h> #include <openssl/sha.h> #include <openssl/md5.h> #include <openssl/hmac.h> @@ -22,30 +22,30 @@ using namespace Swift; namespace { class SHA1Hash : public Hash { public: SHA1Hash() : finalized(false) { if (!SHA1_Init(&context)) { assert(false); } } - ~SHA1Hash() { + ~SHA1Hash() override { } - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const ByteArray& data) override { return updateInternal(data); } - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const SafeByteArray& data) override { return updateInternal(data); } - virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { + virtual std::vector<unsigned char> getHash() override { assert(!finalized); std::vector<unsigned char> result(SHA_DIGEST_LENGTH); SHA1_Final(vecptr(result), &context); return result; } private: template<typename ContainerType> Hash& updateInternal(const ContainerType& data) { @@ -63,30 +63,30 @@ namespace { class MD5Hash : public Hash { public: MD5Hash() : finalized(false) { if (!MD5_Init(&context)) { assert(false); } } - ~MD5Hash() { + ~MD5Hash() override { } - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const ByteArray& data) override { return updateInternal(data); } - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const SafeByteArray& data) override { return updateInternal(data); } - virtual std::vector<unsigned char> getHash() SWIFTEN_OVERRIDE { + virtual std::vector<unsigned char> getHash() override { assert(!finalized); std::vector<unsigned char> result(MD5_DIGEST_LENGTH); MD5_Final(vecptr(result), &context); return result; } private: template<typename ContainerType> Hash& updateInternal(const ContainerType& data) { @@ -101,19 +101,24 @@ namespace { MD5_CTX context; bool finalized; }; template<typename T> ByteArray getHMACSHA1Internal(const T& key, const ByteArray& data) { unsigned int len = SHA_DIGEST_LENGTH; std::vector<unsigned char> result(len); - HMAC(EVP_sha1(), vecptr(key), boost::numeric_cast<int>(key.size()), vecptr(data), data.size(), vecptr(result), &len); + try { + HMAC(EVP_sha1(), vecptr(key), boost::numeric_cast<int>(key.size()), vecptr(data), data.size(), vecptr(result), &len); + } + catch (const boost::numeric::bad_numeric_cast&) { + assert(false); + } return result; } } OpenSSLCryptoProvider::OpenSSLCryptoProvider() { } OpenSSLCryptoProvider::~OpenSSLCryptoProvider() { } diff --git a/Swiften/Crypto/OpenSSLCryptoProvider.h b/Swiften/Crypto/OpenSSLCryptoProvider.h index 6e0c01b..e4ee97d 100644 --- a/Swiften/Crypto/OpenSSLCryptoProvider.h +++ b/Swiften/Crypto/OpenSSLCryptoProvider.h @@ -1,24 +1,23 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once -#include <Swiften/Base/Override.h> #include <Swiften/Crypto/CryptoProvider.h> namespace Swift { class OpenSSLCryptoProvider : public CryptoProvider { public: OpenSSLCryptoProvider(); - ~OpenSSLCryptoProvider(); + virtual ~OpenSSLCryptoProvider() override; - virtual Hash* createSHA1() SWIFTEN_OVERRIDE; - virtual Hash* createMD5() SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE; + virtual Hash* createSHA1() override; + virtual Hash* createMD5() override; + virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) override; + virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) override; + virtual bool isMD5AllowedForCrypto() const override; }; } diff --git a/Swiften/Crypto/WindowsCryptoProvider.cpp b/Swiften/Crypto/WindowsCryptoProvider.cpp index 513941f..c784283 100644 --- a/Swiften/Crypto/WindowsCryptoProvider.cpp +++ b/Swiften/Crypto/WindowsCryptoProvider.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ /* * Copyright (c) 2013 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -37,23 +37,23 @@ namespace { if (!CryptCreateHash(context, algorithm, 0, 0, &hash)) { assert(false); } } virtual ~WindowsHash() { CryptDestroyHash(hash); } - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const ByteArray& data) override { return updateInternal(data); } - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const SafeByteArray& data) override { return updateInternal(data); } virtual std::vector<unsigned char> getHash() { std::vector<unsigned char> result; DWORD hashLength = sizeof(DWORD); DWORD hashSize; CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0); result.resize(static_cast<size_t>(hashSize)); @@ -117,23 +117,23 @@ namespace { } ZeroMemory(&info, sizeof(info)); info.HashAlgid = CALG_SHA1; } ~HMACHash() { CryptDestroyHash(hash); } - virtual Hash& update(const ByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const ByteArray& data) override { return updateInternal(data); } - virtual Hash& update(const SafeByteArray& data) SWIFTEN_OVERRIDE { + virtual Hash& update(const SafeByteArray& data) override { return updateInternal(data); } virtual std::vector<unsigned char> getHash() { std::vector<unsigned char> result; DWORD hashLength = sizeof(DWORD); DWORD hashSize; CryptGetHashParam(hash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&hashSize), &hashLength, 0); result.resize(static_cast<size_t>(hashSize)); diff --git a/Swiften/Crypto/WindowsCryptoProvider.h b/Swiften/Crypto/WindowsCryptoProvider.h index f446027..d0c982e 100644 --- a/Swiften/Crypto/WindowsCryptoProvider.h +++ b/Swiften/Crypto/WindowsCryptoProvider.h @@ -1,32 +1,31 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <boost/noncopyable.hpp> -#include <Swiften/Base/Override.h> #include <Swiften/Crypto/CryptoProvider.h> namespace Swift { class WindowsCryptoProvider : public CryptoProvider, public boost::noncopyable { public: WindowsCryptoProvider(); virtual ~WindowsCryptoProvider(); - virtual Hash* createSHA1() SWIFTEN_OVERRIDE; - virtual Hash* createMD5() SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) SWIFTEN_OVERRIDE; - virtual bool isMD5AllowedForCrypto() const SWIFTEN_OVERRIDE; + virtual Hash* createSHA1() override; + virtual Hash* createMD5() override; + virtual ByteArray getHMACSHA1(const SafeByteArray& key, const ByteArray& data) override; + virtual ByteArray getHMACSHA1(const ByteArray& key, const ByteArray& data) override; + virtual bool isMD5AllowedForCrypto() const override; private: struct Private; const std::unique_ptr<Private> p; }; } diff --git a/Swiften/Disco/UnitTest/CapsManagerTest.cpp b/Swiften/Disco/UnitTest/CapsManagerTest.cpp index 153e821..5f1aaf4 100644 --- a/Swiften/Disco/UnitTest/CapsManagerTest.cpp +++ b/Swiften/Disco/UnitTest/CapsManagerTest.cpp @@ -41,21 +41,21 @@ class CapsManagerTest : public CppUnit::TestFixture { CPPUNIT_TEST(testReceiveFailingFallbackDiscoFallsBack); CPPUNIT_TEST(testReceiveSameHashFromFailingUserAfterReconnectRequestsDisco); CPPUNIT_TEST(testReconnectResetsFallback); CPPUNIT_TEST(testReconnectResetsRequests); CPPUNIT_TEST_SUITE_END(); public: void setUp() { crypto = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - stanzaChannel = std::unique_ptr<DummyStanzaChannel>(new DummyStanzaChannel()); - iqRouter = std::unique_ptr<IQRouter>(new IQRouter(stanzaChannel.get())); - storage = std::unique_ptr<CapsMemoryStorage>(new CapsMemoryStorage()); + stanzaChannel = std::make_unique<DummyStanzaChannel>(); + iqRouter = std::make_unique<IQRouter>(stanzaChannel.get()); + storage = std::make_unique<CapsMemoryStorage>(); user1 = JID("user1@bar.com/bla"); discoInfo1 = std::make_shared<DiscoInfo>(); discoInfo1->addFeature("http://swift.im/feature1"); capsInfo1 = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); capsInfo1alt = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); user2 = JID("user2@foo.com/baz"); discoInfo2 = std::make_shared<DiscoInfo>(); discoInfo2->addFeature("http://swift.im/feature2"); capsInfo2 = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo2.get())); diff --git a/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp b/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp index 8c59741..6548485 100644 --- a/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp +++ b/Swiften/Disco/UnitTest/EntityCapsManagerTest.cpp @@ -31,20 +31,20 @@ class EntityCapsManagerTest : public CppUnit::TestFixture { CPPUNIT_TEST(testReceiveUnavailablePresenceAfterKnownHashTriggersChangeAndClearsCaps); CPPUNIT_TEST(testReconnectTriggersChangeAndClearsCaps); CPPUNIT_TEST(testHashAvailable); CPPUNIT_TEST_SUITE_END(); public: void setUp() { crypto = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); - stanzaChannel = std::unique_ptr<DummyStanzaChannel>(new DummyStanzaChannel()); - capsProvider = std::unique_ptr<DummyCapsProvider>(new DummyCapsProvider()); + stanzaChannel = std::make_unique<DummyStanzaChannel>(); + capsProvider = std::make_unique<DummyCapsProvider>(); user1 = JID("user1@bar.com/bla"); discoInfo1 = std::make_shared<DiscoInfo>(); discoInfo1->addFeature("http://swift.im/feature1"); capsInfo1 = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node1.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); capsInfo1alt = std::make_shared<CapsInfo>(CapsInfoGenerator("http://node2.im", crypto.get()).generateCapsInfo(*discoInfo1.get())); user2 = JID("user2@foo.com/baz"); discoInfo2 = std::make_shared<DiscoInfo>(); discoInfo2->addFeature("http://swift.im/feature2"); diff --git a/Swiften/Elements/Bytestreams.h b/Swiften/Elements/Bytestreams.h index ca30922..599ed46 100644 --- a/Swiften/Elements/Bytestreams.h +++ b/Swiften/Elements/Bytestreams.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> @@ -16,23 +16,23 @@ #include <Swiften/Elements/Payload.h> #include <Swiften/JID/JID.h> namespace Swift { class SWIFTEN_API Bytestreams : public Payload { public: typedef std::shared_ptr<Bytestreams> ref; struct StreamHost { - StreamHost(const std::string& host = "", const JID& jid = JID(), int port = -1) : host(host), jid(jid), port(port) {} + StreamHost(const std::string& host = "", const JID& jid = JID(), unsigned short port = 0) : host(host), jid(jid), port(port) {} std::string host; JID jid; - int port; + unsigned short port; }; Bytestreams() {} const std::string& getStreamID() const { return id; } void setStreamID(const std::string& id) { diff --git a/Swiften/Elements/ContainerPayload.h b/Swiften/Elements/ContainerPayload.h index 3da04b7..033575a 100644 --- a/Swiften/Elements/ContainerPayload.h +++ b/Swiften/Elements/ContainerPayload.h @@ -1,22 +1,21 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <vector> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { template<typename T> class SWIFTEN_API ContainerPayload : public Payload { public: ContainerPayload() {} ContainerPayload(std::shared_ptr<T> payload) : payload(payload) {} diff --git a/Swiften/Elements/DiscoInfo.cpp b/Swiften/Elements/DiscoInfo.cpp index 11f0623..701ed40 100644 --- a/Swiften/Elements/DiscoInfo.cpp +++ b/Swiften/Elements/DiscoInfo.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2015 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Elements/DiscoInfo.h> #include <algorithm> namespace Swift { @@ -20,18 +20,19 @@ const std::string DiscoInfo::MessageCorrectionFeature = std::string("urn:xmpp:me const std::string DiscoInfo::JingleFeature = std::string("urn:xmpp:jingle:1"); const std::string DiscoInfo::JingleFTFeature = std::string("urn:xmpp:jingle:apps:file-transfer:4"); 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"); const std::string DiscoInfo::MessageDeliveryReceiptsFeature = std::string("urn:xmpp:receipts"); const std::string DiscoInfo::WhiteboardFeature = std::string("http://swift.im/whiteboard"); const std::string DiscoInfo::BlockingCommandFeature = std::string("urn:xmpp:blocking"); const std::string DiscoInfo::MessageCarbonsFeature = std::string("urn:xmpp:carbons:2"); +const std::string DiscoInfo::ReferencesFeature = std::string("urn:xmpp:references:0"); bool DiscoInfo::Identity::operator<(const Identity& other) const { if (category_ == other.category_) { if (type_ == other.type_) { if (lang_ == other.lang_) { return name_ < other.name_; } else { return lang_ < other.lang_; diff --git a/Swiften/Elements/DiscoInfo.h b/Swiften/Elements/DiscoInfo.h index c8009ee..713eaba 100644 --- a/Swiften/Elements/DiscoInfo.h +++ b/Swiften/Elements/DiscoInfo.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <vector> @@ -31,18 +31,19 @@ namespace Swift { 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; static const std::string MessageDeliveryReceiptsFeature; static const std::string WhiteboardFeature; static const std::string BlockingCommandFeature; static const std::string MessageCarbonsFeature; + static const std::string ReferencesFeature; class Identity { public: Identity(const std::string& name, const std::string& category = "client", const std::string& type = "pc", const std::string& lang = "") : name_(name), category_(category), type_(type), lang_(lang) { } const std::string& getCategory() const { return category_; } diff --git a/Swiften/Elements/Form.h b/Swiften/Elements/Form.h index 899fb93..827e497 100644 --- a/Swiften/Elements/Form.h +++ b/Swiften/Elements/Form.h @@ -83,26 +83,32 @@ namespace Swift { void setInstructions(const std::string& instructions) { instructions_ = instructions; } const std::string& getInstructions() const { return instructions_; } + /** Returns the Form::Type enum (ie. ResultType, CancelType etc.). + * NOT to be confused with Form::getFormType(). + */ Type getType() const { return type_; } void setType(Type type) { type_ = type; } + /** Returns the value of the field FORM_TYPE + * NOT to be confused with Form::getType(). + */ std::string getFormType() const; FormField::ref getField(const std::string& name) const; void addItem(const FormItem& item); const std::vector<FormItem>& getItems() const; void clearItems() { items_.clear(); } void clearEmptyTextFields(); void addReportedField(FormField::ref field); diff --git a/Swiften/Elements/IBB.h b/Swiften/Elements/IBB.h index bd0b661..6ebe66e 100644 --- a/Swiften/Elements/IBB.h +++ b/Swiften/Elements/IBB.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> @@ -22,22 +22,22 @@ namespace Swift { Open, Close, Data }; enum StanzaType { IQStanza, MessageStanza }; - IBB(Action action = Open, const std::string& streamID = "") : action(action), streamID(streamID), stanzaType(IQStanza), blockSize(-1), sequenceNumber(-1) { + IBB(Action action = Open, const std::string& streamID = "") : action(action), streamID(streamID), stanzaType(IQStanza), blockSize(0), sequenceNumber(-1) { } - static IBB::ref createIBBOpen(const std::string& streamID, int blockSize) { + static IBB::ref createIBBOpen(const std::string& streamID, unsigned int blockSize) { IBB::ref result = std::make_shared<IBB>(Open, streamID); result->setBlockSize(blockSize); return result; } static IBB::ref createIBBData(const std::string& streamID, int sequenceNumber, const std::vector<unsigned char>& data) { IBB::ref result = std::make_shared<IBB>(Data, streamID); result->setSequenceNumber(sequenceNumber); result->setData(data); @@ -74,34 +74,34 @@ namespace Swift { const std::vector<unsigned char>& getData() const { return data; } void setData(const std::vector<unsigned char>& data) { this->data = data; } - int getBlockSize() const { + unsigned int getBlockSize() const { return blockSize; } - void setBlockSize(int blockSize) { + void setBlockSize(unsigned int blockSize) { this->blockSize = blockSize; } int getSequenceNumber() const { return sequenceNumber; } void setSequenceNumber(int i) { sequenceNumber = i; } private: Action action; std::string streamID; std::vector<unsigned char> data; StanzaType stanzaType; - int blockSize; + unsigned int blockSize; int sequenceNumber; }; } diff --git a/Swiften/Elements/IsodeIQDelegation.h b/Swiften/Elements/IsodeIQDelegation.h index 39655ce..074a06d 100644 --- a/Swiften/Elements/IsodeIQDelegation.h +++ b/Swiften/Elements/IsodeIQDelegation.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Forwarded.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API IsodeIQDelegation : public Payload { public: IsodeIQDelegation(); diff --git a/Swiften/Elements/MIXJoin.h b/Swiften/Elements/MIXJoin.h index 2d82adc..ecd7b12 100644 --- a/Swiften/Elements/MIXJoin.h +++ b/Swiften/Elements/MIXJoin.h @@ -2,72 +2,76 @@ * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ #pragma once #include <memory> #include <string> +#include <unordered_set> #include <boost/optional.hpp> #include <Swiften/Base/API.h> #include <Swiften/Elements/Payload.h> -#include <Swiften/Elements/MIXSubscribe.h> #include <Swiften/Elements/Form.h> #include <Swiften/JID/JID.h> namespace Swift { class SWIFTEN_API MIXJoin : public Payload { public: using ref = std::shared_ptr<MIXJoin>; public: MIXJoin() {} const boost::optional<JID>& getChannel() const { return channel_; } - void setChannel(const JID& channel) { + void setChannel(JID channel) { channel_ = channel; } const boost::optional<JID>& getJID() const { return jid_; } - void setJID(const JID& jid) { + void setJID(JID jid) { jid_ = jid; } - const std::vector<MIXSubscribe::ref>& getSubscriptions() const { + const std::unordered_set<std::string>& getSubscriptions() const { return subscribeItems_; } - void setSubscriptions(const std::vector<MIXSubscribe::ref>& value) { - subscribeItems_ = value ; + void setSubscriptions(std::unordered_set<std::string> values) { + subscribeItems_ = values ; } - void addSubscription(MIXSubscribe::ref value) { - subscribeItems_.push_back(value); + void addSubscription(std::string value) { + subscribeItems_.insert(value); + } + + bool hasSubscription(const std::string& value) const { + return std::find(subscribeItems_.begin(), subscribeItems_.end(), value) != subscribeItems_.end(); } void setForm(std::shared_ptr<Form> form) { form_ = form; } const std::shared_ptr<Form>& getForm() const { return form_; } private: boost::optional<JID> jid_; boost::optional<JID> channel_; - std::vector<MIXSubscribe::ref> subscribeItems_; + std::unordered_set<std::string> subscribeItems_; std::shared_ptr<Form> form_; // FIXME: MIXInvitation to be implemented. boost::optional<MIXInvitation> invitation_; }; } diff --git a/Swiften/Elements/MIXLeave.h b/Swiften/Elements/MIXLeave.h new file mode 100644 index 0000000..76ca09d --- /dev/null +++ b/Swiften/Elements/MIXLeave.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#pragma once + +#include <memory> + +#include <boost/optional.hpp> + +#include <Swiften/Base/API.h> +#include <Swiften/JID/JID.h> +#include <Swiften/Elements/Payload.h> + +namespace Swift { + class SWIFTEN_API MIXLeave : public Payload { + public: + using ref = std::shared_ptr<MIXLeave>; + + public: + + MIXLeave() {} + + const boost::optional<JID>& getChannel() const { + return channel_; + } + + void setChannel(const JID& channel) { + channel_ = channel; + } + + private: + boost::optional<JID> channel_; + }; +} diff --git a/Swiften/Elements/MIXPayload.h b/Swiften/Elements/MIXPayload.h new file mode 100644 index 0000000..3989c18 --- /dev/null +++ b/Swiften/Elements/MIXPayload.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#pragma once + +#include <memory> +#include <string> + +#include <boost/optional.hpp> + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/Payload.h> +#include <Swiften/JID/JID.h> + +namespace Swift { + class SWIFTEN_API MIXPayload : public Payload { + public: + using ref = std::shared_ptr<MIXPayload>; + + public: + + MIXPayload() {} + + const boost::optional<std::string>& getNick() const { + return nick_; + } + + void setNick(const std::string& nick) { + nick_ = nick; + } + + const boost::optional<JID>& getJID() const { + return jid_; + } + + void setJID(const JID& jid) { + jid_ = jid; + } + + const boost::optional<std::string>& getSubmissionID() const { + return submissionId_; + } + + void setSubmissionID(const std::string& submissionId) { + submissionId_ = submissionId; + } + + private: + boost::optional<JID> jid_; + boost::optional<std::string> nick_; + boost::optional<std::string> submissionId_; + }; +} diff --git a/Swiften/Elements/MIXSubscribe.h b/Swiften/Elements/MIXRegisterNick.h index eaf1aa9..3bd8c4a 100644 --- a/Swiften/Elements/MIXSubscribe.h +++ b/Swiften/Elements/MIXRegisterNick.h @@ -3,36 +3,33 @@ * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ #pragma once #include <memory> #include <string> -#include <boost/optional.hpp> - #include <Swiften/Base/API.h> #include <Swiften/Elements/Payload.h> namespace Swift { - class SWIFTEN_API MIXSubscribe : public Payload { - + class SWIFTEN_API MIXRegisterNick : public Payload { public: - using ref = std::shared_ptr<MIXSubscribe>; + using ref = std::shared_ptr<MIXRegisterNick>; public: - MIXSubscribe() {} + MIXRegisterNick() {} - const std::string& getNode() const { - return node_; + const std::string& getNick() const { + return nick_; } - void setNode(const std::string& node) { - node_ = node; + void setNick(const std::string& nick) { + nick_ = nick; } private: - std::string node_; + std::string nick_; }; } diff --git a/Swiften/Elements/MIXSetNick.h b/Swiften/Elements/MIXSetNick.h new file mode 100644 index 0000000..94c5a3b --- /dev/null +++ b/Swiften/Elements/MIXSetNick.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#pragma once + +#include <memory> +#include <string> + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/Payload.h> + +namespace Swift { + class SWIFTEN_API MIXSetNick : public Payload { + public: + using ref = std::shared_ptr<MIXSetNick>; + + public: + + MIXSetNick() {} + + const std::string& getNick() const { + return nick_; + } + + void setNick(const std::string& nick) { + nick_ = nick; + } + + private: + std::string nick_; + }; +} diff --git a/Swiften/Elements/MIXUpdateSubscription.h b/Swiften/Elements/MIXUpdateSubscription.h new file mode 100644 index 0000000..dc6ed27 --- /dev/null +++ b/Swiften/Elements/MIXUpdateSubscription.h @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#pragma once + +#include <memory> +#include <unordered_set> + +#include <boost/optional.hpp> + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/Payload.h> +#include <Swiften/JID/JID.h> + +namespace Swift { + class SWIFTEN_API MIXUpdateSubscription : public Payload { + + public: + using ref = std::shared_ptr<MIXUpdateSubscription>; + + public: + + MIXUpdateSubscription() {} + + const boost::optional<JID>& getJID() const { + return jid_; + } + + void setJID(JID jid) { + jid_ = jid; + } + + const std::unordered_set<std::string>& getSubscriptions() const { + return subscribeItems_; + } + + void setSubscriptions(std::unordered_set<std::string> values) { + subscribeItems_ = values ; + } + + void addSubscription(std::string value) { + subscribeItems_.insert(value); + } + + bool hasSubscription(const std::string& value) const { + return std::find(subscribeItems_.begin(), subscribeItems_.end(), value) != subscribeItems_.end(); + } + + private: + boost::optional<JID> jid_; + std::unordered_set<std::string> subscribeItems_; + }; +} diff --git a/Swiften/Elements/PubSub.h b/Swiften/Elements/PubSub.h index d62c54e..47b8c3f 100644 --- a/Swiften/Elements/PubSub.h +++ b/Swiften/Elements/PubSub.h @@ -1,19 +1,18 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/ContainerPayload.h> #include <Swiften/Elements/PubSubPayload.h> namespace Swift { class SWIFTEN_API PubSub : public ContainerPayload<PubSubPayload> { public: PubSub(); virtual ~PubSub(); }; diff --git a/Swiften/Elements/PubSubAffiliation.h b/Swiften/Elements/PubSubAffiliation.h index b19e84b..058ef88 100644 --- a/Swiften/Elements/PubSubAffiliation.h +++ b/Swiften/Elements/PubSubAffiliation.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API PubSubAffiliation : public Payload { public: enum Type { None, Member, Outcast, diff --git a/Swiften/Elements/PubSubAffiliations.h b/Swiften/Elements/PubSubAffiliations.h index c7e22ce..f3a6dda 100644 --- a/Swiften/Elements/PubSubAffiliations.h +++ b/Swiften/Elements/PubSubAffiliations.h @@ -1,25 +1,24 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubAffiliation.h> #include <Swiften/Elements/PubSubPayload.h> namespace Swift { class SWIFTEN_API PubSubAffiliations : public PubSubPayload { public: PubSubAffiliations(); diff --git a/Swiften/Elements/PubSubConfigure.h b/Swiften/Elements/PubSubConfigure.h index 8442198..88a1ea9 100644 --- a/Swiften/Elements/PubSubConfigure.h +++ b/Swiften/Elements/PubSubConfigure.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Form.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API PubSubConfigure : public Payload { public: PubSubConfigure(); diff --git a/Swiften/Elements/PubSubCreate.h b/Swiften/Elements/PubSubCreate.h index 5ece36e..ac6b987 100644 --- a/Swiften/Elements/PubSubCreate.h +++ b/Swiften/Elements/PubSubCreate.h @@ -1,22 +1,21 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubConfigure.h> #include <Swiften/Elements/PubSubPayload.h> namespace Swift { class SWIFTEN_API PubSubCreate : public PubSubPayload { public: PubSubCreate(); diff --git a/Swiften/Elements/PubSubDefault.h b/Swiften/Elements/PubSubDefault.h index 08482b4..aa058ac 100644 --- a/Swiften/Elements/PubSubDefault.h +++ b/Swiften/Elements/PubSubDefault.h @@ -1,23 +1,22 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubPayload.h> namespace Swift { class SWIFTEN_API PubSubDefault : public PubSubPayload { public: enum Type { None, Collection, diff --git a/Swiften/Elements/PubSubEvent.h b/Swiften/Elements/PubSubEvent.h index 8f02258..561f731 100644 --- a/Swiften/Elements/PubSubEvent.h +++ b/Swiften/Elements/PubSubEvent.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/ContainerPayload.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubEventPayload.h> namespace Swift { class SWIFTEN_API PubSubEvent : public ContainerPayload<PubSubEventPayload> { public: PubSubEvent(); virtual ~PubSubEvent(); diff --git a/Swiften/Elements/PubSubEventAssociate.h b/Swiften/Elements/PubSubEventAssociate.h index 5d963a0..b7bb839 100644 --- a/Swiften/Elements/PubSubEventAssociate.h +++ b/Swiften/Elements/PubSubEventAssociate.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API PubSubEventAssociate : public Payload { public: PubSubEventAssociate(); virtual ~PubSubEventAssociate(); diff --git a/Swiften/Elements/PubSubEventCollection.h b/Swiften/Elements/PubSubEventCollection.h index 61056e2..367fe02 100644 --- a/Swiften/Elements/PubSubEventCollection.h +++ b/Swiften/Elements/PubSubEventCollection.h @@ -1,24 +1,23 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubEventAssociate.h> #include <Swiften/Elements/PubSubEventDisassociate.h> #include <Swiften/Elements/PubSubEventPayload.h> namespace Swift { class SWIFTEN_API PubSubEventCollection : public PubSubEventPayload { public: diff --git a/Swiften/Elements/PubSubEventConfiguration.h b/Swiften/Elements/PubSubEventConfiguration.h index 6c5305d..e529014 100644 --- a/Swiften/Elements/PubSubEventConfiguration.h +++ b/Swiften/Elements/PubSubEventConfiguration.h @@ -1,22 +1,21 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Form.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubEventPayload.h> namespace Swift { class SWIFTEN_API PubSubEventConfiguration : public PubSubEventPayload { public: PubSubEventConfiguration(); diff --git a/Swiften/Elements/PubSubEventDelete.h b/Swiften/Elements/PubSubEventDelete.h index 787dce0..f899d4e 100644 --- a/Swiften/Elements/PubSubEventDelete.h +++ b/Swiften/Elements/PubSubEventDelete.h @@ -1,22 +1,21 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubEventPayload.h> #include <Swiften/Elements/PubSubEventRedirect.h> namespace Swift { class SWIFTEN_API PubSubEventDelete : public PubSubEventPayload { public: PubSubEventDelete(); diff --git a/Swiften/Elements/PubSubEventDisassociate.h b/Swiften/Elements/PubSubEventDisassociate.h index 826b1f4..415ac29 100644 --- a/Swiften/Elements/PubSubEventDisassociate.h +++ b/Swiften/Elements/PubSubEventDisassociate.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API PubSubEventDisassociate : public Payload { public: PubSubEventDisassociate(); virtual ~PubSubEventDisassociate(); diff --git a/Swiften/Elements/PubSubEventItem.h b/Swiften/Elements/PubSubEventItem.h index 50e8757..defdbf4 100644 --- a/Swiften/Elements/PubSubEventItem.h +++ b/Swiften/Elements/PubSubEventItem.h @@ -1,25 +1,24 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API PubSubEventItem : public Payload { public: PubSubEventItem(); virtual ~PubSubEventItem(); diff --git a/Swiften/Elements/PubSubEventItems.h b/Swiften/Elements/PubSubEventItems.h index 48fd340..aade826 100644 --- a/Swiften/Elements/PubSubEventItems.h +++ b/Swiften/Elements/PubSubEventItems.h @@ -1,23 +1,22 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubEventItem.h> #include <Swiften/Elements/PubSubEventPayload.h> #include <Swiften/Elements/PubSubEventRetract.h> namespace Swift { class SWIFTEN_API PubSubEventItems : public PubSubEventPayload { public: diff --git a/Swiften/Elements/PubSubEventPurge.h b/Swiften/Elements/PubSubEventPurge.h index 743cc25..647598d 100644 --- a/Swiften/Elements/PubSubEventPurge.h +++ b/Swiften/Elements/PubSubEventPurge.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubEventPayload.h> namespace Swift { class SWIFTEN_API PubSubEventPurge : public PubSubEventPayload { public: PubSubEventPurge(); diff --git a/Swiften/Elements/PubSubEventRedirect.h b/Swiften/Elements/PubSubEventRedirect.h index e0e351f..063cf8c 100644 --- a/Swiften/Elements/PubSubEventRedirect.h +++ b/Swiften/Elements/PubSubEventRedirect.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API PubSubEventRedirect : public Payload { public: PubSubEventRedirect(); virtual ~PubSubEventRedirect(); diff --git a/Swiften/Elements/PubSubEventRetract.h b/Swiften/Elements/PubSubEventRetract.h index b0aea96..19e02c9 100644 --- a/Swiften/Elements/PubSubEventRetract.h +++ b/Swiften/Elements/PubSubEventRetract.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API PubSubEventRetract : public Payload { public: PubSubEventRetract(); virtual ~PubSubEventRetract(); diff --git a/Swiften/Elements/PubSubEventSubscription.h b/Swiften/Elements/PubSubEventSubscription.h index 0b8297c..37e8b74 100644 --- a/Swiften/Elements/PubSubEventSubscription.h +++ b/Swiften/Elements/PubSubEventSubscription.h @@ -1,24 +1,23 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubEventPayload.h> #include <Swiften/JID/JID.h> namespace Swift { class SWIFTEN_API PubSubEventSubscription : public PubSubEventPayload { public: enum SubscriptionType { None, diff --git a/Swiften/Elements/PubSubItem.cpp b/Swiften/Elements/PubSubItem.cpp index 4dc0907..b5f17cc 100644 --- a/Swiften/Elements/PubSubItem.cpp +++ b/Swiften/Elements/PubSubItem.cpp @@ -1,15 +1,18 @@ /* - * Copyright (c) 2013 Isode Limited. + * Copyright (c) 2013-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Elements/PubSubItem.h> using namespace Swift; PubSubItem::PubSubItem() { } +PubSubItem::PubSubItem(const std::string& id) : id_(id) { +} + PubSubItem::~PubSubItem() { } diff --git a/Swiften/Elements/PubSubItem.h b/Swiften/Elements/PubSubItem.h index d424ae4..161b733 100644 --- a/Swiften/Elements/PubSubItem.h +++ b/Swiften/Elements/PubSubItem.h @@ -1,50 +1,49 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API PubSubItem : public Payload { public: PubSubItem(); + PubSubItem(const std::string& id); virtual ~PubSubItem(); const std::vector< std::shared_ptr<Payload> >& getData() const { - return data; + return data_; } void setData(const std::vector< std::shared_ptr<Payload> >& value) { - this->data = value ; + this->data_ = value ; } void addData(std::shared_ptr<Payload> value) { - this->data.push_back(value); + this->data_.push_back(value); } const std::string& getID() const { - return id; + return id_; } void setID(const std::string& value) { - this->id = value ; + this->id_ = value ; } - private: - std::vector< std::shared_ptr<Payload> > data; - std::string id; + std::vector< std::shared_ptr<Payload> > data_; + std::string id_; }; } diff --git a/Swiften/Elements/PubSubItems.h b/Swiften/Elements/PubSubItems.h index 9903075..c8b7f53 100644 --- a/Swiften/Elements/PubSubItems.h +++ b/Swiften/Elements/PubSubItems.h @@ -1,25 +1,24 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubItem.h> #include <Swiften/Elements/PubSubPayload.h> namespace Swift { class SWIFTEN_API PubSubItems : public PubSubPayload { public: PubSubItems(); @@ -56,17 +55,16 @@ namespace Swift { const boost::optional< std::string >& getSubscriptionID() const { return subscriptionID; } void setSubscriptionID(const boost::optional< std::string >& value) { this->subscriptionID = value ; } - private: std::string node; std::vector< std::shared_ptr<PubSubItem> > items; boost::optional< unsigned int > maximumItems; boost::optional< std::string > subscriptionID; }; } diff --git a/Swiften/Elements/PubSubOptions.h b/Swiften/Elements/PubSubOptions.h index 2b312a7..80a3b03 100644 --- a/Swiften/Elements/PubSubOptions.h +++ b/Swiften/Elements/PubSubOptions.h @@ -1,24 +1,23 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Form.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubPayload.h> #include <Swiften/JID/JID.h> namespace Swift { class SWIFTEN_API PubSubOptions : public PubSubPayload { public: diff --git a/Swiften/Elements/PubSubOwnerAffiliation.h b/Swiften/Elements/PubSubOwnerAffiliation.h index a8c1d91..77886d1 100644 --- a/Swiften/Elements/PubSubOwnerAffiliation.h +++ b/Swiften/Elements/PubSubOwnerAffiliation.h @@ -1,19 +1,18 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/JID/JID.h> namespace Swift { class SWIFTEN_API PubSubOwnerAffiliation : public Payload { public: enum Type { None, Member, diff --git a/Swiften/Elements/PubSubOwnerAffiliations.h b/Swiften/Elements/PubSubOwnerAffiliations.h index f1085bb..2434d4e 100644 --- a/Swiften/Elements/PubSubOwnerAffiliations.h +++ b/Swiften/Elements/PubSubOwnerAffiliations.h @@ -1,23 +1,22 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubOwnerAffiliation.h> #include <Swiften/Elements/PubSubOwnerPayload.h> namespace Swift { class SWIFTEN_API PubSubOwnerAffiliations : public PubSubOwnerPayload { public: PubSubOwnerAffiliations(); diff --git a/Swiften/Elements/PubSubOwnerConfigure.h b/Swiften/Elements/PubSubOwnerConfigure.h index 7dcf792..2b84753 100644 --- a/Swiften/Elements/PubSubOwnerConfigure.h +++ b/Swiften/Elements/PubSubOwnerConfigure.h @@ -1,24 +1,23 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Form.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubOwnerPayload.h> namespace Swift { class SWIFTEN_API PubSubOwnerConfigure : public PubSubOwnerPayload { public: PubSubOwnerConfigure(); diff --git a/Swiften/Elements/PubSubOwnerDefault.h b/Swiften/Elements/PubSubOwnerDefault.h index 322f47a..a17d9f3 100644 --- a/Swiften/Elements/PubSubOwnerDefault.h +++ b/Swiften/Elements/PubSubOwnerDefault.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Form.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubOwnerPayload.h> namespace Swift { class SWIFTEN_API PubSubOwnerDefault : public PubSubOwnerPayload { public: PubSubOwnerDefault(); diff --git a/Swiften/Elements/PubSubOwnerDelete.h b/Swiften/Elements/PubSubOwnerDelete.h index 7cc5d79..a222e85 100644 --- a/Swiften/Elements/PubSubOwnerDelete.h +++ b/Swiften/Elements/PubSubOwnerDelete.h @@ -1,22 +1,21 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubOwnerPayload.h> #include <Swiften/Elements/PubSubOwnerRedirect.h> namespace Swift { class SWIFTEN_API PubSubOwnerDelete : public PubSubOwnerPayload { public: PubSubOwnerDelete(); diff --git a/Swiften/Elements/PubSubOwnerPubSub.h b/Swiften/Elements/PubSubOwnerPubSub.h index f3474cf..9989cde 100644 --- a/Swiften/Elements/PubSubOwnerPubSub.h +++ b/Swiften/Elements/PubSubOwnerPubSub.h @@ -1,19 +1,18 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/ContainerPayload.h> #include <Swiften/Elements/PubSubOwnerPayload.h> namespace Swift { class SWIFTEN_API PubSubOwnerPubSub : public ContainerPayload<PubSubOwnerPayload> { public: PubSubOwnerPubSub(); virtual ~PubSubOwnerPubSub(); }; diff --git a/Swiften/Elements/PubSubOwnerPurge.h b/Swiften/Elements/PubSubOwnerPurge.h index aca48e1..3631bd9 100644 --- a/Swiften/Elements/PubSubOwnerPurge.h +++ b/Swiften/Elements/PubSubOwnerPurge.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubOwnerPayload.h> namespace Swift { class SWIFTEN_API PubSubOwnerPurge : public PubSubOwnerPayload { public: PubSubOwnerPurge(); diff --git a/Swiften/Elements/PubSubOwnerRedirect.h b/Swiften/Elements/PubSubOwnerRedirect.h index c481f98..f7deca8 100644 --- a/Swiften/Elements/PubSubOwnerRedirect.h +++ b/Swiften/Elements/PubSubOwnerRedirect.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API PubSubOwnerRedirect : public Payload { public: PubSubOwnerRedirect(); virtual ~PubSubOwnerRedirect(); diff --git a/Swiften/Elements/PubSubOwnerSubscription.h b/Swiften/Elements/PubSubOwnerSubscription.h index 6a3fcc1..cf2edd9 100644 --- a/Swiften/Elements/PubSubOwnerSubscription.h +++ b/Swiften/Elements/PubSubOwnerSubscription.h @@ -1,19 +1,18 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/JID/JID.h> namespace Swift { class SWIFTEN_API PubSubOwnerSubscription : public Payload { public: enum SubscriptionType { None, Pending, diff --git a/Swiften/Elements/PubSubOwnerSubscriptions.h b/Swiften/Elements/PubSubOwnerSubscriptions.h index ec5aa17..d7cd8df 100644 --- a/Swiften/Elements/PubSubOwnerSubscriptions.h +++ b/Swiften/Elements/PubSubOwnerSubscriptions.h @@ -1,23 +1,22 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubOwnerPayload.h> #include <Swiften/Elements/PubSubOwnerSubscription.h> namespace Swift { class SWIFTEN_API PubSubOwnerSubscriptions : public PubSubOwnerPayload { public: PubSubOwnerSubscriptions(); diff --git a/Swiften/Elements/PubSubPublish.h b/Swiften/Elements/PubSubPublish.h index dff099b..2d6d5bb 100644 --- a/Swiften/Elements/PubSubPublish.h +++ b/Swiften/Elements/PubSubPublish.h @@ -1,23 +1,22 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubItem.h> #include <Swiften/Elements/PubSubPayload.h> namespace Swift { class SWIFTEN_API PubSubPublish : public PubSubPayload { public: PubSubPublish(); diff --git a/Swiften/Elements/PubSubSubscribe.h b/Swiften/Elements/PubSubSubscribe.h index a4c0b68..aaaca38 100644 --- a/Swiften/Elements/PubSubSubscribe.h +++ b/Swiften/Elements/PubSubSubscribe.h @@ -1,24 +1,23 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubOptions.h> #include <Swiften/Elements/PubSubPayload.h> #include <Swiften/JID/JID.h> namespace Swift { class SWIFTEN_API PubSubSubscribe : public PubSubPayload { public: diff --git a/Swiften/Elements/PubSubSubscribeOptions.h b/Swiften/Elements/PubSubSubscribeOptions.h index c837787..1521427 100644 --- a/Swiften/Elements/PubSubSubscribeOptions.h +++ b/Swiften/Elements/PubSubSubscribeOptions.h @@ -1,19 +1,18 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API PubSubSubscribeOptions : public Payload { public: PubSubSubscribeOptions(); virtual ~PubSubSubscribeOptions(); diff --git a/Swiften/Elements/PubSubSubscription.h b/Swiften/Elements/PubSubSubscription.h index e2b527f..9645ebb 100644 --- a/Swiften/Elements/PubSubSubscription.h +++ b/Swiften/Elements/PubSubSubscription.h @@ -1,24 +1,23 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubPayload.h> #include <Swiften/Elements/PubSubSubscribeOptions.h> #include <Swiften/JID/JID.h> namespace Swift { class SWIFTEN_API PubSubSubscription : public PubSubPayload { public: enum SubscriptionType { diff --git a/Swiften/Elements/PubSubSubscriptions.h b/Swiften/Elements/PubSubSubscriptions.h index 441e6c1..f721bd5 100644 --- a/Swiften/Elements/PubSubSubscriptions.h +++ b/Swiften/Elements/PubSubSubscriptions.h @@ -1,25 +1,24 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubPayload.h> #include <Swiften/Elements/PubSubSubscription.h> namespace Swift { class SWIFTEN_API PubSubSubscriptions : public PubSubPayload { public: PubSubSubscriptions(); diff --git a/Swiften/Elements/PubSubUnsubscribe.h b/Swiften/Elements/PubSubUnsubscribe.h index 305af9a..c0c25bd 100644 --- a/Swiften/Elements/PubSubUnsubscribe.h +++ b/Swiften/Elements/PubSubUnsubscribe.h @@ -1,23 +1,22 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> #include <Swiften/Elements/PubSubPayload.h> #include <Swiften/JID/JID.h> namespace Swift { class SWIFTEN_API PubSubUnsubscribe : public PubSubPayload { public: PubSubUnsubscribe(); diff --git a/Swiften/Elements/ReferencePayload.cpp b/Swiften/Elements/ReferencePayload.cpp new file mode 100644 index 0000000..288f28f --- /dev/null +++ b/Swiften/Elements/ReferencePayload.cpp @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#include <Swiften/Elements/ReferencePayload.h> + +namespace Swift { + +ReferencePayload::ReferencePayload() + : type_(Type::Data) { +} + +const ReferencePayload::Type& ReferencePayload::getType() const { + return type_; +} + +void ReferencePayload::setType(const ReferencePayload::Type& type) { + type_ = type; +} + +const boost::optional<std::string>& ReferencePayload::getUri() const { + return uri_; +} + +void ReferencePayload::setUri(const boost::optional<std::string>& uri) { + uri_ = uri; +} + +const boost::optional<std::string>& ReferencePayload::getBegin() const { + return begin_; +} + +void ReferencePayload::setBegin(const boost::optional<std::string>& begin) { + begin_ = begin; +} + +const boost::optional<std::string>& ReferencePayload::getEnd() const { + return end_; +} + +void ReferencePayload::setEnd(const boost::optional<std::string>& end) { + end_ = end; +} + +const boost::optional<std::string>& ReferencePayload::getAnchor() const { + return anchor_; +} + +void ReferencePayload::setAnchor(const boost::optional<std::string>& anchor) { + anchor_ = anchor; +} + +const std::vector<std::shared_ptr<Payload>>& ReferencePayload::getPayloads() const { + return payloads_; +} + +void ReferencePayload::addPayload(const std::shared_ptr<Payload>& payload) { + payloads_.push_back(payload); +} + +} diff --git a/Swiften/Elements/ReferencePayload.h b/Swiften/Elements/ReferencePayload.h new file mode 100644 index 0000000..b9a394e --- /dev/null +++ b/Swiften/Elements/ReferencePayload.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <string> +#include <vector> + +#include <boost/optional.hpp> + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/Payload.h> + +namespace Swift { + /** + * reference from XEP-0372 + */ + class SWIFTEN_API ReferencePayload : public Payload { + + public: + + typedef std::shared_ptr<ReferencePayload> ref; + + enum class Type { + Data, + Mention, + PubSub, + Unknown + }; + + ReferencePayload(); + + const Type& getType() const; + const boost::optional<std::string>& getUri() const; + const boost::optional<std::string>& getBegin() const; + const boost::optional<std::string>& getEnd() const; + const boost::optional<std::string>& getAnchor() const; + + const std::vector<std::shared_ptr<Payload>>& getPayloads() const; + + void setType(const Type& type); + void setUri(const boost::optional<std::string>& uri); + void setBegin(const boost::optional<std::string>& begin); + void setEnd(const boost::optional<std::string>& end); + void setAnchor(const boost::optional<std::string>& anchor); + + void addPayload(const std::shared_ptr<Payload>& payload); + + private: + + Type type_; + boost::optional<std::string> uri_; + boost::optional<std::string> begin_; + boost::optional<std::string> end_; + boost::optional<std::string> anchor_; + + std::vector<std::shared_ptr<Payload>> payloads_; + }; +} diff --git a/Swiften/Elements/S5BProxyRequest.h b/Swiften/Elements/S5BProxyRequest.h index e3f5206..2fecae4 100644 --- a/Swiften/Elements/S5BProxyRequest.h +++ b/Swiften/Elements/S5BProxyRequest.h @@ -1,17 +1,17 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <boost/optional.hpp> @@ -24,19 +24,19 @@ namespace Swift { class SWIFTEN_API S5BProxyRequest : public Payload { public: typedef std::shared_ptr<S5BProxyRequest> ref; public: struct StreamHost { std::string host; - int port; + unsigned short port; JID jid; }; public: const boost::optional<StreamHost>& getStreamHost() const { return streamHost; } void setStreamHost(const StreamHost& streamHost) { diff --git a/Swiften/Elements/SecurityLabel.h b/Swiften/Elements/SecurityLabel.h index 748c65e..fcaa610 100644 --- a/Swiften/Elements/SecurityLabel.h +++ b/Swiften/Elements/SecurityLabel.h @@ -1,27 +1,27 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <vector> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API SecurityLabel : public Payload { public: + using ref = std::shared_ptr<SecurityLabel>; SecurityLabel(); virtual ~SecurityLabel(); const std::vector< std::string >& getEquivalentLabels() const { return equivalentLabels; } diff --git a/Swiften/Elements/StanzaAck.cpp b/Swiften/Elements/StanzaAck.cpp index bd0b78d..dda97f5 100644 --- a/Swiften/Elements/StanzaAck.cpp +++ b/Swiften/Elements/StanzaAck.cpp @@ -1,19 +1,17 @@ /* - * Copyright (c) 2013 Isode Limited. + * Copyright (c) 2013-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Elements/StanzaAck.h> -#include <boost/numeric/conversion/cast.hpp> - using namespace Swift; StanzaAck::~StanzaAck() { } -void StanzaAck::setHandledStanzasCount(int i) { - handledStanzasCount = boost::numeric_cast<unsigned int>(i); +void StanzaAck::setHandledStanzasCount(unsigned int i) { + handledStanzasCount = i; valid = true; } diff --git a/Swiften/Elements/StanzaAck.h b/Swiften/Elements/StanzaAck.h index 68f0a2f..f664aca 100644 --- a/Swiften/Elements/StanzaAck.h +++ b/Swiften/Elements/StanzaAck.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> @@ -18,19 +18,19 @@ namespace Swift { StanzaAck() : valid(false), handledStanzasCount(0) {} StanzaAck(unsigned int handledStanzasCount) : valid(true), handledStanzasCount(handledStanzasCount) {} virtual ~StanzaAck(); unsigned int getHandledStanzasCount() const { return handledStanzasCount; } - void setHandledStanzasCount(int i); + void setHandledStanzasCount(unsigned int i); bool isValid() const { return valid; } private: bool valid; unsigned int handledStanzasCount; }; diff --git a/Swiften/Elements/UserLocation.h b/Swiften/Elements/UserLocation.h index 3bdaec6..b59fc5c 100644 --- a/Swiften/Elements/UserLocation.h +++ b/Swiften/Elements/UserLocation.h @@ -1,24 +1,23 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API UserLocation : public Payload { public: UserLocation(); virtual ~UserLocation(); diff --git a/Swiften/Elements/UserTune.h b/Swiften/Elements/UserTune.h index 7def9b9..5413085 100644 --- a/Swiften/Elements/UserTune.h +++ b/Swiften/Elements/UserTune.h @@ -1,23 +1,22 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Payload.h> namespace Swift { class SWIFTEN_API UserTune : public Payload { public: UserTune(); virtual ~UserTune(); diff --git a/Swiften/EventLoop/EventLoop.cpp b/Swiften/EventLoop/EventLoop.cpp index 186616f..f6af699 100644 --- a/Swiften/EventLoop/EventLoop.cpp +++ b/Swiften/EventLoop/EventLoop.cpp @@ -1,30 +1,25 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/EventLoop/EventLoop.h> #include <algorithm> #include <cassert> #include <vector> -#include <boost/bind.hpp> -#include <boost/lambda/bind.hpp> -#include <boost/lambda/lambda.hpp> #include <boost/optional.hpp> #include <Swiften/Base/Log.h> -namespace lambda = boost::lambda; - namespace Swift { inline void invokeCallback(const Event& event) { try { assert(!event.callback.empty()); event.callback(); } catch (const std::exception& e) { SWIFT_LOG(error) << "Uncaught exception in event loop: " << e.what() << std::endl; @@ -90,13 +85,15 @@ void EventLoop::postEvent(boost::function<void ()> callback, std::shared_ptr<Eve } } void EventLoop::removeEventsFromOwner(std::shared_ptr<EventOwner> owner) { std::unique_lock<std::recursive_mutex> removeLock(removeEventsMutex_, std::defer_lock); std::unique_lock<std::recursive_mutex> eventsLock(eventsMutex_, std::defer_lock); std::lock(removeLock, eventsLock); - events_.remove_if(lambda::bind(&Event::owner, lambda::_1) == owner); + events_.remove_if([&](const Event& event) { + return event.owner == owner; + }); } } diff --git a/Swiften/FileTransfer/ByteArrayReadBytestream.cpp b/Swiften/FileTransfer/ByteArrayReadBytestream.cpp index cd9fa4a..3fdff27 100644 --- a/Swiften/FileTransfer/ByteArrayReadBytestream.cpp +++ b/Swiften/FileTransfer/ByteArrayReadBytestream.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/FileTransfer/ByteArrayReadBytestream.h> #include <memory> #include <boost/numeric/conversion/cast.hpp> @@ -13,22 +13,28 @@ #include <Swiften/Base/Algorithm.h> using namespace Swift; std::shared_ptr<ByteArray> ByteArrayReadBytestream::read(size_t size) { size_t readSize = size; if (position + readSize > data.size()) { readSize = data.size() - position; } - std::shared_ptr<ByteArray> result = std::make_shared<ByteArray>( - data.begin() + boost::numeric_cast<long long>(position), - data.begin() + boost::numeric_cast<long long>(position) + boost::numeric_cast<long long>(readSize)); - - onRead(*result); - position += readSize; - return result; + try { + std::shared_ptr<ByteArray> result = std::make_shared<ByteArray>( + data.begin() + boost::numeric_cast<long long>(position), + data.begin() + boost::numeric_cast<long long>(position) + boost::numeric_cast<long long>(readSize)); + onRead(*result); + position += readSize; + return result; + } + catch (const boost::numeric::bad_numeric_cast&) { + // If we cannot cast to long long, we probably ran out of memory long ago + assert(false); + return {}; + } } void ByteArrayReadBytestream::addData(const std::vector<unsigned char>& moreData) { append(data, moreData); onDataAvailable(); } diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporter.h b/Swiften/FileTransfer/DefaultFileTransferTransporter.h index 339232f..1bfe799 100644 --- a/Swiften/FileTransfer/DefaultFileTransferTransporter.h +++ b/Swiften/FileTransfer/DefaultFileTransferTransporter.h @@ -1,19 +1,18 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/ErrorPayload.h> #include <Swiften/FileTransfer/FileTransferTransporter.h> namespace Swift { class LocalJingleTransportCandidateGenerator; class RemoteJingleTransportCandidateSelector; class SOCKS5BytestreamRegistry; class SOCKS5BytestreamServerManager; class SOCKS5BytestreamProxiesManager; @@ -42,47 +41,47 @@ namespace Swift { SOCKS5BytestreamRegistry*, SOCKS5BytestreamServerManager* s5bServerManager, SOCKS5BytestreamProxiesManager* s5bProxy, IDGenerator* idGenerator, ConnectionFactory*, TimerFactory*, CryptoProvider*, IQRouter*, const FileTransferOptions&); - virtual ~DefaultFileTransferTransporter(); + virtual ~DefaultFileTransferTransporter() override; virtual void initialize(); virtual void initialize(const std::string& s5bSessionID); - virtual void startGeneratingLocalCandidates() SWIFTEN_OVERRIDE; - virtual void stopGeneratingLocalCandidates() SWIFTEN_OVERRIDE; + virtual void startGeneratingLocalCandidates() override; + virtual void stopGeneratingLocalCandidates() override; virtual void addRemoteCandidates( - const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) SWIFTEN_OVERRIDE; - virtual void startTryingRemoteCandidates() SWIFTEN_OVERRIDE; - virtual void stopTryingRemoteCandidates() SWIFTEN_OVERRIDE; + const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string&) override; + virtual void startTryingRemoteCandidates() override; + virtual void stopTryingRemoteCandidates() override; - virtual void startActivatingProxy(const JID& jid) SWIFTEN_OVERRIDE; - virtual void stopActivatingProxy() SWIFTEN_OVERRIDE; + virtual void startActivatingProxy(const JID& jid) override; + virtual void stopActivatingProxy() override; virtual std::shared_ptr<TransportSession> createIBBSendSession( - const std::string& sessionID, unsigned int blockSize, std::shared_ptr<ReadBytestream>) SWIFTEN_OVERRIDE; + const std::string& sessionID, unsigned int blockSize, std::shared_ptr<ReadBytestream>) override; virtual std::shared_ptr<TransportSession> createIBBReceiveSession( - const std::string& sessionID, unsigned long long size, std::shared_ptr<WriteBytestream>) SWIFTEN_OVERRIDE; + const std::string& sessionID, unsigned long long size, std::shared_ptr<WriteBytestream>) override; virtual std::shared_ptr<TransportSession> createRemoteCandidateSession( - std::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; + std::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) override; virtual std::shared_ptr<TransportSession> createRemoteCandidateSession( - std::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; + std::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) override; virtual std::shared_ptr<TransportSession> createLocalCandidateSession( - std::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; + std::shared_ptr<ReadBytestream>, const JingleS5BTransportPayload::Candidate& candidate) override; virtual std::shared_ptr<TransportSession> createLocalCandidateSession( - std::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) SWIFTEN_OVERRIDE; + std::shared_ptr<WriteBytestream>, const JingleS5BTransportPayload::Candidate& candidate) override; private: void handleLocalCandidatesGenerated(const std::vector<JingleS5BTransportPayload::Candidate>&); void handleRemoteCandidateSelectFinished( const boost::optional<JingleS5BTransportPayload::Candidate>&, std::shared_ptr<SOCKS5BytestreamClientSession>); void handleActivateProxySessionResult(const std::string& sessionID, ErrorPayload::ref error); void closeLocalSession(); void closeRemoteSession(); diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h index 3cc3455..fe4f6ea 100644 --- a/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h +++ b/Swiften/FileTransfer/DefaultFileTransferTransporterFactory.h @@ -1,19 +1,18 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/FileTransfer/FileTransferTransporterFactory.h> namespace Swift { class SOCKS5BytestreamRegistry; class SOCKS5BytestreamServerManager; class SOCKS5BytestreamProxiesManager; class IDGenerator; class ConnectionFactory; class TimerFactory; @@ -25,24 +24,24 @@ namespace Swift { DefaultFileTransferTransporterFactory( SOCKS5BytestreamRegistry*, SOCKS5BytestreamServerManager* s5bServerManager, SOCKS5BytestreamProxiesManager* s5bProxy, IDGenerator* idGenerator, ConnectionFactory*, TimerFactory*, CryptoProvider*, IQRouter*); - virtual ~DefaultFileTransferTransporterFactory(); + virtual ~DefaultFileTransferTransporterFactory() override; virtual FileTransferTransporter* createInitiatorTransporter( - const JID& initiator, const JID& responder, const FileTransferOptions&) SWIFTEN_OVERRIDE; + const JID& initiator, const JID& responder, const FileTransferOptions&) override; virtual FileTransferTransporter* createResponderTransporter( - const JID& initiator, const JID& responder, const std::string& s5bSessionID, const FileTransferOptions&) SWIFTEN_OVERRIDE; + const JID& initiator, const JID& responder, const std::string& s5bSessionID, const FileTransferOptions&) override; private: SOCKS5BytestreamRegistry* s5bRegistry; SOCKS5BytestreamServerManager* s5bServerManager; SOCKS5BytestreamProxiesManager* s5bProxiesManager; IDGenerator* idGenerator; ConnectionFactory* connectionFactory; TimerFactory* timerFactory; CryptoProvider* cryptoProvider; diff --git a/Swiften/FileTransfer/FailingTransportSession.h b/Swiften/FileTransfer/FailingTransportSession.h index 6e0e16e..489786b 100644 --- a/Swiften/FileTransfer/FailingTransportSession.h +++ b/Swiften/FileTransfer/FailingTransportSession.h @@ -1,22 +1,22 @@ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> #include <Swiften/FileTransfer/TransportSession.h> namespace Swift { class SWIFTEN_API FailingTransportSession : public TransportSession { public: - virtual ~FailingTransportSession(); + virtual ~FailingTransportSession() override; - virtual void start() SWIFTEN_OVERRIDE; - virtual void stop() SWIFTEN_OVERRIDE; + virtual void start() override; + virtual void stop() override; }; } diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.h b/Swiften/FileTransfer/FileTransferManagerImpl.h index 026c8b7..d3d55f0 100644 --- a/Swiften/FileTransfer/FileTransferManagerImpl.h +++ b/Swiften/FileTransfer/FileTransferManagerImpl.h @@ -1,34 +1,33 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <vector> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/filesystem/path.hpp> #include <boost/optional.hpp> #include <boost/signals2.hpp> #include <Swiften/Base/API.h> #include <Swiften/Base/IDGenerator.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/S5BProxyRequest.h> #include <Swiften/FileTransfer/FileTransferManager.h> #include <Swiften/FileTransfer/FileTransferOptions.h> #include <Swiften/FileTransfer/IncomingFileTransfer.h> #include <Swiften/FileTransfer/OutgoingFileTransfer.h> namespace Swift { class ConnectionFactory; class ConnectionServerFactory; @@ -59,34 +58,34 @@ namespace Swift { EntityCapsProvider* capsProvider, PresenceOracle* presOracle, ConnectionFactory* connectionFactory, ConnectionServerFactory* connectionServerFactory, TimerFactory* timerFactory, DomainNameResolver* domainNameResolver, NetworkEnvironment* networkEnvironment, NATTraverser* natTraverser, CryptoProvider* crypto); - virtual ~FileTransferManagerImpl(); + virtual ~FileTransferManagerImpl() override; OutgoingFileTransfer::ref createOutgoingFileTransfer( const JID& to, const boost::filesystem::path& filepath, const std::string& description, std::shared_ptr<ReadBytestream> bytestream, - const FileTransferOptions&) SWIFTEN_OVERRIDE; + const FileTransferOptions&) override; 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, std::shared_ptr<ReadBytestream> bytestream, - const FileTransferOptions&) SWIFTEN_OVERRIDE; + const FileTransferOptions&) override; void start(); void stop(); private: boost::optional<JID> highestPriorityJIDSupportingFileTransfer(const JID& bareJID); private: OutgoingFileTransferManager* outgoingFTManager; diff --git a/Swiften/FileTransfer/FileTransferOptions.h b/Swiften/FileTransfer/FileTransferOptions.h index 2bc4ee1..aa9aa97 100644 --- a/Swiften/FileTransfer/FileTransferOptions.h +++ b/Swiften/FileTransfer/FileTransferOptions.h @@ -1,19 +1,18 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> namespace Swift { class SWIFTEN_API FileTransferOptions { public: FileTransferOptions() : allowInBand_(true), allowAssisted_(true), allowProxied_(true), allowDirect_(true) { } SWIFTEN_DEFAULT_COPY_CONSTRUCTOR(FileTransferOptions) ~FileTransferOptions(); diff --git a/Swiften/FileTransfer/IBBReceiveTransportSession.h b/Swiften/FileTransfer/IBBReceiveTransportSession.h index 8b304c3..5b1fd8d 100644 --- a/Swiften/FileTransfer/IBBReceiveTransportSession.h +++ b/Swiften/FileTransfer/IBBReceiveTransportSession.h @@ -1,31 +1,31 @@ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/signals2.hpp> #include <Swiften/Base/API.h> #include <Swiften/FileTransfer/IBBReceiveSession.h> #include <Swiften/FileTransfer/TransportSession.h> namespace Swift { class SWIFTEN_API IBBReceiveTransportSession : public TransportSession { public: IBBReceiveTransportSession(std::shared_ptr<IBBReceiveSession> session); - virtual ~IBBReceiveTransportSession(); + virtual ~IBBReceiveTransportSession() override; - virtual void start() SWIFTEN_OVERRIDE; - virtual void stop() SWIFTEN_OVERRIDE; + virtual void start() override; + virtual void stop() override; private: std::shared_ptr<IBBReceiveSession> session; boost::signals2::scoped_connection finishedConnection; boost::signals2::scoped_connection bytesSentConnection; }; } diff --git a/Swiften/FileTransfer/IBBSendSession.cpp b/Swiften/FileTransfer/IBBSendSession.cpp index e51c91c..258412b 100644 --- a/Swiften/FileTransfer/IBBSendSession.cpp +++ b/Swiften/FileTransfer/IBBSendSession.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/FileTransfer/IBBSendSession.h> #include <boost/bind.hpp> #include <boost/numeric/conversion/cast.hpp> @@ -34,19 +34,19 @@ IBBSendSession::IBBSendSession( bytestream->onDataAvailable.connect(boost::bind(&IBBSendSession::handleDataAvailable, this)); } IBBSendSession::~IBBSendSession() { bytestream->onDataAvailable.disconnect(boost::bind(&IBBSendSession::handleDataAvailable, this)); } void IBBSendSession::start() { IBBRequest::ref request = IBBRequest::create( - from, to, IBB::createIBBOpen(id, boost::numeric_cast<int>(blockSize)), router); + from, to, IBB::createIBBOpen(id, blockSize), router); request->onResponse.connect(boost::bind(&IBBSendSession::handleIBBResponse, this, _1, _2)); active = true; request->send(); currentRequest = request; } void IBBSendSession::stop() { if (active && router->isAvailable()) { IBBRequest::create(from, to, IBB::createIBBClose(id), router)->send(); diff --git a/Swiften/FileTransfer/IBBSendTransportSession.h b/Swiften/FileTransfer/IBBSendTransportSession.h index d1e786b..7deaaac 100644 --- a/Swiften/FileTransfer/IBBSendTransportSession.h +++ b/Swiften/FileTransfer/IBBSendTransportSession.h @@ -1,31 +1,31 @@ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/signals2.hpp> #include <Swiften/Base/API.h> #include <Swiften/FileTransfer/IBBSendSession.h> #include <Swiften/FileTransfer/TransportSession.h> namespace Swift { class SWIFTEN_API IBBSendTransportSession : public TransportSession { public: IBBSendTransportSession(std::shared_ptr<IBBSendSession> session); - virtual ~IBBSendTransportSession(); + virtual ~IBBSendTransportSession() override; - virtual void start() SWIFTEN_OVERRIDE; - virtual void stop() SWIFTEN_OVERRIDE; + virtual void start() override; + virtual void stop() override; private: std::shared_ptr<IBBSendSession> session; boost::signals2::scoped_connection finishedConnection; boost::signals2::scoped_connection bytesSentConnection; }; } diff --git a/Swiften/FileTransfer/IncomingJingleFileTransfer.h b/Swiften/FileTransfer/IncomingJingleFileTransfer.h index 7ddf700..f42004d 100644 --- a/Swiften/FileTransfer/IncomingJingleFileTransfer.h +++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.h @@ -7,19 +7,18 @@ #pragma once #include <memory> #include <string> #include <boost/cstdint.hpp> #include <Swiften/Base/API.h> #include <Swiften/Base/ByteArray.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/JingleS5BTransportPayload.h> #include <Swiften/FileTransfer/FileTransferOptions.h> #include <Swiften/FileTransfer/IncomingFileTransfer.h> #include <Swiften/FileTransfer/JingleFileTransfer.h> #include <Swiften/Jingle/JingleContentID.h> namespace Swift { class CryptoProvider; class FileTransferTransporterFactory; @@ -43,75 +42,75 @@ namespace Swift { typedef std::shared_ptr<IncomingJingleFileTransfer> ref; IncomingJingleFileTransfer( const JID& recipient, std::shared_ptr<JingleSession>, std::shared_ptr<JingleContentPayload> content, FileTransferTransporterFactory*, TimerFactory*, CryptoProvider*); - virtual ~IncomingJingleFileTransfer(); + virtual ~IncomingJingleFileTransfer() override; - virtual void accept(std::shared_ptr<WriteBytestream>, const FileTransferOptions& = FileTransferOptions()) SWIFTEN_OVERRIDE; - virtual void cancel() SWIFTEN_OVERRIDE; + virtual void accept(std::shared_ptr<WriteBytestream>, const FileTransferOptions& = FileTransferOptions()) override; + virtual void cancel() override; private: enum State { Initial, GeneratingInitialLocalCandidates, TryingCandidates, WaitingForPeerProxyActivate, WaitingForLocalProxyActivate, WaitingForFallbackOrTerminate, Transferring, WaitingForHash, Finished }; virtual void handleSessionTerminateReceived( - boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE; - virtual void handleSessionInfoReceived(std::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE; + boost::optional<JinglePayload::Reason> reason) override; + virtual void handleSessionInfoReceived(std::shared_ptr<JinglePayload>) override; virtual void handleTransportReplaceReceived( - const JingleContentID&, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; + const JingleContentID&, std::shared_ptr<JingleTransportPayload>) override; virtual void handleLocalTransportCandidatesGenerated( const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>&, - const std::string& dstAddr) SWIFTEN_OVERRIDE; + const std::string& dstAddr) override; void handleWriteStreamDataReceived(const std::vector<unsigned char>& data); void stopActiveTransport(); void checkCandidateSelected(); - virtual JingleContentID getContentID() const SWIFTEN_OVERRIDE; + virtual JingleContentID getContentID() const override; void checkIfAllDataReceived(); bool verifyData(); void handleWaitOnHashTimerTicked(); void handleTransferFinished(boost::optional<FileTransferError>); private: - virtual void startTransferViaRemoteCandidate() SWIFTEN_OVERRIDE; - virtual void startTransferViaLocalCandidate() SWIFTEN_OVERRIDE; + virtual void startTransferViaRemoteCandidate() override; + virtual void startTransferViaLocalCandidate() override; void checkHashAndTerminate(); void stopAll(); void setState(State state); void setFinishedState(FileTransfer::State::Type, const boost::optional<FileTransferError>& error); - const JID& getSender() const SWIFTEN_OVERRIDE; - const JID& getRecipient() const SWIFTEN_OVERRIDE; + const JID& getSender() const override; + const JID& getRecipient() const override; static FileTransfer::State::Type getExternalState(State state); - virtual bool hasPriorityOnCandidateTie() const SWIFTEN_OVERRIDE; - virtual void fallback() SWIFTEN_OVERRIDE; - virtual void startTransferring(std::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE; - virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE; - virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE; - virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE; - virtual std::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE; - virtual std::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE; - virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE; + virtual bool hasPriorityOnCandidateTie() const override; + virtual void fallback() override; + virtual void startTransferring(std::shared_ptr<TransportSession>) override; + virtual bool isWaitingForPeerProxyActivate() const override; + virtual bool isWaitingForLocalProxyActivate() const override; + virtual bool isTryingCandidates() const override; + virtual std::shared_ptr<TransportSession> createLocalCandidateSession() override; + virtual std::shared_ptr<TransportSession> createRemoteCandidateSession() override; + virtual void terminate(JinglePayload::Reason::Type reason) override; private: std::shared_ptr<JingleContentPayload> initialContent; CryptoProvider* crypto; State state; std::shared_ptr<JingleFileTransferDescription> description; std::shared_ptr<WriteBytestream> stream; boost::uintmax_t receivedBytes; diff --git a/Swiften/FileTransfer/JingleFileTransfer.cpp b/Swiften/FileTransfer/JingleFileTransfer.cpp index 62c3a53..cc1cd1c 100644 --- a/Swiften/FileTransfer/JingleFileTransfer.cpp +++ b/Swiften/FileTransfer/JingleFileTransfer.cpp @@ -1,19 +1,17 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/FileTransfer/JingleFileTransfer.h> -#include <boost/typeof/typeof.hpp> - #include <Swiften/Base/Log.h> #include <Swiften/Crypto/CryptoProvider.h> #include <Swiften/FileTransfer/FileTransferTransporter.h> #include <Swiften/JID/JID.h> #include <Swiften/Jingle/JingleSession.h> #include <Swiften/StringCodecs/Hexify.h> using namespace Swift; @@ -23,19 +21,18 @@ JingleFileTransfer::JingleFileTransfer( FileTransferTransporterFactory* transporterFactory) : session(session), target(target), transporterFactory(transporterFactory), transporter(nullptr), ourCandidateSelectFinished(false), theirCandidateSelectFinished(false) { session->addListener(this); - } JingleFileTransfer::~JingleFileTransfer() { session->removeListener(this); } void JingleFileTransfer::fillCandidateMap(CandidateMap& map, const std::vector<JingleS5BTransportPayload::Candidate>& candidates) { map.clear(); for (auto&& candidate : candidates) { @@ -170,19 +167,19 @@ void JingleFileTransfer::handleTransportInfoReceived( SWIFT_LOG(debug) << std::endl; if (JingleS5BTransportPayload::ref s5bPayload = std::dynamic_pointer_cast<JingleS5BTransportPayload>(transport)) { if (s5bPayload->hasCandidateError() || !s5bPayload->getCandidateUsed().empty()) { SWIFT_LOG(debug) << "Received candidate decision from peer" << std::endl; if (!isTryingCandidates()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; } theirCandidateSelectFinished = true; if (!s5bPayload->hasCandidateError()) { - BOOST_AUTO(theirCandidate, localCandidates.find(s5bPayload->getCandidateUsed())); + auto theirCandidate = localCandidates.find(s5bPayload->getCandidateUsed()); if (theirCandidate == localCandidates.end()) { SWIFT_LOG(warning) << "Got invalid candidate" << std::endl; terminate(JinglePayload::Reason::GeneralError); return; } theirCandidateChoice = theirCandidate->second; } decideOnCandidates(); } @@ -225,10 +222,9 @@ void JingleFileTransfer::setTransporter(FileTransferTransporter* transporter) { void JingleFileTransfer::removeTransporter() { if (transporter) { localTransportCandidatesGeneratedConnection.release(); remoteTransportCandidateSelectFinishedConnection.release(); proxyActivatedConnection.release(); delete transporter; transporter = nullptr; } } - diff --git a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h index 2159063..8c53d16 100644 --- a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h +++ b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h @@ -1,29 +1,28 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.h> #include <boost/signals2.hpp> #include <Swiften/Base/IDGenerator.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/JingleS5BTransportPayload.h> #include <Swiften/FileTransfer/FileTransferOptions.h> #include <Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.h> #include <Swiften/JID/JID.h> namespace Swift { class SOCKS5BytestreamServerManager; class SOCKS5BytestreamProxiesManager; class SOCKS5BytestreamServerInitializeRequest; diff --git a/Swiften/FileTransfer/OutgoingJingleFileTransfer.h b/Swiften/FileTransfer/OutgoingJingleFileTransfer.h index 9fd1d76..6db4e40 100644 --- a/Swiften/FileTransfer/OutgoingJingleFileTransfer.h +++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.h @@ -11,19 +11,18 @@ */ #pragma once #include <memory> #include <boost/optional/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/JingleFileTransferFileInfo.h> #include <Swiften/FileTransfer/FileTransferOptions.h> #include <Swiften/FileTransfer/JingleFileTransfer.h> #include <Swiften/FileTransfer/OutgoingFileTransfer.h> #include <Swiften/Jingle/JingleContentID.h> #include <Swiften/Network/Timer.h> namespace Swift { class CryptoProvider; @@ -40,66 +39,66 @@ namespace Swift { const JID& to, std::shared_ptr<JingleSession>, std::shared_ptr<ReadBytestream>, FileTransferTransporterFactory*, TimerFactory*, IDGenerator*, const JingleFileTransferFileInfo&, const FileTransferOptions&, CryptoProvider*); - virtual ~OutgoingJingleFileTransfer(); + virtual ~OutgoingJingleFileTransfer() override; - virtual void start() SWIFTEN_OVERRIDE; - virtual void cancel() SWIFTEN_OVERRIDE; + virtual void start() override; + virtual void cancel() override; private: enum State { Initial, GeneratingInitialLocalCandidates, WaitingForAccept, TryingCandidates, WaitingForPeerProxyActivate, WaitingForLocalProxyActivate, WaitingForCandidateAcknowledge, FallbackRequested, Transferring, WaitForTermination, Finished }; - virtual void handleSessionAcceptReceived(const JingleContentID&, std::shared_ptr<JingleDescription>, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) SWIFTEN_OVERRIDE; - virtual void handleTransportAcceptReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportRejectReceived(const JingleContentID &, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void startTransferViaRemoteCandidate() SWIFTEN_OVERRIDE; - virtual void startTransferViaLocalCandidate() SWIFTEN_OVERRIDE; + virtual void handleSessionAcceptReceived(const JingleContentID&, std::shared_ptr<JingleDescription>, std::shared_ptr<JingleTransportPayload>) override; + virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) override; + virtual void handleTransportAcceptReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) override; + virtual void handleTransportRejectReceived(const JingleContentID &, std::shared_ptr<JingleTransportPayload>) override; + virtual void startTransferViaRemoteCandidate() override; + virtual void startTransferViaLocalCandidate() override; void startTransferringIfCandidateAcknowledged(); - virtual void handleLocalTransportCandidatesGenerated(const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& dstAddr) SWIFTEN_OVERRIDE; - virtual void handleTransportInfoAcknowledged(const std::string& id) SWIFTEN_OVERRIDE; + virtual void handleLocalTransportCandidatesGenerated(const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>&, const std::string& dstAddr) override; + virtual void handleTransportInfoAcknowledged(const std::string& id) override; - virtual JingleContentID getContentID() const SWIFTEN_OVERRIDE; + virtual JingleContentID getContentID() const override; - virtual void terminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE; + virtual void terminate(JinglePayload::Reason::Type reason) override; - virtual void fallback() SWIFTEN_OVERRIDE; + virtual void fallback() override; void handleTransferFinished(boost::optional<FileTransferError>); void sendSessionInfoHash(); - virtual void startTransferring(std::shared_ptr<TransportSession>) SWIFTEN_OVERRIDE; + virtual void startTransferring(std::shared_ptr<TransportSession>) override; - virtual bool hasPriorityOnCandidateTie() const SWIFTEN_OVERRIDE; - virtual bool isWaitingForPeerProxyActivate() const SWIFTEN_OVERRIDE; - virtual bool isWaitingForLocalProxyActivate() const SWIFTEN_OVERRIDE; - virtual bool isTryingCandidates() const SWIFTEN_OVERRIDE; - virtual std::shared_ptr<TransportSession> createLocalCandidateSession() SWIFTEN_OVERRIDE; - virtual std::shared_ptr<TransportSession> createRemoteCandidateSession() SWIFTEN_OVERRIDE; + virtual bool hasPriorityOnCandidateTie() const override; + virtual bool isWaitingForPeerProxyActivate() const override; + virtual bool isWaitingForLocalProxyActivate() const override; + virtual bool isTryingCandidates() const override; + virtual std::shared_ptr<TransportSession> createLocalCandidateSession() override; + virtual std::shared_ptr<TransportSession> createRemoteCandidateSession() override; void handleWaitForRemoteTerminationTimeout(); void stopAll(); void setInternalState(State state); void setFinishedState(FileTransfer::State::Type, const boost::optional<FileTransferError>& error); static FileTransfer::State::Type getExternalState(State state); diff --git a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h index c4257f6..c205516 100644 --- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h +++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h @@ -1,30 +1,29 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.h> #include <memory> #include <queue> #include <vector> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/JingleS5BTransportPayload.h> #include <Swiften/FileTransfer/FileTransferOptions.h> #include <Swiften/FileTransfer/SOCKS5BytestreamClientSession.h> #include <Swiften/JID/JID.h> #include <Swiften/Network/Connection.h> namespace Swift { class ConnectionFactory; class TimerFactory; diff --git a/Swiften/FileTransfer/S5BTransportSession.h b/Swiften/FileTransfer/S5BTransportSession.h index 3e064fa..fd92f2e 100644 --- a/Swiften/FileTransfer/S5BTransportSession.h +++ b/Swiften/FileTransfer/S5BTransportSession.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/bind.hpp> #include <boost/signals2.hpp> @@ -29,31 +29,31 @@ class SWIFTEN_API S5BTransportSession : public TransportSession { S5BTransportSession( std::shared_ptr<T> session, std::shared_ptr<WriteBytestream> writeStream) : session(session), writeStream(writeStream) { initialize(); } - virtual ~S5BTransportSession() { + virtual ~S5BTransportSession() override { } - virtual void start() SWIFTEN_OVERRIDE { + virtual void start() override { if (readStream) { session->startSending(readStream); } else { session->startReceiving(writeStream); } } - virtual void stop() SWIFTEN_OVERRIDE { + virtual void stop() override { session->stop(); } private: void initialize() { finishedConnection = session->onFinished.connect(boost::bind(boost::ref(onFinished), _1)); bytesSentConnection = session->onBytesSent.connect(boost::bind(boost::ref(onBytesSent), _1)); } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp index f749735..a6b75da 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ @@ -108,19 +108,19 @@ bool SOCKS5BytestreamServerManager::isInitialized() const { return state == Initialized; } void SOCKS5BytestreamServerManager::initialize() { if (state == Start) { state = Initializing; // Find a port to listen on assert(!connectionServer); - int port; + unsigned short port; for (port = LISTEN_PORTS_BEGIN; port < LISTEN_PORTS_END; ++port) { SWIFT_LOG(debug) << "Trying to start server on port " << port << std::endl; connectionServer = connectionServerFactory->createConnectionServer(HostAddress::fromString("::").get(), port); boost::optional<ConnectionServer::Error> error = connectionServer->tryStart(); if (!error) { break; } else if (*error != ConnectionServer::Conflict) { SWIFT_LOG(debug) << "Error starting server" << std::endl; @@ -158,19 +158,19 @@ void SOCKS5BytestreamServerManager::setupPortForwarding() { assert(!getPublicIPRequest); publicAddress = boost::optional<HostAddress>(); if ((getPublicIPRequest = natTraverser->createGetPublicIPRequest())) { getPublicIPRequest->onResult.connect( boost::bind(&SOCKS5BytestreamServerManager::handleGetPublicIPResult, this, _1)); getPublicIPRequest->start(); } // Forward ports - int port = server->getAddressPort().getPort(); + auto port = server->getAddressPort().getPort(); assert(!forwardPortRequest); portMapping = boost::optional<NATPortMapping>(); if ((forwardPortRequest = natTraverser->createForwardPortRequest(port, port))) { forwardPortRequest->onResult.connect( boost::bind(&SOCKS5BytestreamServerManager::handleForwardPortResult, this, _1)); forwardPortRequest->start(); } } diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h index 3c06513..74578cc 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <vector> @@ -72,19 +72,19 @@ namespace Swift { private: friend class SOCKS5BytestreamServerInitializeRequest; SOCKS5BytestreamRegistry* bytestreamRegistry; ConnectionServerFactory* connectionServerFactory; NetworkEnvironment* networkEnvironment; NATTraverser* natTraverser; enum { Start, Initializing, Initialized } state; SOCKS5BytestreamServer* server; std::shared_ptr<ConnectionServer> connectionServer; - int connectionServerPort = -1; + unsigned short connectionServerPort = 0; std::shared_ptr<NATTraversalGetPublicIPRequest> getPublicIPRequest; std::shared_ptr<NATTraversalForwardPortRequest> forwardPortRequest; std::shared_ptr<NATTraversalRemovePortForwardingRequest> unforwardPortRequest; boost::optional<HostAddress> publicAddress; boost::optional<NATPortMapping> portMapping; bool attemptedPortMapping_; std::weak_ptr<SOCKS5BytestreamServerResourceUser> s5bServerResourceUser_; diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp index bc4e8e4..0fd40bf 100644 --- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp +++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/FileTransfer/SOCKS5BytestreamServerSession.h> #include <boost/bind.hpp> #include <boost/numeric/conversion/cast.hpp> @@ -132,19 +132,26 @@ void SOCKS5BytestreamServerSession::process() { if (i != unprocessedData.size()) { SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl; } unprocessedData.clear(); streamID = byteArrayToString(requestID); bool hasBytestream = bytestreams->hasBytestream(streamID); SafeByteArray result = createSafeByteArray("\x05", 1); result.push_back(hasBytestream ? 0x0 : 0x4); append(result, createByteArray("\x00\x03", 2)); - result.push_back(boost::numeric_cast<unsigned char>(requestID.size())); + try { + result.push_back(boost::numeric_cast<unsigned char>(requestID.size())); + } + catch (const boost::numeric::bad_numeric_cast& e) { + SWIFT_LOG(warning) << "SOCKS5 request ID is too long (" << requestID.size() << "): " << e.what() << std::endl; + finish(); + return; + } append(result, concat(requestID, createByteArray("\x00\x00", 2))); if (!hasBytestream) { SWIFT_LOG(debug) << "Readstream or Wrtiestream with ID " << streamID << " not found!" << std::endl; connection->write(result); finish(boost::optional<FileTransferError>(FileTransferError::PeerError)); } else { SWIFT_LOG(debug) << "Found stream. Sent OK." << std::endl; connection->write(result); diff --git a/Swiften/FileTransfer/TransportSession.h b/Swiften/FileTransfer/TransportSession.h index dc6e59a..2d56517 100644 --- a/Swiften/FileTransfer/TransportSession.h +++ b/Swiften/FileTransfer/TransportSession.h @@ -1,21 +1,20 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/signals2.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/FileTransfer/FileTransferError.h> namespace Swift { class SWIFTEN_API TransportSession { public: virtual ~TransportSession(); virtual void start() = 0; virtual void stop() = 0; diff --git a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h index 03e2476..6119658 100644 --- a/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h +++ b/Swiften/FileTransfer/UnitTest/DummyFileTransferManager.h @@ -1,56 +1,55 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2016 Isode Limited. + * Copyright (c) 2016-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/filesystem/path.hpp> -#include <Swiften/Base/Override.h> #include <Swiften/FileTransfer/FileTransferManager.h> namespace Swift { class S5BProxyRequest; class FileTransferOptions; class DummyFileTransferManager : public FileTransferManager { public: DummyFileTransferManager() : FileTransferManager() { } virtual OutgoingFileTransfer::ref createOutgoingFileTransfer( const JID&, const boost::filesystem::path&, const std::string&, std::shared_ptr<ReadBytestream>, - const FileTransferOptions&) SWIFTEN_OVERRIDE { + const FileTransferOptions&) override { return OutgoingFileTransfer::ref(); } virtual OutgoingFileTransfer::ref createOutgoingFileTransfer( const JID&, const std::string&, const std::string&, const boost::uintmax_t, const boost::posix_time::ptime&, std::shared_ptr<ReadBytestream>, - const FileTransferOptions&) SWIFTEN_OVERRIDE { + const FileTransferOptions&) override { return OutgoingFileTransfer::ref(); } virtual void addS5BProxy(std::shared_ptr<S5BProxyRequest>) { } }; } diff --git a/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp b/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp index f9057f8..2399cbe 100644 --- a/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp +++ b/Swiften/FileTransfer/UnitTest/IBBSendSessionTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <vector> #include <boost/bind.hpp> #include <cppunit/extensions/HelperMacros.h> @@ -52,19 +52,19 @@ class IBBSendSessionTest : public CppUnit::TestFixture { std::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); testling->setBlockSize(1234); testling->start(); CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(stanzaChannel->sentStanzas.size())); CPPUNIT_ASSERT(stanzaChannel->isRequestAtIndex<IBB>(0, JID("foo@bar.com/baz"), IQ::Set)); IBB::ref ibb = stanzaChannel->sentStanzas[0]->getPayload<IBB>(); CPPUNIT_ASSERT_EQUAL(IBB::Open, ibb->getAction()); - CPPUNIT_ASSERT_EQUAL(1234, ibb->getBlockSize()); + CPPUNIT_ASSERT_EQUAL(1234u, ibb->getBlockSize()); CPPUNIT_ASSERT_EQUAL(std::string("myid"), ibb->getStreamID()); } void testStart_ResponseStartsSending() { std::shared_ptr<IBBSendSession> testling = createSession("foo@bar.com/baz"); testling->setBlockSize(3); testling->start(); stanzaChannel->onIQReceived(createIBBResult()); diff --git a/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp b/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp index 72b933d..9793b87 100644 --- a/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp +++ b/Swiften/FileTransfer/UnitTest/IncomingJingleFileTransferTest.cpp @@ -1,30 +1,29 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <iostream> #include <memory> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <Swiften/Base/ByteArray.h> #include <Swiften/Base/Log.h> -#include <Swiften/Base/Override.h> #include <Swiften/Client/DummyStanzaChannel.h> #include <Swiften/Crypto/CryptoProvider.h> #include <Swiften/Crypto/PlatformCryptoProvider.h> #include <Swiften/Elements/IBB.h> #include <Swiften/Elements/JingleFileTransferDescription.h> #include <Swiften/Elements/JingleIBBTransportPayload.h> #include <Swiften/Elements/JingleS5BTransportPayload.h> #include <Swiften/EventLoop/DummyEventLoop.h> #include <Swiften/FileTransfer/ByteArrayWriteBytestream.h> diff --git a/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp b/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp index 3f4d20f..a0fe057 100644 --- a/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp +++ b/Swiften/FileTransfer/UnitTest/OutgoingJingleFileTransferTest.cpp @@ -1,33 +1,32 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <iostream> #include <memory> #include <boost/bind.hpp> #include <boost/optional.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <Swiften/Base/ByteArray.h> #include <Swiften/Base/IDGenerator.h> -#include <Swiften/Base/Override.h> #include <Swiften/Client/DummyStanzaChannel.h> #include <Swiften/Crypto/CryptoProvider.h> #include <Swiften/Crypto/PlatformCryptoProvider.h> #include <Swiften/Elements/IBB.h> #include <Swiften/Elements/JingleFileTransferDescription.h> #include <Swiften/Elements/JingleIBBTransportPayload.h> #include <Swiften/Elements/JingleS5BTransportPayload.h> #include <Swiften/EventLoop/DummyEventLoop.h> #include <Swiften/FileTransfer/ByteArrayReadBytestream.h> diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp index 290dda5..80667b6 100644 --- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp +++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp @@ -53,20 +53,20 @@ class SOCKS5BytestreamClientSessionTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE_END(); public: SOCKS5BytestreamClientSessionTest() : destinationAddressPort(HostAddressPort(HostAddress::fromString("127.0.0.1").get(), 8888)) {} void setUp() { crypto = std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()); destination = "092a44d859d19c9eed676b551ee80025903351c2"; randomGen.seed(static_cast<unsigned int>(time(nullptr))); - eventLoop = std::unique_ptr<DummyEventLoop>(new DummyEventLoop()); - timerFactory = std::unique_ptr<DummyTimerFactory>(new DummyTimerFactory()); + eventLoop = std::make_unique<DummyEventLoop>(); + timerFactory = std::make_unique<DummyTimerFactory>(); connection = std::make_shared<MockeryConnection>(failingPorts, true, eventLoop.get()); //connection->onDataSent.connect(boost::bind(&SOCKS5BytestreamServerSessionTest::handleDataWritten, this, _1)); //stream1 = std::make_shared<ByteArrayReadBytestream>(createByteArray("abcdefg"))); // connection->onDataRead.connect(boost::bind(&SOCKS5BytestreamClientSessionTest::handleDataRead, this, _1)); } void tearDown() { //connection.reset(); } diff --git a/Swiften/IDN/ICUConverter.cpp b/Swiften/IDN/ICUConverter.cpp index d6b0827..37ce708 100644 --- a/Swiften/IDN/ICUConverter.cpp +++ b/Swiften/IDN/ICUConverter.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/IDN/ICUConverter.h> #pragma GCC diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wheader-hygiene" #include <unicode/uidna.h> @@ -13,18 +13,20 @@ #include <unicode/ucnv.h> #include <unicode/ustring.h> #include <boost/numeric/conversion/cast.hpp> using namespace Swift; using boost::numeric_cast; namespace { + static constexpr auto maxStringPrepLength = 1023; + typedef std::vector<UChar, SafeAllocator<UChar> > ICUString; const char* toConstCharArray(const std::string& input) { return input.c_str(); } const char* toConstCharArray(const std::vector<unsigned char, SafeAllocator<unsigned char> >& input) { return reinterpret_cast<const char*>(vecptr(input)); } @@ -87,27 +89,20 @@ namespace { std::vector<char, SafeAllocator<char> > getStringPreparedDetail(const StringType& s, IDNConverter::StringPrepProfile profile) { UErrorCode status = U_ZERO_ERROR; std::shared_ptr<UStringPrepProfile> icuProfile(usprep_openByType(getICUProfileType(profile), &status), usprep_close); assert(U_SUCCESS(status)); ICUString icuInput = convertToICUString(s); ICUString icuResult; UParseError parseError; - icuResult.resize(icuInput.size()); + icuResult.resize(maxStringPrepLength); int32_t icuResultLength = usprep_prepare(icuProfile.get(), vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), USPREP_ALLOW_UNASSIGNED, &parseError, &status); - icuResult.resize(numeric_cast<size_t>(icuResultLength)); - if (status == U_BUFFER_OVERFLOW_ERROR) { - status = U_ZERO_ERROR; - icuResult.resize(numeric_cast<size_t>(icuResultLength)); - icuResultLength = usprep_prepare(icuProfile.get(), vecptr(icuInput), numeric_cast<int32_t>(icuInput.size()), vecptr(icuResult), numeric_cast<int32_t>(icuResult.size()), USPREP_ALLOW_UNASSIGNED, &parseError, &status); - icuResult.resize(numeric_cast<size_t>(icuResultLength)); - } if (U_FAILURE(status)) { return std::vector<char, SafeAllocator<char> >(); } icuResult.resize(numeric_cast<size_t>(icuResultLength)); return convertToArray(icuResult); } } diff --git a/Swiften/IDN/ICUConverter.h b/Swiften/IDN/ICUConverter.h index 0a0b0d3..b0f5d85 100644 --- a/Swiften/IDN/ICUConverter.h +++ b/Swiften/IDN/ICUConverter.h @@ -1,23 +1,22 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/IDN/IDNConverter.h> namespace Swift { class SWIFTEN_API ICUConverter : public IDNConverter { public: - virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; - virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; + virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) override; + virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) override; - virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) SWIFTEN_OVERRIDE; + virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) override; }; } diff --git a/Swiften/IDN/LibIDNConverter.cpp b/Swiften/IDN/LibIDNConverter.cpp index 0c01352..e2a87be 100644 --- a/Swiften/IDN/LibIDNConverter.cpp +++ b/Swiften/IDN/LibIDNConverter.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/IDN/LibIDNConverter.h> extern "C" { #include <stringprep.h> #include <idna.h> @@ -18,19 +18,19 @@ extern "C" { #include <memory> #include <Swiften/Base/ByteArray.h> #include <Swiften/Base/SafeAllocator.h> #include <Swiften/IDN/UTF8Validator.h> using namespace Swift; namespace { - static const int MAX_STRINGPREP_SIZE = 1024; + static const size_t MAX_STRINGPREP_SIZE = 1024; const Stringprep_profile* getLibIDNProfile(IDNConverter::StringPrepProfile profile) { switch(profile) { case IDNConverter::NamePrep: return stringprep_nameprep; case IDNConverter::XMPPNodePrep: return stringprep_xmpp_nodeprep; case IDNConverter::XMPPResourcePrep: return stringprep_xmpp_resourceprep; case IDNConverter::SASLPrep: return stringprep_saslprep; } assert(false); @@ -38,19 +38,20 @@ namespace { } template<typename StringType, typename ContainerType> ContainerType getStringPreparedInternal(const StringType& s, IDNConverter::StringPrepProfile profile) { ContainerType input(s.begin(), s.end()); if (!UTF8IsValid(s.data(), s.size())) { return ContainerType(); } - input.resize(MAX_STRINGPREP_SIZE); + // Ensure we have enough space for stringprepping, and that input is always NUL terminated + input.resize(std::max(MAX_STRINGPREP_SIZE, input.size() + 1)); if (stringprep(&input[0], MAX_STRINGPREP_SIZE, static_cast<Stringprep_profile_flags>(0), getLibIDNProfile(profile)) == 0) { return input; } else { return ContainerType(); } } } @@ -71,17 +72,20 @@ SafeByteArray LibIDNConverter::getStringPrepared(const SafeByteArray& s, StringP } return createSafeByteArray(reinterpret_cast<const char*>(vecptr(preparedData))); } boost::optional<std::string> LibIDNConverter::getIDNAEncoded(const std::string& domain) { char* output; if (idna_to_ascii_8z(domain.c_str(), &output, IDNA_USE_STD3_ASCII_RULES) == IDNA_SUCCESS) { std::string result(output); free(output); + if (result.size() > 255) { + return boost::optional<std::string>(); + } return result; } else { return boost::optional<std::string>(); } } } diff --git a/Swiften/IDN/LibIDNConverter.h b/Swiften/IDN/LibIDNConverter.h index 3f1d1f7..5553ab3 100644 --- a/Swiften/IDN/LibIDNConverter.h +++ b/Swiften/IDN/LibIDNConverter.h @@ -1,24 +1,23 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/IDN/IDNConverter.h> namespace Swift { class SWIFTEN_API LibIDNConverter : public IDNConverter { public: - virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; - virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) SWIFTEN_OVERRIDE; + virtual std::string getStringPrepared(const std::string& s, StringPrepProfile profile) override; + virtual SafeByteArray getStringPrepared(const SafeByteArray& s, StringPrepProfile profile) override; - virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) SWIFTEN_OVERRIDE; + virtual boost::optional<std::string> getIDNAEncoded(const std::string& s) override; }; } diff --git a/Swiften/IDN/PlatformIDNConverter.cpp b/Swiften/IDN/PlatformIDNConverter.cpp index c85d3b6..c6104fb 100644 --- a/Swiften/IDN/PlatformIDNConverter.cpp +++ b/Swiften/IDN/PlatformIDNConverter.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/IDN/PlatformIDNConverter.h> #if defined(HAVE_LIBIDN) #include <Swiften/IDN/LibIDNConverter.h> #elif defined(HAVE_ICU) #include <Swiften/IDN/ICUConverter.h> @@ -15,15 +15,16 @@ namespace Swift { IDNConverter* PlatformIDNConverter::create() { #if defined(HAVE_LIBIDN) return new LibIDNConverter(); #elif defined(HAVE_ICU) return new ICUConverter(); #else #if defined(NEED_IDN) #error "No IDN implementation" -#endif +#else return nullptr; #endif +#endif } } diff --git a/Swiften/IDN/SConscript b/Swiften/IDN/SConscript index 28596f7..0afad0e 100644 --- a/Swiften/IDN/SConscript +++ b/Swiften/IDN/SConscript @@ -17,15 +17,16 @@ if myenv.get("HAVE_LIBIDN") : objects += myenv.SwiftenObject([ "PlatformIDNConverter.cpp" ]) swiften_env.Append(SWIFTEN_OBJECTS = [objects]) if env["TEST"] : test_env = myenv.Clone() test_env.UseFlags(swiften_env["CPPUNIT_FLAGS"]) + test_env.UseFlags(myenv.get("GOOGLETEST_FLAGS", "")) env.Append(UNITTEST_OBJECTS = test_env.SwiftenObject([ File("UnitTest/IDNConverterTest.cpp"), File("UnitTest/UTF8ValidatorTest.cpp") ])) diff --git a/Swiften/IDN/UnitTest/IDNConverterTest.cpp b/Swiften/IDN/UnitTest/IDNConverterTest.cpp index 508a28c..77a1ece 100644 --- a/Swiften/IDN/UnitTest/IDNConverterTest.cpp +++ b/Swiften/IDN/UnitTest/IDNConverterTest.cpp @@ -1,64 +1,98 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <memory> -#include <cppunit/extensions/HelperMacros.h> -#include <cppunit/extensions/TestFactoryRegistry.h> +#include <gtest/gtest.h> #include <Swiften/IDN/IDNConverter.h> #include <Swiften/IDN/PlatformIDNConverter.h> using namespace Swift; -class IDNConverterTest : public CppUnit::TestFixture { - CPPUNIT_TEST_SUITE(IDNConverterTest); - CPPUNIT_TEST(testStringPrep); - CPPUNIT_TEST(testStringPrep_Empty); - CPPUNIT_TEST(testGetEncoded); - CPPUNIT_TEST(testGetEncoded_International); - CPPUNIT_TEST(testGetEncoded_Invalid); - CPPUNIT_TEST_SUITE_END(); - - public: - void setUp() { - testling = std::shared_ptr<IDNConverter>(PlatformIDNConverter::create()); - } - - void testStringPrep() { - std::string result = testling->getStringPrepared("tron\xc3\x87on", IDNConverter::NamePrep); - - CPPUNIT_ASSERT_EQUAL(std::string("tron\xc3\xa7on"), result); - } - - void testStringPrep_Empty() { - CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::NamePrep)); - CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::XMPPNodePrep)); - CPPUNIT_ASSERT_EQUAL(std::string(""), testling->getStringPrepared("", IDNConverter::XMPPResourcePrep)); - } - - void testGetEncoded() { - boost::optional<std::string> result = testling->getIDNAEncoded("www.swift.im"); - CPPUNIT_ASSERT(!!result); - CPPUNIT_ASSERT_EQUAL(std::string("www.swift.im"), *result); - } - - void testGetEncoded_International() { - boost::optional<std::string> result = testling->getIDNAEncoded("www.tron\xc3\x87on.com"); - CPPUNIT_ASSERT(!!result); - CPPUNIT_ASSERT_EQUAL(std::string("www.xn--tronon-zua.com"), *result); - } - - void testGetEncoded_Invalid() { - boost::optional<std::string> result = testling->getIDNAEncoded("www.foo,bar.com"); - CPPUNIT_ASSERT(!result); - } - - private: - std::shared_ptr<IDNConverter> testling; +class IDNConverterTest : public ::testing::Test { + +protected: + virtual void SetUp() { + testling_ = std::shared_ptr<IDNConverter>(PlatformIDNConverter::create()); + } + + std::shared_ptr<IDNConverter> testling_; }; -CPPUNIT_TEST_SUITE_REGISTRATION(IDNConverterTest); +TEST_F(IDNConverterTest, testStringPrep) { + std::string result = testling_->getStringPrepared("tron\xc3\x87on", IDNConverter::NamePrep); + + ASSERT_EQ(std::string("tron\xc3\xa7on"), result); +} + +TEST_F(IDNConverterTest, testStringPrep_Empty) { + ASSERT_EQ(std::string(""), testling_->getStringPrepared("", IDNConverter::NamePrep)); + ASSERT_EQ(std::string(""), testling_->getStringPrepared("", IDNConverter::XMPPNodePrep)); + ASSERT_EQ(std::string(""), testling_->getStringPrepared("", IDNConverter::XMPPResourcePrep)); +} + +TEST_F(IDNConverterTest, testStringPrep_MaximumOutputSize) { + const std::string input(1023, 'x'); + ASSERT_EQ(input, testling_->getStringPrepared(input, IDNConverter::NamePrep)); + ASSERT_EQ(input, testling_->getStringPrepared(input, IDNConverter::XMPPNodePrep)); + ASSERT_EQ(input, testling_->getStringPrepared(input, IDNConverter::XMPPResourcePrep)); +} + +TEST_F(IDNConverterTest, testStringPrep_TooLong) { + const std::string input(1024, 'x'); + ASSERT_THROW(testling_->getStringPrepared(input, IDNConverter::NamePrep), std::exception); + ASSERT_THROW(testling_->getStringPrepared(input, IDNConverter::XMPPNodePrep), std::exception); + ASSERT_THROW(testling_->getStringPrepared(input, IDNConverter::XMPPResourcePrep), std::exception); +} + +TEST_F(IDNConverterTest, testStringPrep_ShrinkingBelow1023) { + std::string input; + std::string expected; + // The four byte \u03b1\u0313 UTF-8 string will shrink to the three byte \u1f00 + for (auto i = 0; i < 300; ++i) { + input +="\xce\xb1\xcc\x93"; // UTF-8 repesentation of U+03B1 U+0313 + expected += "\xe1\xbc\x80"; // UTF-8 representation of U+1F00 + } + ASSERT_EQ(expected, testling_->getStringPrepared(input, IDNConverter::NamePrep)); + ASSERT_EQ(expected, testling_->getStringPrepared(input, IDNConverter::XMPPNodePrep)); + ASSERT_EQ(expected, testling_->getStringPrepared(input, IDNConverter::XMPPResourcePrep)); +} + +TEST_F(IDNConverterTest, testGetEncoded) { + boost::optional<std::string> result = testling_->getIDNAEncoded("www.swift.im"); + ASSERT_TRUE(!!result); + ASSERT_EQ(std::string("www.swift.im"), *result); +} + +TEST_F(IDNConverterTest, testGetEncoded_International) { + boost::optional<std::string> result = testling_->getIDNAEncoded("www.tron\xc3\x87on.com"); + ASSERT_TRUE(result); + ASSERT_EQ(std::string("www.xn--tronon-zua.com"), *result); +} + +TEST_F(IDNConverterTest, testGetEncoded_Invalid) { + boost::optional<std::string> result = testling_->getIDNAEncoded("www.foo,bar.com"); + ASSERT_FALSE(result); +} + +TEST_F(IDNConverterTest, testRFC1035LengthRestrictions) { + // label size check, 63 octets or less + ASSERT_TRUE(testling_->getIDNAEncoded(std::string(63, 'a') + ".example")); + ASSERT_TRUE(testling_->getIDNAEncoded(std::string(63, 'a') + "." + std::string(63, 'a') + ".example")); + ASSERT_FALSE(testling_->getIDNAEncoded(std::string(64, 'a') + "." + std::string(63, 'a') + ".example")); + ASSERT_FALSE(testling_->getIDNAEncoded(std::string(63, 'a') + "." + std::string(64, 'a') + ".example")); + ASSERT_FALSE(testling_->getIDNAEncoded(std::string(0, 'a') + "." + std::string(63, 'a') + ".example")); + ASSERT_FALSE(testling_->getIDNAEncoded(std::string(63, 'a') + "." + std::string(0, 'a') + ".example")); + + // domain name 255 octets or less + ASSERT_TRUE(testling_->getIDNAEncoded(std::string(63, 'a') + ".example")); + ASSERT_TRUE(testling_->getIDNAEncoded(std::string(63, 'a') + "." + std::string(63, 'a') + ".example")); + ASSERT_TRUE(testling_->getIDNAEncoded(std::string(63, 'a') + "." + std::string(63, 'a') + "." + std::string(63, 'a') + ".example")); + ASSERT_TRUE(testling_->getIDNAEncoded(std::string(63, 'a') + "." + std::string(63, 'a') + "." + std::string(63, 'a') + "." + std::string(55, 'a') + ".example")); + ASSERT_FALSE(testling_->getIDNAEncoded(std::string(63, 'a') + "." + std::string(63, 'a') + "." + std::string(63, 'a') + "." + std::string(56, 'a') + ".example")); + ASSERT_FALSE(testling_->getIDNAEncoded(std::string(63, 'a') + "." + std::string(56, 'a') + "." + std::string(63, 'a') + "." + std::string(63, 'a') + ".example")); +} diff --git a/Swiften/JID/JID.cpp b/Swiften/JID/JID.cpp index c82674d..fff88e9 100644 --- a/Swiften/JID/JID.cpp +++ b/Swiften/JID/JID.cpp @@ -1,48 +1,32 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ -#define SWIFTEN_CACHE_JID_PREP - #include <sstream> #include <string> #include <vector> -#ifdef SWIFTEN_CACHE_JID_PREP -#include <mutex> -#include <unordered_map> -#endif - #include <boost/optional.hpp> #include <Swiften/Base/String.h> #include <Swiften/IDN/IDNConverter.h> #include <Swiften/JID/JID.h> #ifndef SWIFTEN_JID_NO_DEFAULT_IDN_CONVERTER #include <memory> #include <Swiften/IDN/PlatformIDNConverter.h> #endif using namespace Swift; -#ifdef SWIFTEN_CACHE_JID_PREP -typedef std::unordered_map<std::string, std::string> PrepCache; - -static std::mutex namePrepCacheMutex; -static PrepCache nodePrepCache; -static PrepCache domainPrepCache; -static PrepCache resourcePrepCache; -#endif - static const std::vector<char> escapedChars = {' ', '"', '&', '\'', '/', '<', '>', '@', ':'}; static IDNConverter* idnConverter = nullptr; #ifndef SWIFTEN_JID_NO_DEFAULT_IDN_CONVERTER namespace { struct IDNInitializer { IDNInitializer() : defaultIDNConverter(PlatformIDNConverter::create()) { idnConverter = defaultIDNConverter.get(); @@ -98,86 +82,52 @@ void JID::initializeFromString(const std::string& jid) { if (slashIndex != jid.npos) { hasResource_ = true; bare = jid.substr(0, slashIndex); resource = jid.substr(slashIndex + 1, jid.npos); } else { hasResource_ = false; bare = jid; } - std::pair<std::string,std::string> nodeAndDomain = String::getSplittedAtFirst(bare, '@'); - if (nodeAndDomain.second.empty()) { - nameprepAndSetComponents("", nodeAndDomain.first, resource); + auto firstMatch = bare.find('@'); + if (firstMatch != bare.npos) { + nameprepAndSetComponents(bare.substr(0, firstMatch), bare.substr(firstMatch + 1), resource); } else { - nameprepAndSetComponents(nodeAndDomain.first, nodeAndDomain.second, resource); + nameprepAndSetComponents("", bare, resource); } } void JID::nameprepAndSetComponents(const std::string& node, const std::string& domain, const std::string& resource) { if (domain.empty() || !idnConverter->getIDNAEncoded(domain)) { valid_ = false; return; } if (hasResource_ && resource.empty()) { valid_ = false; return; } -#ifndef SWIFTEN_CACHE_JID_PREP - node_ = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep); - domain_ = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep); - resource_ = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep); -#else - std::unique_lock<std::mutex> lock(namePrepCacheMutex); - - std::pair<PrepCache::iterator, bool> r; - - r = nodePrepCache.insert(std::make_pair(node, std::string())); - if (r.second) { - try { - r.first->second = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep); - } - catch (...) { - nodePrepCache.erase(r.first); - valid_ = false; - return; - } - } - node_ = r.first->second; - r = domainPrepCache.insert(std::make_pair(domain, std::string())); - if (r.second) { - try { - r.first->second = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep); - } - catch (...) { - domainPrepCache.erase(r.first); - valid_ = false; - return; + try { + node_ = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep); + if (domain.back() == '.') { + domain_ = idnConverter->getStringPrepared(domain.substr(0, domain.size() - 1), IDNConverter::NamePrep); } - } - domain_ = r.first->second; - - r = resourcePrepCache.insert(std::make_pair(resource, std::string())); - if (r.second) { - try { - r.first->second = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep); - } - catch (...) { - resourcePrepCache.erase(r.first); - valid_ = false; - return; + else { + domain_ = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep); } + resource_ = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep); + } catch (...) { + valid_ = false; + return; } - resource_ = r.first->second; -#endif if (domain_.empty()) { valid_ = false; return; } } std::string JID::toString() const { std::string string; diff --git a/Swiften/JID/UnitTest/JIDTest.cpp b/Swiften/JID/UnitTest/JIDTest.cpp index ca3e5ae..0753fb5 100644 --- a/Swiften/JID/UnitTest/JIDTest.cpp +++ b/Swiften/JID/UnitTest/JIDTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <Swiften/JID/JID.h> @@ -14,23 +14,31 @@ using namespace Swift; class JIDTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(JIDTest); CPPUNIT_TEST(testConstructorWithString); CPPUNIT_TEST(testConstructorWithString_Empty); CPPUNIT_TEST(testConstructorWithString_NoResource); CPPUNIT_TEST(testConstructorWithString_NoNode); CPPUNIT_TEST(testConstructorWithString_EmptyResource); CPPUNIT_TEST(testConstructorWithString_OnlyDomain); + CPPUNIT_TEST(testConstructorWithString_OnlyDomainWithDot); + CPPUNIT_TEST(testConstructorWithString_OnlyDomainDotStrippedOff); + CPPUNIT_TEST(testConstructorWithString_InvalidOnlyDomainSingleDot); CPPUNIT_TEST(testConstructorWithString_InvalidDomain); + CPPUNIT_TEST(testConstructorWithString_InvalidDomainEmptyLabel); CPPUNIT_TEST(testConstructorWithString_UpperCaseNode); CPPUNIT_TEST(testConstructorWithString_UpperCaseDomain); CPPUNIT_TEST(testConstructorWithString_UpperCaseResource); CPPUNIT_TEST(testConstructorWithString_EmptyNode); + CPPUNIT_TEST(testConstructorWithString_EmptyDomain); + CPPUNIT_TEST(testConstructorWithString_EmptyDomainWithResource); + CPPUNIT_TEST(testConstructorWithString_DotDomain); + CPPUNIT_TEST(testConstructorWithString_DotDomainWithResource); CPPUNIT_TEST(testConstructorWithString_IllegalResource); CPPUNIT_TEST(testConstructorWithString_SpacesInNode); CPPUNIT_TEST(testConstructorWithStrings); CPPUNIT_TEST(testConstructorWithStrings_EmptyDomain); CPPUNIT_TEST(testConstructorWithStrings_EmptyResource); CPPUNIT_TEST(testIsBare); CPPUNIT_TEST(testIsBare_NotBare); CPPUNIT_TEST(testToBare); CPPUNIT_TEST(testToBare_EmptyNode); @@ -56,18 +64,19 @@ class JIDTest : public CppUnit::TestFixture CPPUNIT_TEST(testSmallerThan_Equal); CPPUNIT_TEST(testSmallerThan_Larger); CPPUNIT_TEST(testHasResource); CPPUNIT_TEST(testHasResource_NoResource); CPPUNIT_TEST(testGetEscapedNode); CPPUNIT_TEST(testGetEscapedNode_XEP106Examples); CPPUNIT_TEST(testGetEscapedNode_BackslashAtEnd); CPPUNIT_TEST(testGetUnescapedNode); CPPUNIT_TEST(testGetUnescapedNode_XEP106Examples); + CPPUNIT_TEST(testStringPrepFailures); CPPUNIT_TEST_SUITE_END(); public: JIDTest() {} void testConstructorWithString() { JID testling("foo@bar/baz"); CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode()); @@ -113,22 +122,50 @@ class JIDTest : public CppUnit::TestFixture JID testling("bar"); CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getNode()); CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResource()); CPPUNIT_ASSERT(testling.isBare()); CPPUNIT_ASSERT(testling.isValid()); } + void testConstructorWithString_OnlyDomainWithDot() { + JID testling("bar."); + + CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); + CPPUNIT_ASSERT_EQUAL(std::string(""), testling.getResource()); + CPPUNIT_ASSERT(testling.isBare()); + CPPUNIT_ASSERT(testling.isValid()); + } + + void testConstructorWithString_OnlyDomainDotStrippedOff() { + JID testling("foo.@bar./resource."); + + CPPUNIT_ASSERT_EQUAL(std::string("foo."), testling.getNode()); + CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); + CPPUNIT_ASSERT_EQUAL(std::string("resource."), testling.getResource()); + CPPUNIT_ASSERT(!testling.isBare()); + CPPUNIT_ASSERT(testling.isValid()); + } + + void testConstructorWithString_InvalidOnlyDomainSingleDot() { + CPPUNIT_ASSERT(!JID(".").isValid()); + } + void testConstructorWithString_InvalidDomain() { CPPUNIT_ASSERT(!JID("foo@bar,baz").isValid()); } + void testConstructorWithString_InvalidDomainEmptyLabel() { + CPPUNIT_ASSERT(!JID("foo@bar..").isValid()); + } + void testConstructorWithString_UpperCaseNode() { JID testling("Fo\xCE\xA9@bar"); CPPUNIT_ASSERT_EQUAL(std::string("fo\xCF\x89"), testling.getNode()); CPPUNIT_ASSERT_EQUAL(std::string("bar"), testling.getDomain()); CPPUNIT_ASSERT(testling.isValid()); } void testConstructorWithString_UpperCaseDomain() { @@ -145,18 +182,48 @@ class JIDTest : public CppUnit::TestFixture CPPUNIT_ASSERT(testling.isValid()); } void testConstructorWithString_EmptyNode() { JID testling("@bar"); CPPUNIT_ASSERT(!testling.isValid()); } + void testConstructorWithString_EmptyDomain() { + JID testling("bar@"); + + CPPUNIT_ASSERT(!testling.isValid()); + } + + void testStringPrepFailures() { + CPPUNIT_ASSERT_EQUAL(false, JID("foo@bar", "example.com").isValid()); + CPPUNIT_ASSERT_EQUAL(false, JID("foo^", "example*com").isValid()); + CPPUNIT_ASSERT_EQUAL(false, JID("foobar", "example^com").isValid()); + } + + void testConstructorWithString_EmptyDomainWithResource() { + JID testling("bar@/resource"); + + CPPUNIT_ASSERT(!testling.isValid()); + } + + void testConstructorWithString_DotDomain() { + JID testling("bar@."); + + CPPUNIT_ASSERT(!testling.isValid()); + } + + void testConstructorWithString_DotDomainWithResource() { + JID testling("bar@./resource"); + + CPPUNIT_ASSERT(!testling.isValid()); + } + void testConstructorWithString_IllegalResource() { JID testling("foo@bar.com/\xd8\xb1\xd9\x85\xd9\x82\xd9\x87\x20\xd8\xaa\xd8\xb1\xd9\x86\xd8\xb3\x20"); CPPUNIT_ASSERT(!testling.isValid()); } void testConstructorWithString_SpacesInNode() { CPPUNIT_ASSERT(!JID(" alice@wonderland.lit").isValid()); CPPUNIT_ASSERT(!JID("alice @wonderland.lit").isValid()); diff --git a/Swiften/Jingle/AbstractJingleSessionListener.h b/Swiften/Jingle/AbstractJingleSessionListener.h index 590cd14..dd8bd1e 100644 --- a/Swiften/Jingle/AbstractJingleSessionListener.h +++ b/Swiften/Jingle/AbstractJingleSessionListener.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Jingle/JingleSessionListener.h> namespace Swift { class SWIFTEN_API AbstractJingleSessionListener : public JingleSessionListener { public: - virtual void handleSessionAcceptReceived(const JingleContentID&, std::shared_ptr<JingleDescription>, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleSessionInfoReceived(std::shared_ptr<JinglePayload>) SWIFTEN_OVERRIDE; - virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) SWIFTEN_OVERRIDE; - virtual void handleTransportAcceptReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportInfoReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportRejectReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportReplaceReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) SWIFTEN_OVERRIDE; - virtual void handleTransportInfoAcknowledged(const std::string& id) SWIFTEN_OVERRIDE; + virtual void handleSessionAcceptReceived(const JingleContentID&, std::shared_ptr<JingleDescription>, std::shared_ptr<JingleTransportPayload>) override; + virtual void handleSessionInfoReceived(std::shared_ptr<JinglePayload>) override; + virtual void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) override; + virtual void handleTransportAcceptReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) override; + virtual void handleTransportInfoReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) override; + virtual void handleTransportRejectReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) override; + virtual void handleTransportReplaceReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) override; + virtual void handleTransportInfoAcknowledged(const std::string& id) override; }; } diff --git a/Swiften/Jingle/FakeJingleSession.h b/Swiften/Jingle/FakeJingleSession.h index 6218544..0ed97d5 100644 --- a/Swiften/Jingle/FakeJingleSession.h +++ b/Swiften/Jingle/FakeJingleSession.h @@ -1,32 +1,31 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> #include <boost/signals2.hpp> #include <boost/variant.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Base/SimpleIDGenerator.h> #include <Swiften/Elements/JinglePayload.h> #include <Swiften/JID/JID.h> #include <Swiften/Jingle/JingleContentID.h> #include <Swiften/Jingle/JingleSession.h> namespace Swift { class JingleContentID; @@ -80,28 +79,28 @@ namespace Swift { JingleTransportPayload::ref payload; }; typedef boost::variant<InitiateCall, TerminateCall, AcceptCall, InfoCall, InfoTransportCall, AcceptTransportCall, RejectTransportCall, ReplaceTransportCall> Command; public: typedef std::shared_ptr<FakeJingleSession> ref; FakeJingleSession(const JID& initiator, const std::string& id); - virtual ~FakeJingleSession(); - - virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; - virtual void sendTerminate(JinglePayload::Reason::Type reason) SWIFTEN_OVERRIDE; - virtual void sendInfo(std::shared_ptr<Payload>) SWIFTEN_OVERRIDE; - virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) SWIFTEN_OVERRIDE; - virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; - virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; - virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; - virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) SWIFTEN_OVERRIDE; + virtual ~FakeJingleSession() override; + + virtual void sendInitiate(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref) override; + virtual void sendTerminate(JinglePayload::Reason::Type reason) override; + virtual void sendInfo(std::shared_ptr<Payload>) override; + virtual void sendAccept(const JingleContentID&, JingleDescription::ref, JingleTransportPayload::ref = JingleTransportPayload::ref()) override; + virtual std::string sendTransportInfo(const JingleContentID&, JingleTransportPayload::ref) override; + virtual void sendTransportAccept(const JingleContentID&, JingleTransportPayload::ref) override; + virtual void sendTransportReject(const JingleContentID&, JingleTransportPayload::ref) override; + virtual void sendTransportReplace(const JingleContentID&, JingleTransportPayload::ref) override; void handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>); void handleSessionAcceptReceived(const JingleContentID&, std::shared_ptr<JingleDescription>, std::shared_ptr<JingleTransportPayload>); void handleSessionInfoReceived(std::shared_ptr<JinglePayload>); void handleTransportReplaceReceived(const JingleContentID&, JingleTransportPayload::ref); void handleTransportAcceptReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>); void handleTransportInfoReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>); void handleTransportRejectReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>); diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp index 1b79946..66b4ae8 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h> #include <iostream> #include <Swiften/LinkLocal/DNSSD/Avahi/AvahiBrowseQuery.h> @@ -19,19 +19,19 @@ AvahiQuerier::AvahiQuerier(EventLoop* eventLoop) : eventLoop(eventLoop), client( } AvahiQuerier::~AvahiQuerier() { } std::shared_ptr<DNSSDBrowseQuery> AvahiQuerier::createBrowseQuery() { return std::make_shared<AvahiBrowseQuery>(shared_from_this(), eventLoop); } -std::shared_ptr<DNSSDRegisterQuery> AvahiQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) { +std::shared_ptr<DNSSDRegisterQuery> AvahiQuerier::createRegisterQuery(const std::string& name, unsigned short port, const ByteArray& info) { return std::make_shared<AvahiRegisterQuery>(name, port, info, shared_from_this(), eventLoop); } std::shared_ptr<DNSSDResolveServiceQuery> AvahiQuerier::createResolveServiceQuery(const DNSSDServiceID& service) { return std::make_shared<AvahiResolveServiceQuery>(service, shared_from_this(), eventLoop); } std::shared_ptr<DNSSDResolveHostnameQuery> AvahiQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) { return std::make_shared<AvahiResolveHostnameQuery>(hostname, interfaceIndex, shared_from_this(), eventLoop); diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h index 5dce19d..73dd11d 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiQuerier.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <avahi-client/client.h> @@ -24,19 +24,19 @@ namespace Swift { class AvahiQuerier : public DNSSDQuerier, public std::enable_shared_from_this<AvahiQuerier> { public: AvahiQuerier(EventLoop* eventLoop); ~AvahiQuerier(); std::shared_ptr<DNSSDBrowseQuery> createBrowseQuery(); std::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( - const std::string& name, int port, const ByteArray& info); + const std::string& name, unsigned short port, const ByteArray& info); std::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( const DNSSDServiceID&); std::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( const std::string& hostname, int interfaceIndex); void start(); void stop(); AvahiThreadedPoll* getThreadedPoll() const { diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h index 68281d0..b780043 100644 --- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h +++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiRegisterQuery.h @@ -1,30 +1,30 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <avahi-client/publish.h> #include <Swiften/Base/ByteArray.h> #include <Swiften/EventLoop/EventLoop.h> #include <Swiften/LinkLocal/DNSSD/Avahi/AvahiQuery.h> #include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h> namespace Swift { class AvahiQuerier; class AvahiRegisterQuery : public DNSSDRegisterQuery, public AvahiQuery { public: - AvahiRegisterQuery(const std::string& name, int port, const ByteArray& txtRecord, std::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), name(name), port(port), txtRecord(txtRecord), group(0) { + AvahiRegisterQuery(const std::string& name, unsigned short port, const ByteArray& txtRecord, std::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), name(name), port(port), txtRecord(txtRecord), group(0) { } void registerService(); void unregisterService(); void updateServiceInfo(const ByteArray& txtRecord); private: void doRegisterService(); @@ -44,14 +44,14 @@ namespace Swift { eventLoop->postEvent(boost::bind(boost::ref(onRegisterFinished), boost::optional<DNSSDServiceID>()), shared_from_this()); } else { } } */ private: std::string name; - int port; + unsigned short port; ByteArray txtRecord; AvahiEntryGroup* group; }; } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h index c049ed2..63f34db 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/numeric/conversion/cast.hpp> #include <Swiften/EventLoop/EventLoop.h> @@ -44,20 +44,25 @@ namespace Swift { static_cast<BonjourBrowseQuery*>(context)->handleServiceDiscovered(flags, interfaceIndex, errorCode, name, type, domain); } void handleServiceDiscovered(DNSServiceFlags flags, uint32_t interfaceIndex, DNSServiceErrorType errorCode, const char *name, const char *type, const char *domain) { if (errorCode != kDNSServiceErr_NoError) { eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this()); } else { //std::cout << "Discovered service: name:" << name << " domain:" << domain << " type: " << type << std::endl; - DNSSDServiceID service(name, domain, type, boost::numeric_cast<int>(interfaceIndex)); - if (flags & kDNSServiceFlagsAdd) { - eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this()); + try { + DNSSDServiceID service(name, domain, type, boost::numeric_cast<int>(interfaceIndex)); + if (flags & kDNSServiceFlagsAdd) { + eventLoop->postEvent(boost::bind(boost::ref(onServiceAdded), service), shared_from_this()); + } + else { + eventLoop->postEvent(boost::bind(boost::ref(onServiceRemoved), service), shared_from_this()); + } } - else { - eventLoop->postEvent(boost::bind(boost::ref(onServiceRemoved), service), shared_from_this()); + catch (...) { + eventLoop->postEvent(boost::bind(boost::ref(onError)), shared_from_this()); } } } }; } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp index 0906ffc..551421e 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.cpp @@ -1,22 +1,23 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h> #include <fcntl.h> #include <sys/socket.h> #include <unistd.h> #include <Swiften/Base/Algorithm.h> +#include <Swiften/Base/Log.h> #include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourBrowseQuery.h> #include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h> #include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h> #include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h> namespace Swift { BonjourQuerier::BonjourQuerier(EventLoop* eventLoop) : eventLoop(eventLoop), stopRequested(false), thread(nullptr) { int fds[2]; @@ -30,19 +31,19 @@ BonjourQuerier::BonjourQuerier(EventLoop* eventLoop) : eventLoop(eventLoop), sto BonjourQuerier::~BonjourQuerier() { assert(!thread); } std::shared_ptr<DNSSDBrowseQuery> BonjourQuerier::createBrowseQuery() { return std::make_shared<BonjourBrowseQuery>(shared_from_this(), eventLoop); } -std::shared_ptr<DNSSDRegisterQuery> BonjourQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) { +std::shared_ptr<DNSSDRegisterQuery> BonjourQuerier::createRegisterQuery(const std::string& name, unsigned short port, const ByteArray& info) { return std::make_shared<BonjourRegisterQuery>(name, port, info, shared_from_this(), eventLoop); } std::shared_ptr<DNSSDResolveServiceQuery> BonjourQuerier::createResolveServiceQuery(const DNSSDServiceID& service) { return std::make_shared<BonjourResolveServiceQuery>(service, shared_from_this(), eventLoop); } std::shared_ptr<DNSSDResolveHostnameQuery> BonjourQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) { return std::make_shared<BonjourResolveHostnameQuery>(hostname, interfaceIndex, shared_from_this(), eventLoop); diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h index 77326bc..6af1c1f 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuerier.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <list> #include <memory> #include <mutex> @@ -19,19 +19,19 @@ namespace Swift { class BonjourQuerier : public DNSSDQuerier, public std::enable_shared_from_this<BonjourQuerier> { public: BonjourQuerier(EventLoop* eventLoop); ~BonjourQuerier(); std::shared_ptr<DNSSDBrowseQuery> createBrowseQuery(); std::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( - const std::string& name, int port, const ByteArray& info); + const std::string& name, unsigned short port, const ByteArray& info); std::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( const DNSSDServiceID&); std::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( const std::string& hostname, int interfaceIndex); void start(); void stop(); private: diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h index 8b2e955..9eb8cd9 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <mutex> #include <boost/numeric/conversion/cast.hpp> @@ -14,24 +14,33 @@ #include <Swiften/EventLoop/EventLoop.h> #include <Swiften/LinkLocal/DNSSD/Bonjour/BonjourQuery.h> #include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h> namespace Swift { class BonjourQuerier; class BonjourRegisterQuery : public DNSSDRegisterQuery, public BonjourQuery { public: - BonjourRegisterQuery(const std::string& name, int port, const ByteArray& txtRecord, std::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { + BonjourRegisterQuery(const std::string& name, unsigned short port, const ByteArray& txtRecord, std::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { + unsigned short recordSize = 0; + try { + recordSize = boost::numeric_cast<unsigned short>(txtRecord.size()); + } + catch (const boost::numeric::bad_numeric_cast&) { + SWIFT_LOG(warning) << "Bonjour TXT record is too long (" << txtRecord.size() << " bytes), not registring service" << std::endl; + return; + } DNSServiceErrorType result = DNSServiceRegister( - &sdRef, 0, 0, name.c_str(), "_presence._tcp", nullptr, nullptr, boost::numeric_cast<unsigned short>(port), - boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), + &sdRef, 0, 0, name.c_str(), "_presence._tcp", nullptr, nullptr, port, + recordSize, vecptr(txtRecord), &BonjourRegisterQuery::handleServiceRegisteredStatic, this); if (result != kDNSServiceErr_NoError) { + SWIFT_LOG(warning) << "Failed to register Bonjour service" << std::endl; sdRef = nullptr; } } void registerService() { if (sdRef) { run(); } else { @@ -39,19 +48,24 @@ namespace Swift { } } void unregisterService() { finish(); } void updateServiceInfo(const ByteArray& txtRecord) { std::lock_guard<std::mutex> lock(sdRefMutex); - DNSServiceUpdateRecord(sdRef, nullptr, 0, boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), 0); + try { + DNSServiceUpdateRecord(sdRef, nullptr, 0, boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), 0); + } + catch (const boost::numeric::bad_numeric_cast&) { + SWIFT_LOG(warning) << "Bonjour TXT record is too long (" << txtRecord.size() << " bytes), not updating service record" << std::endl; + } } private: static void handleServiceRegisteredStatic(DNSServiceRef, DNSServiceFlags, DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain, void *context) { static_cast<BonjourRegisterQuery*>(context)->handleServiceRegistered(errorCode, name, regtype, domain); } void handleServiceRegistered(DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain) { if (errorCode != kDNSServiceErr_NoError) { diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h index dbf3f0e..61f000e 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveHostnameQuery.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #pragma GCC diagnostic ignored "-Wold-style-cast" #include <string> @@ -17,23 +17,28 @@ #include <netinet/in.h> namespace Swift { class BonjourQuerier; class BonjourResolveHostnameQuery : public DNSSDResolveHostnameQuery, public BonjourQuery { public: BonjourResolveHostnameQuery(const std::string& hostname, int interfaceIndex, std::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { - DNSServiceErrorType result = DNSServiceGetAddrInfo( - &sdRef, 0, boost::numeric_cast<unsigned int>(interfaceIndex), kDNSServiceProtocol_IPv4, - hostname.c_str(), - &BonjourResolveHostnameQuery::handleHostnameResolvedStatic, this); - if (result != kDNSServiceErr_NoError) { + try { + DNSServiceErrorType result = DNSServiceGetAddrInfo( + &sdRef, 0, boost::numeric_cast<unsigned int>(interfaceIndex), kDNSServiceProtocol_IPv4, + hostname.c_str(), + &BonjourResolveHostnameQuery::handleHostnameResolvedStatic, this); + if (result != kDNSServiceErr_NoError) { + sdRef = nullptr; + } + } + catch (...) { sdRef = nullptr; } } //void DNSSDResolveHostnameQuery::run() { void run() { if (sdRef) { BonjourQuery::run(); } diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h index 7a5555e..4baf87b 100644 --- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h +++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourResolveServiceQuery.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/ByteArray.h> @@ -14,24 +14,29 @@ #include <Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h> #include <Swiften/LinkLocal/LinkLocalServiceInfo.h> namespace Swift { class BonjourQuerier; class BonjourResolveServiceQuery : public DNSSDResolveServiceQuery, public BonjourQuery { public: BonjourResolveServiceQuery(const DNSSDServiceID& service, std::shared_ptr<BonjourQuerier> querier, EventLoop* eventLoop) : BonjourQuery(querier, eventLoop) { - DNSServiceErrorType result = DNSServiceResolve( - &sdRef, 0, boost::numeric_cast<unsigned int>(service.getNetworkInterfaceID()), - service.getName().c_str(), service.getType().c_str(), - service.getDomain().c_str(), - &BonjourResolveServiceQuery::handleServiceResolvedStatic, this); - if (result != kDNSServiceErr_NoError) { + try { + DNSServiceErrorType result = DNSServiceResolve( + &sdRef, 0, boost::numeric_cast<unsigned int>(service.getNetworkInterfaceID()), + service.getName().c_str(), service.getType().c_str(), + service.getDomain().c_str(), + &BonjourResolveServiceQuery::handleServiceResolvedStatic, this); + if (result != kDNSServiceErr_NoError) { + sdRef = nullptr; + } + } + catch (...) { sdRef = nullptr; } } void start() { if (sdRef) { run(); } else { diff --git a/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h b/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h index 8f3c3ec..3924c05 100644 --- a/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h +++ b/Swiften/LinkLocal/DNSSD/DNSSDQuerier.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/ByteArray.h> @@ -20,16 +20,16 @@ namespace Swift { class DNSSDQuerier { public: virtual ~DNSSDQuerier(); virtual void start() = 0; virtual void stop() = 0; virtual std::shared_ptr<DNSSDBrowseQuery> createBrowseQuery() = 0; virtual std::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( - const std::string& name, int port, const ByteArray& info) = 0; + const std::string& name, unsigned short port, const ByteArray& info) = 0; virtual std::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( const DNSSDServiceID&) = 0; virtual std::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( const std::string& hostname, int interfaceIndex) = 0; }; } diff --git a/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h b/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h index b55447a..6416d69 100644 --- a/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h +++ b/Swiften/LinkLocal/DNSSD/DNSSDResolveServiceQuery.h @@ -1,32 +1,32 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/optional.hpp> #include <boost/signals2.hpp> #include <Swiften/Base/ByteArray.h> #include <Swiften/LinkLocal/DNSSD/DNSSDServiceID.h> namespace Swift { class DNSSDResolveServiceQuery { public: struct Result { - Result(const std::string& fullName, const std::string& host, int port, const ByteArray& info) : + Result(const std::string& fullName, const std::string& host, unsigned short port, const ByteArray& info) : fullName(fullName), host(host), port(port), info(info) {} std::string fullName; std::string host; - int port; + unsigned short port; ByteArray info; }; virtual ~DNSSDResolveServiceQuery(); virtual void start() = 0; virtual void stop() = 0; boost::signals2::signal<void (const boost::optional<Result>&)> onServiceResolved; diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp index c17f8b2..3381a26 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h> #include <iostream> #include <boost/bind.hpp> @@ -26,19 +26,19 @@ FakeDNSSDQuerier::~FakeDNSSDQuerier() { if (!runningQueries.empty()) { std::cerr << "FakeDNSSDQuerier: Running queries not empty at destruction time" << std::endl; } } std::shared_ptr<DNSSDBrowseQuery> FakeDNSSDQuerier::createBrowseQuery() { return std::make_shared<FakeDNSSDBrowseQuery>(shared_from_this()); } -std::shared_ptr<DNSSDRegisterQuery> FakeDNSSDQuerier::createRegisterQuery(const std::string& name, int port, const ByteArray& info) { +std::shared_ptr<DNSSDRegisterQuery> FakeDNSSDQuerier::createRegisterQuery(const std::string& name, unsigned short port, const ByteArray& info) { return std::make_shared<FakeDNSSDRegisterQuery>(name, port, info, shared_from_this()); } std::shared_ptr<DNSSDResolveServiceQuery> FakeDNSSDQuerier::createResolveServiceQuery(const DNSSDServiceID& service) { return std::make_shared<FakeDNSSDResolveServiceQuery>(service, shared_from_this()); } std::shared_ptr<DNSSDResolveHostnameQuery> FakeDNSSDQuerier::createResolveHostnameQuery(const std::string& hostname, int interfaceIndex) { return std::make_shared<FakeDNSSDResolveHostnameQuery>(hostname, interfaceIndex, shared_from_this()); @@ -99,19 +99,19 @@ void FakeDNSSDQuerier::setServiceInfo(const DNSSDServiceID& id, const DNSSDResol r.first->second = info; } for (const auto& query : getQueries<FakeDNSSDResolveServiceQuery>()) { if (query->service == id) { eventLoop->postEvent(boost::bind(boost::ref(query->onServiceResolved), info), shared_from_this()); } } } -bool FakeDNSSDQuerier::isServiceRegistered(const std::string& name, int port, const ByteArray& info) { +bool FakeDNSSDQuerier::isServiceRegistered(const std::string& name, unsigned short port, const ByteArray& info) { for (const auto& query : getQueries<FakeDNSSDRegisterQuery>()) { if (query->name == name && query->port == port && query->info == info) { return true; } } return false; } void FakeDNSSDQuerier::setBrowseError() { diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h index 5d4fefd..07cb75c 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuerier.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2017 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <list> #include <memory> #include <set> @@ -33,31 +33,31 @@ namespace Swift { void start() {} void stop() {} void clearAllQueriesEverRun() { allQueriesEverRun.clear(); } std::shared_ptr<DNSSDBrowseQuery> createBrowseQuery(); std::shared_ptr<DNSSDRegisterQuery> createRegisterQuery( - const std::string& name, int port, const ByteArray& info); + const std::string& name, unsigned short port, const ByteArray& info); std::shared_ptr<DNSSDResolveServiceQuery> createResolveServiceQuery( const DNSSDServiceID&); std::shared_ptr<DNSSDResolveHostnameQuery> createResolveHostnameQuery( const std::string& hostname, int interfaceIndex); void addRunningQuery(std::shared_ptr<FakeDNSSDQuery>); void removeRunningQuery(std::shared_ptr<FakeDNSSDQuery>); void addService(const DNSSDServiceID& id); void removeService(const DNSSDServiceID& id); void setServiceInfo(const DNSSDServiceID& id, const DNSSDResolveServiceQuery::Result& info); - bool isServiceRegistered(const std::string& name, int port, const ByteArray& info); + bool isServiceRegistered(const std::string& name, unsigned short port, const ByteArray& info); void setAddress(const std::string& hostname, boost::optional<HostAddress> address); void setBrowseError(); void setRegisterError(); public: template<typename T> std::vector< std::shared_ptr<T> > getAllQueriesEverRun() const { std::vector< std::shared_ptr<T> > result; diff --git a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h index 7478841..ee6bb92 100644 --- a/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h +++ b/Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDRegisterQuery.h @@ -1,39 +1,39 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/ByteArray.h> #include <Swiften/LinkLocal/DNSSD/DNSSDRegisterQuery.h> #include <Swiften/LinkLocal/DNSSD/Fake/FakeDNSSDQuery.h> namespace Swift { class FakeDNSSDQuerier; class FakeDNSSDRegisterQuery : public DNSSDRegisterQuery, public FakeDNSSDQuery { public: - FakeDNSSDRegisterQuery(const std::string& name, int port, const ByteArray& info, std::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), name(name), port(port), info(info) { + FakeDNSSDRegisterQuery(const std::string& name, unsigned short port, const ByteArray& info, std::shared_ptr<FakeDNSSDQuerier> querier) : FakeDNSSDQuery(querier), name(name), port(port), info(info) { } void registerService() { run(); } void updateServiceInfo(const ByteArray& i) { info = i; } void unregisterService() { finish(); } std::string name; - int port; + unsigned short port; ByteArray info; }; } diff --git a/Swiften/LinkLocal/LinkLocalService.h b/Swiften/LinkLocal/LinkLocalService.h index 9b0e2ab..c51f890 100644 --- a/Swiften/LinkLocal/LinkLocalService.h +++ b/Swiften/LinkLocal/LinkLocalService.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Swiften/Base/API.h> @@ -25,19 +25,19 @@ namespace Swift { const DNSSDServiceID& getID() const { return id; } const std::string& getName() const { return id.getName(); } - int getPort() const { + unsigned short getPort() const { return info.port; } const std::string& getHostname() const { return info.host; } LinkLocalServiceInfo getInfo() const { return LinkLocalServiceInfo::createFromTXTRecord(info.info); diff --git a/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp b/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp index b79f184..0498384 100644 --- a/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp +++ b/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/LinkLocal/LinkLocalServiceBrowser.h> #include <iostream> #include <boost/bind.hpp> @@ -59,29 +59,41 @@ bool LinkLocalServiceBrowser::isRunning() const { bool LinkLocalServiceBrowser::hasError() const { return haveError; } bool LinkLocalServiceBrowser::isRegistered() const { return !!registerQuery; } -void LinkLocalServiceBrowser::registerService(const std::string& name, int port, const LinkLocalServiceInfo& info) { +void LinkLocalServiceBrowser::registerService(const std::string& name, unsigned short port, const LinkLocalServiceInfo& info) { assert(!registerQuery); - registerQuery = querier->createRegisterQuery(name, port, info.toTXTRecord()); - registerQuery->onRegisterFinished.connect( - boost::bind(&LinkLocalServiceBrowser::handleRegisterFinished, this, _1)); - registerQuery->registerService(); + if (auto txtRecord = info.toTXTRecord()) { + registerQuery = querier->createRegisterQuery(name, port, *txtRecord); + registerQuery->onRegisterFinished.connect( + boost::bind(&LinkLocalServiceBrowser::handleRegisterFinished, this, _1)); + registerQuery->registerService(); + } + else { + haveError = true; + stop(); + } } void LinkLocalServiceBrowser::updateService(const LinkLocalServiceInfo& info) { assert(registerQuery); - registerQuery->updateServiceInfo(info.toTXTRecord()); + if (auto txtRecord = info.toTXTRecord()) { + registerQuery->updateServiceInfo(*txtRecord); + } + else { + haveError = true; + stop(); + } } void LinkLocalServiceBrowser::unregisterService() { assert(registerQuery); registerQuery->unregisterService(); registerQuery.reset(); selfService.reset(); } diff --git a/Swiften/LinkLocal/LinkLocalServiceBrowser.h b/Swiften/LinkLocal/LinkLocalServiceBrowser.h index c59a4d0..bfcfc07 100644 --- a/Swiften/LinkLocal/LinkLocalServiceBrowser.h +++ b/Swiften/LinkLocal/LinkLocalServiceBrowser.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <map> #include <memory> #include <string> @@ -29,19 +29,19 @@ namespace Swift { ~LinkLocalServiceBrowser(); void start(); void stop(); bool isRunning() const; bool hasError() const; void registerService( const std::string& name, - int port, + unsigned short port, const LinkLocalServiceInfo& info = LinkLocalServiceInfo()); void updateService( const LinkLocalServiceInfo& info = LinkLocalServiceInfo()); void unregisterService(); bool isRegistered() const; std::vector<LinkLocalService> getServices() const; // FIXME: Ugly that we need this diff --git a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp index 7a7ed3b..914fab4 100644 --- a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp +++ b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp @@ -1,56 +1,63 @@ /* - * Copyright (c) 2010-2013 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/LinkLocal/LinkLocalServiceInfo.h> #include <boost/lexical_cast.hpp> #include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/Algorithm.h> #include <Swiften/Base/Concat.h> +#include <Swiften/Base/Log.h> namespace Swift { -ByteArray LinkLocalServiceInfo::toTXTRecord() const { - ByteArray result(getEncoded("txtvers=1")); - if (!firstName.empty()) { - append(result, getEncoded("1st=" + firstName)); - } - if (!lastName.empty()) { - append(result, getEncoded("last=" + lastName)); - } - if (!email.empty()) { - append(result, getEncoded("email=" + email)); - } - if (jid.isValid()) { - append(result, getEncoded("jid=" + jid.toString())); - } - if (!message.empty()) { - append(result, getEncoded("msg=" + message)); - } - if (!nick.empty()) { - append(result, getEncoded("nick=" + nick)); - } - if (port) { - append(result, getEncoded("port.p2pj=" + std::string(boost::lexical_cast<std::string>(*port)))); - } +boost::optional<ByteArray> LinkLocalServiceInfo::toTXTRecord() const { + try { + ByteArray result(getEncoded("txtvers=1")); + if (!firstName.empty()) { + append(result, getEncoded("1st=" + firstName)); + } + if (!lastName.empty()) { + append(result, getEncoded("last=" + lastName)); + } + if (!email.empty()) { + append(result, getEncoded("email=" + email)); + } + if (jid.isValid()) { + append(result, getEncoded("jid=" + jid.toString())); + } + if (!message.empty()) { + append(result, getEncoded("msg=" + message)); + } + if (!nick.empty()) { + append(result, getEncoded("nick=" + nick)); + } + if (port) { + append(result, getEncoded("port.p2pj=" + std::string(std::to_string(*port)))); + } - switch (status) { - case Available: append(result, getEncoded("status=avail")); break; - case Away: append(result, getEncoded("status=away")); break; - case DND: append(result, getEncoded("status=dnd")); break; - } + switch (status) { + case Available: append(result, getEncoded("status=avail")); break; + case Away: append(result, getEncoded("status=away")); break; + case DND: append(result, getEncoded("status=dnd")); break; + } - return result; + return result; + } + catch (const std::exception& e) { + SWIFT_LOG(warning) << "Failed to create TXT record for link local service info: " << e.what() << std::endl; + return boost::none; + } } ByteArray LinkLocalServiceInfo::getEncoded(const std::string& s) { ByteArray sizeByte; sizeByte.resize(1); sizeByte[0] = boost::numeric_cast<unsigned char>(s.size()); return concat(sizeByte, createByteArray(s)); } @@ -76,19 +83,25 @@ LinkLocalServiceInfo LinkLocalServiceInfo::createFromTXTRecord(const ByteArray& info.setJID(JID(entry.second)); } else if (entry.first == "msg") { info.setMessage(entry.second); } else if (entry.first == "nick") { info.setNick(entry.second); } else if (entry.first == "port.p2pj") { - info.setPort(boost::lexical_cast<int>(entry.second)); + try { + info.setPort(boost::numeric_cast<unsigned short>(boost::lexical_cast<int>(entry.second))); + } + catch (const boost::bad_lexical_cast&) { + } + catch (const boost::numeric::bad_numeric_cast&) { + } } else if (entry.first == "status") { if (entry.second == "away") { info.setStatus(Away); } else if (entry.second == "dnd") { info.setStatus(DND); } } diff --git a/Swiften/LinkLocal/LinkLocalServiceInfo.h b/Swiften/LinkLocal/LinkLocalServiceInfo.h index 9f15c6e..adfd062 100644 --- a/Swiften/LinkLocal/LinkLocalServiceInfo.h +++ b/Swiften/LinkLocal/LinkLocalServiceInfo.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <boost/optional.hpp> @@ -37,31 +37,31 @@ namespace Swift { const std::string& getMessage() const { return message; } void setMessage(const std::string& m) { message = m; } const std::string& getNick() const { return nick; } void setNick(const std::string& n) { nick = n; } Status getStatus() const { return status; } void setStatus(Status s) { status = s; } - boost::optional<int> getPort() const { return port; } - void setPort(int p) { port = p; } + boost::optional<unsigned short> getPort() const { return port; } + void setPort(unsigned short p) { port = p; } - ByteArray toTXTRecord() const; + boost::optional<ByteArray> toTXTRecord() const; static LinkLocalServiceInfo createFromTXTRecord(const ByteArray& record); private: static ByteArray getEncoded(const std::string&); static std::pair<std::string,std::string> readEntry(const ByteArray&, size_t*); private: std::string firstName; std::string lastName; std::string email; JID jid; std::string message; std::string nick; Status status; - boost::optional<int> port; + boost::optional<unsigned short> port; }; } diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp index 85ae537..59cf996 100644 --- a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp +++ b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <boost/bind.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> @@ -47,19 +47,19 @@ class LinkLocalConnectorTest : public CppUnit::TestFixture { querier->setAddress("rabbithole.local", HostAddress::fromString("192.168.1.1").get()); testling->connect(); eventLoop->processEvents(); CPPUNIT_ASSERT(connectFinished); CPPUNIT_ASSERT(!connectError); CPPUNIT_ASSERT(connection->connectedTo); CPPUNIT_ASSERT_EQUAL(std::string(connection->connectedTo->getAddress().toString()), std::string("192.168.1.1")); - CPPUNIT_ASSERT_EQUAL(connection->connectedTo->getPort(), 1234); + CPPUNIT_ASSERT_EQUAL(connection->connectedTo->getPort(), static_cast<unsigned short>(1234)); } void testConnect_UnableToResolve() { std::shared_ptr<LinkLocalConnector> testling(createConnector("rabbithole.local", 1234)); querier->setAddress("rabbithole.local", boost::optional<HostAddress>()); testling->connect(); eventLoop->processEvents(); @@ -108,24 +108,26 @@ class LinkLocalConnectorTest : public CppUnit::TestFixture { CPPUNIT_ASSERT(FakeConnection::Connecting == connection->state); testling->cancel(); eventLoop->processEvents(); CPPUNIT_ASSERT(FakeConnection::Disconnected == connection->state); } private: - std::shared_ptr<LinkLocalConnector> createConnector(const std::string& hostname, int port) { + std::shared_ptr<LinkLocalConnector> createConnector(const std::string& hostname, unsigned short port) { + auto txtRecord = LinkLocalServiceInfo().toTXTRecord(); + CPPUNIT_ASSERT(txtRecord); LinkLocalService service( DNSSDServiceID("myname", "local."), DNSSDResolveServiceQuery::Result( "myname._presence._tcp.local", hostname, port, - LinkLocalServiceInfo().toTXTRecord())); + *txtRecord)); std::shared_ptr<LinkLocalConnector> result( new LinkLocalConnector(service, querier, connection)); result->onConnectFinished.connect( boost::bind(&LinkLocalConnectorTest::handleConnected, this, _1)); return result; } void handleConnected(bool e) { connectFinished = true; diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp index a80d748..3491634 100644 --- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp +++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <map> #include <memory> #include <boost/bind.hpp> @@ -41,22 +41,24 @@ class LinkLocalServiceBrowserTest : public CppUnit::TestFixture { CPPUNIT_TEST(testRegisterService_Reregister); CPPUNIT_TEST(testUpdateService); CPPUNIT_TEST_SUITE_END(); public: void setUp() { eventLoop = new DummyEventLoop(); querier = std::make_shared<FakeDNSSDQuerier>("wonderland.lit", eventLoop); aliceServiceID = new DNSSDServiceID("alice", "wonderland.lit"); - aliceServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.wonderland.lit", "xmpp.wonderland.lit", 1234, LinkLocalServiceInfo().toTXTRecord()); + auto txtRecord = LinkLocalServiceInfo().toTXTRecord(); + CPPUNIT_ASSERT(txtRecord); + aliceServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.wonderland.lit", "xmpp.wonderland.lit", 1234, *txtRecord); testServiceID = new DNSSDServiceID("foo", "bar.local"); - testServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.bar.local", "xmpp.bar.local", 1234, LinkLocalServiceInfo().toTXTRecord()); - testServiceInfo2 = new DNSSDResolveServiceQuery::Result("_presence.tcp.bar.local", "xmpp.foo.local", 2345, LinkLocalServiceInfo().toTXTRecord()); + testServiceInfo = new DNSSDResolveServiceQuery::Result("_presence._tcp.bar.local", "xmpp.bar.local", 1234, *txtRecord); + testServiceInfo2 = new DNSSDResolveServiceQuery::Result("_presence.tcp.bar.local", "xmpp.foo.local", 2345, *txtRecord); errorStopReceived = false; normalStopReceived = false; } void tearDown() { querier->clearAllQueriesEverRun(); addedServices.clear(); removedServices.clear(); changedServices.clear(); @@ -286,73 +288,81 @@ class LinkLocalServiceBrowserTest : public CppUnit::TestFixture { std::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); testling->start(); eventLoop->processEvents(); LinkLocalServiceInfo info; info.setFirstName("Foo"); testling->registerService("foo@bar", 1234, info); eventLoop->processEvents(); - CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord())); + auto txtRecord = info.toTXTRecord(); + CPPUNIT_ASSERT(txtRecord); + CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, *txtRecord)); CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(registeredServices.size())); CPPUNIT_ASSERT(registeredServices[0] == DNSSDServiceID("foo@bar", "wonderland.lit")); testling->stop(); } void testRegisterService_Error() { std::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); testling->start(); LinkLocalServiceInfo info; testling->registerService("foo@bar", 1234, info); eventLoop->processEvents(); querier->setRegisterError(); eventLoop->processEvents(); CPPUNIT_ASSERT(!testling->isRunning()); CPPUNIT_ASSERT(testling->hasError()); CPPUNIT_ASSERT(errorStopReceived); - CPPUNIT_ASSERT(!querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord())); + auto txtRecord = info.toTXTRecord(); + CPPUNIT_ASSERT(txtRecord); + CPPUNIT_ASSERT(!querier->isServiceRegistered("foo@bar", 1234, *txtRecord)); } void testRegisterService_Reregister() { std::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); testling->start(); eventLoop->processEvents(); LinkLocalServiceInfo info; info.setFirstName("Foo"); testling->registerService("foo@bar", 1234, info); eventLoop->processEvents(); testling->unregisterService(); eventLoop->processEvents(); info.setFirstName("Bar"); testling->registerService("bar@baz", 3456, info); eventLoop->processEvents(); - CPPUNIT_ASSERT(querier->isServiceRegistered("bar@baz", 3456, info.toTXTRecord())); + auto txtRecord = info.toTXTRecord(); + CPPUNIT_ASSERT(txtRecord); + CPPUNIT_ASSERT(querier->isServiceRegistered("bar@baz", 3456, *txtRecord)); testling->stop(); } void testUpdateService() { std::shared_ptr<LinkLocalServiceBrowser> testling = createTestling(); testling->start(); eventLoop->processEvents(); LinkLocalServiceInfo info; info.setFirstName("Foo"); testling->registerService("foo@bar", 1234, info); eventLoop->processEvents(); info.setFirstName("Bar"); testling->updateService(info); - CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, info.toTXTRecord())); + auto txtRecord = info.toTXTRecord(); + CPPUNIT_ASSERT(txtRecord); + CPPUNIT_ASSERT(querier->isServiceRegistered("foo@bar", 1234, *txtRecord)); testling->stop(); } private: std::shared_ptr<LinkLocalServiceBrowser> createTestling() { std::shared_ptr<LinkLocalServiceBrowser> testling( new LinkLocalServiceBrowser(querier)); testling->onServiceAdded.connect(boost::bind( diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp index 0a94a98..35cb1b4 100644 --- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp +++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <QA/Checker/IO.h> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> @@ -23,19 +23,21 @@ class LinkLocalServiceInfoTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE_END(); public: void testGetTXTRecord() { LinkLocalServiceInfo info; info.setFirstName("Remko"); info.setLastName("Tron\xc3\xe7on"); info.setStatus(LinkLocalServiceInfo::Away); - CPPUNIT_ASSERT_EQUAL(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away")), info.toTXTRecord()); + auto txtRecord = info.toTXTRecord(); + CPPUNIT_ASSERT(txtRecord); + CPPUNIT_ASSERT_EQUAL(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away")), *txtRecord); } void testCreateFromTXTRecord() { LinkLocalServiceInfo info = LinkLocalServiceInfo::createFromTXTRecord(createByteArray("\x09txtvers=1\x09" + std::string("1st=Remko\x0dlast=Tron\xc3\xe7on\x0bstatus=away"))); CPPUNIT_ASSERT_EQUAL(std::string("Remko"), info.getFirstName()); CPPUNIT_ASSERT_EQUAL(std::string("Tron\xc3\xe7on"), info.getLastName()); CPPUNIT_ASSERT_EQUAL(LinkLocalServiceInfo::Away, info.getStatus()); } @@ -51,22 +53,31 @@ class LinkLocalServiceInfoTest : public CppUnit::TestFixture { info.setFirstName("Remko"); info.setLastName("Tron\xc3\xe7on"); info.setEMail("remko-email@swift.im"); info.setJID(JID("remko-jid@swift.im")); info.setMessage("I'm busy"); info.setNick("el-tramo"); info.setStatus(LinkLocalServiceInfo::DND); info.setPort(1234); - LinkLocalServiceInfo info2 = LinkLocalServiceInfo::createFromTXTRecord(info.toTXTRecord()); + auto txtRecord = info.toTXTRecord(); + CPPUNIT_ASSERT(txtRecord); + LinkLocalServiceInfo info2 = LinkLocalServiceInfo::createFromTXTRecord(*txtRecord); CPPUNIT_ASSERT_EQUAL(info.getFirstName(), info2.getFirstName()); CPPUNIT_ASSERT_EQUAL(info.getLastName(), info2.getLastName()); CPPUNIT_ASSERT_EQUAL(info.getEMail(), info2.getEMail()); CPPUNIT_ASSERT_EQUAL(info.getJID(), info2.getJID()); CPPUNIT_ASSERT_EQUAL(info.getMessage(), info2.getMessage()); CPPUNIT_ASSERT_EQUAL(info.getNick(), info2.getNick()); CPPUNIT_ASSERT(info.getStatus() == info2.getStatus()); CPPUNIT_ASSERT(info.getPort() == info2.getPort()); } + + void testToTXTRecordWithInvalidParameter() { + LinkLocalServiceInfo info; + info.setFirstName(std::string(256, 'x')); + auto txtRecord = info.toTXTRecord(); + CPPUNIT_ASSERT(!txtRecord); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalServiceInfoTest); diff --git a/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp b/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp index 206d824..cb5f40a 100644 --- a/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp +++ b/Swiften/LinkLocal/UnitTest/LinkLocalServiceTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <Swiften/LinkLocal/LinkLocalService.h> @@ -52,17 +52,19 @@ class LinkLocalServiceTest : public CppUnit::TestFixture { } private: LinkLocalService createService(const std::string& name, const std::string& nickName = std::string(), const std::string& firstName = std::string(), const std::string& lastName = std::string()) { DNSSDServiceID service(name, "local."); LinkLocalServiceInfo info; info.setFirstName(firstName); info.setLastName(lastName); info.setNick(nickName); + auto txtRecord = info.toTXTRecord(); + CPPUNIT_ASSERT(txtRecord); return LinkLocalService(service, DNSSDResolveServiceQuery::Result( name + "._presence._tcp.local", "rabbithole.local", 1234, - info.toTXTRecord())); + *txtRecord)); } }; CPPUNIT_TEST_SUITE_REGISTRATION(LinkLocalServiceTest); diff --git a/Swiften/MIX/MIX.cpp b/Swiften/MIX/MIX.cpp new file mode 100644 index 0000000..f3e3d69 --- /dev/null +++ b/Swiften/MIX/MIX.cpp @@ -0,0 +1,14 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/MIX/MIX.h> + +namespace Swift { + +MIX::~MIX() { +} + +} diff --git a/Swiften/MIX/MIX.h b/Swiften/MIX/MIX.h new file mode 100644 index 0000000..1398a6e --- /dev/null +++ b/Swiften/MIX/MIX.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#pragma once + +#include <memory> +#include <string> +#include <unordered_set> + +#include <boost/signals2.hpp> + +#include <Swiften/Base/API.h> +#include <Swiften/JID/JID.h> +#include <Swiften/Elements/Form.h> +#include <Swiften/Elements/MIXJoin.h> +#include <Swiften/Elements/MIXLeave.h> +#include <Swiften/Elements/MIXUpdateSubscription.h> +#include <Swiften/Elements/MIXUserPreference.h> +#include <Swiften/Elements/ErrorPayload.h> + +namespace Swift { + class SWIFTEN_API MIX { + public: + using ref = std::shared_ptr<MIX>; + + public: + virtual ~MIX(); + + /** + * Join a MIX channel and subscribe to nodes. + */ + virtual void joinChannel(const std::unordered_set<std::string>& nodes) = 0; + + /** + * Join Channel with a set of preferences. + */ + virtual void joinChannelWithPreferences(const std::unordered_set<std::string>& nodes, Form::ref form) = 0; + + /** + * Update subscription of nodes. + */ + virtual void updateSubscription(const std::unordered_set<std::string>& nodes) = 0; + + /** + * Leave a MIX channel and unsubcribe nodes. + */ + virtual void leaveChannel() = 0; + + /** + * Request a configuration form for updating preferences. + */ + virtual void requestPreferencesForm() = 0; + + /** + * Update preferences after requesting preference form. + */ + virtual void updatePreferences(Form::ref form) = 0; + + public: + boost::signals2::signal<void (MIXJoin::ref /* joinResponse */, ErrorPayload::ref /* joinError */)> onJoinResponse; + boost::signals2::signal<void (MIXLeave::ref /* leaveResponse */, ErrorPayload::ref /* leaveError */)> onLeaveResponse; + boost::signals2::signal<void (MIXUpdateSubscription::ref /* updateResponse */, ErrorPayload::ref /* updateError */)> onSubscriptionUpdateResponse; + boost::signals2::signal<void (Form::ref /* preferencesForm */, ErrorPayload::ref /* failedConfiguration */)> onPreferencesFormResponse; + boost::signals2::signal<void (MIXUserPreference::ref /* userPreferenceResponse */, ErrorPayload::ref /* failedUpdate */)> onPreferencesUpdateResponse; + }; +} diff --git a/Swiften/MIX/MIXImpl.cpp b/Swiften/MIX/MIXImpl.cpp new file mode 100644 index 0000000..cd3eb21 --- /dev/null +++ b/Swiften/MIX/MIXImpl.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/MIX/MIXImpl.h> + +#include <Swiften/Client/StanzaChannel.h> +#include <Swiften/Elements/IQ.h> +#include <Swiften/Queries/GenericRequest.h> +#include <Swiften/Queries/IQRouter.h> + +namespace Swift { + +MIXImpl::MIXImpl(const JID& ownJID, const JID& channelJID, IQRouter* iqRouter) : ownJID_(ownJID), channelJID_(channelJID), iqRouter_(iqRouter) { + +} + +MIXImpl::~MIXImpl() { + +} + +void MIXImpl::joinChannel(const std::unordered_set<std::string>& nodes) { + joinChannelWithPreferences(nodes, nullptr); +} + +void MIXImpl::joinChannelWithPreferences(const std::unordered_set<std::string>& nodes, Form::ref form) { + auto joinPayload = std::make_shared<MIXJoin>(); + joinPayload->setChannel(channelJID_); + for (auto node : nodes) { + joinPayload->addSubscription(node); + } + if (form) { + joinPayload->setForm(form); + } + auto request = std::make_shared<GenericRequest<MIXJoin>>(IQ::Set, getJID(), joinPayload, iqRouter_); + request->onResponse.connect(boost::bind(&MIXImpl::handleJoinResponse, this, _1, _2)); + request->send(); +} + +void MIXImpl::handleJoinResponse(MIXJoin::ref payload, ErrorPayload::ref error) { + onJoinResponse(payload, error); +} + +void MIXImpl::updateSubscription(const std::unordered_set<std::string>& nodes) { + auto updateSubscriptionPayload = std::make_shared<MIXUpdateSubscription>(); + updateSubscriptionPayload->setSubscriptions(nodes); + auto request = std::make_shared<GenericRequest<MIXUpdateSubscription>>(IQ::Set, channelJID_, updateSubscriptionPayload, iqRouter_); + request->onResponse.connect(boost::bind(&MIXImpl::handleUpdateSubscriptionResponse, this, _1, _2)); + request->send(); +} + +void MIXImpl::handleUpdateSubscriptionResponse(MIXUpdateSubscription::ref payload, ErrorPayload::ref error) { + onSubscriptionUpdateResponse(payload, error); +} + +void MIXImpl::leaveChannel() { + auto leavePayload = std::make_shared<MIXLeave>(); + leavePayload->setChannel(channelJID_); + auto request = std::make_shared<GenericRequest<MIXLeave>>(IQ::Set, getJID(), leavePayload, iqRouter_); + request->onResponse.connect(boost::bind(&MIXImpl::handleLeaveResponse, this, _1, _2)); + request->send(); +} + +void MIXImpl::handleLeaveResponse(MIXLeave::ref payload, ErrorPayload::ref error) { + onLeaveResponse(payload, error); +} + +void MIXImpl::requestPreferencesForm() { + auto prefPayload = std::make_shared<MIXUserPreference>(); + auto request = std::make_shared<GenericRequest<MIXUserPreference>>(IQ::Get, channelJID_, prefPayload, iqRouter_); + request->onResponse.connect(boost::bind(&MIXImpl::handlePreferencesFormReceived, this, _1, _2)); + request->send(); +} + +void MIXImpl::handlePreferencesFormReceived(MIXUserPreference::ref payload, ErrorPayload::ref error) { + Form::ref form = nullptr; + if (payload) { + form = payload->getData(); + } + onPreferencesFormResponse(form, error); +} + +void MIXImpl::handlePreferencesResultReceived(MIXUserPreference::ref payload, ErrorPayload::ref error) { + onPreferencesUpdateResponse(payload, error); +} + +void MIXImpl::updatePreferences(Form::ref form) { + auto prefPayload = std::make_shared<MIXUserPreference>(); + prefPayload->setData(form); + auto request = std::make_shared<GenericRequest<MIXUserPreference>>(IQ::Set, channelJID_, prefPayload, iqRouter_); + request->onResponse.connect(boost::bind(&MIXImpl::handlePreferencesResultReceived, this, _1, _2)); + request->send(); +} + +} diff --git a/Swiften/MIX/MIXImpl.h b/Swiften/MIX/MIXImpl.h new file mode 100644 index 0000000..4da7a62 --- /dev/null +++ b/Swiften/MIX/MIXImpl.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + + /* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#pragma once + +#include <Swiften/MIX/MIX.h> + +namespace Swift { + class StanzaChannel; + class IQRouter; + + class SWIFTEN_API MIXImpl : public MIX { + public: + using ref = std::shared_ptr<MIXImpl>; + + public: + MIXImpl(const JID& ownJID, const JID& channelJID, IQRouter* iqRouter); + virtual ~MIXImpl() override; + + /** + * Returns the (bare) JID of the user. + */ + virtual JID getJID() const { + return ownJID_.toBare(); + } + + /** + * Returns the JID of MIX channel. + */ + virtual JID getChannelJID() const { + return channelJID_; + } + + virtual void joinChannel(const std::unordered_set<std::string>& nodes) override; + + virtual void joinChannelWithPreferences(const std::unordered_set<std::string>& nodes, Form::ref form) override; + + virtual void updateSubscription(const std::unordered_set<std::string>& nodes) override; + + virtual void leaveChannel() override; + + virtual void requestPreferencesForm() override; + + virtual void updatePreferences(Form::ref form) override; + + private: + void handleJoinResponse(MIXJoin::ref, ErrorPayload::ref); + void handleLeaveResponse(MIXLeave::ref, ErrorPayload::ref); + void handleUpdateSubscriptionResponse(MIXUpdateSubscription::ref, ErrorPayload::ref); + void handlePreferencesFormReceived(MIXUserPreference::ref, ErrorPayload::ref); + void handlePreferencesResultReceived(MIXUserPreference::ref /*payload*/, ErrorPayload::ref error); + + private: + JID ownJID_; + JID channelJID_; + IQRouter* iqRouter_; + }; +} diff --git a/Swiften/MIX/UnitTest/MIXImplTest.cpp b/Swiften/MIX/UnitTest/MIXImplTest.cpp new file mode 100644 index 0000000..05dde17 --- /dev/null +++ b/Swiften/MIX/UnitTest/MIXImplTest.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <boost/bind.hpp> + +#include <Swiften/Elements/FormField.h> +#include <Swiften/Client/DummyStanzaChannel.h> +#include <Swiften/MIX/MIXImpl.h> +#include <Swiften/Queries/IQRouter.h> + +using namespace Swift; + +class MIXImplTest : public ::testing::Test { + + protected: + void SetUp() { + ownJID_ = JID("hag66@shakespeare.example/UUID-a1j/7533"); + channelJID_ = JID("coven@mix.shakespeare.example"); + channel_ = new DummyStanzaChannel(); + router_ = new IQRouter(channel_); + successfulJoins_ = 0; + } + + void TearDown() { + delete router_; + delete channel_; + } + + MIX::ref createMIXClient() { + auto mix = std::make_shared<MIXImpl>(ownJID_, channelJID_, router_); + mix->onJoinResponse.connect(boost::bind(&MIXImplTest::handleJoin, this, _1, _2)); + mix->onLeaveResponse.connect(boost::bind(&MIXImplTest::handleLeave, this, _1, _2)); + mix->onSubscriptionUpdateResponse.connect(boost::bind(&MIXImplTest::handleSubscriptionUpdate, this, _1, _2)); + mix->onPreferencesFormResponse.connect(boost::bind(&MIXImplTest::handlePreferencesForm, this, _1, _2)); + return mix; + } + + void handleJoin(MIXJoin::ref joinPayload, ErrorPayload::ref error) { + if (joinPayload) { + ASSERT_FALSE(error); + ASSERT_TRUE(joinPayload->getJID()); + ASSERT_EQ(*joinPayload->getJID(), JID("123456#coven@mix.shakespeare.example")); + if (joinPayload->getForm()) { + preferenceForm_ = joinPayload->getForm(); + } + ++successfulJoins_; + subscribedNodes_ = joinPayload->getSubscriptions(); + } + } + + void handleLeave(MIXLeave::ref leavePayload, ErrorPayload::ref error) { + ASSERT_TRUE(leavePayload); + ASSERT_FALSE(error); + ASSERT_EQ(static_cast<int>(0), subscribedNodes_.size()); + } + + void handleSubscriptionUpdate(MIXUpdateSubscription::ref payload, ErrorPayload::ref error) { + ASSERT_TRUE(payload); + ASSERT_FALSE(error); + if (payload) { + for (auto node : payload->getSubscriptions()) { + subscribedNodes_.insert(node); + } + } + } + + void handlePreferencesForm(Form::ref form, ErrorPayload::ref error) { + ASSERT_FALSE(error); + if (form) { + preferenceForm_ = form; + } + } + + IQ::ref createJoinResult(const std::unordered_set<std::string>& nodes, Form::ref form) { + auto joinResultPayload = std::make_shared<MIXJoin>(); + for (auto node : nodes) { + joinResultPayload->addSubscription(node); + } + if (form) { + joinResultPayload->setForm(form); + } + joinResultPayload->setJID(JID("123456#coven@mix.shakespeare.example")); + return IQ::createResult(ownJID_, channel_->sentStanzas[0]->getTo(), channel_->sentStanzas[0]->getID(), joinResultPayload); + } + + IQ::ref createLeaveResult() { + auto leaveResultPayload = std::make_shared<MIXLeave>(); + return IQ::createResult(ownJID_, channel_->sentStanzas[0]->getTo(), channel_->sentStanzas[0]->getID(), leaveResultPayload); + } + + IQ::ref createError() { + return IQ::createError(ownJID_, channel_->sentStanzas[0]->getTo(), channel_->sentStanzas[0]->getID()); + } + + bool hasSubscription(const std::string& value) { + return std::find(subscribedNodes_.begin(), subscribedNodes_.end(), value) != subscribedNodes_.end(); + } + + JID ownJID_; + JID channelJID_; + DummyStanzaChannel* channel_; + IQRouter* router_; + int successfulJoins_; + Form::ref preferenceForm_; + std::unordered_set<std::string> subscribedNodes_; +}; + +TEST_F(MIXImplTest, testJoinError) { + MIX::ref testling = createMIXClient(); + testling->joinChannel(std::unordered_set<std::string>()); + + ASSERT_EQ(1, static_cast<int>(channel_->sentStanzas.size())); + ASSERT_TRUE(channel_->isRequestAtIndex<MIXJoin>(0, ownJID_.toBare(), IQ::Set)); + + auto iq = channel_->getStanzaAtIndex<IQ>(0); + ASSERT_TRUE(iq); + ASSERT_TRUE(iq->getPayload<MIXJoin>()); + ASSERT_FALSE(iq->getPayload<MIXJoin>()->getForm()); + ASSERT_EQ(static_cast<size_t>(0), iq->getPayload<MIXJoin>()->getSubscriptions().size()); + + channel_->onIQReceived(createError()); + ASSERT_EQ(static_cast<int>(0), successfulJoins_); + ASSERT_EQ(static_cast<int>(0), subscribedNodes_.size()); +} + +TEST_F(MIXImplTest, testJoinWithAllSubscriptions) { + MIX::ref testling = createMIXClient(); + std::unordered_set<std::string> nodes; + nodes.insert(std::string("urn:xmpp:mix:nodes:messages")); + nodes.insert(std::string("urn:xmpp:mix:nodes:presence")); + nodes.insert(std::string("urn:xmpp:mix:nodes:participants")); + nodes.insert(std::string("urn:xmpp:mix:nodes:config")); + + testling->joinChannel(nodes); + + ASSERT_EQ(1, static_cast<int>(channel_->sentStanzas.size())); + ASSERT_TRUE(channel_->isRequestAtIndex<MIXJoin>(0, ownJID_.toBare(), IQ::Set)); + + auto iq = channel_->getStanzaAtIndex<IQ>(0); + ASSERT_TRUE(iq); + ASSERT_TRUE(iq->getPayload<MIXJoin>()); + ASSERT_FALSE(iq->getPayload<MIXJoin>()->getForm()); + ASSERT_EQ(static_cast<size_t>(4), iq->getPayload<MIXJoin>()->getSubscriptions().size()); + + channel_->onIQReceived(createJoinResult(nodes, nullptr)); + ASSERT_EQ(static_cast<int>(1), successfulJoins_); + ASSERT_EQ(static_cast<int>(4), subscribedNodes_.size()); +} + +TEST_F(MIXImplTest, testJoinWithSomeSubscriptions) { + MIX::ref testling = createMIXClient(); + std::unordered_set<std::string> nodes; + nodes.insert(std::string("urn:xmpp:mix:nodes:messages")); + nodes.insert(std::string("urn:xmpp:mix:nodes:presence")); + nodes.insert(std::string("urn:xmpp:mix:nodes:participants")); + nodes.insert(std::string("urn:xmpp:mix:nodes:config")); + + testling->joinChannel(nodes); + + ASSERT_EQ(1, static_cast<int>(channel_->sentStanzas.size())); + ASSERT_TRUE(channel_->isRequestAtIndex<MIXJoin>(0, ownJID_.toBare(), IQ::Set)); + + auto iq = channel_->getStanzaAtIndex<IQ>(0); + ASSERT_TRUE(iq); + ASSERT_TRUE(iq->getPayload<MIXJoin>()); + ASSERT_FALSE(iq->getPayload<MIXJoin>()->getForm()); + ASSERT_EQ(static_cast<size_t>(4), iq->getPayload<MIXJoin>()->getSubscriptions().size()); + + std::unordered_set<std::string> subscribedTo; + subscribedTo.insert(std::string("urn:xmpp:mix:nodes:messages")); + + channel_->onIQReceived(createJoinResult(subscribedTo, nullptr)); + ASSERT_EQ(static_cast<int>(1), successfulJoins_); + ASSERT_EQ(static_cast<int>(1), subscribedNodes_.size()); + ASSERT_TRUE(hasSubscription(std::string("urn:xmpp:mix:nodes:messages"))); +} + +TEST_F(MIXImplTest, testLeaveChannel) { + MIX::ref testling = createMIXClient(); + testling->leaveChannel(); + ASSERT_EQ(1, static_cast<int>(channel_->sentStanzas.size())); + ASSERT_TRUE(channel_->isRequestAtIndex<MIXLeave>(0, ownJID_.toBare(), IQ::Set)); + + auto iq = channel_->getStanzaAtIndex<IQ>(0); + ASSERT_TRUE(iq); + ASSERT_TRUE(iq->getPayload<MIXLeave>()); + ASSERT_TRUE(iq->getPayload<MIXLeave>()->getChannel()); + + channel_->onIQReceived(createLeaveResult()); +} + +TEST_F(MIXImplTest, testUpdateSubscription) { + MIX::ref testling = createMIXClient(); + std::unordered_set<std::string> nodes; + nodes.insert(std::string("urn:xmpp:mix:nodes:messages")); + nodes.insert(std::string("urn:xmpp:mix:nodes:presence")); + + testling->joinChannel(nodes); + + ASSERT_EQ(1, static_cast<int>(channel_->sentStanzas.size())); + ASSERT_TRUE(channel_->isRequestAtIndex<MIXJoin>(0, ownJID_.toBare(), IQ::Set)); + + channel_->onIQReceived(createJoinResult(nodes, nullptr)); + ASSERT_EQ(static_cast<int>(1), successfulJoins_); + ASSERT_EQ(static_cast<int>(2), subscribedNodes_.size()); + + nodes.clear(); + nodes.insert(std::string("urn:xmpp:mix:nodes:participants")); + nodes.insert(std::string("urn:xmpp:mix:nodes:config")); + + testling->updateSubscription(nodes); + + ASSERT_EQ(2, static_cast<int>(channel_->sentStanzas.size())); + ASSERT_TRUE(channel_->isRequestAtIndex<MIXUpdateSubscription>(1, channelJID_, IQ::Set)); + + // fake response + auto subscriptionUpdate = std::make_shared<MIXUpdateSubscription>(); + subscriptionUpdate->setSubscriptions(nodes); + subscriptionUpdate->setJID(JID("hag66@shakespeare.example")); + auto response = IQ::createResult(ownJID_, channel_->sentStanzas[1]->getTo(), channel_->sentStanzas[1]->getID(), subscriptionUpdate); + + channel_->onIQReceived(response); + ASSERT_EQ(static_cast<int>(4), subscribedNodes_.size()); + ASSERT_TRUE(hasSubscription(std::string("urn:xmpp:mix:nodes:participants"))); + ASSERT_TRUE(hasSubscription(std::string("urn:xmpp:mix:nodes:config"))); + ASSERT_TRUE(hasSubscription(std::string("urn:xmpp:mix:nodes:messages"))); +} + +TEST_F(MIXImplTest, testJoinWithPreference) { + MIX::ref testling = createMIXClient(); + std::unordered_set<std::string> nodes; + nodes.insert(std::string("urn:xmpp:mix:nodes:messages")); + nodes.insert(std::string("urn:xmpp:mix:nodes:presence")); + + auto parameters = std::make_shared<Form>(); + parameters->setType(Form::Type::SubmitType); + + auto fieldType = std::make_shared<FormField>(FormField::HiddenType); + fieldType->setName("FORM_TYPE"); + fieldType->addValue("urn:xmpp:mix:0"); + parameters->addField(fieldType); + + auto fieldJIDVisibility = std::make_shared<FormField>(); + fieldJIDVisibility->setName("JID Visibility"); + fieldJIDVisibility->addValue("never"); + parameters->addField(fieldJIDVisibility); + + testling->joinChannelWithPreferences(nodes, parameters); + + ASSERT_EQ(1, static_cast<int>(channel_->sentStanzas.size())); + ASSERT_TRUE(channel_->isRequestAtIndex<MIXJoin>(0, ownJID_.toBare(), IQ::Set)); + + //fake response + auto responseForm = std::make_shared<Form>(); + responseForm->setType(Form::Type::ResultType); + + auto fieldTypeResponse = std::make_shared<FormField>(FormField::HiddenType); + fieldTypeResponse->setName("FORM_TYPE"); + fieldTypeResponse->addValue("urn:xmpp:mix:0"); + responseForm->addField(fieldTypeResponse); + + auto fieldJIDVisibilityResponse = std::make_shared<FormField>(); + fieldJIDVisibilityResponse->setName("JID Visibility"); + fieldJIDVisibilityResponse->addValue("never"); + responseForm->addField(fieldJIDVisibilityResponse); + + auto fieldprivateMessagesResponse = std::make_shared<FormField>(); + fieldprivateMessagesResponse->setName("Private Messages"); + fieldprivateMessagesResponse->addValue("allow"); + responseForm->addField(fieldprivateMessagesResponse); + + auto vCardResponse = std::make_shared<FormField>(); + vCardResponse->setName("vCard"); + vCardResponse->addValue("block"); + responseForm->addField(vCardResponse); + + channel_->onIQReceived(createJoinResult(nodes, responseForm)); + ASSERT_EQ(static_cast<int>(1), successfulJoins_); + ASSERT_EQ(static_cast<int>(2), subscribedNodes_.size()); + ASSERT_TRUE(preferenceForm_); + + ASSERT_TRUE(preferenceForm_->getField("JID Visibility")); + ASSERT_EQ(std::string("never"), preferenceForm_->getField("JID Visibility")->getTextSingleValue()); +} + +TEST_F(MIXImplTest, preferenceFormRequest) { + MIX::ref testling = createMIXClient(); + testling->requestPreferencesForm(); + + ASSERT_EQ(1, static_cast<int>(channel_->sentStanzas.size())); + ASSERT_TRUE(channel_->isRequestAtIndex<MIXUserPreference>(0, channelJID_, IQ::Get)); + + //fake response + auto responseForm = std::make_shared<Form>(); + responseForm->setType(Form::Type::FormType); + + auto fieldTypeResponse = std::make_shared<FormField>(FormField::HiddenType); + fieldTypeResponse->setName("FORM_TYPE"); + fieldTypeResponse->addValue("urn:xmpp:mix:0"); + responseForm->addField(fieldTypeResponse); + + auto preferenceResponse = std::make_shared<MIXUserPreference>(); + preferenceResponse->setData(responseForm); + + channel_->onIQReceived(IQ::createResult(ownJID_, channel_->sentStanzas[0]->getTo(), channel_->sentStanzas[0]->getID(), preferenceResponse)); + ASSERT_TRUE(preferenceForm_); +} diff --git a/Swiften/MUC/MUCBookmarkManager.cpp b/Swiften/MUC/MUCBookmarkManager.cpp index 511c88a..e0922ae 100644 --- a/Swiften/MUC/MUCBookmarkManager.cpp +++ b/Swiften/MUC/MUCBookmarkManager.cpp @@ -1,17 +1,18 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/MUC/MUCBookmarkManager.h> +#include <algorithm> #include <memory> #include <boost/bind.hpp> #include <Swiften/Queries/IQRouter.h> #include <Swiften/Queries/Requests/GetPrivateStorageRequest.h> #include <Swiften/Queries/Requests/SetPrivateStorageRequest.h> namespace Swift { @@ -24,96 +25,122 @@ MUCBookmarkManager::MUCBookmarkManager(IQRouter* iqRouter) { request->send(); } void MUCBookmarkManager::handleBookmarksReceived(std::shared_ptr<Storage> payload, ErrorPayload::ref error) { if (error || !payload) { return; } ready_ = true; + handlingReceivedBookmarks_ = true; onBookmarksReady(); - storage = payload; + storage_ = payload; std::vector<MUCBookmark> receivedBookmarks; for (const auto& room : payload->getRooms()) { receivedBookmarks.push_back(MUCBookmark(room)); } std::vector<MUCBookmark> newBookmarks; for (const auto& oldBookmark : bookmarks_) { if (containsEquivalent(receivedBookmarks, oldBookmark)) { newBookmarks.push_back(oldBookmark); } else { onBookmarkRemoved(oldBookmark); } } - + std::vector<MUCBookmark> newAddedBookmarksToBeSignaled; for (const auto& newBookmark : receivedBookmarks) { if (!containsEquivalent(bookmarks_, newBookmark)) { newBookmarks.push_back(newBookmark); - onBookmarkAdded(newBookmark); + //If the bookmark does not exist in bookmark manager, after emmiting the signal, chatsmanager will try to join the room, if the bookmark has autojoin to true. + //The bookmark is not yet available in bookmark manager, therefore a new bookmark will be created which will be lost when newBookmarks replace bookmarks. + newAddedBookmarksToBeSignaled.push_back(newBookmark); } } bookmarks_ = newBookmarks; + for (auto bookmark : newAddedBookmarksToBeSignaled) { + onBookmarkAdded(bookmark); + } + + handlingReceivedBookmarks_ = false; } bool MUCBookmarkManager::containsEquivalent(const std::vector<MUCBookmark>& list, const MUCBookmark& bookmark) { - return std::find(list.begin(), list.end(), bookmark) != list.end(); + return std::find_if(list.begin(), list.end(), [&](const MUCBookmark& val) { return bookmark.getRoom() == val.getRoom(); }) != list.end(); } void MUCBookmarkManager::replaceBookmark(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark) { if (!ready_) return; for (auto& bookmark : bookmarks_) { if (bookmark == oldBookmark) { bookmark = newBookmark; flush(); onBookmarkRemoved(oldBookmark); onBookmarkAdded(newBookmark); return; } } } void MUCBookmarkManager::addBookmark(const MUCBookmark& bookmark) { if (!ready_) return; - bookmarks_.push_back(bookmark); - onBookmarkAdded(bookmark); + if (auto found = lookupBookmark(bookmark.getRoom())) { + if (found != bookmark) { + replaceBookmark(found.get(), bookmark); + } + } + else { + bookmarks_.push_back(bookmark); + onBookmarkAdded(bookmark); + } flush(); } void MUCBookmarkManager::removeBookmark(const MUCBookmark& bookmark) { if (!ready_) return; std::vector<MUCBookmark>::iterator it; for (it = bookmarks_.begin(); it != bookmarks_.end(); ++it) { if ((*it) == bookmark) { bookmarks_.erase(it); onBookmarkRemoved(bookmark); break; } } flush(); } void MUCBookmarkManager::flush() { - if (!storage) { - storage = std::make_shared<Storage>(); + if (handlingReceivedBookmarks_) { + return; + } + if (!storage_) { + storage_ = std::make_shared<Storage>(); } // Update the storage element - storage->clearRooms(); + storage_->clearRooms(); for (const auto& bookmark : bookmarks_) { - storage->addRoom(bookmark.toStorage()); + storage_->addRoom(bookmark.toStorage()); } // Send an iq to save the storage element - SetPrivateStorageRequest<Storage>::ref request = SetPrivateStorageRequest<Storage>::create(storage, iqRouter_); + SetPrivateStorageRequest<Storage>::ref request = SetPrivateStorageRequest<Storage>::create(storage_, iqRouter_); // FIXME: We should care about the result //request->onResponse.connect(boost::bind(&MUCBookmarkManager::handleBookmarksSet, this, _1, _2)); request->send(); } const std::vector<MUCBookmark>& MUCBookmarkManager::getBookmarks() const { return bookmarks_; } +boost::optional<MUCBookmark> MUCBookmarkManager::lookupBookmark(const JID& bookmarkJID) const { + auto bookmarkIterator = std::find_if(bookmarks_.begin(), bookmarks_.end(), [&](const MUCBookmark& val) { return bookmarkJID == val.getRoom(); }); + if (bookmarkIterator != bookmarks_.end()) { + return *bookmarkIterator; + } + return boost::none; +} + } diff --git a/Swiften/MUC/MUCBookmarkManager.h b/Swiften/MUC/MUCBookmarkManager.h index 78fbbb0..1ef227d 100644 --- a/Swiften/MUC/MUCBookmarkManager.h +++ b/Swiften/MUC/MUCBookmarkManager.h @@ -21,32 +21,33 @@ namespace Swift { class IQRouter; class SWIFTEN_API MUCBookmarkManager { public: MUCBookmarkManager(IQRouter* iqRouter); void addBookmark(const MUCBookmark& bookmark); void removeBookmark(const MUCBookmark& bookmark); void replaceBookmark(const MUCBookmark& oldBookmark, const MUCBookmark& newBookmark); - const std::vector<MUCBookmark>& getBookmarks() const; + boost::optional<MUCBookmark> lookupBookmark(const JID& bookmarkJID) const; public: boost::signals2::signal<void (const MUCBookmark&)> onBookmarkAdded; boost::signals2::signal<void (const MUCBookmark&)> onBookmarkRemoved; /** * When server bookmarks are ready to be used (request response has been received). */ boost::signals2::signal<void ()> onBookmarksReady; private: bool containsEquivalent(const std::vector<MUCBookmark>& list, const MUCBookmark& bookmark); void handleBookmarksReceived(std::shared_ptr<Storage> payload, ErrorPayload::ref error); void flush(); private: bool ready_; + bool handlingReceivedBookmarks_; std::vector<MUCBookmark> bookmarks_; IQRouter* iqRouter_; - std::shared_ptr<Storage> storage; + std::shared_ptr<Storage> storage_; }; } diff --git a/Swiften/MUC/MUCImpl.cpp b/Swiften/MUC/MUCImpl.cpp index 029bb4b..d2b33f3 100644 --- a/Swiften/MUC/MUCImpl.cpp +++ b/Swiften/MUC/MUCImpl.cpp @@ -365,19 +365,19 @@ void MUCImpl::requestAffiliationList(MUCOccupant::Affiliation affiliation) { } /** * Must be called with the real JID, not the room JID. */ void MUCImpl::changeAffiliation(const JID& jid, MUCOccupant::Affiliation affiliation) { MUCAdminPayload::ref mucPayload = std::make_shared<MUCAdminPayload>(); MUCItem item; item.affiliation = affiliation; - item.realJID = jid.toBare(); + item.realJID = jid; mucPayload->addItem(item); std::shared_ptr<GenericRequest<MUCAdminPayload> > request = std::make_shared<GenericRequest<MUCAdminPayload> >(IQ::Set, getJID(), mucPayload, iqRouter_); request->onResponse.connect(boost::bind(&MUCImpl::handleAffiliationChangeResponse, this, _1, _2, jid, affiliation)); request->send(); } void MUCImpl::handleAffiliationListResponse(MUCAdminPayload::ref payload, ErrorPayload::ref error, MUCOccupant::Affiliation affiliation) { if (error) { onAffiliationListFailed(error); diff --git a/Swiften/Network/BOSHConnection.cpp b/Swiften/Network/BOSHConnection.cpp index b4ffa7d..aaec9f2 100644 --- a/Swiften/Network/BOSHConnection.cpp +++ b/Swiften/Network/BOSHConnection.cpp @@ -1,17 +1,17 @@ /* * Copyright (c) 2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2011-2017 Isode Limited. + * Copyright (c) 2011-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/BOSHConnection.h> #include <string> #include <thread> @@ -21,34 +21,36 @@ #include <Swiften/Base/ByteArray.h> #include <Swiften/Base/Concat.h> #include <Swiften/Base/Log.h> #include <Swiften/Base/String.h> #include <Swiften/Network/HostAddressPort.h> #include <Swiften/Parser/BOSHBodyExtractor.h> #include <Swiften/StreamStack/DummyStreamLayer.h> #include <Swiften/StreamStack/TLSLayer.h> #include <Swiften/TLS/TLSContext.h> +#include <Swiften/TLS/TLSContextFactory.h> #include <Swiften/TLS/TLSOptions.h> namespace Swift { BOSHConnection::BOSHConnection(const URL& boshURL, Connector::ref connector, XMLParserFactory* parserFactory, TLSContextFactory* tlsContextFactory, const TLSOptions& tlsOptions) : boshURL_(boshURL), connector_(connector), parserFactory_(parserFactory), sid_(), waitingForStartResponse_(false), rid_(~0ULL), pending_(false), connectionReady_(false) { if (boshURL_.getScheme() == "https") { - tlsLayer_ = std::make_shared<TLSLayer>(tlsContextFactory, tlsOptions); + auto tlsContext = tlsContextFactory->createTLSContext(tlsOptions); + tlsLayer_ = std::make_shared<TLSLayer>(std::move(tlsContext)); // The following dummyLayer_ is needed as the TLSLayer will pass the decrypted data to its parent layer. // The dummyLayer_ will serve as the parent layer. dummyLayer_ = std::make_shared<DummyStreamLayer>(tlsLayer_.get()); } } BOSHConnection::~BOSHConnection() { cancelConnector(); if (connection_) { @@ -85,20 +87,20 @@ void BOSHConnection::handleTLSNetowrkDataWriteRequest(const SafeByteArray& data) SWIFT_LOG(debug) << std::endl; connection_->write(data); } void BOSHConnection::handleRawDataRead(std::shared_ptr<SafeByteArray> data) { SWIFT_LOG(debug) << std::endl; tlsLayer_->handleDataRead(*data.get()); } -void BOSHConnection::handleTLSError(std::shared_ptr<TLSError> /* error */) { - +void BOSHConnection::handleTLSError(std::shared_ptr<TLSError> error) { + SWIFT_LOG(debug) << (error ? error->getMessage() : "Unknown TLS error") << std::endl; } void BOSHConnection::writeData(const SafeByteArray& data) { if (tlsLayer_) { tlsLayer_->writeData(data); } else { connection_->write(data); } diff --git a/Swiften/Network/BoostConnection.cpp b/Swiften/Network/BoostConnection.cpp index 0de7b25..551363d 100644 --- a/Swiften/Network/BoostConnection.cpp +++ b/Swiften/Network/BoostConnection.cpp @@ -1,26 +1,25 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/BoostConnection.h> #include <algorithm> #include <memory> #include <mutex> #include <string> #include <boost/asio/placeholders.hpp> #include <boost/asio/write.hpp> #include <boost/bind.hpp> -#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/Algorithm.h> #include <Swiften/Base/ByteArray.h> #include <Swiften/Base/Log.h> #include <Swiften/Base/SafeAllocator.h> #include <Swiften/Base/sleep.h> #include <Swiften/EventLoop/EventLoop.h> #include <Swiften/Network/HostAddressPort.h> @@ -58,19 +57,19 @@ BoostConnection::BoostConnection(std::shared_ptr<boost::asio::io_service> ioServ BoostConnection::~BoostConnection() { } void BoostConnection::listen() { doRead(); } void BoostConnection::connect(const HostAddressPort& addressPort) { boost::asio::ip::tcp::endpoint endpoint( - boost::asio::ip::address::from_string(addressPort.getAddress().toString()), boost::numeric_cast<unsigned short>(addressPort.getPort())); + boost::asio::ip::address::from_string(addressPort.getAddress().toString()), addressPort.getPort()); socket_.async_connect( endpoint, boost::bind(&BoostConnection::handleConnectFinished, shared_from_this(), boost::asio::placeholders::error)); } void BoostConnection::disconnect() { //MainEventLoop::removeEventsFromOwner(shared_from_this()); // Mac OS X apparently exhibits a problem where closing a socket during a write could potentially go into uninterruptable sleep. diff --git a/Swiften/Network/BoostConnectionServer.cpp b/Swiften/Network/BoostConnectionServer.cpp index 34b5799..8db9656 100644 --- a/Swiften/Network/BoostConnectionServer.cpp +++ b/Swiften/Network/BoostConnectionServer.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/BoostConnectionServer.h> #include <boost/asio/ip/v6_only.hpp> #include <boost/asio/placeholders.hpp> #include <boost/bind.hpp> @@ -13,57 +13,60 @@ #include <boost/optional.hpp> #include <boost/system/error_code.hpp> #include <boost/system/system_error.hpp> #include <Swiften/Base/Log.h> #include <Swiften/EventLoop/EventLoop.h> namespace Swift { -BoostConnectionServer::BoostConnectionServer(int port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : port_(port), ioService_(ioService), eventLoop(eventLoop), acceptor_(nullptr) { +BoostConnectionServer::BoostConnectionServer(unsigned short port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : port_(port), ioService_(ioService), eventLoop(eventLoop), acceptor_(nullptr) { } -BoostConnectionServer::BoostConnectionServer(const HostAddress &address, int port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : address_(address), port_(port), ioService_(ioService), eventLoop(eventLoop), acceptor_(nullptr) { +BoostConnectionServer::BoostConnectionServer(const HostAddress &address, unsigned short port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : address_(address), port_(port), ioService_(ioService), eventLoop(eventLoop), acceptor_(nullptr) { } void BoostConnectionServer::start() { boost::optional<Error> error = tryStart(); if (error) { eventLoop->postEvent(boost::bind(boost::ref(onStopped), *error), shared_from_this()); } } boost::optional<BoostConnectionServer::Error> BoostConnectionServer::tryStart() { try { assert(!acceptor_); boost::asio::ip::tcp::endpoint endpoint; if (address_.isValid()) { - endpoint = boost::asio::ip::tcp::endpoint(address_.getRawAddress(), boost::numeric_cast<unsigned short>(port_)); + endpoint = boost::asio::ip::tcp::endpoint(address_.getRawAddress(), port_); } else { - endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), boost::numeric_cast<unsigned short>(port_)); + endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), port_); } acceptor_ = new boost::asio::ip::tcp::acceptor(*ioService_, endpoint); if (endpoint.protocol() == boost::asio::ip::tcp::v6()) { boost::system::error_code ec; acceptor_->set_option(boost::asio::ip::v6_only(false), ec); SWIFT_LOG_ASSERT(ec, warning) << "IPv4/IPv6 dual-stack support is not supported on this platform." << std::endl; } acceptNextConnection(); } catch (const boost::system::system_error& e) { if (e.code() == boost::asio::error::address_in_use) { return Conflict; } else { return UnknownError; } } + catch (const boost::numeric::bad_numeric_cast&) { + return UnknownError; + } return boost::optional<Error>(); } void BoostConnectionServer::stop() { stop(boost::optional<Error>()); } void BoostConnectionServer::stop(boost::optional<Error> e) { diff --git a/Swiften/Network/BoostConnectionServer.h b/Swiften/Network/BoostConnectionServer.h index 3dd9830..917d638 100644 --- a/Swiften/Network/BoostConnectionServer.h +++ b/Swiften/Network/BoostConnectionServer.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <boost/asio/io_service.hpp> @@ -17,41 +17,41 @@ #include <Swiften/EventLoop/EventOwner.h> #include <Swiften/Network/BoostConnection.h> #include <Swiften/Network/ConnectionServer.h> namespace Swift { class SWIFTEN_API BoostConnectionServer : public ConnectionServer, public EventOwner, public std::enable_shared_from_this<BoostConnectionServer> { public: typedef std::shared_ptr<BoostConnectionServer> ref; - static ref create(int port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) { + static ref create(unsigned short port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) { return ref(new BoostConnectionServer(port, ioService, eventLoop)); } - static ref create(const HostAddress &address, int port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) { + static ref create(const HostAddress &address, unsigned short port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) { return ref(new BoostConnectionServer(address, port, ioService, eventLoop)); } virtual boost::optional<Error> tryStart(); // FIXME: This should become the new start virtual void start(); virtual void stop(); virtual HostAddressPort getAddressPort() const; boost::signals2::signal<void (boost::optional<Error>)> onStopped; private: - BoostConnectionServer(int port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); - BoostConnectionServer(const HostAddress &address, int port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); + BoostConnectionServer(unsigned short port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); + BoostConnectionServer(const HostAddress &address, unsigned short port, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop); void stop(boost::optional<Error> e); void acceptNextConnection(); void handleAccept(std::shared_ptr<BoostConnection> newConnection, const boost::system::error_code& error); private: HostAddress address_; - int port_; + unsigned short port_; std::shared_ptr<boost::asio::io_service> ioService_; EventLoop* eventLoop; boost::asio::ip::tcp::acceptor* acceptor_; }; } diff --git a/Swiften/Network/BoostConnectionServerFactory.cpp b/Swiften/Network/BoostConnectionServerFactory.cpp index 8b3fd2f..6936453 100644 --- a/Swiften/Network/BoostConnectionServerFactory.cpp +++ b/Swiften/Network/BoostConnectionServerFactory.cpp @@ -13,18 +13,18 @@ #include <Swiften/Network/BoostConnectionServerFactory.h> #include <Swiften/Network/BoostConnectionServer.h> namespace Swift { BoostConnectionServerFactory::BoostConnectionServerFactory(std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : ioService(ioService), eventLoop(eventLoop) { } -std::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(int port) { +std::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(unsigned short port) { return BoostConnectionServer::create(port, ioService, eventLoop); } -std::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(const Swift::HostAddress &hostAddress, int port) { +std::shared_ptr<ConnectionServer> BoostConnectionServerFactory::createConnectionServer(const Swift::HostAddress &hostAddress, unsigned short port) { return BoostConnectionServer::create(hostAddress, port, ioService, eventLoop); } } diff --git a/Swiften/Network/BoostConnectionServerFactory.h b/Swiften/Network/BoostConnectionServerFactory.h index 033e63d..956132b 100644 --- a/Swiften/Network/BoostConnectionServerFactory.h +++ b/Swiften/Network/BoostConnectionServerFactory.h @@ -1,17 +1,17 @@ /* * Copyright (c) 2011 Jan Kaluza * Licensed under the Simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/asio/io_service.hpp> #include <Swiften/Base/API.h> @@ -19,18 +19,18 @@ #include <Swiften/Network/ConnectionServerFactory.h> namespace Swift { class ConnectionServer; class SWIFTEN_API BoostConnectionServerFactory : public ConnectionServerFactory { public: BoostConnectionServerFactory(std::shared_ptr<boost::asio::io_service>, EventLoop* eventLoop); - virtual std::shared_ptr<ConnectionServer> createConnectionServer(int port); + virtual std::shared_ptr<ConnectionServer> createConnectionServer(unsigned short port); - virtual std::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress &hostAddress, int port); + virtual std::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress &hostAddress, unsigned short port); private: std::shared_ptr<boost::asio::io_service> ioService; EventLoop* eventLoop; }; } diff --git a/Swiften/Network/BoostNetworkFactories.h b/Swiften/Network/BoostNetworkFactories.h index 72afb04..2bf8d33 100644 --- a/Swiften/Network/BoostNetworkFactories.h +++ b/Swiften/Network/BoostNetworkFactories.h @@ -1,84 +1,83 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Network/BoostIOServiceThread.h> #include <Swiften/Network/NetworkFactories.h> namespace Swift { class EventLoop; class NATTraverser; class PlatformTLSFactories; class SWIFTEN_API BoostNetworkFactories : public NetworkFactories { public: /** * Construct the network factories, using the provided EventLoop. * @param ioService If this optional parameter is provided, it will be * used for the construction of the BoostIOServiceThread. */ BoostNetworkFactories(EventLoop* eventLoop, std::shared_ptr<boost::asio::io_service> ioService = std::shared_ptr<boost::asio::io_service>()); - virtual ~BoostNetworkFactories(); + virtual ~BoostNetworkFactories() override; - virtual TimerFactory* getTimerFactory() const SWIFTEN_OVERRIDE { + virtual TimerFactory* getTimerFactory() const override { return timerFactory; } - virtual ConnectionFactory* getConnectionFactory() const SWIFTEN_OVERRIDE { + virtual ConnectionFactory* getConnectionFactory() const override { return connectionFactory; } BoostIOServiceThread* getIOServiceThread() { return &ioServiceThread; } - DomainNameResolver* getDomainNameResolver() const SWIFTEN_OVERRIDE { + DomainNameResolver* getDomainNameResolver() const override { return domainNameResolver; } - ConnectionServerFactory* getConnectionServerFactory() const SWIFTEN_OVERRIDE { + ConnectionServerFactory* getConnectionServerFactory() const override { return connectionServerFactory; } - NetworkEnvironment* getNetworkEnvironment() const SWIFTEN_OVERRIDE { + NetworkEnvironment* getNetworkEnvironment() const override { return networkEnvironment; } - NATTraverser* getNATTraverser() const SWIFTEN_OVERRIDE { + NATTraverser* getNATTraverser() const override { return natTraverser; } - virtual XMLParserFactory* getXMLParserFactory() const SWIFTEN_OVERRIDE { + virtual XMLParserFactory* getXMLParserFactory() const override { return xmlParserFactory; } - virtual TLSContextFactory* getTLSContextFactory() const SWIFTEN_OVERRIDE; + virtual TLSContextFactory* getTLSContextFactory() const override; - virtual ProxyProvider* getProxyProvider() const SWIFTEN_OVERRIDE { + virtual ProxyProvider* getProxyProvider() const override { return proxyProvider; } - virtual EventLoop* getEventLoop() const SWIFTEN_OVERRIDE { + virtual EventLoop* getEventLoop() const override { return eventLoop; } - virtual IDNConverter* getIDNConverter() const SWIFTEN_OVERRIDE { + virtual IDNConverter* getIDNConverter() const override { return idnConverter; } - virtual CryptoProvider* getCryptoProvider() const SWIFTEN_OVERRIDE { + virtual CryptoProvider* getCryptoProvider() const override { return cryptoProvider; } private: BoostIOServiceThread ioServiceThread; TimerFactory* timerFactory; ConnectionFactory* connectionFactory; DomainNameResolver* domainNameResolver; ConnectionServerFactory* connectionServerFactory; diff --git a/Swiften/Network/ChainedConnector.cpp b/Swiften/Network/ChainedConnector.cpp index ea55db3..94899ad 100644 --- a/Swiften/Network/ChainedConnector.cpp +++ b/Swiften/Network/ChainedConnector.cpp @@ -1,30 +1,30 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/ChainedConnector.h> #include <typeinfo> #include <boost/bind.hpp> #include <Swiften/Base/Log.h> #include <Swiften/Network/ConnectionFactory.h> #include <Swiften/Network/Connector.h> using namespace Swift; ChainedConnector::ChainedConnector( const std::string& hostname, - int port, + unsigned short port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver* resolver, const std::vector<ConnectionFactory*>& connectionFactories, TimerFactory* timerFactory) : hostname(hostname), port(port), serviceLookupPrefix(serviceLookupPrefix), resolver(resolver), connectionFactories(connectionFactories), diff --git a/Swiften/Network/ChainedConnector.h b/Swiften/Network/ChainedConnector.h index a00d7e5..9620293 100644 --- a/Swiften/Network/ChainedConnector.h +++ b/Swiften/Network/ChainedConnector.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <deque> #include <memory> #include <string> @@ -20,35 +20,35 @@ namespace Swift { class Connection; class Connector; class ConnectionFactory; class TimerFactory; class DomainNameResolver; class SWIFTEN_API ChainedConnector { public: - ChainedConnector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, const std::vector<ConnectionFactory*>&, TimerFactory*); + ChainedConnector(const std::string& hostname, unsigned short port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, const std::vector<ConnectionFactory*>&, TimerFactory*); ~ChainedConnector(); void setTimeoutMilliseconds(int milliseconds); void start(); void stop(); boost::signals2::signal<void (std::shared_ptr<Connection>, std::shared_ptr<Error>)> onConnectFinished; private: void finish(std::shared_ptr<Connection> connection, std::shared_ptr<Error>); void tryNextConnectionFactory(); void handleConnectorFinished(std::shared_ptr<Connection>, std::shared_ptr<Error>); private: std::string hostname; - int port; + unsigned short port; boost::optional<std::string> serviceLookupPrefix; DomainNameResolver* resolver; std::vector<ConnectionFactory*> connectionFactories; TimerFactory* timerFactory; int timeoutMilliseconds; std::deque<ConnectionFactory*> connectionFactoryQueue; std::shared_ptr<Connector> currentConnector; std::shared_ptr<Error> lastError; }; diff --git a/Swiften/Network/ConnectionServerFactory.h b/Swiften/Network/ConnectionServerFactory.h index 413131e..2ebccc1 100644 --- a/Swiften/Network/ConnectionServerFactory.h +++ b/Swiften/Network/ConnectionServerFactory.h @@ -1,31 +1,31 @@ /* * Copyright (c) 2011 Jan Kaluza * Licensed under the Simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> namespace Swift { class ConnectionServer; class HostAddress; class SWIFTEN_API ConnectionServerFactory { public: virtual ~ConnectionServerFactory(); - virtual std::shared_ptr<ConnectionServer> createConnectionServer(int port) = 0; + virtual std::shared_ptr<ConnectionServer> createConnectionServer(unsigned short port) = 0; - virtual std::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) = 0; + virtual std::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, unsigned short port) = 0; }; } diff --git a/Swiften/Network/Connector.cpp b/Swiften/Network/Connector.cpp index 5eddaba..a0e6b23 100644 --- a/Swiften/Network/Connector.cpp +++ b/Swiften/Network/Connector.cpp @@ -11,37 +11,37 @@ #include <Swiften/Base/Log.h> #include <Swiften/Network/ConnectionFactory.h> #include <Swiften/Network/DomainNameAddressQuery.h> #include <Swiften/Network/DomainNameResolver.h> #include <Swiften/Network/HostAddress.h> #include <Swiften/Network/TimerFactory.h> namespace Swift { -Connector::Connector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) : hostname(hostname), port(port), serviceLookupPrefix(serviceLookupPrefix), resolver(resolver), connectionFactory(connectionFactory), timerFactory(timerFactory), timeoutMilliseconds(0), queriedAllServices(true), foundSomeDNS(false) { +Connector::Connector(const std::string& hostname, unsigned short port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) : hostname(hostname), port(port), serviceLookupPrefix(serviceLookupPrefix), resolver(resolver), connectionFactory(connectionFactory), timerFactory(timerFactory), timeoutMilliseconds(0), queriedAllServices(true), foundSomeDNS(false) { } void Connector::setTimeoutMilliseconds(int milliseconds) { timeoutMilliseconds = milliseconds; } void Connector::start() { SWIFT_LOG(debug) << "Starting connector for " << hostname << std::endl; assert(!currentConnection); assert(!serviceQuery); assert(!timer); - queriedAllServices = false; auto hostAddress = HostAddress::fromString(hostname); if (timeoutMilliseconds > 0) { timer = timerFactory->createTimer(timeoutMilliseconds); timer->onTick.connect(boost::bind(&Connector::handleTimeout, shared_from_this())); } if (serviceLookupPrefix) { + queriedAllServices = false; serviceQuery = resolver->createServiceQuery(*serviceLookupPrefix, hostname); serviceQuery->onResult.connect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1)); serviceQuery->run(); } else if (hostAddress) { // hostname is already a valid address; skip name lookup. foundSomeDNS = true; addressQueryResults.push_back(hostAddress.get()); tryNextAddress(); @@ -116,19 +116,19 @@ void Connector::tryNextAddress() { serviceQueryResults.pop_front(); } tryNextServiceOrFallback(); } else { SWIFT_LOG(debug) << "Trying next address" << std::endl; HostAddress address = addressQueryResults.front(); addressQueryResults.pop_front(); - int connectPort = (port == -1 ? 5222 : port); + unsigned short connectPort = (port == 0 ? 5222 : port); if (!serviceQueryResults.empty()) { connectPort = serviceQueryResults.front().port; } tryConnect(HostAddressPort(address, connectPort)); } } void Connector::tryConnect(const HostAddressPort& target) { diff --git a/Swiften/Network/Connector.h b/Swiften/Network/Connector.h index d8a1b88..c76a4af 100644 --- a/Swiften/Network/Connector.h +++ b/Swiften/Network/Connector.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <deque> #include <memory> #include <string> @@ -24,52 +24,52 @@ namespace Swift { class DomainNameAddressQuery; class DomainNameResolver; class ConnectionFactory; class TimerFactory; class SWIFTEN_API Connector : public boost::signals2::trackable, public std::enable_shared_from_this<Connector> { public: typedef std::shared_ptr<Connector> ref; - static Connector::ref create(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) { + static Connector::ref create(const std::string& hostname, unsigned short port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory) { return ref(new Connector(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory)); } void setTimeoutMilliseconds(int milliseconds); /** * Start the connection attempt. * Note that after calling this method, the caller is responsible for calling #stop() * if it wants to cancel it. Not doing so can leak references. */ void start(); void stop(); boost::signals2::signal<void (std::shared_ptr<Connection>, std::shared_ptr<Error>)> onConnectFinished; private: - Connector(const std::string& hostname, int port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, ConnectionFactory*, TimerFactory*); + Connector(const std::string& hostname, unsigned short port, const boost::optional<std::string>& serviceLookupPrefix, DomainNameResolver*, ConnectionFactory*, TimerFactory*); void handleServiceQueryResult(const std::vector<DomainNameServiceQuery::Result>& result); void handleAddressQueryResult(const std::vector<HostAddress>& address, boost::optional<DomainNameResolveError> error); void queryAddress(const std::string& hostname); void tryNextServiceOrFallback(); void tryNextAddress(); void tryConnect(const HostAddressPort& target); void handleConnectionConnectFinished(bool error); void finish(std::shared_ptr<Connection>); void handleTimeout(); private: std::string hostname; - int port; + unsigned short port; boost::optional<std::string> serviceLookupPrefix; DomainNameResolver* resolver; ConnectionFactory* connectionFactory; TimerFactory* timerFactory; int timeoutMilliseconds; std::shared_ptr<Timer> timer; std::shared_ptr<DomainNameServiceQuery> serviceQuery; std::deque<DomainNameServiceQuery::Result> serviceQueryResults; std::shared_ptr<DomainNameAddressQuery> addressQuery; diff --git a/Swiften/Network/DomainNameServiceQuery.cpp b/Swiften/Network/DomainNameServiceQuery.cpp index 708bbce..5784dd7 100644 --- a/Swiften/Network/DomainNameServiceQuery.cpp +++ b/Swiften/Network/DomainNameServiceQuery.cpp @@ -1,31 +1,27 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/DomainNameServiceQuery.h> #include <cassert> #include <functional> #include <iterator> #include <numeric> -#include <boost/lambda/bind.hpp> -#include <boost/lambda/lambda.hpp> #include <boost/numeric/conversion/cast.hpp> -#include <boost/typeof/typeof.hpp> #include <Swiften/Base/RandomGenerator.h> using namespace Swift; -namespace lambda = boost::lambda; namespace { struct ResultPriorityComparator { bool operator()(const DomainNameServiceQuery::Result& a, const DomainNameServiceQuery::Result& b) const { return a.priority < b.priority; } }; } @@ -37,30 +33,36 @@ DomainNameServiceQuery::~DomainNameServiceQuery() { void DomainNameServiceQuery::sortResults(std::vector<DomainNameServiceQuery::Result>& queries, RandomGenerator& generator) { ResultPriorityComparator comparator; std::stable_sort(queries.begin(), queries.end(), comparator); std::vector<DomainNameServiceQuery::Result>::iterator i = queries.begin(); while (i != queries.end()) { std::vector<DomainNameServiceQuery::Result>::iterator next = std::upper_bound(i, queries.end(), *i, comparator); if (std::distance(i, next) > 1) { std::vector<int> weights; - std::transform(i, next, std::back_inserter(weights), - /* easy hack to account for '0' weights getting at least some weight */ - lambda::bind(&Result::weight, lambda::_1) + 1); - for (int j = 0; j < boost::numeric_cast<int>(weights.size() - 1); ++j) { - std::vector<int> cumulativeWeights; - std::partial_sum( - weights.begin() + j, - weights.end(), - std::back_inserter(cumulativeWeights)); - int randomNumber = generator.generateRandomInteger(cumulativeWeights.back()); - BOOST_AUTO(selectedIndex, std::lower_bound(cumulativeWeights.begin(), cumulativeWeights.end(), randomNumber) - cumulativeWeights.begin()); - std::swap(i[j], i[j + selectedIndex]); - std::swap(weights.begin()[j], weights.begin()[j + selectedIndex]); + std::transform(i, next, std::back_inserter(weights), [](const DomainNameServiceQuery::Result& result) { + /* easy hack to account for '0' weights getting at least some weight */ + return result.weight + 1; + }); + try { + for (int j = 0; j < boost::numeric_cast<int>(weights.size()) - 1; ++j) { + std::vector<int> cumulativeWeights; + std::partial_sum( + weights.begin() + j, + weights.end(), + std::back_inserter(cumulativeWeights)); + int randomNumber = generator.generateRandomInteger(cumulativeWeights.back()); + auto selectedIndex = std::lower_bound(cumulativeWeights.begin(), cumulativeWeights.end(), randomNumber) - cumulativeWeights.begin(); + std::swap(i[j], i[j + selectedIndex]); + std::swap(weights.begin()[j], weights.begin()[j + selectedIndex]); + } + } + catch (const boost::numeric::bad_numeric_cast&) { + // In the unlikely event of weights.size() being too large, use the list as-is. } } i = next; } } } diff --git a/Swiften/Network/DomainNameServiceQuery.h b/Swiften/Network/DomainNameServiceQuery.h index b27f32e..1631b99 100644 --- a/Swiften/Network/DomainNameServiceQuery.h +++ b/Swiften/Network/DomainNameServiceQuery.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <vector> @@ -18,21 +18,21 @@ namespace Swift { class RandomGenerator; class SWIFTEN_API DomainNameServiceQuery { public: typedef std::shared_ptr<DomainNameServiceQuery> ref; struct Result { - Result(const std::string& hostname = "", int port = -1, int priority = -1, int weight = -1) : hostname(hostname), port(port), priority(priority), weight(weight) {} + Result(const std::string& hostname = "", unsigned short port = 0, int priority = -1, int weight = -1) : hostname(hostname), port(port), priority(priority), weight(weight) {} std::string hostname; - int port; + unsigned short port; int priority; int weight; }; virtual ~DomainNameServiceQuery(); virtual void run() = 0; static void sortResults(std::vector<DomainNameServiceQuery::Result>& queries, RandomGenerator& generator); diff --git a/Swiften/Network/DummyConnectionServer.h b/Swiften/Network/DummyConnectionServer.h index 970cbb7..a4fd07f 100644 --- a/Swiften/Network/DummyConnectionServer.h +++ b/Swiften/Network/DummyConnectionServer.h @@ -1,30 +1,30 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> #include <Swiften/EventLoop/EventLoop.h> #include <Swiften/EventLoop/EventOwner.h> #include <Swiften/Network/ConnectionServer.h> #include <Swiften/Network/HostAddressPort.h> namespace Swift { class SWIFTEN_API DummyConnectionServer : public ConnectionServer, public EventOwner, public std::enable_shared_from_this<DummyConnectionServer> { public: - DummyConnectionServer(EventLoop* /*eventLoop*/, int port) : localAddressPort(HostAddress(), port) {} - DummyConnectionServer(EventLoop* /*eventLoop*/, const Swift::HostAddress& hostAddress, int port) : localAddressPort(hostAddress, port) {} + DummyConnectionServer(EventLoop* /*eventLoop*/, unsigned short port) : localAddressPort(HostAddress(), port) {} + DummyConnectionServer(EventLoop* /*eventLoop*/, const Swift::HostAddress& hostAddress, unsigned short port) : localAddressPort(hostAddress, port) {} virtual ~DummyConnectionServer() {} virtual HostAddressPort getAddressPort() const { return localAddressPort; } virtual boost::optional<Error> tryStart() { return boost::optional<Error>(); } diff --git a/Swiften/Network/DummyConnectionServerFactory.h b/Swiften/Network/DummyConnectionServerFactory.h index 822f95f..4b25118 100644 --- a/Swiften/Network/DummyConnectionServerFactory.h +++ b/Swiften/Network/DummyConnectionServerFactory.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Network/ConnectionServerFactory.h> @@ -14,22 +14,22 @@ namespace Swift { class EventLoop; class DummyConnectionServerFactory : public ConnectionServerFactory { public: DummyConnectionServerFactory(EventLoop* eventLoop) : eventLoop(eventLoop) {} virtual ~DummyConnectionServerFactory() {} - virtual std::shared_ptr<ConnectionServer> createConnectionServer(int port) { + virtual std::shared_ptr<ConnectionServer> createConnectionServer(unsigned short port) { return std::make_shared<DummyConnectionServer>(eventLoop, port); } - virtual std::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, int port) { + virtual std::shared_ptr<ConnectionServer> createConnectionServer(const Swift::HostAddress& hostAddress, unsigned short port) { return std::make_shared<DummyConnectionServer>(eventLoop, hostAddress, port); } private: EventLoop* eventLoop; }; } diff --git a/Swiften/Network/EnvironmentProxyProvider.cpp b/Swiften/Network/EnvironmentProxyProvider.cpp index 8edb136..65cf4ff 100644 --- a/Swiften/Network/EnvironmentProxyProvider.cpp +++ b/Swiften/Network/EnvironmentProxyProvider.cpp @@ -11,18 +11,20 @@ */ #include <Swiften/Network/EnvironmentProxyProvider.h> #include <stdio.h> #include <stdlib.h> #include <iostream> +#include <boost/numeric/conversion/cast.hpp> + #include <Swiften/Base/Log.h> namespace Swift { EnvironmentProxyProvider::EnvironmentProxyProvider() { socksProxy = getFromEnv("all_proxy", "socks"); httpProxy = getFromEnv("http_proxy", "http"); SWIFT_LOG(debug) << "Environment: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl; } @@ -32,25 +34,29 @@ HostAddressPort EnvironmentProxyProvider::getHTTPConnectProxy() const { } HostAddressPort EnvironmentProxyProvider::getSOCKS5Proxy() const { return socksProxy; } HostAddressPort EnvironmentProxyProvider::getFromEnv(const char* envVarName, std::string proxyProtocol) { char* envVar = nullptr; std::string address; - int port = 0; + unsigned short port = 0; envVar = getenv(envVarName); proxyProtocol += "://"; address = envVar != nullptr ? envVar : "0.0.0.0"; if(envVar != nullptr && address.compare(0, proxyProtocol.length(), proxyProtocol) == 0) { address = address.substr(proxyProtocol.length(), address.length()); - port = atoi(address.substr(address.find(':') + 1, address.length()).c_str()); + try { + port = boost::numeric_cast<unsigned short>(atoi(address.substr(address.find(':') + 1, address.length()).c_str())); + } + catch (boost::numeric::bad_numeric_cast&) { + } address = address.substr(0, address.find(':')); } return HostAddressPort(HostAddress::fromString(address).get_value_or(HostAddress()), port); } } diff --git a/Swiften/Network/GConfProxyProvider.cpp b/Swiften/Network/GConfProxyProvider.cpp index eade450..7c31868 100644 --- a/Swiften/Network/GConfProxyProvider.cpp +++ b/Swiften/Network/GConfProxyProvider.cpp @@ -1,32 +1,34 @@ /* * Copyright (c) 2010-2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2016-2017 Isode Limited. + * Copyright (c) 2016-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/GConfProxyProvider.h> #include <cstdio> #include <cstdlib> #include <iostream> extern "C" { #include <gconf/gconf-client.h> } +#include <boost/numeric/conversion/cast.hpp> + #include <Swiften/Base/Log.h> namespace Swift { GConfProxyProvider::GConfProxyProvider() { #if !GLIB_CHECK_VERSION(2,35,0) // Ensure static GLib initialization methods are called static bool glibInitialized = false; if (!glibInitialized) { @@ -44,25 +46,29 @@ HostAddressPort GConfProxyProvider::getHTTPConnectProxy() const { return httpProxy; } HostAddressPort GConfProxyProvider::getSOCKS5Proxy() const { return socksProxy; } HostAddressPort GConfProxyProvider::getFromGConf(const char* gcHost, const char* gcPort) { std::string address; - int port = 0; + unsigned short port = 0; gchar* str; GConfClient* client = gconf_client_get_default(); str = gconf_client_get_string(client, gcHost, NULL); - port = static_cast<int> (gconf_client_get_int(client, gcPort, NULL)); + try { + port = boost::numeric_cast<unsigned short>(gconf_client_get_int(client, gcPort, NULL)); + } + catch (const boost::numeric::bad_numeric_cast&) { + } if(str) { address = static_cast<char*> (str); g_free(str); } g_object_unref(client); return HostAddressPort(HostAddress::fromString(address).get_value_or(HostAddress()), port); } diff --git a/Swiften/Network/HTTPConnectProxiedConnection.cpp b/Swiften/Network/HTTPConnectProxiedConnection.cpp index b5e521b..8eba49e 100644 --- a/Swiften/Network/HTTPConnectProxiedConnection.cpp +++ b/Swiften/Network/HTTPConnectProxiedConnection.cpp @@ -1,17 +1,17 @@ /* * Copyright (c) 2010-2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/HTTPConnectProxiedConnection.h> #include <iostream> #include <utility> @@ -30,19 +30,19 @@ #include <Swiften/StringCodecs/Base64.h> using namespace Swift; HTTPConnectProxiedConnection::HTTPConnectProxiedConnection( DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, - int proxyPort, + unsigned short proxyPort, const SafeString& authID, const SafeString& authPassword) : ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort), authID_(authID), authPassword_(authPassword) { } HTTPConnectProxiedConnection::~HTTPConnectProxiedConnection() { diff --git a/Swiften/Network/HTTPConnectProxiedConnection.h b/Swiften/Network/HTTPConnectProxiedConnection.h index 6592839..a83d47c 100644 --- a/Swiften/Network/HTTPConnectProxiedConnection.h +++ b/Swiften/Network/HTTPConnectProxiedConnection.h @@ -1,17 +1,17 @@ /* * Copyright (c) 2010-2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2011-2017 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> @@ -24,26 +24,26 @@ namespace Swift { class HTTPTrafficFilter; class TimerFactory; class SWIFTEN_API HTTPConnectProxiedConnection : public ProxiedConnection { public: typedef std::shared_ptr<HTTPConnectProxiedConnection> ref; virtual ~HTTPConnectProxiedConnection(); - static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword) { + static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort, const SafeString& authID, const SafeString& authPassword) { return ref(new HTTPConnectProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort, authID, authPassword)); } void setHTTPTrafficFilter(std::shared_ptr<HTTPTrafficFilter> trafficFilter); private: - HTTPConnectProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword); + HTTPConnectProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort, const SafeString& authID, const SafeString& authPassword); virtual void initializeProxy(); virtual void handleProxyInitializeData(std::shared_ptr<SafeByteArray> data); void sendHTTPRequest(const std::string& statusLine, const std::vector<std::pair<std::string, std::string> >& headerFields); void parseHTTPHeader(const std::string& data, std::string& statusLine, std::vector<std::pair<std::string, std::string> >& headerFields); private: SafeByteArray authID_; diff --git a/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp b/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp index 91ace3d..54b998a 100644 --- a/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp +++ b/Swiften/Network/HTTPConnectProxiedConnectionFactory.cpp @@ -1,32 +1,32 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ /* * Copyright (c) 2010-2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ #include <Swiften/Network/HTTPConnectProxiedConnectionFactory.h> #include <Swiften/Network/HTTPConnectProxiedConnection.h> namespace Swift { -HTTPConnectProxiedConnectionFactory::HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort), authID_(""), authPassword_(""), httpTrafficFilter_(httpTrafficFilter) { +HTTPConnectProxiedConnectionFactory::HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort), authID_(""), authPassword_(""), httpTrafficFilter_(httpTrafficFilter) { } -HTTPConnectProxiedConnectionFactory::HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort), authID_(authID), authPassword_(authPassword), httpTrafficFilter_(httpTrafficFilter) { +HTTPConnectProxiedConnectionFactory::HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort, const SafeString& authID, const SafeString& authPassword, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort), authID_(authID), authPassword_(authPassword), httpTrafficFilter_(httpTrafficFilter) { } std::shared_ptr<Connection> HTTPConnectProxiedConnectionFactory::createConnection() { HTTPConnectProxiedConnection::ref proxyConnection = HTTPConnectProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_, authID_, authPassword_); proxyConnection->setHTTPTrafficFilter(httpTrafficFilter_); return proxyConnection; } } diff --git a/Swiften/Network/HTTPConnectProxiedConnectionFactory.h b/Swiften/Network/HTTPConnectProxiedConnectionFactory.h index 395f64f..7a5f527 100644 --- a/Swiften/Network/HTTPConnectProxiedConnectionFactory.h +++ b/Swiften/Network/HTTPConnectProxiedConnectionFactory.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2012-2017 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ /* * Copyright (c) 2010-2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ @@ -18,25 +18,25 @@ #include <Swiften/Network/HostAddressPort.h> namespace Swift { class DomainNameResolver; class HTTPTrafficFilter; class TimerFactory; class SWIFTEN_API HTTPConnectProxiedConnectionFactory : public ConnectionFactory { public: - HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = std::shared_ptr<HTTPTrafficFilter>()); - HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort, const SafeString& authID, const SafeString& authPassword, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = std::shared_ptr<HTTPTrafficFilter>()); + HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = std::shared_ptr<HTTPTrafficFilter>()); + HTTPConnectProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort, const SafeString& authID, const SafeString& authPassword, std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter = std::shared_ptr<HTTPTrafficFilter>()); virtual std::shared_ptr<Connection> createConnection(); private: DomainNameResolver* resolver_; ConnectionFactory* connectionFactory_; TimerFactory* timerFactory_; std::string proxyHost_; - int proxyPort_; + unsigned short proxyPort_; SafeString authID_; SafeString authPassword_; std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter_; }; } diff --git a/Swiften/Network/HostAddress.h b/Swiften/Network/HostAddress.h index e4ddffb..7a22cf4 100644 --- a/Swiften/Network/HostAddress.h +++ b/Swiften/Network/HostAddress.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <boost/asio/ip/address.hpp> @@ -21,18 +21,22 @@ namespace Swift { HostAddress(const boost::asio::ip::address& address); std::string toString() const; boost::asio::ip::address getRawAddress() const; bool operator==(const HostAddress& o) const { return address_ == o.address_; } + bool operator<(const HostAddress& o) const { + return address_ < o.address_; + } + bool isValid() const; bool isLocalhost() const; static boost::optional<HostAddress> fromString(const std::string& addressString); private: boost::asio::ip::address address_; }; } diff --git a/Swiften/Network/HostAddressPort.cpp b/Swiften/Network/HostAddressPort.cpp index 76c276e..248be2d 100644 --- a/Swiften/Network/HostAddressPort.cpp +++ b/Swiften/Network/HostAddressPort.cpp @@ -1,28 +1,28 @@ /* - * Copyright (c) 2010 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/HostAddressPort.h> #include <boost/lexical_cast.hpp> using namespace Swift; -HostAddressPort::HostAddressPort(const HostAddress& address, int port) : address_(address), port_(port) { +HostAddressPort::HostAddressPort(const HostAddress& address, unsigned short port) : address_(address), port_(port) { } HostAddressPort::HostAddressPort(const boost::asio::ip::tcp::endpoint& endpoint) { address_ = HostAddress(endpoint.address()); port_ = endpoint.port(); } std::string HostAddressPort::toString() const { std::string portAsString; try { - portAsString = boost::lexical_cast<std::string>(getPort()); + portAsString = std::to_string(getPort()); } catch (boost::bad_lexical_cast&) { } return getAddress().toString() + ":" + portAsString; } diff --git a/Swiften/Network/HostAddressPort.h b/Swiften/Network/HostAddressPort.h index e42e1d1..759af01 100644 --- a/Swiften/Network/HostAddressPort.h +++ b/Swiften/Network/HostAddressPort.h @@ -1,42 +1,49 @@ /* - * Copyright (c) 2010 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/asio/ip/tcp.hpp> #include <Swiften/Base/API.h> #include <Swiften/Network/HostAddress.h> namespace Swift { class SWIFTEN_API HostAddressPort { public: - HostAddressPort(const HostAddress& address = HostAddress(), int port = -1); + HostAddressPort(const HostAddress& address = HostAddress(), unsigned short port = 0); HostAddressPort(const boost::asio::ip::tcp::endpoint& endpoint); const HostAddress& getAddress() const { return address_; } - int getPort() const { + unsigned short getPort() const { return port_; } bool operator==(const HostAddressPort& o) const { return address_ == o.address_ && port_ == o.port_; } + bool operator<(const HostAddressPort& o) const { + if (address_ < o.address_) { + return true; + } + return address_ == o.address_ && port_ < o.port_; + } + bool isValid() const { return address_.isValid() && port_ > 0; } std::string toString() const; private: HostAddress address_; - int port_; + unsigned short port_; }; } diff --git a/Swiften/Network/MacOSXProxyProvider.cpp b/Swiften/Network/MacOSXProxyProvider.cpp index 232fc60..d3b10dd 100644 --- a/Swiften/Network/MacOSXProxyProvider.cpp +++ b/Swiften/Network/MacOSXProxyProvider.cpp @@ -1,17 +1,17 @@ /* * Copyright (c) 2010-2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Base/Platform.h> #include <Swiften/Network/MacOSXProxyProvider.h> #include <stdio.h> #include <stdlib.h> @@ -34,25 +34,27 @@ static HostAddressPort getFromDictionary(CFDictionaryRef dict, CFStringRef enabl HostAddressPort ret = HostAddressPort(HostAddress(), 0); if(CFDictionaryGetValueIfPresent(dict, reinterpret_cast<const void*> (enabledKey), reinterpret_cast<const void**> (&numberValue)) == true) { const int i = 0; CFNumberRef zero = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &i); CFComparisonResult result = CFNumberCompare(numberValue, zero, nullptr); CFRelease(zero); if(result != kCFCompareEqualTo) { - int port = 0; + unsigned short port = 0; std::string host = ""; try { CFNumberRef numberValue = reinterpret_cast<CFNumberRef> (CFDictionaryGetValue(dict, portKey)); if(numberValue != nullptr) { - CFNumberGetValue(numberValue, kCFNumberIntType, &port); + int intPort = 0; + CFNumberGetValue(numberValue, kCFNumberIntType, &intPort); + port = boost::numeric_cast<unsigned short>(intPort); } CFStringRef stringValue = reinterpret_cast<CFStringRef> (CFDictionaryGetValue(dict, hostKey)); if(stringValue != nullptr) { std::vector<char> buffer; // length must be +1 for the ending zero; and the Docu of CFStringGetCString tells it like // if the string is toby the length must be at least 5. CFIndex length = CFStringGetLength(stringValue) + 1; buffer.resize(boost::numeric_cast<size_t>(length)); diff --git a/Swiften/Network/MiniUPnPInterface.cpp b/Swiften/Network/MiniUPnPInterface.cpp index dbe8bcd..8425c77 100644 --- a/Swiften/Network/MiniUPnPInterface.cpp +++ b/Swiften/Network/MiniUPnPInterface.cpp @@ -1,27 +1,25 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/MiniUPnPInterface.h> #include <memory> -#include <boost/lexical_cast.hpp> - #include <miniupnpc.h> #include <upnpcommands.h> #include <upnperrors.h> #include <Swiften/Base/Log.h> namespace Swift { struct MiniUPnPInterface::Private { @@ -67,28 +65,28 @@ boost::optional<HostAddress> MiniUPnPInterface::getPublicIP() { int ret = UPNP_GetExternalIPAddress(p->urls.controlURL, p->data.first.servicetype, externalIPAddress); if (ret != UPNPCOMMAND_SUCCESS) { return boost::optional<HostAddress>(); } else { return HostAddress::fromString(std::string(externalIPAddress)); } } -boost::optional<NATPortMapping> MiniUPnPInterface::addPortForward(int actualLocalPort, int actualPublicPort) { +boost::optional<NATPortMapping> MiniUPnPInterface::addPortForward(unsigned short actualLocalPort, unsigned short actualPublicPort) { if (!p->isValid) { return boost::optional<NATPortMapping>(); } NATPortMapping mapping(actualLocalPort, actualPublicPort, NATPortMapping::TCP); - std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort()); - std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort()); - std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds()); + std::string publicPort = std::to_string(mapping.getPublicPort()); + std::string localPort = std::to_string(mapping.getLocalPort()); + std::string leaseSeconds = std::to_string(mapping.getLeaseInSeconds()); int ret = UPNP_AddPortMapping( p->urls.controlURL, p->data.first.servicetype, publicPort.c_str(), localPort.c_str(), p->localAddress.c_str(), "Swift", mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP", @@ -101,21 +99,21 @@ boost::optional<NATPortMapping> MiniUPnPInterface::addPortForward(int actualLoca return boost::optional<NATPortMapping>(); } } bool MiniUPnPInterface::removePortForward(const NATPortMapping& mapping) { if (!p->isValid) { return false; } - std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort()); - std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort()); - std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds()); + std::string publicPort = std::to_string(mapping.getPublicPort()); + std::string localPort = std::to_string(mapping.getLocalPort()); + std::string leaseSeconds = std::to_string(mapping.getLeaseInSeconds()); int ret = UPNP_DeletePortMapping(p->urls.controlURL, p->data.first.servicetype, publicPort.c_str(), mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP", nullptr); return ret == UPNPCOMMAND_SUCCESS; } bool MiniUPnPInterface::isAvailable() { return p->isValid; } diff --git a/Swiften/Network/MiniUPnPInterface.h b/Swiften/Network/MiniUPnPInterface.h index 89457b8..8c68268 100644 --- a/Swiften/Network/MiniUPnPInterface.h +++ b/Swiften/Network/MiniUPnPInterface.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ #pragma once #include <memory> #include <boost/noncopyable.hpp> @@ -17,17 +17,17 @@ namespace Swift { class MiniUPnPInterface : public NATTraversalInterface, boost::noncopyable { public: MiniUPnPInterface(); virtual ~MiniUPnPInterface(); virtual bool isAvailable(); boost::optional<HostAddress> getPublicIP(); - boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort); + boost::optional<NATPortMapping> addPortForward(unsigned short localPort, unsigned short publicPort); bool removePortForward(const NATPortMapping&); private: struct Private; const std::unique_ptr<Private> p; }; } diff --git a/Swiften/Network/NATPMPInterface.cpp b/Swiften/Network/NATPMPInterface.cpp index 5e0b3b3..0c33c1f 100644 --- a/Swiften/Network/NATPMPInterface.cpp +++ b/Swiften/Network/NATPMPInterface.cpp @@ -1,27 +1,25 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/NATPMPInterface.h> #include <memory> -#include <boost/numeric/conversion/cast.hpp> - #include <Swiften/Base/Log.h> // This has to be included after the previous headers, because of WIN32 macro // being defined somewhere. #include <natpmp.h> #pragma GCC diagnostic ignored "-Wold-style-cast" namespace Swift { @@ -68,26 +66,26 @@ boost::optional<HostAddress> NATPMPInterface::getPublicIP() { if (r == 0) { return boost::optional<HostAddress>(HostAddress(reinterpret_cast<const unsigned char*>(&(response.pnu.publicaddress.addr)), 4)); } else { SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl; return boost::optional<HostAddress>(); } } -boost::optional<NATPortMapping> NATPMPInterface::addPortForward(int localPort, int publicPort) { +boost::optional<NATPortMapping> NATPMPInterface::addPortForward(unsigned short localPort, unsigned short publicPort) { NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); if (sendnewportmappingrequest( &p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, - boost::numeric_cast<uint16_t>(mapping.getLocalPort()), - boost::numeric_cast<uint16_t>(mapping.getPublicPort()), - boost::numeric_cast<uint32_t>(mapping.getLeaseInSeconds())) < 0) { + mapping.getLocalPort(), + mapping.getPublicPort(), + mapping.getLeaseInSeconds()) < 0) { SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl; return boost::optional<NATPortMapping>(); } int r = 0; natpmpresp_t response; do { fd_set fds; struct timeval timeout; @@ -98,29 +96,29 @@ boost::optional<NATPortMapping> NATPMPInterface::addPortForward(int localPort, i // Limit NAT-PMP timeout to ten seconds. timeout.tv_sec = 10; timeout.tv_usec = 0; select(FD_SETSIZE, &fds, nullptr, nullptr, &timeout); r = readnatpmpresponseorretry(&p->natpmp, &response); } while(false /*r == NATPMP_TRYAGAIN*/); if (r == 0) { - NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, boost::numeric_cast<int>(response.pnu.newportmapping.lifetime)); + NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, response.pnu.newportmapping.lifetime); return result; } else { SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl; return boost::optional<NATPortMapping>(); } } bool NATPMPInterface::removePortForward(const NATPortMapping& mapping) { - if (sendnewportmappingrequest(&p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, 0, 0, boost::numeric_cast<uint32_t>(mapping.getLocalPort())) < 0) { + if (sendnewportmappingrequest(&p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, mapping.getLocalPort(), 0, 0) < 0) { SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!" << std::endl; return false; } int r = 0; natpmpresp_t response; do { fd_set fds; struct timeval timeout; diff --git a/Swiften/Network/NATPMPInterface.h b/Swiften/Network/NATPMPInterface.h index e1666c8..58d62b6 100644 --- a/Swiften/Network/NATPMPInterface.h +++ b/Swiften/Network/NATPMPInterface.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ #pragma once #include <memory> #include <boost/noncopyable.hpp> @@ -17,17 +17,17 @@ namespace Swift { class NATPMPInterface : public NATTraversalInterface, boost::noncopyable { public: NATPMPInterface(); virtual ~NATPMPInterface(); virtual bool isAvailable(); virtual boost::optional<HostAddress> getPublicIP(); - virtual boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort); + virtual boost::optional<NATPortMapping> addPortForward(unsigned short localPort, unsigned short publicPort); virtual bool removePortForward(const NATPortMapping&); private: struct Private; const std::unique_ptr<Private> p; }; } diff --git a/Swiften/Network/NATPortMapping.h b/Swiften/Network/NATPortMapping.h index ff8fde3..bf0fb1c 100644 --- a/Swiften/Network/NATPortMapping.h +++ b/Swiften/Network/NATPortMapping.h @@ -1,53 +1,53 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> #include <Swiften/Network/HostAddress.h> namespace Swift { class SWIFTEN_API NATPortMapping { public: enum Protocol { TCP, UDP }; - NATPortMapping(int localPort, int publicPort, Protocol protocol = TCP, int leaseInSeconds = 60 * 60 * 24) : + NATPortMapping(unsigned short localPort, unsigned short publicPort, Protocol protocol = TCP, uint32_t leaseInSeconds = 60 * 60 * 24) : publicPort(publicPort), localPort(localPort), protocol(protocol), leaseInSeconds(leaseInSeconds) { } - int getPublicPort() const { + unsigned short getPublicPort() const { return publicPort; } - int getLocalPort() const { + unsigned short getLocalPort() const { return localPort; } Protocol getProtocol() const { return protocol; } - int getLeaseInSeconds() const { + uint32_t getLeaseInSeconds() const { return leaseInSeconds; } private: - int publicPort; - int localPort; + unsigned short publicPort; + unsigned short localPort; Protocol protocol; - int leaseInSeconds; + uint32_t leaseInSeconds; }; } diff --git a/Swiften/Network/NATTraversalInterface.h b/Swiften/Network/NATTraversalInterface.h index ea9ed6a..1655eb6 100644 --- a/Swiften/Network/NATTraversalInterface.h +++ b/Swiften/Network/NATTraversalInterface.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2015 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ #pragma once #include <boost/optional.hpp> #include <Swiften/Base/API.h> @@ -13,13 +13,13 @@ namespace Swift { class SWIFTEN_API NATTraversalInterface { public: virtual ~NATTraversalInterface(); virtual bool isAvailable() = 0; virtual boost::optional<HostAddress> getPublicIP() = 0; - virtual boost::optional<NATPortMapping> addPortForward(int localPort, int publicPort) = 0; + virtual boost::optional<NATPortMapping> addPortForward(unsigned short localPort, unsigned short publicPort) = 0; virtual bool removePortForward(const NATPortMapping&) = 0; }; } diff --git a/Swiften/Network/NATTraversalRemovePortForwardingRequest.h b/Swiften/Network/NATTraversalRemovePortForwardingRequest.h index 3db9ee1..83235f9 100644 --- a/Swiften/Network/NATTraversalRemovePortForwardingRequest.h +++ b/Swiften/Network/NATTraversalRemovePortForwardingRequest.h @@ -1,17 +1,17 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/signals2.hpp> #include <Swiften/Base/API.h> @@ -20,20 +20,20 @@ namespace Swift { class SWIFTEN_API NATTraversalRemovePortForwardingRequest { public: struct PortMapping { enum Protocol { TCP, UDP }; - unsigned int publicPort; - unsigned int localPort; + unsigned short publicPort; + unsigned short localPort; Protocol protocol; unsigned long leaseInSeconds; }; public: virtual ~NATTraversalRemovePortForwardingRequest(); virtual void start() = 0; virtual void stop() = 0; diff --git a/Swiften/Network/NATTraverser.h b/Swiften/Network/NATTraverser.h index 716bfcb..7f03c03 100644 --- a/Swiften/Network/NATTraverser.h +++ b/Swiften/Network/NATTraverser.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> @@ -14,13 +14,13 @@ namespace Swift { class NATTraversalGetPublicIPRequest; class NATTraversalForwardPortRequest; class NATTraversalRemovePortForwardingRequest; class SWIFTEN_API NATTraverser { public: virtual ~NATTraverser(); virtual std::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest() = 0; - virtual std::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort) = 0; - virtual std::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort) = 0; + virtual std::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(unsigned short localPort, unsigned short publicPort) = 0; + virtual std::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(unsigned short localPort, unsigned short publicPort) = 0; }; } diff --git a/Swiften/Network/NullNATTraversalInterface.h b/Swiften/Network/NullNATTraversalInterface.h index ecbf110..eabc197 100644 --- a/Swiften/Network/NullNATTraversalInterface.h +++ b/Swiften/Network/NullNATTraversalInterface.h @@ -15,18 +15,18 @@ namespace Swift { public: virtual bool isAvailable() { return true; } virtual boost::optional<HostAddress> getPublicIP() { return boost::optional<HostAddress>(); } - virtual boost::optional<NATPortMapping> addPortForward(int, int) { + virtual boost::optional<NATPortMapping> addPortForward(unsigned short, unsigned short) { return boost::optional<NATPortMapping>(); } virtual bool removePortForward(const NATPortMapping&) { return false; } }; } diff --git a/Swiften/Network/NullNATTraverser.cpp b/Swiften/Network/NullNATTraverser.cpp index cc8bae0..0b9464e 100644 --- a/Swiften/Network/NullNATTraverser.cpp +++ b/Swiften/Network/NullNATTraverser.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/NullNATTraverser.h> #include <memory> #include <boost/bind.hpp> @@ -66,18 +66,18 @@ class NullNATTraversalRemovePortForwardingRequest : public NATTraversalRemovePor }; NullNATTraverser::NullNATTraverser(EventLoop* eventLoop) : eventLoop(eventLoop) { } std::shared_ptr<NATTraversalGetPublicIPRequest> NullNATTraverser::createGetPublicIPRequest() { return std::make_shared<NullNATTraversalGetPublicIPRequest>(eventLoop); } -std::shared_ptr<NATTraversalForwardPortRequest> NullNATTraverser::createForwardPortRequest(int, int) { +std::shared_ptr<NATTraversalForwardPortRequest> NullNATTraverser::createForwardPortRequest(unsigned short, unsigned short) { return std::make_shared<NullNATTraversalForwardPortRequest>(eventLoop); } -std::shared_ptr<NATTraversalRemovePortForwardingRequest> NullNATTraverser::createRemovePortForwardingRequest(int, int) { +std::shared_ptr<NATTraversalRemovePortForwardingRequest> NullNATTraverser::createRemovePortForwardingRequest(unsigned short, unsigned short) { return std::make_shared<NullNATTraversalRemovePortForwardingRequest>(eventLoop); } } diff --git a/Swiften/Network/NullNATTraverser.h b/Swiften/Network/NullNATTraverser.h index d3a6640..2f975bf 100644 --- a/Swiften/Network/NullNATTraverser.h +++ b/Swiften/Network/NullNATTraverser.h @@ -1,25 +1,25 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Network/NATTraverser.h> namespace Swift { class EventLoop; class NullNATTraverser : public NATTraverser { public: NullNATTraverser(EventLoop* eventLoop); std::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest(); - std::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort); - std::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort); + std::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(unsigned short localPort, unsigned short publicPort); + std::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(unsigned short localPort, unsigned short publicPort); private: EventLoop* eventLoop; }; } diff --git a/Swiften/Network/PlatformDomainNameServiceQuery.cpp b/Swiften/Network/PlatformDomainNameServiceQuery.cpp index a5d180b..f884500 100644 --- a/Swiften/Network/PlatformDomainNameServiceQuery.cpp +++ b/Swiften/Network/PlatformDomainNameServiceQuery.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <boost/asio.hpp> #include <Swiften/Network/PlatformDomainNameServiceQuery.h> #pragma GCC diagnostic ignored "-Wold-style-cast" @@ -123,47 +123,54 @@ void PlatformDomainNameServiceQuery::runBlocking() { // Process the SRV answers int answersCount = ntohs(header->ancount); while (answersCount > 0) { DomainNameServiceQuery::Result record; int entryLength = dn_skipname(currentEntry, messageEnd); currentEntry += entryLength; currentEntry += NS_RRFIXEDSZ; - // Priority - if (currentEntry + 2 >= messageEnd) { - emitError(); - return; - } - record.priority = boost::numeric_cast<int>(ns_get16(currentEntry)); - currentEntry += 2; - - // Weight - if (currentEntry + 2 >= messageEnd) { - emitError(); - return; + try { + // Priority + if (currentEntry + 2 >= messageEnd) { + emitError(); + return; + } + record.priority = boost::numeric_cast<int>(ns_get16(currentEntry)); + currentEntry += 2; + + // Weight + if (currentEntry + 2 >= messageEnd) { + emitError(); + return; + } + record.weight = boost::numeric_cast<int>(ns_get16(currentEntry)); + currentEntry += 2; + + // Port + if (currentEntry + 2 >= messageEnd) { + emitError(); + return; + } + record.port = boost::numeric_cast<unsigned short>(ns_get16(currentEntry)); + currentEntry += 2; + + // Hostname + if (currentEntry >= messageEnd) { + emitError(); + return; + } } - record.weight = boost::numeric_cast<int>(ns_get16(currentEntry)); - currentEntry += 2; - - // Port - if (currentEntry + 2 >= messageEnd) { + catch (const boost::numeric::bad_numeric_cast&) { emitError(); return; } - record.port = boost::numeric_cast<int>(ns_get16(currentEntry)); - currentEntry += 2; - // Hostname - if (currentEntry >= messageEnd) { - emitError(); - return; - } ByteArray entry; entry.resize(NS_MAXDNAME); entryLength = dn_expand(messageStart, messageEnd, currentEntry, reinterpret_cast<char*>(vecptr(entry)), entry.size()); if (entryLength < 0) { emitError(); return; } record.hostname = std::string(reinterpret_cast<const char*>(vecptr(entry))); records.push_back(record); diff --git a/Swiften/Network/PlatformNATTraversalWorker.cpp b/Swiften/Network/PlatformNATTraversalWorker.cpp index f56de0b..af12049 100644 --- a/Swiften/Network/PlatformNATTraversalWorker.cpp +++ b/Swiften/Network/PlatformNATTraversalWorker.cpp @@ -78,39 +78,39 @@ class PlatformNATTraversalGetPublicIPRequest : public NATTraversalGetPublicIPReq } virtual void runBlocking() { getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->getPublicIP()), shared_from_this()); } }; class PlatformNATTraversalForwardPortRequest : public NATTraversalForwardPortRequest, public PlatformNATTraversalRequest { public: - PlatformNATTraversalForwardPortRequest(PlatformNATTraversalWorker* worker, unsigned int localIP, unsigned int publicIP) : PlatformNATTraversalRequest(worker), localIP(localIP), publicIP(publicIP) { + PlatformNATTraversalForwardPortRequest(PlatformNATTraversalWorker* worker, unsigned short localPort, unsigned short publicPort) : PlatformNATTraversalRequest(worker), localPort(localPort), publicPort(publicPort) { } virtual ~PlatformNATTraversalForwardPortRequest() { } virtual void start() { doRun(); } virtual void stop() { onResult.disconnect_all_slots(); } virtual void runBlocking() { - getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->addPortForward(boost::numeric_cast<int>(localIP), boost::numeric_cast<int>(publicIP))), shared_from_this()); + getEventLoop()->postEvent(boost::bind(boost::ref(onResult), getNATTraversalInterface()->addPortForward(localPort, publicPort)), shared_from_this()); } private: - unsigned int localIP; - unsigned int publicIP; + unsigned short localPort; + unsigned short publicPort; }; class PlatformNATTraversalRemovePortForwardingRequest : public NATTraversalRemovePortForwardingRequest, public PlatformNATTraversalRequest { public: PlatformNATTraversalRemovePortForwardingRequest(PlatformNATTraversalWorker* worker, const NATPortMapping& mapping) : PlatformNATTraversalRequest(worker), mapping(mapping) { } virtual ~PlatformNATTraversalRemovePortForwardingRequest() { } @@ -175,23 +175,23 @@ NATTraversalInterface* PlatformNATTraversalWorker::getNATTraversalInterface() co #endif return nullNATTraversalInterface; } std::shared_ptr<NATTraversalGetPublicIPRequest> PlatformNATTraversalWorker::createGetPublicIPRequest() { return std::make_shared<PlatformNATTraversalGetPublicIPRequest>(this); } -std::shared_ptr<NATTraversalForwardPortRequest> PlatformNATTraversalWorker::createForwardPortRequest(int localPort, int publicPort) { +std::shared_ptr<NATTraversalForwardPortRequest> PlatformNATTraversalWorker::createForwardPortRequest(unsigned short localPort, unsigned short publicPort) { return std::make_shared<PlatformNATTraversalForwardPortRequest>(this, localPort, publicPort); } -std::shared_ptr<NATTraversalRemovePortForwardingRequest> PlatformNATTraversalWorker::createRemovePortForwardingRequest(int localPort, int publicPort) { +std::shared_ptr<NATTraversalRemovePortForwardingRequest> PlatformNATTraversalWorker::createRemovePortForwardingRequest(unsigned short localPort, unsigned short publicPort) { NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); // FIXME return std::make_shared<PlatformNATTraversalRemovePortForwardingRequest>(this, mapping); } void PlatformNATTraversalWorker::start() { while (!stopRequested) { PlatformNATTraversalRequest::ref request; { std::unique_lock<std::mutex> lock(queueMutex); diff --git a/Swiften/Network/PlatformNATTraversalWorker.h b/Swiften/Network/PlatformNATTraversalWorker.h index aee1052..368798e 100644 --- a/Swiften/Network/PlatformNATTraversalWorker.h +++ b/Swiften/Network/PlatformNATTraversalWorker.h @@ -1,17 +1,17 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2016-2017 Isode Limited. + * Copyright (c) 2016-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <condition_variable> #include <deque> #include <mutex> @@ -38,20 +38,20 @@ namespace Swift { class SWIFTEN_API PlatformNATTraversalWorker : public NATTraverser { friend class PlatformNATTraversalRequest; public: PlatformNATTraversalWorker(EventLoop* eventLoop); virtual ~PlatformNATTraversalWorker(); std::shared_ptr<NATTraversalGetPublicIPRequest> createGetPublicIPRequest(); - std::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(int localPort, int publicPort); - std::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(int localPort, int publicPort); + std::shared_ptr<NATTraversalForwardPortRequest> createForwardPortRequest(unsigned short localPort, unsigned short publicPort); + std::shared_ptr<NATTraversalRemovePortForwardingRequest> createRemovePortForwardingRequest(unsigned short localPort, unsigned short publicPort); private: NATTraversalInterface* getNATTraversalInterface() const; void addRequestToQueue(std::shared_ptr<PlatformNATTraversalRequest>); void start(); void stop(); EventLoop* getEventLoop() const { return eventLoop; diff --git a/Swiften/Network/ProxiedConnection.cpp b/Swiften/Network/ProxiedConnection.cpp index aa6c4d2..4c97e31 100644 --- a/Swiften/Network/ProxiedConnection.cpp +++ b/Swiften/Network/ProxiedConnection.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/ProxiedConnection.h> #include <boost/bind.hpp> #include <Swiften/Base/ByteArray.h> @@ -14,19 +14,19 @@ #include <Swiften/Network/HostAddressPort.h> using namespace Swift; ProxiedConnection::ProxiedConnection( DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, - int proxyPort) : + unsigned short proxyPort) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort), server_(HostAddressPort(HostAddress::fromString("0.0.0.0").get(), 0)) { connected_ = false; } diff --git a/Swiften/Network/ProxiedConnection.h b/Swiften/Network/ProxiedConnection.h index 440fb86..f79845a 100644 --- a/Swiften/Network/ProxiedConnection.h +++ b/Swiften/Network/ProxiedConnection.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2012-2017 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> @@ -14,19 +14,19 @@ #include <Swiften/Network/Connection.h> #include <Swiften/Network/Connector.h> #include <Swiften/Network/HostAddressPort.h> namespace Swift { class ConnectionFactory; class SWIFTEN_API ProxiedConnection : public Connection, public std::enable_shared_from_this<ProxiedConnection> { public: - ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort); + ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort); virtual ~ProxiedConnection(); virtual void listen(); virtual void connect(const HostAddressPort& address); virtual void disconnect(); virtual void write(const SafeByteArray& data); virtual HostAddressPort getLocalAddress() const; virtual HostAddressPort getRemoteAddress() const; @@ -49,16 +49,16 @@ namespace Swift { void reconnect(); private: bool connected_; DomainNameResolver* resolver_; ConnectionFactory* connectionFactory_; TimerFactory* timerFactory_; std::string proxyHost_; - int proxyPort_; + unsigned short proxyPort_; HostAddressPort server_; Connector::ref connector_; std::shared_ptr<Connection> connection_; }; } diff --git a/Swiften/Network/SOCKS5ProxiedConnection.cpp b/Swiften/Network/SOCKS5ProxiedConnection.cpp index 2492827..d7036f2 100644 --- a/Swiften/Network/SOCKS5ProxiedConnection.cpp +++ b/Swiften/Network/SOCKS5ProxiedConnection.cpp @@ -1,17 +1,17 @@ /* * Copyright (c) 2010-2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/SOCKS5ProxiedConnection.h> #include <boost/bind.hpp> #include <Swiften/Base/ByteArray.h> @@ -21,19 +21,19 @@ #include <Swiften/Network/HostAddressPort.h> using namespace Swift; SOCKS5ProxiedConnection::SOCKS5ProxiedConnection( DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, - int proxyPort) : + unsigned short proxyPort) : ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort), proxyState_(Initial) { } void SOCKS5ProxiedConnection::initializeProxy() { proxyState_ = ProxyAuthenticating; SafeByteArray socksConnect; socksConnect.push_back(0x05); // VER = SOCKS5 = 0x05 socksConnect.push_back(0x01); // Number of authentication methods after this byte. diff --git a/Swiften/Network/SOCKS5ProxiedConnection.h b/Swiften/Network/SOCKS5ProxiedConnection.h index c8faae9..515c5b7 100644 --- a/Swiften/Network/SOCKS5ProxiedConnection.h +++ b/Swiften/Network/SOCKS5ProxiedConnection.h @@ -1,41 +1,41 @@ /* * Copyright (c) 2010-2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> #include <Swiften/Network/ProxiedConnection.h> namespace Swift { class ConnectionFactory; class DomainNameResolver; class TimerFactory; class SWIFTEN_API SOCKS5ProxiedConnection : public ProxiedConnection { public: typedef std::shared_ptr<SOCKS5ProxiedConnection> ref; - static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort) { + static ref create(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort) { return ref(new SOCKS5ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort)); } private: - SOCKS5ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort); + SOCKS5ProxiedConnection(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort); virtual void initializeProxy(); virtual void handleProxyInitializeData(std::shared_ptr<SafeByteArray> data); private: enum { Initial = 0, ProxyAuthenticating, ProxyConnecting diff --git a/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp b/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp index 01ce8ac..abd7718 100644 --- a/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp +++ b/Swiften/Network/SOCKS5ProxiedConnectionFactory.cpp @@ -10,17 +10,17 @@ * See the COPYING file for more information. */ #include <Swiften/Network/SOCKS5ProxiedConnectionFactory.h> #include <Swiften/Network/SOCKS5ProxiedConnection.h> namespace Swift { -SOCKS5ProxiedConnectionFactory::SOCKS5ProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort) { +SOCKS5ProxiedConnectionFactory::SOCKS5ProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), proxyHost_(proxyHost), proxyPort_(proxyPort) { } std::shared_ptr<Connection> SOCKS5ProxiedConnectionFactory::createConnection() { return SOCKS5ProxiedConnection::create(resolver_, connectionFactory_, timerFactory_, proxyHost_, proxyPort_); } } diff --git a/Swiften/Network/SOCKS5ProxiedConnectionFactory.h b/Swiften/Network/SOCKS5ProxiedConnectionFactory.h index 8631239..47ae9a3 100644 --- a/Swiften/Network/SOCKS5ProxiedConnectionFactory.h +++ b/Swiften/Network/SOCKS5ProxiedConnectionFactory.h @@ -1,37 +1,37 @@ /* * Copyright (c) 2010-2011 Thilo Cestonaro * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> #include <Swiften/Network/ConnectionFactory.h> #include <Swiften/Network/HostAddressPort.h> #include <Swiften/Network/HostNameOrAddress.h> namespace Swift { class DomainNameResolver; class TimerFactory; class SWIFTEN_API SOCKS5ProxiedConnectionFactory : public ConnectionFactory { public: - SOCKS5ProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, int proxyPort); + SOCKS5ProxiedConnectionFactory(DomainNameResolver* resolver, ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, unsigned short proxyPort); virtual std::shared_ptr<Connection> createConnection(); private: DomainNameResolver* resolver_; ConnectionFactory* connectionFactory_; TimerFactory* timerFactory_; std::string proxyHost_; - int proxyPort_; + unsigned short proxyPort_; }; } diff --git a/Swiften/Network/StaticDomainNameResolver.cpp b/Swiften/Network/StaticDomainNameResolver.cpp index 95b3dd9..eca6687 100644 --- a/Swiften/Network/StaticDomainNameResolver.cpp +++ b/Swiften/Network/StaticDomainNameResolver.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/StaticDomainNameResolver.h> #include <string> #include <boost/bind.hpp> @@ -44,18 +44,22 @@ namespace { }; struct AddressQuery : public DomainNameAddressQuery, public std::enable_shared_from_this<AddressQuery> { AddressQuery(const std::string& host, StaticDomainNameResolver* resolver, EventLoop* eventLoop, std::shared_ptr<EventOwner> owner) : eventLoop(eventLoop), host(host), resolver(resolver), owner(owner) {} virtual void run() { if (!resolver->getIsResponsive()) { return; } + if (auto address = HostAddress::fromString(host)) { + // IP Literals should resolve to themselves + resolver->addAddress(host, *address); + } StaticDomainNameResolver::AddressesMap::const_iterator i = resolver->getAddresses().find(host); if (i != resolver->getAddresses().end()) { eventLoop->postEvent( boost::bind(&AddressQuery::emitOnResult, shared_from_this(), i->second, boost::optional<DomainNameResolveError>())); } else { eventLoop->postEvent(boost::bind(&AddressQuery::emitOnResult, shared_from_this(), std::vector<HostAddress>(), boost::optional<DomainNameResolveError>(DomainNameResolveError())), owner); } } @@ -92,26 +96,26 @@ void StaticDomainNameResolver::addAddress(const std::string& domain, const HostA addresses[domain].push_back(address); } void StaticDomainNameResolver::addService(const std::string& service, const DomainNameServiceQuery::Result& result) { services.push_back(std::make_pair(service, result)); } void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, const HostAddressPort& address) { static int hostid = 0; - std::string hostname(std::string("host-") + boost::lexical_cast<std::string>(hostid)); + std::string hostname(std::string("host-") + std::to_string(hostid)); hostid++; addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, address.getPort(), 0, 0)); addAddress(hostname, address.getAddress()); } -void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, const std::string& hostname, int port) { +void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, const std::string& hostname, unsigned short port) { addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, port, 0, 0)); } std::shared_ptr<DomainNameServiceQuery> StaticDomainNameResolver::createServiceQuery(const std::string& serviceLookupPrefix, const std::string& domain) { return std::make_shared<ServiceQuery>(serviceLookupPrefix + domain, this, eventLoop, owner); } std::shared_ptr<DomainNameAddressQuery> StaticDomainNameResolver::createAddressQuery(const std::string& name) { return std::make_shared<AddressQuery>(name, this, eventLoop, owner); diff --git a/Swiften/Network/StaticDomainNameResolver.h b/Swiften/Network/StaticDomainNameResolver.h index 76394d0..2064046 100644 --- a/Swiften/Network/StaticDomainNameResolver.h +++ b/Swiften/Network/StaticDomainNameResolver.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <map> #include <memory> #include <vector> @@ -25,19 +25,19 @@ namespace Swift { typedef std::vector< std::pair<std::string, DomainNameServiceQuery::Result> > ServicesCollection; public: StaticDomainNameResolver(EventLoop* eventLoop); virtual ~StaticDomainNameResolver(); void addAddress(const std::string& domain, const HostAddress& address); void addService(const std::string& service, const DomainNameServiceQuery::Result& result); void addXMPPClientService(const std::string& domain, const HostAddressPort&); - void addXMPPClientService(const std::string& domain, const std::string& host, int port); + void addXMPPClientService(const std::string& domain, const std::string& host, unsigned short port); const AddressesMap& getAddresses() const { return addresses; } const ServicesCollection& getServices() const { return services; } diff --git a/Swiften/Network/TLSConnection.cpp b/Swiften/Network/TLSConnection.cpp index 7c293d1..82bf114 100644 --- a/Swiften/Network/TLSConnection.cpp +++ b/Swiften/Network/TLSConnection.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Network/TLSConnection.h> #include <boost/bind.hpp> #include <Swiften/Network/HostAddressPort.h> @@ -26,19 +26,18 @@ TLSConnection::TLSConnection(Connection::ref connection, TLSContextFactory* tlsF connection->onDataWritten.connect(boost::bind(&TLSConnection::handleRawDataWritten, this)); connection->onDisconnected.connect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1)); } TLSConnection::~TLSConnection() { connection->onConnectFinished.disconnect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1)); connection->onDataRead.disconnect(boost::bind(&TLSConnection::handleRawDataRead, this, _1)); connection->onDataWritten.disconnect(boost::bind(&TLSConnection::handleRawDataWritten, this)); connection->onDisconnected.disconnect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1)); - delete context; } void TLSConnection::handleTLSConnectFinished(bool error) { onConnectFinished(error); if (error) { disconnect(); } } @@ -65,19 +64,19 @@ void TLSConnection::write(const SafeByteArray& data) { HostAddressPort TLSConnection::getLocalAddress() const { return connection->getLocalAddress(); } HostAddressPort TLSConnection::getRemoteAddress() const { return connection->getRemoteAddress(); } TLSContext* TLSConnection::getTLSContext() const { - return context; + return context.get(); } void TLSConnection::handleRawConnectFinished(bool error) { connection->onConnectFinished.disconnect(boost::bind(&TLSConnection::handleRawConnectFinished, this, _1)); if (error) { onConnectFinished(true); } else { context->connect(); diff --git a/Swiften/Network/TLSConnection.h b/Swiften/Network/TLSConnection.h index 0c395d1..1ab1ec6 100644 --- a/Swiften/Network/TLSConnection.h +++ b/Swiften/Network/TLSConnection.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <boost/signals2.hpp> @@ -40,13 +40,13 @@ namespace Swift { void handleRawConnectFinished(bool error); void handleRawDisconnected(const boost::optional<Error>& error); void handleRawDataRead(std::shared_ptr<SafeByteArray> data); void handleRawDataWritten(); void handleTLSConnectFinished(bool error); void handleTLSDataForNetwork(const SafeByteArray& data); void handleTLSDataForApplication(const SafeByteArray& data); private: - TLSContext* context; + std::unique_ptr<TLSContext> context; Connection::ref connection; }; } diff --git a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp index 5d6fedd..4aeaf24 100644 --- a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp +++ b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp @@ -188,19 +188,19 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture { eventLoop->processEvents(); readResponse("<body/>", connectionFactory->connections[0]); rid++; testling->write(createSafeByteArray("<blah/>")); eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); /* 0 was waiting for response, open and send on 1 */ CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* data */ c1 = connectionFactory->connections[1]; - std::string fullBody = "<body rid='" + boost::lexical_cast<std::string>(rid) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'><blah/></body>"; /* check empty write */ + std::string fullBody = "<body rid='" + std::to_string(rid) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'><blah/></body>"; /* check empty write */ CPPUNIT_ASSERT_EQUAL(fullBody, lastBody()); CPPUNIT_ASSERT(c0->pending); CPPUNIT_ASSERT(c1->pending); rid++; readResponse("<body xmlns='http://jabber.org/protocol/httpbind'><message><splatploing/></message></body>", c0); /* Doesn't include necessary attributes - as the support is improved this'll start to fail */ eventLoop->processEvents(); CPPUNIT_ASSERT(!c0->pending); @@ -304,19 +304,19 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture { eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(st(1), boshDataWritten.size()); /* Shouldn't have sent anything extra */ eventLoop->processEvents(); testling->restartStream(); eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(st(2), boshDataWritten.size()); readResponse("<body></body>", c0); eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size()); - std::string fullBody = "<body rid='" + boost::lexical_cast<std::string>(initialRID + 2) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'></body>"; + std::string fullBody = "<body rid='" + std::to_string(initialRID + 2) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'></body>"; std::string response = boshDataWritten[2]; size_t bodyPosition = response.find("\r\n\r\n"); CPPUNIT_ASSERT_EQUAL(fullBody, response.substr(bodyPosition+4)); } private: @@ -421,32 +421,32 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture { void readResponse(const std::string& response, std::shared_ptr<MockConnection> connection) { connection->pending = false; std::shared_ptr<SafeByteArray> data1 = std::make_shared<SafeByteArray>(createSafeByteArray( "HTTP/1.1 200 OK\r\n" "Content-Type: text/xml; charset=utf-8\r\n" "Access-Control-Allow-Origin: *\r\n" "Access-Control-Allow-Headers: Content-Type\r\n" "Content-Length: ")); connection->onDataRead(data1); - std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size()))); + std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(std::to_string(response.size()))); connection->onDataRead(data2); std::shared_ptr<SafeByteArray> data3 = std::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n")); connection->onDataRead(data3); std::shared_ptr<SafeByteArray> data4 = std::make_shared<SafeByteArray>(createSafeByteArray(response)); connection->onDataRead(data4); } std::string fullRequestFor(const std::string& data) { std::string body = data; std::string result = "POST /" + path + " HTTP/1.1\r\n" + "Host: " + to + ":" + port + "\r\n" + "Content-Type: text/xml; charset=utf-8\r\n" - + "Content-Length: " + boost::lexical_cast<std::string>(body.size()) + "\r\n\r\n" + + "Content-Length: " + std::to_string(body.size()) + "\r\n\r\n" + body; return result; } private: URL boshURL; DummyEventLoop* eventLoop; MockConnectionFactory* connectionFactory; std::vector<std::string> xmppDataRead; diff --git a/Swiften/Network/UnitTest/BOSHConnectionTest.cpp b/Swiften/Network/UnitTest/BOSHConnectionTest.cpp index e34cb96..17d8333 100644 --- a/Swiften/Network/UnitTest/BOSHConnectionTest.cpp +++ b/Swiften/Network/UnitTest/BOSHConnectionTest.cpp @@ -312,19 +312,19 @@ class BOSHConnectionTest : public CppUnit::TestFixture { void readResponse(const std::string& response, std::shared_ptr<MockConnection> connection) { std::shared_ptr<SafeByteArray> data1 = std::make_shared<SafeByteArray>(createSafeByteArray( "HTTP/1.1 200 OK\r\n" "Content-Type: text/xml; charset=utf-8\r\n" "Access-Control-Allow-Origin: *\r\n" "Access-Control-Allow-Headers: Content-Type\r\n" "Content-Length: ")); connection->onDataRead(data1); - std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size()))); + std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(std::to_string(response.size()))); connection->onDataRead(data2); std::shared_ptr<SafeByteArray> data3 = std::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n")); connection->onDataRead(data3); std::shared_ptr<SafeByteArray> data4 = std::make_shared<SafeByteArray>(createSafeByteArray(response)); connection->onDataRead(data4); } private: diff --git a/Swiften/Network/UnitTest/ConnectorTest.cpp b/Swiften/Network/UnitTest/ConnectorTest.cpp index 8524439..065911d 100644 --- a/Swiften/Network/UnitTest/ConnectorTest.cpp +++ b/Swiften/Network/UnitTest/ConnectorTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <boost/bind.hpp> #include <boost/optional.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> @@ -20,18 +20,19 @@ #include <Swiften/Network/StaticDomainNameResolver.h> using namespace Swift; class ConnectorTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ConnectorTest); CPPUNIT_TEST(testConnect); CPPUNIT_TEST(testConnect_NoServiceLookups); CPPUNIT_TEST(testConnect_NoServiceLookups_DefaultPort); + CPPUNIT_TEST(testConnect_OnlyLiteral); CPPUNIT_TEST(testConnect_FirstAddressHostFails); CPPUNIT_TEST(testConnect_NoSRVHost); CPPUNIT_TEST(testConnect_NoHosts); CPPUNIT_TEST(testConnect_FirstSRVHostFails); CPPUNIT_TEST(testConnect_AllSRVHostsFailWithoutFallbackHost); CPPUNIT_TEST(testConnect_AllSRVHostsFailWithFallbackHost); CPPUNIT_TEST(testConnect_SRVAndFallbackHostsFail); //CPPUNIT_TEST(testConnect_TimeoutDuringResolve); CPPUNIT_TEST(testConnect_TimeoutDuringConnectToOnlyCandidate); @@ -85,46 +86,61 @@ class ConnectorTest : public CppUnit::TestFixture { CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); CPPUNIT_ASSERT(connections[0]); CPPUNIT_ASSERT(host3.getAddress() == (*(connections[0]->hostAddressPort)).getAddress()); CPPUNIT_ASSERT(4321 == (*(connections[0]->hostAddressPort)).getPort()); CPPUNIT_ASSERT(!std::dynamic_pointer_cast<DomainNameResolveError>(error)); } void testConnect_NoServiceLookups_DefaultPort() { - Connector::ref testling(createConnector(-1, boost::optional<std::string>())); + Connector::ref testling(createConnector(0, boost::optional<std::string>())); resolver->addXMPPClientService("foo.com", host1); resolver->addXMPPClientService("foo.com", host2); resolver->addAddress("foo.com", host3.getAddress()); testling->start(); eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); CPPUNIT_ASSERT(connections[0]); CPPUNIT_ASSERT(host3.getAddress() == (*(connections[0]->hostAddressPort)).getAddress()); - CPPUNIT_ASSERT_EQUAL(5222, (*(connections[0]->hostAddressPort)).getPort()); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(5222), (*(connections[0]->hostAddressPort)).getPort()); CPPUNIT_ASSERT(!std::dynamic_pointer_cast<DomainNameResolveError>(error)); } void testConnect_NoSRVHost() { Connector::ref testling(createConnector()); resolver->addAddress("foo.com", host3.getAddress()); testling->start(); eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); CPPUNIT_ASSERT(connections[0]); CPPUNIT_ASSERT(host3 == *(connections[0]->hostAddressPort)); CPPUNIT_ASSERT(!std::dynamic_pointer_cast<DomainNameResolveError>(error)); } + void testConnect_OnlyLiteral() { + auto testling = Connector::create("1.1.1.1", 1234, boost::none, resolver, connectionFactory, timerFactory); + testling->onConnectFinished.connect(boost::bind(&ConnectorTest::handleConnectorFinished, this, _1, _2)); + + auto address1 = HostAddress::fromString("1.1.1.1").get(); + connectionFactory->failingPorts.push_back(HostAddressPort(address1, 1234)); + + testling->start(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); + CPPUNIT_ASSERT(!connections[0]); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connectionFactory->createdConnections.size())); + } + void testConnect_FirstAddressHostFails() { Connector::ref testling(createConnector()); auto address1 = HostAddress::fromString("1.1.1.1").get(); auto address2 = HostAddress::fromString("2.2.2.2").get(); resolver->addXMPPClientService("foo.com", "host-foo.com", 1234); resolver->addAddress("host-foo.com", address1); resolver->addAddress("host-foo.com", address2); connectionFactory->failingPorts.push_back(HostAddressPort(address1, 1234)); @@ -306,19 +322,19 @@ class ConnectorTest : public CppUnit::TestFixture { timerFactory->setTime(10); eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); CPPUNIT_ASSERT(!connections[0]); } private: - Connector::ref createConnector(int port = -1, boost::optional<std::string> serviceLookupPrefix = boost::optional<std::string>("_xmpp-client._tcp.")) { + Connector::ref createConnector(unsigned short port = 0, boost::optional<std::string> serviceLookupPrefix = boost::optional<std::string>("_xmpp-client._tcp.")) { Connector::ref connector = Connector::create("foo.com", port, serviceLookupPrefix, resolver, connectionFactory, timerFactory); connector->onConnectFinished.connect(boost::bind(&ConnectorTest::handleConnectorFinished, this, _1, _2)); return connector; } void handleConnectorFinished(std::shared_ptr<Connection> connection, std::shared_ptr<Error> resultError) { std::shared_ptr<MockConnection> c(std::dynamic_pointer_cast<MockConnection>(connection)); if (connection) { assert(c); @@ -350,24 +366,27 @@ class ConnectorTest : public CppUnit::TestFixture { std::vector<HostAddressPort> failingPorts; bool isResponsive; }; struct MockConnectionFactory : public ConnectionFactory { MockConnectionFactory(EventLoop* eventLoop) : eventLoop(eventLoop), isResponsive(true) { } std::shared_ptr<Connection> createConnection() { - return std::make_shared<MockConnection>(failingPorts, isResponsive, eventLoop); + auto connection = std::make_shared<MockConnection>(failingPorts, isResponsive, eventLoop); + createdConnections.push_back(connection); + return connection; } EventLoop* eventLoop; bool isResponsive; std::vector<HostAddressPort> failingPorts; + std::vector<std::shared_ptr<MockConnection>> createdConnections; }; private: HostAddressPort host1; HostAddressPort host2; HostAddressPort host3; DummyEventLoop* eventLoop; StaticDomainNameResolver* resolver; MockConnectionFactory* connectionFactory; diff --git a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp index 1a160b7..065d015 100644 --- a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp +++ b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <memory> #include <boost/algorithm/string.hpp> #include <boost/bind.hpp> #include <boost/lexical_cast.hpp> @@ -415,19 +415,19 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture { EventLoop* eventLoop; std::vector< std::shared_ptr<MockConnection> > connections; std::vector<HostAddressPort> failingPorts; }; private: std::string proxyHost; HostAddressPort proxyHostAddress; - int proxyPort; + unsigned short proxyPort; HostAddressPort host; DummyEventLoop* eventLoop; StaticDomainNameResolver* resolver; MockConnectionFactory* connectionFactory; TimerFactory* timerFactory; bool connectFinished; bool connectFinishedWithError; bool disconnected; boost::optional<Connection::Error> disconnectedError; diff --git a/Swiften/Network/UnitTest/HostAddressTest.cpp b/Swiften/Network/UnitTest/HostAddressTest.cpp index 226346b..bd345a7 100644 --- a/Swiften/Network/UnitTest/HostAddressTest.cpp +++ b/Swiften/Network/UnitTest/HostAddressTest.cpp @@ -1,32 +1,34 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <string> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <Swiften/Network/HostAddress.h> +#include <Swiften/Network/HostAddressPort.h> using namespace Swift; class HostAddressTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(HostAddressTest); CPPUNIT_TEST(testConstructor); CPPUNIT_TEST(testConstructor_Invalid); CPPUNIT_TEST(testConstructor_InvalidString); CPPUNIT_TEST(testToString); CPPUNIT_TEST(testToString_IPv6); CPPUNIT_TEST(testToString_Invalid); + CPPUNIT_TEST(testComparison); CPPUNIT_TEST_SUITE_END(); public: void testConstructor() { auto testling = HostAddress::fromString("192.168.1.254"); CPPUNIT_ASSERT_EQUAL(std::string("192.168.1.254"), testling->toString()); CPPUNIT_ASSERT(testling->isValid()); } @@ -56,12 +58,38 @@ class HostAddressTest : public CppUnit::TestFixture { CPPUNIT_ASSERT_EQUAL(std::string("102:304:506:708:90a:b0c:d0e:f11"), testling.toString()); } void testToString_Invalid() { HostAddress testling; CPPUNIT_ASSERT_EQUAL(std::string("0.0.0.0"), testling.toString()); } + + void testComparison() { + auto ha127_0_0_1 = *HostAddress::fromString("127.0.0.1"); + auto ha127_0_0_2 = *HostAddress::fromString("127.0.0.2"); + auto ha127_0_1_0 = *HostAddress::fromString("127.0.1.0"); + + CPPUNIT_ASSERT(ha127_0_0_1 < ha127_0_0_2); + CPPUNIT_ASSERT(ha127_0_0_2 < ha127_0_1_0); + CPPUNIT_ASSERT(!(ha127_0_0_1 < ha127_0_0_1)); + CPPUNIT_ASSERT(!(ha127_0_0_2 < ha127_0_0_1)); + CPPUNIT_ASSERT(!(ha127_0_0_2 == ha127_0_0_1)); + CPPUNIT_ASSERT(ha127_0_0_1 == ha127_0_0_1); + + auto hap_127_0_0_1__1 = HostAddressPort(ha127_0_0_1, 1); + auto hap_127_0_0_1__2 = HostAddressPort(ha127_0_0_1, 2); + auto hap_127_0_0_2__1 = HostAddressPort(ha127_0_0_2, 1); + auto hap_127_0_0_2__2 = HostAddressPort(ha127_0_0_2, 2); + + CPPUNIT_ASSERT(hap_127_0_0_1__1 < hap_127_0_0_1__2); + CPPUNIT_ASSERT(!(hap_127_0_0_1__1 < hap_127_0_0_1__1)); + CPPUNIT_ASSERT(!(hap_127_0_0_1__1 == hap_127_0_0_1__2)); + CPPUNIT_ASSERT(hap_127_0_0_1__1 == hap_127_0_0_1__1); + CPPUNIT_ASSERT(!(hap_127_0_0_1__2 == hap_127_0_0_1__1)); + CPPUNIT_ASSERT(hap_127_0_0_1__2 < hap_127_0_0_2__1); + CPPUNIT_ASSERT(hap_127_0_0_2__1 < hap_127_0_0_2__2); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(HostAddressTest); diff --git a/Swiften/Network/WindowsProxyProvider.cpp b/Swiften/Network/WindowsProxyProvider.cpp index 78bd72f..9a60bb4 100644 --- a/Swiften/Network/WindowsProxyProvider.cpp +++ b/Swiften/Network/WindowsProxyProvider.cpp @@ -11,18 +11,19 @@ */ #include <Swiften/Network/WindowsProxyProvider.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <boost/lexical_cast.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <windows.h> #include <Swiften/Base/ByteArray.h> #include <Swiften/Base/Log.h> #include <Swiften/Network/HostAddress.h> #include <Swiften/Network/HostAddressPort.h> namespace Swift { @@ -71,23 +72,23 @@ HostAddressPort WindowsProxyProvider::getHTTPConnectProxy() const { HostAddressPort WindowsProxyProvider::getSOCKS5Proxy() const { return socksProxy; } HostAddressPort WindowsProxyProvider::getAsHostAddressPort(std::string proxy) { HostAddressPort ret(HostAddress(), 0); try { std::pair<std::string, std::string> tmp; - int port = 0; + unsigned short port = 0; tmp = String::getSplittedAtFirst(proxy, ':'); // .c_str() is needed as tmp.second can include a \0 char which will end in an exception of the lexical cast. // with .c_str() the \0 will not be part of the string which is to be casted - port = boost::lexical_cast<int> (tmp.second.c_str()); + port = boost::numeric_cast<unsigned short>(boost::lexical_cast<int> (tmp.second.c_str())); ret = HostAddressPort(HostAddress::fromString(tmp.first).get(), port); } catch(...) { SWIFT_LOG(error) << "Exception occured while parsing windows proxy \"getHostAddressPort\"." << std::endl; } return ret; } diff --git a/Swiften/Parser/AttributeMap.cpp b/Swiften/Parser/AttributeMap.cpp index c112d52..f6767de 100644 --- a/Swiften/Parser/AttributeMap.cpp +++ b/Swiften/Parser/AttributeMap.cpp @@ -1,54 +1,54 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Parser/AttributeMap.h> #include <algorithm> -#include <boost/lambda/bind.hpp> -#include <boost/lambda/lambda.hpp> #include <boost/optional.hpp> using namespace Swift; -namespace lambda = boost::lambda; AttributeMap::AttributeMap() { } std::string AttributeMap::getAttribute(const std::string& attribute, const std::string& ns) const { - AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(), - lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, ns)); + const auto i = std::find_if(attributes.begin(), attributes.end(), [&](const Entry& entry) { + return entry.getAttribute() == Attribute(attribute, ns); + }); if (i == attributes.end()) { return ""; } else { return i->getValue(); } } bool AttributeMap::getBoolAttribute(const std::string& attribute, bool defaultValue) const { - AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(), - lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, "")); + const auto i = std::find_if(attributes.begin(), attributes.end(), [&](const Entry& entry) { + return entry.getAttribute() == Attribute(attribute, ""); + }); if (i == attributes.end()) { return defaultValue; } else { return i->getValue() == "true" || i->getValue() == "1"; } } boost::optional<std::string> AttributeMap::getAttributeValue(const std::string& attribute) const { - AttributeValueMap::const_iterator i = std::find_if(attributes.begin(), attributes.end(), - lambda::bind(&AttributeMap::Entry::getAttribute, lambda::_1) == Attribute(attribute, "")); + const auto i = std::find_if(attributes.begin(), attributes.end(), [&](const Entry& entry) { + return entry.getAttribute() == Attribute(attribute, ""); + }); if (i == attributes.end()) { return boost::optional<std::string>(); } else { return i->getValue(); } } void AttributeMap::addAttribute(const std::string& name, const std::string& ns, const std::string& value) { diff --git a/Swiften/Parser/BOSHBodyExtractor.cpp b/Swiften/Parser/BOSHBodyExtractor.cpp index c45d338..ff56792 100644 --- a/Swiften/Parser/BOSHBodyExtractor.cpp +++ b/Swiften/Parser/BOSHBodyExtractor.cpp @@ -1,21 +1,19 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Parser/BOSHBodyExtractor.h> #include <memory> -#include <boost/numeric/conversion/cast.hpp> - #include <Swiften/Parser/XMLParser.h> #include <Swiften/Parser/XMLParserClient.h> #include <Swiften/Parser/XMLParserFactory.h> namespace Swift { class BOSHBodyParserClient : public XMLParserClient { public: BOSHBodyParserClient(BOSHBodyExtractor* bodyExtractor) : bodyExtractor(bodyExtractor) { @@ -113,28 +111,30 @@ BOSHBodyExtractor::BOSHBodyExtractor(XMLParserFactory* parserFactory, const Byte if (std::distance(j, data.rend()) < 6 || *(j+5) != '<' || *(j+4) != '/' || *(j+3) != 'b' || *(j+2) != 'o' || *(j+1) != 'd' || *j != 'y') { return; } j += 6; } body = BOSHBody(); if (!endElementSeen) { + assert(i <= j.base()); body->content = std::string( reinterpret_cast<const char*>(vecptr(data) + std::distance(data.begin(), i)), - boost::numeric_cast<size_t>(std::distance(i, j.base()))); + static_cast<size_t>(std::distance(i, j.base()))); } // Parse the body element BOSHBodyParserClient parserClient(this); std::shared_ptr<XMLParser> parser(parserFactory->createXMLParser(&parserClient)); + assert(data.begin() <= i); if (!parser->parse(std::string( reinterpret_cast<const char*>(vecptr(data)), - boost::numeric_cast<size_t>(std::distance(data.begin(), i))))) { + static_cast<size_t>(std::distance(data.begin(), i))))) { /* TODO: This needs to be only validating the BOSH <body> element, so that XMPP parsing errors are caught at the correct higher layer */ body = boost::optional<BOSHBody>(); return; } } } diff --git a/Swiften/Parser/EnumParser.h b/Swiften/Parser/EnumParser.h index cf17ead..0da765e 100644 --- a/Swiften/Parser/EnumParser.h +++ b/Swiften/Parser/EnumParser.h @@ -1,25 +1,24 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <cassert> #include <map> #include <string> #include <boost/optional.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> namespace Swift { template<typename T> class SWIFTEN_API EnumParser { public: EnumParser() { } EnumParser& operator()(T value, const std::string& text) { diff --git a/Swiften/Parser/ExpatParser.cpp b/Swiften/Parser/ExpatParser.cpp index 77d959c..8415c42 100644 --- a/Swiften/Parser/ExpatParser.cpp +++ b/Swiften/Parser/ExpatParser.cpp @@ -1,25 +1,24 @@ /* * Copyright (c) 2010-2016 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Parser/ExpatParser.h> #include <cassert> +#include <limits> #include <memory> #include <string> #include <expat.h> -#include <boost/numeric/conversion/cast.hpp> - #include <Swiften/Base/String.h> #include <Swiften/Parser/XMLParserClient.h> #pragma clang diagnostic ignored "-Wdisabled-macro-expansion" namespace Swift { static const char NAMESPACE_SEPARATOR = '\x01'; @@ -78,19 +77,22 @@ ExpatParser::ExpatParser(XMLParserClient* client) : XMLParser(client), p(new Pri XML_SetXmlDeclHandler(p->parser_, handleXMLDeclaration); XML_SetEntityDeclHandler(p->parser_, handleEntityDeclaration); } ExpatParser::~ExpatParser() { XML_ParserFree(p->parser_); } bool ExpatParser::parse(const std::string& data) { - bool success = XML_Parse(p->parser_, data.c_str(), boost::numeric_cast<int>(data.size()), false) == XML_STATUS_OK; + if (data.size() > std::numeric_limits<int>::max()) { + return false; + } + bool success = XML_Parse(p->parser_, data.c_str(), static_cast<int>(data.size()), false) == XML_STATUS_OK; /*if (!success) { std::cout << "ERROR: " << XML_ErrorString(XML_GetErrorCode(p->parser_)) << " while parsing " << data << std::endl; }*/ return success; } void ExpatParser::stopParser() { XML_StopParser(p->parser_, static_cast<XML_Bool>(0)); } diff --git a/Swiften/Parser/LibXMLParser.cpp b/Swiften/Parser/LibXMLParser.cpp index be0a92d..5bd3737 100644 --- a/Swiften/Parser/LibXMLParser.cpp +++ b/Swiften/Parser/LibXMLParser.cpp @@ -1,24 +1,23 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Parser/LibXMLParser.h> #include <cassert> #include <cstring> +#include <limits> #include <memory> #include <string> -#include <boost/numeric/conversion/cast.hpp> - #include <libxml/parser.h> #include <Swiften/Base/Log.h> #include <Swiften/Parser/XMLParserClient.h> namespace Swift { struct LibXMLParser::Private { xmlSAXHandler handler_; @@ -30,33 +29,35 @@ static void handleStartElement(void* parser, const xmlChar* name, const xmlChar* if (nbDefaulted != 0) { // Just because i don't understand what this means yet :-) SWIFT_LOG(error) << "Unexpected nbDefaulted on XML element" << std::endl; } for (int i = 0; i < nbAttributes*5; i += 5) { std::string attributeNS = ""; if (attributes[i+2]) { attributeNS = std::string(reinterpret_cast<const char*>(attributes[i+2])); } + assert(attributes[i+4] >= attributes[i+3]); attributeValues.addAttribute( std::string(reinterpret_cast<const char*>(attributes[i])), attributeNS, std::string(reinterpret_cast<const char*>(attributes[i+3]), - boost::numeric_cast<size_t>(attributes[i+4]-attributes[i+3]))); + static_cast<size_t>(attributes[i+4]-attributes[i+3]))); } static_cast<XMLParser*>(parser)->getClient()->handleStartElement(reinterpret_cast<const char*>(name), (xmlns ? reinterpret_cast<const char*>(xmlns) : std::string()), attributeValues); } static void handleEndElement(void *parser, const xmlChar* name, const xmlChar*, const xmlChar* xmlns) { static_cast<XMLParser*>(parser)->getClient()->handleEndElement(reinterpret_cast<const char*>(name), (xmlns ? reinterpret_cast<const char*>(xmlns) : std::string())); } static void handleCharacterData(void* parser, const xmlChar* data, int len) { - static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(reinterpret_cast<const char*>(data), boost::numeric_cast<size_t>(len))); + assert(len >= 0); + static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(reinterpret_cast<const char*>(data), static_cast<size_t>(len))); } static void handleError(void*, const char* /*m*/, ... ) { /* va_list args; va_start(args, m); vfprintf(stdout, m, args); va_end(args); */ @@ -88,19 +89,22 @@ LibXMLParser::LibXMLParser(XMLParserClient* client) : XMLParser(client), p(new P } LibXMLParser::~LibXMLParser() { if (p->context_) { xmlFreeParserCtxt(p->context_); } } bool LibXMLParser::parse(const std::string& data) { - if (xmlParseChunk(p->context_, data.c_str(), boost::numeric_cast<int>(data.size()), false) == XML_ERR_OK) { + if (data.size() > std::numeric_limits<int>::max()) { + return false; + } + if (xmlParseChunk(p->context_, data.c_str(), static_cast<int>(data.size()), false) == XML_ERR_OK) { return true; } xmlError* error = xmlCtxtGetLastError(p->context_); if (error->code == XML_WAR_NS_URI || error->code == XML_WAR_NS_URI_RELATIVE) { xmlCtxtResetLastError(p->context_); p->context_->errNo = XML_ERR_OK; return true; } return false; diff --git a/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp b/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp index 405c593..71bce54 100644 --- a/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp +++ b/Swiften/Parser/PayloadParsers/BytestreamsParser.cpp @@ -1,35 +1,38 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Parser/PayloadParsers/BytestreamsParser.h> #include <boost/lexical_cast.hpp> +#include <boost/numeric/conversion/cast.hpp> namespace Swift { BytestreamsParser::BytestreamsParser() : level(TopLevel) { } BytestreamsParser::~BytestreamsParser() { } void BytestreamsParser::handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) { if (level == TopLevel) { getPayloadInternal()->setStreamID(attributes.getAttribute("sid")); } else if (level == PayloadLevel) { if (element == "streamhost") { try { - getPayloadInternal()->addStreamHost(Bytestreams::StreamHost(attributes.getAttribute("host"), JID(attributes.getAttribute("jid")), boost::lexical_cast<int>(attributes.getAttribute("port")))); + getPayloadInternal()->addStreamHost(Bytestreams::StreamHost(attributes.getAttribute("host"), JID(attributes.getAttribute("jid")), boost::numeric_cast<unsigned short>(boost::lexical_cast<int>(attributes.getAttribute("port"))))); + } + catch (boost::numeric::bad_numeric_cast&) { } catch (boost::bad_lexical_cast&) { } } else if (element == "streamhost-used") { getPayloadInternal()->setUsedStreamHost(JID(attributes.getAttribute("jid"))); } } ++level; diff --git a/Swiften/Parser/PayloadParsers/ForwardedParser.h b/Swiften/Parser/PayloadParsers/ForwardedParser.h index f91fda5..c9f13df 100644 --- a/Swiften/Parser/PayloadParsers/ForwardedParser.h +++ b/Swiften/Parser/PayloadParsers/ForwardedParser.h @@ -1,36 +1,35 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Forwarded.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class StanzaParser; class DelayParser; class SWIFTEN_API ForwardedParser : public GenericPayloadParser<Forwarded> { public: ForwardedParser(PayloadParserFactoryCollection* factories); - virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; enum Level { TopLevel = 0, PayloadLevel = 1 }; private: PayloadParserFactoryCollection* factories_; std::shared_ptr<StanzaParser> childParser_; diff --git a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp index ea7bdbf..9e56b63 100644 --- a/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp +++ b/Swiften/Parser/PayloadParsers/FullPayloadParserFactoryCollection.cpp @@ -47,35 +47,41 @@ #include <Swiften/Parser/PayloadParsers/JingleParserFactory.h> #include <Swiften/Parser/PayloadParsers/JingleReasonParser.h> #include <Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h> #include <Swiften/Parser/PayloadParsers/LastParser.h> #include <Swiften/Parser/PayloadParsers/MAMFinParser.h> #include <Swiften/Parser/PayloadParsers/MAMQueryParser.h> #include <Swiften/Parser/PayloadParsers/MAMResultParser.h> #include <Swiften/Parser/PayloadParsers/MIXParticipantParserFactory.h> #include <Swiften/Parser/PayloadParsers/MIXCreateParser.h> +#include <Swiften/Parser/PayloadParsers/MIXRegisterNickParserFactory.h> +#include <Swiften/Parser/PayloadParsers/MIXSetNickParserFactory.h> #include <Swiften/Parser/PayloadParsers/MIXDestroyParser.h> +#include <Swiften/Parser/PayloadParsers/MIXUpdateSubscriptionParser.h> #include <Swiften/Parser/PayloadParsers/MIXJoinParserFactory.h> +#include <Swiften/Parser/PayloadParsers/MIXPayloadParserFactory.h> #include <Swiften/Parser/PayloadParsers/MIXUserPreferenceParser.h> +#include <Swiften/Parser/PayloadParsers/MIXLeaveParser.h> #include <Swiften/Parser/PayloadParsers/MUCAdminPayloadParser.h> #include <Swiften/Parser/PayloadParsers/MUCDestroyPayloadParser.h> #include <Swiften/Parser/PayloadParsers/MUCInvitationPayloadParser.h> #include <Swiften/Parser/PayloadParsers/MUCOwnerPayloadParser.h> #include <Swiften/Parser/PayloadParsers/MUCOwnerPayloadParserFactory.h> #include <Swiften/Parser/PayloadParsers/MUCUserPayloadParserFactory.h> #include <Swiften/Parser/PayloadParsers/NicknameParser.h> #include <Swiften/Parser/PayloadParsers/PriorityParser.h> #include <Swiften/Parser/PayloadParsers/PrivateStorageParserFactory.h> #include <Swiften/Parser/PayloadParsers/PubSubErrorParserFactory.h> #include <Swiften/Parser/PayloadParsers/PubSubEventParser.h> #include <Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h> #include <Swiften/Parser/PayloadParsers/PubSubParser.h> #include <Swiften/Parser/PayloadParsers/RawXMLPayloadParserFactory.h> +#include <Swiften/Parser/PayloadParsers/ReferencePayloadParser.h> #include <Swiften/Parser/PayloadParsers/ReplaceParser.h> #include <Swiften/Parser/PayloadParsers/ResourceBindParser.h> #include <Swiften/Parser/PayloadParsers/ResultSetParser.h> #include <Swiften/Parser/PayloadParsers/RosterItemExchangeParser.h> #include <Swiften/Parser/PayloadParsers/RosterParser.h> #include <Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h> #include <Swiften/Parser/PayloadParsers/SearchPayloadParser.h> #include <Swiften/Parser/PayloadParsers/SecurityLabelParserFactory.h> #include <Swiften/Parser/PayloadParsers/SecurityLabelsCatalogParser.h> @@ -129,21 +135,26 @@ FullPayloadParserFactoryCollection::FullPayloadParserFactoryCollection() { factories_.push_back(std::make_shared<GenericPayloadParserFactory<SearchPayloadParser> >("query", "jabber:iq:search")); factories_.push_back(std::make_shared<GenericPayloadParserFactory<StreamInitiationParser> >("si", "http://jabber.org/protocol/si")); factories_.push_back(std::make_shared<GenericPayloadParserFactory<BytestreamsParser> >("query", "http://jabber.org/protocol/bytestreams")); factories_.push_back(std::make_shared<GenericPayloadParserFactory<VCardUpdateParser> >("x", "vcard-temp:x:update")); factories_.push_back(std::make_shared<GenericPayloadParserFactory<VCardParser> >("vCard", "vcard-temp")); factories_.push_back(std::make_shared<PrivateStorageParserFactory>(this)); factories_.push_back(std::make_shared<ChatStateParserFactory>()); factories_.push_back(std::make_shared<ClientStateParserFactory>()); factories_.push_back(std::make_shared<MIXParticipantParserFactory>()); - factories_.push_back(std::make_shared<GenericPayloadParserFactory<MIXDestroyParser> >("destroy", "urn:xmpp:mix:1")); - factories_.push_back(std::make_shared<GenericPayloadParserFactory<MIXCreateParser> >("create", "urn:xmpp:mix:1")); - factories_.push_back(std::make_shared<GenericPayloadParserFactory<MIXUserPreferenceParser> >("user-preference", "urn:xmpp:mix:1")); + factories_.push_back(std::make_shared<GenericPayloadParserFactory<MIXDestroyParser> >("destroy", "urn:xmpp:mix:0")); + factories_.push_back(std::make_shared<MIXRegisterNickParserFactory>()); + factories_.push_back(std::make_shared<MIXSetNickParserFactory>()); + factories_.push_back(std::make_shared<GenericPayloadParserFactory<MIXCreateParser> >("create", "urn:xmpp:mix:0")); + factories_.push_back(std::make_shared<GenericPayloadParserFactory<MIXUpdateSubscriptionParser> >("update-subscription", "urn:xmpp:mix:0")); + factories_.push_back(std::make_shared<GenericPayloadParserFactory<MIXUserPreferenceParser> >("user-preference", "urn:xmpp:mix:0")); + factories_.push_back(std::make_shared<MIXPayloadParserFactory>()); + factories_.push_back(std::make_shared<GenericPayloadParserFactory<MIXLeaveParser> >("leave", "urn:xmpp:mix:0")); factories_.push_back(std::make_shared<MUCUserPayloadParserFactory>(this)); factories_.push_back(std::make_shared<MUCOwnerPayloadParserFactory>(this)); factories_.push_back(std::make_shared<GenericPayloadParserFactory<MUCInvitationPayloadParser> >("x", "jabber:x:conference")); factories_.push_back(std::make_shared<GenericPayloadParserFactory<MUCAdminPayloadParser> >("query", "http://jabber.org/protocol/muc#admin")); factories_.push_back(std::make_shared<GenericPayloadParserFactory<MUCDestroyPayloadParser> >("destroy", "http://jabber.org/protocol/muc#user")); factories_.push_back(std::make_shared<GenericPayloadParserFactory<MUCDestroyPayloadParser> >("destroy", "http://jabber.org/protocol/muc#owner")); factories_.push_back(std::make_shared<GenericPayloadParserFactory<NicknameParser> >("nick", "http://jabber.org/protocol/nick")); factories_.push_back(std::make_shared<JingleParserFactory>(this)); factories_.push_back(std::make_shared<GenericPayloadParserFactory<JingleReasonParser> >("reason", "urn:xmpp:jingle:1")); @@ -171,18 +182,19 @@ FullPayloadParserFactoryCollection::FullPayloadParserFactoryCollection() { factories_.push_back(std::make_shared<GenericPayloadParserFactory<MAMQueryParser> >("query", "urn:xmpp:mam:0")); factories_.push_back(std::make_shared<GenericPayloadParserFactory<MAMFinParser> >("fin", "urn:xmpp:mam:0")); factories_.push_back(std::make_shared<GenericPayloadParserFactory2<IsodeIQDelegationParser> >("delegate", "http://isode.com/iq_delegation", this)); factories_.push_back(std::make_shared<GenericPayloadParserFactory<CarbonsEnableParser> >("enable", "urn:xmpp:carbons:2")); factories_.push_back(std::make_shared<GenericPayloadParserFactory<CarbonsDisableParser> >("disable", "urn:xmpp:carbons:2")); factories_.push_back(std::make_shared<GenericPayloadParserFactory2<CarbonsReceivedParser> >("received", "urn:xmpp:carbons:2", this)); factories_.push_back(std::make_shared<GenericPayloadParserFactory2<CarbonsSentParser> >("sent", "urn:xmpp:carbons:2", this)); factories_.push_back(std::make_shared<GenericPayloadParserFactory<CarbonsPrivateParser> >("private", "urn:xmpp:carbons:2")); factories_.push_back(std::make_shared<MIXJoinParserFactory>()); + factories_.push_back(std::make_shared<GenericPayloadParserFactory2<ReferencePayloadParser> >("reference", "urn:xmpp:reference:0", this)); for (auto& factory : factories_) { addFactory(factory.get()); } defaultFactory_ = new RawXMLPayloadParserFactory(); setDefaultFactory(defaultFactory_); } FullPayloadParserFactoryCollection::~FullPayloadParserFactoryCollection() { diff --git a/Swiften/Parser/PayloadParsers/IBBParser.cpp b/Swiften/Parser/PayloadParsers/IBBParser.cpp index 9b6babc..1ba44e1 100644 --- a/Swiften/Parser/PayloadParsers/IBBParser.cpp +++ b/Swiften/Parser/PayloadParsers/IBBParser.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Parser/PayloadParsers/IBBParser.h> #include <boost/lexical_cast.hpp> #include <Swiften/StringCodecs/Base64.h> @@ -33,19 +33,19 @@ void IBBParser::handleStartElement(const std::string& element, const std::string getPayloadInternal()->setAction(IBB::Open); getPayloadInternal()->setStreamID(attributes.getAttribute("sid")); if (attributes.getAttribute("stanza") == "message") { getPayloadInternal()->setStanzaType(IBB::MessageStanza); } else { getPayloadInternal()->setStanzaType(IBB::IQStanza); } try { - getPayloadInternal()->setBlockSize(boost::lexical_cast<int>(attributes.getAttribute("block-size"))); + getPayloadInternal()->setBlockSize(boost::lexical_cast<unsigned int>(attributes.getAttribute("block-size"))); } catch (boost::bad_lexical_cast&) { } } else if (element == "close") { getPayloadInternal()->setAction(IBB::Close); getPayloadInternal()->setStreamID(attributes.getAttribute("sid")); } } diff --git a/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h b/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h index eaedd27..af2f061 100644 --- a/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h +++ b/Swiften/Parser/PayloadParsers/IsodeIQDelegationParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/IsodeIQDelegation.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API IsodeIQDelegationParser : public GenericPayloadParser<IsodeIQDelegation> { public: IsodeIQDelegationParser(PayloadParserFactoryCollection* parsers); - virtual ~IsodeIQDelegationParser(); + virtual ~IsodeIQDelegationParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp index e639e20..a405e0e 100644 --- a/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp +++ b/Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.cpp @@ -1,24 +1,25 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Parser/PayloadParsers/JingleS5BTransportMethodPayloadParser.h> #include <boost/lexical_cast.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <boost/optional.hpp> #include <Swiften/Base/Log.h> namespace Swift { JingleS5BTransportMethodPayloadParser::JingleS5BTransportMethodPayloadParser() : level(0) { } @@ -34,22 +35,22 @@ namespace Swift { SWIFT_LOG(warning) << "Unknown S5B mode; falling back to defaul!"; getPayloadInternal()->setMode(JingleS5BTransportPayload::TCPMode); } getPayloadInternal()->setDstAddr(attributes.getAttributeValue("dstaddr").get_value_or("")); } else if (level == 1) { if (element == "candidate") { JingleS5BTransportPayload::Candidate candidate; candidate.cid = attributes.getAttributeValue("cid").get_value_or(""); - int port = -1; + unsigned short port = 0; try { - port = boost::lexical_cast<int>(attributes.getAttributeValue("port").get_value_or("-1")); - } catch(boost::bad_lexical_cast &) { } + port = boost::numeric_cast<unsigned short>(boost::lexical_cast<int>(attributes.getAttributeValue("port").get_value_or("0"))); + } catch(...) { } candidate.hostPort = HostAddressPort(HostAddress::fromString(attributes.getAttributeValue("host").get_value_or("")).get_value_or(HostAddress()), 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")); diff --git a/Swiften/Parser/PayloadParsers/MAMFinParser.h b/Swiften/Parser/PayloadParsers/MAMFinParser.h index f08231e..419d542 100644 --- a/Swiften/Parser/PayloadParsers/MAMFinParser.h +++ b/Swiften/Parser/PayloadParsers/MAMFinParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MAMFin.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class ResultSetParser; class SWIFTEN_API MAMFinParser : public GenericPayloadParser<MAMFin> { public: MAMFinParser(); - virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; enum Level { TopLevel = 0, PayloadLevel = 1 }; private: std::shared_ptr<ResultSetParser> resultSetParser_; int level_; diff --git a/Swiften/Parser/PayloadParsers/MAMQueryParser.h b/Swiften/Parser/PayloadParsers/MAMQueryParser.h index 7e4b58a..ab062c5 100644 --- a/Swiften/Parser/PayloadParsers/MAMQueryParser.h +++ b/Swiften/Parser/PayloadParsers/MAMQueryParser.h @@ -1,36 +1,35 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MAMQuery.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class ResultSetParser; class FormParser; class SWIFTEN_API MAMQueryParser : public GenericPayloadParser<MAMQuery> { public: MAMQueryParser(); - virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; enum Level { TopLevel = 0, PayloadLevel = 1 }; private: std::shared_ptr<FormParser> formParser_; std::shared_ptr<ResultSetParser> resultSetParser_; diff --git a/Swiften/Parser/PayloadParsers/MAMResultParser.h b/Swiften/Parser/PayloadParsers/MAMResultParser.h index e68e365..f058e15 100644 --- a/Swiften/Parser/PayloadParsers/MAMResultParser.h +++ b/Swiften/Parser/PayloadParsers/MAMResultParser.h @@ -1,36 +1,35 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MAMResult.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class ForwardedParser; class SWIFTEN_API MAMResultParser : public GenericPayloadParser<MAMResult> { public: MAMResultParser(PayloadParserFactoryCollection* factories); - virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; enum Level { TopLevel = 0, PayloadLevel = 1 }; private: std::shared_ptr<ForwardedParser> payloadParser_; PayloadParserFactoryCollection* factories_; diff --git a/Swiften/Parser/PayloadParsers/MIXCreateParser.h b/Swiften/Parser/PayloadParsers/MIXCreateParser.h index 60e3040..ef123e1 100644 --- a/Swiften/Parser/PayloadParsers/MIXCreateParser.h +++ b/Swiften/Parser/PayloadParsers/MIXCreateParser.h @@ -1,32 +1,37 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MIXCreate.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParser; class SWIFTEN_API MIXCreateParser : public GenericPayloadParser<MIXCreate> { public: MIXCreateParser(); - virtual ~MIXCreateParser(); + virtual ~MIXCreateParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level_; std::shared_ptr<PayloadParser> currentPayloadParser_; }; } diff --git a/Swiften/Parser/PayloadParsers/MIXDestroyParser.h b/Swiften/Parser/PayloadParsers/MIXDestroyParser.h index 3a925de..8cfd91e 100644 --- a/Swiften/Parser/PayloadParsers/MIXDestroyParser.h +++ b/Swiften/Parser/PayloadParsers/MIXDestroyParser.h @@ -1,31 +1,36 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MIXDestroy.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParser; class SWIFTEN_API MIXDestroyParser : public GenericPayloadParser<MIXDestroy> { public: MIXDestroyParser(); - virtual ~MIXDestroyParser(); + virtual ~MIXDestroyParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level_; }; } diff --git a/Swiften/Parser/PayloadParsers/MIXJoinParser.cpp b/Swiften/Parser/PayloadParsers/MIXJoinParser.cpp index 2509667..6e72f90 100644 --- a/Swiften/Parser/PayloadParsers/MIXJoinParser.cpp +++ b/Swiften/Parser/PayloadParsers/MIXJoinParser.cpp @@ -3,19 +3,18 @@ * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ #include <Swiften/Parser/PayloadParsers/MIXJoinParser.h> #include <boost/optional.hpp> #include <Swiften/Parser/PayloadParserFactory.h> -#include <Swiften/Parser/PayloadParsers/MIXSubscribeParser.h> #include <Swiften/Parser/PayloadParsers/FormParser.h> using namespace Swift; MIXJoinParser::MIXJoinParser() : level_(0) { } MIXJoinParser::~MIXJoinParser() { } @@ -29,20 +28,22 @@ void MIXJoinParser::handleStartElement(const std::string& element, const std::st } if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) { if (boost::optional<JID> jid = JID::parse(*attributeValue)) { getPayloadInternal()->setJID(*jid); } } } if (level_ == 1) { - if (element == "subscribe" && ns == "urn:xmpp:mix:1") { - currentPayloadParser_ = std::make_shared<MIXSubscribeParser>(); + if (element == "subscribe" && ns == "urn:xmpp:mix:0") { + if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) { + getPayloadInternal()->addSubscription(*attributeValue); + } } if (element == "x" && ns == "jabber:x:data") { currentPayloadParser_ = std::make_shared<FormParser>(); } } if (level_ >= 1 && currentPayloadParser_) { currentPayloadParser_->handleStartElement(element, ns, attributes); } @@ -51,21 +52,18 @@ void MIXJoinParser::handleStartElement(const std::string& element, const std::st void MIXJoinParser::handleEndElement(const std::string& element, const std::string& ns) { --level_; if (currentPayloadParser_) { if (level_ >= 1) { currentPayloadParser_->handleEndElement(element, ns); } if (level_ == 1) { - if (element == "subscribe" && ns == "urn:xmpp:mix:1") { - getPayloadInternal()->addSubscription(std::dynamic_pointer_cast<MIXSubscribe>(currentPayloadParser_->getPayload())); - } if (element == "x" && ns == "jabber:x:data") { getPayloadInternal()->setForm(std::dynamic_pointer_cast<Form>(currentPayloadParser_->getPayload())); } currentPayloadParser_.reset(); } } } void MIXJoinParser::handleCharacterData(const std::string& data) { diff --git a/Swiften/Parser/PayloadParsers/MIXJoinParser.h b/Swiften/Parser/PayloadParsers/MIXJoinParser.h index c0ded7b..f371d6f 100644 --- a/Swiften/Parser/PayloadParsers/MIXJoinParser.h +++ b/Swiften/Parser/PayloadParsers/MIXJoinParser.h @@ -1,32 +1,37 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MIXJoin.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParser; class SWIFTEN_API MIXJoinParser : public GenericPayloadParser<MIXJoin> { public: MIXJoinParser(); - virtual ~MIXJoinParser(); + virtual ~MIXJoinParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level_; std::shared_ptr<PayloadParser> currentPayloadParser_; }; } diff --git a/Swiften/Parser/PayloadParsers/MIXJoinParserFactory.h b/Swiften/Parser/PayloadParsers/MIXJoinParserFactory.h index 6103c70..8432c61 100644 --- a/Swiften/Parser/PayloadParsers/MIXJoinParserFactory.h +++ b/Swiften/Parser/PayloadParsers/MIXJoinParserFactory.h @@ -11,17 +11,17 @@ #include <Swiften/Parser/PayloadParsers/MIXJoinParser.h> namespace Swift { class SWIFTEN_API MIXJoinParserFactory : public PayloadParserFactory { public: MIXJoinParserFactory() { } virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const { - return element == "join" && ns == "urn:xmpp:mix:1"; + return element == "join" && ns == "urn:xmpp:mix:0"; } virtual PayloadParser* createPayloadParser() { return new MIXJoinParser(); } }; } diff --git a/Swiften/Parser/PayloadParsers/MIXLeaveParser.cpp b/Swiften/Parser/PayloadParsers/MIXLeaveParser.cpp new file mode 100644 index 0000000..6330925 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXLeaveParser.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/Parser/PayloadParsers/MIXLeaveParser.h> + +#include <boost/optional.hpp> + +namespace Swift { + +MIXLeaveParser::MIXLeaveParser() : level_(0) { +} + +MIXLeaveParser::~MIXLeaveParser() { +} + +void MIXLeaveParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) { + if (level_ == 0) { + if (auto attributeValue = attributes.getAttributeValue("channel")) { + if (auto jid = JID::parse(*attributeValue)) { + getPayloadInternal()->setChannel(*jid); + } + } + } + ++level_; +} + +void MIXLeaveParser::handleEndElement(const std::string&, const std::string&) { + --level_; +} + +void MIXLeaveParser::handleCharacterData(const std::string&) { + +} +} diff --git a/Swiften/Parser/PayloadParsers/MIXSubscribeParser.h b/Swiften/Parser/PayloadParsers/MIXLeaveParser.h index eecc0d2..b0798b4 100644 --- a/Swiften/Parser/PayloadParsers/MIXSubscribeParser.h +++ b/Swiften/Parser/PayloadParsers/MIXLeaveParser.h @@ -1,32 +1,35 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> -#include <Swiften/Elements/MIXSubscribe.h> +#include <Swiften/Elements/MIXLeave.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { - class PayloadParserFactoryCollection; - class PayloadParser; - class SWIFTEN_API MIXSubscribeParser : public GenericPayloadParser<MIXSubscribe> { + class SWIFTEN_API MIXLeaveParser : public GenericPayloadParser<MIXLeave> { public: - MIXSubscribeParser(); - virtual ~MIXSubscribeParser(); + MIXLeaveParser(); + virtual ~MIXLeaveParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level_; }; } diff --git a/Swiften/Parser/PayloadParsers/MIXPayloadParser.cpp b/Swiften/Parser/PayloadParsers/MIXPayloadParser.cpp new file mode 100644 index 0000000..51ef584 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXPayloadParser.cpp @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/Parser/PayloadParsers/MIXPayloadParser.h> + +namespace Swift { + +void MIXPayloadParser::handleTree(ParserElement::ref root) { + for (const auto& child : root->getAllChildren()) { + if (child->getName() == "nick" && child->getNamespace() == root->getNamespace()) { + getPayloadInternal()->setNick(child->getText()); + } else if (child->getName() == "jid" && child->getNamespace() == root->getNamespace()) { + if (boost::optional<JID> jid = JID::parse(child->getText())) { + getPayloadInternal()->setJID(*jid); + } + } else if (child->getName() == "submission-id" && child->getNamespace() == root->getNamespace()) { + getPayloadInternal()->setSubmissionID(child->getText()); + } + } +} + +} diff --git a/Swiften/Parser/PayloadParsers/MIXPayloadParser.h b/Swiften/Parser/PayloadParsers/MIXPayloadParser.h new file mode 100644 index 0000000..9133e8b --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXPayloadParser.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/MIXPayload.h> +#include <Swiften/Parser/GenericPayloadTreeParser.h> + +namespace Swift { + class SWIFTEN_API MIXPayloadParser : public GenericPayloadTreeParser<MIXPayload> { + public: + MIXPayloadParser() {} + virtual void handleTree(ParserElement::ref root) override; + }; +} diff --git a/Swiften/Parser/PayloadParsers/MIXPayloadParserFactory.h b/Swiften/Parser/PayloadParsers/MIXPayloadParserFactory.h new file mode 100644 index 0000000..8397b78 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXPayloadParserFactory.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <Swiften/Base/API.h> +#include <Swiften/Parser/GenericPayloadParserFactory.h> +#include <Swiften/Parser/PayloadParsers/MIXPayloadParser.h> + +namespace Swift { + class SWIFTEN_API MIXPayloadParserFactory : public PayloadParserFactory { + public: + MIXPayloadParserFactory() { + } + + virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const override { + return element == "mix" && ns == "urn:xmpp:mix:0"; + } + + virtual PayloadParser* createPayloadParser() override { + return new MIXPayloadParser(); + } + }; +} diff --git a/Swiften/Parser/PayloadParsers/MIXRegisterNickParser.cpp b/Swiften/Parser/PayloadParsers/MIXRegisterNickParser.cpp new file mode 100644 index 0000000..945e9b2 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXRegisterNickParser.cpp @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/Parser/PayloadParsers/MIXRegisterNickParser.h> + +namespace Swift { + +void MIXRegisterNickParser::handleTree(ParserElement::ref root) { + for (const auto& child : root->getAllChildren()) { + if (child->getName() == "nick" && child->getNamespace() == root->getNamespace()) { + getPayloadInternal()->setNick(child->getText()); + } + } +} + +} diff --git a/Swiften/Parser/PayloadParsers/MIXRegisterNickParser.h b/Swiften/Parser/PayloadParsers/MIXRegisterNickParser.h new file mode 100644 index 0000000..cfb618e --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXRegisterNickParser.h @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#pragma once + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/MIXRegisterNick.h> +#include <Swiften/Parser/GenericPayloadTreeParser.h> + +namespace Swift { + class SWIFTEN_API MIXRegisterNickParser : public GenericPayloadTreeParser<MIXRegisterNick> { + public: + MIXRegisterNickParser() {} + virtual void handleTree(ParserElement::ref root) override; + }; +} diff --git a/Swiften/Parser/PayloadParsers/MIXRegisterNickParserFactory.h b/Swiften/Parser/PayloadParsers/MIXRegisterNickParserFactory.h new file mode 100644 index 0000000..e03392c --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXRegisterNickParserFactory.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#pragma once + +#include <Swiften/Base/API.h> +#include <Swiften/Parser/GenericPayloadParserFactory.h> +#include <Swiften/Parser/PayloadParsers/MIXRegisterNickParser.h> + +namespace Swift { + class SWIFTEN_API MIXRegisterNickParserFactory : public PayloadParserFactory { + public: + MIXRegisterNickParserFactory() { + } + + virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const override { + return element == "register" && ns == "urn:xmpp:mix:0"; + } + + virtual PayloadParser* createPayloadParser() override { + return new MIXRegisterNickParser(); + } + }; +} diff --git a/Swiften/Parser/PayloadParsers/MIXSetNickParser.cpp b/Swiften/Parser/PayloadParsers/MIXSetNickParser.cpp new file mode 100644 index 0000000..34fec70 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXSetNickParser.cpp @@ -0,0 +1,19 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/Parser/PayloadParsers/MIXSetNickParser.h> + +namespace Swift { + +void MIXSetNickParser::handleTree(ParserElement::ref root) { + for (const auto& child : root->getAllChildren()) { + if (child->getName() == "nick" && child->getNamespace() == root->getNamespace()) { + getPayloadInternal()->setNick(child->getText()); + } + } +} + +} diff --git a/Swiften/Parser/PayloadParsers/MIXSetNickParser.h b/Swiften/Parser/PayloadParsers/MIXSetNickParser.h new file mode 100644 index 0000000..6d552c8 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXSetNickParser.h @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/MIXSetNick.h> +#include <Swiften/Parser/GenericPayloadTreeParser.h> + +namespace Swift { + class SWIFTEN_API MIXSetNickParser : public GenericPayloadTreeParser<MIXSetNick> { + public: + MIXSetNickParser() {} + virtual void handleTree(ParserElement::ref root) override; + }; +} diff --git a/Swiften/Parser/PayloadParsers/MIXSetNickParserFactory.h b/Swiften/Parser/PayloadParsers/MIXSetNickParserFactory.h new file mode 100644 index 0000000..e028873 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXSetNickParserFactory.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <Swiften/Base/API.h> +#include <Swiften/Parser/GenericPayloadParserFactory.h> +#include <Swiften/Parser/PayloadParsers/MIXSetNickParser.h> + +namespace Swift { + class SWIFTEN_API MIXSetNickParserFactory : public PayloadParserFactory { + public: + MIXSetNickParserFactory() { + } + + virtual bool canParse(const std::string& element, const std::string& ns, const AttributeMap&) const override { + return element == "setnick" && ns == "urn:xmpp:mix:0"; + } + + virtual PayloadParser* createPayloadParser() override { + return new MIXSetNickParser(); + } + }; +} diff --git a/Swiften/Parser/PayloadParsers/MIXSubscribeParser.cpp b/Swiften/Parser/PayloadParsers/MIXSubscribeParser.cpp deleted file mode 100644 index 1500716..0000000 --- a/Swiften/Parser/PayloadParsers/MIXSubscribeParser.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2017 Tarun Gupta - * Licensed under the simplified BSD license. - * See Documentation/Licenses/BSD-simplified.txt for more information. - */ - -#include <Swiften/Parser/PayloadParsers/MIXSubscribeParser.h> - -#include <boost/optional.hpp> - -#include <Swiften/Parser/PayloadParserFactory.h> -#include <Swiften/Parser/PayloadParserFactoryCollection.h> - -using namespace Swift; - -MIXSubscribeParser::MIXSubscribeParser() : level_(0) { -} - -MIXSubscribeParser::~MIXSubscribeParser() { -} - -void MIXSubscribeParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) { - if (level_ == 0) { - if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) { - getPayloadInternal()->setNode(*attributeValue); - } - } - ++level_; -} - -void MIXSubscribeParser::handleEndElement(const std::string& , const std::string& ) { - --level_; -} - -void MIXSubscribeParser::handleCharacterData(const std::string& ) { -} diff --git a/Swiften/Parser/PayloadParsers/MIXUpdateSubscriptionParser.cpp b/Swiften/Parser/PayloadParsers/MIXUpdateSubscriptionParser.cpp new file mode 100644 index 0000000..d530e49 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXUpdateSubscriptionParser.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/Parser/PayloadParsers/MIXUpdateSubscriptionParser.h> + +#include <boost/optional.hpp> + +#include <Swiften/Parser/PayloadParserFactory.h> +#include <Swiften/Parser/PayloadParsers/FormParser.h> + +namespace Swift { + +MIXUpdateSubscriptionParser::MIXUpdateSubscriptionParser() : level_(0) { +} + +MIXUpdateSubscriptionParser::~MIXUpdateSubscriptionParser() { +} + +void MIXUpdateSubscriptionParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) { + if (level_ == 0) { + if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("jid")) { + if (boost::optional<JID> jid = JID::parse(*attributeValue)) { + getPayloadInternal()->setJID(*jid); + } + } + } + + if (level_ == 1) { + if (element == "subscribe" && ns == "urn:xmpp:mix:0") { + if (boost::optional<std::string> attributeValue = attributes.getAttributeValue("node")) { + getPayloadInternal()->addSubscription(*attributeValue); + } + } + } + + ++level_; +} + +void MIXUpdateSubscriptionParser::handleEndElement(const std::string&, const std::string&) { + --level_; +} + +void MIXUpdateSubscriptionParser::handleCharacterData(const std::string&) { +} + +} diff --git a/Swiften/Parser/PayloadParsers/MIXUpdateSubscriptionParser.h b/Swiften/Parser/PayloadParsers/MIXUpdateSubscriptionParser.h new file mode 100644 index 0000000..47966ff --- /dev/null +++ b/Swiften/Parser/PayloadParsers/MIXUpdateSubscriptionParser.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +/* + * Copyright (c) 2017-2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <memory> + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/MIXUpdateSubscription.h> +#include <Swiften/Parser/GenericPayloadParser.h> + +namespace Swift { + class PayloadParser; + + class SWIFTEN_API MIXUpdateSubscriptionParser : public GenericPayloadParser<MIXUpdateSubscription> { + public: + MIXUpdateSubscriptionParser(); + virtual ~MIXUpdateSubscriptionParser() override; + + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; + + private: + int level_; + }; +} diff --git a/Swiften/Parser/PayloadParsers/MIXUserPreferenceParser.h b/Swiften/Parser/PayloadParsers/MIXUserPreferenceParser.h index 505087d..b2a2c10 100644 --- a/Swiften/Parser/PayloadParsers/MIXUserPreferenceParser.h +++ b/Swiften/Parser/PayloadParsers/MIXUserPreferenceParser.h @@ -1,32 +1,37 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MIXUserPreference.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParser; class SWIFTEN_API MIXUserPreferenceParser : public GenericPayloadParser<MIXUserPreference> { public: MIXUserPreferenceParser(); - virtual ~MIXUserPreferenceParser(); + virtual ~MIXUserPreferenceParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level_; std::shared_ptr<PayloadParser> currentPayloadParser_; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h b/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h index eabe3db..383ceae 100644 --- a/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubAffiliationParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubAffiliation.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubAffiliationParser : public GenericPayloadParser<PubSubAffiliation> { public: PubSubAffiliationParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubAffiliationParser(); + virtual ~PubSubAffiliationParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h b/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h index 2f80dbd..48e3825 100644 --- a/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubAffiliationsParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubAffiliations.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubAffiliationsParser : public GenericPayloadParser<PubSubAffiliations> { public: PubSubAffiliationsParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubAffiliationsParser(); + virtual ~PubSubAffiliationsParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubConfigureParser.h b/Swiften/Parser/PayloadParsers/PubSubConfigureParser.h index 90c2f3e..e53d477 100644 --- a/Swiften/Parser/PayloadParsers/PubSubConfigureParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubConfigureParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubConfigure.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubConfigureParser : public GenericPayloadParser<PubSubConfigure> { public: PubSubConfigureParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubConfigureParser(); + virtual ~PubSubConfigureParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubCreateParser.h b/Swiften/Parser/PayloadParsers/PubSubCreateParser.h index a1ada74..626419c 100644 --- a/Swiften/Parser/PayloadParsers/PubSubCreateParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubCreateParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubCreate.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubCreateParser : public GenericPayloadParser<PubSubCreate> { public: PubSubCreateParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubCreateParser(); + virtual ~PubSubCreateParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubDefaultParser.h b/Swiften/Parser/PayloadParsers/PubSubDefaultParser.h index 01bea7b..08f6b43 100644 --- a/Swiften/Parser/PayloadParsers/PubSubDefaultParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubDefaultParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubDefault.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubDefaultParser : public GenericPayloadParser<PubSubDefault> { public: PubSubDefaultParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubDefaultParser(); + virtual ~PubSubDefaultParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubErrorParser.h b/Swiften/Parser/PayloadParsers/PubSubErrorParser.h index 9c41095..273da82 100644 --- a/Swiften/Parser/PayloadParsers/PubSubErrorParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubErrorParser.h @@ -3,30 +3,29 @@ * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubError.h> #include <Swiften/Parser/EnumParser.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class SWIFTEN_API PubSubErrorParser : public GenericPayloadParser<PubSubError> { public: PubSubErrorParser(); - virtual ~PubSubErrorParser(); + virtual ~PubSubErrorParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; EnumParser<PubSubError::Type> typeParser; EnumParser<PubSubError::UnsupportedFeatureType> unsupportedTypeParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h b/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h index 4bb9bd9..f4d6327 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventAssociateParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventAssociate.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventAssociateParser : public GenericPayloadParser<PubSubEventAssociate> { public: PubSubEventAssociateParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventAssociateParser(); + virtual ~PubSubEventAssociateParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h b/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h index ffdafcf..ffa1deb 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventCollectionParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventCollection.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventCollectionParser : public GenericPayloadParser<PubSubEventCollection> { public: PubSubEventCollectionParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventCollectionParser(); + virtual ~PubSubEventCollectionParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h b/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h index dddb7a4..6b68d86 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventConfigurationParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventConfiguration.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventConfigurationParser : public GenericPayloadParser<PubSubEventConfiguration> { public: PubSubEventConfigurationParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventConfigurationParser(); + virtual ~PubSubEventConfigurationParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h b/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h index 270430e..54a1913 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventDeleteParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventDelete.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventDeleteParser : public GenericPayloadParser<PubSubEventDelete> { public: PubSubEventDeleteParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventDeleteParser(); + virtual ~PubSubEventDeleteParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h b/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h index 5f7f1af..6a0a7ce 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventDisassociateParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventDisassociate.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventDisassociateParser : public GenericPayloadParser<PubSubEventDisassociate> { public: PubSubEventDisassociateParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventDisassociateParser(); + virtual ~PubSubEventDisassociateParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventItemParser.h b/Swiften/Parser/PayloadParsers/PubSubEventItemParser.h index bd2e72e..e9a986d 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventItemParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventItemParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventItem.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventItemParser : public GenericPayloadParser<PubSubEventItem> { public: PubSubEventItemParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventItemParser(); + virtual ~PubSubEventItemParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h b/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h index 34b3669..067a9f7 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventItemsParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventItems.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventItemsParser : public GenericPayloadParser<PubSubEventItems> { public: PubSubEventItemsParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventItemsParser(); + virtual ~PubSubEventItemsParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventParser.h b/Swiften/Parser/PayloadParsers/PubSubEventParser.h index 3b231b0..02cf01f 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEvent.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventParser : public GenericPayloadParser<PubSubEvent> { public: PubSubEventParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventParser(); + virtual ~PubSubEventParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h b/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h index 563283c..1c9e623 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventPurgeParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventPurge.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventPurgeParser : public GenericPayloadParser<PubSubEventPurge> { public: PubSubEventPurgeParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventPurgeParser(); + virtual ~PubSubEventPurgeParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h b/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h index 603fbec..be7593e 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventRedirectParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventRedirect.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventRedirectParser : public GenericPayloadParser<PubSubEventRedirect> { public: PubSubEventRedirectParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventRedirectParser(); + virtual ~PubSubEventRedirectParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h b/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h index 141790b..83a8e66 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventRetractParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventRetract.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventRetractParser : public GenericPayloadParser<PubSubEventRetract> { public: PubSubEventRetractParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventRetractParser(); + virtual ~PubSubEventRetractParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h b/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h index 0d56a20..6f2eeeb 100644 --- a/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubEventSubscriptionParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventSubscription.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubEventSubscriptionParser : public GenericPayloadParser<PubSubEventSubscription> { public: PubSubEventSubscriptionParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubEventSubscriptionParser(); + virtual ~PubSubEventSubscriptionParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubItemParser.h b/Swiften/Parser/PayloadParsers/PubSubItemParser.h index c6e4ccf..cbbd3a5 100644 --- a/Swiften/Parser/PayloadParsers/PubSubItemParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubItemParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubItem.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubItemParser : public GenericPayloadParser<PubSubItem> { public: PubSubItemParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubItemParser(); + virtual ~PubSubItemParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubItemsParser.h b/Swiften/Parser/PayloadParsers/PubSubItemsParser.h index ad6e746..d792e1b 100644 --- a/Swiften/Parser/PayloadParsers/PubSubItemsParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubItemsParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubItems.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubItemsParser : public GenericPayloadParser<PubSubItems> { public: PubSubItemsParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubItemsParser(); + virtual ~PubSubItemsParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOptionsParser.h b/Swiften/Parser/PayloadParsers/PubSubOptionsParser.h index ac14caf..ee11f70 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOptionsParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOptionsParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOptions.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOptionsParser : public GenericPayloadParser<PubSubOptions> { public: PubSubOptionsParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOptionsParser(); + virtual ~PubSubOptionsParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h index 0a6503f..7bb93f1 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerAffiliation.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOwnerAffiliationParser : public GenericPayloadParser<PubSubOwnerAffiliation> { public: PubSubOwnerAffiliationParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOwnerAffiliationParser(); + virtual ~PubSubOwnerAffiliationParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h index 52c7fa9..20df72f 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOwnerAffiliationsParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerAffiliations.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOwnerAffiliationsParser : public GenericPayloadParser<PubSubOwnerAffiliations> { public: PubSubOwnerAffiliationsParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOwnerAffiliationsParser(); + virtual ~PubSubOwnerAffiliationsParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h index 34000fa..f11f357 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOwnerConfigureParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerConfigure.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOwnerConfigureParser : public GenericPayloadParser<PubSubOwnerConfigure> { public: PubSubOwnerConfigureParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOwnerConfigureParser(); + virtual ~PubSubOwnerConfigureParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h index 528c297..2f80b85 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOwnerDefaultParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerDefault.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOwnerDefaultParser : public GenericPayloadParser<PubSubOwnerDefault> { public: PubSubOwnerDefaultParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOwnerDefaultParser(); + virtual ~PubSubOwnerDefaultParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h index 99a8c0e..4484329 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOwnerDeleteParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerDelete.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOwnerDeleteParser : public GenericPayloadParser<PubSubOwnerDelete> { public: PubSubOwnerDeleteParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOwnerDeleteParser(); + virtual ~PubSubOwnerDeleteParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h index 35420f7..cfacc97 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOwnerPubSubParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerPubSub.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOwnerPubSubParser : public GenericPayloadParser<PubSubOwnerPubSub> { public: PubSubOwnerPubSubParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOwnerPubSubParser(); + virtual ~PubSubOwnerPubSubParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h index f85b2bb..8d233b6 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOwnerPurgeParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerPurge.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOwnerPurgeParser : public GenericPayloadParser<PubSubOwnerPurge> { public: PubSubOwnerPurgeParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOwnerPurgeParser(); + virtual ~PubSubOwnerPurgeParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h index 1197952..ebb6436 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOwnerRedirectParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerRedirect.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOwnerRedirectParser : public GenericPayloadParser<PubSubOwnerRedirect> { public: PubSubOwnerRedirectParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOwnerRedirectParser(); + virtual ~PubSubOwnerRedirectParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h index 74a61a2..d68d910 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerSubscription.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOwnerSubscriptionParser : public GenericPayloadParser<PubSubOwnerSubscription> { public: PubSubOwnerSubscriptionParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOwnerSubscriptionParser(); + virtual ~PubSubOwnerSubscriptionParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h index 541d225..ca868e6 100644 --- a/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubOwnerSubscriptionsParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerSubscriptions.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubOwnerSubscriptionsParser : public GenericPayloadParser<PubSubOwnerSubscriptions> { public: PubSubOwnerSubscriptionsParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubOwnerSubscriptionsParser(); + virtual ~PubSubOwnerSubscriptionsParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubParser.h b/Swiften/Parser/PayloadParsers/PubSubParser.h index 1f40ca9..5cc50e1 100644 --- a/Swiften/Parser/PayloadParsers/PubSubParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubParser.h @@ -1,38 +1,37 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSub.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class PubSubOptions; class PubSubConfigure; class SWIFTEN_API PubSubParser : public GenericPayloadParser<PubSub> { public: PubSubParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubParser(); + virtual ~PubSubParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; std::shared_ptr<PubSubConfigure> configurePayload; std::shared_ptr<PubSubOptions> optionsPayload; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubPublishParser.h b/Swiften/Parser/PayloadParsers/PubSubPublishParser.h index ad7dd11..e3b05ff 100644 --- a/Swiften/Parser/PayloadParsers/PubSubPublishParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubPublishParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubPublish.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubPublishParser : public GenericPayloadParser<PubSubPublish> { public: PubSubPublishParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubPublishParser(); + virtual ~PubSubPublishParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubRetractParser.h b/Swiften/Parser/PayloadParsers/PubSubRetractParser.h index 6bea498..aa9bbcc 100644 --- a/Swiften/Parser/PayloadParsers/PubSubRetractParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubRetractParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubRetract.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubRetractParser : public GenericPayloadParser<PubSubRetract> { public: PubSubRetractParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubRetractParser(); + virtual ~PubSubRetractParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h b/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h index 328818b..9deae2d 100644 --- a/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubSubscribeOptionsParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubSubscribeOptions.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubSubscribeOptionsParser : public GenericPayloadParser<PubSubSubscribeOptions> { public: PubSubSubscribeOptionsParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubSubscribeOptionsParser(); + virtual ~PubSubSubscribeOptionsParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h b/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h index 31221cb..ccd8ac8 100644 --- a/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubSubscribeParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubSubscribe.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubSubscribeParser : public GenericPayloadParser<PubSubSubscribe> { public: PubSubSubscribeParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubSubscribeParser(); + virtual ~PubSubSubscribeParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h b/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h index 7075a99..3d9be23 100644 --- a/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubSubscriptionParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubSubscription.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubSubscriptionParser : public GenericPayloadParser<PubSubSubscription> { public: PubSubSubscriptionParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubSubscriptionParser(); + virtual ~PubSubSubscriptionParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h b/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h index 2371a56..c7169ae 100644 --- a/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubSubscriptionsParser.h @@ -1,34 +1,33 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubSubscriptions.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubSubscriptionsParser : public GenericPayloadParser<PubSubSubscriptions> { public: PubSubSubscriptionsParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubSubscriptionsParser(); + virtual ~PubSubSubscriptionsParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: PayloadParserFactoryCollection* parsers; int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h b/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h index e471130..21d5599 100644 --- a/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h +++ b/Swiften/Parser/PayloadParsers/PubSubUnsubscribeParser.h @@ -1,33 +1,32 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubUnsubscribe.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class PayloadParserFactoryCollection; class PayloadParser; class SWIFTEN_API PubSubUnsubscribeParser : public GenericPayloadParser<PubSubUnsubscribe> { public: PubSubUnsubscribeParser(PayloadParserFactoryCollection* parsers); - virtual ~PubSubUnsubscribeParser(); + virtual ~PubSubUnsubscribeParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::shared_ptr<PayloadParser> currentPayloadParser; }; } diff --git a/Swiften/Parser/PayloadParsers/ReferencePayloadParser.cpp b/Swiften/Parser/PayloadParsers/ReferencePayloadParser.cpp new file mode 100644 index 0000000..a337a29 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/ReferencePayloadParser.cpp @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#include <Swiften/Parser/PayloadParsers/ReferencePayloadParser.h> + +#include <cassert> +#include <iostream> + +#include <Swiften/Parser/PayloadParserFactory.h> +#include <Swiften/Parser/PayloadParserFactoryCollection.h> + +namespace Swift { + +ReferencePayloadParser::ReferencePayloadParser(PayloadParserFactoryCollection* factories) : factories_(factories) { +} + +ReferencePayload::Type ReferencePayloadParser::getTypeFromString(const std::string& typeString) const { + if (typeString == "data") { + return ReferencePayload::Type::Data; + } + else if (typeString == "mention") { + return ReferencePayload::Type::Mention; + } + else if (typeString == "pubsub") { + return ReferencePayload::Type::PubSub; + } + else { + return ReferencePayload::Type::Unknown; + } +} + +void ReferencePayloadParser::handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) { + if (level_ == topLevel_) { + if (element == "reference") { + getPayloadInternal()->setType(getTypeFromString(attributes.getAttribute("type"))); + getPayloadInternal()->setUri(attributes.getAttributeValue("uri")); + getPayloadInternal()->setBegin(attributes.getAttributeValue("begin")); + getPayloadInternal()->setEnd(attributes.getAttributeValue("end")); + getPayloadInternal()->setAnchor(attributes.getAttributeValue("anchor")); + } + } + else if (level_ == payloadLevel_) { + PayloadParserFactory* payloadParserFactory = factories_->getPayloadParserFactory(element, ns, attributes); + if (payloadParserFactory) { + currentPayloadParser_.reset(payloadParserFactory->createPayloadParser()); + } + } + + if (level_ >= payloadLevel_ && currentPayloadParser_) { + currentPayloadParser_->handleStartElement(element, ns, attributes); + } + + ++level_; +} + +void ReferencePayloadParser::handleEndElement(const std::string& element, const std::string& ns) { + --level_; + if (currentPayloadParser_) { + if (level_ >= payloadLevel_) { + currentPayloadParser_->handleEndElement(element, ns); + } + + if (level_ == payloadLevel_) { + getPayloadInternal()->addPayload(currentPayloadParser_->getPayload()); + currentPayloadParser_.reset(); + } + } +} + +void ReferencePayloadParser::handleCharacterData(const std::string& data) { + if (level_ > payloadLevel_ && currentPayloadParser_) { + currentPayloadParser_->handleCharacterData(data); + } +} + +} diff --git a/Swiften/Parser/PayloadParsers/ReferencePayloadParser.h b/Swiften/Parser/PayloadParsers/ReferencePayloadParser.h new file mode 100644 index 0000000..3afd181 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/ReferencePayloadParser.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/ReferencePayload.h> +#include <Swiften/Parser/GenericPayloadParser.h> + +namespace Swift { + + class PayloadParserFactoryCollection; + + class SWIFTEN_API ReferencePayloadParser : public GenericPayloadParser<ReferencePayload> { + public: + + ReferencePayloadParser(PayloadParserFactoryCollection* factories); + + virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes); + virtual void handleEndElement(const std::string& element, const std::string& ns); + virtual void handleCharacterData(const std::string& data); + + private: + + ReferencePayload::Type getTypeFromString(const std::string& typeString) const; + int level_ = 0; + const int topLevel_ = 0; + const int payloadLevel_ = 1; + PayloadParserFactoryCollection* factories_; + std::shared_ptr<PayloadParser> currentPayloadParser_; + }; +} diff --git a/Swiften/Parser/PayloadParsers/ResultSetParser.h b/Swiften/Parser/PayloadParsers/ResultSetParser.h index 819c0a5..edf6f2f 100644 --- a/Swiften/Parser/PayloadParsers/ResultSetParser.h +++ b/Swiften/Parser/PayloadParsers/ResultSetParser.h @@ -3,30 +3,29 @@ * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/ResultSet.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class SWIFTEN_API ResultSetParser : public GenericPayloadParser<ResultSet> { public: ResultSetParser(); - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; enum Level { TopLevel = 0, PayloadLevel = 1 }; private: std::string currentText_; int level_; diff --git a/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp index 502f400..7a5a1fd 100644 --- a/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp +++ b/Swiften/Parser/PayloadParsers/S5BProxyRequestParser.cpp @@ -1,47 +1,47 @@ /* * Copyright (c) 2011 Tobias Markmann * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Parser/PayloadParsers/S5BProxyRequestParser.h> #include <boost/lexical_cast.hpp> +#include <boost/numeric/conversion/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")) { std::string host = attributes.getAttributeValue("host").get_value_or(""); - int port = -1; + unsigned short port = 0; 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; + port = boost::numeric_cast<unsigned short>(boost::lexical_cast<int>(attributes.getAttributeValue("port").get())); + } catch (...) { } - if (!host.empty() && port != -1 && jid.isValid()) { + if (!host.empty() && port != 0 && jid.isValid()) { S5BProxyRequest::StreamHost streamHost; streamHost.host = host; streamHost.port = port; streamHost.jid = jid; getPayloadInternal()->setStreamHost(streamHost); } } } else if (element == "activate") { parseActivate = true; diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXCreateParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXCreateParserTest.cpp index 85c79c6..f48bbc7 100644 --- a/Swiften/Parser/PayloadParsers/UnitTest/MIXCreateParserTest.cpp +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXCreateParserTest.cpp @@ -8,50 +8,50 @@ #include <Swiften/Elements/MIXCreate.h> #include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> using namespace Swift; TEST(MIXCreateParserTest, XEP0369_Example68) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<create xmlns=\"urn:xmpp:mix:1\"/>" + "<create xmlns=\"urn:xmpp:mix:0\"/>" )); auto payload = parser.getPayload<MIXCreate>(); ASSERT_TRUE(payload); ASSERT_FALSE(payload->getData()); ASSERT_FALSE(payload->getChannel()); } TEST(MIXCreateParserTest, XEP0369_Example66) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<create channel=\"coven\" xmlns=\"urn:xmpp:mix:1\"/>" + "<create channel=\"coven\" xmlns=\"urn:xmpp:mix:0\"/>" )); auto payload = parser.getPayload<MIXCreate>(); ASSERT_TRUE(payload); ASSERT_FALSE(payload->getData()); ASSERT_TRUE(payload->getChannel()); ASSERT_EQ(std::string("coven"), *payload->getChannel()); } TEST(MIXCreateParserTest, XEP0369_Example67) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<create channel=\"coven\" xmlns=\"urn:xmpp:mix:1\">" + "<create channel=\"coven\" xmlns=\"urn:xmpp:mix:0\">" "<x xmlns=\"jabber:x:data\" type=\"result\">" "<field var=\"FORM_TYPE\" type=\"hidden\">" - "<value>urn:xmpp:mix:1</value>" + "<value>urn:xmpp:mix:0</value>" "</field>" "<field var=\"Owner\">" "<value>hecate@shakespeare.lit</value>" "<value>greymalkin@shakespeare.lit</value>" "</field>" "<field var=\"Messages Node Subscription\">" "<value>allowed</value>" "</field>" "<field var=\"JID Visibility\">" diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXDestroyParser.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXDestroyParser.cpp index fc2588a..80eb144 100644 --- a/Swiften/Parser/PayloadParsers/UnitTest/MIXDestroyParser.cpp +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXDestroyParser.cpp @@ -8,18 +8,18 @@ #include <Swiften/Elements/MIXDestroy.h> #include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> using namespace Swift; TEST(MIXDestroyParserTest, XEP0369_Example70) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<destroy channel=\"coven\" xmlns=\"urn:xmpp:mix:1\"/>" + "<destroy channel=\"coven\" xmlns=\"urn:xmpp:mix:0\"/>" )); auto payload = parser.getPayload<MIXDestroy>(); ASSERT_TRUE(payload); ASSERT_TRUE(payload->getChannel()); ASSERT_EQ(std::string("coven"), *payload->getChannel()); } diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXDestroyParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXDestroyParserTest.cpp index 8e4dff2..5fa321e 100644 --- a/Swiften/Parser/PayloadParsers/UnitTest/MIXDestroyParserTest.cpp +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXDestroyParserTest.cpp @@ -8,17 +8,17 @@ #include <Swiften/Elements/MIXDestroy.h> #include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> using namespace Swift; TEST(MIXDestroyParserTest, XEP0369_Example70) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<destroy channel=\"coven\" xmlns=\"urn:xmpp:mix:1\"/>" + "<destroy channel=\"coven\" xmlns=\"urn:xmpp:mix:0\"/>" )); auto payload = parser.getPayload<MIXDestroy>(); ASSERT_TRUE(payload); ASSERT_EQ(std::string("coven"), payload->getChannel()); } diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXJoinParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXJoinParserTest.cpp index 7a422f4..0ad4589 100644 --- a/Swiften/Parser/PayloadParsers/UnitTest/MIXJoinParserTest.cpp +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXJoinParserTest.cpp @@ -8,140 +8,137 @@ #include <Swiften/Elements/MIXJoin.h> #include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> using namespace Swift; TEST(MIXJoinParserTest, XEP0369_Example22) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<join xmlns=\"urn:xmpp:mix:1\" channel=\"coven@mix.shakespeare.example\">" + "<join xmlns=\"urn:xmpp:mix:0\" channel=\"coven@mix.shakespeare.example\">" "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:participants\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:config\"/>" "</join>" )); MIXJoin::ref payload = parser.getPayload<MIXJoin>(); ASSERT_TRUE(payload); ASSERT_TRUE(payload->getChannel()); ASSERT_EQ(JID("coven@mix.shakespeare.example"), *payload->getChannel()); ASSERT_FALSE(payload->getJID()); ASSERT_FALSE(payload->getForm()); - const std::vector<MIXSubscribe::ref> items = payload->getSubscriptions(); - ASSERT_EQ(static_cast<size_t>(4), items.size()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:messages"), items[0]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:presence"), items[1]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:participants"), items[2]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:config"), items[3]->getNode()); + ASSERT_EQ(static_cast<size_t>(4), payload->getSubscriptions().size()); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:messages"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:presence"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:participants"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:config"))); } TEST(MIXJoinParserTest, XEP0369_Example23) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<join xmlns=\"urn:xmpp:mix:1\">" + "<join xmlns=\"urn:xmpp:mix:0\">" "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:participants\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:config\"/>" "</join>" )); MIXJoin::ref payload = parser.getPayload<MIXJoin>(); ASSERT_TRUE(payload); ASSERT_FALSE(payload->getChannel()); ASSERT_FALSE(payload->getJID()); ASSERT_FALSE(payload->getForm()); - const std::vector<MIXSubscribe::ref> items = payload->getSubscriptions(); - ASSERT_EQ(static_cast<size_t>(4), items.size()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:messages"), items[0]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:presence"), items[1]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:participants"), items[2]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:config"), items[3]->getNode()); + ASSERT_EQ(static_cast<size_t>(4), payload->getSubscriptions().size()); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:messages"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:presence"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:participants"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:config"))); } TEST(MIXJoinParserTest, XEP0369_Example24) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<join xmlns=\"urn:xmpp:mix:1\" jid=\"123456#coven@mix.shakespeare.example\">" + "<join xmlns=\"urn:xmpp:mix:0\" jid=\"123456#coven@mix.shakespeare.example\">" "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:participants\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:config\"/>" "</join>" )); MIXJoin::ref payload = parser.getPayload<MIXJoin>(); ASSERT_TRUE(payload); ASSERT_FALSE(payload->getChannel()); ASSERT_TRUE(payload->getJID()); ASSERT_EQ(JID("123456#coven@mix.shakespeare.example"), *payload->getJID()); ASSERT_FALSE(payload->getForm()); - const std::vector<MIXSubscribe::ref> items = payload->getSubscriptions(); - ASSERT_EQ(static_cast<size_t>(4), items.size()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:messages"), items[0]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:presence"), items[1]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:participants"), items[2]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:config"), items[3]->getNode()); + ASSERT_EQ(static_cast<size_t>(4), payload->getSubscriptions().size()); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:messages"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:presence"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:participants"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:config"))); } TEST(MIXJoinParserTest, XEP0369_Example29) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<join xmlns=\"urn:xmpp:mix:1\">" + "<join xmlns=\"urn:xmpp:mix:0\">" "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "<x xmlns=\"jabber:x:data\" type=\"submit\">" "<field var=\"FORM_TYPE\" type=\"hidden\">" - "<value>urn:xmpp:mix:1</value>" + "<value>urn:xmpp:mix:0</value>" "</field>" "<field var=\"JID Visibility\">" "<value>never</value>" "</field>" "</x>" "</join>")); MIXJoin::ref payload = parser.getPayload<MIXJoin>(); ASSERT_TRUE(payload); ASSERT_FALSE(payload->getChannel()); ASSERT_FALSE(payload->getJID()); - const std::vector<MIXSubscribe::ref> items = payload->getSubscriptions(); - ASSERT_EQ(static_cast<size_t>(2), items.size()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:messages"), items[0]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:presence"), items[1]->getNode()); + + ASSERT_EQ(static_cast<size_t>(2), payload->getSubscriptions().size()); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:messages"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:presence"))); ASSERT_TRUE(payload->getForm()); ASSERT_EQ(Form::Type::SubmitType, payload->getForm()->getType()); std::shared_ptr<FormField> fieldType = payload->getForm()->getField("FORM_TYPE"); ASSERT_TRUE(fieldType); std::shared_ptr<FormField> fieldJIDVisibility = payload->getForm()->getField("JID Visibility"); ASSERT_TRUE(fieldJIDVisibility); ASSERT_EQ(std::string("never"), fieldJIDVisibility->getTextSingleValue()); } TEST(MIXJoinParserTest, XEP0369_Example30) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<join xmlns=\"urn:xmpp:mix:1\" jid=\"hag66@shakespeare.example\">" + "<join xmlns=\"urn:xmpp:mix:0\" jid=\"hag66@shakespeare.example\">" "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "<x xmlns=\"jabber:x:data\" type=\"result\">" "<field var=\"FORM_TYPE\" type=\"hidden\">" - "<value>urn:xmpp:mix:1</value>" + "<value>urn:xmpp:mix:0</value>" "</field>" "<field var=\"JID Visibility\">" "<value>never</value>" "</field>" "<field var=\"Private Messages\">" "<value>allow</value>" "</field>" "<field var=\"vCard\">" "<value>block</value>" @@ -150,22 +147,21 @@ TEST(MIXJoinParserTest, XEP0369_Example30) { "</join>")); MIXJoin::ref payload = parser.getPayload<MIXJoin>(); ASSERT_TRUE(payload); ASSERT_FALSE(payload->getChannel()); ASSERT_TRUE(payload->getJID()); ASSERT_EQ(JID("hag66@shakespeare.example"), *payload->getJID()); - const std::vector<MIXSubscribe::ref> items = payload->getSubscriptions(); - ASSERT_EQ(static_cast<size_t>(2), items.size()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:messages"), items[0]->getNode()); - ASSERT_EQ(std::string("urn:xmpp:mix:nodes:presence"), items[1]->getNode()); + ASSERT_EQ(static_cast<size_t>(2), payload->getSubscriptions().size()); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:messages"))); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:presence"))); ASSERT_TRUE(payload->getForm()); ASSERT_EQ(Form::Type::ResultType, payload->getForm()->getType()); std::shared_ptr<FormField> fieldType = payload->getForm()->getField("FORM_TYPE"); ASSERT_TRUE(fieldType); std::shared_ptr<FormField> fieldJIDVisibility = payload->getForm()->getField("JID Visibility"); ASSERT_TRUE(fieldJIDVisibility); ASSERT_EQ(std::string("never"), fieldJIDVisibility->getTextSingleValue()); diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXLeaveParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXLeaveParserTest.cpp new file mode 100644 index 0000000..0a2839e --- /dev/null +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXLeaveParserTest.cpp @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Elements/MIXLeave.h> +#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> + +using namespace Swift; + +TEST(MIXLeaveParserTest, XEP0369_Example33) { + PayloadsParserTester parser; + ASSERT_TRUE(parser.parse("<leave xmlns=\"urn:xmpp:mix:0\" channel=\"coven@mix.shakespeare.example\"/>")); + + auto payload = parser.getPayload<MIXLeave>(); + ASSERT_TRUE(payload); + + ASSERT_TRUE(payload->getChannel()); + ASSERT_EQ(JID("coven@mix.shakespeare.example"), *payload->getChannel()); +} + +TEST(MIXLeaveParserTest, XEP0369_Example34) { + PayloadsParserTester parser; + ASSERT_TRUE(parser.parse("<leave xmlns=\"urn:xmpp:mix:0\"/>")); + + auto payload = parser.getPayload<MIXLeave>(); + ASSERT_TRUE(payload); + ASSERT_FALSE(payload->getChannel()); +} diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXParticipantParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXParticipantParserTest.cpp index 27c02e7..57d4b35 100644 --- a/Swiften/Parser/PayloadParsers/UnitTest/MIXParticipantParserTest.cpp +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXParticipantParserTest.cpp @@ -48,12 +48,9 @@ TEST(MIXParticipantParserTest, XEP0369_Example27_ParticipantEmpty) { ASSERT_TRUE(parser.parse( "<participant xmlns='urn:xmpp:mix:0'/>" )); MIXParticipant::ref payload = parser.getPayload<MIXParticipant>(); ASSERT_TRUE(payload); ASSERT_FALSE(payload->getNick()); ASSERT_FALSE(payload->getJID()); } - - - diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXPayloadParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXPayloadParserTest.cpp new file mode 100644 index 0000000..920aca7 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXPayloadParserTest.cpp @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Elements/MIXPayload.h> +#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> + +using namespace Swift; + +TEST(MIXPayloadParserTest, WithNick) { + PayloadsParserTester parser; + ASSERT_TRUE(parser.parse( + "<mix xmlns=\"urn:xmpp:mix:0\"> <nick>thirdwitch</nick> </mix>" + )); + + auto payload = parser.getPayload<MIXPayload>(); + ASSERT_TRUE(payload); + + ASSERT_TRUE(payload->getNick()); + std::string nick = *payload->getNick(); + ASSERT_EQ("thirdwitch", nick); + + ASSERT_FALSE(payload->getJID()); + ASSERT_FALSE(payload->getSubmissionID()); +} + +TEST(MIXPayloadParserTest, WithJID) { + PayloadsParserTester parser; + ASSERT_TRUE(parser.parse( + "<mix xmlns=\"urn:xmpp:mix:0\"> <jid>hecate@mix.shakespeare.example</jid> </mix>" + )); + + auto payload = parser.getPayload<MIXPayload>(); + ASSERT_TRUE(payload); + + ASSERT_TRUE(payload->getJID()); + JID jid = *payload->getJID(); + ASSERT_EQ("hecate@mix.shakespeare.example", jid.toString()); + + ASSERT_FALSE(payload->getNick()); + ASSERT_FALSE(payload->getSubmissionID()); +} + +TEST(MIXPayloadParserTest, WithAll) { + PayloadsParserTester parser; + ASSERT_TRUE(parser.parse( + "<mix xmlns=\"urn:xmpp:mix:0\">" + "<nick>thirdwitch</nick>" + "<jid>hecate@mix.shakespeare.example</jid>" + "<submission-id>92vax143g</submission-id>" + "</mix>" + )); + + auto payload = parser.getPayload<MIXPayload>(); + ASSERT_TRUE(payload); + + ASSERT_TRUE(payload->getNick()); + std::string nick = *payload->getNick(); + ASSERT_EQ("thirdwitch", nick); + + ASSERT_TRUE(payload->getJID()); + JID jid = *payload->getJID(); + ASSERT_EQ("hecate@mix.shakespeare.example", jid.toString()); + + ASSERT_TRUE(payload->getSubmissionID()); + std::string subID = *payload->getSubmissionID(); + ASSERT_EQ("92vax143g", subID); +} + +TEST(MIXPayloadParserTest, Empty) { + PayloadsParserTester parser; + ASSERT_TRUE(parser.parse( + "<mix xmlns=\"urn:xmpp:mix:0\"/>" + )); + + auto payload = parser.getPayload<MIXPayload>(); + ASSERT_TRUE(payload); + ASSERT_FALSE(payload->getNick()); + ASSERT_FALSE(payload->getJID()); + ASSERT_FALSE(payload->getSubmissionID()); +} diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXRegisterNickParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXRegisterNickParserTest.cpp new file mode 100644 index 0000000..d0539fd --- /dev/null +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXRegisterNickParserTest.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Elements/MIXRegisterNick.h> +#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> + +using namespace Swift; + +TEST(MIXRegisterNickParserTest, WithNick) { + PayloadsParserTester parser; + ASSERT_TRUE(parser.parse( + "<register xmlns=\"urn:xmpp:mix:0\"> <nick>thirdwitch</nick> </register>" + )); + + auto payload = parser.getPayload<MIXRegisterNick>(); + ASSERT_TRUE(payload); + ASSERT_EQ("thirdwitch", payload->getNick()); +} diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXSetNickParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXSetNickParserTest.cpp new file mode 100644 index 0000000..84f8a5e --- /dev/null +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXSetNickParserTest.cpp @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Elements/MIXSetNick.h> +#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> + +using namespace Swift; + +TEST(MIXSetNickParserTest, WithNick) { + PayloadsParserTester parser; + ASSERT_TRUE(parser.parse( + "<setnick xmlns=\"urn:xmpp:mix:0\"> <nick>thirdwitch</nick> </setnick>" + )); + + auto payload = parser.getPayload<MIXSetNick>(); + ASSERT_TRUE(payload); + ASSERT_EQ("thirdwitch", payload->getNick()); +} diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXUpdateSubscriptionParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXUpdateSubscriptionParserTest.cpp new file mode 100644 index 0000000..985a34b --- /dev/null +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXUpdateSubscriptionParserTest.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Elements/MIXUpdateSubscription.h> +#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> + +using namespace Swift; + +TEST(MIXUpdateSubscriptionParserTest, XEP0369_Example28) { + PayloadsParserTester parser; + ASSERT_TRUE(parser.parse( + "<update-subscription xmlns=\"urn:xmpp:mix:0\">" + "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" + "</update-subscription>" + )); + + auto payload = parser.getPayload<MIXUpdateSubscription>(); + ASSERT_TRUE(payload); + + ASSERT_FALSE(payload->getJID()); + + auto items = payload->getSubscriptions(); + ASSERT_EQ(static_cast<size_t>(1), items.size()); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:messages"))); +} + +TEST(MIXUpdateSubscriptionParserTest, XEP0369_Example28_WithJID) { + PayloadsParserTester parser; + ASSERT_TRUE(parser.parse( + "<update-subscription xmlns=\"urn:xmpp:mix:0\" jid=\"hag66@shakespeare.example\">" + "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" + "</update-subscription>" + )); + + auto payload = parser.getPayload<MIXUpdateSubscription>(); + ASSERT_TRUE(payload); + + ASSERT_TRUE(payload->getJID()); + ASSERT_EQ(JID("hag66@shakespeare.example"), *payload->getJID()); + + auto items = payload->getSubscriptions(); + ASSERT_EQ(static_cast<size_t>(1), items.size()); + ASSERT_TRUE(payload->hasSubscription(std::string("urn:xmpp:mix:nodes:messages"))); +} diff --git a/Swiften/Parser/PayloadParsers/UnitTest/MIXUserPreferenceParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/MIXUserPreferenceParserTest.cpp index 3d048a5..7115f2a 100644 --- a/Swiften/Parser/PayloadParsers/UnitTest/MIXUserPreferenceParserTest.cpp +++ b/Swiften/Parser/PayloadParsers/UnitTest/MIXUserPreferenceParserTest.cpp @@ -8,34 +8,34 @@ #include <Swiften/Elements/MIXUserPreference.h> #include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> using namespace Swift; TEST(MIXUserPreferenceParserTest, XEP0369_Example31) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<user-preference xmlns='urn:xmpp:mix:1'/>" + "<user-preference xmlns='urn:xmpp:mix:0'/>" )); auto payload = parser.getPayload<MIXUserPreference>(); ASSERT_TRUE(payload); ASSERT_FALSE(payload->getData()); } TEST(MIXUserPreferenceParserTest, XEP0369_Example32) { PayloadsParserTester parser; ASSERT_TRUE(parser.parse( - "<user-preference xmlns='urn:xmpp:mix:1'>" + "<user-preference xmlns='urn:xmpp:mix:0'>" "<x xmlns='jabber:x:data' type='result'>" "<field var='FORM_TYPE' type='hidden'>" - "<value>urn:xmpp:mix:1</value>" + "<value>urn:xmpp:mix:0</value>" "</field>" "<field var='JID Visibility'>" "<value>never</value>" "</field>" "<field var='Private Messages'>" "<value>allow</value>" "</field>" "<field var='vCard'>" "<value>block</value>" diff --git a/Swiften/Parser/PayloadParsers/UnitTest/ReferencePayloadParserTest.cpp b/Swiften/Parser/PayloadParsers/UnitTest/ReferencePayloadParserTest.cpp new file mode 100644 index 0000000..ca7b280 --- /dev/null +++ b/Swiften/Parser/PayloadParsers/UnitTest/ReferencePayloadParserTest.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Elements/Body.h> +#include <Swiften/Elements/Delay.h> +#include <Swiften/Elements/ErrorPayload.h> +#include <Swiften/Parser/PayloadParsers/ReferencePayloadParser.h> +#include <Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h> + +using namespace Swift; + +TEST(ReferencePayloadParserTest, testParse) { + PayloadsParserTester parser; + + ASSERT_TRUE(parser.parse( + "<reference xmlns='urn:xmpp:reference:0' " + "type='data' " + "uri='https://www.example.com/mindBlowingImage.jpeg' " + "begin='11' " + "end='22' " + "anchor='xmpp:data@localhost.example.test'>" + "</reference>")); + + auto payload = std::dynamic_pointer_cast<ReferencePayload>(parser.getPayload()); + ASSERT_EQ(static_cast<int>(ReferencePayload::Type::Data), static_cast<int>(payload->getType())); + ASSERT_EQ(std::string("https://www.example.com/mindBlowingImage.jpeg"), *payload->getUri()); + ASSERT_EQ(std::string("11"), *payload->getBegin()); + ASSERT_EQ(std::string("22"), *payload->getEnd()); + ASSERT_EQ(std::string("xmpp:data@localhost.example.test"), *payload->getAnchor()); +} + +TEST(ReferencePayloadParserTest, testParseNoType) { + PayloadsParserTester parser; + + ASSERT_TRUE(parser.parse( + "<reference xmlns='urn:xmpp:reference:0' " + "uri='https://www.example.com/mindBlowingImage.jpeg' " + "begin='11' " + "end='22' " + "anchor='xmpp:data@localhost.example.test'>" + "</reference>")); + + auto payload = std::dynamic_pointer_cast<ReferencePayload>(parser.getPayload()); + ASSERT_EQ(static_cast<int>(ReferencePayload::Type::Unknown), static_cast<int>(payload->getType())); + ASSERT_EQ(std::string("https://www.example.com/mindBlowingImage.jpeg"), *payload->getUri()); + ASSERT_EQ(std::string("11"), *payload->getBegin()); + ASSERT_EQ(std::string("22"), *payload->getEnd()); + ASSERT_EQ(std::string("xmpp:data@localhost.example.test"), *payload->getAnchor()); +} + +TEST(ReferencePayloadParserTest, testParseEmbeddedPayloads) { + PayloadsParserTester parser; + + ASSERT_TRUE(parser.parse( + "<reference xmlns='urn:xmpp:reference:0' type='data'> " + "<error type=\"modify\">" + "<bad-request xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\"/>" + "<delay xmlns='urn:xmpp:delay' from='juliet@capulet.com/balcony' stamp='2002-09-10T23:41:07Z'/>" + "<text xmlns=\"urn:ietf:params:xml:ns:xmpp-stanzas\">boo</text>" + "</error>" + "</reference>")); + + auto payload = std::dynamic_pointer_cast<ReferencePayload>(parser.getPayload()); + ASSERT_EQ(static_cast<int>(ReferencePayload::Type::Data), static_cast<int>(payload->getType())); + ASSERT_FALSE(payload->getUri()); + ASSERT_FALSE(payload->getBegin()); + ASSERT_FALSE(payload->getEnd()); + ASSERT_FALSE(payload->getAnchor()); + auto childPayloadList = payload->getPayloads(); + auto errorPayload = std::dynamic_pointer_cast<ErrorPayload>(childPayloadList[0]); + ASSERT_TRUE(errorPayload); + ASSERT_EQ("boo", errorPayload->getText()); + auto delayPayload = std::dynamic_pointer_cast<Delay>(errorPayload->getPayload()); + ASSERT_TRUE(delayPayload); +} + +TEST(ReferencePayloadParserTest, testParseEmbeddedPayloadWithText) { + PayloadsParserTester parser; + + ASSERT_TRUE(parser.parse( + "<reference xmlns='urn:xmpp:reference:0' type='data'> " + "<body>Example Text</body>" + "</reference>")); + + auto payload = std::dynamic_pointer_cast<ReferencePayload>(parser.getPayload()); + auto childPayloadList = payload->getPayloads(); + auto bodyPayload = std::dynamic_pointer_cast<Body>(childPayloadList[0]); + ASSERT_EQ("Example Text", bodyPayload->getText()); +} + +TEST(ReferencePayloadParserTest, testParseRecursive) { + PayloadsParserTester parser; + + ASSERT_TRUE(parser.parse( + "<reference xmlns='urn:xmpp:reference:0' type='data'> " + "<reference xmlns='urn:xmpp:reference:0' type='data' uri='https://download.montague.lit/4a771ac1-f0b2-4a4a-9700-f2a26fa2bb67/summit.jpg' /> " + "<reference xmlns='urn:xmpp:reference:0' type='data' uri='xmpp:romeo@montague.lit/resource?jingle;id=9559976B-3FBF-4E7E-B457-2DAA225972BB' /> " + "<reference xmlns='urn:xmpp:reference:0' type='data'> " + "<reference xmlns='urn:xmpp:reference:0' type='data' uri='https://www.example.com/mindBlowingImage.jpeg' /> " + "</reference>" + "</reference>")); + + auto payload = std::dynamic_pointer_cast<ReferencePayload>(parser.getPayload()); + ASSERT_EQ(static_cast<int>(ReferencePayload::Type::Data), static_cast<int>(payload->getType())); + auto childPayloadList = payload->getPayloads(); + auto childPayloadA = std::dynamic_pointer_cast<ReferencePayload>(childPayloadList[0]); + auto childPayloadB = std::dynamic_pointer_cast<ReferencePayload>(childPayloadList[1]); + auto childPayloadC = std::dynamic_pointer_cast<ReferencePayload>(childPayloadList[2]); + ASSERT_TRUE(childPayloadA); + ASSERT_TRUE(childPayloadB); + ASSERT_TRUE(childPayloadC); + ASSERT_EQ(static_cast<int>(ReferencePayload::Type::Data), static_cast<int>(childPayloadA->getType())); + ASSERT_EQ(static_cast<int>(ReferencePayload::Type::Data), static_cast<int>(childPayloadB->getType())); + ASSERT_EQ(static_cast<int>(ReferencePayload::Type::Data), static_cast<int>(childPayloadC->getType())); + ASSERT_EQ(std::string("https://download.montague.lit/4a771ac1-f0b2-4a4a-9700-f2a26fa2bb67/summit.jpg"), *childPayloadA->getUri()); + ASSERT_EQ(std::string("xmpp:romeo@montague.lit/resource?jingle;id=9559976B-3FBF-4E7E-B457-2DAA225972BB"), *childPayloadB->getUri()); + ASSERT_FALSE(childPayloadC->getUri()); + ASSERT_FALSE(childPayloadC->getBegin()); + ASSERT_FALSE(childPayloadC->getEnd()); + ASSERT_FALSE(childPayloadC->getAnchor()); + auto grandChildPayloadList = childPayloadC->getPayloads(); + auto grandChildPayload = std::dynamic_pointer_cast<ReferencePayload>(grandChildPayloadList[0]); + ASSERT_TRUE(grandChildPayload); + ASSERT_EQ(static_cast<int>(ReferencePayload::Type::Data), static_cast<int>(grandChildPayload->getType())); + ASSERT_EQ(std::string("https://www.example.com/mindBlowingImage.jpeg"), *grandChildPayload->getUri()); + ASSERT_FALSE(grandChildPayload->getBegin()); + ASSERT_FALSE(grandChildPayload->getEnd()); + ASSERT_FALSE(grandChildPayload->getAnchor()); +} diff --git a/Swiften/Parser/PayloadParsers/UserLocationParser.h b/Swiften/Parser/PayloadParsers/UserLocationParser.h index 1445d3e..39df9de 100644 --- a/Swiften/Parser/PayloadParsers/UserLocationParser.h +++ b/Swiften/Parser/PayloadParsers/UserLocationParser.h @@ -1,31 +1,30 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/UserLocation.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class SWIFTEN_API UserLocationParser : public GenericPayloadParser<UserLocation> { public: UserLocationParser(); - virtual ~UserLocationParser(); + virtual ~UserLocationParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::string currentText; }; } diff --git a/Swiften/Parser/PayloadParsers/UserTuneParser.h b/Swiften/Parser/PayloadParsers/UserTuneParser.h index 5a27273..8c7e8c5 100644 --- a/Swiften/Parser/PayloadParsers/UserTuneParser.h +++ b/Swiften/Parser/PayloadParsers/UserTuneParser.h @@ -1,31 +1,30 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <string> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/UserTune.h> #include <Swiften/Parser/GenericPayloadParser.h> namespace Swift { class SWIFTEN_API UserTuneParser : public GenericPayloadParser<UserTune> { public: UserTuneParser(); - virtual ~UserTuneParser(); + virtual ~UserTuneParser() override; - virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) SWIFTEN_OVERRIDE; - virtual void handleEndElement(const std::string& element, const std::string&) SWIFTEN_OVERRIDE; - virtual void handleCharacterData(const std::string& data) SWIFTEN_OVERRIDE; + virtual void handleStartElement(const std::string& element, const std::string&, const AttributeMap& attributes) override; + virtual void handleEndElement(const std::string& element, const std::string&) override; + virtual void handleCharacterData(const std::string& data) override; private: int level; std::string currentText; }; } diff --git a/Swiften/Parser/PlatformXMLParserFactory.cpp b/Swiften/Parser/PlatformXMLParserFactory.cpp index 97e1c9e..bf66734 100644 --- a/Swiften/Parser/PlatformXMLParserFactory.cpp +++ b/Swiften/Parser/PlatformXMLParserFactory.cpp @@ -16,16 +16,16 @@ namespace Swift { PlatformXMLParserFactory::PlatformXMLParserFactory() { } std::unique_ptr<XMLParser> PlatformXMLParserFactory::createXMLParser(XMLParserClient* client) { #ifdef HAVE_LIBXML - return std::unique_ptr<XMLParser>(new LibXMLParser(client)); + return std::make_unique<LibXMLParser>(client); #else - return std::unique_ptr<XMLParser>(new ExpatParser(client)); + return std::make_unique<ExpatParser>(client); #endif } } diff --git a/Swiften/Parser/SConscript b/Swiften/Parser/SConscript index 3c778f5..4ac5aa4 100644 --- a/Swiften/Parser/SConscript +++ b/Swiften/Parser/SConscript @@ -47,38 +47,43 @@ sources = [ "PayloadParsers/JingleFileTransferFileInfoParser.cpp", "PayloadParsers/StreamInitiationFileInfoParser.cpp", "PayloadParsers/CommandParser.cpp", "PayloadParsers/InBandRegistrationPayloadParser.cpp", "PayloadParsers/SearchPayloadParser.cpp", "PayloadParsers/FullPayloadParserFactoryCollection.cpp", "PayloadParsers/PriorityParser.cpp", "PayloadParsers/PrivateStorageParser.cpp", "PayloadParsers/RawXMLPayloadParser.cpp", + "PayloadParsers/ReferencePayloadParser.cpp", "PayloadParsers/ResourceBindParser.cpp", "PayloadParsers/RosterItemExchangeParser.cpp", "PayloadParsers/RosterParser.cpp", "PayloadParsers/SecurityLabelParser.cpp", "PayloadParsers/SecurityLabelsCatalogParser.cpp", "PayloadParsers/SoftwareVersionParser.cpp", "PayloadParsers/StorageParser.cpp", "PayloadParsers/StatusParser.cpp", "PayloadParsers/StatusShowParser.cpp", "PayloadParsers/StreamInitiationParser.cpp", "PayloadParsers/BytestreamsParser.cpp", "PayloadParsers/VCardParser.cpp", "PayloadParsers/VCardUpdateParser.cpp", "PayloadParsers/DelayParser.cpp", "PayloadParsers/MIXParticipantParser.cpp", + "PayloadParsers/MIXSetNickParser.cpp", + "PayloadParsers/MIXRegisterNickParser.cpp", "PayloadParsers/MIXDestroyParser.cpp", "PayloadParsers/MIXCreateParser.cpp", + "PayloadParsers/MIXPayloadParser.cpp", + "PayloadParsers/MIXLeaveParser.cpp", "PayloadParsers/MIXJoinParser.cpp", - "PayloadParsers/MIXSubscribeParser.cpp", "PayloadParsers/MIXUserPreferenceParser.cpp", + "PayloadParsers/MIXUpdateSubscriptionParser.cpp", "PayloadParsers/MUCUserPayloadParser.cpp", "PayloadParsers/MUCAdminPayloadParser.cpp", "PayloadParsers/MUCOwnerPayloadParser.cpp", "PayloadParsers/MUCDestroyPayloadParser.cpp", "PayloadParsers/MUCInvitationPayloadParser.cpp", "PayloadParsers/MUCItemParser.cpp", "PayloadParsers/NicknameParser.cpp", "PayloadParsers/ReplaceParser.cpp", "PayloadParsers/LastParser.cpp", diff --git a/Swiften/Parser/StanzaAckParser.cpp b/Swiften/Parser/StanzaAckParser.cpp index de0287e..42ab181 100644 --- a/Swiften/Parser/StanzaAckParser.cpp +++ b/Swiften/Parser/StanzaAckParser.cpp @@ -1,29 +1,29 @@ /* - * Copyright (c) 2010 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Parser/StanzaAckParser.h> #include <boost/lexical_cast.hpp> namespace Swift { StanzaAckParser::StanzaAckParser() : GenericElementParser<StanzaAck>(), depth(0) { } void StanzaAckParser::handleStartElement(const std::string&, const std::string&, const AttributeMap& attributes) { if (depth == 0) { std::string handledStanzasString = attributes.getAttribute("h"); try { - getElementGeneric()->setHandledStanzasCount(boost::lexical_cast<int>(handledStanzasString)); + getElementGeneric()->setHandledStanzasCount(boost::lexical_cast<unsigned int>(handledStanzasString)); } catch (const boost::bad_lexical_cast &) { } } ++depth; } void StanzaAckParser::handleEndElement(const std::string&, const std::string&) { --depth; diff --git a/Swiften/Parser/Tree/ParserElement.cpp b/Swiften/Parser/Tree/ParserElement.cpp index 5415945..988bc13 100644 --- a/Swiften/Parser/Tree/ParserElement.cpp +++ b/Swiften/Parser/Tree/ParserElement.cpp @@ -1,25 +1,20 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Parser/Tree/ParserElement.h> -#include <boost/lambda/bind.hpp> -#include <boost/lambda/lambda.hpp> - #include <Swiften/Parser/Tree/NullParserElement.h> -namespace lambda = boost::lambda; - namespace Swift { ParserElement::ParserElement(const std::string& name, const std::string& xmlns, const AttributeMap& attributes) : name_(name), xmlns_(xmlns), attributes_(attributes) { } ParserElement::~ParserElement() { } ParserElement::ref ParserElement::addChild(const std::string& name, const std::string& xmlns, const AttributeMap& attributes) { @@ -28,20 +23,21 @@ ParserElement::ref ParserElement::addChild(const std::string& name, const std::s return child; } void ParserElement::appendCharacterData(const std::string& data) { text_ += data; } std::vector<ParserElement::ref> ParserElement::getChildren(const std::string& name, const std::string& xmlns) const { std::vector<ParserElement::ref> result; - std::remove_copy_if(children_.begin(), children_.end(), std::back_inserter(result), - lambda::bind(&ParserElement::getName, *lambda::_1) != name || lambda::bind(&ParserElement::getNamespace, *lambda::_1) != xmlns); + std::remove_copy_if(children_.begin(), children_.end(), std::back_inserter(result), [&](const ParserElement::ref& element) { + return (element->getName() != name) || (element->getNamespace() != xmlns); + }); return result; } ParserElement::ref ParserElement::getChild(const std::string& name, const std::string& xmlns) const { std::vector<ParserElement::ref> results = getChildren(name, xmlns); ParserElement::ref result = results.empty() ? NullParserElement::element : results[0]; return result; } diff --git a/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp b/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp index 38e67fb..e313124 100644 --- a/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp +++ b/Swiften/Presence/UnitTest/DirectedPresenceSenderTest.cpp @@ -23,24 +23,24 @@ class DirectedPresenceSenderTest : public CppUnit::TestFixture { CPPUNIT_TEST(testAddDirectedPresenceReceiver); CPPUNIT_TEST(testAddDirectedPresenceReceiver_WithoutSendingPresence); CPPUNIT_TEST(testAddDirectedPresenceReceiver_AfterSendingDirectedPresence); CPPUNIT_TEST(testRemoveDirectedPresenceReceiver); CPPUNIT_TEST(testRemoveDirectedPresenceReceiver_WithoutSendingPresence); CPPUNIT_TEST_SUITE_END(); public: void setUp() { - channel = std::unique_ptr<DummyStanzaChannel>(new DummyStanzaChannel()); + channel = std::make_unique<DummyStanzaChannel>(); testPresence = std::make_shared<Presence>(); testPresence->setStatus("Foo"); secondTestPresence = std::make_shared<Presence>(); secondTestPresence->setStatus("Bar"); - stanzaChannelPresenceSender = std::unique_ptr<StanzaChannelPresenceSender>(new StanzaChannelPresenceSender(channel.get())); + stanzaChannelPresenceSender = std::make_unique<StanzaChannelPresenceSender>(channel.get()); } void testSendPresence() { std::shared_ptr<DirectedPresenceSender> testling(createPresenceSender()); testling->sendPresence(testPresence); CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(channel->sentStanzas.size())); std::shared_ptr<Presence> presence = std::dynamic_pointer_cast<Presence>(channel->sentStanzas[0]); CPPUNIT_ASSERT(testPresence == presence); diff --git a/Swiften/PubSub/PubSubManager.h b/Swiften/PubSub/PubSubManager.h index eba5dd9..477b3de 100644 --- a/Swiften/PubSub/PubSubManager.h +++ b/Swiften/PubSub/PubSubManager.h @@ -1,23 +1,22 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <boost/signals2.hpp> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/IQ.h> #include <Swiften/Elements/PubSub.h> #include <Swiften/Elements/PubSubAffiliations.h> #include <Swiften/Elements/PubSubCreate.h> #include <Swiften/Elements/PubSubDefault.h> #include <Swiften/Elements/PubSubEventPayload.h> #include <Swiften/Elements/PubSubItems.h> #include <Swiften/Elements/PubSubOwnerAffiliations.h> #include <Swiften/Elements/PubSubOwnerConfigure.h> diff --git a/Swiften/PubSub/PubSubManagerImpl.h b/Swiften/PubSub/PubSubManagerImpl.h index 2f2b96b..0d0739c 100644 --- a/Swiften/PubSub/PubSubManagerImpl.h +++ b/Swiften/PubSub/PubSubManagerImpl.h @@ -3,34 +3,33 @@ * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/PubSub/PubSubManager.h> #define SWIFTEN_PUBSUBMANAGERIMPL_DECLARE_CREATE_REQUEST(payload, container, response) \ virtual std::shared_ptr< PubSubRequest<payload> > \ - createRequest(IQ::Type type, const JID& receiver, std::shared_ptr<payload> p) SWIFTEN_OVERRIDE { \ + createRequest(IQ::Type type, const JID& receiver, std::shared_ptr<payload> p) override { \ return std::make_shared< PubSubRequest<payload> >(type, receiver, p, router); \ } namespace Swift { class StanzaChannel; class Message; class SWIFTEN_API PubSubManagerImpl : public PubSubManager { public: PubSubManagerImpl(StanzaChannel* stanzaChannel, IQRouter* router); - virtual ~PubSubManagerImpl(); + virtual ~PubSubManagerImpl() override; SWIFTEN_PUBSUB_FOREACH_PUBSUB_PAYLOAD_TYPE( SWIFTEN_PUBSUBMANAGERIMPL_DECLARE_CREATE_REQUEST) private: void handleMessageRecevied(std::shared_ptr<Message>); private: StanzaChannel* stanzaChannel; diff --git a/Swiften/QA/ClientTest/ClientTest.cpp b/Swiften/QA/ClientTest/ClientTest.cpp index 5cb1765..c5117fa 100644 --- a/Swiften/QA/ClientTest/ClientTest.cpp +++ b/Swiften/QA/ClientTest/ClientTest.cpp @@ -1,19 +1,20 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <iostream> #include <thread> #include <boost/bind.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Client/Client.h> #include <Swiften/Client/ClientXMLTracer.h> #include <Swiften/EventLoop/EventLoop.h> #include <Swiften/EventLoop/SimpleEventLoop.h> #include <Swiften/Network/BoostNetworkFactories.h> #include <Swiften/Network/TimerFactory.h> #include <Swiften/Roster/GetRosterRequest.h> @@ -68,19 +69,29 @@ int main(int, char**) { return -1; } char* boshHost = getenv("SWIFT_CLIENTTEST_BOSH_HOST"); char* boshPort = getenv("SWIFT_CLIENTTEST_BOSH_PORT"); char* boshPath = getenv("SWIFT_CLIENTTEST_BOSH_PATH"); if (boshHost && boshPort && boshPath) { std::cout << "Using BOSH with URL: http://" << boshHost << ":" << boshPort << boshPath << std::endl; - options.boshURL = URL("http", boshHost, atoi(boshPort), boshPath); + try { + options.boshURL = URL("http", boshHost, boost::numeric_cast<unsigned short>(boost::lexical_cast<int>(boshPort)), boshPath); + } + catch (const boost::numeric::bad_numeric_cast& e) { + std::cerr << "SWIFT_CLIENTTEST_BOSH_PORT doesn't hold a valid port number: " << e.what() << std::endl; + return -1; + } + catch (const boost::bad_lexical_cast& e) { + std::cerr << "SWIFT_CLIENTTEST_BOSH_PORT doesn't hold a valid port number: " << e.what() << std::endl; + return -1; + } } client = new Swift::Client(JID(jid), std::string(pass), &networkFactories); ClientXMLTracer* tracer = new ClientXMLTracer(client, !options.boshURL.isEmpty()); client->onConnected.connect(&handleConnected); client->onDisconnected.connect(boost::bind(&handleDisconnected, _1)); client->setAlwaysTrustCertificates(); stage = FirstConnect; client->connect(options); diff --git a/Swiften/QA/DNSSDTest/DNSSDTest.cpp b/Swiften/QA/DNSSDTest/DNSSDTest.cpp index ae2fafd..5a78d2f 100644 --- a/Swiften/QA/DNSSDTest/DNSSDTest.cpp +++ b/Swiften/QA/DNSSDTest/DNSSDTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ // TODO: Test registering on different interfaces #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <boost/bind.hpp> @@ -29,19 +29,19 @@ using namespace Swift; template <typename DNSSDQuerierType> class DNSSDTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(DNSSDTest); CPPUNIT_TEST(testPublish); CPPUNIT_TEST_SUITE_END(); public: void setUp() { eventLoop = new DummyEventLoop(); - querier = std::make_shared<DNSSDQuerier>(); + querier = std::make_shared<DNSSDQuerierType>(eventLoop); querier->start(); } void tearDown() { querier->stop(); querier.reset(); delete eventLoop; } @@ -49,19 +49,19 @@ class DNSSDTest : public CppUnit::TestFixture { std::shared_ptr<DNSSDBrowseQuery> browseQuery = querier->createBrowseQuery(); browseQuery->onServiceAdded.connect(boost::bind(&DNSSDTest::handleServiceAdded, this, _1)); browseQuery->onServiceRemoved.connect(boost::bind(&DNSSDTest::handleServiceRemoved, this, _1)); browseQuery->onError.connect(boost::bind(&DNSSDTest::handleBrowseError, this)); browseQuery->startBrowsing(); eventLoop->processEvents(); // Publish the service LinkLocalServiceInfo info; - std::shared_ptr<DNSSDRegisterQuery> registerQuery = querier->createRegisterQuery("DNSSDTest", 1234, info.toTXTRecord()); + std::shared_ptr<DNSSDRegisterQuery> registerQuery = querier->createRegisterQuery("DNSSDTest", 1234, *info.toTXTRecord()); registerQuery->onRegisterFinished.connect(boost::bind(&DNSSDTest::handleRegisterFinished, this, _1)); registerQuery->registerService(); // Wait for a while wait(); // Check that our registered queries are correct CPPUNIT_ASSERT_EQUAL(1, static_cast<int>((registered.size()))); CPPUNIT_ASSERT_EQUAL(std::string("DNSSDTest"), registered[0].getName()); @@ -131,19 +131,19 @@ class DNSSDTest : public CppUnit::TestFixture { } void handleResolveFinished(const boost::optional<DNSSDResolveServiceQuery::Result>& result) { CPPUNIT_ASSERT(result); resolvedServices.push_back(*result); } private: DummyEventLoop* eventLoop; - std::shared_ptr<DNSSDQuerier> querier; + std::shared_ptr<DNSSDQuerierType> querier; std::vector<DNSSDServiceID> added; std::vector<DNSSDServiceID> registered; std::vector<DNSSDServiceID> toRemove; std::vector<DNSSDResolveServiceQuery::Result> resolvedServices; }; #ifdef HAVE_AVAHI CPPUNIT_TEST_SUITE_REGISTRATION(DNSSDTest<AvahiQuerier>); #endif diff --git a/Swiften/QA/DNSSDTest/SConscript b/Swiften/QA/DNSSDTest/SConscript index 275a314..d9c9b04 100644 --- a/Swiften/QA/DNSSDTest/SConscript +++ b/Swiften/QA/DNSSDTest/SConscript @@ -1,21 +1,23 @@ import os Import("env") if env["TEST"] : myenv = env.Clone() myenv.MergeFlags(myenv["CHECKER_FLAGS"]) myenv.MergeFlags(myenv["SWIFTEN_FLAGS"]) myenv.MergeFlags(myenv["CPPUNIT_FLAGS"]) + myenv.MergeFlags(myenv["GOOGLETEST_FLAGS"]) myenv.MergeFlags(myenv["BOOST_FLAGS"]) myenv.MergeFlags(myenv["LIBIDN_FLAGS"]) if myenv.get("HAVE_BONJOUR", 0) : myenv.Append(CPPDEFINES = "HAVE_BONJOUR") elif myenv.get("HAVE_AVAHI", 0) : myenv.Append(CPPDEFINES = ["HAVE_AVAHI"]) myenv.MergeFlags(myenv["AVAHI_FLAGS"]) + myenv.MergeFlags(myenv["PLATFORM_FLAGS"]) tester = myenv.Program("DNSSDTest", [ "DNSSDTest.cpp", ]) myenv.Test(tester, "system") diff --git a/Swiften/QA/FileTransferTest/FileTransferTest.cpp b/Swiften/QA/FileTransferTest/FileTransferTest.cpp index ebdb36a..7d69277 100644 --- a/Swiften/QA/FileTransferTest/FileTransferTest.cpp +++ b/Swiften/QA/FileTransferTest/FileTransferTest.cpp @@ -1,20 +1,19 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <fstream> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> -#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/Debug.h> #include <Swiften/Base/Log.h> #include <Swiften/Base/sleep.h> #include <Swiften/Base/StdRandomGenerator.h> #include <Swiften/Client/Client.h> #include <Swiften/Client/ClientXMLTracer.h> #include <Swiften/Disco/ClientDiscoManager.h> @@ -72,26 +71,26 @@ class FileTransferTest { receiver_->connect(options); timeOut_ = networkFactories->getTimerFactory()->createTimer(60000); timeOut_->onTick.connect(boost::bind(&FileTransferTest::handleTimeOut, this)); // Create randomly sized data to exchange. sendFilePath_ = boost::filesystem::unique_path("ft_send_%%%%%%%%%%%%%%%%.bin"); receiveFilePath_ = boost::filesystem::unique_path("ft_receive_%%%%%%%%%%%%%%%%.bin"); - size_t size = 1024 + boost::numeric_cast<size_t>(randGen.generateRandomInteger(1024 * 10)); + size_t size = 1024 + static_cast<size_t>(randGen.generateRandomInteger(1024 * 10)); sendData_.resize(size); for (unsigned char& n : sendData_) { - n = boost::numeric_cast<unsigned char>(randGen.generateRandomInteger(255)); + n = static_cast<unsigned char>(randGen.generateRandomInteger(255)); } std::ofstream outfile(sendFilePath_.native().c_str(), std::ios::out | std::ios::binary); - outfile.write(reinterpret_cast<char *>(&sendData_[0]), boost::numeric_cast<ptrdiff_t>(sendData_.size())); + outfile.write(reinterpret_cast<char *>(&sendData_[0]), static_cast<ptrdiff_t>(sendData_.size())); outfile.close(); } ~FileTransferTest() { timeOut_->stop(); delete senderTracer_; delete receiverTracer_; diff --git a/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp b/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp index 95ebb6d..69e6fe8 100644 --- a/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp +++ b/Swiften/QA/NetworkTest/DomainNameResolverTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <algorithm> #include <string> #include <boost/bind.hpp> @@ -173,31 +173,31 @@ class DomainNameResolverTest : public CppUnit::TestFixture { void testResolveService() { std::shared_ptr<DomainNameServiceQuery> query(createServiceQuery("_xmpp-client._tcp.", "xmpp-srv.test.swift.im")); query->run(); waitForResults(); CPPUNIT_ASSERT_EQUAL(4, static_cast<int>(serviceQueryResult.size())); CPPUNIT_ASSERT_EQUAL(std::string("xmpp1.test.swift.im"), serviceQueryResult[0].hostname); - CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[0].port); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(5000), serviceQueryResult[0].port); CPPUNIT_ASSERT_EQUAL(0, serviceQueryResult[0].priority); CPPUNIT_ASSERT_EQUAL(1, serviceQueryResult[0].weight); CPPUNIT_ASSERT_EQUAL(std::string("xmpp-invalid.test.swift.im"), serviceQueryResult[1].hostname); - CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[1].port); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(5000), serviceQueryResult[1].port); CPPUNIT_ASSERT_EQUAL(1, serviceQueryResult[1].priority); CPPUNIT_ASSERT_EQUAL(100, serviceQueryResult[1].weight); CPPUNIT_ASSERT_EQUAL(std::string("xmpp3.test.swift.im"), serviceQueryResult[2].hostname); - CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[2].port); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(5000), serviceQueryResult[2].port); CPPUNIT_ASSERT_EQUAL(3, serviceQueryResult[2].priority); CPPUNIT_ASSERT_EQUAL(100, serviceQueryResult[2].weight); CPPUNIT_ASSERT_EQUAL(std::string("xmpp2.test.swift.im"), serviceQueryResult[3].hostname); - CPPUNIT_ASSERT_EQUAL(5000, serviceQueryResult[3].port); + CPPUNIT_ASSERT_EQUAL(static_cast<unsigned short>(5000), serviceQueryResult[3].port); CPPUNIT_ASSERT_EQUAL(5, serviceQueryResult[3].priority); CPPUNIT_ASSERT_EQUAL(100, serviceQueryResult[3].weight); } void testResolveService_Error() { } private: std::shared_ptr<DomainNameAddressQuery> createAddressQuery(const std::string& domain) { diff --git a/Swiften/QA/StorageTest/SConscript b/Swiften/QA/StorageTest/SConscript index b8360ec..46107a0 100644 --- a/Swiften/QA/StorageTest/SConscript +++ b/Swiften/QA/StorageTest/SConscript @@ -4,19 +4,20 @@ Import("env") if env["TEST"] : myenv = env.Clone() myenv.MergeFlags(myenv["CHECKER_FLAGS"]) myenv.MergeFlags(myenv["SWIFTOOLS_FLAGS"]) myenv.MergeFlags(myenv["SWIFTEN_FLAGS"]) myenv.MergeFlags(myenv["CPPUNIT_FLAGS"]) myenv.MergeFlags(myenv["GOOGLETEST_FLAGS"]) myenv.MergeFlags(myenv["BOOST_FLAGS"]) - myenv.MergeFlags(myenv["LIBIDN_FLAGS"]) + myenv.MergeFlags(myenv.get("LIBIDN_FLAGS", {})) + myenv.MergeFlags(myenv.get("ICU_FLAGS", {})) myenv.MergeFlags(myenv.get("EXPAT_FLAGS", {})) myenv.MergeFlags(myenv.get("LIBXML_FLAGS", {})) myenv.MergeFlags(myenv["PLATFORM_FLAGS"]) tester = myenv.Program("StorageTest", [ #"VCardFileStorageTest.cpp", "FileReadBytestreamTest.cpp", "FileWriteBytestreamTest.cpp", ]) diff --git a/Swiften/QA/TLSTest/CertificateTest.cpp b/Swiften/QA/TLSTest/CertificateTest.cpp index b53cd2f..02ec0f8 100644 --- a/Swiften/QA/TLSTest/CertificateTest.cpp +++ b/Swiften/QA/TLSTest/CertificateTest.cpp @@ -28,19 +28,19 @@ class CertificateTest : public CppUnit::TestFixture { //CPPUNIT_TEST(testGetSubjectName); CPPUNIT_TEST(testGetCommonNames); CPPUNIT_TEST(testGetSRVNames); CPPUNIT_TEST(testGetDNSNames); CPPUNIT_TEST(testGetXMPPAddresses); CPPUNIT_TEST_SUITE_END(); public: void setUp() { - pathProvider = std::unique_ptr<PlatformApplicationPathProvider>(new PlatformApplicationPathProvider("FileReadBytestreamTest")); + pathProvider = std::make_unique<PlatformApplicationPathProvider>("FileReadBytestreamTest"); readByteArrayFromFile(certificateData, (pathProvider->getExecutableDir() / "jabber_org.crt")); certificateFactory = std::unique_ptr<CertificateFactory>(new CERTIFICATE_FACTORY()); } void testConstructFromDER() { Certificate::ref testling = Certificate::ref(certificateFactory->createCertificateFromDER(certificateData)); CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getCommonNames()[0]); } diff --git a/Swiften/QA/TLSTest/SConscript b/Swiften/QA/TLSTest/SConscript index 7811b50..81e2471 100644 --- a/Swiften/QA/TLSTest/SConscript +++ b/Swiften/QA/TLSTest/SConscript @@ -18,10 +18,10 @@ if env["TEST"] : myenv.Append(CPPDEFINES = "HAVE_SCHANNEL") elif myenv.get("HAVE_SECURETRANSPORT", 0) : myenv.Append(CPPDEFINES = "HAVE_SECURETRANSPORT") tester = myenv.Program("TLSTest", [ "CertificateTest.cpp", # Reenable if either http://www.tls-o-matic.com/ is fixed or we have setup a replacement. #"CertificateErrorTest.cpp" ]) - myenv.Test(tester, "system")
\ No newline at end of file + myenv.Test(tester, "system") diff --git a/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp b/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp index 8a4b9fc..ed242f9 100644 --- a/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp +++ b/Swiften/Queries/Requests/UnitTest/GetPrivateStorageRequestTest.cpp @@ -28,20 +28,20 @@ class GetPrivateStorageRequestTest : public CppUnit::TestFixture { public: class MyPayload : public Payload { public: MyPayload(const std::string& text = "") : text(text) {} std::string text; }; public: void setUp() { - channel = std::unique_ptr<DummyIQChannel>(new DummyIQChannel()); - router = std::unique_ptr<IQRouter>(new IQRouter(channel.get())); + channel = std::make_unique<DummyIQChannel>(); + router = std::make_unique<IQRouter>(channel.get()); } void tearDown() { router.reset(); } void testSend() { GetPrivateStorageRequest<MyPayload>::ref request = GetPrivateStorageRequest<MyPayload>::create(router.get()); request->send(); diff --git a/Swiften/Queries/UnitTest/ResponderTest.cpp b/Swiften/Queries/UnitTest/ResponderTest.cpp index 94bfed1..fa5072b 100644 --- a/Swiften/Queries/UnitTest/ResponderTest.cpp +++ b/Swiften/Queries/UnitTest/ResponderTest.cpp @@ -26,20 +26,20 @@ class ResponderTest : public CppUnit::TestFixture { CPPUNIT_TEST(testHandleIQ_Set); CPPUNIT_TEST(testHandleIQ_Get); CPPUNIT_TEST(testHandleIQ_Error); CPPUNIT_TEST(testHandleIQ_Result); CPPUNIT_TEST(testHandleIQ_NoPayload); CPPUNIT_TEST_SUITE_END(); public: void setUp() { - channel_ = std::unique_ptr<DummyIQChannel>(new DummyIQChannel()); - router_ = std::unique_ptr<IQRouter>(new IQRouter(channel_.get())); + channel_ = std::make_unique<DummyIQChannel>(); + router_ = std::make_unique<IQRouter>(channel_.get()); payload_ = std::make_shared<SoftwareVersion>("foo"); } void tearDown() { router_.reset(); } void testConstructor() { MyResponder testling(router_.get()); diff --git a/Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp b/Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp index 73e76d3..4137ebf 100644 --- a/Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp +++ b/Swiften/Roster/UnitTest/XMPPRosterImplTest.cpp @@ -24,20 +24,20 @@ class XMPPRosterImplTest : public CppUnit::TestFixture { CPPUNIT_TEST(testJIDRemoved); CPPUNIT_TEST(testJIDUpdated); CPPUNIT_TEST_SUITE_END(); public: void setUp() { jid1_ = JID("a@b.c"); jid2_ = JID("b@c.d"); jid3_ = JID("c@d.e"); - roster_ = std::unique_ptr<XMPPRosterImpl>(new XMPPRosterImpl()); - handler_ = std::unique_ptr<XMPPRosterSignalHandler>(new XMPPRosterSignalHandler(roster_.get())); + roster_ = std::make_unique<XMPPRosterImpl>(); + handler_ = std::make_unique<XMPPRosterSignalHandler>(roster_.get()); groups1_.push_back("bobs"); groups1_.push_back("berts"); groups2_.push_back("ernies"); } void testJIDAdded() { roster_->addContact(jid1_, "NewName", groups1_, RosterItemPayload::Both); CPPUNIT_ASSERT_EQUAL(Add, handler_->getLastEvent()); CPPUNIT_ASSERT_EQUAL(jid1_, handler_->getLastJID()); diff --git a/Swiften/SASL/EXTERNALClientAuthenticator.cpp b/Swiften/SASL/EXTERNALClientAuthenticator.cpp index 546140f..027bc89 100644 --- a/Swiften/SASL/EXTERNALClientAuthenticator.cpp +++ b/Swiften/SASL/EXTERNALClientAuthenticator.cpp @@ -6,19 +6,25 @@ #include <Swiften/SASL/EXTERNALClientAuthenticator.h> namespace Swift { EXTERNALClientAuthenticator::EXTERNALClientAuthenticator() : ClientAuthenticator("EXTERNAL"), finished(false) { } boost::optional<SafeByteArray> EXTERNALClientAuthenticator::getResponse() const { - return boost::optional<SafeByteArray>(); + const std::string& authorizationID = getAuthorizationID(); + + if (authorizationID.empty()) { + return boost::optional<SafeByteArray>(); + } else { + return createSafeByteArray(authorizationID); + } } bool EXTERNALClientAuthenticator::setChallenge(const boost::optional<ByteArray>&) { if (finished) { return false; } finished = true; return true; } diff --git a/Swiften/SASL/SConscript b/Swiften/SASL/SConscript index 6aa3e72..8a248cc 100644 --- a/Swiften/SASL/SConscript +++ b/Swiften/SASL/SConscript @@ -17,17 +17,18 @@ if myenv["PLATFORM"] == "win32" : "WindowsAuthentication.cpp", "WindowsGSSAPIClientAuthenticator.cpp" ]) swiften_env.Append(SWIFTEN_OBJECTS = [objects]) env.Append(UNITTEST_SOURCES = [ File("UnitTest/PLAINMessageTest.cpp"), File("UnitTest/PLAINClientAuthenticatorTest.cpp"), + File("UnitTest/EXTERNALClientAuthenticatorTest.cpp"), File("UnitTest/SCRAMSHA1ClientAuthenticatorTest.cpp"), File("UnitTest/DIGESTMD5PropertiesTest.cpp"), File("UnitTest/DIGESTMD5ClientAuthenticatorTest.cpp"), ]) if myenv["PLATFORM"] == "win32" : env.Append(UNITTEST_SOURCES = [ File("UnitTest/WindowsServicePrincipalNameTest.cpp"), ]) diff --git a/Swiften/SASL/UnitTest/EXTERNALClientAuthenticatorTest.cpp b/Swiften/SASL/UnitTest/EXTERNALClientAuthenticatorTest.cpp new file mode 100644 index 0000000..728eed6 --- /dev/null +++ b/Swiften/SASL/UnitTest/EXTERNALClientAuthenticatorTest.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#include <QA/Checker/IO.h> + +#include <cppunit/extensions/HelperMacros.h> +#include <cppunit/extensions/TestFactoryRegistry.h> + +#include <Swiften/SASL/EXTERNALClientAuthenticator.h> + +using namespace Swift; + +class EXTERNALClientAuthenticatorTest : public CppUnit::TestFixture { + CPPUNIT_TEST_SUITE(EXTERNALClientAuthenticatorTest); + CPPUNIT_TEST(testGetResponse_WithoutAuthzID); + CPPUNIT_TEST(testGetResponse_WithAuthzID); + CPPUNIT_TEST_SUITE_END(); + + public: + void testGetResponse_WithoutAuthzID() { + EXTERNALClientAuthenticator testling; + + // Authcid and password are not used (ignored) + testling.setCredentials("user", createSafeByteArray("pass")); + + boost::optional<SafeByteArray> response = testling.getResponse(); + + // No data should have been returned + bool result = !response; + + CPPUNIT_ASSERT(result); + } + + void testGetResponse_WithAuthzID() { + EXTERNALClientAuthenticator testling; + + // Authcid and password are not used (ignored) + testling.setCredentials("user", createSafeByteArray("pass"), "authz"); + + CPPUNIT_ASSERT_EQUAL(*testling.getResponse(), createSafeByteArray("authz", 5)); + } +}; + +CPPUNIT_TEST_SUITE_REGISTRATION(EXTERNALClientAuthenticatorTest); diff --git a/Swiften/SASL/UnitTest/WindowsServicePrincipalNameTest.cpp b/Swiften/SASL/UnitTest/WindowsServicePrincipalNameTest.cpp index fa07052..ef3a9b3 100644 --- a/Swiften/SASL/UnitTest/WindowsServicePrincipalNameTest.cpp +++ b/Swiften/SASL/UnitTest/WindowsServicePrincipalNameTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2015 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <cppunit/extensions/HelperMacros.h> #include <Swiften/SASL/WindowsServicePrincipalName.h> using namespace Swift; @@ -91,28 +91,28 @@ class WindowsServicePrincipalNameTest : public CppUnit::TestFixture { } catch (std::runtime_error) { /* expected */ } } void testInstancePort() { WindowsServicePrincipalName spn("adlon.isode.net"); spn.setInstanceName("mlink.adlon.isode.net"); - spn.setInstancePort(6222); - CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net:6222/adlon.isode.net")); + spn.setInstancePort(55222); + CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net:55222/adlon.isode.net")); spn.setInstancePort(0); CPPUNIT_ASSERT_EQUAL(spn.toString(), std::string("xmpp/mlink.adlon.isode.net/adlon.isode.net")); WindowsServicePrincipalName spn2("mlink.adlon.isode.net"); - spn2.setInstancePort(6222); - CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net:6222")); + spn2.setInstancePort(55222); + CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net:55222")); spn2.setInstancePort(0); CPPUNIT_ASSERT_EQUAL(spn2.toString(), std::string("xmpp/mlink.adlon.isode.net")); } void testReferrer() { WindowsServicePrincipalName spn("127.0.0.1"); spn.setReferrer("referrer.net"); diff --git a/Swiften/SASL/WindowsServicePrincipalName.h b/Swiften/SASL/WindowsServicePrincipalName.h index 4c9f557..2e4e5c4 100644 --- a/Swiften/SASL/WindowsServicePrincipalName.h +++ b/Swiften/SASL/WindowsServicePrincipalName.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2015 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <string> #include <Windows.h> @@ -43,19 +43,19 @@ namespace Swift { /* * This sets a non-default port for the service. Note * that the default value is 0 which indicates the * default port for the service. So if the XMPP service * is using the default port of 5222 for client * connections, then do not set the port to 5222 but let * it remain 0 to indicate that the default port is * used. */ - void setInstancePort(short int instancePort) { instancePort_ = instancePort; } + void setInstancePort(unsigned short instancePort) { instancePort_ = instancePort; } /* * This follows the rules of SPN creation on Windows and * returns the SPN string constructed from the set * values. */ std::string toString(); private: diff --git a/Swiften/SConscript b/Swiften/SConscript index f52637b..4deddaf 100644 --- a/Swiften/SConscript +++ b/Swiften/SConscript @@ -136,18 +136,19 @@ if env["SCONS_STAGE"] == "build" : "Elements/FormText.cpp", "Elements/StreamFeatures.cpp", "Elements/Element.cpp", "Elements/ToplevelElement.cpp", "Elements/IQ.cpp", "Elements/Payload.cpp", "Elements/PubSubPayload.cpp", "Elements/PubSubOwnerPayload.cpp", "Elements/PubSubEventPayload.cpp", + "Elements/ReferencePayload.cpp", "Elements/RosterItemExchangePayload.cpp", "Elements/RosterPayload.cpp", "Elements/SecurityLabel.cpp", "Elements/Stanza.cpp", "Elements/StanzaAck.cpp", "Elements/StatusShow.cpp", "Elements/StreamManagementEnabled.cpp", "Elements/StreamResume.cpp", "Elements/StreamResumed.cpp", @@ -158,18 +159,20 @@ if env["SCONS_STAGE"] == "build" : "Elements/ResultSet.cpp", "Elements/Forwarded.cpp", "Elements/MAMResult.cpp", "Elements/MAMQuery.cpp", "Elements/MAMFin.cpp", "Elements/Thread.cpp", "Elements/IsodeIQDelegation.cpp", "Entity/Entity.cpp", "Entity/PayloadPersister.cpp", + "MIX/MIX.cpp", + "MIX/MIXImpl.cpp", "MUC/MUC.cpp", "MUC/MUCImpl.cpp", "MUC/MUCManager.cpp", "MUC/MUCRegistry.cpp", "MUC/MUCBookmarkManager.cpp", "PubSub/PubSubManager.cpp", "PubSub/PubSubManagerImpl.cpp", "Queries/IQChannel.cpp", "Queries/IQHandler.cpp", @@ -202,29 +205,34 @@ if env["SCONS_STAGE"] == "build" : "Serializer/PayloadSerializers/CarbonsSentSerializer.cpp", "Serializer/PayloadSerializers/CarbonsReceivedSerializer.cpp", "Serializer/PayloadSerializers/ChatStateSerializer.cpp", "Serializer/PayloadSerializers/ClientStateSerializer.cpp", "Serializer/PayloadSerializers/DiscoInfoSerializer.cpp", "Serializer/PayloadSerializers/DiscoItemsSerializer.cpp", "Serializer/PayloadSerializers/ErrorSerializer.cpp", "Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp", "Serializer/PayloadSerializers/MIXParticipantSerializer.cpp", + "Serializer/PayloadSerializers/MIXSetNickSerializer.cpp", + "Serializer/PayloadSerializers/MIXRegisterNickSerializer.cpp", "Serializer/PayloadSerializers/MIXDestroySerializer.cpp", "Serializer/PayloadSerializers/MIXCreateSerializer.cpp", + "Serializer/PayloadSerializers/MIXPayloadSerializer.cpp", "Serializer/PayloadSerializers/MIXUserPreferenceSerializer.cpp", + "Serializer/PayloadSerializers/MIXLeaveSerializer.cpp", "Serializer/PayloadSerializers/MIXJoinSerializer.cpp", - "Serializer/PayloadSerializers/MIXSubscribeSerializer.cpp", + "Serializer/PayloadSerializers/MIXUpdateSubscriptionSerializer.cpp", "Serializer/PayloadSerializers/MUCPayloadSerializer.cpp", "Serializer/PayloadSerializers/MUCUserPayloadSerializer.cpp", "Serializer/PayloadSerializers/MUCAdminPayloadSerializer.cpp", "Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.cpp", "Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.cpp", "Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.cpp", + "Serializer/PayloadSerializers/ReferencePayloadSerializer.cpp", "Serializer/PayloadSerializers/ResourceBindSerializer.cpp", "Serializer/PayloadSerializers/RosterItemExchangeSerializer.cpp", "Serializer/PayloadSerializers/RosterSerializer.cpp", "Serializer/PayloadSerializers/SecurityLabelSerializer.cpp", "Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.cpp", "Serializer/PayloadSerializers/SoftwareVersionSerializer.cpp", "Serializer/PayloadSerializers/StreamInitiationSerializer.cpp", "Serializer/PayloadSerializers/BytestreamsSerializer.cpp", "Serializer/PayloadSerializers/VCardSerializer.cpp", @@ -405,18 +413,19 @@ if env["SCONS_STAGE"] == "build" : File("Elements/UnitTest/FormTest.cpp"), File("EventLoop/UnitTest/EventLoopTest.cpp"), File("EventLoop/UnitTest/SimpleEventLoopTest.cpp"), # File("History/UnitTest/SQLiteHistoryManagerTest.cpp"), File("JID/UnitTest/JIDTest.cpp"), File("LinkLocal/UnitTest/LinkLocalConnectorTest.cpp"), File("LinkLocal/UnitTest/LinkLocalServiceBrowserTest.cpp"), File("LinkLocal/UnitTest/LinkLocalServiceInfoTest.cpp"), File("LinkLocal/UnitTest/LinkLocalServiceTest.cpp"), + File("MIX/UnitTest/MIXImplTest.cpp"), File("MUC/UnitTest/MUCTest.cpp"), File("MUC/UnitTest/MockMUC.cpp"), File("Network/UnitTest/HostAddressTest.cpp"), File("Network/UnitTest/ConnectorTest.cpp"), File("Network/UnitTest/ChainedConnectorTest.cpp"), File("Network/UnitTest/DomainNameServiceQueryTest.cpp"), File("Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp"), File("Network/UnitTest/BOSHConnectionTest.cpp"), File("Network/UnitTest/BOSHConnectionPoolTest.cpp"), @@ -424,26 +433,32 @@ if env["SCONS_STAGE"] == "build" : File("Parser/PayloadParsers/UnitTest/BodyParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/ClientStateParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/DiscoInfoParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/DiscoItemsParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/ErrorParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/FormParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/CommandParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/PriorityParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/RawXMLPayloadParserTest.cpp"), + File("Parser/PayloadParsers/UnitTest/ReferencePayloadParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/ResourceBindParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/RosterItemExchangeParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/RosterParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/IBBParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/InBandRegistrationPayloadParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/JingleParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/MIXParticipantParserTest.cpp"), + File("Parser/PayloadParsers/UnitTest/MIXPayloadParserTest.cpp"), + File("Parser/PayloadParsers/UnitTest/MIXUpdateSubscriptionParserTest.cpp"), + File("Parser/PayloadParsers/UnitTest/MIXRegisterNickParserTest.cpp"), + File("Parser/PayloadParsers/UnitTest/MIXSetNickParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/MIXDestroyParserTest.cpp"), + File("Parser/PayloadParsers/UnitTest/MIXLeaveParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/MIXCreateParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/MIXUserPreferenceParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/SearchPayloadParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/SecurityLabelParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/SecurityLabelsCatalogParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/SoftwareVersionParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/StatusParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/StatusShowParserTest.cpp"), File("Parser/PayloadParsers/UnitTest/StreamInitiationParserTest.cpp"), @@ -496,18 +511,19 @@ if env["SCONS_STAGE"] == "build" : File("Serializer/PayloadSerializers/UnitTest/CarbonsSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/CapsInfoSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/ChatStateSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/ClientStateSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/FormSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/DiscoInfoSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/ErrorSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/IBBSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/PrioritySerializerTest.cpp"), + File("Serializer/PayloadSerializers/UnitTest/ReferencePayloadSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/ResourceBindSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/RosterItemExchangeSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/RosterSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/SearchPayloadSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/SecurityLabelSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/SecurityLabelsCatalogSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/SoftwareVersionSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/StatusSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/StatusShowSerializerTest.cpp"), @@ -515,21 +531,26 @@ if env["SCONS_STAGE"] == "build" : File("Serializer/PayloadSerializers/UnitTest/InBandRegistrationPayloadSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/IsodeIQDelegationSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/VCardUpdateSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/VCardSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/StorageSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/PrivateStorageSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/ReplaceSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/MUCAdminPayloadSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/MIXParticipantSerializerTest.cpp"), + File("Serializer/PayloadSerializers/UnitTest/MIXSetNickSerializerTest.cpp"), + File("Serializer/PayloadSerializers/UnitTest/MIXUpdateSubscriptionSerializerTest.cpp"), + File("Serializer/PayloadSerializers/UnitTest/MIXRegisterNickSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/MIXDestroySerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/MIXCreateSerializerTest.cpp"), + File("Serializer/PayloadSerializers/UnitTest/MIXPayloadSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/MIXUserPreferenceSerializerTest.cpp"), + File("Serializer/PayloadSerializers/UnitTest/MIXLeaveSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/JingleSerializersTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/DeliveryReceiptSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/IdleSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/ResultSetSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/ForwardedSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/MIXJoinSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/MAMFinSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/MAMResultSerializerTest.cpp"), File("Serializer/PayloadSerializers/UnitTest/MAMQuerySerializerTest.cpp"), @@ -552,28 +573,34 @@ if env["SCONS_STAGE"] == "build" : File("StringCodecs/UnitTest/Base64Test.cpp"), File("StringCodecs/UnitTest/HexifyTest.cpp"), File("StringCodecs/UnitTest/PBKDF2Test.cpp"), File("TLS/UnitTest/ServerIdentityVerifierTest.cpp"), File("TLS/UnitTest/CertificateTest.cpp"), File("VCards/UnitTest/VCardManagerTest.cpp"), File("Whiteboard/UnitTest/WhiteboardServerTest.cpp"), File("Whiteboard/UnitTest/WhiteboardClientTest.cpp"), ]) + if env.get("HAVE_OPENSSL", 0) : + env.Append(UNITTEST_SOURCES = [ + File("TLS/UnitTest/ClientServerTest.cpp"), + ]) # Generate the Swiften header def relpath(path, start) : i = len(os.path.commonprefix([path, start])) return path[i+1:] swiften_header = "#pragma once\n" swiften_includes = [] swiften_public_includes = [] top_path = env.Dir("..").abspath for root, dirs, files in os.walk(env.Dir(".").abspath) : + dirs.sort() + files.sort() if root.endswith("UnitTest") : continue for file in files : if not file.endswith(".h") : continue include = relpath(os.path.join(root, file), top_path) if swiften_env["PLATFORM"] == "win32" : include = include.replace("\\", "/") swiften_includes.append(include) diff --git a/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp index 78bb0eb..37a9c03 100644 --- a/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/BytestreamsSerializer.cpp @@ -19,19 +19,19 @@ BytestreamsSerializer::BytestreamsSerializer() { } std::string BytestreamsSerializer::serializePayload(std::shared_ptr<Bytestreams> bytestreams) const { XMLElement queryElement("query", "http://jabber.org/protocol/bytestreams"); queryElement.setAttribute("sid", bytestreams->getStreamID()); for (const auto& streamHost : bytestreams->getStreamHosts()) { std::shared_ptr<XMLElement> streamHostElement(new XMLElement("streamhost")); streamHostElement->setAttribute("host", streamHost.host); streamHostElement->setAttribute("jid", streamHost.jid.toString()); - streamHostElement->setAttribute("port", boost::lexical_cast<std::string>(streamHost.port)); + streamHostElement->setAttribute("port", std::to_string(streamHost.port)); queryElement.addNode(streamHostElement); } if (bytestreams->getUsedStreamHost()) { std::shared_ptr<XMLElement> streamHostElement(new XMLElement("streamhost-used")); streamHostElement->setAttribute("jid", *bytestreams->getUsedStreamHost()); queryElement.addNode(streamHostElement); } return queryElement.serialize(); diff --git a/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h b/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h index f3eb6fb..439e684 100644 --- a/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/ForwardedSerializer.h @@ -1,29 +1,28 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/Forwarded.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API ForwardedSerializer : public GenericPayloadSerializer<Forwarded> { public: ForwardedSerializer(PayloadSerializerCollection* serializers); - virtual ~ForwardedSerializer(); + virtual ~ForwardedSerializer() override; - virtual std::string serializePayload(std::shared_ptr<Forwarded>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<Forwarded>) const override; private: PayloadSerializerCollection* serializers_; }; } diff --git a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp index 9832bd5..31294f1 100644 --- a/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp +++ b/Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.cpp @@ -41,35 +41,41 @@ #include <Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/LastSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h> #include <Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MIXJoinSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MIXDestroySerializer.h> +#include <Swiften/Serializer/PayloadSerializers/MIXUpdateSubscriptionSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MIXParticipantSerializer.h> +#include <Swiften/Serializer/PayloadSerializers/MIXRegisterNickSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MIXCreateSerializer.h> +#include <Swiften/Serializer/PayloadSerializers/MIXPayloadSerializer.h> +#include <Swiften/Serializer/PayloadSerializers/MIXSetNickSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MIXUserPreferenceSerializer.h> +#include <Swiften/Serializer/PayloadSerializers/MIXLeaveSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MUCAdminPayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MUCDestroyPayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MUCInvitationPayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MUCOwnerPayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/MUCUserPayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/NicknameSerializer.h> #include <Swiften/Serializer/PayloadSerializers/PrioritySerializer.h> #include <Swiften/Serializer/PayloadSerializers/PrivateStorageSerializer.h> #include <Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h> #include <Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h> #include <Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h> #include <Swiften/Serializer/PayloadSerializers/PubSubSerializer.h> #include <Swiften/Serializer/PayloadSerializers/RawXMLPayloadSerializer.h> +#include <Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/ReplaceSerializer.h> #include <Swiften/Serializer/PayloadSerializers/ResourceBindSerializer.h> #include <Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h> #include <Swiften/Serializer/PayloadSerializers/RosterItemExchangeSerializer.h> #include <Swiften/Serializer/PayloadSerializers/RosterSerializer.h> #include <Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h> #include <Swiften/Serializer/PayloadSerializers/SearchPayloadSerializer.h> #include <Swiften/Serializer/PayloadSerializers/SecurityLabelSerializer.h> #include <Swiften/Serializer/PayloadSerializers/SecurityLabelsCatalogSerializer.h> @@ -155,33 +161,40 @@ FullPayloadSerializerCollection::FullPayloadSerializerCollection() { serializers_.push_back(new PubSubSerializer(this)); serializers_.push_back(new PubSubEventSerializer(this)); serializers_.push_back(new PubSubOwnerPubSubSerializer(this)); serializers_.push_back(new PubSubErrorSerializer()); serializers_.push_back(new ResultSetSerializer()); serializers_.push_back(new ForwardedSerializer(this)); serializers_.push_back(new MIXParticipantSerializer()); serializers_.push_back(new MIXCreateSerializer()); + serializers_.push_back(new MIXRegisterNickSerializer()); + serializers_.push_back(new MIXPayloadSerializer()); + serializers_.push_back(new MIXSetNickSerializer()); serializers_.push_back(new MIXUserPreferenceSerializer()); + serializers_.push_back(new MIXLeaveSerializer()); serializers_.push_back(new MIXJoinSerializer()); serializers_.push_back(new MIXDestroySerializer()); + serializers_.push_back(new MIXUpdateSubscriptionSerializer()); serializers_.push_back(new MAMResultSerializer(this)); serializers_.push_back(new MAMQuerySerializer()); serializers_.push_back(new MAMFinSerializer()); serializers_.push_back(new CarbonsDisableSerializer()); serializers_.push_back(new CarbonsEnableSerializer()); serializers_.push_back(new CarbonsPrivateSerializer()); serializers_.push_back(new CarbonsReceivedSerializer(this)); serializers_.push_back(new CarbonsSentSerializer(this)); serializers_.push_back(new IsodeIQDelegationSerializer(this)); + serializers_.push_back(new ReferencePayloadSerializer(this)); + for (auto serializer : serializers_) { addSerializer(serializer); } } FullPayloadSerializerCollection::~FullPayloadSerializerCollection() { for (auto serializer : serializers_) { removeSerializer(serializer); delete serializer; diff --git a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp index e41ff8c..74a8e7b 100644 --- a/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/IBBSerializer.cpp @@ -20,32 +20,32 @@ namespace Swift { IBBSerializer::IBBSerializer() { } std::string IBBSerializer::serializePayload(std::shared_ptr<IBB> ibb) const { switch(ibb->getAction()) { case IBB::Data: { XMLElement ibbElement("data", "http://jabber.org/protocol/ibb"); ibbElement.setAttribute("sid", ibb->getStreamID()); if (ibb->getSequenceNumber() >= 0) { - ibbElement.setAttribute("seq", boost::lexical_cast<std::string>(ibb->getSequenceNumber())); + ibbElement.setAttribute("seq", std::to_string(ibb->getSequenceNumber())); } ibbElement.addNode(std::make_shared<XMLTextNode>(Base64::encode(ibb->getData()))); return ibbElement.serialize(); } case IBB::Open: { XMLElement ibbElement("open", "http://jabber.org/protocol/ibb"); ibbElement.setAttribute("sid", ibb->getStreamID()); switch (ibb->getStanzaType()) { case IBB::IQStanza: ibbElement.setAttribute("stanza", "iq"); break; case IBB::MessageStanza: ibbElement.setAttribute("stanza", "message"); break; } assert(ibb->getBlockSize() > 0); - ibbElement.setAttribute("block-size", boost::lexical_cast<std::string>(ibb->getBlockSize())); + ibbElement.setAttribute("block-size", std::to_string(ibb->getBlockSize())); return ibbElement.serialize(); } case IBB::Close: { XMLElement ibbElement("close", "http://jabber.org/protocol/ibb"); ibbElement.setAttribute("sid", ibb->getStreamID()); return ibbElement.serialize(); } } assert(false); diff --git a/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h b/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h index e7cfef9..419e2d5 100644 --- a/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/IsodeIQDelegationSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/IsodeIQDelegation.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API IsodeIQDelegationSerializer : public GenericPayloadSerializer<IsodeIQDelegation> { public: IsodeIQDelegationSerializer(PayloadSerializerCollection* serializers); - virtual ~IsodeIQDelegationSerializer(); - - virtual std::string serializePayload(std::shared_ptr<IsodeIQDelegation>) const SWIFTEN_OVERRIDE; - - private: + virtual ~IsodeIQDelegationSerializer() override; + virtual std::string serializePayload(std::shared_ptr<IsodeIQDelegation>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp index 35a0a6e..95996c7 100644 --- a/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/JingleFileTransferFileInfoSerializer.cpp @@ -38,25 +38,25 @@ std::string JingleFileTransferFileInfoSerializer::serializePayload(std::shared_p } if (!fileInfo->getName().empty()) { fileElement.addNode(std::make_shared<XMLElement>("name", "", fileInfo->getName())); } if (fileInfo->getSupportsRangeRequests()) { std::shared_ptr<XMLElement> range = std::make_shared<XMLElement>("range"); if (fileInfo->getRangeOffset() != 0) { - range->setAttribute("offset", boost::lexical_cast<std::string>(fileInfo->getRangeOffset())); + range->setAttribute("offset", std::to_string(fileInfo->getRangeOffset())); } fileElement.addNode(range); } if (fileInfo->getSize() > 0) { - fileElement.addNode(std::make_shared<XMLElement>("size", "", boost::lexical_cast<std::string>(fileInfo->getSize()))); + fileElement.addNode(std::make_shared<XMLElement>("size", "", std::to_string(fileInfo->getSize()))); } for (const auto& hashElement : fileInfo->getHashes()) { std::shared_ptr<XMLElement> hash = std::make_shared<XMLElement>("hash", "urn:xmpp:hashes:1", Base64::encode(hashElement.second)); hash->setAttribute("algo", hashElement.first); fileElement.addNode(hash); } return fileElement.serialize(); diff --git a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp index 9930e44..c5c45e1 100644 --- a/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/JingleIBBTransportPayloadSerializer.cpp @@ -22,17 +22,17 @@ namespace Swift { JingleIBBTransportPayloadSerializer::JingleIBBTransportPayloadSerializer() { } std::string JingleIBBTransportPayloadSerializer::serializePayload(std::shared_ptr<JingleIBBTransportPayload> payload) const { XMLElement payloadXML("transport", "urn:xmpp:jingle:transports:ibb:1"); if (payload->getBlockSize()) { - payloadXML.setAttribute("block-size", boost::lexical_cast<std::string>(*payload->getBlockSize())); + payloadXML.setAttribute("block-size", std::to_string(*payload->getBlockSize())); } payloadXML.setAttribute("sid", payload->getSessionID()); return payloadXML.serialize(); } } diff --git a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp index 5e74d8e..f9a1832 100644 --- a/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/JingleS5BTransportPayloadSerializer.cpp @@ -33,20 +33,20 @@ std::string JingleS5BTransportPayloadSerializer::serializePayload(std::shared_pt if (!payload->getDstAddr().empty()) { payloadXML.setAttribute("dstaddr", payload->getDstAddr()); } for (const auto& candidate : payload->getCandidates()) { std::shared_ptr<XMLElement> candidateXML = std::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("port", std::to_string(candidate.hostPort.getPort())); + candidateXML->setAttribute("priority", std::to_string(candidate.priority)); candidateXML->setAttribute("type", typeToString(candidate.type)); payloadXML.addNode(candidateXML); } if (payload->hasCandidateError()) { payloadXML.addNode(std::make_shared<XMLElement>("candidate-error")); } if (payload->hasProxyError()) { payloadXML.addNode(std::make_shared<XMLElement>("proxy-error")); diff --git a/Swiften/Serializer/PayloadSerializers/LastSerializer.h b/Swiften/Serializer/PayloadSerializers/LastSerializer.h index 1710bc0..719eff5 100644 --- a/Swiften/Serializer/PayloadSerializers/LastSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/LastSerializer.h @@ -12,13 +12,13 @@ #include <Swiften/Elements/Last.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class SWIFTEN_API LastSerializer : public GenericPayloadSerializer<Last> { public: LastSerializer() : GenericPayloadSerializer<Last>() {} virtual std::string serializePayload(std::shared_ptr<Last> last) const { - return "<query xmlns='jabber:iq:last' seconds='" + boost::lexical_cast<std::string>(last->getSeconds()) + "'/>"; + return "<query xmlns='jabber:iq:last' seconds='" + std::to_string(last->getSeconds()) + "'/>"; } }; } diff --git a/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h b/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h index 7c5bd29..d8cff6a 100644 --- a/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/MAMFinSerializer.h @@ -3,22 +3,21 @@ * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MAMFin.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class SWIFTEN_API MAMFinSerializer : public GenericPayloadSerializer<MAMFin> { public: MAMFinSerializer(); - virtual ~MAMFinSerializer(); + virtual ~MAMFinSerializer() override; - virtual std::string serializePayload(std::shared_ptr<MAMFin>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<MAMFin>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h b/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h index 6b2403f..e2ed063 100644 --- a/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h +++ b/Swiften/Serializer/PayloadSerializers/MAMQuerySerializer.h @@ -3,22 +3,21 @@ * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MAMQuery.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class SWIFTEN_API MAMQuerySerializer : public GenericPayloadSerializer<MAMQuery> { public: MAMQuerySerializer(); - virtual ~MAMQuerySerializer(); + virtual ~MAMQuerySerializer() override; - virtual std::string serializePayload(std::shared_ptr<MAMQuery>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<MAMQuery>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h b/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h index f4fc054..5cac8c4 100644 --- a/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/MAMResultSerializer.h @@ -1,29 +1,28 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MAMResult.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API MAMResultSerializer : public GenericPayloadSerializer<MAMResult> { public: MAMResultSerializer(PayloadSerializerCollection* serializers); - virtual ~MAMResultSerializer(); + virtual ~MAMResultSerializer() override; - virtual std::string serializePayload(std::shared_ptr<MAMResult>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<MAMResult>) const override; private: PayloadSerializerCollection* serializers_; }; } diff --git a/Swiften/Serializer/PayloadSerializers/MIXCreateSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MIXCreateSerializer.cpp index 9476df2..2034d86 100644 --- a/Swiften/Serializer/PayloadSerializers/MIXCreateSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/MIXCreateSerializer.cpp @@ -18,19 +18,19 @@ MIXCreateSerializer::MIXCreateSerializer() { } MIXCreateSerializer::~MIXCreateSerializer() { } std::string MIXCreateSerializer::serializePayload(std::shared_ptr<MIXCreate> payload) const { if (!payload) { return ""; } - XMLElement element("create", "urn:xmpp:mix:1"); + XMLElement element("create", "urn:xmpp:mix:0"); if(payload->getChannel()) { element.setAttribute("channel", *payload->getChannel()); } if(payload->getData()) { element.addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData()))); } diff --git a/Swiften/Serializer/PayloadSerializers/MIXCreateSerializer.h b/Swiften/Serializer/PayloadSerializers/MIXCreateSerializer.h index 23cc65d..54f3adc 100644 --- a/Swiften/Serializer/PayloadSerializers/MIXCreateSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/MIXCreateSerializer.h @@ -1,25 +1,30 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MIXCreate.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class SWIFTEN_API MIXCreateSerializer : public GenericPayloadSerializer<MIXCreate> { public: MIXCreateSerializer(); - virtual ~MIXCreateSerializer(); + virtual ~MIXCreateSerializer() override; - virtual std::string serializePayload(std::shared_ptr<MIXCreate>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<MIXCreate>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/MIXDestroySerializer.cpp b/Swiften/Serializer/PayloadSerializers/MIXDestroySerializer.cpp index a395416..ed0d252 100644 --- a/Swiften/Serializer/PayloadSerializers/MIXDestroySerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/MIXDestroySerializer.cpp @@ -18,13 +18,13 @@ MIXDestroySerializer::MIXDestroySerializer() { } MIXDestroySerializer::~MIXDestroySerializer() { } std::string MIXDestroySerializer::serializePayload(std::shared_ptr<MIXDestroy> payload) const { if (!payload) { return ""; } - XMLElement element("destroy", "urn:xmpp:mix:1"); + XMLElement element("destroy", "urn:xmpp:mix:0"); element.setAttribute("channel", payload->getChannel()); return element.serialize(); } diff --git a/Swiften/Serializer/PayloadSerializers/MIXDestroySerializer.h b/Swiften/Serializer/PayloadSerializers/MIXDestroySerializer.h index c14c0dd..a0640a1 100644 --- a/Swiften/Serializer/PayloadSerializers/MIXDestroySerializer.h +++ b/Swiften/Serializer/PayloadSerializers/MIXDestroySerializer.h @@ -1,25 +1,30 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MIXDestroy.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class SWIFTEN_API MIXDestroySerializer : public GenericPayloadSerializer<MIXDestroy> { public: MIXDestroySerializer(); - virtual ~MIXDestroySerializer(); + virtual ~MIXDestroySerializer() override; - virtual std::string serializePayload(std::shared_ptr<MIXDestroy>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<MIXDestroy>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/MIXJoinSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MIXJoinSerializer.cpp index cae15c2..509e41e 100644 --- a/Swiften/Serializer/PayloadSerializers/MIXJoinSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/MIXJoinSerializer.cpp @@ -1,42 +1,49 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ #include <Swiften/Serializer/PayloadSerializers/MIXJoinSerializer.h> #include <memory> +#include <string> -#include <Swiften/Serializer/PayloadSerializers/MIXSubscribeSerializer.h> #include <Swiften/Serializer/PayloadSerializers/FormSerializer.h> #include <Swiften/Serializer/XML/XMLElement.h> #include <Swiften/Serializer/XML/XMLRawTextNode.h> using namespace Swift; MIXJoinSerializer::MIXJoinSerializer() { } MIXJoinSerializer::~MIXJoinSerializer() { } std::string MIXJoinSerializer::serializePayload(std::shared_ptr<MIXJoin> payload) const { if (!payload) { return ""; } - XMLElement element("join", "urn:xmpp:mix:1"); + XMLElement element("join", "urn:xmpp:mix:0"); if (payload->getChannel()) { element.setAttribute("channel", *payload->getChannel()); } if (payload->getJID()) { element.setAttribute("jid", *payload->getJID()); } - for (const auto& item : payload->getSubscriptions()) { - element.addNode(std::make_shared<XMLRawTextNode>(MIXSubscribeSerializer().serialize(item))); + auto subscriptionData = payload->getSubscriptions(); + std::vector<std::string> subscriptions(subscriptionData.begin(), subscriptionData.end()); + std::sort(subscriptions.begin(), subscriptions.end()); + + for (const auto& item : subscriptions) { + auto subscribeElement = std::make_shared<XMLElement>("subscribe"); + subscribeElement->setAttribute("node", item); + element.addNode(subscribeElement); } + if (payload->getForm()) { element.addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getForm()))); } return element.serialize(); } diff --git a/Swiften/Serializer/PayloadSerializers/MIXJoinSerializer.h b/Swiften/Serializer/PayloadSerializers/MIXJoinSerializer.h index a53fbe3..9be6915 100644 --- a/Swiften/Serializer/PayloadSerializers/MIXJoinSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/MIXJoinSerializer.h @@ -1,25 +1,30 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MIXJoin.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class SWIFTEN_API MIXJoinSerializer : public GenericPayloadSerializer<MIXJoin> { public: MIXJoinSerializer(); - virtual ~MIXJoinSerializer(); + virtual ~MIXJoinSerializer() override; - virtual std::string serializePayload(std::shared_ptr<MIXJoin>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<MIXJoin>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/MIXLeaveSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MIXLeaveSerializer.cpp new file mode 100644 index 0000000..111186a --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/MIXLeaveSerializer.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/Serializer/PayloadSerializers/MIXLeaveSerializer.h> + +#include <memory> + +#include <Swiften/Serializer/XML/XMLElement.h> + +namespace Swift { + +MIXLeaveSerializer::MIXLeaveSerializer() { +} + +MIXLeaveSerializer::~MIXLeaveSerializer() { +} + +std::string MIXLeaveSerializer::serializePayload(std::shared_ptr<MIXLeave> payload) const { + if (!payload) { + return ""; + } + XMLElement element("leave", "urn:xmpp:mix:0"); + if (payload->getChannel()) { + element.setAttribute("channel", *payload->getChannel()); + } + return element.serialize(); +} +} diff --git a/Swiften/Serializer/PayloadSerializers/MIXLeaveSerializer.h b/Swiften/Serializer/PayloadSerializers/MIXLeaveSerializer.h new file mode 100644 index 0000000..dd593b6 --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/MIXLeaveSerializer.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <memory> + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/MIXLeave.h> +#include <Swiften/Serializer/GenericPayloadSerializer.h> + +namespace Swift { + class SWIFTEN_API MIXLeaveSerializer : public GenericPayloadSerializer<MIXLeave> { + public: + MIXLeaveSerializer(); + virtual ~MIXLeaveSerializer() override; + + virtual std::string serializePayload(std::shared_ptr<MIXLeave>) const override; + }; +} diff --git a/Swiften/Serializer/PayloadSerializers/MIXPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MIXPayloadSerializer.cpp new file mode 100644 index 0000000..843270a --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/MIXPayloadSerializer.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/Serializer/PayloadSerializers/MIXPayloadSerializer.h> + +#include <memory> + +#include <Swiften/Serializer/XML/XMLElement.h> +#include <Swiften/Serializer/XML/XMLRawTextNode.h> +#include <Swiften/Serializer/XML/XMLTextNode.h> + +namespace Swift { + +MIXPayloadSerializer::MIXPayloadSerializer() : GenericPayloadSerializer<MIXPayload>() { +} + +std::string MIXPayloadSerializer::serializePayload(std::shared_ptr<MIXPayload> payload) const { + XMLElement mixElement("mix", "urn:xmpp:mix:0"); + + if (payload->getNick()) { + std::shared_ptr<XMLElement> nickElement = std::make_shared<XMLElement>("nick"); + nickElement->addNode(std::make_shared<XMLTextNode>(*payload->getNick())); + mixElement.addNode(nickElement); + } + + if (payload->getJID()) { + std::shared_ptr<XMLElement> jidElement = std::make_shared<XMLElement>("jid"); + jidElement->addNode(std::make_shared<XMLTextNode>(*payload->getJID())); + mixElement.addNode(jidElement); + } + + if (payload->getSubmissionID()) { + std::shared_ptr<XMLElement> subIDElement = std::make_shared<XMLElement>("submission-id"); + subIDElement->addNode(std::make_shared<XMLTextNode>(*payload->getSubmissionID())); + mixElement.addNode(subIDElement); + } + + return mixElement.serialize(); +} + +} diff --git a/Swiften/Serializer/PayloadSerializers/MIXPayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/MIXPayloadSerializer.h new file mode 100644 index 0000000..bc7ec7f --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/MIXPayloadSerializer.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/MIXPayload.h> +#include <Swiften/Serializer/GenericPayloadSerializer.h> + +namespace Swift { + class SWIFTEN_API MIXPayloadSerializer : public GenericPayloadSerializer<MIXPayload> { + public: + MIXPayloadSerializer(); + + virtual std::string serializePayload(std::shared_ptr<MIXPayload> payload) const override; + }; +} diff --git a/Swiften/Serializer/PayloadSerializers/MIXRegisterNickSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MIXRegisterNickSerializer.cpp new file mode 100644 index 0000000..9045ffe --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/MIXRegisterNickSerializer.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/Serializer/PayloadSerializers/MIXRegisterNickSerializer.h> + +#include <memory> + +#include <Swiften/Serializer/XML/XMLElement.h> +#include <Swiften/Serializer/XML/XMLTextNode.h> + +namespace Swift { + +MIXRegisterNickSerializer::MIXRegisterNickSerializer() : GenericPayloadSerializer<MIXRegisterNick>() { +} + +std::string MIXRegisterNickSerializer::serializePayload(std::shared_ptr<MIXRegisterNick> payload) const { + XMLElement registernickElement("register", "urn:xmpp:mix:0"); + + auto nickElement = std::make_shared<XMLElement>("nick"); + nickElement->addNode(std::make_shared<XMLTextNode>(payload->getNick())); + registernickElement.addNode(nickElement); + + return registernickElement.serialize(); +} + +} diff --git a/Swiften/Serializer/PayloadSerializers/MIXSubscribeSerializer.h b/Swiften/Serializer/PayloadSerializers/MIXRegisterNickSerializer.h index b343f86..011fb18 100644 --- a/Swiften/Serializer/PayloadSerializers/MIXSubscribeSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/MIXRegisterNickSerializer.h @@ -1,25 +1,20 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ #pragma once -#include <memory> - #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> -#include <Swiften/Elements/MIXSubscribe.h> +#include <Swiften/Elements/MIXRegisterNick.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { - - class SWIFTEN_API MIXSubscribeSerializer : public GenericPayloadSerializer<MIXSubscribe> { + class SWIFTEN_API MIXRegisterNickSerializer : public GenericPayloadSerializer<MIXRegisterNick> { public: - MIXSubscribeSerializer(); - virtual ~MIXSubscribeSerializer(); + MIXRegisterNickSerializer(); - virtual std::string serializePayload(std::shared_ptr<MIXSubscribe>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<MIXRegisterNick> payload) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/MIXSetNickSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MIXSetNickSerializer.cpp new file mode 100644 index 0000000..d111d8c --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/MIXSetNickSerializer.cpp @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/Serializer/PayloadSerializers/MIXSetNickSerializer.h> + +#include <memory> + +#include <Swiften/Serializer/XML/XMLElement.h> +#include <Swiften/Serializer/XML/XMLTextNode.h> + +namespace Swift { + +MIXSetNickSerializer::MIXSetNickSerializer() : GenericPayloadSerializer<MIXSetNick>() { +} + +std::string MIXSetNickSerializer::serializePayload(std::shared_ptr<MIXSetNick> payload) const { + XMLElement setnickElement("setnick", "urn:xmpp:mix:0"); + + auto nickElement = std::make_shared<XMLElement>("nick"); + nickElement->addNode(std::make_shared<XMLTextNode>(payload->getNick())); + setnickElement.addNode(nickElement); + + return setnickElement.serialize(); +} + +} diff --git a/Swiften/Serializer/PayloadSerializers/MIXSetNickSerializer.h b/Swiften/Serializer/PayloadSerializers/MIXSetNickSerializer.h new file mode 100644 index 0000000..7c28d8e --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/MIXSetNickSerializer.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/MIXSetNick.h> +#include <Swiften/Serializer/GenericPayloadSerializer.h> + +namespace Swift { + class SWIFTEN_API MIXSetNickSerializer : public GenericPayloadSerializer<MIXSetNick> { + public: + MIXSetNickSerializer(); + + virtual std::string serializePayload(std::shared_ptr<MIXSetNick> payload) const override ; + }; +} diff --git a/Swiften/Serializer/PayloadSerializers/MIXSubscribeSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MIXSubscribeSerializer.cpp deleted file mode 100644 index 3ce6d89..0000000 --- a/Swiften/Serializer/PayloadSerializers/MIXSubscribeSerializer.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2017 Tarun Gupta - * Licensed under the simplified BSD license. - * See Documentation/Licenses/BSD-simplified.txt for more information. - */ - -#include <Swiften/Serializer/PayloadSerializers/MIXSubscribeSerializer.h> - -#include <memory> - -#include <Swiften/Serializer/XML/XMLElement.h> -#include <Swiften/Serializer/XML/XMLRawTextNode.h> - -using namespace Swift; - -MIXSubscribeSerializer::MIXSubscribeSerializer() { -} - -MIXSubscribeSerializer::~MIXSubscribeSerializer() { -} - -std::string MIXSubscribeSerializer::serializePayload(std::shared_ptr<MIXSubscribe> payload) const { - if (!payload) { - return ""; - } - XMLElement element("subscribe"); - element.setAttribute("node", payload->getNode()); - return element.serialize(); -} diff --git a/Swiften/Serializer/PayloadSerializers/MIXUpdateSubscriptionSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MIXUpdateSubscriptionSerializer.cpp new file mode 100644 index 0000000..8e95474 --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/MIXUpdateSubscriptionSerializer.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <Swiften/Serializer/PayloadSerializers/MIXUpdateSubscriptionSerializer.h> + +#include <memory> + +#include <Swiften/Serializer/PayloadSerializers/FormSerializer.h> +#include <Swiften/Serializer/XML/XMLElement.h> +#include <Swiften/Serializer/XML/XMLRawTextNode.h> + +namespace Swift { + +MIXUpdateSubscriptionSerializer::MIXUpdateSubscriptionSerializer() { +} + +MIXUpdateSubscriptionSerializer::~MIXUpdateSubscriptionSerializer() { +} + +std::string MIXUpdateSubscriptionSerializer::serializePayload(std::shared_ptr<MIXUpdateSubscription> payload) const { + if (!payload) { + return ""; + } + XMLElement element("update-subscription", "urn:xmpp:mix:0"); + if (payload->getJID()) { + element.setAttribute("jid", *payload->getJID()); + } + auto subscriptionData = payload->getSubscriptions(); + std::vector<std::string> subscriptions(subscriptionData.begin(), subscriptionData.end()); + std::sort(subscriptions.begin(), subscriptions.end()); + + for (const auto& item : subscriptions) { + auto subscribeElement = std::make_shared<XMLElement>("subscribe"); + subscribeElement->setAttribute("node", item); + element.addNode(subscribeElement); + } + return element.serialize(); +} + +} diff --git a/Swiften/Serializer/PayloadSerializers/MIXUpdateSubscriptionSerializer.h b/Swiften/Serializer/PayloadSerializers/MIXUpdateSubscriptionSerializer.h new file mode 100644 index 0000000..4ba9584 --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/MIXUpdateSubscriptionSerializer.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +/* + * Copyright (c) 2017-2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <memory> + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/MIXUpdateSubscription.h> +#include <Swiften/Serializer/GenericPayloadSerializer.h> + +namespace Swift { + + class SWIFTEN_API MIXUpdateSubscriptionSerializer : public GenericPayloadSerializer<MIXUpdateSubscription> { + public: + MIXUpdateSubscriptionSerializer(); + virtual ~MIXUpdateSubscriptionSerializer() override; + + virtual std::string serializePayload(std::shared_ptr<MIXUpdateSubscription>) const override; + }; +} diff --git a/Swiften/Serializer/PayloadSerializers/MIXUserPreferenceSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MIXUserPreferenceSerializer.cpp index 2d057ad..618e0b3 100644 --- a/Swiften/Serializer/PayloadSerializers/MIXUserPreferenceSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/MIXUserPreferenceSerializer.cpp @@ -18,16 +18,16 @@ MIXUserPreferenceSerializer::MIXUserPreferenceSerializer() { } MIXUserPreferenceSerializer::~MIXUserPreferenceSerializer() { } std::string MIXUserPreferenceSerializer::serializePayload(std::shared_ptr<MIXUserPreference> payload) const { if (!payload) { return ""; } - XMLElement element("user-preference", "urn:xmpp:mix:1"); + XMLElement element("user-preference", "urn:xmpp:mix:0"); if(payload->getData()) { element.addNode(std::make_shared<XMLRawTextNode>(FormSerializer().serialize(payload->getData()))); } return element.serialize(); } } diff --git a/Swiften/Serializer/PayloadSerializers/MIXUserPreferenceSerializer.h b/Swiften/Serializer/PayloadSerializers/MIXUserPreferenceSerializer.h index 301083a..f262b83 100644 --- a/Swiften/Serializer/PayloadSerializers/MIXUserPreferenceSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/MIXUserPreferenceSerializer.h @@ -1,25 +1,30 @@ /* * Copyright (c) 2017 Tarun Gupta * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ +/* + * Copyright (c) 2017 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/MIXUserPreference.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class SWIFTEN_API MIXUserPreferenceSerializer : public GenericPayloadSerializer<MIXUserPreference> { public: MIXUserPreferenceSerializer(); - virtual ~MIXUserPreferenceSerializer(); + virtual ~MIXUserPreferenceSerializer() override; - virtual std::string serializePayload(std::shared_ptr<MIXUserPreference>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<MIXUserPreference>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp index 4f0f637..cde129e 100644 --- a/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/MUCPayloadSerializer.cpp @@ -19,27 +19,27 @@ namespace Swift { MUCPayloadSerializer::MUCPayloadSerializer() : GenericPayloadSerializer<MUCPayload>() { } std::string MUCPayloadSerializer::serializePayload(std::shared_ptr<MUCPayload> muc) const { XMLElement mucElement("x", "http://jabber.org/protocol/muc"); std::shared_ptr<XMLElement> historyElement(new XMLElement("history")); bool history = false; if (muc->getMaxChars() >= 0) { - historyElement->setAttribute("maxchars", boost::lexical_cast<std::string>(muc->getMaxChars())); + historyElement->setAttribute("maxchars", std::to_string(muc->getMaxChars())); history = true; } if (muc->getMaxStanzas() >= 0) { - historyElement->setAttribute("maxstanzas", boost::lexical_cast<std::string>(muc->getMaxStanzas())); + historyElement->setAttribute("maxstanzas", std::to_string(muc->getMaxStanzas())); history = true; } if (muc->getSeconds() >= 0) { - historyElement->setAttribute("seconds", boost::lexical_cast<std::string>(muc->getSeconds())); + historyElement->setAttribute("seconds", std::to_string(muc->getSeconds())); history = true; } if (muc->getSince() != boost::posix_time::not_a_date_time) { std::string sinceString = std::string(boost::posix_time::to_iso_extended_string(muc->getSince())); String::replaceAll(sinceString, ',', "."); sinceString += "Z"; historyElement->setAttribute("since", sinceString); history = true; } diff --git a/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h b/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h index 687d07f..fa2cef0 100644 --- a/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PrioritySerializer.h @@ -12,13 +12,13 @@ #include <Swiften/Elements/Priority.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class SWIFTEN_API PrioritySerializer : public GenericPayloadSerializer<Priority> { public: PrioritySerializer() : GenericPayloadSerializer<Priority>() {} virtual std::string serializePayload(std::shared_ptr<Priority> priority) const { - return "<priority>" + boost::lexical_cast<std::string>(priority->getPriority()) + "</priority>"; + return "<priority>" + std::to_string(priority->getPriority()) + "</priority>"; } }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h index 8862414..9b6dadb 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationSerializer.h @@ -1,29 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubAffiliation.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubAffiliationSerializer : public GenericPayloadSerializer<PubSubAffiliation> { public: PubSubAffiliationSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubAffiliationSerializer(); + virtual ~PubSubAffiliationSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubAffiliation>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubAffiliation>) const override; private: static std::string serializeType(PubSubAffiliation::Type); }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h index c51d70e..b8096d3 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubAffiliationsSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubAffiliations.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubAffiliationsSerializer : public GenericPayloadSerializer<PubSubAffiliations> { public: PubSubAffiliationsSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubAffiliationsSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubAffiliations>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubAffiliationsSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubAffiliations>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h index 6a6241c..ead5c4f 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubConfigureSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubConfigure.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubConfigureSerializer : public GenericPayloadSerializer<PubSubConfigure> { public: PubSubConfigureSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubConfigureSerializer(); + virtual ~PubSubConfigureSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubConfigure>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubConfigure>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h index 876e26f..0aa32af 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubCreateSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubCreate.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubCreateSerializer : public GenericPayloadSerializer<PubSubCreate> { public: PubSubCreateSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubCreateSerializer(); + virtual ~PubSubCreateSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubCreate>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubCreate>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h index 4f5031b..42419e3 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubDefaultSerializer.h @@ -1,29 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubDefault.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubDefaultSerializer : public GenericPayloadSerializer<PubSubDefault> { public: PubSubDefaultSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubDefaultSerializer(); + virtual ~PubSubDefaultSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubDefault>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubDefault>) const override; private: static std::string serializeType(PubSubDefault::Type); }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h index d3d1227..0f075fe 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubErrorSerializer.h @@ -1,26 +1,25 @@ /* * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubError.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class SWIFTEN_API PubSubErrorSerializer : public GenericPayloadSerializer<PubSubError> { public: PubSubErrorSerializer(); - virtual ~PubSubErrorSerializer(); + virtual ~PubSubErrorSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubError>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubError>) const override; private: static std::string serializeType(PubSubError::Type); static std::string serializeUnsupportedFeatureType(PubSubError::UnsupportedFeatureType); }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h index 9348549..766ad93 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventAssociateSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventAssociate.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventAssociateSerializer : public GenericPayloadSerializer<PubSubEventAssociate> { public: PubSubEventAssociateSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventAssociateSerializer(); + virtual ~PubSubEventAssociateSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubEventAssociate>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubEventAssociate>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h index 33144e9..749abdd 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventCollectionSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventCollection.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventCollectionSerializer : public GenericPayloadSerializer<PubSubEventCollection> { public: PubSubEventCollectionSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventCollectionSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubEventCollection>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubEventCollectionSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubEventCollection>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h index a1e565c..3902840 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventConfigurationSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventConfiguration.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventConfigurationSerializer : public GenericPayloadSerializer<PubSubEventConfiguration> { public: PubSubEventConfigurationSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventConfigurationSerializer(); + virtual ~PubSubEventConfigurationSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubEventConfiguration>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubEventConfiguration>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h index e02d44c..94f7441 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventDeleteSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventDelete.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventDeleteSerializer : public GenericPayloadSerializer<PubSubEventDelete> { public: PubSubEventDeleteSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventDeleteSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubEventDelete>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubEventDeleteSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubEventDelete>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h index 0d2d426..8f9fd00 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventDisassociateSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventDisassociate.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventDisassociateSerializer : public GenericPayloadSerializer<PubSubEventDisassociate> { public: PubSubEventDisassociateSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventDisassociateSerializer(); + virtual ~PubSubEventDisassociateSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubEventDisassociate>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubEventDisassociate>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h index f292a53..5bb2b83 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventItem.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventItemSerializer : public GenericPayloadSerializer<PubSubEventItem> { public: PubSubEventItemSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventItemSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubEventItem>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubEventItemSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubEventItem>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h index 7220fde..83d3d95 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventItemsSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventItems.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventItemsSerializer : public GenericPayloadSerializer<PubSubEventItems> { public: PubSubEventItemsSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventItemsSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubEventItems>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubEventItemsSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubEventItems>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h index 161a733..533841f 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventPurgeSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventPurge.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventPurgeSerializer : public GenericPayloadSerializer<PubSubEventPurge> { public: PubSubEventPurgeSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventPurgeSerializer(); + virtual ~PubSubEventPurgeSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubEventPurge>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubEventPurge>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h index 1720847..391d93e 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventRedirectSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventRedirect.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventRedirectSerializer : public GenericPayloadSerializer<PubSubEventRedirect> { public: PubSubEventRedirectSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventRedirectSerializer(); + virtual ~PubSubEventRedirectSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubEventRedirect>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubEventRedirect>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h index ff2f7e7..5a70fdd 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventRetractSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventRetract.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventRetractSerializer : public GenericPayloadSerializer<PubSubEventRetract> { public: PubSubEventRetractSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventRetractSerializer(); + virtual ~PubSubEventRetractSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubEventRetract>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubEventRetract>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h index bebb101..f16a749 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSerializer.h @@ -1,30 +1,29 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <vector> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEvent.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventSerializer : public GenericPayloadSerializer<PubSubEvent> { public: PubSubEventSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventSerializer(); + virtual ~PubSubEventSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubEvent>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubEvent>) const override; private: std::vector< std::shared_ptr<PayloadSerializer> > pubsubSerializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h index 7d85ba1..80830ac 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubEventSubscriptionSerializer.h @@ -1,29 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubEventSubscription.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubEventSubscriptionSerializer : public GenericPayloadSerializer<PubSubEventSubscription> { public: PubSubEventSubscriptionSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubEventSubscriptionSerializer(); + virtual ~PubSubEventSubscriptionSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubEventSubscription>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubEventSubscription>) const override; private: static std::string serializeSubscriptionType(PubSubEventSubscription::SubscriptionType); }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h index 866d09b..54a8ead 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubItemSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubItem.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubItemSerializer : public GenericPayloadSerializer<PubSubItem> { public: PubSubItemSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubItemSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubItem>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubItemSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubItem>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp index 9786f51..b2c7326 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.cpp @@ -31,18 +31,18 @@ std::string PubSubItemsSerializer::serializePayload(std::shared_ptr<PubSubItems> XMLElement element("items", "http://jabber.org/protocol/pubsub"); if (payload->getNode().empty()) { SWIFT_LOG(warning) << "Serializing PubSubItems with empty node attribute"; } element.setAttribute("node", payload->getNode()); for (const auto& item : payload->getItems()) { element.addNode(std::make_shared<XMLRawTextNode>(PubSubItemSerializer(serializers).serialize(item))); } if (payload->getMaximumItems()) { - element.setAttribute("max_items", boost::lexical_cast<std::string>(*payload->getMaximumItems())); + element.setAttribute("max_items", std::to_string(*payload->getMaximumItems())); } if (payload->getSubscriptionID()) { element.setAttribute("subid", *payload->getSubscriptionID()); } return element.serialize(); } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h index 51b0578..416c47e 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubItemsSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubItems.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubItemsSerializer : public GenericPayloadSerializer<PubSubItems> { public: PubSubItemsSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubItemsSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubItems>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubItemsSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubItems>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h index 0b7a9a7..6f30756 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOptionsSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOptions.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOptionsSerializer : public GenericPayloadSerializer<PubSubOptions> { public: PubSubOptionsSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOptionsSerializer(); + virtual ~PubSubOptionsSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubOptions>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubOptions>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h index ac6379a..ae97086 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationSerializer.h @@ -1,29 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerAffiliation.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOwnerAffiliationSerializer : public GenericPayloadSerializer<PubSubOwnerAffiliation> { public: PubSubOwnerAffiliationSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOwnerAffiliationSerializer(); + virtual ~PubSubOwnerAffiliationSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubOwnerAffiliation>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubOwnerAffiliation>) const override; private: static std::string serializeType(PubSubOwnerAffiliation::Type); }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h index 6c53189..ed244ff 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerAffiliationsSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerAffiliations.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOwnerAffiliationsSerializer : public GenericPayloadSerializer<PubSubOwnerAffiliations> { public: PubSubOwnerAffiliationsSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOwnerAffiliationsSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubOwnerAffiliations>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubOwnerAffiliationsSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubOwnerAffiliations>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h index 528f29e..4512eda 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerConfigureSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerConfigure.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOwnerConfigureSerializer : public GenericPayloadSerializer<PubSubOwnerConfigure> { public: PubSubOwnerConfigureSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOwnerConfigureSerializer(); + virtual ~PubSubOwnerConfigureSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubOwnerConfigure>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubOwnerConfigure>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h index e41900c..c19b250 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDefaultSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerDefault.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOwnerDefaultSerializer : public GenericPayloadSerializer<PubSubOwnerDefault> { public: PubSubOwnerDefaultSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOwnerDefaultSerializer(); + virtual ~PubSubOwnerDefaultSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubOwnerDefault>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubOwnerDefault>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h index c06a916..7a0cecc 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerDeleteSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerDelete.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOwnerDeleteSerializer : public GenericPayloadSerializer<PubSubOwnerDelete> { public: PubSubOwnerDeleteSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOwnerDeleteSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubOwnerDelete>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubOwnerDeleteSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubOwnerDelete>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h index b179c82..13889b6 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPubSubSerializer.h @@ -1,30 +1,29 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <vector> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerPubSub.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOwnerPubSubSerializer : public GenericPayloadSerializer<PubSubOwnerPubSub> { public: PubSubOwnerPubSubSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOwnerPubSubSerializer(); + virtual ~PubSubOwnerPubSubSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubOwnerPubSub>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubOwnerPubSub>) const override; private: std::vector< std::shared_ptr<PayloadSerializer> > pubsubSerializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h index 32f6523..d361928 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerPurgeSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerPurge.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOwnerPurgeSerializer : public GenericPayloadSerializer<PubSubOwnerPurge> { public: PubSubOwnerPurgeSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOwnerPurgeSerializer(); + virtual ~PubSubOwnerPurgeSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubOwnerPurge>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubOwnerPurge>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h index cd78fc8..c35b3ea 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerRedirectSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerRedirect.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOwnerRedirectSerializer : public GenericPayloadSerializer<PubSubOwnerRedirect> { public: PubSubOwnerRedirectSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOwnerRedirectSerializer(); + virtual ~PubSubOwnerRedirectSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubOwnerRedirect>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubOwnerRedirect>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h index 9f9e80d..52089b7 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionSerializer.h @@ -1,29 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerSubscription.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOwnerSubscriptionSerializer : public GenericPayloadSerializer<PubSubOwnerSubscription> { public: PubSubOwnerSubscriptionSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOwnerSubscriptionSerializer(); + virtual ~PubSubOwnerSubscriptionSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubOwnerSubscription>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubOwnerSubscription>) const override; private: static std::string serializeSubscriptionType(PubSubOwnerSubscription::SubscriptionType); }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h index 0c282b4..42956cf 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubOwnerSubscriptionsSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubOwnerSubscriptions.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubOwnerSubscriptionsSerializer : public GenericPayloadSerializer<PubSubOwnerSubscriptions> { public: PubSubOwnerSubscriptionsSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubOwnerSubscriptionsSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubOwnerSubscriptions>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubOwnerSubscriptionsSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubOwnerSubscriptions>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h index fb1af2e..5eeb8bf 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubPublishSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubPublish.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubPublishSerializer : public GenericPayloadSerializer<PubSubPublish> { public: PubSubPublishSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubPublishSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubPublish>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubPublishSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubPublish>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h index 64737df..23b6b59 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubRetractSerializer.h @@ -1,29 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubRetract.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubRetractSerializer : public GenericPayloadSerializer<PubSubRetract> { public: PubSubRetractSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubRetractSerializer(); + virtual ~PubSubRetractSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubRetract>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubRetract>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h index 829f827..fb14c29 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubSerializer.h @@ -1,30 +1,29 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSub.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubSerializer : public GenericPayloadSerializer<PubSub> { public: PubSubSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubSerializer(); + virtual ~PubSubSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSub>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSub>) const override; private: std::vector< std::shared_ptr<PayloadSerializer> > pubsubSerializers; PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h index fba02fe..028a437 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeOptionsSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubSubscribeOptions.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubSubscribeOptionsSerializer : public GenericPayloadSerializer<PubSubSubscribeOptions> { public: PubSubSubscribeOptionsSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubSubscribeOptionsSerializer(); + virtual ~PubSubSubscribeOptionsSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubSubscribeOptions>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubSubscribeOptions>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h index b48e849..1c0070b 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscribeSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubSubscribe.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubSubscribeSerializer : public GenericPayloadSerializer<PubSubSubscribe> { public: PubSubSubscribeSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubSubscribeSerializer(); + virtual ~PubSubSubscribeSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubSubscribe>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubSubscribe>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h index 5a5f847..b849269 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionSerializer.h @@ -1,32 +1,31 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubSubscription.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubSubscriptionSerializer : public GenericPayloadSerializer<PubSubSubscription> { public: PubSubSubscriptionSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubSubscriptionSerializer(); + virtual ~PubSubSubscriptionSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubSubscription>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubSubscription>) const override; private: static std::string serializeSubscriptionType(PubSubSubscription::SubscriptionType); private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h index caeb3ef..1430cdf 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubSubscriptionsSerializer.h @@ -1,32 +1,28 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubSubscriptions.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubSubscriptionsSerializer : public GenericPayloadSerializer<PubSubSubscriptions> { public: PubSubSubscriptionsSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubSubscriptionsSerializer(); - - virtual std::string serializePayload(std::shared_ptr<PubSubSubscriptions>) const SWIFTEN_OVERRIDE; - - private: + virtual ~PubSubSubscriptionsSerializer() override; + virtual std::string serializePayload(std::shared_ptr<PubSubSubscriptions>) const override; private: PayloadSerializerCollection* serializers; }; } diff --git a/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h b/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h index 959bd9f..002d337 100644 --- a/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/PubSubUnsubscribeSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/PubSubUnsubscribe.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API PubSubUnsubscribeSerializer : public GenericPayloadSerializer<PubSubUnsubscribe> { public: PubSubUnsubscribeSerializer(PayloadSerializerCollection* serializers); - virtual ~PubSubUnsubscribeSerializer(); + virtual ~PubSubUnsubscribeSerializer() override; - virtual std::string serializePayload(std::shared_ptr<PubSubUnsubscribe>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<PubSubUnsubscribe>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.cpp new file mode 100644 index 0000000..6e78a8d --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.cpp @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#include <Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.h> + +#include <memory> + +#include <Swiften/Base/Log.h> +#include <Swiften/Serializer/XML/XMLElement.h> +#include <Swiften/Serializer/XML/XMLRawTextNode.h> +#include <Swiften/Serializer/PayloadSerializerCollection.h> + +namespace Swift { + +ReferencePayloadSerializer::ReferencePayloadSerializer(PayloadSerializerCollection* payloadSerializers) : GenericPayloadSerializer<ReferencePayload>(), payloadSerializers_(payloadSerializers) { +} + +std::string ReferencePayloadSerializer::serializePayload(ReferencePayload::ref reference) const { + XMLElement element("reference", "urn:xmpp:reference:0"); + + auto type = reference->getType(); + if (type != ReferencePayload::Type::Unknown) { + element.setAttribute("type", getTypeString(type)); + + if (auto uri = reference->getUri()) { + element.setAttribute("uri", *uri); + } + if (auto begin = reference->getBegin()) { + element.setAttribute("begin", *begin); + } + if (auto end = reference->getEnd()) { + element.setAttribute("end", *end); + } + if (auto anchor = reference->getAnchor()) { + element.setAttribute("anchor", *anchor); + } + + std::string serializedPayloads; + for (const auto& payload : reference->getPayloads()) { + if (auto serializer = payloadSerializers_->getPayloadSerializer(payload)) { + element.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(payload))); + } + else { + SWIFT_LOG(warning) << "Could not find serializer for " << typeid(*(payload.get())).name() << std::endl; + } + } + } + return element.serialize(); +} + +const std::string ReferencePayloadSerializer::getTypeString(const ReferencePayload::Type type) const { + switch(type) { + case ReferencePayload::Type::Data: return "data"; + case ReferencePayload::Type::Mention: return "mention"; + case ReferencePayload::Type::PubSub: return "pubsub"; + case ReferencePayload::Type::Unknown: return "unknown"; + } + return ""; +} + +} diff --git a/Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.h b/Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.h new file mode 100644 index 0000000..2af6045 --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <Swiften/Base/API.h> +#include <Swiften/Elements/ReferencePayload.h> +#include <Swiften/Serializer/GenericPayloadSerializer.h> + +namespace Swift { + class PayloadSerializerCollection; + + class SWIFTEN_API ReferencePayloadSerializer : public GenericPayloadSerializer<ReferencePayload> { + public: + ReferencePayloadSerializer(PayloadSerializerCollection* payloadSerializers); + virtual std::string serializePayload(ReferencePayload::ref reference) const; + + private: + const std::string getTypeString(const ReferencePayload::Type type) const; + + PayloadSerializerCollection* payloadSerializers_; + }; +} diff --git a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp index 3302863..3d13ce3 100644 --- a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.cpp @@ -23,33 +23,33 @@ ResultSetSerializer::~ResultSetSerializer() { std::string ResultSetSerializer::serializePayload(std::shared_ptr<ResultSet> payload) const { if (!payload) { return ""; } XMLElement element("set", "http://jabber.org/protocol/rsm"); if (payload->getMaxItems()) { - element.addNode(std::make_shared<XMLElement>("max", "", boost::lexical_cast<std::string>(*payload->getMaxItems()))); + element.addNode(std::make_shared<XMLElement>("max", "", std::to_string(*payload->getMaxItems()))); } if (payload->getCount()) { - element.addNode(std::make_shared<XMLElement>("count", "", boost::lexical_cast<std::string>(*payload->getCount()))); + element.addNode(std::make_shared<XMLElement>("count", "", std::to_string(*payload->getCount()))); } if (payload->getIndex()) { - element.addNode(std::make_shared<XMLElement>("index", "", boost::lexical_cast<std::string>(*payload->getIndex()))); + element.addNode(std::make_shared<XMLElement>("index", "", std::to_string(*payload->getIndex()))); } if (payload->getFirstID()) { std::shared_ptr<XMLElement> firstElement = std::make_shared<XMLElement>("first", "", *payload->getFirstID()); if (payload->getFirstIDIndex()) { - firstElement->setAttribute("index", boost::lexical_cast<std::string>(*payload->getFirstIDIndex())); + firstElement->setAttribute("index", std::to_string(*payload->getFirstIDIndex())); } element.addNode(firstElement); } if (payload->getLastID()) { element.addNode(std::make_shared<XMLElement>("last", "", *payload->getLastID())); } if (payload->getBefore()) { diff --git a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h index 6a1429a..6f850eb 100644 --- a/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/ResultSetSerializer.h @@ -3,22 +3,21 @@ * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/ResultSet.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class SWIFTEN_API ResultSetSerializer : public GenericPayloadSerializer<ResultSet> { public: ResultSetSerializer(); - virtual ~ResultSetSerializer(); + virtual ~ResultSetSerializer() override; - virtual std::string serializePayload(std::shared_ptr<ResultSet>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<ResultSet>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h b/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h index 14cbd14..e992f72 100644 --- a/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/S5BProxyRequestSerializer.h @@ -23,19 +23,19 @@ namespace Swift { class SWIFTEN_API S5BProxyRequestSerializer : public GenericPayloadSerializer<S5BProxyRequest> { public: virtual std::string serializePayload(std::shared_ptr<S5BProxyRequest> s5bProxyRequest) const { XMLElement queryElement("query", "http://jabber.org/protocol/bytestreams"); if (s5bProxyRequest && s5bProxyRequest->getStreamHost()) { std::shared_ptr<XMLElement> streamHost = std::make_shared<XMLElement>("streamhost"); streamHost->setAttribute("host", s5bProxyRequest->getStreamHost().get().host); - streamHost->setAttribute("port", boost::lexical_cast<std::string>(s5bProxyRequest->getStreamHost().get().port)); + streamHost->setAttribute("port", std::to_string(s5bProxyRequest->getStreamHost().get().port)); streamHost->setAttribute("jid", s5bProxyRequest->getStreamHost().get().jid.toString()); queryElement.addNode(streamHost); } else if (s5bProxyRequest && s5bProxyRequest->getActivate()) { queryElement.setAttribute("sid", s5bProxyRequest->getSID()); std::shared_ptr<XMLElement> activate = std::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 index ba296f9..718e550 100644 --- a/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationFileInfoSerializer.cpp @@ -34,26 +34,26 @@ std::string StreamInitiationFileInfoSerializer::serializePayload(std::shared_ptr } 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())); + fileElement.setAttribute("size", std::to_string(fileInfo->getSize())); } if (!fileInfo->getDescription().empty()) { std::shared_ptr<XMLElement> desc = std::make_shared<XMLElement>("desc", "", fileInfo->getDescription()); fileElement.addNode(desc); } if (fileInfo->getSupportsRangeRequests()) { std::shared_ptr<XMLElement> range = std::make_shared<XMLElement>("range"); if (fileInfo->getRangeOffset() != 0) { - range->setAttribute("offset", boost::lexical_cast<std::string>(fileInfo->getRangeOffset())); + range->setAttribute("offset", std::to_string(fileInfo->getRangeOffset())); } fileElement.addNode(range); } return fileElement.serialize(); } } diff --git a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp index 3faa5b7..813edb4 100644 --- a/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/StreamInitiationSerializer.cpp @@ -32,19 +32,19 @@ std::string StreamInitiationSerializer::serializePayload(std::shared_ptr<StreamI siElement.setAttribute("id", streamInitiation->getID()); } siElement.setAttribute("profile", FILE_TRANSFER_NS); if (streamInitiation->getFileInfo()) { StreamInitiationFileInfo file = *streamInitiation->getFileInfo(); std::shared_ptr<XMLElement> fileElement(new XMLElement("file", "http://jabber.org/protocol/si/profile/file-transfer")); fileElement->setAttribute("name", file.getName()); if (file.getSize() != 0) { - fileElement->setAttribute("size", boost::lexical_cast<std::string>(file.getSize())); + fileElement->setAttribute("size", std::to_string(file.getSize())); } if (!file.getDescription().empty()) { std::shared_ptr<XMLElement> descElement(new XMLElement("desc")); descElement->addNode(std::make_shared<XMLTextNode>(file.getDescription())); fileElement->addNode(descElement); } siElement.addNode(fileElement); } diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXCreateSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXCreateSerializerTest.cpp index 78424be..80210a5 100644 --- a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXCreateSerializerTest.cpp +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXCreateSerializerTest.cpp @@ -8,22 +8,22 @@ #include <Swiften/Serializer/PayloadSerializers/MIXCreateSerializer.h> using namespace Swift; TEST(MIXCreateSerializerTest, XEP0369_Example31) { MIXCreateSerializer testling; auto create = std::make_shared<MIXCreate>(); - std::string expectedResult = "<create xmlns=\"urn:xmpp:mix:1\"/>"; + std::string expectedResult = "<create xmlns=\"urn:xmpp:mix:0\"/>"; ASSERT_EQ(expectedResult, testling.serialize(create)); } TEST(MIXCreateSerializerTest, XEP0369_Example66) { MIXCreateSerializer testling; auto create = std::make_shared<MIXCreate>(); create->setChannel(std::string("coven")); - std::string expectedResult = "<create channel=\"coven\" xmlns=\"urn:xmpp:mix:1\"/>"; + std::string expectedResult = "<create channel=\"coven\" xmlns=\"urn:xmpp:mix:0\"/>"; ASSERT_EQ(expectedResult, testling.serialize(create)); } diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXDestroySerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXDestroySerializerTest.cpp index e9cfa8b..5b21873 100644 --- a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXDestroySerializerTest.cpp +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXDestroySerializerTest.cpp @@ -10,12 +10,12 @@ using namespace Swift; TEST(MIXDestroySerializerTest, XEP0369_Example31) { MIXDestroySerializer testling; auto destroy = std::make_shared<MIXDestroy>(); destroy->setChannel(std::string("coven")); - std::string expectedResult = "<destroy channel=\"coven\" xmlns=\"urn:xmpp:mix:1\"/>"; + std::string expectedResult = "<destroy channel=\"coven\" xmlns=\"urn:xmpp:mix:0\"/>"; ASSERT_EQ(expectedResult, testling.serialize(destroy)); } diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXJoinSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXJoinSerializerTest.cpp index 61d8a4a..2987a20 100644 --- a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXJoinSerializerTest.cpp +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXJoinSerializerTest.cpp @@ -10,156 +10,124 @@ using namespace Swift; TEST(MIXJoinSerializerTest, XEP0369_Example22) { MIXJoinSerializer testling; auto join = std::make_shared<MIXJoin>(); join->setChannel(JID("coven@mix.shakespeare.example")); - std::shared_ptr<MIXSubscribe> node1(new MIXSubscribe()); - node1->setNode(std::string("urn:xmpp:mix:nodes:messages")); - join->addSubscription(node1); - std::shared_ptr<MIXSubscribe> node2(new MIXSubscribe()); - node2->setNode(std::string("urn:xmpp:mix:nodes:presence")); - join->addSubscription(node2); - std::shared_ptr<MIXSubscribe> node3(new MIXSubscribe()); - node3->setNode(std::string("urn:xmpp:mix:nodes:participants")); - join->addSubscription(node3); - std::shared_ptr<MIXSubscribe> node4(new MIXSubscribe()); - node4->setNode(std::string("urn:xmpp:mix:nodes:config")); - join->addSubscription(node4); - - std::string expectedResult = "<join channel=\"coven@mix.shakespeare.example\" xmlns=\"urn:xmpp:mix:1\">" + join->addSubscription(std::string("urn:xmpp:mix:nodes:messages")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:presence")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:participants")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:config")); + + std::string expectedResult = "<join channel=\"coven@mix.shakespeare.example\" xmlns=\"urn:xmpp:mix:0\">" + "<subscribe node=\"urn:xmpp:mix:nodes:config\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" - "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:participants\"/>" - "<subscribe node=\"urn:xmpp:mix:nodes:config\"/>" + "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "</join>"; ASSERT_EQ(expectedResult, testling.serialize(join)); } TEST(MIXJoinSerializerTest, XEP0369_Example23) { MIXJoinSerializer testling; std::shared_ptr<MIXJoin> join(new MIXJoin()); - std::shared_ptr<MIXSubscribe> node1(new MIXSubscribe()); - node1->setNode(std::string("urn:xmpp:mix:nodes:messages")); - join->addSubscription(node1); - std::shared_ptr<MIXSubscribe> node2(new MIXSubscribe()); - node2->setNode(std::string("urn:xmpp:mix:nodes:presence")); - join->addSubscription(node2); - std::shared_ptr<MIXSubscribe> node3(new MIXSubscribe()); - node3->setNode(std::string("urn:xmpp:mix:nodes:participants")); - join->addSubscription(node3); - std::shared_ptr<MIXSubscribe> node4(new MIXSubscribe()); - node4->setNode(std::string("urn:xmpp:mix:nodes:config")); - join->addSubscription(node4); - - std::string expectedResult = "<join xmlns=\"urn:xmpp:mix:1\">" + join->addSubscription(std::string("urn:xmpp:mix:nodes:messages")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:presence")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:participants")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:config")); + + std::string expectedResult = "<join xmlns=\"urn:xmpp:mix:0\">" + "<subscribe node=\"urn:xmpp:mix:nodes:config\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" - "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:participants\"/>" - "<subscribe node=\"urn:xmpp:mix:nodes:config\"/>" + "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "</join>"; ASSERT_EQ(expectedResult, testling.serialize(join)); } TEST(MIXJoinSerializerTest, XEP0369_Example24) { MIXJoinSerializer testling; std::shared_ptr<MIXJoin> join(new MIXJoin()); join->setJID(JID("123456#coven@mix.shakespeare.example")); - std::shared_ptr<MIXSubscribe> node1(new MIXSubscribe()); - node1->setNode(std::string("urn:xmpp:mix:nodes:messages")); - join->addSubscription(node1); - std::shared_ptr<MIXSubscribe> node2(new MIXSubscribe()); - node2->setNode(std::string("urn:xmpp:mix:nodes:presence")); - join->addSubscription(node2); - std::shared_ptr<MIXSubscribe> node3(new MIXSubscribe()); - node3->setNode(std::string("urn:xmpp:mix:nodes:participants")); - join->addSubscription(node3); - std::shared_ptr<MIXSubscribe> node4(new MIXSubscribe()); - node4->setNode(std::string("urn:xmpp:mix:nodes:config")); - join->addSubscription(node4); - - std::string expectedResult = "<join jid=\"123456#coven@mix.shakespeare.example\" xmlns=\"urn:xmpp:mix:1\">" + join->addSubscription(std::string("urn:xmpp:mix:nodes:messages")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:presence")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:participants")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:config")); + + std::string expectedResult = "<join jid=\"123456#coven@mix.shakespeare.example\" xmlns=\"urn:xmpp:mix:0\">" + "<subscribe node=\"urn:xmpp:mix:nodes:config\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" - "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:participants\"/>" - "<subscribe node=\"urn:xmpp:mix:nodes:config\"/>" + "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "</join>"; ASSERT_EQ(expectedResult, testling.serialize(join)); } TEST(MIXJoinSerializerTest, XEP0369_Example29) { MIXJoinSerializer testling; std::shared_ptr<MIXJoin> join(new MIXJoin()); - std::shared_ptr<MIXSubscribe> node1(new MIXSubscribe()); - node1->setNode(std::string("urn:xmpp:mix:nodes:messages")); - join->addSubscription(node1); - std::shared_ptr<MIXSubscribe> node2(new MIXSubscribe()); - node2->setNode(std::string("urn:xmpp:mix:nodes:presence")); - join->addSubscription(node2); + join->addSubscription(std::string("urn:xmpp:mix:nodes:messages")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:presence")); std::shared_ptr<Form> parameters(std::make_shared<Form>()); parameters->setType(Form::Type::SubmitType); std::shared_ptr<FormField> fieldType = std::make_shared<FormField>(FormField::HiddenType); fieldType->setName("FORM_TYPE"); - fieldType->addValue("urn:xmpp:mix:1"); + fieldType->addValue("urn:xmpp:mix:0"); parameters->addField(fieldType); std::shared_ptr<FormField> fieldJIDVisibility = std::make_shared<FormField>(); fieldJIDVisibility->setName("JID Visibility"); fieldJIDVisibility->addValue("never"); parameters->addField(fieldJIDVisibility); join->setForm(parameters); - std::string expectedResult = "<join xmlns=\"urn:xmpp:mix:1\">" + std::string expectedResult = "<join xmlns=\"urn:xmpp:mix:0\">" "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "<x type=\"submit\" xmlns=\"jabber:x:data\">" "<field type=\"hidden\" var=\"FORM_TYPE\">" - "<value>urn:xmpp:mix:1</value>" + "<value>urn:xmpp:mix:0</value>" "</field>" "<field var=\"JID Visibility\">" "<value>never</value>" "</field>" "</x>" "</join>"; ASSERT_EQ(expectedResult, testling.serialize(join)); } TEST(MIXJoinSerializerTest, XEP0369_Example30) { MIXJoinSerializer testling; std::shared_ptr<MIXJoin> join(new MIXJoin()); join->setJID(JID("hag66@shakespeare.example")); - std::shared_ptr<MIXSubscribe> node1(new MIXSubscribe()); - node1->setNode(std::string("urn:xmpp:mix:nodes:messages")); - join->addSubscription(node1); - std::shared_ptr<MIXSubscribe> node2(new MIXSubscribe()); - node2->setNode(std::string("urn:xmpp:mix:nodes:presence")); - join->addSubscription(node2); + join->addSubscription(std::string("urn:xmpp:mix:nodes:messages")); + join->addSubscription(std::string("urn:xmpp:mix:nodes:presence")); std::shared_ptr<Form> parameters(std::make_shared<Form>()); parameters->setType(Form::Type::ResultType); std::shared_ptr<FormField> fieldType = std::make_shared<FormField>(FormField::HiddenType); fieldType->setName("FORM_TYPE"); - fieldType->addValue("urn:xmpp:mix:1"); + fieldType->addValue("urn:xmpp:mix:0"); parameters->addField(fieldType); std::shared_ptr<FormField> fieldJIDVisibility = std::make_shared<FormField>(); fieldJIDVisibility->setName("JID Visibility"); fieldJIDVisibility->addValue("never"); parameters->addField(fieldJIDVisibility); std::shared_ptr<FormField> fieldprivateMessages = std::make_shared<FormField>(); fieldprivateMessages->setName("Private Messages"); @@ -167,24 +135,24 @@ TEST(MIXJoinSerializerTest, XEP0369_Example30) { parameters->addField(fieldprivateMessages); std::shared_ptr<FormField> vCard = std::make_shared<FormField>(); vCard->setName("vCard"); vCard->addValue("block"); parameters->addField(vCard); join->setForm(parameters); - std::string expectedResult = "<join jid=\"hag66@shakespeare.example\" xmlns=\"urn:xmpp:mix:1\">" + std::string expectedResult = "<join jid=\"hag66@shakespeare.example\" xmlns=\"urn:xmpp:mix:0\">" "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" "<subscribe node=\"urn:xmpp:mix:nodes:presence\"/>" "<x type=\"result\" xmlns=\"jabber:x:data\">" "<field type=\"hidden\" var=\"FORM_TYPE\">" - "<value>urn:xmpp:mix:1</value>" + "<value>urn:xmpp:mix:0</value>" "</field>" "<field var=\"JID Visibility\">" "<value>never</value>" "</field>" "<field var=\"Private Messages\">" "<value>allow</value>" "</field>" "<field var=\"vCard\">" "<value>block</value>" diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXLeaveSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXLeaveSerializerTest.cpp new file mode 100644 index 0000000..d9537a8 --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXLeaveSerializerTest.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Serializer/PayloadSerializers/MIXLeaveSerializer.h> + +using namespace Swift; + +TEST(MIXLeaveSerializerTest, XEP0369_Example33) { + MIXLeaveSerializer testling; + + auto leave = std::shared_ptr<MIXLeave>(new MIXLeave()); + leave->setChannel(JID("coven@mix.shakespeare.example")); + + std::string expectedResult = "<leave channel=\"coven@mix.shakespeare.example\" xmlns=\"urn:xmpp:mix:0\"/>"; + ASSERT_EQ(expectedResult, testling.serialize(leave)); +} + +TEST(MIXLeaveSerializerTest, XEP0369_Example34) { + MIXLeaveSerializer testling; + + auto leave = std::shared_ptr<MIXLeave>(new MIXLeave()); + + std::string expectedResult = "<leave xmlns=\"urn:xmpp:mix:0\"/>"; + ASSERT_EQ(expectedResult, testling.serialize(leave)); +} diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXPayloadSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXPayloadSerializerTest.cpp new file mode 100644 index 0000000..266b066 --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXPayloadSerializerTest.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Serializer/PayloadSerializers/MIXPayloadSerializer.h> +#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h> + +using namespace Swift; + +TEST(MIXPayloadSerializerTest, testSerializeEmpty) { + MIXPayloadSerializer testling; + + auto mix = std::shared_ptr<MIXPayload>(new MIXPayload()); + + std::string expectedResult = "<mix xmlns=\"urn:xmpp:mix:0\"/>"; + ASSERT_EQ(expectedResult, testling.serialize(mix)); +} + +TEST(MIXPayloadSerializerTest, testSerializeNick) { + MIXPayloadSerializer testling; + + auto mix = std::shared_ptr<MIXPayload>(new MIXPayload()); + mix->setNick("thirdwitch"); + + std::string expectedResult = "<mix xmlns=\"urn:xmpp:mix:0\">" + "<nick>thirdwitch</nick>" + "</mix>"; + ASSERT_EQ(expectedResult, testling.serialize(mix)); +} + +TEST(MIXPayloadSerializerTest, testSerializeJID) { + MIXPayloadSerializer testling; + + auto mix = std::shared_ptr<MIXPayload>(new MIXPayload()); + mix->setJID(JID("hecate@mix.shakespeare.example")); + + std::string expectedResult = "<mix xmlns=\"urn:xmpp:mix:0\">" + "<jid>hecate@mix.shakespeare.example</jid>" + "</mix>"; + ASSERT_EQ(expectedResult, testling.serialize(mix)); +} + +TEST(MIXPayloadSerializerTest, testSerializeAll) { + MIXPayloadSerializer testling; + + auto mix = std::shared_ptr<MIXPayload>(new MIXPayload()); + mix->setNick("thirdwitch"); + mix->setJID(JID("hecate@mix.shakespeare.example")); + mix->setSubmissionID("92vax143g"); + + std::string expectedResult = "<mix xmlns=\"urn:xmpp:mix:0\">" + "<nick>thirdwitch</nick>" + "<jid>hecate@mix.shakespeare.example</jid>" + "<submission-id>92vax143g</submission-id>" + "</mix>"; + ASSERT_EQ(expectedResult, testling.serialize(mix)); +} diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXRegisterNickSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXRegisterNickSerializerTest.cpp new file mode 100644 index 0000000..dc6cf0c --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXRegisterNickSerializerTest.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Serializer/PayloadSerializers/MIXRegisterNickSerializer.h> +#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h> + +using namespace Swift; + +TEST(MIXRegisterNickSerializerTest, testSerializeNick) { + MIXRegisterNickSerializer testling; + + auto mix = std::shared_ptr<MIXRegisterNick>(new MIXRegisterNick()); + mix->setNick(std::string("thirdwitch")); + + std::string expectedResult = "<register xmlns=\"urn:xmpp:mix:0\"><nick>thirdwitch</nick></register>"; + ASSERT_EQ(expectedResult, testling.serialize(mix)); +} diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXSetNickSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXSetNickSerializerTest.cpp new file mode 100644 index 0000000..ab29bc5 --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXSetNickSerializerTest.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Serializer/PayloadSerializers/MIXSetNickSerializer.h> +#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h> + +using namespace Swift; + +TEST(MIXSetNickSerializerTest, testSerializeNick) { + MIXSetNickSerializer testling; + + auto mix = std::shared_ptr<MIXSetNick>(new MIXSetNick()); + mix->setNick(std::string("thirdwitch")); + + std::string expectedResult = "<setnick xmlns=\"urn:xmpp:mix:0\"><nick>thirdwitch</nick></setnick>"; + ASSERT_EQ(expectedResult, testling.serialize(mix)); +} diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXUpdateSubscriptionSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXUpdateSubscriptionSerializerTest.cpp new file mode 100644 index 0000000..3e35a82 --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXUpdateSubscriptionSerializerTest.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2017 Tarun Gupta + * Licensed under the simplified BSD license. + * See Documentation/Licenses/BSD-simplified.txt for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Serializer/PayloadSerializers/MIXUpdateSubscriptionSerializer.h> + +using namespace Swift; + +TEST(MIXUpdateSubscriptionSerializerTest, XEP0369_Example28) { + MIXUpdateSubscriptionSerializer testling; + + auto update = std::make_shared<MIXUpdateSubscription>(); + update->addSubscription(std::string("urn:xmpp:mix:nodes:messages")); + + std::string expectedResult = "<update-subscription xmlns=\"urn:xmpp:mix:0\">" + "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" + "</update-subscription>"; + ASSERT_EQ(expectedResult, testling.serialize(update)); +} + +TEST(MIXUpdateSubscriptionSerializerTest, XEP0369_Example28WithJID) { + MIXUpdateSubscriptionSerializer testling; + + auto update = std::make_shared<MIXUpdateSubscription>(); + update->setJID(JID("hag66@shakespeare.example")); + update->addSubscription(std::string("urn:xmpp:mix:nodes:messages")); + + std::string expectedResult = "<update-subscription jid=\"hag66@shakespeare.example\" xmlns=\"urn:xmpp:mix:0\">" + "<subscribe node=\"urn:xmpp:mix:nodes:messages\"/>" + "</update-subscription>"; + ASSERT_EQ(expectedResult, testling.serialize(update)); +} diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXUserPreferenceSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXUserPreferenceSerializerTest.cpp index 7cbfbfc..0226b0f 100644 --- a/Swiften/Serializer/PayloadSerializers/UnitTest/MIXUserPreferenceSerializerTest.cpp +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/MIXUserPreferenceSerializerTest.cpp @@ -9,32 +9,32 @@ #include <Swiften/Serializer/PayloadSerializers/MIXUserPreferenceSerializer.h> #include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h> using namespace Swift; TEST(MIXUserPreferenceSerializerTest, XEP0369_Example31) { MIXUserPreferenceSerializer testling; auto userpreference = std::shared_ptr<MIXUserPreference>(new MIXUserPreference()); - std::string expectedResult = "<user-preference xmlns=\"urn:xmpp:mix:1\"/>"; + std::string expectedResult = "<user-preference xmlns=\"urn:xmpp:mix:0\"/>"; ASSERT_EQ(expectedResult, testling.serialize(userpreference)); } TEST(MIXUserPreferenceSerializerTest, XEP0369_Example32) { MIXUserPreferenceSerializer testling; auto userpreference = std::shared_ptr<MIXUserPreference>(new MIXUserPreference()); std::shared_ptr<Form> parameters(std::make_shared<Form>()); parameters->setType(Form::Type::ResultType); std::shared_ptr<FormField> fieldType = std::make_shared<FormField>(FormField::HiddenType); fieldType->setName("FORM_TYPE"); - fieldType->addValue("urn:xmpp:mix:1"); + fieldType->addValue("urn:xmpp:mix:0"); parameters->addField(fieldType); std::shared_ptr<FormField> fieldJIDVisibility = std::make_shared<FormField>(); fieldJIDVisibility->setName("JID Visibility"); fieldJIDVisibility->addValue("never"); parameters->addField(fieldJIDVisibility); std::shared_ptr<FormField> fieldprivateMessages = std::make_shared<FormField>(); fieldprivateMessages->setName("Private Messages"); @@ -42,22 +42,22 @@ TEST(MIXUserPreferenceSerializerTest, XEP0369_Example32) { parameters->addField(fieldprivateMessages); std::shared_ptr<FormField> vCard = std::make_shared<FormField>(); vCard->setName("vCard"); vCard->addValue("block"); parameters->addField(vCard); userpreference->setData(parameters); - std::string expectedResult = "<user-preference xmlns=\"urn:xmpp:mix:1\">" + std::string expectedResult = "<user-preference xmlns=\"urn:xmpp:mix:0\">" "<x type=\"result\" xmlns=\"jabber:x:data\">" "<field type=\"hidden\" var=\"FORM_TYPE\">" - "<value>urn:xmpp:mix:1</value>" + "<value>urn:xmpp:mix:0</value>" "</field>" "<field var=\"JID Visibility\">" "<value>never</value>" "</field>" "<field var=\"Private Messages\">" "<value>allow</value>" "</field>" "<field var=\"vCard\">" "<value>block</value>" diff --git a/Swiften/Serializer/PayloadSerializers/UnitTest/ReferencePayloadSerializerTest.cpp b/Swiften/Serializer/PayloadSerializers/UnitTest/ReferencePayloadSerializerTest.cpp new file mode 100644 index 0000000..82465d7 --- /dev/null +++ b/Swiften/Serializer/PayloadSerializers/UnitTest/ReferencePayloadSerializerTest.cpp @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#include <gtest/gtest.h> + +#include <Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.h> + +#include <Swiften/Elements/Body.h> +#include <Swiften/Serializer/PayloadSerializers/FullPayloadSerializerCollection.h> + +using namespace Swift; + +static FullPayloadSerializerCollection serializers; + +TEST(ReferencePayloadSerializerTest, testSerialize) { + ReferencePayloadSerializer testling(&serializers); + auto reference = std::make_shared<ReferencePayload>(); + reference->setType(ReferencePayload::Type::Data); + reference->setUri(boost::optional<std::string>("https://www.example.com/mindBlowingImage.jpeg")); + reference->setBegin(boost::optional<std::string>("11")); + reference->setEnd(boost::optional<std::string>("22")); + reference->setAnchor(boost::optional<std::string>("xmpp:data@localhost.example.test")); + + std::string expectedResult = + "<reference " + "anchor=\"xmpp:data@localhost.example.test\" " + "begin=\"11\" " + "end=\"22\" " + "type=\"data\" " + "uri=\"https://www.example.com/mindBlowingImage.jpeg\" " + "xmlns=\"urn:xmpp:reference:0\"/>"; + + ASSERT_EQ(expectedResult, testling.serialize(reference)); +} + +TEST(ReferencePayloadSerializerTest, testSerializeNoType) { + ReferencePayloadSerializer testling(&serializers); + auto reference = std::make_shared<ReferencePayload>(); + reference->setUri(boost::optional<std::string>("https://www.example.com/mindBlowingImage.jpeg")); + reference->setBegin(boost::optional<std::string>("11")); + reference->setEnd(boost::optional<std::string>("22")); + reference->setAnchor(boost::optional<std::string>("xmpp:data@localhost.example.test")); + + std::string expectedResult = + "<reference " + "anchor=\"xmpp:data@localhost.example.test\" " + "begin=\"11\" " + "end=\"22\" " + "type=\"data\" " + "uri=\"https://www.example.com/mindBlowingImage.jpeg\" " + "xmlns=\"urn:xmpp:reference:0\"/>"; + + ASSERT_EQ(expectedResult, testling.serialize(reference)); +} + +TEST(ReferencePayloadSerializerTest, testSerializeWithEmbeddedPayload) { + ReferencePayloadSerializer testling(&serializers); + auto reference = std::make_shared<ReferencePayload>(); + reference->setUri(boost::optional<std::string>("https://www.example.com/mindBlowingImage.jpeg")); + reference->setBegin(boost::optional<std::string>("11")); + reference->setEnd(boost::optional<std::string>("22")); + reference->setAnchor(boost::optional<std::string>("xmpp:data@localhost.example.test")); + auto payload = std::make_shared<Body>(std::string("Look, I'm in a reference")); + reference->addPayload(payload); + + std::string expectedResult = + "<reference " + "anchor=\"xmpp:data@localhost.example.test\" " + "begin=\"11\" " + "end=\"22\" " + "type=\"data\" " + "uri=\"https://www.example.com/mindBlowingImage.jpeg\" " + "xmlns=\"urn:xmpp:reference:0\">" + "<body>Look, I'm in a reference</body>" + "</reference>"; + + ASSERT_EQ(expectedResult, testling.serialize(reference)); +} diff --git a/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h b/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h index 5d38997..9c2f2db 100644 --- a/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/UserLocationSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/UserLocation.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API UserLocationSerializer : public GenericPayloadSerializer<UserLocation> { public: UserLocationSerializer(PayloadSerializerCollection* serializers); - virtual ~UserLocationSerializer(); + virtual ~UserLocationSerializer() override; - virtual std::string serializePayload(std::shared_ptr<UserLocation>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<UserLocation>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp index 687b566..8bb3a4b 100644 --- a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.cpp @@ -20,33 +20,33 @@ UserTuneSerializer::UserTuneSerializer(PayloadSerializerCollection* /*serializer UserTuneSerializer::~UserTuneSerializer() { } std::string UserTuneSerializer::serializePayload(std::shared_ptr<UserTune> payload) const { if (!payload) { return ""; } XMLElement element("tune", "http://jabber.org/protocol/tune"); if (payload->getRating()) { - element.addNode(std::make_shared<XMLElement>("rating", "", boost::lexical_cast<std::string>(*payload->getRating()))); + element.addNode(std::make_shared<XMLElement>("rating", "", std::to_string(*payload->getRating()))); } if (payload->getTitle()) { element.addNode(std::make_shared<XMLElement>("title", "", *payload->getTitle())); } if (payload->getTrack()) { element.addNode(std::make_shared<XMLElement>("track", "", *payload->getTrack())); } if (payload->getArtist()) { element.addNode(std::make_shared<XMLElement>("artist", "", *payload->getArtist())); } if (payload->getURI()) { element.addNode(std::make_shared<XMLElement>("uri", "", *payload->getURI())); } if (payload->getSource()) { element.addNode(std::make_shared<XMLElement>("source", "", *payload->getSource())); } if (payload->getLength()) { - element.addNode(std::make_shared<XMLElement>("length", "", boost::lexical_cast<std::string>(*payload->getLength()))); + element.addNode(std::make_shared<XMLElement>("length", "", std::to_string(*payload->getLength()))); } return element.serialize(); } diff --git a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h index 06e9a0e..1d5737a 100644 --- a/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h +++ b/Swiften/Serializer/PayloadSerializers/UserTuneSerializer.h @@ -1,26 +1,25 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> -#include <Swiften/Base/Override.h> #include <Swiften/Elements/UserTune.h> #include <Swiften/Serializer/GenericPayloadSerializer.h> namespace Swift { class PayloadSerializerCollection; class SWIFTEN_API UserTuneSerializer : public GenericPayloadSerializer<UserTune> { public: UserTuneSerializer(PayloadSerializerCollection* serializers); - virtual ~UserTuneSerializer(); + virtual ~UserTuneSerializer() override; - virtual std::string serializePayload(std::shared_ptr<UserTune>) const SWIFTEN_OVERRIDE; + virtual std::string serializePayload(std::shared_ptr<UserTune>) const override; }; } diff --git a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp index 34fd149..4743089 100644 --- a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp +++ b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp @@ -20,168 +20,168 @@ #include <Swiften/Elements/Whiteboard/WhiteboardDeleteOperation.h> #include <Swiften/Elements/Whiteboard/WhiteboardInsertOperation.h> #include <Swiften/Elements/Whiteboard/WhiteboardUpdateOperation.h> #include <Swiften/Serializer/XML/XMLTextNode.h> namespace Swift { void WhiteboardElementSerializingVisitor::visit(WhiteboardLineElement& line) { element = std::make_shared<XMLElement>("line"); try { - element->setAttribute("x1", boost::lexical_cast<std::string>(line.x1())); - element->setAttribute("y1", boost::lexical_cast<std::string>(line.y1())); - element->setAttribute("x2", boost::lexical_cast<std::string>(line.x2())); - element->setAttribute("y2", boost::lexical_cast<std::string>(line.y2())); + element->setAttribute("x1", std::to_string(line.x1())); + element->setAttribute("y1", std::to_string(line.y1())); + element->setAttribute("x2", std::to_string(line.x2())); + element->setAttribute("y2", std::to_string(line.y2())); element->setAttribute("id", line.getID()); element->setAttribute("stroke", line.getColor().toHex()); - element->setAttribute("stroke-width", boost::lexical_cast<std::string>(line.getPenWidth())); + element->setAttribute("stroke-width", std::to_string(line.getPenWidth())); element->setAttribute("opacity", alphaToOpacity(line.getColor().getAlpha())); } catch (boost::bad_lexical_cast&) { } } void WhiteboardElementSerializingVisitor::visit(WhiteboardFreehandPathElement& path) { element = std::make_shared<XMLElement>("path"); element->setAttribute("id", path.getID()); element->setAttribute("stroke", path.getColor().toHex()); try { - element->setAttribute("stroke-width", boost::lexical_cast<std::string>(path.getPenWidth())); + element->setAttribute("stroke-width", std::to_string(path.getPenWidth())); element->setAttribute("opacity", alphaToOpacity(path.getColor().getAlpha())); std::string pathData; if (path.getPoints().size() != 0) { std::vector<std::pair<int, int> >::const_iterator it = path.getPoints().begin(); - pathData = "M"+boost::lexical_cast<std::string>(it->first)+" "+boost::lexical_cast<std::string>(it->second)+"L"; + pathData = "M"+std::to_string(it->first)+" "+std::to_string(it->second)+"L"; for (; it != path.getPoints().end(); ++it) { - pathData += boost::lexical_cast<std::string>(it->first)+" "+boost::lexical_cast<std::string>(it->second)+" "; + pathData += std::to_string(it->first)+" "+std::to_string(it->second)+" "; } } element->setAttribute("d", pathData); } catch (boost::bad_lexical_cast&) { } } void WhiteboardElementSerializingVisitor::visit(WhiteboardRectElement& rect) { element = std::make_shared<XMLElement>("rect"); try { - element->setAttribute("x", boost::lexical_cast<std::string>(rect.getX())); - element->setAttribute("y", boost::lexical_cast<std::string>(rect.getY())); - element->setAttribute("width", boost::lexical_cast<std::string>(rect.getWidth())); - element->setAttribute("height", boost::lexical_cast<std::string>(rect.getHeight())); + element->setAttribute("x", std::to_string(rect.getX())); + element->setAttribute("y", std::to_string(rect.getY())); + element->setAttribute("width", std::to_string(rect.getWidth())); + element->setAttribute("height", std::to_string(rect.getHeight())); element->setAttribute("id", rect.getID()); element->setAttribute("stroke", rect.getPenColor().toHex()); element->setAttribute("fill", rect.getBrushColor().toHex());; - element->setAttribute("stroke-width", boost::lexical_cast<std::string>(rect.getPenWidth())); + element->setAttribute("stroke-width", std::to_string(rect.getPenWidth())); element->setAttribute("opacity", alphaToOpacity(rect.getPenColor().getAlpha())); element->setAttribute("fill-opacity", alphaToOpacity(rect.getBrushColor().getAlpha())); } catch (boost::bad_lexical_cast&) { } } void WhiteboardElementSerializingVisitor::visit(WhiteboardPolygonElement& polygon) { element = std::make_shared<XMLElement>("polygon"); try { element->setAttribute("id", polygon.getID()); element->setAttribute("stroke", polygon.getPenColor().toHex()); element->setAttribute("fill", polygon.getBrushColor().toHex());; - element->setAttribute("stroke-width", boost::lexical_cast<std::string>(polygon.getPenWidth())); + element->setAttribute("stroke-width", std::to_string(polygon.getPenWidth())); element->setAttribute("opacity", alphaToOpacity(polygon.getPenColor().getAlpha())); element->setAttribute("fill-opacity", alphaToOpacity(polygon.getBrushColor().getAlpha())); std::string points; std::vector<std::pair<int, int> >::const_iterator it = polygon.getPoints().begin(); for (; it != polygon.getPoints().end(); ++it) { - points += boost::lexical_cast<std::string>(it->first)+","+boost::lexical_cast<std::string>(it->second)+" "; + points += std::to_string(it->first)+","+std::to_string(it->second)+" "; } element->setAttribute("points", points); } catch (boost::bad_lexical_cast&) { } } void WhiteboardElementSerializingVisitor::visit(WhiteboardTextElement& text) { element = std::make_shared<XMLElement>("text"); try { - element->setAttribute("x", boost::lexical_cast<std::string>(text.getX())); - element->setAttribute("y", boost::lexical_cast<std::string>(text.getY())); - element->setAttribute("font-size", boost::lexical_cast<std::string>(text.getSize())); + element->setAttribute("x", std::to_string(text.getX())); + element->setAttribute("y", std::to_string(text.getY())); + element->setAttribute("font-size", std::to_string(text.getSize())); element->setAttribute("id", text.getID()); element->setAttribute("fill", text.getColor().toHex()); element->setAttribute("opacity", alphaToOpacity(text.getColor().getAlpha())); element->addNode(std::make_shared<XMLTextNode>(text.getText())); } catch (boost::bad_lexical_cast&) { } } void WhiteboardElementSerializingVisitor::visit(WhiteboardEllipseElement& ellipse) { element = std::make_shared<XMLElement>("ellipse"); try { - element->setAttribute("cx", boost::lexical_cast<std::string>(ellipse.getCX())); - element->setAttribute("cy", boost::lexical_cast<std::string>(ellipse.getCY())); - element->setAttribute("rx", boost::lexical_cast<std::string>(ellipse.getRX())); - element->setAttribute("ry", boost::lexical_cast<std::string>(ellipse.getRY())); + element->setAttribute("cx", std::to_string(ellipse.getCX())); + element->setAttribute("cy", std::to_string(ellipse.getCY())); + element->setAttribute("rx", std::to_string(ellipse.getRX())); + element->setAttribute("ry", std::to_string(ellipse.getRY())); element->setAttribute("id", ellipse.getID()); element->setAttribute("stroke", ellipse.getPenColor().toHex()); element->setAttribute("fill", ellipse.getBrushColor().toHex());; - element->setAttribute("stroke-width", boost::lexical_cast<std::string>(ellipse.getPenWidth())); + element->setAttribute("stroke-width", std::to_string(ellipse.getPenWidth())); element->setAttribute("opacity", alphaToOpacity(ellipse.getPenColor().getAlpha())); element->setAttribute("fill-opacity", alphaToOpacity(ellipse.getBrushColor().getAlpha())); } catch (boost::bad_lexical_cast&) { } } XMLElement::ref WhiteboardElementSerializingVisitor::getResult() const { return element; } std::string WhiteboardElementSerializingVisitor::alphaToOpacity(int alpha) const { int opacity = 100*alpha/254; if (opacity == 100) { return "1"; } else { - return "."+boost::lexical_cast<std::string>(opacity); + return "."+std::to_string(opacity); } } std::string WhiteboardSerializer::serializePayload(std::shared_ptr<WhiteboardPayload> payload) const { XMLElement element("wb", "http://swift.im/whiteboard"); if (payload->getType() == WhiteboardPayload::Data) { XMLElement::ref operationNode = std::make_shared<XMLElement>("operation"); WhiteboardElementSerializingVisitor visitor; // payload->getElement()->accept(visitor); WhiteboardInsertOperation::ref insertOp = std::dynamic_pointer_cast<WhiteboardInsertOperation>(payload->getOperation()); if (insertOp) { try { operationNode->setAttribute("type", "insert"); - operationNode->setAttribute("pos", boost::lexical_cast<std::string>(insertOp->getPos())); + operationNode->setAttribute("pos", std::to_string(insertOp->getPos())); operationNode->setAttribute("id", insertOp->getID()); operationNode->setAttribute("parentid", insertOp->getParentID()); } catch (boost::bad_lexical_cast&) { } insertOp->getElement()->accept(visitor); operationNode->addNode(visitor.getResult()); } WhiteboardUpdateOperation::ref updateOp = std::dynamic_pointer_cast<WhiteboardUpdateOperation>(payload->getOperation()); if (updateOp) { try { operationNode->setAttribute("type", "update"); - operationNode->setAttribute("pos", boost::lexical_cast<std::string>(updateOp->getPos())); + operationNode->setAttribute("pos", std::to_string(updateOp->getPos())); operationNode->setAttribute("id", updateOp->getID()); operationNode->setAttribute("parentid", updateOp->getParentID()); - operationNode->setAttribute("newpos", boost::lexical_cast<std::string>(updateOp->getNewPos())); + operationNode->setAttribute("newpos", std::to_string(updateOp->getNewPos())); } catch (boost::bad_lexical_cast&) { } updateOp->getElement()->accept(visitor); operationNode->addNode(visitor.getResult()); } WhiteboardDeleteOperation::ref deleteOp = std::dynamic_pointer_cast<WhiteboardDeleteOperation>(payload->getOperation()); if (deleteOp) { try { operationNode->setAttribute("type", "delete"); - operationNode->setAttribute("pos", boost::lexical_cast<std::string>(deleteOp->getPos())); + operationNode->setAttribute("pos", std::to_string(deleteOp->getPos())); operationNode->setAttribute("id", deleteOp->getID()); operationNode->setAttribute("parentid", deleteOp->getParentID()); operationNode->setAttribute("elementid", deleteOp->getElementID()); } catch (boost::bad_lexical_cast&) { } } element.addNode(operationNode); } element.setAttribute("type", typeToString(payload->getType())); diff --git a/Swiften/Serializer/StanzaAckSerializer.h b/Swiften/Serializer/StanzaAckSerializer.h index f5a27dc..228d67b 100644 --- a/Swiften/Serializer/StanzaAckSerializer.h +++ b/Swiften/Serializer/StanzaAckSerializer.h @@ -19,14 +19,14 @@ namespace Swift { class SWIFTEN_API StanzaAckSerializer : public GenericElementSerializer<StanzaAck> { public: StanzaAckSerializer() : GenericElementSerializer<StanzaAck>() { } virtual SafeByteArray serialize(std::shared_ptr<ToplevelElement> element) const { StanzaAck::ref stanzaAck(std::dynamic_pointer_cast<StanzaAck>(element)); assert(stanzaAck->isValid()); XMLElement result("a", "urn:xmpp:sm:2"); - result.setAttribute("h", std::string(boost::lexical_cast<std::string>(stanzaAck->getHandledStanzasCount()))); + result.setAttribute("h", std::string(std::to_string(stanzaAck->getHandledStanzasCount()))); return createSafeByteArray(result.serialize()); } }; } diff --git a/Swiften/Serializer/StreamResumeSerializer.cpp b/Swiften/Serializer/StreamResumeSerializer.cpp index 619ac9c..e4a40c9 100644 --- a/Swiften/Serializer/StreamResumeSerializer.cpp +++ b/Swiften/Serializer/StreamResumeSerializer.cpp @@ -17,13 +17,13 @@ using namespace Swift; StreamResumeSerializer::StreamResumeSerializer() : GenericElementSerializer<StreamResume>() { } SafeByteArray StreamResumeSerializer::serialize(std::shared_ptr<ToplevelElement> el) const { std::shared_ptr<StreamResume> e(std::dynamic_pointer_cast<StreamResume>(el)); XMLElement element("resume", "urn:xmpp:sm:2"); element.setAttribute("previd", e->getResumeID()); if (e->getHandledStanzasCount()) { - element.setAttribute("h", boost::lexical_cast<std::string>(e->getHandledStanzasCount().get())); + element.setAttribute("h", std::to_string(e->getHandledStanzasCount().get())); } return createSafeByteArray(element.serialize()); } diff --git a/Swiften/Serializer/StreamResumedSerializer.cpp b/Swiften/Serializer/StreamResumedSerializer.cpp index 5b88ded..2398335 100644 --- a/Swiften/Serializer/StreamResumedSerializer.cpp +++ b/Swiften/Serializer/StreamResumedSerializer.cpp @@ -17,13 +17,13 @@ using namespace Swift; StreamResumedSerializer::StreamResumedSerializer() : GenericElementSerializer<StreamResumed>() { } SafeByteArray StreamResumedSerializer::serialize(std::shared_ptr<ToplevelElement> el) const { std::shared_ptr<StreamResumed> e(std::dynamic_pointer_cast<StreamResumed>(el)); XMLElement element("resumed", "urn:xmpp:sm:2"); element.setAttribute("previd", e->getResumeID()); if (e->getHandledStanzasCount()) { - element.setAttribute("h", boost::lexical_cast<std::string>(e->getHandledStanzasCount().get())); + element.setAttribute("h", std::to_string(e->getHandledStanzasCount().get())); } return createSafeByteArray(element.serialize()); } diff --git a/Swiften/Session/BasicSessionStream.cpp b/Swiften/Session/BasicSessionStream.cpp index 10c6ad0..c44961d 100644 --- a/Swiften/Session/BasicSessionStream.cpp +++ b/Swiften/Session/BasicSessionStream.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Session/BasicSessionStream.h> #include <memory> #include <boost/bind.hpp> @@ -28,150 +28,147 @@ BasicSessionStream::BasicSessionStream( PayloadSerializerCollection* payloadSerializers, TLSContextFactory* tlsContextFactory, TimerFactory* timerFactory, XMLParserFactory* xmlParserFactory, const TLSOptions& tlsOptions) : available(false), connection(connection), tlsContextFactory(tlsContextFactory), timerFactory(timerFactory), - compressionLayer(nullptr), - tlsLayer(nullptr), - whitespacePingLayer(nullptr), tlsOptions_(tlsOptions) { - xmppLayer = new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, streamType); + auto xmppLayer = std::make_unique<XMPPLayer>(payloadParserFactories, payloadSerializers, xmlParserFactory, streamType); xmppLayer->onStreamStart.connect(boost::bind(&BasicSessionStream::handleStreamStartReceived, this, _1)); xmppLayer->onStreamEnd.connect(boost::bind(&BasicSessionStream::handleStreamEndReceived, this)); xmppLayer->onElement.connect(boost::bind(&BasicSessionStream::handleElementReceived, this, _1)); xmppLayer->onError.connect(boost::bind(&BasicSessionStream::handleXMPPError, this)); xmppLayer->onDataRead.connect(boost::bind(&BasicSessionStream::handleDataRead, this, _1)); xmppLayer->onWriteData.connect(boost::bind(&BasicSessionStream::handleDataWritten, this, _1)); connection->onDisconnected.connect(boost::bind(&BasicSessionStream::handleConnectionFinished, this, _1)); - connectionLayer = new ConnectionLayer(connection); - - streamStack = new StreamStack(xmppLayer, connectionLayer); + streamStack = std::make_unique<StreamStack>(std::move(xmppLayer), std::unique_ptr<ConnectionLayer>(new ConnectionLayer(connection))); available = true; } BasicSessionStream::~BasicSessionStream() { - delete compressionLayer; - if (tlsLayer) { + if (auto tlsLayer = streamStack->getLayer<TLSLayer>()) { tlsLayer->onError.disconnect(boost::bind(&BasicSessionStream::handleTLSError, this, _1)); tlsLayer->onConnected.disconnect(boost::bind(&BasicSessionStream::handleTLSConnected, this)); - delete tlsLayer; } - delete whitespacePingLayer; - delete streamStack; connection->onDisconnected.disconnect(boost::bind(&BasicSessionStream::handleConnectionFinished, this, _1)); - delete connectionLayer; + auto xmppLayer = streamStack->getLayer<XMPPLayer>(); xmppLayer->onStreamStart.disconnect(boost::bind(&BasicSessionStream::handleStreamStartReceived, this, _1)); xmppLayer->onStreamEnd.disconnect(boost::bind(&BasicSessionStream::handleStreamEndReceived, this)); xmppLayer->onElement.disconnect(boost::bind(&BasicSessionStream::handleElementReceived, this, _1)); xmppLayer->onError.disconnect(boost::bind(&BasicSessionStream::handleXMPPError, this)); xmppLayer->onDataRead.disconnect(boost::bind(&BasicSessionStream::handleDataRead, this, _1)); xmppLayer->onWriteData.disconnect(boost::bind(&BasicSessionStream::handleDataWritten, this, _1)); - delete xmppLayer; } void BasicSessionStream::writeHeader(const ProtocolHeader& header) { assert(available); + auto* xmppLayer = streamStack->getLayer<XMPPLayer>(); xmppLayer->writeHeader(header); } void BasicSessionStream::writeElement(std::shared_ptr<ToplevelElement> element) { assert(available); + auto* xmppLayer = streamStack->getLayer<XMPPLayer>(); xmppLayer->writeElement(element); } void BasicSessionStream::writeFooter() { assert(available); + auto* xmppLayer = streamStack->getLayer<XMPPLayer>(); xmppLayer->writeFooter(); } void BasicSessionStream::writeData(const std::string& data) { assert(available); + auto* xmppLayer = streamStack->getLayer<XMPPLayer>(); xmppLayer->writeData(data); } void BasicSessionStream::close() { connection->disconnect(); } bool BasicSessionStream::isOpen() { return available; } bool BasicSessionStream::supportsTLSEncryption() { return tlsContextFactory && tlsContextFactory->canCreate(); } void BasicSessionStream::addTLSEncryption() { assert(available); - tlsLayer = new TLSLayer(tlsContextFactory, tlsOptions_); + auto tlsContext = tlsContextFactory->createTLSContext(tlsOptions_); + auto tlsLayer = std::make_unique<TLSLayer>(std::move(tlsContext)); if (hasTLSCertificate() && !tlsLayer->setClientCertificate(getTLSCertificate())) { onClosed(std::make_shared<SessionStreamError>(SessionStreamError::InvalidTLSCertificateError)); } else { - streamStack->addLayer(tlsLayer); + streamStack->addLayer(std::move(tlsLayer)); + auto tlsLayer = streamStack->getLayer<TLSLayer>(); tlsLayer->onError.connect(boost::bind(&BasicSessionStream::handleTLSError, this, _1)); tlsLayer->onConnected.connect(boost::bind(&BasicSessionStream::handleTLSConnected, this)); tlsLayer->connect(); } } bool BasicSessionStream::isTLSEncrypted() { - return tlsLayer; + return streamStack->getLayer<TLSLayer>(); } Certificate::ref BasicSessionStream::getPeerCertificate() const { - return tlsLayer->getPeerCertificate(); + return streamStack->getLayer<TLSLayer>()->getPeerCertificate(); } std::vector<Certificate::ref> BasicSessionStream::getPeerCertificateChain() const { - return tlsLayer->getPeerCertificateChain(); + return streamStack->getLayer<TLSLayer>()->getPeerCertificateChain(); } std::shared_ptr<CertificateVerificationError> BasicSessionStream::getPeerCertificateVerificationError() const { - return tlsLayer->getPeerCertificateVerificationError(); + return streamStack->getLayer<TLSLayer>()->getPeerCertificateVerificationError(); } ByteArray BasicSessionStream::getTLSFinishMessage() const { - return tlsLayer->getContext()->getFinishMessage(); + return streamStack->getLayer<TLSLayer>()->getContext()->getFinishMessage(); } bool BasicSessionStream::supportsZLibCompression() { return true; } void BasicSessionStream::addZLibCompression() { - compressionLayer = new CompressionLayer(); - streamStack->addLayer(compressionLayer); + streamStack->addLayer(std::make_unique<CompressionLayer>()); } void BasicSessionStream::setWhitespacePingEnabled(bool enabled) { + auto whitespacePingLayer = streamStack->getLayer<WhitespacePingLayer>(); if (enabled) { if (!whitespacePingLayer) { - whitespacePingLayer = new WhitespacePingLayer(timerFactory); - streamStack->addLayer(whitespacePingLayer); + streamStack->addLayer(std::make_unique<WhitespacePingLayer>(timerFactory)); + whitespacePingLayer = streamStack->getLayer<WhitespacePingLayer>(); } whitespacePingLayer->setActive(); } else if (whitespacePingLayer) { whitespacePingLayer->setInactive(); } } void BasicSessionStream::resetXMPPParser() { + auto* xmppLayer = streamStack->getLayer<XMPPLayer>(); xmppLayer->resetParser(); } void BasicSessionStream::handleStreamStartReceived(const ProtocolHeader& header) { onStreamStartReceived(header); } void BasicSessionStream::handleStreamEndReceived() { onStreamEndReceived(); diff --git a/Swiften/Session/BasicSessionStream.h b/Swiften/Session/BasicSessionStream.h index 48b3d63..30a7e3b 100644 --- a/Swiften/Session/BasicSessionStream.h +++ b/Swiften/Session/BasicSessionStream.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <Swiften/Base/API.h> @@ -77,19 +77,14 @@ namespace Swift { void handleElementReceived(std::shared_ptr<ToplevelElement>); void handleDataRead(const SafeByteArray& data); void handleDataWritten(const SafeByteArray& data); private: bool available; std::shared_ptr<Connection> connection; TLSContextFactory* tlsContextFactory; TimerFactory* timerFactory; - XMPPLayer* xmppLayer; - ConnectionLayer* connectionLayer; - CompressionLayer* compressionLayer; - TLSLayer* tlsLayer; - WhitespacePingLayer* whitespacePingLayer; - StreamStack* streamStack; + std::unique_ptr<StreamStack> streamStack; TLSOptions tlsOptions_; }; } diff --git a/Swiften/Session/Session.cpp b/Swiften/Session/Session.cpp index ebdb5d1..b1525b8 100644 --- a/Swiften/Session/Session.cpp +++ b/Swiften/Session/Session.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/Session/Session.h> #include <boost/bind.hpp> #include <Swiften/StreamStack/StreamStack.h> @@ -16,74 +16,76 @@ namespace Swift { Session::Session( std::shared_ptr<Connection> connection, PayloadParserFactoryCollection* payloadParserFactories, PayloadSerializerCollection* payloadSerializers, XMLParserFactory* xmlParserFactory) : connection(connection), payloadParserFactories(payloadParserFactories), payloadSerializers(payloadSerializers), xmlParserFactory(xmlParserFactory), - xmppLayer(nullptr), - connectionLayer(nullptr), - streamStack(nullptr), finishing(false) { } Session::~Session() { - delete streamStack; - delete connectionLayer; - delete xmppLayer; } void Session::startSession() { initializeStreamStack(); handleSessionStarted(); } void Session::finishSession() { if (finishing) { return; } finishing = true; - if (xmppLayer) { + if (auto xmppLayer = getXMPPLayer()) { xmppLayer->writeFooter(); } connection->disconnect(); } void Session::finishSession(const SessionError& /*error*/) { if (finishing) { return; } finishing = true; - if (xmppLayer) { + if (auto xmppLayer = getXMPPLayer()) { xmppLayer->writeFooter(); } connection->disconnect(); } void Session::initializeStreamStack() { - xmppLayer = new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, ClientStreamType); + auto xmppLayer = std::unique_ptr<XMPPLayer>(new XMPPLayer(payloadParserFactories, payloadSerializers, xmlParserFactory, ClientStreamType)); xmppLayer->onStreamStart.connect( boost::bind(&Session::handleStreamStart, this, _1)); xmppLayer->onElement.connect(boost::bind(&Session::handleElement, this, _1)); xmppLayer->onError.connect( boost::bind(&Session::finishSession, this, XMLError)); xmppLayer->onDataRead.connect(boost::bind(boost::ref(onDataRead), _1)); xmppLayer->onWriteData.connect(boost::bind(boost::ref(onDataWritten), _1)); connection->onDisconnected.connect( boost::bind(&Session::handleDisconnected, this, _1)); - connectionLayer = new ConnectionLayer(connection); - streamStack = new StreamStack(xmppLayer, connectionLayer); + streamStack = std::unique_ptr<StreamStack>(new StreamStack(std::move(xmppLayer), std::unique_ptr<ConnectionLayer>(new ConnectionLayer(connection)))); } +XMPPLayer* Session::getXMPPLayer() const { + return dynamic_cast<XMPPLayer*>(streamStack->getTopLayer()); +} + +StreamStack* Session::getStreamStack() const { + return streamStack.get(); +} + + void Session::sendElement(std::shared_ptr<ToplevelElement> stanza) { - xmppLayer->writeElement(stanza); + getXMPPLayer()->writeElement(stanza); } void Session::handleDisconnected(const boost::optional<Connection::Error>& connectionError) { connection->onDisconnected.disconnect( boost::bind(&Session::handleDisconnected, this, _1)); if (connectionError) { switch (*connectionError) { case Connection::ReadError: handleSessionFinished(ConnectionReadError); diff --git a/Swiften/Session/Session.h b/Swiften/Session/Session.h index 04153ec..e6a0d53 100644 --- a/Swiften/Session/Session.h +++ b/Swiften/Session/Session.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2017 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <boost/optional.hpp> @@ -79,35 +79,29 @@ namespace Swift { void finishSession(const SessionError&); virtual void handleSessionStarted() {} virtual void handleSessionFinished(const boost::optional<SessionError>&) {} virtual void handleElement(std::shared_ptr<ToplevelElement>) = 0; virtual void handleStreamStart(const ProtocolHeader&) = 0; void initializeStreamStack(); - XMPPLayer* getXMPPLayer() const { - return xmppLayer; - } - - StreamStack* getStreamStack() const { - return streamStack; - } + XMPPLayer* getXMPPLayer() const; + StreamStack* getStreamStack() const; void setFinished(); private: void handleDisconnected(const boost::optional<Connection::Error>& error); private: JID localJID; JID remoteJID; std::shared_ptr<Connection> connection; PayloadParserFactoryCollection* payloadParserFactories; PayloadSerializerCollection* payloadSerializers; XMLParserFactory* xmlParserFactory; - XMPPLayer* xmppLayer; - ConnectionLayer* connectionLayer; - StreamStack* streamStack; + + std::unique_ptr<StreamStack> streamStack; bool finishing; }; } diff --git a/Swiften/StreamManagement/StanzaAckRequester.cpp b/Swiften/StreamManagement/StanzaAckRequester.cpp index 8941f4a..a0f5b70 100644 --- a/Swiften/StreamManagement/StanzaAckRequester.cpp +++ b/Swiften/StreamManagement/StanzaAckRequester.cpp @@ -1,25 +1,23 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/StreamManagement/StanzaAckRequester.h> -#include <boost/numeric/conversion/cast.hpp> - #include <Swiften/Base/Log.h> #include <Swiften/Elements/Message.h> namespace Swift { -static const unsigned int MAX_HANDLED_STANZA_COUNT = boost::numeric_cast<unsigned int>((1ULL<<32) - 1); +static const unsigned int MAX_HANDLED_STANZA_COUNT = static_cast<unsigned int>((1ULL<<32) - 1); StanzaAckRequester::StanzaAckRequester() : lastHandledStanzasCount(0) { } void StanzaAckRequester::handleStanzaSent(std::shared_ptr<Stanza> stanza) { unackedStanzas.push_back(stanza); if (std::dynamic_pointer_cast<Message>(stanza)) { onRequestAck(); diff --git a/Swiften/StreamManagement/StanzaAckResponder.cpp b/Swiften/StreamManagement/StanzaAckResponder.cpp index b6171d0..bfe6f4d 100644 --- a/Swiften/StreamManagement/StanzaAckResponder.cpp +++ b/Swiften/StreamManagement/StanzaAckResponder.cpp @@ -1,22 +1,20 @@ /* - * Copyright (c) 2010 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/StreamManagement/StanzaAckResponder.h> -#include <boost/numeric/conversion/cast.hpp> - namespace Swift { -static const unsigned int MAX_HANDLED_STANZA_COUNT = boost::numeric_cast<unsigned int>((1ULL<<32) - 1); +static const unsigned int MAX_HANDLED_STANZA_COUNT = static_cast<unsigned int>((1ULL << 32) - 1); StanzaAckResponder::StanzaAckResponder() : handledStanzasCount(0) { } void StanzaAckResponder::handleStanzaReceived() { handledStanzasCount = (handledStanzasCount == MAX_HANDLED_STANZA_COUNT ? 0 : handledStanzasCount + 1); } void StanzaAckResponder::handleAckRequestReceived() { diff --git a/Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp b/Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp index ce16e1f..e0ebefd 100644 --- a/Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp +++ b/Swiften/StreamManagement/UnitTest/StanzaAckRequesterTest.cpp @@ -1,17 +1,18 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ +#include <cstdint> + #include <boost/bind.hpp> -#include <boost/numeric/conversion/cast.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <Swiften/Elements/IQ.h> #include <Swiften/Elements/Message.h> #include <Swiften/Elements/Presence.h> #include <Swiften/StreamManagement/StanzaAckRequester.h> @@ -105,19 +106,19 @@ class StanzaAckRequesterTest : public CppUnit::TestFixture { CPPUNIT_ASSERT_EQUAL(3, static_cast<int>(ackedStanzas.size())); CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[0]->getID()); CPPUNIT_ASSERT_EQUAL(std::string("m2"), ackedStanzas[1]->getID()); CPPUNIT_ASSERT_EQUAL(std::string("m3"), ackedStanzas[2]->getID()); } // Handle stanza ack count wrapping, as per the XEP void testHandleAckReceived_WrapAround() { std::shared_ptr<StanzaAckRequester> testling(createRequester()); - testling->lastHandledStanzasCount = boost::numeric_cast<unsigned int>((1ULL<<32) - 1); + testling->lastHandledStanzasCount = UINT32_MAX; testling->handleStanzaSent(createMessage("m1")); testling->handleStanzaSent(createMessage("m2")); testling->handleAckReceived(1); CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(ackedStanzas.size())); CPPUNIT_ASSERT_EQUAL(std::string("m1"), ackedStanzas[0]->getID()); CPPUNIT_ASSERT_EQUAL(std::string("m2"), ackedStanzas[1]->getID()); } diff --git a/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp b/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp index ffdabe9..ee4b913 100644 --- a/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp +++ b/Swiften/StreamManagement/UnitTest/StanzaAckResponderTest.cpp @@ -1,17 +1,18 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ +#include <cstdint> + #include <boost/bind.hpp> -#include <boost/numeric/conversion/cast.hpp> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <Swiften/Elements/Message.h> #include <Swiften/StreamManagement/StanzaAckResponder.h> using namespace Swift; @@ -57,19 +58,19 @@ class StanzaAckResponderTest : public CppUnit::TestFixture { CPPUNIT_ASSERT_EQUAL(2, static_cast<int>(acks.size())); CPPUNIT_ASSERT_EQUAL(1U, acks[0]); CPPUNIT_ASSERT_EQUAL(2U, acks[1]); } // Handle stanza ack count wrapping, as per the XEP void testHandleAckRequestReceived_WrapAround() { std::shared_ptr<StanzaAckResponder> testling(createResponder()); - testling->handledStanzasCount = boost::numeric_cast<unsigned int>((1ULL<<32) - 1); + testling->handledStanzasCount = UINT32_MAX; testling->handleStanzaReceived(); testling->handleStanzaReceived(); testling->handleAckRequestReceived(); CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(acks.size())); CPPUNIT_ASSERT_EQUAL(1U, acks[0]); } diff --git a/Swiften/StreamStack/StreamStack.cpp b/Swiften/StreamStack/StreamStack.cpp index 44a018d..cf80fb1 100644 --- a/Swiften/StreamStack/StreamStack.cpp +++ b/Swiften/StreamStack/StreamStack.cpp @@ -1,37 +1,37 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/StreamStack/StreamStack.h> #include <boost/bind.hpp> +#include <Swiften/StreamStack/HighLayer.h> #include <Swiften/StreamStack/LowLayer.h> #include <Swiften/StreamStack/StreamLayer.h> -#include <Swiften/StreamStack/XMPPLayer.h> namespace Swift { -StreamStack::StreamStack(XMPPLayer* xmppLayer, LowLayer* physicalLayer) : xmppLayer_(xmppLayer), physicalLayer_(physicalLayer) { - physicalLayer_->setParentLayer(xmppLayer_); - xmppLayer_->setChildLayer(physicalLayer_); +StreamStack::StreamStack(std::unique_ptr<HighLayer> topLayer, std::unique_ptr<LowLayer> bottomLayer) : topLayer_(std::move(topLayer)), bottomLayer_(std::move(bottomLayer)) { + bottomLayer_->setParentLayer(topLayer_.get()); + topLayer_->setChildLayer(bottomLayer_.get()); } StreamStack::~StreamStack() { } -void StreamStack::addLayer(StreamLayer* newLayer) { - LowLayer* lowLayer = layers_.empty() ? physicalLayer_ : *layers_.rbegin(); +void StreamStack::addLayer(std::unique_ptr<StreamLayer> streamLayer) { + auto* lowLayer = layers_.empty() ? bottomLayer_.get() : layers_.rbegin()->get(); - xmppLayer_->setChildLayer(newLayer); - newLayer->setParentLayer(xmppLayer_); + topLayer_->setChildLayer(streamLayer.get()); + streamLayer->setParentLayer(topLayer_.get()); - lowLayer->setParentLayer(newLayer); - newLayer->setChildLayer(lowLayer); + lowLayer->setParentLayer(streamLayer.get()); + streamLayer->setChildLayer(lowLayer); - layers_.push_back(newLayer); + layers_.emplace_back(std::move(streamLayer)); } } diff --git a/Swiften/StreamStack/StreamStack.h b/Swiften/StreamStack/StreamStack.h index b12a69f..263b1f5 100644 --- a/Swiften/StreamStack/StreamStack.h +++ b/Swiften/StreamStack/StreamStack.h @@ -1,48 +1,54 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <vector> #include <boost/signals2.hpp> #include <Swiften/Base/API.h> #include <Swiften/Elements/Stanza.h> namespace Swift { - class XMPPLayer; + class HighLayer; class LowLayer; class StreamLayer; class SWIFTEN_API StreamStack { public: - StreamStack(XMPPLayer* xmppLayer, LowLayer* physicalLayer); + StreamStack(std::unique_ptr<HighLayer> topLayer, std::unique_ptr<LowLayer> bottomLayer); ~StreamStack(); - void addLayer(StreamLayer*); + void addLayer(std::unique_ptr<StreamLayer> /* streamLayer */); - XMPPLayer* getXMPPLayer() const { - return xmppLayer_; + HighLayer* getTopLayer() const { + return topLayer_.get(); } - template<typename T> T* getLayer() { - for (auto& i : layers_) { - T* layer = dynamic_cast<T*>(i); + template<typename T> T* getLayer() const { + for (const auto& i : layers_) { + T* layer = dynamic_cast<T*>(i.get()); if (layer) { return layer; } } + if (T* layer = dynamic_cast<T*>(topLayer_.get())) { + return layer; + } + if (T* layer = dynamic_cast<T*>(bottomLayer_.get())) { + return layer; + } return nullptr; } private: - XMPPLayer* xmppLayer_; - LowLayer* physicalLayer_; - std::vector<StreamLayer*> layers_; + std::unique_ptr<HighLayer> topLayer_; + std::unique_ptr<LowLayer> bottomLayer_; + std::vector<std::unique_ptr<StreamLayer>> layers_; }; } diff --git a/Swiften/StreamStack/TLSLayer.cpp b/Swiften/StreamStack/TLSLayer.cpp index ced879e..9f84889 100644 --- a/Swiften/StreamStack/TLSLayer.cpp +++ b/Swiften/StreamStack/TLSLayer.cpp @@ -1,56 +1,56 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/StreamStack/TLSLayer.h> +#include <memory> + #include <boost/bind.hpp> #include <Swiften/TLS/TLSContext.h> #include <Swiften/TLS/TLSContextFactory.h> namespace Swift { -TLSLayer::TLSLayer(TLSContextFactory* factory, const TLSOptions& tlsOptions) { - context = factory->createTLSContext(tlsOptions); - context->onDataForNetwork.connect(boost::bind(&TLSLayer::writeDataToChildLayer, this, _1)); - context->onDataForApplication.connect(boost::bind(&TLSLayer::writeDataToParentLayer, this, _1)); - context->onConnected.connect(onConnected); - context->onError.connect(onError); +TLSLayer::TLSLayer(std::unique_ptr<TLSContext> tlsContext) : context_(std::move(tlsContext)) { + context_->onDataForNetwork.connect(boost::bind(&TLSLayer::writeDataToChildLayer, this, _1)); + context_->onDataForApplication.connect(boost::bind(&TLSLayer::writeDataToParentLayer, this, _1)); + context_->onConnected.connect(onConnected); + context_->onError.connect(onError); } TLSLayer::~TLSLayer() { - delete context; } void TLSLayer::connect() { - context->connect(); + context_->connect(); } void TLSLayer::writeData(const SafeByteArray& data) { - context->handleDataFromApplication(data); + context_->handleDataFromApplication(data); } void TLSLayer::handleDataRead(const SafeByteArray& data) { - context->handleDataFromNetwork(data); + context_->handleDataFromNetwork(data); } bool TLSLayer::setClientCertificate(CertificateWithKey::ref certificate) { - return context->setClientCertificate(certificate); + return context_->setClientCertificate(certificate); } Certificate::ref TLSLayer::getPeerCertificate() const { - return context->getPeerCertificate(); + return context_->getPeerCertificate(); } std::vector<Certificate::ref> TLSLayer::getPeerCertificateChain() const { - return context->getPeerCertificateChain(); + return context_->getPeerCertificateChain(); } std::shared_ptr<CertificateVerificationError> TLSLayer::getPeerCertificateVerificationError() const { - return context->getPeerCertificateVerificationError(); + return context_->getPeerCertificateVerificationError(); } } diff --git a/Swiften/StreamStack/TLSLayer.h b/Swiften/StreamStack/TLSLayer.h index 415a3f0..89588e3 100644 --- a/Swiften/StreamStack/TLSLayer.h +++ b/Swiften/StreamStack/TLSLayer.h @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <boost/signals2.hpp> #include <Swiften/Base/API.h> @@ -17,34 +17,34 @@ #include <Swiften/TLS/TLSError.h> #include <Swiften/TLS/TLSOptions.h> namespace Swift { class TLSContext; class TLSContextFactory; class SWIFTEN_API TLSLayer : public StreamLayer { public: - TLSLayer(TLSContextFactory*, const TLSOptions&); + TLSLayer(std::unique_ptr<TLSContext> tlsContext); virtual ~TLSLayer(); void connect(); bool setClientCertificate(CertificateWithKey::ref cert); Certificate::ref getPeerCertificate() const; std::vector<Certificate::ref> getPeerCertificateChain() const; std::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const; void writeData(const SafeByteArray& data); void handleDataRead(const SafeByteArray& data); TLSContext* getContext() const { - return context; + return context_.get(); } public: boost::signals2::signal<void (std::shared_ptr<TLSError>)> onError; boost::signals2::signal<void ()> onConnected; private: - TLSContext* context; + std::unique_ptr<TLSContext> context_; }; } diff --git a/Swiften/StreamStack/UnitTest/StreamStackTest.cpp b/Swiften/StreamStack/UnitTest/StreamStackTest.cpp index f0f82c9..b074736 100644 --- a/Swiften/StreamStack/UnitTest/StreamStackTest.cpp +++ b/Swiften/StreamStack/UnitTest/StreamStackTest.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <memory> #include <vector> #include <boost/bind.hpp> @@ -33,100 +33,92 @@ class StreamStackTest : public CppUnit::TestFixture { CPPUNIT_TEST(testWriteData_TwoIntermediateStreamStack); CPPUNIT_TEST(testReadData_NoIntermediateStreamStack); CPPUNIT_TEST(testReadData_OneIntermediateStream); CPPUNIT_TEST(testReadData_TwoIntermediateStreamStack); CPPUNIT_TEST(testAddLayer_ExistingOnWriteDataSlot); CPPUNIT_TEST_SUITE_END(); public: void setUp() { - physicalStream_ = new TestLowLayer(); - xmppStream_ = new XMPPLayer(&parserFactories_, &serializers_, &xmlParserFactory_, ClientStreamType); + testling_ = std::make_unique<StreamStack>(std::make_unique<XMPPLayer>(&parserFactories_, &serializers_, &xmlParserFactory_, ClientStreamType), std::make_unique<TestLowLayer>()); + physicalStream_ = testling_->getLayer<TestLowLayer>(); + xmppStream_ = testling_->getLayer<XMPPLayer>(); elementsReceived_ = 0; dataWriteReceived_ = 0; } void tearDown() { - delete physicalStream_; - delete xmppStream_; } void testWriteData_NoIntermediateStreamStack() { - StreamStack testling(xmppStream_, physicalStream_); xmppStream_->writeData("foo"); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size()); CPPUNIT_ASSERT_EQUAL(createSafeByteArray("foo"), physicalStream_->data_[0]); } void testWriteData_OneIntermediateStream() { - StreamStack testling(xmppStream_, physicalStream_); - std::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X")); - testling.addLayer(xStream.get()); + std::unique_ptr<MyStreamLayer> xStream(new MyStreamLayer("X")); + testling_->addLayer(std::move(xStream)); xmppStream_->writeData("foo"); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size()); CPPUNIT_ASSERT_EQUAL(createSafeByteArray("Xfoo"), physicalStream_->data_[0]); } void testWriteData_TwoIntermediateStreamStack() { - StreamStack testling(xmppStream_, physicalStream_); - std::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X")); - std::shared_ptr<MyStreamLayer> yStream(new MyStreamLayer("Y")); - testling.addLayer(xStream.get()); - testling.addLayer(yStream.get()); + std::unique_ptr<MyStreamLayer> xStream(new MyStreamLayer("X")); + std::unique_ptr<MyStreamLayer> yStream(new MyStreamLayer("Y")); + testling_->addLayer(std::move(xStream)); + testling_->addLayer(std::move(yStream)); xmppStream_->writeData("foo"); CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), physicalStream_->data_.size()); CPPUNIT_ASSERT_EQUAL(createSafeByteArray("XYfoo"), physicalStream_->data_[0]); } void testReadData_NoIntermediateStreamStack() { - StreamStack testling(xmppStream_, physicalStream_); xmppStream_->onElement.connect(boost::bind(&StreamStackTest::handleElement, this, _1)); physicalStream_->onDataRead(createSafeByteArray("<stream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>")); CPPUNIT_ASSERT_EQUAL(1, elementsReceived_); } void testReadData_OneIntermediateStream() { - StreamStack testling(xmppStream_, physicalStream_); xmppStream_->onElement.connect(boost::bind(&StreamStackTest::handleElement, this, _1)); - std::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("<")); - testling.addLayer(xStream.get()); + std::unique_ptr<MyStreamLayer> xStream(new MyStreamLayer("<")); + testling_->addLayer(std::move(xStream)); physicalStream_->onDataRead(createSafeByteArray("stream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>")); CPPUNIT_ASSERT_EQUAL(1, elementsReceived_); } void testReadData_TwoIntermediateStreamStack() { - StreamStack testling(xmppStream_, physicalStream_); xmppStream_->onElement.connect(boost::bind(&StreamStackTest::handleElement, this, _1)); - std::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("s")); - std::shared_ptr<MyStreamLayer> yStream(new MyStreamLayer("<")); - testling.addLayer(xStream.get()); - testling.addLayer(yStream.get()); + std::unique_ptr<MyStreamLayer> xStream(new MyStreamLayer("s")); + std::unique_ptr<MyStreamLayer> yStream(new MyStreamLayer("<")); + testling_->addLayer(std::move(xStream)); + testling_->addLayer(std::move(yStream)); physicalStream_->onDataRead(createSafeByteArray("tream:stream xmlns:stream='http://etherx.jabber.org/streams'><presence/>")); CPPUNIT_ASSERT_EQUAL(1, elementsReceived_); } void testAddLayer_ExistingOnWriteDataSlot() { - StreamStack testling(xmppStream_, physicalStream_); xmppStream_->onWriteData.connect(boost::bind(&StreamStackTest::handleWriteData, this, _1)); - std::shared_ptr<MyStreamLayer> xStream(new MyStreamLayer("X")); - testling.addLayer(xStream.get()); + std::unique_ptr<MyStreamLayer> xStream(new MyStreamLayer("X")); + testling_->addLayer(std::move(xStream)); xmppStream_->writeData("foo"); CPPUNIT_ASSERT_EQUAL(1, dataWriteReceived_); } void handleElement(std::shared_ptr<ToplevelElement>) { ++elementsReceived_; } @@ -170,14 +162,15 @@ class StreamStackTest : public CppUnit::TestFixture { }; private: FullPayloadParserFactoryCollection parserFactories_; FullPayloadSerializerCollection serializers_; TestLowLayer* physicalStream_; PlatformXMLParserFactory xmlParserFactory_; XMPPLayer* xmppStream_; + std::unique_ptr<StreamStack> testling_; int elementsReceived_; int dataWriteReceived_; }; CPPUNIT_TEST_SUITE_REGISTRATION(StreamStackTest); diff --git a/Swiften/TLS/CertificateFactory.cpp b/Swiften/TLS/CertificateFactory.cpp index 487f7cd..303bcf7 100644 --- a/Swiften/TLS/CertificateFactory.cpp +++ b/Swiften/TLS/CertificateFactory.cpp @@ -1,14 +1,35 @@ /* - * Copyright (c) 2010 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/TLS/CertificateFactory.h> +#include <cassert> +#include <memory> +#include <sstream> +#include <string> + +#include <boost/algorithm/string/predicate.hpp> +#include <boost/optional.hpp> + +#include <Swiften/Base/Log.h> +#include <Swiften/StringCodecs/Base64.h> +#include <Swiften/TLS/PrivateKey.h> + namespace Swift { CertificateFactory::~CertificateFactory() { } +std::vector<Certificate::ref> CertificateFactory::createCertificateChain(const ByteArray& /* data */) { + assert(false); + return std::vector<Certificate::ref>(); +} + +PrivateKey::ref CertificateFactory::createPrivateKey(const SafeByteArray& data, boost::optional<SafeByteArray> password) { + return std::make_shared<PrivateKey>(data, password); +} + } diff --git a/Swiften/TLS/CertificateFactory.h b/Swiften/TLS/CertificateFactory.h index 522a6e6..cb7fb6e 100644 --- a/Swiften/TLS/CertificateFactory.h +++ b/Swiften/TLS/CertificateFactory.h @@ -1,19 +1,25 @@ /* - * Copyright (c) 2010-2015 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once +#include <boost/optional.hpp> + #include <Swiften/Base/API.h> +#include <Swiften/Base/SafeByteArray.h> #include <Swiften/TLS/Certificate.h> +#include <Swiften/TLS/PrivateKey.h> namespace Swift { class SWIFTEN_API CertificateFactory { public: virtual ~CertificateFactory(); virtual Certificate* createCertificateFromDER(const ByteArray& der) = 0; + virtual std::vector<Certificate::ref> createCertificateChain(const ByteArray& data); + PrivateKey::ref createPrivateKey(const SafeByteArray& data, boost::optional<SafeByteArray> password = boost::optional<SafeByteArray>()); }; } diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp index 17ac8cc..8d2d965 100644 --- a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp +++ b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp @@ -24,31 +24,31 @@ OpenSSLCertificate::OpenSSLCertificate(std::shared_ptr<X509> cert) : cert(cert) } OpenSSLCertificate::OpenSSLCertificate(const ByteArray& der) { #if OPENSSL_VERSION_NUMBER <= 0x009070cfL unsigned char* p = const_cast<unsigned char*>(vecptr(der)); #else const unsigned char* p = vecptr(der); #endif - cert = std::shared_ptr<X509>(d2i_X509(NULL, &p, der.size()), X509_free); + cert = std::shared_ptr<X509>(d2i_X509(nullptr, &p, der.size()), X509_free); if (!cert) { SWIFT_LOG(warning) << "Error creating certificate from DER data" << std::endl; } parse(); } ByteArray OpenSSLCertificate::toDER() const { ByteArray result; if (!cert) { return result; } - result.resize(i2d_X509(cert.get(), NULL)); + result.resize(i2d_X509(cert.get(), nullptr)); unsigned char* p = vecptr(result); i2d_X509(cert.get(), &p); return result; } void OpenSSLCertificate::parse() { if (!cert) { return; } diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp new file mode 100644 index 0000000..c94702c --- /dev/null +++ b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#include <Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h> + +#include <openssl/pem.h> + +namespace Swift { + +OpenSSLCertificateFactory::OpenSSLCertificateFactory() { +} + +OpenSSLCertificateFactory::~OpenSSLCertificateFactory() { +} + +Certificate* OpenSSLCertificateFactory::createCertificateFromDER(const ByteArray& der) { + return new OpenSSLCertificate(der); +} + +std::vector<Certificate::ref> OpenSSLCertificateFactory::createCertificateChain(const ByteArray& data) { + std::vector<Certificate::ref> certificateChain; + + if (data.size() > std::numeric_limits<int>::max()) { + return certificateChain; + } + + auto bio = std::shared_ptr<BIO>(BIO_new(BIO_s_mem()), BIO_free); + BIO_write(bio.get(), vecptr(data), int(data.size())); + + // Attempt parsing data as PEM + X509* openSSLCert = nullptr; + auto x509certFromPEM = PEM_read_bio_X509(bio.get(), &openSSLCert, nullptr, nullptr); + if (x509certFromPEM && openSSLCert) { + std::shared_ptr<X509> x509Cert(openSSLCert, X509_free); + certificateChain.push_back(std::make_shared<OpenSSLCertificate>(x509Cert)); + openSSLCert = nullptr; + while ((x509certFromPEM = PEM_read_bio_X509(bio.get(), &openSSLCert, nullptr, nullptr)) != nullptr) { + std::shared_ptr<X509> x509Cert(openSSLCert, X509_free); + certificateChain.push_back(std::make_shared<OpenSSLCertificate>(x509Cert)); + openSSLCert = nullptr; + } + } + + return certificateChain; +} + +} diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h index c996cd5..af45a33 100644 --- a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h +++ b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h @@ -1,19 +1,21 @@ /* - * Copyright (c) 2010-2014 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <Swiften/TLS/CertificateFactory.h> #include <Swiften/TLS/OpenSSL/OpenSSLCertificate.h> namespace Swift { class OpenSSLCertificateFactory : public CertificateFactory { public: - virtual Certificate* createCertificateFromDER(const ByteArray& der) { - return new OpenSSLCertificate(der); - } + OpenSSLCertificateFactory(); + virtual ~OpenSSLCertificateFactory() override final; + + virtual Certificate* createCertificateFromDER(const ByteArray& der) override final; + virtual std::vector<Certificate::ref> createCertificateChain(const ByteArray& data) override final; }; } diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp index 0805917..968ef8f 100644 --- a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp +++ b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp @@ -1,30 +1,37 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ + #include <Swiften/Base/Platform.h> #ifdef SWIFTEN_PLATFORM_WINDOWS #include <windows.h> #include <wincrypt.h> #endif +#include <cassert> +#include <memory> #include <vector> + + +#include <openssl/bio.h> #include <openssl/err.h> #include <openssl/pkcs12.h> -#include <memory> #if defined(SWIFTEN_PLATFORM_MACOSX) #include <Security/Security.h> #endif +#include <Swiften/Base/Log.h> +#include <Swiften/Base/Algorithm.h> #include <Swiften/TLS/OpenSSL/OpenSSLContext.h> #include <Swiften/TLS/OpenSSL/OpenSSLCertificate.h> #include <Swiften/TLS/CertificateWithKey.h> #include <Swiften/TLS/PKCS12Certificate.h> #pragma GCC diagnostic ignored "-Wold-style-cast" #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #pragma clang diagnostic ignored "-Wshorten-64-to-32" #pragma clang diagnostic ignored "-Wcast-align" @@ -33,56 +40,112 @@ namespace Swift { static const int MAX_FINISHED_SIZE = 4096; static const int SSL_READ_BUFFERSIZE = 8192; static void freeX509Stack(STACK_OF(X509)* stack) { sk_X509_free(stack); } -OpenSSLContext::OpenSSLContext() : state_(Start), context_(0), handle_(0), readBIO_(0), writeBIO_(0) { +namespace { + class OpenSSLInitializerFinalizer { + public: + OpenSSLInitializerFinalizer() { + SSL_load_error_strings(); + SSL_library_init(); + OpenSSL_add_all_algorithms(); + + // Disable compression + /* + STACK_OF(SSL_COMP)* compressionMethods = SSL_COMP_get_compression_methods(); + sk_SSL_COMP_zero(compressionMethods);*/ + } + + ~OpenSSLInitializerFinalizer() { + EVP_cleanup(); + } + + OpenSSLInitializerFinalizer(const OpenSSLInitializerFinalizer &) = delete; + }; + + std::unique_ptr<SSL_CTX> createSSL_CTX(OpenSSLContext::Mode mode) { + std::unique_ptr<SSL_CTX> sslCtx; + switch (mode) { + case OpenSSLContext::Mode::Client: + sslCtx = std::unique_ptr<SSL_CTX>(SSL_CTX_new(SSLv23_client_method())); + break; + case OpenSSLContext::Mode::Server: + sslCtx = std::unique_ptr<SSL_CTX>(SSL_CTX_new(SSLv23_server_method())); + break; + } + return sslCtx; + } + + std::string openSSLInternalErrorToString() { + auto bio = std::shared_ptr<BIO>(BIO_new(BIO_s_mem()), BIO_free); + ERR_print_errors(bio.get()); + std::string errorString; + errorString.resize(BIO_pending(bio.get())); + BIO_read(bio.get(), (void*)errorString.data(), errorString.size()); + return errorString; + } + } + +OpenSSLContext::OpenSSLContext(Mode mode) : mode_(mode), state_(State::Start) { ensureLibraryInitialized(); - context_ = SSL_CTX_new(SSLv23_client_method()); - SSL_CTX_set_options(context_, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); + context_ = createSSL_CTX(mode_); + SSL_CTX_set_options(context_.get(), SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); + + if (mode_ == Mode::Server) { +#if OPENSSL_VERSION_NUMBER < 0x1010 + // Automatically select highest preference curve used for ECDH temporary keys used during + // key exchange if possible. + // Since version 1.1.0, this option is always enabled. + SSL_CTX_set_ecdh_auto(context_.get(), 1); +#endif + + SSL_CTX_set_tlsext_servername_arg(context_.get(), this); + SSL_CTX_set_tlsext_servername_callback(context_.get(), OpenSSLContext::handleServerNameCallback); + } // TODO: implement CRL checking // TODO: download CRL (HTTP transport) // TODO: cache CRL downloads for configurable time period // TODO: implement OCSP support // TODO: handle OCSP stapling see https://www.rfc-editor.org/rfc/rfc4366.txt // Load system certs #if defined(SWIFTEN_PLATFORM_WINDOWS) - X509_STORE* store = SSL_CTX_get_cert_store(context_); + X509_STORE* store = SSL_CTX_get_cert_store(context_.get()); HCERTSTORE systemStore = CertOpenSystemStore(0, "ROOT"); if (systemStore) { PCCERT_CONTEXT certContext = NULL; while (true) { certContext = CertFindCertificateInStore(systemStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, certContext); if (!certContext) { break; } OpenSSLCertificate cert(createByteArray(certContext->pbCertEncoded, certContext->cbCertEncoded)); if (store && cert.getInternalX509()) { X509_STORE_add_cert(store, cert.getInternalX509().get()); } } } #elif !defined(SWIFTEN_PLATFORM_MACOSX) - SSL_CTX_set_default_verify_paths(context_); + SSL_CTX_set_default_verify_paths(context_.get()); #elif defined(SWIFTEN_PLATFORM_MACOSX) && !defined(SWIFTEN_PLATFORM_IPHONE) // On Mac OS X 10.5 (OpenSSL < 0.9.8), OpenSSL does not automatically look in the system store. // On Mac OS X 10.6 (OpenSSL >= 0.9.8), OpenSSL *does* look in the system store to determine trust. // However, if there is a certificate error, it will always emit the "Invalid CA" error if we didn't add // the certificates first. See // http://opensource.apple.com/source/OpenSSL098/OpenSSL098-27/src/crypto/x509/x509_vfy_apple.c // to understand why. We therefore add all certs from the system store ourselves. - X509_STORE* store = SSL_CTX_get_cert_store(context_); + X509_STORE* store = SSL_CTX_get_cert_store(context_.get()); CFArrayRef anchorCertificates; if (SecTrustCopyAnchorCertificates(&anchorCertificates) == 0) { for (int i = 0; i < CFArrayGetCount(anchorCertificates); ++i) { SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(const_cast<void*>(CFArrayGetValueAtIndex(anchorCertificates, i))); CSSM_DATA certCSSMData; if (SecCertificateGetData(cert, &certCSSMData) != 0 || certCSSMData.Length == 0) { continue; } std::vector<unsigned char> certData; @@ -93,198 +156,389 @@ OpenSSLContext::OpenSSLContext() : state_(Start), context_(0), handle_(0), readB X509_STORE_add_cert(store, certificate.getInternalX509().get()); } } CFRelease(anchorCertificates); } #endif } OpenSSLContext::~OpenSSLContext() { - SSL_free(handle_); - SSL_CTX_free(context_); } void OpenSSLContext::ensureLibraryInitialized() { - static bool isLibraryInitialized = false; - if (!isLibraryInitialized) { - SSL_load_error_strings(); - SSL_library_init(); - OpenSSL_add_all_algorithms(); + static OpenSSLInitializerFinalizer openSSLInit; +} - // Disable compression - /* - STACK_OF(SSL_COMP)* compressionMethods = SSL_COMP_get_compression_methods(); - sk_SSL_COMP_zero(compressionMethods);*/ +void OpenSSLContext::initAndSetBIOs() { + // Ownership of BIOs is transferred + readBIO_ = BIO_new(BIO_s_mem()); + writeBIO_ = BIO_new(BIO_s_mem()); + SSL_set_bio(handle_.get(), readBIO_, writeBIO_); +} - isLibraryInitialized = true; +void OpenSSLContext::accept() { + assert(mode_ == Mode::Server); + handle_ = std::unique_ptr<SSL>(SSL_new(context_.get())); + if (!handle_) { + state_ = State::Error; + onError(std::make_shared<TLSError>(TLSError::AcceptFailed, openSSLInternalErrorToString())); + return; } + + initAndSetBIOs(); + + state_ = State::Accepting; + doAccept(); } void OpenSSLContext::connect() { - handle_ = SSL_new(context_); - if (handle_ == nullptr) { - state_ = Error; - onError(std::make_shared<TLSError>()); + connect(std::string()); +} + +void OpenSSLContext::connect(const std::string& requestedServerName) { + assert(mode_ == Mode::Client); + handle_ = std::unique_ptr<SSL>(SSL_new(context_.get())); + if (!handle_) { + state_ = State::Error; + onError(std::make_shared<TLSError>(TLSError::ConnectFailed, openSSLInternalErrorToString())); return; } - // Ownership of BIOs is ransferred - readBIO_ = BIO_new(BIO_s_mem()); - writeBIO_ = BIO_new(BIO_s_mem()); - SSL_set_bio(handle_, readBIO_, writeBIO_); + if (!requestedServerName.empty()) { + if (SSL_set_tlsext_host_name(handle_.get(), const_cast<char*>(requestedServerName.c_str())) != 1) { + onError(std::make_shared<TLSError>(TLSError::ConnectFailed, "Failed to set Server Name Indication: " + openSSLInternalErrorToString()));\ + return; + } + } - state_ = Connecting; + // Ownership of BIOs is transferred to the SSL_CTX instance in handle_. + initAndSetBIOs(); + + state_ = State::Connecting; doConnect(); } +void OpenSSLContext::doAccept() { + auto acceptResult = SSL_accept(handle_.get()); + auto error = SSL_get_error(handle_.get(), acceptResult); + switch (error) { + case SSL_ERROR_NONE: { + state_ = State::Connected; + //std::cout << x->name << std::endl; + //const char* comp = SSL_get_current_compression(handle_.get()); + //std::cout << "Compression: " << SSL_COMP_get_name(comp) << std::endl; + onConnected(); + // The following call is important so the client knowns the handshake is finished. + sendPendingDataToNetwork(); + break; + } + case SSL_ERROR_WANT_READ: + sendPendingDataToNetwork(); + break; + case SSL_ERROR_WANT_WRITE: + sendPendingDataToNetwork(); + break; + default: + state_ = State::Error; + onError(std::make_shared<TLSError>(TLSError::AcceptFailed, openSSLInternalErrorToString())); + sendPendingDataToNetwork(); + } +} + void OpenSSLContext::doConnect() { - int connectResult = SSL_connect(handle_); - int error = SSL_get_error(handle_, connectResult); + int connectResult = SSL_connect(handle_.get()); + int error = SSL_get_error(handle_.get(), connectResult); switch (error) { case SSL_ERROR_NONE: { - state_ = Connected; + state_ = State::Connected; //std::cout << x->name << std::endl; - //const char* comp = SSL_get_current_compression(handle_); + //const char* comp = SSL_get_current_compression(handle_.get()); //std::cout << "Compression: " << SSL_COMP_get_name(comp) << std::endl; onConnected(); break; } case SSL_ERROR_WANT_READ: sendPendingDataToNetwork(); break; default: - state_ = Error; + state_ = State::Error; onError(std::make_shared<TLSError>()); + onError(std::make_shared<TLSError>(TLSError::ConnectFailed, openSSLInternalErrorToString())); } } +int OpenSSLContext::handleServerNameCallback(SSL* ssl, int*, void* arg) { + if (ssl == nullptr) + return SSL_TLSEXT_ERR_NOACK; + + const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); + if (servername) { + auto serverNameString = std::string(servername); + auto context = reinterpret_cast<OpenSSLContext*>(arg); + context->onServerNameRequested(serverNameString); + + if (context->abortTLSHandshake_) { + context->abortTLSHandshake_ = false; + return SSL_TLSEXT_ERR_ALERT_FATAL; + } + } + return SSL_TLSEXT_ERR_OK; +} + void OpenSSLContext::sendPendingDataToNetwork() { int size = BIO_pending(writeBIO_); if (size > 0) { SafeByteArray data; data.resize(size); BIO_read(writeBIO_, vecptr(data), size); onDataForNetwork(data); } } void OpenSSLContext::handleDataFromNetwork(const SafeByteArray& data) { BIO_write(readBIO_, vecptr(data), data.size()); switch (state_) { - case Connecting: + case State::Accepting: + doAccept(); + break; + case State::Connecting: doConnect(); break; - case Connected: + case State::Connected: sendPendingDataToApplication(); break; - case Start: assert(false); break; - case Error: /*assert(false);*/ break; + case State::Start: assert(false); break; + case State::Error: /*assert(false);*/ break; } } void OpenSSLContext::handleDataFromApplication(const SafeByteArray& data) { - if (SSL_write(handle_, vecptr(data), data.size()) >= 0) { - sendPendingDataToNetwork(); + auto ret = SSL_write(handle_.get(), vecptr(data), data.size()); + if (ret > 0 || SSL_get_error(handle_.get(), ret) == SSL_ERROR_WANT_READ) { + sendPendingDataToNetwork(); } else { - state_ = Error; - onError(std::make_shared<TLSError>()); + state_ = State::Error; + onError(std::make_shared<TLSError>(TLSError::UnknownError, openSSLInternalErrorToString())); } } void OpenSSLContext::sendPendingDataToApplication() { SafeByteArray data; data.resize(SSL_READ_BUFFERSIZE); - int ret = SSL_read(handle_, vecptr(data), data.size()); + int ret = SSL_read(handle_.get(), vecptr(data), data.size()); while (ret > 0) { data.resize(ret); onDataForApplication(data); data.resize(SSL_READ_BUFFERSIZE); - ret = SSL_read(handle_, vecptr(data), data.size()); + ret = SSL_read(handle_.get(), vecptr(data), data.size()); + } + if (ret < 0 && SSL_get_error(handle_.get(), ret) != SSL_ERROR_WANT_READ) { + state_ = State::Error; + onError(std::make_shared<TLSError>(TLSError::UnknownError, openSSLInternalErrorToString())); + } +} + +bool OpenSSLContext::setCertificateChain(const std::vector<Certificate::ref>& certificateChain) { + if (certificateChain.size() == 0) { + SWIFT_LOG(warning) << "Trying to load empty certificate chain." << std::endl; + return false; + } + + // load endpoint certificate + auto openSSLCert = std::dynamic_pointer_cast<OpenSSLCertificate>(certificateChain[0]); + if (!openSSLCert) { + return false; + } + + if (SSL_CTX_use_certificate(context_.get(), openSSLCert->getInternalX509().get()) != 1) { + return false; + } + + if (certificateChain.size() > 1) { + for (auto certificate : range(certificateChain.begin() + 1, certificateChain.end())) { + auto openSSLCert = std::dynamic_pointer_cast<OpenSSLCertificate>(certificate); + if (!openSSLCert) { + return false; + } + if (SSL_CTX_add_extra_chain_cert(context_.get(), openSSLCert->getInternalX509().get()) != 1) { + SWIFT_LOG(warning) << "Trying to load empty certificate chain." << std::endl; + return false; + } + } + } + + if (handle_) { + // This workaround is needed as OpenSSL has a shortcut to not do anything + // if you set the SSL_CTX to the existing SSL_CTX and not reloading the + // certificates from the SSL_CTX. + auto dummyContext = createSSL_CTX(mode_); + SSL_set_SSL_CTX(handle_.get(), dummyContext.get()); + SSL_set_SSL_CTX(handle_.get(), context_.get()); + } + + return true; +} + +int empty_or_preset_password_cb(char* buf, int max_len, int flag, void* password); + +int empty_or_preset_password_cb(char* buf, int max_len, int /* flag */, void* password) { + char* charPassword = (char*)password; + if (charPassword == nullptr) { + return 0; + } + int len = strlen(charPassword); + if(len > max_len) { + return 0; } - if (ret < 0 && SSL_get_error(handle_, ret) != SSL_ERROR_WANT_READ) { - state_ = Error; - onError(std::make_shared<TLSError>()); + memcpy(buf, charPassword, len); + return len; +} + +bool OpenSSLContext::setPrivateKey(const PrivateKey::ref& privateKey) { + if (privateKey->getData().size() > std::numeric_limits<int>::max()) { + return false; + } + + auto bio = std::shared_ptr<BIO>(BIO_new(BIO_s_mem()), BIO_free); + BIO_write(bio.get(), vecptr(privateKey->getData()), int(privateKey->getData().size())); + + SafeByteArray safePassword; + void* password = nullptr; + if (privateKey->getPassword()) { + safePassword = privateKey->getPassword().get(); + safePassword.push_back(0); + password = safePassword.data(); + } + auto resultKey = PEM_read_bio_PrivateKey(bio.get(), nullptr, empty_or_preset_password_cb, password); + if (resultKey) { + if (handle_) { + auto result = SSL_use_PrivateKey(handle_.get(), resultKey);; + if (result != 1) { + return false; + } + } + else { + auto result = SSL_CTX_use_PrivateKey(context_.get(), resultKey); + if (result != 1) { + return false; + } + } + } + else { + return false; } + return true; +} + +void OpenSSLContext::setAbortTLSHandshake(bool abort) { + abortTLSHandshake_ = abort; } bool OpenSSLContext::setClientCertificate(CertificateWithKey::ref certificate) { std::shared_ptr<PKCS12Certificate> pkcs12Certificate = std::dynamic_pointer_cast<PKCS12Certificate>(certificate); if (!pkcs12Certificate || pkcs12Certificate->isNull()) { return false; } // Create a PKCS12 structure BIO* bio = BIO_new(BIO_s_mem()); BIO_write(bio, vecptr(pkcs12Certificate->getData()), pkcs12Certificate->getData().size()); - std::shared_ptr<PKCS12> pkcs12(d2i_PKCS12_bio(bio, NULL), PKCS12_free); + std::shared_ptr<PKCS12> pkcs12(d2i_PKCS12_bio(bio, nullptr), PKCS12_free); BIO_free(bio); if (!pkcs12) { return false; } // Parse PKCS12 - X509 *certPtr = 0; - EVP_PKEY* privateKeyPtr = 0; - STACK_OF(X509)* caCertsPtr = 0; + X509 *certPtr = nullptr; + EVP_PKEY* privateKeyPtr = nullptr; + STACK_OF(X509)* caCertsPtr = nullptr; SafeByteArray password(pkcs12Certificate->getPassword()); password.push_back(0); int result = PKCS12_parse(pkcs12.get(), reinterpret_cast<const char*>(vecptr(password)), &privateKeyPtr, &certPtr, &caCertsPtr); if (result != 1) { return false; } std::shared_ptr<X509> cert(certPtr, X509_free); std::shared_ptr<EVP_PKEY> privateKey(privateKeyPtr, EVP_PKEY_free); std::shared_ptr<STACK_OF(X509)> caCerts(caCertsPtr, freeX509Stack); // Use the key & certificates - if (SSL_CTX_use_certificate(context_, cert.get()) != 1) { + if (SSL_CTX_use_certificate(context_.get(), cert.get()) != 1) { return false; } - if (SSL_CTX_use_PrivateKey(context_, privateKey.get()) != 1) { + if (SSL_CTX_use_PrivateKey(context_.get(), privateKey.get()) != 1) { return false; } for (int i = 0; i < sk_X509_num(caCerts.get()); ++i) { - SSL_CTX_add_extra_chain_cert(context_, sk_X509_value(caCerts.get(), i)); + SSL_CTX_add_extra_chain_cert(context_.get(), sk_X509_value(caCerts.get(), i)); } return true; } +bool OpenSSLContext::setDiffieHellmanParameters(const ByteArray& parametersInOpenSslDer) { + auto bio = std::unique_ptr<BIO, decltype(&BIO_free)>(BIO_new(BIO_s_mem()), BIO_free); + if (bio) { + BIO_write(bio.get(), vecptr(parametersInOpenSslDer), parametersInOpenSslDer.size()); + auto result = 0L; + if (auto dhparams = d2i_DHparams_bio(bio.get(), NULL)) { + if (handle_) { + result = SSL_set_tmp_dh(handle_.get(), dhparams); + } + else { + result = SSL_CTX_set_tmp_dh(context_.get(), dhparams); + } + DH_free(dhparams); + } + return result == 1; + } + return false; +} + std::vector<Certificate::ref> OpenSSLContext::getPeerCertificateChain() const { std::vector<Certificate::ref> result; - STACK_OF(X509)* chain = SSL_get_peer_cert_chain(handle_); + STACK_OF(X509)* chain = SSL_get_peer_cert_chain(handle_.get()); for (int i = 0; i < sk_X509_num(chain); ++i) { std::shared_ptr<X509> x509Cert(X509_dup(sk_X509_value(chain, i)), X509_free); Certificate::ref cert = std::make_shared<OpenSSLCertificate>(x509Cert); result.push_back(cert); } return result; } std::shared_ptr<CertificateVerificationError> OpenSSLContext::getPeerCertificateVerificationError() const { - int verifyResult = SSL_get_verify_result(handle_); + int verifyResult = SSL_get_verify_result(handle_.get()); if (verifyResult != X509_V_OK) { return std::make_shared<CertificateVerificationError>(getVerificationErrorTypeForResult(verifyResult)); } else { return std::shared_ptr<CertificateVerificationError>(); } } ByteArray OpenSSLContext::getFinishMessage() const { ByteArray data; data.resize(MAX_FINISHED_SIZE); - size_t size = SSL_get_finished(handle_, vecptr(data), data.size()); + auto size = SSL_get_finished(handle_.get(), vecptr(data), data.size()); data.resize(size); return data; } +ByteArray OpenSSLContext::getPeerFinishMessage() const { + ByteArray data; + data.resize(MAX_FINISHED_SIZE); + auto size = SSL_get_peer_finished(handle_.get(), vecptr(data), data.size()); + data.resize(size); + return data; + } + CertificateVerificationError::Type OpenSSLContext::getVerificationErrorTypeForResult(int result) { assert(result != 0); switch (result) { case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: return CertificateVerificationError::NotYetValid; case X509_V_ERR_CERT_HAS_EXPIRED: case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.h b/Swiften/TLS/OpenSSL/OpenSSLContext.h index e75b3c9..cfa852a 100644 --- a/Swiften/TLS/OpenSSL/OpenSSLContext.h +++ b/Swiften/TLS/OpenSSL/OpenSSLContext.h @@ -1,54 +1,85 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once +#include <memory> + #include <boost/noncopyable.hpp> #include <boost/signals2.hpp> #include <openssl/ssl.h> #include <Swiften/Base/ByteArray.h> #include <Swiften/TLS/CertificateWithKey.h> #include <Swiften/TLS/TLSContext.h> -namespace Swift { +namespace std { + template<> + class default_delete<SSL_CTX> { + public: + void operator()(SSL_CTX *ptr) { + SSL_CTX_free(ptr); + } + }; + template<> + class default_delete<SSL> { + public: + void operator()(SSL *ptr) { + SSL_free(ptr); + } + }; +} + +namespace Swift { class OpenSSLContext : public TLSContext, boost::noncopyable { public: - OpenSSLContext(); - virtual ~OpenSSLContext(); + OpenSSLContext(Mode mode); + virtual ~OpenSSLContext() override final; - void connect(); - bool setClientCertificate(CertificateWithKey::ref cert); + void accept() override final; + void connect() override final; + void connect(const std::string& requestHostname) override final; - void handleDataFromNetwork(const SafeByteArray&); - void handleDataFromApplication(const SafeByteArray&); + bool setCertificateChain(const std::vector<Certificate::ref>& certificateChain) override final; + bool setPrivateKey(const PrivateKey::ref& privateKey) override final; + bool setClientCertificate(CertificateWithKey::ref cert) override final; + void setAbortTLSHandshake(bool abort) override final; + bool setDiffieHellmanParameters(const ByteArray& parametersInOpenSslDer) override final; - std::vector<Certificate::ref> getPeerCertificateChain() const; - std::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const; + void handleDataFromNetwork(const SafeByteArray&) override final; + void handleDataFromApplication(const SafeByteArray&) override final; - virtual ByteArray getFinishMessage() const; + std::vector<Certificate::ref> getPeerCertificateChain() const override final; + std::shared_ptr<CertificateVerificationError> getPeerCertificateVerificationError() const override final; + + virtual ByteArray getFinishMessage() const override final; + virtual ByteArray getPeerFinishMessage() const override final; private: static void ensureLibraryInitialized(); - + static int handleServerNameCallback(SSL *ssl, int *ad, void *arg); static CertificateVerificationError::Type getVerificationErrorTypeForResult(int); + void initAndSetBIOs(); + void doAccept(); void doConnect(); void sendPendingDataToNetwork(); void sendPendingDataToApplication(); private: - enum State { Start, Connecting, Connected, Error }; + enum class State { Start, Accepting, Connecting, Connected, Error }; + const Mode mode_; State state_; - SSL_CTX* context_; - SSL* handle_; - BIO* readBIO_; - BIO* writeBIO_; + std::unique_ptr<SSL_CTX> context_; + std::unique_ptr<SSL> handle_; + BIO* readBIO_ = nullptr; + BIO* writeBIO_ = nullptr; + bool abortTLSHandshake_ = false; }; } diff --git a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp index 9f7b2aa..a9ba5ab 100644 --- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp +++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp @@ -1,28 +1,54 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/TLS/OpenSSL/OpenSSLContextFactory.h> +#include <openssl/bio.h> +#include <openssl/dh.h> +#include <openssl/pem.h> + #include <Swiften/Base/Log.h> #include <Swiften/TLS/OpenSSL/OpenSSLContext.h> +#pragma clang diagnostic ignored "-Wshorten-64-to-32" + namespace Swift { bool OpenSSLContextFactory::canCreate() const { return true; } -TLSContext* OpenSSLContextFactory::createTLSContext(const TLSOptions&) { - return new OpenSSLContext(); +std::unique_ptr<TLSContext> OpenSSLContextFactory::createTLSContext(const TLSOptions&, TLSContext::Mode mode) { + return std::unique_ptr<TLSContext>(new OpenSSLContext(mode)); +} + +ByteArray OpenSSLContextFactory::convertDHParametersFromPEMToDER(const std::string& dhParametersInPEM) { + ByteArray dhParametersInDER; + + auto bio = std::unique_ptr<BIO, decltype(&BIO_free)>(BIO_new(BIO_s_mem()), BIO_free); + if (bio) { + BIO_write(bio.get(), dhParametersInPEM.data(), dhParametersInPEM.size()); + if (auto params = PEM_read_bio_DHparams(bio.get(), nullptr, nullptr, nullptr)) { + unsigned char* buffer = nullptr; + auto len = i2d_DHparams(params, &buffer); + if (len > 0) { + dhParametersInDER = createByteArray(buffer, static_cast<size_t>(len)); + free(buffer); + } + DH_free(params); + + } + } + return dhParametersInDER; } void OpenSSLContextFactory::setCheckCertificateRevocation(bool check) { if (check) { SWIFT_LOG(warning) << "CRL Checking not supported for OpenSSL" << std::endl; assert(false); } } diff --git a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h index e121a1a..95a2b0c 100644 --- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h +++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h @@ -1,23 +1,25 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once -#include <cassert> +#include <memory> #include <Swiften/TLS/TLSContextFactory.h> namespace Swift { class OpenSSLContextFactory : public TLSContextFactory { public: - bool canCreate() const; - virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions); + bool canCreate() const override final; + virtual std::unique_ptr<TLSContext> createTLSContext(const TLSOptions& tlsOptions, TLSContext::Mode mode) override final; + + virtual ByteArray convertDHParametersFromPEMToDER(const std::string& dhParametersInPEM) override final; // Not supported - virtual void setCheckCertificateRevocation(bool b); - virtual void setDisconnectOnCardRemoval(bool b); + virtual void setCheckCertificateRevocation(bool b) override final; + virtual void setDisconnectOnCardRemoval(bool b) override final; }; } diff --git a/Swiften/TLS/PrivateKey.cpp b/Swiften/TLS/PrivateKey.cpp new file mode 100644 index 0000000..31cac1d --- /dev/null +++ b/Swiften/TLS/PrivateKey.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#include <Swiften/TLS/PrivateKey.h> + +namespace Swift { + +PrivateKey::PrivateKey(const SafeByteArray& data, boost::optional<SafeByteArray> password) : data_(data), password_(password) { +} + +const SafeByteArray& PrivateKey::getData() const { + return data_; +} + +const boost::optional<SafeByteArray>& PrivateKey::getPassword() const { + return password_; +} + +} diff --git a/Swiften/TLS/PrivateKey.h b/Swiften/TLS/PrivateKey.h new file mode 100644 index 0000000..332fc48 --- /dev/null +++ b/Swiften/TLS/PrivateKey.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#pragma once + +#include <memory> + +#include <boost/optional.hpp> + +#include <Swiften/Base/SafeByteArray.h> +#include <Swiften/TLS/PrivateKey.h> + +namespace Swift { + +class PrivateKey { +public: + using ref = std::shared_ptr<PrivateKey>; + +public: + PrivateKey(const SafeByteArray& data, boost::optional<SafeByteArray> password = boost::optional<SafeByteArray>()); + + const SafeByteArray& getData() const; + const boost::optional<SafeByteArray>& getPassword() const; + +private: + SafeByteArray data_; + boost::optional<SafeByteArray> password_; +}; + +} diff --git a/Swiften/TLS/SConscript b/Swiften/TLS/SConscript index 68bf50b..a79e6a1 100644 --- a/Swiften/TLS/SConscript +++ b/Swiften/TLS/SConscript @@ -1,29 +1,33 @@ Import("swiften_env") objects = swiften_env.SwiftenObject([ "Certificate.cpp", "CertificateFactory.cpp", "CertificateTrustChecker.cpp", + "PrivateKey.cpp", "ServerIdentityVerifier.cpp", "TLSContext.cpp", "TLSContextFactory.cpp", ]) myenv = swiften_env.Clone() if myenv.get("HAVE_OPENSSL", 0) : myenv.MergeFlags(myenv["OPENSSL_FLAGS"]) objects += myenv.SwiftenObject([ "OpenSSL/OpenSSLContext.cpp", "OpenSSL/OpenSSLCertificate.cpp", "OpenSSL/OpenSSLContextFactory.cpp", + "OpenSSL/OpenSSLCertificateFactory.cpp", ]) myenv.Append(CPPDEFINES = "HAVE_OPENSSL") + if myenv["PLATFORM"] == "win32" : + myenv.Append(CPPDEFINES = "NOMINMAX") elif myenv.get("HAVE_SCHANNEL", 0) : swiften_env.Append(LIBS = ["Winscard"]) objects += myenv.SwiftenObject([ "CAPICertificate.cpp", "Schannel/SchannelContext.cpp", "Schannel/SchannelCertificate.cpp", "Schannel/SchannelContextFactory.cpp", ]) myenv.Append(CPPDEFINES = "HAVE_SCHANNEL") diff --git a/Swiften/TLS/Schannel/SchannelContextFactory.cpp b/Swiften/TLS/Schannel/SchannelContextFactory.cpp index f78d386..d029730 100644 --- a/Swiften/TLS/Schannel/SchannelContextFactory.cpp +++ b/Swiften/TLS/Schannel/SchannelContextFactory.cpp @@ -1,39 +1,41 @@ /* * Copyright (c) 2011 Soren Dreijer * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/TLS/Schannel/SchannelContextFactory.h> #include <Swiften/TLS/Schannel/SchannelContext.h> namespace Swift { SchannelContextFactory::SchannelContextFactory() : checkCertificateRevocation(true), disconnectOnCardRemoval(true) { } bool SchannelContextFactory::canCreate() const { return true; } -TLSContext* SchannelContextFactory::createTLSContext(const TLSOptions& tlsOptions) { +std::unique_ptr<TLSContext> SchannelContextFactory::createTLSContext(const TLSOptions& tlsOptions, TLSContext::Mode mode) { + // TLS server mode is not supported for the SecureTransport backend yet. + assert(mode == TLSContext::Mode::Client); SchannelContext* context = new SchannelContext(tlsOptions.schannelTLS1_0Workaround); context->setCheckCertificateRevocation(checkCertificateRevocation); context->setDisconnectOnCardRemoval(disconnectOnCardRemoval); - return context; + return std::unique_ptr<TLSContext>(context); } void SchannelContextFactory::setCheckCertificateRevocation(bool b) { checkCertificateRevocation = b; } void SchannelContextFactory::setDisconnectOnCardRemoval(bool b) { disconnectOnCardRemoval = b; } diff --git a/Swiften/TLS/Schannel/SchannelContextFactory.h b/Swiften/TLS/Schannel/SchannelContextFactory.h index 142f193..76ff365 100644 --- a/Swiften/TLS/Schannel/SchannelContextFactory.h +++ b/Swiften/TLS/Schannel/SchannelContextFactory.h @@ -1,33 +1,34 @@ /* * Copyright (c) 2011 Soren Dreijer * Licensed under the simplified BSD license. * See Documentation/Licenses/BSD-simplified.txt for more information. */ /* - * Copyright (c) 2015 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once +#include <memory> + #include <Swiften/TLS/TLSContextFactory.h> namespace Swift { class SchannelContextFactory : public TLSContextFactory { public: SchannelContextFactory(); bool canCreate() const; - virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions); - + virtual std::unique_ptr<TLSContext> createTLSContext(const TLSOptions& tlsOptions, TLSContext::Mode mode = TLSContext::Mode::Client); virtual void setCheckCertificateRevocation(bool b); virtual void setDisconnectOnCardRemoval(bool b); public: bool checkCertificateRevocation; bool disconnectOnCardRemoval; }; } diff --git a/Swiften/TLS/SecureTransport/SecureTransportCertificate.mm b/Swiften/TLS/SecureTransport/SecureTransportCertificate.mm index db0af89..fffb3ed 100644 --- a/Swiften/TLS/SecureTransport/SecureTransportCertificate.mm +++ b/Swiften/TLS/SecureTransport/SecureTransportCertificate.mm @@ -1,11 +1,11 @@ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2017 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/TLS/SecureTransport/SecureTransportCertificate.h> #include <boost/numeric/conversion/cast.hpp> #include <Cocoa/Cocoa.h> @@ -87,25 +87,26 @@ void SecureTransportCertificate::parse() { if (commonName) { CFRelease(commonName); } // Handle Subject Alternative Names NSDictionary* certDict = bridge_cast<NSDictionary*>(valueDict); NSDictionary* subjectAltNamesDict = certDict[@"2.5.29.17"][@"value"]; for (NSDictionary* entry in subjectAltNamesDict) { - if ([entry[@"label"] isEqualToString:static_cast<NSString * _Nonnull>([NSString stringWithUTF8String:ID_ON_XMPPADDR_OID])]) { + NSString* label = entry[@"label"]; + if ([label isEqualToString:static_cast<NSString * _Nonnull>([NSString stringWithUTF8String:ID_ON_XMPPADDR_OID])]) { xmppAddresses_.push_back(ns2StdString(entry[@"value"])); } - else if ([entry[@"label"] isEqualToString:static_cast<NSString * _Nonnull>([NSString stringWithUTF8String:ID_ON_DNSSRV_OID])]) { + else if ([label isEqualToString:static_cast<NSString * _Nonnull>([NSString stringWithUTF8String:ID_ON_DNSSRV_OID])]) { srvNames_.push_back(ns2StdString(entry[@"value"])); } - else if ([entry[@"label"] isEqualToString:@"DNS Name"]) { + else if ([label isEqualToString:@"DNS Name"]) { dnsNames_.push_back(ns2StdString(entry[@"value"])); } } CFRelease(valueDict); } if (error) { CFRelease(error); } diff --git a/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp b/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp index 1fac1fb..cc10987 100644 --- a/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp +++ b/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp @@ -1,11 +1,11 @@ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/TLS/SecureTransport/SecureTransportContextFactory.h> #include <Swiften/Base/Log.h> #include <Swiften/TLS/SecureTransport/SecureTransportContext.h> @@ -20,20 +20,22 @@ SecureTransportContextFactory::SecureTransportContextFactory() : checkCertificat SecureTransportContextFactory::~SecureTransportContextFactory() { } bool SecureTransportContextFactory::canCreate() const { return true; } -TLSContext* SecureTransportContextFactory::createTLSContext(const TLSOptions& /* tlsOptions */) { - return new SecureTransportContext(checkCertificateRevocation_); +std::unique_ptr<TLSContext> SecureTransportContextFactory::createTLSContext(const TLSOptions& /* tlsOptions */, TLSContext::Mode mode) { + // TLS server mode is not supported for the SecureTransport backend yet. + assert(mode == TLSContext::Mode::Client); + return std::unique_ptr<TLSContext>(new SecureTransportContext(checkCertificateRevocation_)); } void SecureTransportContextFactory::setCheckCertificateRevocation(bool b) { checkCertificateRevocation_ = b; } void SecureTransportContextFactory::setDisconnectOnCardRemoval(bool b) { disconnectOnCardRemoval_ = b; if (disconnectOnCardRemoval_) { diff --git a/Swiften/TLS/SecureTransport/SecureTransportContextFactory.h b/Swiften/TLS/SecureTransport/SecureTransportContextFactory.h index 74c598f..b86639a 100644 --- a/Swiften/TLS/SecureTransport/SecureTransportContextFactory.h +++ b/Swiften/TLS/SecureTransport/SecureTransportContextFactory.h @@ -1,29 +1,31 @@ /* - * Copyright (c) 2015 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once +#include <memory> + #include <Swiften/TLS/TLSContextFactory.h> namespace Swift { class SecureTransportContextFactory : public TLSContextFactory { public: SecureTransportContextFactory(); virtual ~SecureTransportContextFactory(); virtual bool canCreate() const; - virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions); + virtual std::unique_ptr<TLSContext> createTLSContext(const TLSOptions& tlsOptions, TLSContext::Mode mode = TLSContext::Mode::Client); virtual void setCheckCertificateRevocation(bool b); virtual void setDisconnectOnCardRemoval(bool b); private: bool checkCertificateRevocation_; bool disconnectOnCardRemoval_; }; } diff --git a/Swiften/TLS/TLSContext.cpp b/Swiften/TLS/TLSContext.cpp index 2763547..cc05834 100644 --- a/Swiften/TLS/TLSContext.cpp +++ b/Swiften/TLS/TLSContext.cpp @@ -1,19 +1,53 @@ /* - * Copyright (c) 2010 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/TLS/TLSContext.h> +#include <cassert> + namespace Swift { TLSContext::~TLSContext() { } +void TLSContext::accept() { + assert(false); +} + +void TLSContext::connect(const std::string& /* serverName */) { + assert(false); +} + +bool TLSContext::setCertificateChain(const std::vector<Certificate::ref>& /* certificateChain */) { + assert(false); + return false; +} + +bool TLSContext::setPrivateKey(const PrivateKey::ref& /* privateKey */) { + assert(false); + return false; +} + +bool TLSContext::setDiffieHellmanParameters(const ByteArray& /*parametersInOpenSslDer*/) { + assert(false); + return false; +} + +void TLSContext::setAbortTLSHandshake(bool /* abort */) { + assert(false); +} + Certificate::ref TLSContext::getPeerCertificate() const { std::vector<Certificate::ref> chain = getPeerCertificateChain(); return chain.empty() ? Certificate::ref() : chain[0]; } +ByteArray TLSContext::getPeerFinishMessage() const { + assert(false); + return ByteArray(); +} + } diff --git a/Swiften/TLS/TLSContext.h b/Swiften/TLS/TLSContext.h index 79e3485..9b0a2eb 100644 --- a/Swiften/TLS/TLSContext.h +++ b/Swiften/TLS/TLSContext.h @@ -1,45 +1,66 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> #include <boost/signals2.hpp> #include <Swiften/Base/API.h> #include <Swiften/Base/SafeByteArray.h> #include <Swiften/TLS/Certificate.h> #include <Swiften/TLS/CertificateVerificationError.h> #include <Swiften/TLS/CertificateWithKey.h> +#include <Swiften/TLS/PrivateKey.h> #include <Swiften/TLS/TLSError.h> namespace Swift { class SWIFTEN_API TLSContext { public: virtual ~TLSContext(); + virtual void accept(); virtual void connect() = 0; + virtual void connect(const std::string& serverName); + + virtual bool setCertificateChain(const std::vector<Certificate::ref>& /* certificateChain */); + virtual bool setPrivateKey(const PrivateKey::ref& /* privateKey */); virtual bool setClientCertificate(CertificateWithKey::ref cert) = 0; + virtual bool setDiffieHellmanParameters(const ByteArray& parametersInOpenSslDer); + + /** + * This method can be used during the \ref onServerNameRequested signal, + * to report an error about an unknown host back to the requesting client. + */ + virtual void setAbortTLSHandshake(bool /* abort */); virtual void handleDataFromNetwork(const SafeByteArray&) = 0; virtual void handleDataFromApplication(const SafeByteArray&) = 0; Certificate::ref getPeerCertificate() const; virtual std::vector<Certificate::ref> getPeerCertificateChain() const = 0; virtual CertificateVerificationError::ref getPeerCertificateVerificationError() const = 0; virtual ByteArray getFinishMessage() const = 0; + virtual ByteArray getPeerFinishMessage() const; + + public: + enum class Mode { + Client, + Server + }; public: boost::signals2::signal<void (const SafeByteArray&)> onDataForNetwork; boost::signals2::signal<void (const SafeByteArray&)> onDataForApplication; boost::signals2::signal<void (std::shared_ptr<TLSError>)> onError; boost::signals2::signal<void ()> onConnected; + boost::signals2::signal<void (const std::string&)> onServerNameRequested; }; } diff --git a/Swiften/TLS/TLSContextFactory.cpp b/Swiften/TLS/TLSContextFactory.cpp index d196e15..91e60d6 100644 --- a/Swiften/TLS/TLSContextFactory.cpp +++ b/Swiften/TLS/TLSContextFactory.cpp @@ -1,14 +1,21 @@ /* * Copyright (c) 2010 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Swiften/TLS/TLSContextFactory.h> +#include <cassert> + namespace Swift { TLSContextFactory::~TLSContextFactory() { } +ByteArray TLSContextFactory::convertDHParametersFromPEMToDER(const std::string& /* pem */) { + assert(false); + return ByteArray(); +} + } diff --git a/Swiften/TLS/TLSContextFactory.h b/Swiften/TLS/TLSContextFactory.h index d2ffe15..5f70541 100644 --- a/Swiften/TLS/TLSContextFactory.h +++ b/Swiften/TLS/TLSContextFactory.h @@ -1,25 +1,29 @@ /* - * Copyright (c) 2010-2015 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once +#include <memory> + #include <Swiften/Base/API.h> +#include <Swiften/Base/ByteArray.h> +#include <Swiften/TLS/TLSContext.h> #include <Swiften/TLS/TLSOptions.h> namespace Swift { - class TLSContext; - class SWIFTEN_API TLSContextFactory { public: virtual ~TLSContextFactory(); virtual bool canCreate() const = 0; - virtual TLSContext* createTLSContext(const TLSOptions& tlsOptions) = 0; + virtual std::unique_ptr<TLSContext> createTLSContext(const TLSOptions& tlsOptions, TLSContext::Mode = TLSContext::Mode::Client) = 0; virtual void setCheckCertificateRevocation(bool b) = 0; virtual void setDisconnectOnCardRemoval(bool b) = 0; + + virtual ByteArray convertDHParametersFromPEMToDER(const std::string& pem); }; } diff --git a/Swiften/TLS/TLSError.h b/Swiften/TLS/TLSError.h index ae775e6..9e4af2f 100644 --- a/Swiften/TLS/TLSError.h +++ b/Swiften/TLS/TLSError.h @@ -1,33 +1,41 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once #include <memory> +#include <string> #include <Swiften/Base/API.h> #include <Swiften/Base/Error.h> namespace Swift { class SWIFTEN_API TLSError : public Error { public: typedef std::shared_ptr<TLSError> ref; enum Type { UnknownError, - CertificateCardRemoved + CertificateCardRemoved, + AcceptFailed, + ConnectFailed }; - TLSError(Type type = UnknownError) : type(type) {} + TLSError(Type type = UnknownError, std::string message = "") : type_(type), message_(std::move(message)) {} Type getType() const { - return type; + return type_; + } + + const std::string& getMessage() const { + return message_; } private: - Type type; + Type type_; + std::string message_; }; } diff --git a/Swiften/TLS/UnitTest/CertificateTest.cpp b/Swiften/TLS/UnitTest/CertificateTest.cpp index 2483dae..aac2cfb 100644 --- a/Swiften/TLS/UnitTest/CertificateTest.cpp +++ b/Swiften/TLS/UnitTest/CertificateTest.cpp @@ -1,34 +1,143 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <memory> #include <cppunit/extensions/HelperMacros.h> #include <cppunit/extensions/TestFactoryRegistry.h> #include <Swiften/Base/ByteArray.h> +#include <Swiften/Base/Platform.h> #include <Swiften/Crypto/CryptoProvider.h> #include <Swiften/Crypto/PlatformCryptoProvider.h> #include <Swiften/TLS/Certificate.h> +#include <Swiften/TLS/CertificateFactory.h> +#include <Swiften/TLS/PlatformTLSFactories.h> #include <Swiften/TLS/SimpleCertificate.h> using namespace Swift; class CertificateTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(CertificateTest); CPPUNIT_TEST(testGetSHA1Fingerprint); +#ifdef HAVE_OPENSSL + CPPUNIT_TEST(testParsingPEMCertificate); +#endif + CPPUNIT_TEST(testParsingPEMPrivateKey); CPPUNIT_TEST_SUITE_END(); public: void testGetSHA1Fingerprint() { SimpleCertificate::ref testling = std::make_shared<SimpleCertificate>(); testling->setDER(createByteArray("abcdefg")); CPPUNIT_ASSERT_EQUAL(std::string("2f:b5:e1:34:19:fc:89:24:68:65:e7:a3:24:f4:76:ec:62:4e:87:40"), Certificate::getSHA1Fingerprint(testling, std::shared_ptr<CryptoProvider>(PlatformCryptoProvider::create()).get())); } + + void testParsingPEMCertificate() { + PlatformTLSFactories tlsFactories; + + auto PEMCertificate = R"(-----BEGIN CERTIFICATE----- +MIIEsjCCApoCCQCbkjlQfUqPtTANBgkqhkiG9w0BAQsFADAbMRkwFwYDVQQDDBBt +b250YWd1ZS5leGFtcGxlMB4XDTE4MDExODE2NTMxMloXDTQ1MDYwNDE2NTMxMlow +GzEZMBcGA1UEAwwQbW9udGFndWUuZXhhbXBsZTCCAiIwDQYJKoZIhvcNAQEBBQAD +ggIPADCCAgoCggIBALAx5xuEYOjDJ9QHMvwRuDzxbHl1zR97SJFPAkmD8xH0sC61 +DNRyUvRq6UXb4znhqeqrNuZ9PV47GyK2Dpy/c/MY5NE3m/c+Z1tUnrcqyCkxITIn +jdSI/elc9yhtMXX6lRi68BdPJnj/9+6trW0cWHlKEgnaSTAgCVB+4Dg9mjTIroCa +HLoAKhr2zS7Ihs28aWb0cSvZ+qFgQhr7FGP2kfssTTQYyRPn9uHhtyWH6RqSv5x9 +BBGZWN5GtjkJvupcYWLt8ftuQyFpwEeEz5cgtiyKgsfz9CYvS9/OcwdLQr4z5Zq6 +eKxsog9GdwIi1Us4KR0X6tKu9ze42iEWF+foEWFP9/bjrVK/tt5lTSKnenk0nA8I +amkG0btNAGihDti3lv60bGpd3B2/uh4gzzT2buXdf0EaybCt52MIr8xkwMU0Tkri +RAYchdS8U8sekWG5Lg9m3L2BDa8/TKS/WflJhGcZeInGQslgIx7fCgO1M7Zr50pO +wSURPXpvqUkXNEBy639UQEUsnBhntEQwZWx/6x6Ma/U5a5dL6qbtEJjlwIvS+nl9 +3w26g3DvWydNMCtZIVhgdrl+dZs+Uw5eA3QkHkDTSfYvQk7X5SYL0J5ZxwBvU9r1 +ED054+TAEuX2euiRA37xLhxonj8BaKkPQGlAHCLZaZPmNJWkNxElJhMoCfqBAgMB +AAEwDQYJKoZIhvcNAQELBQADggIBAF+FNyW3nVeQeugBMksIhj7EMJl1AEKi0+78 +ZPsYX3CDbc/8GRZoTg/EWSiwPCBYc9VsxuKtODEYABCZgk7LnSBYoEauJDKWqkgM +UOKPJI2hu7mIK7FJpjvEZe2MnRRA63oI/NVDJm8T2clrv/vPkY+ppsVl0toC0SpH +/3dF5c65vYI19rTJraRU6kIrrgxFBzxzpn07LGh2rrOCQfy2umTSRMwz3ORAFfmi ++Kek1Dt7c+JVJ0ivCwhhc8MKza3JS2MuDfVWGnXtDLb81Ai0t4tQfLKvZEcgW+lh +Drz9gv22buwncWL/IxtuhzyILtDSDKAYFbhfG6IAQut9BjMgpMnKrBCDlOLJl08K +tgj2h7vUKyNSt3ndcSAtXjr6FD7+xPExJuyn/MgLONGGAZoZHFB4QO90wQaXxMPh +7rnjUtzfLR8qkDmX8ZB4f4VOWpDWo4hBpgjTk0gYfzEkrh+zTqE9reh7CZ1WzwXO +KnIBU2dZOE+XsJe49lW106DLqGzKRuQMUAwFMb7C7Nlg9GKTnvi41o+g6YE+MgxR +uPKu891pCBtnDxZiWPT+7Fa/9UXxdIOTVIHW6utSWiWYbeNwXSmIm2ShfmNfWj9m +x1JgJrFB6daWGR9aDBeDVRhgL6Z35lH7xI62pLJ4o2d2Y/9dUWAJfz5O8opeCyrF +zqCzpwGL +-----END CERTIFICATE----- +)"; + + auto certificateChain = tlsFactories.getCertificateFactory()->createCertificateChain(createByteArray(PEMCertificate)); + CPPUNIT_ASSERT_EQUAL(size_t(1), certificateChain.size()); + + auto certificate = certificateChain[0]; + CPPUNIT_ASSERT_EQUAL(std::string("/CN=montague.example"), certificate->getSubjectName()); + } + + void testParsingPEMPrivateKey() { + PlatformTLSFactories tlsFactories; + + auto PEMPrivateKey = R"(-----BEGIN PRIVATE KEY----- +MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQCwMecbhGDowyfU +BzL8Ebg88Wx5dc0fe0iRTwJJg/MR9LAutQzUclL0aulF2+M54anqqzbmfT1eOxsi +tg6cv3PzGOTRN5v3PmdbVJ63KsgpMSEyJ43UiP3pXPcobTF1+pUYuvAXTyZ4//fu +ra1tHFh5ShIJ2kkwIAlQfuA4PZo0yK6Amhy6ACoa9s0uyIbNvGlm9HEr2fqhYEIa ++xRj9pH7LE00GMkT5/bh4bclh+kakr+cfQQRmVjeRrY5Cb7qXGFi7fH7bkMhacBH +hM+XILYsioLH8/QmL0vfznMHS0K+M+WaunisbKIPRncCItVLOCkdF+rSrvc3uNoh +Fhfn6BFhT/f2461Sv7beZU0ip3p5NJwPCGppBtG7TQBooQ7Yt5b+tGxqXdwdv7oe +IM809m7l3X9BGsmwredjCK/MZMDFNE5K4kQGHIXUvFPLHpFhuS4PZty9gQ2vP0yk +v1n5SYRnGXiJxkLJYCMe3woDtTO2a+dKTsElET16b6lJFzRAcut/VEBFLJwYZ7RE +MGVsf+sejGv1OWuXS+qm7RCY5cCL0vp5fd8NuoNw71snTTArWSFYYHa5fnWbPlMO +XgN0JB5A00n2L0JO1+UmC9CeWccAb1Pa9RA9OePkwBLl9nrokQN+8S4caJ4/AWip +D0BpQBwi2WmT5jSVpDcRJSYTKAn6gQIDAQABAoICABqc/wZ2AVlHGP36tGXEm2qB +INxbwcbujTB9mZ/XEWD176KucCiquAL5HxERPIointK2V82Kvzk7fkbI7v4YIQBo +Ey/S0XkP8Panmm2aRa+LHzN/K/odUxTrmN1/WMg0OE8K9Xbf2rTOHPntO9POQ0LW +wFDCqulc/WsuLtnv3Bn68fi0zn/9xF5cRvO5EDuFKPqHE40HGMdFTdbbc+IBfV1N +/L9QuxaJpA3MVSiTFc+QuOZ/L50k53pzfdSxtyeZGpCh1jofFn62hXeIBP8TztB9 +f3GKVKdr328HtPI2GPe3yQeNAOsyYWwjPZiSAFujOPqPAUYfbXH6NuBmgOfjcrRb +AhOv9F1VNi+G56NJ6jo/NPygD+LYQdIKs5rv3E4ehyQzbu+SoGyVCnF3qm0cvz+v +tB5/gNiWiyRhNF94DZHlceDMQSdyB/pfTZsKZ44Yv44Bzl54YbzR8yr/ZKzAj6gt +5lwAqCIcdRj4i5DmIa7psj3iYWe9hYV7f+zwdosPKibRvO9FpvDCbb7biIPkMozw +cYH6QlSsZ+XsK/Z3WPFPq0wHOgoWW9Tr8LYyQxGjLO+xD8ziQ7Rp0KApEunuO29s +CPXj+l1HqNmAK2LkdNI3c/yStlaAcOzYD6pauciHWlTnIGZG8aHV6elIjK0C/h7B +3GndVc0TbewbP0bL56QBAoIBAQDU/yl4nlELhpoI1WW8v/FcDnc3V5dBilJ3LQtp +a3SKBcNWXE850TviOAklMrYmS1wuWdBTjEay9Ka6dImqMFGupmJjLmUw0KXrtPin +xIz5DZ42nmTKnYevuBQoQrrq7toxf5hYow2ZjeH2vSX+igY1gxDZbLW4Wb9GPYMo +Au5+z8XpA8R0key52nvnKastm5YxNstAlBOodAPKlbIr2bzmrHSjXAGjUzb+z6NZ +5Lx+zvQCy9kaIYvfOJm3eLSbMXzeP2S59qbwL+dC4ZJ5m3hjRmMaactV6LSchVNt +eLEYJpm92IdjQhG6oqM0IaU3aSjWMSrOAytylmqoEt4wA+WhAoIBAQDTxJ9VLb+J +OD0x/9cm17KpK1nGQBQ0T0oZQUH5M/tXTPCCoIpoL9UhKQ34vlPaZXkBQrXPw+PN +Y0J26uR6w4CowWAMn8LR6cYsWcOKuURcDYs/SPflD3rraevJwugQhkXtub2nV7dP +88Z/jGvhXthJmjUmNoKq3OC2MuSfHSkm8ipvaAblwb+lt5zBJGQ6iGXbi5TI6b+D +lnAidQpG/V464Zc9gb788P0K2vUeoZRLI7CurYqpDV0mBtPhFv5L1M0S8+psG7Pa +NIEKcW/b76vU9odTrtGBT0gCVYU7f8QnTN4g6c7dEhcZa2Zvg0YSmb4XuU9RQGC5 +As47nEUnPCjhAoIBAQDTXKnAogn2kAmGvoyIs0hFe61d47ObPDH9RVvPruwkkvd2 +WX/c9f6gy853dU0/zwSYklOitM7rgs94s3BwzCYiU8XKeh28RTCBKEKf6PGjq5nW +xXNrhMtC2j5WfXGS9JbdC6sYOiWivSMAgE6Vuk3TCE7OE4x4dcbTYvMl31Lf0Dqq +sixfKPdqrp7Jk5XkWkK+b4teeBLR1N52R/pYfWdw2K2d9g1CD6/BSDbnW46Zn7CQ +nczAm417Y2VWpZdDceZhfTLtPxAFxOOOgN2jg14B1bU+XsGCbLvdnohdV6kVOCjU +NWyUWNnTBNVDRCf5RodZlczORmL1AMKyKpcFurhBAoIBABSxbfBg3AqImFI+ccO1 +6BtnxQn+UPsblF4LZmr3jWPmfMoG7f9oTSdEX70ivAbnS3+4CRQYTDZRsLj2EwV7 +/SKAYuZY5iyk71x+GQGBQRDNsgGpG7AiZxyB6Sx6Azs6I7MrJ0Em7R6+73KfQhtv +rSrkCrWFNheEJeEn7/csXk0T9NmWDLZ+zD9hRcwJxlGB6pIdfZh0XuZ42NRFI4/0 +SjTuvlygRQ1qbw+UfcdUeq0s+6LWCmqih6ujlyizmn3GeZOUih+uRVDZOJLQquGO +9feFb4vZ1VcRbDPuL2q0/XHprPsCXdh0YBV3zTawWTSQGWcwEHQcGld50rU4e/lt +g4ECggEBAKwoqsqIHheL+uS2CHXmwFIr+rvOlLYlfB8XrwV/da3p7QChaDLbNIVM +uOAozCMkJY+dufPGI+3cKsR3kLAGejmfbH5OTzTbwCLOJFCWaoMuvOTY2Govte61 +gU1BWnjUgVJgVA/YTwn2yo02d0nG5/rSZ9xIt3hfO6ac5FhHBTA1DAZ1wDiLeow+ +qngZ2sA4ePtwhGFtvLVwTcGAfkWvQFi2YPBpesFIAmQ/ACGC7Ye75Ja4k36/8YwE +NiXR2Yy1hxwwi7CTWWzI0X+mvE/Oqpd8PUqPJCJcpz892Gq4EGCxM7Bz7NxCcvvw +5IMXuORWuoq0gXiCdEyko+saXsyWlqw= +-----END PRIVATE KEY----- +)"; + + auto privateKey = tlsFactories.getCertificateFactory()->createPrivateKey(createSafeByteArray(PEMPrivateKey)); + + CPPUNIT_ASSERT(privateKey != nullptr); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(CertificateTest); diff --git a/Swiften/TLS/UnitTest/ClientServerTest.cpp b/Swiften/TLS/UnitTest/ClientServerTest.cpp new file mode 100644 index 0000000..e60364e --- /dev/null +++ b/Swiften/TLS/UnitTest/ClientServerTest.cpp @@ -0,0 +1,760 @@ +/* + * Copyright (c) 2010-2018 Isode Limited. + * All rights reserved. + * See the COPYING file for more information. + */ + +#include <map> +#include <memory> +#include <utility> +#include <vector> + +#include <boost/variant.hpp> + +#include <gtest/gtest.h> + +#include <Swiften/Base/Log.h> +#include <Swiften/TLS/CertificateFactory.h> +#include <Swiften/TLS/PlatformTLSFactories.h> +#include <Swiften/TLS/TLSContext.h> +#include <Swiften/TLS/TLSContextFactory.h> +#include <Swiften/TLS/TLSOptions.h> + +using namespace Swift; +namespace { + + +std::map<std::string, std::string> certificatePEM = { + {"montague.example", +R"(-----BEGIN CERTIFICATE----- +MIIEsjCCApoCCQCbkjlQfUqPtTANBgkqhkiG9w0BAQsFADAbMRkwFwYDVQQDDBBt +b250YWd1ZS5leGFtcGxlMB4XDTE4MDExODE2NTMxMloXDTQ1MDYwNDE2NTMxMlow +GzEZMBcGA1UEAwwQbW9udGFndWUuZXhhbXBsZTCCAiIwDQYJKoZIhvcNAQEBBQAD +ggIPADCCAgoCggIBALAx5xuEYOjDJ9QHMvwRuDzxbHl1zR97SJFPAkmD8xH0sC61 +DNRyUvRq6UXb4znhqeqrNuZ9PV47GyK2Dpy/c/MY5NE3m/c+Z1tUnrcqyCkxITIn +jdSI/elc9yhtMXX6lRi68BdPJnj/9+6trW0cWHlKEgnaSTAgCVB+4Dg9mjTIroCa +HLoAKhr2zS7Ihs28aWb0cSvZ+qFgQhr7FGP2kfssTTQYyRPn9uHhtyWH6RqSv5x9 +BBGZWN5GtjkJvupcYWLt8ftuQyFpwEeEz5cgtiyKgsfz9CYvS9/OcwdLQr4z5Zq6 +eKxsog9GdwIi1Us4KR0X6tKu9ze42iEWF+foEWFP9/bjrVK/tt5lTSKnenk0nA8I +amkG0btNAGihDti3lv60bGpd3B2/uh4gzzT2buXdf0EaybCt52MIr8xkwMU0Tkri +RAYchdS8U8sekWG5Lg9m3L2BDa8/TKS/WflJhGcZeInGQslgIx7fCgO1M7Zr50pO +wSURPXpvqUkXNEBy639UQEUsnBhntEQwZWx/6x6Ma/U5a5dL6qbtEJjlwIvS+nl9 +3w26g3DvWydNMCtZIVhgdrl+dZs+Uw5eA3QkHkDTSfYvQk7X5SYL0J5ZxwBvU9r1 +ED054+TAEuX2euiRA37xLhxonj8BaKkPQGlAHCLZaZPmNJWkNxElJhMoCfqBAgMB +AAEwDQYJKoZIhvcNAQELBQADggIBAF+FNyW3nVeQeugBMksIhj7EMJl1AEKi0+78 +ZPsYX3CDbc/8GRZoTg/EWSiwPCBYc9VsxuKtODEYABCZgk7LnSBYoEauJDKWqkgM +UOKPJI2hu7mIK7FJpjvEZe2MnRRA63oI/NVDJm8T2clrv/vPkY+ppsVl0toC0SpH +/3dF5c65vYI19rTJraRU6kIrrgxFBzxzpn07LGh2rrOCQfy2umTSRMwz3ORAFfmi ++Kek1Dt7c+JVJ0ivCwhhc8MKza3JS2MuDfVWGnXtDLb81Ai0t4tQfLKvZEcgW+lh +Drz9gv22buwncWL/IxtuhzyILtDSDKAYFbhfG6IAQut9BjMgpMnKrBCDlOLJl08K +tgj2h7vUKyNSt3ndcSAtXjr6FD7+xPExJuyn/MgLONGGAZoZHFB4QO90wQaXxMPh +7rnjUtzfLR8qkDmX8ZB4f4VOWpDWo4hBpgjTk0gYfzEkrh+zTqE9reh7CZ1WzwXO +KnIBU2dZOE+XsJe49lW106DLqGzKRuQMUAwFMb7C7Nlg9GKTnvi41o+g6YE+MgxR +uPKu891pCBtnDxZiWPT+7Fa/9UXxdIOTVIHW6utSWiWYbeNwXSmIm2ShfmNfWj9m +x1JgJrFB6daWGR9aDBeDVRhgL6Z35lH7xI62pLJ4o2d2Y/9dUWAJfz5O8opeCyrF +zqCzpwGL +-----END CERTIFICATE----- +)"}, + {"capulet.example", +R"(-----BEGIN CERTIFICATE----- +MIIEsDCCApgCCQDUGdmqHfGngTANBgkqhkiG9w0BAQsFADAaMRgwFgYDVQQDDA9j +YXB1bGV0LmV4YW1wbGUwHhcNMTgwMTE4MTY1NjEyWhcNNDUwNjA0MTY1NjEyWjAa +MRgwFgYDVQQDDA9jYXB1bGV0LmV4YW1wbGUwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQCgA/CpV7UGqUdjhEVoMjFIZ6Ca/C7utrVPAqBvE14eiurIhQrQ +AmYeC9zA4/uXCdqkGq/a/RbF3OOCKLRUejCcynb0EnxiHxHa48ZsvLbKCK6guoXE +pWnaZsmRpvJrBB2z6ohmxRuaDuc5CJT+Oq8AFPp3StTAFDo3Cju3fsGZPkNpCGbj +ELwk4ok9INtEuTrMEmHZTD+VfjpXauUfN4ygKaPXJanCuxuifyin403BWgd8igkD +oSCWxoDFMy3HGbh/NU+nJPJ23FxVC39RdDG3elvjNFpSZnALbiMnyor7YjF5TN93 +1ZWwn3VTnl7DnFquEbKbYyVFUzRII8Cd1TzKOL48rVLrCAqMXwm6YFtST6qPb9TZ +0SX8qZGCwBfHV5OeS0ZgiBMMlmUPYcw9MlyvZnYyDPCOoPWmhEqd2gQzn//7hzb5 +mriCEyfcMzAqohylBNHXUVZTx5KcazJz6oOYdWEs1jfSXNKefgSWlgeoG2fgTXPN +1OkQVS+FOiI0VCAIwR+vxhG3hVTz3kzXWvEt7M51faaHWWlnSzOrbSuj3f0ibS5J +cj6ClyzOQRQDwzofyZ7oPWh6No/XkepVIn3HTTlnj1/8e6VsH+EBKSzoX2XvWPkO +GAZEGHKiKh944u6d6mW37BPD2oKyusP3uPL5j2Fdm+m0HkP3/7yw+5EFVQIDAQAB +MA0GCSqGSIb3DQEBCwUAA4ICAQCfCGK4iDo8H0i12wBC0+6GB9NBmgn8P09AUN0l +tQjZPaqZCtLtBBqOrAaZQBQMfI0QAm5/h/VkhMvz5HQjqmQhI2drSDOmarYzOGgY +yVItkEwtLEVhiGoeJ+L3Smosoqq6QFjcDzH7UzPTrJNspnY+09+m53pJggh41zzt +1TOU+QasaB5oGopFaFUUlwjHAc7FpZgEd+tV6j0cpdT3GabVkkoLg01Z+0mqkpLD +OjRBKJX8XvZ38VESsy3gWpcXnDq03n+8OgZo4R9SEcyyxjWbyb+qg2dzbQvRB2Va +QNoXp5EzemXvFSulhR+TfDk2K1h45BurikRQxDi8LpBTUsCMwiqXdem68HOlTwLi +/kMWbnVBcdurYcWVSwlJU4EJcTEdk51JStO1V0nAA0nCwn/iEhY8I6BitnrcCJ5e +4CGVWr+zAm8DBjaFMTzy46Q5NcT0hwnHGN6T6l4aMcRggIK9anRbXCn6dSzma1pd +R5N/Do00FTpyZGcUlVPnSlIfZVl7y/9XEO1n6xDJURrefL1JrM7UMyB17jA8HMq3 +S05kF7XRpludRB4QkAJt5BNNv6BPP7HPIKyR/rq94ONvzVPAo7uASyFE2sMBsfwP +pXAI1LVolPCoUC13jEkKdmc8kMSxU+XtsvFryNhkfQtZfSg+nBRFYptFE7GrZ9WY +GMSL4g== +-----END CERTIFICATE----- +)"}}; +std::map<std::string, std::string> privateKeyPEM = { + {"montague.example", +R"(-----BEGIN PRIVATE KEY----- +MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQCwMecbhGDowyfU +BzL8Ebg88Wx5dc0fe0iRTwJJg/MR9LAutQzUclL0aulF2+M54anqqzbmfT1eOxsi +tg6cv3PzGOTRN5v3PmdbVJ63KsgpMSEyJ43UiP3pXPcobTF1+pUYuvAXTyZ4//fu +ra1tHFh5ShIJ2kkwIAlQfuA4PZo0yK6Amhy6ACoa9s0uyIbNvGlm9HEr2fqhYEIa ++xRj9pH7LE00GMkT5/bh4bclh+kakr+cfQQRmVjeRrY5Cb7qXGFi7fH7bkMhacBH +hM+XILYsioLH8/QmL0vfznMHS0K+M+WaunisbKIPRncCItVLOCkdF+rSrvc3uNoh +Fhfn6BFhT/f2461Sv7beZU0ip3p5NJwPCGppBtG7TQBooQ7Yt5b+tGxqXdwdv7oe +IM809m7l3X9BGsmwredjCK/MZMDFNE5K4kQGHIXUvFPLHpFhuS4PZty9gQ2vP0yk +v1n5SYRnGXiJxkLJYCMe3woDtTO2a+dKTsElET16b6lJFzRAcut/VEBFLJwYZ7RE +MGVsf+sejGv1OWuXS+qm7RCY5cCL0vp5fd8NuoNw71snTTArWSFYYHa5fnWbPlMO +XgN0JB5A00n2L0JO1+UmC9CeWccAb1Pa9RA9OePkwBLl9nrokQN+8S4caJ4/AWip +D0BpQBwi2WmT5jSVpDcRJSYTKAn6gQIDAQABAoICABqc/wZ2AVlHGP36tGXEm2qB +INxbwcbujTB9mZ/XEWD176KucCiquAL5HxERPIointK2V82Kvzk7fkbI7v4YIQBo +Ey/S0XkP8Panmm2aRa+LHzN/K/odUxTrmN1/WMg0OE8K9Xbf2rTOHPntO9POQ0LW +wFDCqulc/WsuLtnv3Bn68fi0zn/9xF5cRvO5EDuFKPqHE40HGMdFTdbbc+IBfV1N +/L9QuxaJpA3MVSiTFc+QuOZ/L50k53pzfdSxtyeZGpCh1jofFn62hXeIBP8TztB9 +f3GKVKdr328HtPI2GPe3yQeNAOsyYWwjPZiSAFujOPqPAUYfbXH6NuBmgOfjcrRb +AhOv9F1VNi+G56NJ6jo/NPygD+LYQdIKs5rv3E4ehyQzbu+SoGyVCnF3qm0cvz+v +tB5/gNiWiyRhNF94DZHlceDMQSdyB/pfTZsKZ44Yv44Bzl54YbzR8yr/ZKzAj6gt +5lwAqCIcdRj4i5DmIa7psj3iYWe9hYV7f+zwdosPKibRvO9FpvDCbb7biIPkMozw +cYH6QlSsZ+XsK/Z3WPFPq0wHOgoWW9Tr8LYyQxGjLO+xD8ziQ7Rp0KApEunuO29s +CPXj+l1HqNmAK2LkdNI3c/yStlaAcOzYD6pauciHWlTnIGZG8aHV6elIjK0C/h7B +3GndVc0TbewbP0bL56QBAoIBAQDU/yl4nlELhpoI1WW8v/FcDnc3V5dBilJ3LQtp +a3SKBcNWXE850TviOAklMrYmS1wuWdBTjEay9Ka6dImqMFGupmJjLmUw0KXrtPin +xIz5DZ42nmTKnYevuBQoQrrq7toxf5hYow2ZjeH2vSX+igY1gxDZbLW4Wb9GPYMo +Au5+z8XpA8R0key52nvnKastm5YxNstAlBOodAPKlbIr2bzmrHSjXAGjUzb+z6NZ +5Lx+zvQCy9kaIYvfOJm3eLSbMXzeP2S59qbwL+dC4ZJ5m3hjRmMaactV6LSchVNt +eLEYJpm92IdjQhG6oqM0IaU3aSjWMSrOAytylmqoEt4wA+WhAoIBAQDTxJ9VLb+J +OD0x/9cm17KpK1nGQBQ0T0oZQUH5M/tXTPCCoIpoL9UhKQ34vlPaZXkBQrXPw+PN +Y0J26uR6w4CowWAMn8LR6cYsWcOKuURcDYs/SPflD3rraevJwugQhkXtub2nV7dP +88Z/jGvhXthJmjUmNoKq3OC2MuSfHSkm8ipvaAblwb+lt5zBJGQ6iGXbi5TI6b+D +lnAidQpG/V464Zc9gb788P0K2vUeoZRLI7CurYqpDV0mBtPhFv5L1M0S8+psG7Pa +NIEKcW/b76vU9odTrtGBT0gCVYU7f8QnTN4g6c7dEhcZa2Zvg0YSmb4XuU9RQGC5 +As47nEUnPCjhAoIBAQDTXKnAogn2kAmGvoyIs0hFe61d47ObPDH9RVvPruwkkvd2 +WX/c9f6gy853dU0/zwSYklOitM7rgs94s3BwzCYiU8XKeh28RTCBKEKf6PGjq5nW +xXNrhMtC2j5WfXGS9JbdC6sYOiWivSMAgE6Vuk3TCE7OE4x4dcbTYvMl31Lf0Dqq +sixfKPdqrp7Jk5XkWkK+b4teeBLR1N52R/pYfWdw2K2d9g1CD6/BSDbnW46Zn7CQ +nczAm417Y2VWpZdDceZhfTLtPxAFxOOOgN2jg14B1bU+XsGCbLvdnohdV6kVOCjU +NWyUWNnTBNVDRCf5RodZlczORmL1AMKyKpcFurhBAoIBABSxbfBg3AqImFI+ccO1 +6BtnxQn+UPsblF4LZmr3jWPmfMoG7f9oTSdEX70ivAbnS3+4CRQYTDZRsLj2EwV7 +/SKAYuZY5iyk71x+GQGBQRDNsgGpG7AiZxyB6Sx6Azs6I7MrJ0Em7R6+73KfQhtv +rSrkCrWFNheEJeEn7/csXk0T9NmWDLZ+zD9hRcwJxlGB6pIdfZh0XuZ42NRFI4/0 +SjTuvlygRQ1qbw+UfcdUeq0s+6LWCmqih6ujlyizmn3GeZOUih+uRVDZOJLQquGO +9feFb4vZ1VcRbDPuL2q0/XHprPsCXdh0YBV3zTawWTSQGWcwEHQcGld50rU4e/lt +g4ECggEBAKwoqsqIHheL+uS2CHXmwFIr+rvOlLYlfB8XrwV/da3p7QChaDLbNIVM +uOAozCMkJY+dufPGI+3cKsR3kLAGejmfbH5OTzTbwCLOJFCWaoMuvOTY2Govte61 +gU1BWnjUgVJgVA/YTwn2yo02d0nG5/rSZ9xIt3hfO6ac5FhHBTA1DAZ1wDiLeow+ +qngZ2sA4ePtwhGFtvLVwTcGAfkWvQFi2YPBpesFIAmQ/ACGC7Ye75Ja4k36/8YwE +NiXR2Yy1hxwwi7CTWWzI0X+mvE/Oqpd8PUqPJCJcpz892Gq4EGCxM7Bz7NxCcvvw +5IMXuORWuoq0gXiCdEyko+saXsyWlqw= +-----END PRIVATE KEY----- +)"},{"capulet.example", +R"(-----BEGIN PRIVATE KEY----- +MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQCgA/CpV7UGqUdj +hEVoMjFIZ6Ca/C7utrVPAqBvE14eiurIhQrQAmYeC9zA4/uXCdqkGq/a/RbF3OOC +KLRUejCcynb0EnxiHxHa48ZsvLbKCK6guoXEpWnaZsmRpvJrBB2z6ohmxRuaDuc5 +CJT+Oq8AFPp3StTAFDo3Cju3fsGZPkNpCGbjELwk4ok9INtEuTrMEmHZTD+VfjpX +auUfN4ygKaPXJanCuxuifyin403BWgd8igkDoSCWxoDFMy3HGbh/NU+nJPJ23FxV +C39RdDG3elvjNFpSZnALbiMnyor7YjF5TN931ZWwn3VTnl7DnFquEbKbYyVFUzRI +I8Cd1TzKOL48rVLrCAqMXwm6YFtST6qPb9TZ0SX8qZGCwBfHV5OeS0ZgiBMMlmUP +Ycw9MlyvZnYyDPCOoPWmhEqd2gQzn//7hzb5mriCEyfcMzAqohylBNHXUVZTx5Kc +azJz6oOYdWEs1jfSXNKefgSWlgeoG2fgTXPN1OkQVS+FOiI0VCAIwR+vxhG3hVTz +3kzXWvEt7M51faaHWWlnSzOrbSuj3f0ibS5Jcj6ClyzOQRQDwzofyZ7oPWh6No/X +kepVIn3HTTlnj1/8e6VsH+EBKSzoX2XvWPkOGAZEGHKiKh944u6d6mW37BPD2oKy +usP3uPL5j2Fdm+m0HkP3/7yw+5EFVQIDAQABAoICAQCBom+IYdvwp5eEUhaA0ZkH +lZyRsxi6oB7HAdPD6SbpC5YmGVKnLipY0TdotcqPlJYjONObUErwxYEzY5KkldFo +VMaF+av3OkCW2s1YLpLPnrUK1dGlfHUDUR6f92aRuGXv6mPTDoDMEKLWm9NJG3XH +VTeNCXzOmBSJnqq+f9yML9sg7oOcFWS3ZSfV9BZv2Lh/t6y6BIHGtNrDE4DIB5LP +9qwbkxGzBy7eOLJRQV8u86b5CENBQ3pJbEvKdynxES9dL212dgJQtTnAVG4zKTVV +9bUXnsRF2WOQfwvQItDx051NLjAkv05kJutAcR9IzhTQzNmr9Wiufzft8bkMpUJ3 +Mf8cJk5VNm9mgKvWnqKrPSyfNcicykcVHXr0yDICLgttWy5d9bj9/DcfrIOzEwhd +MOhTixYtR1dv/7p9kqw2mRgMV3GtB6f+AoQ29NrCt9bD6T2Rth9lXSo90sLW47J9 +QIan8jb/T4N7nuga37wLlpL5KhA7nyzlaF37PyvhbErzOxRfq287iQKCyF+nh3n5 +9HzWDWz+8zYcjsxlYc1x7XHWWAYKS1h+ZWPjWCLH8hlh3ZRdPm4CUfwuZmA2EjNT +8dRblRQ8QB9cvsKoLjKt8vB8mIoH6Sjk5I3vqNVXl6Su0JrvLg5A/3tfyPfxsm5c +rTunLQllzpgo2/q6ssz9yQKCAQEAzgDf0ozoyH9+k4ND7LCy5G1vGr8LqMhyjgSC +4AhBIM/Hz56YSrU0hIFpgu/VGWLkGN/0AiwhHBKpt+6KkvLBjxnv71dmI2hBIbb4 +Hzy4EXtPTtFqn4gffYjOen6co8RUl1vTOmRDUdfS6su0v9TD3335TIIfF+5DAGvR +V6OIHkQWWrHazUZx0tbwRyty3Q4NtYgXLFrcWFYfMFd26GhFrM7uHFrbOg5U3gpZ +/YdaaJzfdaJKHNPNQJUPD40n36n8RyjlWSWkUfEV3ITm0IMiCJ19WDjyddLUXuzC +KSoeiTCISXzZ8lhmvnBB4pW9V1O1o8cDJFRT1ouUfOKqK86lxwKCAQEAxtnMzmEp +Z+W3Jlz9istkJHerNATtQzj3KSNHbrM8gB+O0igq0BWbj+lvNtbuZVprLrOpbDk8 +Ksk+PdbgSbsQjALcs1FpoIsPWt6sKTwrZQuMCocHzGfrp0MA613YCRw9sNBM08C6 +TNbjSTiVlBb3xyjsI3hLZ9sj8N9rV6yomlwM6MnpdIDUxfiv5tlqZcqCYdibJ9zu +tWi44O2tim3uCVrajop/NsHXbROjd7MeV4gaj3SsJ4cLyvfcBkfwrhUse5D6qy6y +08ZsbrMUqY50ZG0WUcKzJxJcF/mOANZ+Dgqe9jwKlxV8E1Lj7PaQWWzQ5bWVgnLe +TuKoZurGEaJMAwKCAQEAgWHJMYswlOSGUg2KdrjP0mns8wZ0QzCJyiqJLD3i8cGu +Q/bevWUrs+E3rHYHCCe1DO5zaX3f2arbD1txizOOX9sxd8gTrT9IUO2CztOq48fn +mqAqcEHlTUnELOkiZjTj0CBq/OyF33xGyxLf1e/CibasAeJjtvr89+G/nGRoFGI9 +C/9SZcTNrlcyl/Bw9udhstbjfwceBxkoA4ubcgIzaIKayBJESCVCJiaoOHRvUu7b +5hzkoVBhRCOaTvEfzvkLKoJD8YaTuqdJTLPn56PEl1aap/M0TM36dhgLJiF/BjkG +D+mrVOsytH760l2ripJXraJLleCku0X1H66YpGTodwKCAQA34vCntDEB7VLrKklr +37v2b9ejGBtiwDjey/aAi0lerP/j2rwlnV0KNk42eHOp8p6bEo10SCW71LF0idah +gjylTQygLSpln4+iN2Dlee6sSHGEZ+zuKurVKISyob5c2R4ReomNHeZ+QArDAm8v +nsDmrX6ofV+cAb/5K6Gsk28TavmJ122Qe8DRHxK467P2hdLdExaQPoysWZFUThhv +BnRXFrzEQPJ9/j7Afjt8IdBOQ4dLeDwGI/NRiRXCgieHlZXZ6KY6xDYoROUmu5f8 +C3h03R/fvLvDKGrPpiid3aqx4ZRJmhhT3AryF2LNr4JkT6vqU32Amy4Vt6givKsM +O7PnAoIBAAggpMq7PMugGP4B9PgNb00oGmWfXSa+M83O0GGN7jSirxqkaK+/eDOY +kSnVFWmORNBlSz+bLoA3Bw2mFXI8HfSbHM9E/Qt0scf0hV+SwpTuO3pDWF5ev20G +mL1QEBUNDmvOn2SYERKI1iRevjBBXSzwTpAXnfaWvvTn1XSKzSJK3TjMhFTZHtbj +mgPPV65cznhofUsg2QenT8zKisvYPYN3p3p9Jo6IqHyT/CCymwIB4OMZITiwXxQs +PMAxlZGkX3Uri5A8Ln3QQ46elanI2TlC+ZDa84gu/Gw691JWCfsaSaQDTJKnGqos +dwiNVl130YWaJLjiA9Poc2llKtypfQ8= +-----END PRIVATE KEY----- +)"}}; + +auto montagueEncryptedPEM = R"(-----BEGIN RSA PRIVATE KEY----- +Proc-Type: 4,ENCRYPTED +DEK-Info: AES-256-CBC,6B0A69362920334824667C1B6207279B + +vlDCCnUf9aDbCD4+PUuo5LGvzTFlT03ZRMnHDcBzE2mp1OMBjxeEu4j4cqUJE2qV +NXCRbsedMsydoHlg76LssYM7J/AI9dp5cek0HgYMqdeB+hoNn22AmjRb7WhY4VeW +RqKAzkXT1lsxEF8hykQcalbsrbdmKkPosiNJF4Pb9EEefl01e+Ny3nb7GRs22tzX +lJNBk+lrM0Jlg1Y6c3F5/5CkKHTXP4924Pzjzf6Bw5hG80izrYeBUC5lZJtqDM7B +lmFXAng4RIDKk1TsqeJ11Fa1nMqFkvRvlU8RdrcZ5rtngWxIAvTXAjbDk5mvS6Iw +WdjmH46TrVMQLXC2Qh++grldyx4GDm7rShLm23J9lUAdPLjIvurYT+LfbCRqfgIw +hkPtm6BWkkf95KfpMKZ0giOhikqnF2YsozgqI5SphDFIAGN7bXa7Z8g/xFI9Uqie +2+rWqVvBOQ8PBepTd2H2uahV+pP1wHmgqN/bp/paXt6+Qf7ptH6MNTwgnTanDfnk +wzyhVlw5tTsG8okjD1cT2R7RbuDQRkArpzbnATPEU9Itrx0Sh/ZPKPDDVS+aSBHA +3JytZX5yzd/yilNjE3NfN1G923lcWXRX3KsdZUQjbcPugML7xbC+orqwxeYLipMN +jfNEGK0IrTNmRN5HqFU6JBNbas67BlFU4Zt4Tt73sUHrMpSSRINd8itRZaKtqZuM +8upj7ZUD/j6j/JmSxN2w+TcmHXfNWZirTFWUvtF/l1WCHilsuO49VW/CqGFW2Bad +32YzPkENljj/xuijGOHr1qVFozfG4/noXdVtJm0oflt1ImdjvOO91LneaAhVE8lO +K5SwOnsrlr6UM0tb/HnunT5Se49YQSGnXOiXO68bPO9S0JZ33MeAP5kSbMSZ6VXr +luw7dga0jfJLqnWU2arxOqruc9bSwkfU0RUoWXZqrKwUiXdyl/vVeU1Y67yuYqXH +7eUrdL+BdSDbeOC/5xmWAkeheC4OBBYCcwbVv1Aw67sUaQIcyWMkx8Kq9tn8vpRa +ETcagVjUXqAjrYtRpmCXU6KdmeGKoQZq14EVREytk0KnTUQTFtv8LJhsau16v4pS +in7Yt658hdf9CSA5snfUcvLeETNeQHQWvmN+0uD/UB9vRPbHp3kPSvitoS799QB1 +ydrD8zXdUSpcW+V2P75c7u0XkcUTbyGIBuwLAtr5fweyyiKs/v//rPaBlzEG1WUr +OFSH9KZ+m9UwqmauXesySXoVsmjCQKUVVj4/QI/aWftmMY58CDNJw+q77dAzSYrj +yFbhUt5ZKqAvb+rt3dJswkZ1sxAbmTw290NAV4NPP8cjXUjLwmU+KNZ2VFkxt77p +1LxG+Ia+TV1JystBvFeiJ6sWEC3lQ7+0b8oDfE5aovQpGk+Cb7hyt0EvDh0/AkvT +B/KCQc8wUjyn+yejBicfMzHVaOphwlajrt+vSNF4G7J+Wo5luTEXpWQrKq22xnah +sal7IusjSgPdFpLCuyAy6atb/4aQoeXlE/r8tXbmrl48SnadwAndoZVt3gzIv1/Z +oDc5koTBQk6aIoWHb6qslRt9tmrnF22aP+/a10oahgIliWAL3jUwLqZYzdbMKkMv +NEbobf7kO5LTzv+w09K0A8miF+8js351FBw05gsaUHgufF3OCGAdQfXDN7d6Lxho +HbhiuzxlHOnth3TWNfqhvNkwFP3gfAIaqlU1Z28AP6pZtUw93QYNABUez8QFZj5c +sdUpopUO8krnwUPNup6yTB/m72Vx2aSqXgu4upxUNVJlgDFmnCBhOe0KKjzduIvy +bRHxL93UZxDnpn8DBB1bgmdSzgInc2gfq91j1AyL+nbZv+kob/jG3OxMWNjenVDj ++TeyP3OypAUK/8jP98ExS75mE661mN28kKrUfTRxZGt8CJY4AFL4lAzIf2p4JMch +aPE30/DmXmKng+VP+3ik5FEomMLIc6QkrEzzcMYQkDsNdjd202CAXRSAqnT+VFtR +MlopkSVvEpn83HdCqcANl8rNo+ANnFMyyPL7sFd470KhSVTcQVSb+wR8DOiZr8Vt +uR0G3+KgdEDAvZStkWTCr5eMYhm95QVclnHhsLq0AaLrOm32PqBi2C4mGyW04Mud +m7lUuRkf/mLKWZZfKleefp12waahMqSXAo3shqyTNVPKOFSVA/UF0mFGon1Npo/x +6z4hd5sbG1kiPlrt9EeTgtwFhQ0lxM755QTvAB6GXcLxkGkdNdqhJzFtTRAE9P01 +CiI1JYEvTHBdGcsBbw9zJikOEXCA19fAMkHqSfo5aU/qbuvDsY2QLZkgfiMnpoOx +ghQzeJ95jiYE3V5WNtB/7CRthfC54moWW7w6ZgdIuCEN6JvK0zmsahv2o16kkzWA +YTw1lqaNMHIhlidRwy2Q+ke0mmNTIHHtNqLGVfOE4TwSN3VIIhXNZ5E65LuBw7tQ +SyFK07dfMQXixqaeo+ytXBNTFEq1MEza/PxwUojn7njbCKhO5qGavkiyNs5nk3ZE +htkhtreIUj6kHzWAvylxLbRy9+4AJA3/UCnudMRtX/McjtN2jNwZKPaXWCQF85ff +koOclVf4j/eYQnWT03zXjAx1DKazIk0laEfB4soXfQfgXdFyj3YKXKKD8WzCW/ag +cloY4yZVa+SWnj0P23oPdptL9vOM1NK1lXAp2tvvZHPp0UmLtXVU4eNaabC79dXC +3KU9bVruCdpQki4kGk3MvsoB9OyNEZE1jxLZ+7FI0D1XKJ4qHZcwOyGqD07+Xect +w2xs4stXxvogUZdQ3G6GBANFXEjDzEu5vZn9z668mCe0cQG/iNWOR5ZGmdjlmW5O +6O9ibFmk7pc975V9SVHH9rS/GZGz/PW6CJ8O0GALw5y9fczXxjvCz7dPHK5MO40m +fDWCwIqK1D2LOEewMFqOOleBhHMpVfQX+Uu34UlWHGFnOm1fK+dIdT7tss5o8Gkz +gCBFpmjyi8H+VtXOy5JTTIi/80pnLO8nsv27FNPVU3UZJCZjfR9LCeqZwgF1MFIe +X137HnkpmtJGF+bcMRwY5u9fSQQZtBNLCadRsvHnz6J+1uodFDnre0+Q4dokmFfv +0UveWc1CDRa3qXpzW5U6NpFjYWQmiS3KA5VY5/KHE7UJxnEI1R1gEaQ6/Ogp2cmI +-----END RSA PRIVATE KEY----- +)"; + +auto dhParamsOpenSslDer1024 = R"(-----BEGIN DH PARAMETERS----- +MIGHAoGBANjw4f5+gu8b8X8O6ALyJA1tH9TQTWZEI3YjUKQ1m0dVBMJ6XDC7FLJn +gqE4hIGcm1FAWwIiuo0uMufqyVwFT2c+G8j4JHWK5z1tEP+GaqiO34N0cUo86qHp +THSkJN7LuHbYRqI9fHWDZocW/5yAsDq5RPUCjFZAoh1BWdfDFfrjAgEC +-----END DH PARAMETERS----- +)"; +auto dhParamsOpenSslDer2048 = R"(-----BEGIN DH PARAMETERS----- +MIIBCAKCAQEA0Q6vD5qtrh3XEkVkbN29ord/k3sgo2Q3PiFmyFt89qqVbebEzYmt +t8DwaFGMcGlyKs4Lb1s7vocm9y3M9C0FZm85Muvv8WCbLZVZ+wfEtMibOjgRoDqt +p7Qqe7/iPgMVrSjWegVkg3V8K8dnPpohPClM0yOe4NpBjSVNgBVJRpEtH8gFiCor +H7hw63HpN/MgFdkjZNeCN+erv8p673xH8LrN98gQpkdQ9vCqYt1dHxF2XZcxBp8x +XganwPeGgQosofkA6nVB70hyjwjEyxnHJZIMlx6DPXWC7X6ed0SazgH0sQNdACvG +uU1zHCVIv6/f0adKrJg0s1jrM3qWZ6HmUwIBAg== +-----END DH PARAMETERS----- +)"; + +auto createTLSContext = [](TLSContext::Mode mode) { + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + auto tlsContextFactory = tlsFactories->getTLSContextFactory(); + + auto tlsContext = std::unique_ptr<TLSContext>(tlsContextFactory->createTLSContext({}, mode)); + return tlsContext; +}; + +// This connects a TLSContext to another TLSContext +class ClientServerConnector { + public: + ClientServerConnector(TLSContext* client, TLSContext* server) : clientContext_(client), serverContext_(server) { + connections_.push_back(clientContext_->onDataForNetwork.connect([&](const SafeByteArray& data) { + serverContext_->handleDataFromNetwork(data); + })); + connections_.push_back(serverContext_->onDataForNetwork.connect([&](const SafeByteArray& data) { + clientContext_->handleDataFromNetwork(data); + })); + } + + private: + TLSContext* clientContext_; + TLSContext* serverContext_; + std::vector<boost::signals2::connection> connections_; +}; + +struct TLSDataForNetwork { + SafeByteArray data; +}; + +struct TLSDataForApplication { + SafeByteArray data; +}; + +struct TLSFault { + std::shared_ptr<Swift::TLSError> error; +}; + +struct TLSConnected { + std::vector<Certificate::ref> chain; +}; + +struct TLSServerNameRequested { + std::string name; +}; + +using TLSEvent = boost::variant<TLSDataForNetwork, TLSDataForApplication, TLSFault, TLSConnected, TLSServerNameRequested>; + +class TLSEventToSafeByteArrayVisitor : public boost::static_visitor<SafeByteArray> { + public: + SafeByteArray operator()(const TLSDataForNetwork& tlsData) const { + return tlsData.data; + } + + SafeByteArray operator()(const TLSDataForApplication& tlsData) const { + return tlsData.data; + } + + SafeByteArray operator()(const TLSFault&) const { + return createSafeByteArray(""); + } + + SafeByteArray operator()(const TLSConnected&) const { + return createSafeByteArray(""); + } + + SafeByteArray operator()(const TLSServerNameRequested&) const { + return createSafeByteArray(""); + } + +}; + +class TLSEventToStringVisitor : public boost::static_visitor<std::string> { + public: + std::string operator()(const TLSDataForNetwork& event) const { + return std::string("TLSDataForNetwork(") + "size: " + std::to_string(event.data.size()) + ")"; + } + + std::string operator()(const TLSDataForApplication& event) const { + return std::string("TLSDataForApplication(") + "size: " + std::to_string(event.data.size()) + ")"; + } + + std::string operator()(const TLSFault&) const { + return "TLSFault()"; + } + + std::string operator()(const TLSConnected& event) const { + std::string certificates; + for (auto cert : event.chain) { + certificates += "\t" + cert->getSubjectName() + "\n"; + } + return std::string("TLSConnected()") + "\n" + certificates; + } + + std::string operator()(const TLSServerNameRequested& event) const { + return std::string("TLSServerNameRequested(") + "name: " + event.name + ")"; + } +}; + +class TLSClientServerEventHistory { + public: + TLSClientServerEventHistory(TLSContext* client, TLSContext* server) { + connectContext(std::string("client"), client); + connectContext(std::string("server"), server); + } + + __attribute__((unused)) + void print() { + auto count = 0; + std::cout << "\n"; + for (auto event : events) { + if (event.first == "server") { + std::cout << std::string(80, ' '); + } + std::cout << count << ". "; + std::cout << event.first << " : " << boost::apply_visitor(TLSEventToStringVisitor(), event.second) << std::endl; + count++; + } + } + + private: + void connectContext(const std::string& name, TLSContext* context) { + connections_.push_back(context->onDataForNetwork.connect([=](const SafeByteArray& data) { + events.push_back(std::pair<std::string, TLSEvent>(name, TLSDataForNetwork{data})); + })); + connections_.push_back(context->onDataForApplication.connect([=](const SafeByteArray& data) { + events.push_back(std::pair<std::string, TLSEvent>(name, TLSDataForApplication{data})); + })); + connections_.push_back(context->onError.connect([=](std::shared_ptr<Swift::TLSError> error) { + events.push_back(std::pair<std::string, TLSEvent>(name, TLSFault{error})); + })); + connections_.push_back(context->onConnected.connect([=](){ + events.push_back(std::pair<std::string, TLSEvent>(name, TLSConnected{context->getPeerCertificateChain()})); + })); + } + + public: + std::vector<std::pair<std::string, TLSEvent>> events; + + private: + std::vector<boost::signals2::connection> connections_; +}; + +} + +TEST(ClientServerTest, testInitAndFreeContext) { + auto tlsClientContext = createTLSContext(TLSContext::Mode::Client); + auto tlsServerContext = createTLSContext(TLSContext::Mode::Server); +} + +TEST(ClientServerTest, testServerSetPrivateKey) { + auto tlsServerContext = createTLSContext(TLSContext::Mode::Server); +} + +TEST(ClientServerTest, testServerSetCertificateChain) { + auto tlsServerContext = createTLSContext(TLSContext::Mode::Server); +} + +TEST(ClientServerTest, testClientServerBasicCommunicationWithCertificateMissing) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(privateKeyPEM["capulet.example"])); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(true, serverContext->setPrivateKey(privateKey)); + + serverContext->accept(); + clientContext->connect(); + + ASSERT_EQ("server", events.events[1].first); + ASSERT_EQ("TLSFault()", boost::apply_visitor(TLSEventToStringVisitor(), events.events[1].second)); +} + +TEST(ClientServerTest, testClientServerBasicCommunicationWithPrivateKeyMissing) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["capulet.example"])))); + + serverContext->accept(); + clientContext->connect(); + + ASSERT_EQ("server", events.events[1].first); + ASSERT_EQ("TLSFault()", boost::apply_visitor(TLSEventToStringVisitor(), events.events[1].second)); +} + +TEST(ClientServerTest, testWrongPrivateKeyAfterCertificate) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["capulet.example"])))); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(privateKeyPEM["montague.example"])); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(false, serverContext->setPrivateKey(privateKey)); + + serverContext->accept(); + clientContext->connect(); +} + +TEST(ClientServerTest, testWrongCertificateAfterPrivateKey) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(privateKeyPEM["montague.example"])); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(true, serverContext->setPrivateKey(privateKey)); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["capulet.example"])))); + + serverContext->accept(); + clientContext->connect(); + + ASSERT_EQ("server", events.events[1].first); + ASSERT_EQ("TLSFault()", boost::apply_visitor(TLSEventToStringVisitor(), events.events[1].second)); +} + +TEST(ClientServerTest, testClientServerBasicCommunication) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["capulet.example"])))); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(privateKeyPEM["capulet.example"])); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(true, serverContext->setPrivateKey(privateKey)); + + serverContext->accept(); + clientContext->connect(); + + clientContext->handleDataFromApplication(createSafeByteArray("This is a test message from the client.")); + serverContext->handleDataFromApplication(createSafeByteArray("This is a test message from the server.")); + + ASSERT_EQ(safeByteArrayToString(createSafeByteArray("This is a test message from the client.")), safeByteArrayToString(boost::apply_visitor(TLSEventToSafeByteArrayVisitor(), std::find_if(events.events.begin(), events.events.end(), [](std::pair<std::string, TLSEvent>& event){ + return event.first == "server" && (event.second.type() == typeid(TLSDataForApplication)); + })->second))); + ASSERT_EQ(safeByteArrayToString(createSafeByteArray("This is a test message from the server.")), safeByteArrayToString(boost::apply_visitor(TLSEventToSafeByteArrayVisitor(), std::find_if(events.events.begin(), events.events.end(), [](std::pair<std::string, TLSEvent>& event){ + return event.first == "client" && (event.second.type() == typeid(TLSDataForApplication)); + })->second))); +} + +TEST(ClientServerTest, testClientServerBasicCommunicationEncryptedPrivateKeyRightPassword) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["montague.example"])))); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(montagueEncryptedPEM), createSafeByteArray("test")); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(true, serverContext->setPrivateKey(privateKey)); + + serverContext->accept(); + clientContext->connect(); + + clientContext->handleDataFromApplication(createSafeByteArray("This is a test message from the client.")); + serverContext->handleDataFromApplication(createSafeByteArray("This is a test message from the server.")); + + ASSERT_EQ(safeByteArrayToString(createSafeByteArray("This is a test message from the client.")), safeByteArrayToString(boost::apply_visitor(TLSEventToSafeByteArrayVisitor(), std::find_if(events.events.begin(), events.events.end(), [](std::pair<std::string, TLSEvent>& event){ + return event.first == "server" && (event.second.type() == typeid(TLSDataForApplication)); + })->second))); + ASSERT_EQ(safeByteArrayToString(createSafeByteArray("This is a test message from the server.")), safeByteArrayToString(boost::apply_visitor(TLSEventToSafeByteArrayVisitor(), std::find_if(events.events.begin(), events.events.end(), [](std::pair<std::string, TLSEvent>& event){ + return event.first == "client" && (event.second.type() == typeid(TLSDataForApplication)); + })->second))); +} + +TEST(ClientServerTest, testSettingPrivateKeyWithWrongPassword) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["montague.example"])))); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(montagueEncryptedPEM), createSafeByteArray("foo")); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(false, serverContext->setPrivateKey(privateKey)); +} + +TEST(ClientServerTest, testSettingPrivateKeyWithoutRequiredPassword) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["montague.example"])))); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(montagueEncryptedPEM)); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(false, serverContext->setPrivateKey(privateKey)); +} + +TEST(ClientServerTest, testClientServerSNIRequestedHostAvailable) { + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + serverContext->onServerNameRequested.connect([&](const std::string& requestedName) { + if (certificatePEM.find(requestedName) != certificatePEM.end() && privateKeyPEM.find(requestedName) != privateKeyPEM.end()) { + auto certChain = tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM[requestedName])); + ASSERT_EQ(true, serverContext->setCertificateChain(certChain)); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(privateKeyPEM[requestedName])); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(true, serverContext->setPrivateKey(privateKey)); + } + }); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["capulet.example"])))); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(privateKeyPEM["capulet.example"])); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(true, serverContext->setPrivateKey(privateKey)); + + serverContext->accept(); + clientContext->connect("montague.example"); + + clientContext->handleDataFromApplication(createSafeByteArray("This is a test message from the client.")); + serverContext->handleDataFromApplication(createSafeByteArray("This is a test message from the server.")); + ASSERT_EQ("This is a test message from the client.", safeByteArrayToString(boost::apply_visitor(TLSEventToSafeByteArrayVisitor(), std::find_if(events.events.begin(), events.events.end(), [](std::pair<std::string, TLSEvent>& event){ + return event.first == "server" && (event.second.type() == typeid(TLSDataForApplication)); + })->second))); + ASSERT_EQ("This is a test message from the server.", safeByteArrayToString(boost::apply_visitor(TLSEventToSafeByteArrayVisitor(), std::find_if(events.events.begin(), events.events.end(), [](std::pair<std::string, TLSEvent>& event){ + return event.first == "client" && (event.second.type() == typeid(TLSDataForApplication)); + })->second))); + + ASSERT_EQ("/CN=montague.example", boost::get<TLSConnected>(events.events[5].second).chain[0]->getSubjectName()); +} + +TEST(ClientServerTest, testClientServerSNIRequestedHostUnavailable) { + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + serverContext->onServerNameRequested.connect([&](const std::string&) { + serverContext->setAbortTLSHandshake(true); + }); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["capulet.example"])))); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(privateKeyPEM["capulet.example"])); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(true, serverContext->setPrivateKey(privateKey)); + + serverContext->accept(); + clientContext->connect("montague.example"); + + ASSERT_EQ("server", events.events[1].first); + ASSERT_EQ("TLSFault()", boost::apply_visitor(TLSEventToStringVisitor(), events.events[1].second)); + + ASSERT_EQ("client", events.events[3].first); + ASSERT_EQ("TLSFault()", boost::apply_visitor(TLSEventToStringVisitor(), events.events[3].second)); +} + +TEST(ClientServerTest, testClientServerEqualFinishedMessage) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["capulet.example"])))); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(privateKeyPEM["capulet.example"])); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(true, serverContext->setPrivateKey(privateKey)); + + serverContext->accept(); + clientContext->connect(); + + ASSERT_EQ(serverContext->getPeerFinishMessage(), clientContext->getFinishMessage()); + ASSERT_EQ(clientContext->getPeerFinishMessage(), serverContext->getFinishMessage()); +} + +TEST(ClientServerTest, testClientServerBasicCommunicationWith2048BitDHParams) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["capulet.example"])))); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(privateKeyPEM["capulet.example"])); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(true, serverContext->setPrivateKey(privateKey)); + + ASSERT_EQ(true, serverContext->setDiffieHellmanParameters(tlsFactories->getTLSContextFactory()->convertDHParametersFromPEMToDER(dhParamsOpenSslDer2048))); + + serverContext->accept(); + clientContext->connect(); + + clientContext->handleDataFromApplication(createSafeByteArray("This is a test message from the client.")); + serverContext->handleDataFromApplication(createSafeByteArray("This is a test message from the server.")); + + ASSERT_EQ(safeByteArrayToString(createSafeByteArray("This is a test message from the client.")), safeByteArrayToString(boost::apply_visitor(TLSEventToSafeByteArrayVisitor(), std::find_if(events.events.begin(), events.events.end(), [](std::pair<std::string, TLSEvent>& event){ + return event.first == "server" && (event.second.type() == typeid(TLSDataForApplication)); + })->second))); + ASSERT_EQ(safeByteArrayToString(createSafeByteArray("This is a test message from the server.")), safeByteArrayToString(boost::apply_visitor(TLSEventToSafeByteArrayVisitor(), std::find_if(events.events.begin(), events.events.end(), [](std::pair<std::string, TLSEvent>& event){ + return event.first == "client" && (event.second.type() == typeid(TLSDataForApplication)); + })->second))); +} + +TEST(ClientServerTest, testClientServerBasicCommunicationWith1024BitDHParams) { + auto clientContext = createTLSContext(TLSContext::Mode::Client); + auto serverContext = createTLSContext(TLSContext::Mode::Server); + + TLSClientServerEventHistory events(clientContext.get(), serverContext.get()); + + ClientServerConnector connector(clientContext.get(), serverContext.get()); + + auto tlsFactories = std::make_shared<PlatformTLSFactories>(); + + ASSERT_EQ(true, serverContext->setCertificateChain(tlsFactories->getCertificateFactory()->createCertificateChain(createByteArray(certificatePEM["capulet.example"])))); + + auto privateKey = tlsFactories->getCertificateFactory()->createPrivateKey(createSafeByteArray(privateKeyPEM["capulet.example"])); + ASSERT_NE(nullptr, privateKey.get()); + ASSERT_EQ(true, serverContext->setPrivateKey(privateKey)); + + ASSERT_EQ(true, serverContext->setDiffieHellmanParameters(tlsFactories->getTLSContextFactory()->convertDHParametersFromPEMToDER(dhParamsOpenSslDer1024))); + + serverContext->accept(); + clientContext->connect(); + + clientContext->handleDataFromApplication(createSafeByteArray("This is a test message from the client.")); + serverContext->handleDataFromApplication(createSafeByteArray("This is a test message from the server.")); + + ASSERT_EQ(safeByteArrayToString(createSafeByteArray("This is a test message from the client.")), safeByteArrayToString(boost::apply_visitor(TLSEventToSafeByteArrayVisitor(), std::find_if(events.events.begin(), events.events.end(), [](std::pair<std::string, TLSEvent>& event){ + return event.first == "server" && (event.second.type() == typeid(TLSDataForApplication)); + })->second))); + ASSERT_EQ(safeByteArrayToString(createSafeByteArray("This is a test message from the server.")), safeByteArrayToString(boost::apply_visitor(TLSEventToSafeByteArrayVisitor(), std::find_if(events.events.begin(), events.events.end(), [](std::pair<std::string, TLSEvent>& event){ + return event.first == "client" && (event.second.type() == typeid(TLSDataForApplication)); + })->second))); +} |
Swift