diff options
| author | Edwin Mons <edwin.mons@isode.com> | 2018-10-29 16:28:14 (GMT) |
|---|---|---|
| committer | Edwin Mons <edwin.mons@isode.com> | 2018-11-08 11:31:20 (GMT) |
| commit | cf3d517763a3d74a2ec9fd6f7bdee8cbaee3550f (patch) | |
| tree | 69e11e13ff2e5127d2cbfcc164be761cf104a1b2 | |
| parent | 5ce9e19ef0744f530a797c30a82e9723eb7ea306 (diff) | |
| download | swift-cf3d517763a3d74a2ec9fd6f7bdee8cbaee3550f.zip swift-cf3d517763a3d74a2ec9fd6f7bdee8cbaee3550f.tar.bz2 | |
Consistently use unsigned short for network ports
Network ports are now consistently stored as unsigned shorts, apart from
the options and user interface, where -1 is still used to denote the use
of default ports.
Test-Information:
Unit tests pass on macOS 10.13 and Debian 9
On macOS: tested the UI with various proxy and manual ports, behaviour
as expected.
Change-Id: I7a65f40083022887aa30ed7b21eadc56d0c52be1
88 files changed, 384 insertions, 292 deletions
diff --git a/Slimber/Server.cpp b/Slimber/Server.cpp index 3bc3112..bfa34f5 100644 --- a/Slimber/Server.cpp +++ b/Slimber/Server.cpp @@ -1,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <Slimber/Server.h> @@ -37,12 +37,12 @@ #include <Slimber/VCardCollection.h> namespace Swift { Server::Server( - int clientConnectionPort, - int linkLocalConnectionPort, + unsigned short clientConnectionPort, + unsigned short linkLocalConnectionPort, LinkLocalServiceBrowser* linkLocalServiceBrowser, VCardCollection* vCardCollection, EventLoop* eventLoop) : linkLocalServiceRegistered(false), rosterRequested(false), diff --git a/Slimber/Server.h b/Slimber/Server.h index 4842cd9..2ee5a4a 100644 --- a/Slimber/Server.h +++ b/Slimber/Server.h @@ -1,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -39,25 +39,25 @@ namespace Swift { class EventLoop; class Server { public: Server( - int clientConnectionPort, - int linkLocalConnectionPort, + unsigned short clientConnectionPort, + unsigned short linkLocalConnectionPort, LinkLocalServiceBrowser* browser, VCardCollection* vCardCollection, EventLoop* eventLoop); ~Server(); void start(); void stop(); - int getLinkLocalPort() const { + unsigned short getLinkLocalPort() const { return linkLocalConnectionPort; } - int getClientToServerPort() const { + unsigned short getClientToServerPort() const { return clientConnectionPort; } boost::signals2::signal<void (bool)> onSelfConnected; boost::signals2::signal<void (boost::optional<ServerError>)> onStopped; @@ -103,12 +103,12 @@ namespace Swift { BoostIOServiceThread boostIOServiceThread; DummyUserRegistry userRegistry; PlatformXMLParserFactory xmlParserFactory; bool linkLocalServiceRegistered; bool rosterRequested; - int clientConnectionPort; - int linkLocalConnectionPort; + unsigned short clientConnectionPort; + unsigned short linkLocalConnectionPort; LinkLocalServiceBrowser* linkLocalServiceBrowser; VCardCollection* vCardCollection; EventLoop* eventLoop; LinkLocalPresenceManager* presenceManager; bool stopping; diff --git a/Sluift/SluiftClient.h b/Sluift/SluiftClient.h index 8cc815d..39ff0a8 100644 --- a/Sluift/SluiftClient.h +++ b/Sluift/SluiftClient.h @@ -79,11 +79,10 @@ namespace Swift { ClientOptions& getOptions() { return options; } void connect(); - void connect(const std::string& host, int port); void waitConnected(int timeout); bool isConnected() const; void setTraceEnabled(bool b); template<typename T> diff --git a/Sluift/SluiftComponent.cpp b/Sluift/SluiftComponent.cpp index ee09380..74728ee 100644 --- a/Sluift/SluiftComponent.cpp +++ b/Sluift/SluiftComponent.cpp @@ -38,11 +38,11 @@ SluiftComponent::SluiftComponent( SluiftComponent::~SluiftComponent() { delete tracer; delete component; } -void SluiftComponent::connect(const std::string& host, int port) { +void SluiftComponent::connect(const std::string& host, unsigned short port) { if (component->isActive()) { throw Lua::Exception("Component is already connecting or connected"); } disconnectedError = boost::optional<ComponentError>(); component->connect(host, port); diff --git a/Sluift/SluiftComponent.h b/Sluift/SluiftComponent.h index 9fc7101..586a94e 100644 --- a/Sluift/SluiftComponent.h +++ b/Sluift/SluiftComponent.h @@ -61,11 +61,11 @@ namespace Swift { Component* getComponent() { return component; } - void connect(const std::string& host, int port); + void connect(const std::string& host, unsigned short port); void waitConnected(int timeout); bool isConnected() const; void setTraceEnabled(bool b); template<typename REQUEST_TYPE> diff --git a/Sluift/component.cpp b/Sluift/component.cpp index f3c2e37..c1b1da4 100644 --- a/Sluift/component.cpp +++ b/Sluift/component.cpp @@ -94,17 +94,17 @@ static std::vector< std::shared_ptr<Payload> > getPayloadsFromTable(lua_State* L SLUIFT_LUA_FUNCTION(Component, async_connect) { SluiftComponent* component = getComponent(L); std::string host; - int port = 0; + unsigned short port = 0; if (lua_istable(L, 2)) { if (boost::optional<std::string> hostString = Lua::getStringField(L, 2, "host")) { host = *hostString; } if (boost::optional<int> portInt = Lua::getIntField(L, 2, "port")) { - port = *portInt; + port = boost::numeric_cast<unsigned short>(*portInt); } } component->connect(host, port); return 0; } diff --git a/Swiften/Base/URL.cpp b/Swiften/Base/URL.cpp index 3bc97ba..5c0f0d7 100644 --- a/Swiften/Base/URL.cpp +++ b/Swiften/Base/URL.cpp @@ -1,7 +1,7 @@ /* - * 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> @@ -9,11 +9,11 @@ #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; @@ -60,22 +60,22 @@ URL URL::fromString(const std::string& urlString) { 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 { @@ -85,11 +85,11 @@ URL URL::fromString(const std::string& urlString) { 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(); } } 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,7 +1,7 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -19,11 +19,11 @@ 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) { } @@ -49,11 +49,11 @@ class SWIFTEN_API URL { } /** * Port number */ - boost::optional<int> getPort() const { + boost::optional<unsigned short> getPort() const { return port; } /** * Path @@ -62,20 +62,20 @@ class SWIFTEN_API URL { 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,7 +1,7 @@ /* - * 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> @@ -64,29 +64,29 @@ class URLTest : public CppUnit::TestFixture { 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"); @@ -119,11 +119,11 @@ class URLTest : public CppUnit::TestFixture { 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"); @@ -135,21 +135,21 @@ class URLTest : public CppUnit::TestFixture { 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()); } @@ -157,11 +157,11 @@ class URLTest : public CppUnit::TestFixture { 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()); } @@ -169,11 +169,11 @@ class URLTest : public CppUnit::TestFixture { 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()); } @@ -181,11 +181,11 @@ class URLTest : public CppUnit::TestFixture { 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()); } @@ -193,11 +193,11 @@ class URLTest : public CppUnit::TestFixture { 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()); } @@ -205,11 +205,11 @@ class URLTest : public CppUnit::TestFixture { 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()); } @@ -217,11 +217,11 @@ class URLTest : public CppUnit::TestFixture { 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()); } } diff --git a/Swiften/Client/CoreClient.cpp b/Swiften/Client/CoreClient.cpp index 1de1d61..d3711cb 100644 --- a/Swiften/Client/CoreClient.cpp +++ b/Swiften/Client/CoreClient.cpp @@ -1,7 +1,7 @@ /* - * 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> @@ -83,20 +83,40 @@ void CoreClient::connect(const ClientOptions& o) { } 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; } @@ -106,11 +126,21 @@ void CoreClient::connect(const ClientOptions& o) { 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_); 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,7 +1,7 @@ /* - * 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> @@ -13,11 +13,11 @@ #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; } 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -26,11 +26,11 @@ namespace Swift { 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); @@ -38,11 +38,11 @@ namespace Swift { 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); @@ -51,11 +51,11 @@ namespace Swift { void handleTimeout(); private: std::string hostname; - int port; + unsigned short port; DomainNameResolver* resolver; ConnectionFactory* connectionFactory; TimerFactory* timerFactory; int timeoutMilliseconds; std::shared_ptr<Timer> timer; diff --git a/Swiften/Component/CoreComponent.cpp b/Swiften/Component/CoreComponent.cpp index 5b2277b..2d91c9c 100644 --- a/Swiften/Component/CoreComponent.cpp +++ b/Swiften/Component/CoreComponent.cpp @@ -41,11 +41,11 @@ CoreComponent::~CoreComponent() { 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(); diff --git a/Swiften/Component/CoreComponent.h b/Swiften/Component/CoreComponent.h index 1a487d2..7565d00 100644 --- a/Swiften/Component/CoreComponent.h +++ b/Swiften/Component/CoreComponent.h @@ -44,11 +44,11 @@ namespace Swift { 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); 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,7 +1,7 @@ /* - * 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> @@ -144,11 +144,11 @@ class ComponentConnectorTest : public CppUnit::TestFixture { 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; } 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -20,15 +20,15 @@ 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 { 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 @@ -3,11 +3,11 @@ * 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 @@ -28,11 +28,11 @@ 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 { 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,7 +1,7 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ /* @@ -112,11 +112,11 @@ 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) { @@ -162,11 +162,11 @@ void SOCKS5BytestreamServerManager::setupPortForwarding() { 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)); 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,7 +1,7 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -76,11 +76,11 @@ namespace Swift { 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; 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,7 +1,7 @@ /* - * 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> @@ -23,11 +23,11 @@ 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); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -28,11 +28,11 @@ namespace Swift { 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); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -16,11 +16,11 @@ 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); @@ -48,10 +48,10 @@ namespace Swift { } */ private: std::string name; - int port; + unsigned short port; ByteArray txtRecord; AvahiEntryGroup* group; }; } 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,7 +1,7 @@ /* - * 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> @@ -9,10 +9,11 @@ #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> @@ -34,11 +35,11 @@ BonjourQuerier::~BonjourQuerier() { 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); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -23,11 +23,11 @@ namespace Swift { 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); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -18,16 +18,25 @@ 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() { @@ -43,11 +52,16 @@ namespace Swift { 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); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -24,11 +24,11 @@ namespace Swift { 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -14,15 +14,15 @@ 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(); 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,7 +1,7 @@ /* - * 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> @@ -30,11 +30,11 @@ FakeDNSSDQuerier::~FakeDNSSDQuerier() { 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()); @@ -103,11 +103,11 @@ void FakeDNSSDQuerier::setServiceInfo(const DNSSDServiceID& id, const DNSSDResol 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; } } 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,7 +1,7 @@ /* - * Copyright (c) 2010-2017 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -37,11 +37,11 @@ namespace Swift { 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); @@ -49,11 +49,11 @@ namespace Swift { 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(); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -15,11 +15,11 @@ 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(); } @@ -31,9 +31,9 @@ namespace Swift { 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -29,11 +29,11 @@ namespace Swift { 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; diff --git a/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp b/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp index b79f184..b3328cd 100644 --- a/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp +++ b/Swiften/LinkLocal/LinkLocalServiceBrowser.cpp @@ -1,7 +1,7 @@ /* - * 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> @@ -63,11 +63,11 @@ bool LinkLocalServiceBrowser::hasError() const { 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(); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -33,11 +33,11 @@ namespace Swift { 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; diff --git a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp index 771251a..102b7f3 100644 --- a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp +++ b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp @@ -1,7 +1,7 @@ /* - * 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> @@ -80,11 +80,17 @@ LinkLocalServiceInfo LinkLocalServiceInfo::createFromTXTRecord(const ByteArray& } 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); } diff --git a/Swiften/LinkLocal/LinkLocalServiceInfo.h b/Swiften/LinkLocal/LinkLocalServiceInfo.h index 9f15c6e..eb65706 100644 --- a/Swiften/LinkLocal/LinkLocalServiceInfo.h +++ b/Swiften/LinkLocal/LinkLocalServiceInfo.h @@ -1,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -41,12 +41,12 @@ namespace Swift { 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; static LinkLocalServiceInfo createFromTXTRecord(const ByteArray& record); @@ -60,8 +60,8 @@ namespace Swift { 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..ab1ee0c 100644 --- a/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp +++ b/Swiften/LinkLocal/UnitTest/LinkLocalConnectorTest.cpp @@ -1,7 +1,7 @@ /* - * 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> @@ -51,11 +51,11 @@ class LinkLocalConnectorTest : public CppUnit::TestFixture { 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)); @@ -112,11 +112,11 @@ class LinkLocalConnectorTest : public CppUnit::TestFixture { 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) { LinkLocalService service( DNSSDServiceID("myname", "local."), DNSSDResolveServiceQuery::Result( "myname._presence._tcp.local", hostname, port, LinkLocalServiceInfo().toTXTRecord())); diff --git a/Swiften/Network/BoostConnectionServer.cpp b/Swiften/Network/BoostConnectionServer.cpp index f25f915..8db9656 100644 --- a/Swiften/Network/BoostConnectionServer.cpp +++ b/Swiften/Network/BoostConnectionServer.cpp @@ -1,7 +1,7 @@ /* - * 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> @@ -17,14 +17,14 @@ #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) { @@ -35,14 +35,14 @@ void BoostConnectionServer::start() { 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); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -21,15 +21,15 @@ 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(); @@ -38,20 +38,20 @@ namespace Swift { 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 @@ -17,14 +17,14 @@ 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 @@ -3,11 +3,11 @@ * 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 @@ -23,13 +23,13 @@ namespace Swift { 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/ChainedConnector.cpp b/Swiften/Network/ChainedConnector.cpp index ea55db3..94899ad 100644 --- a/Swiften/Network/ChainedConnector.cpp +++ b/Swiften/Network/ChainedConnector.cpp @@ -1,7 +1,7 @@ /* - * 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> @@ -16,11 +16,11 @@ 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), 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,7 +1,7 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -24,11 +24,11 @@ namespace Swift { 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(); @@ -40,11 +40,11 @@ namespace Swift { 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; 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 @@ -3,11 +3,11 @@ * 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 @@ -22,10 +22,10 @@ namespace Swift { 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 ca924bb..a0e6b23 100644 --- a/Swiften/Network/Connector.cpp +++ b/Swiften/Network/Connector.cpp @@ -15,11 +15,11 @@ #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; } @@ -120,11 +120,11 @@ void Connector::tryNextAddress() { 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)); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -28,11 +28,11 @@ namespace Swift { 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); /** @@ -44,11 +44,11 @@ namespace Swift { 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); @@ -61,11 +61,11 @@ namespace Swift { void handleTimeout(); private: std::string hostname; - int port; + unsigned short port; boost::optional<std::string> serviceLookupPrefix; DomainNameResolver* resolver; ConnectionFactory* connectionFactory; TimerFactory* timerFactory; int timeoutMilliseconds; diff --git a/Swiften/Network/DomainNameServiceQuery.cpp b/Swiften/Network/DomainNameServiceQuery.cpp index 548c837..5784dd7 100644 --- a/Swiften/Network/DomainNameServiceQuery.cpp +++ b/Swiften/Network/DomainNameServiceQuery.cpp @@ -41,20 +41,25 @@ void DomainNameServiceQuery::sortResults(std::vector<DomainNameServiceQuery::Res std::vector<int> weights; 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; }); - 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]); + 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -22,13 +22,13 @@ namespace Swift { 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(); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -15,12 +15,12 @@ #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; } 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,7 +1,7 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -18,15 +18,15 @@ 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 @@ -15,10 +15,12 @@ #include <stdio.h> #include <stdlib.h> #include <iostream> +#include <boost/numeric/conversion/cast.hpp> + #include <Swiften/Base/Log.h> namespace Swift { EnvironmentProxyProvider::EnvironmentProxyProvider() { @@ -36,19 +38,23 @@ HostAddressPort EnvironmentProxyProvider::getSOCKS5Proxy() const { } 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 @@ -3,11 +3,11 @@ * 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> @@ -19,10 +19,12 @@ extern "C" { #include <gconf/gconf-client.h> } +#include <boost/numeric/conversion/cast.hpp> + #include <Swiften/Base/Log.h> namespace Swift { GConfProxyProvider::GConfProxyProvider() { @@ -48,17 +50,21 @@ 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); } 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 @@ -3,11 +3,11 @@ * 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. */ @@ -34,11 +34,11 @@ 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) { 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 @@ -3,11 +3,11 @@ * 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. */ @@ -28,18 +28,18 @@ namespace Swift { 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); 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,7 +1,7 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ /* @@ -14,15 +14,15 @@ #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_); 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,7 +1,7 @@ /* - * Copyright (c) 2012-2017 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ /* @@ -22,21 +22,21 @@ namespace Swift { 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/HostAddressPort.cpp b/Swiften/Network/HostAddressPort.cpp index 401ddec..248be2d 100644 --- a/Swiften/Network/HostAddressPort.cpp +++ b/Swiften/Network/HostAddressPort.cpp @@ -1,18 +1,18 @@ /* - * 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(); diff --git a/Swiften/Network/HostAddressPort.h b/Swiften/Network/HostAddressPort.h index e42e1d1..14c7c66 100644 --- a/Swiften/Network/HostAddressPort.h +++ b/Swiften/Network/HostAddressPort.h @@ -1,7 +1,7 @@ /* - * Copyright (c) 2010 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -12,18 +12,18 @@ #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_; @@ -35,8 +35,8 @@ namespace Swift { 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 @@ -3,11 +3,11 @@ * 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> @@ -38,17 +38,19 @@ static HostAddressPort getFromDictionary(CFDictionaryRef dict, CFStringRef enabl 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; diff --git a/Swiften/Network/MiniUPnPInterface.cpp b/Swiften/Network/MiniUPnPInterface.cpp index 2c61ad3..af3b67c 100644 --- a/Swiften/Network/MiniUPnPInterface.cpp +++ b/Swiften/Network/MiniUPnPInterface.cpp @@ -3,11 +3,11 @@ * 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> @@ -71,11 +71,11 @@ boost::optional<HostAddress> MiniUPnPInterface::getPublicIP() { 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); 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,7 +1,7 @@ /* - * 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 @@ -21,11 +21,11 @@ namespace Swift { 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..8ab26d4 100644 --- a/Swiften/Network/NATPMPInterface.cpp +++ b/Swiften/Network/NATPMPInterface.cpp @@ -3,11 +3,11 @@ * 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> @@ -72,17 +72,17 @@ boost::optional<HostAddress> NATPMPInterface::getPublicIP() { 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()), + mapping.getLocalPort(), + mapping.getPublicPort(), boost::numeric_cast<uint32_t>(mapping.getLeaseInSeconds())) < 0) { SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl; return boost::optional<NATPortMapping>(); } 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,7 +1,7 @@ /* - * 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 @@ -21,11 +21,11 @@ namespace Swift { 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..b68052d 100644 --- a/Swiften/Network/NATPortMapping.h +++ b/Swiften/Network/NATPortMapping.h @@ -21,20 +21,20 @@ namespace Swift { 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, int 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; @@ -43,11 +43,11 @@ namespace Swift { int getLeaseInSeconds() const { return leaseInSeconds; } private: - int publicPort; - int localPort; + unsigned short publicPort; + unsigned short localPort; Protocol protocol; int 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,7 +1,7 @@ /* - * 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 @@ -17,9 +17,9 @@ namespace Swift { 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 @@ -3,11 +3,11 @@ * 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 @@ -24,12 +24,12 @@ namespace Swift { enum Protocol { TCP, UDP }; - unsigned int publicPort; - unsigned int localPort; + unsigned short publicPort; + unsigned short localPort; Protocol protocol; unsigned long leaseInSeconds; }; public: 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,7 +1,7 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -18,9 +18,9 @@ namespace Swift { 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 @@ -19,11 +19,11 @@ namespace Swift { 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,7 +1,7 @@ /* - * 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> @@ -70,14 +70,14 @@ 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,7 +1,7 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -14,12 +14,12 @@ namespace Swift { 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,7 +1,7 @@ /* - * 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> @@ -127,39 +127,46 @@ void PlatformDomainNameServiceQuery::runBlocking() { 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(); 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 @@ -82,11 +82,11 @@ class PlatformNATTraversalGetPublicIPRequest : public NATTraversalGetPublicIPReq } }; 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() { } @@ -97,16 +97,16 @@ class PlatformNATTraversalForwardPortRequest : public NATTraversalForwardPortReq 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) { @@ -179,15 +179,15 @@ NATTraversalInterface* PlatformNATTraversalWorker::getNATTraversalInterface() co 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() { 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 @@ -3,11 +3,11 @@ * 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 @@ -42,12 +42,12 @@ namespace Swift { 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(); 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,7 +1,7 @@ /* - * 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> @@ -18,11 +18,11 @@ 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), 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,7 +1,7 @@ /* - * Copyright (c) 2012-2017 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -18,11 +18,11 @@ 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(); @@ -53,11 +53,11 @@ namespace Swift { 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 @@ -3,11 +3,11 @@ * 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> @@ -25,11 +25,11 @@ 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() { 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 @@ -3,11 +3,11 @@ * 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 @@ -22,16 +22,16 @@ namespace Swift { 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: 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 @@ -14,11 +14,11 @@ #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 @@ -3,11 +3,11 @@ * 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 @@ -21,17 +21,17 @@ 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 5a38fc4..eca6687 100644 --- a/Swiften/Network/StaticDomainNameResolver.cpp +++ b/Swiften/Network/StaticDomainNameResolver.cpp @@ -1,7 +1,7 @@ /* - * 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> @@ -107,11 +107,11 @@ void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, c 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); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once @@ -29,11 +29,11 @@ namespace Swift { 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; } diff --git a/Swiften/Network/UnitTest/ConnectorTest.cpp b/Swiften/Network/UnitTest/ConnectorTest.cpp index 658aaf7..065911d 100644 --- a/Swiften/Network/UnitTest/ConnectorTest.cpp +++ b/Swiften/Network/UnitTest/ConnectorTest.cpp @@ -1,7 +1,7 @@ /* - * 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> @@ -90,22 +90,22 @@ class ConnectorTest : public CppUnit::TestFixture { 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()); @@ -326,11 +326,11 @@ class ConnectorTest : public CppUnit::TestFixture { 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; } 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <memory> @@ -419,11 +419,11 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture { }; private: std::string proxyHost; HostAddressPort proxyHostAddress; - int proxyPort; + unsigned short proxyPort; HostAddressPort host; DummyEventLoop* eventLoop; StaticDomainNameResolver* resolver; MockConnectionFactory* connectionFactory; TimerFactory* timerFactory; 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 @@ -15,10 +15,11 @@ #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> @@ -75,15 +76,15 @@ HostAddressPort WindowsProxyProvider::getSOCKS5Proxy() const { 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; } 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,14 +1,15 @@ /* - * 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) { } @@ -21,11 +22,13 @@ void BytestreamsParser::handleStartElement(const std::string& element, const std 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") { 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 @@ -3,18 +3,19 @@ * 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 { @@ -38,14 +39,14 @@ namespace Swift { } 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")); 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 @@ -3,18 +3,19 @@ * 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) { @@ -25,19 +26,18 @@ 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); 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,15 +1,16 @@ /* - * 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> @@ -72,11 +73,21 @@ int main(int, char**) { 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); 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,7 +1,7 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #include <algorithm> @@ -177,23 +177,23 @@ class DomainNameResolverTest : public CppUnit::TestFixture { 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() { |
Swift