diff options
Diffstat (limited to 'Swiften/Network')
61 files changed, 387 insertions, 293 deletions
diff --git a/Swiften/Network/BOSHConnection.cpp b/Swiften/Network/BOSHConnection.cpp index b4ffa7d..1312a3e 100644 --- a/Swiften/Network/BOSHConnection.cpp +++ b/Swiften/Network/BOSHConnection.cpp @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2011-2017 Isode Limited. + * Copyright (c) 2011-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -27,6 +27,7 @@ #include <Swiften/StreamStack/DummyStreamLayer.h> #include <Swiften/StreamStack/TLSLayer.h> #include <Swiften/TLS/TLSContext.h> +#include <Swiften/TLS/TLSContextFactory.h> #include <Swiften/TLS/TLSOptions.h> namespace Swift { @@ -42,7 +43,8 @@ BOSHConnection::BOSHConnection(const URL& boshURL, Connector::ref connector, XML connectionReady_(false) { if (boshURL_.getScheme() == "https") { - tlsLayer_ = std::make_shared<TLSLayer>(tlsContextFactory, tlsOptions); + auto tlsContext = tlsContextFactory->createTLSContext(tlsOptions); + tlsLayer_ = std::make_shared<TLSLayer>(std::move(tlsContext)); // The following dummyLayer_ is needed as the TLSLayer will pass the decrypted data to its parent layer. // The dummyLayer_ will serve as the parent layer. dummyLayer_ = std::make_shared<DummyStreamLayer>(tlsLayer_.get()); @@ -72,27 +74,27 @@ void BOSHConnection::cancelConnector() { } void BOSHConnection::handleTLSConnected() { - SWIFT_LOG(debug) << std::endl; + SWIFT_LOG(debug); onConnectFinished(false); } void BOSHConnection::handleTLSApplicationDataRead(const SafeByteArray& data) { - SWIFT_LOG(debug) << std::endl; + SWIFT_LOG(debug); handleDataRead(std::make_shared<SafeByteArray>(data)); } void BOSHConnection::handleTLSNetowrkDataWriteRequest(const SafeByteArray& data) { - SWIFT_LOG(debug) << std::endl; + SWIFT_LOG(debug); connection_->write(data); } void BOSHConnection::handleRawDataRead(std::shared_ptr<SafeByteArray> data) { - SWIFT_LOG(debug) << std::endl; + SWIFT_LOG(debug); tlsLayer_->handleDataRead(*data.get()); } -void BOSHConnection::handleTLSError(std::shared_ptr<TLSError> /* error */) { - +void BOSHConnection::handleTLSError(std::shared_ptr<TLSError> error) { + SWIFT_LOG(debug) << (error ? error->getMessage() : "Unknown TLS error"); } void BOSHConnection::writeData(const SafeByteArray& data) { @@ -121,7 +123,7 @@ void BOSHConnection::restartStream() { bool BOSHConnection::setClientCertificate(CertificateWithKey::ref cert) { if (tlsLayer_) { - SWIFT_LOG(debug) << "set client certificate" << std::endl; + SWIFT_LOG(debug) << "set client certificate"; return tlsLayer_->setClientCertificate(cert); } else { @@ -209,7 +211,7 @@ void BOSHConnection::write(const SafeByteArray& data, bool streamRestart, bool t writeData(safeHeader); pending_ = true; - SWIFT_LOG(debug) << "write data: " << safeByteArrayToString(safeHeader) << std::endl; + SWIFT_LOG(debug) << "write data: " << safeByteArrayToString(safeHeader); } void BOSHConnection::handleConnectFinished(Connection::ref connection) { @@ -273,7 +275,7 @@ void BOSHConnection::startStream(const std::string& to, unsigned long long rid) SafeByteArray safeHeader = createSafeByteArray(header.str()); onBOSHDataWritten(safeHeader); writeData(safeHeader); - SWIFT_LOG(debug) << "write stream header: " << safeByteArrayToString(safeHeader) << std::endl; + SWIFT_LOG(debug) << "write stream header: " << safeByteArrayToString(safeHeader); } void BOSHConnection::handleDataRead(std::shared_ptr<SafeByteArray> data) { diff --git a/Swiften/Network/BOSHConnection.h b/Swiften/Network/BOSHConnection.h index c492ac4..f0a946a 100644 --- a/Swiften/Network/BOSHConnection.h +++ b/Swiften/Network/BOSHConnection.h @@ -31,7 +31,7 @@ namespace Swift { class XMLParserFactory; class TLSContextFactory; class TLSLayer; - struct TLSOptions; + class TLSOptions; class HighLayer; class SWIFTEN_API BOSHError : public SessionStream::SessionStreamError { diff --git a/Swiften/Network/BOSHConnectionPool.cpp b/Swiften/Network/BOSHConnectionPool.cpp index 8a75e81..3a79a16 100644 --- a/Swiften/Network/BOSHConnectionPool.cpp +++ b/Swiften/Network/BOSHConnectionPool.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -266,7 +266,7 @@ std::shared_ptr<BOSHConnection> BOSHConnectionPool::createConnection() { if (boshURL.getScheme() == "https") { bool success = connection->setClientCertificate(clientCertificate); - SWIFT_LOG(debug) << "setClientCertificate, success: " << success << std::endl; + SWIFT_LOG(debug) << "setClientCertificate, success: " << success; } connection->connect(); diff --git a/Swiften/Network/BoostConnection.cpp b/Swiften/Network/BoostConnection.cpp index 0de7b25..6ae6bf6 100644 --- a/Swiften/Network/BoostConnection.cpp +++ b/Swiften/Network/BoostConnection.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -14,7 +14,6 @@ #include <boost/asio/placeholders.hpp> #include <boost/asio/write.hpp> #include <boost/bind.hpp> -#include <boost/numeric/conversion/cast.hpp> #include <Swiften/Base/Algorithm.h> #include <Swiften/Base/ByteArray.h> @@ -64,7 +63,7 @@ void BoostConnection::listen() { void BoostConnection::connect(const HostAddressPort& addressPort) { boost::asio::ip::tcp::endpoint endpoint( - boost::asio::ip::address::from_string(addressPort.getAddress().toString()), boost::numeric_cast<unsigned short>(addressPort.getPort())); + boost::asio::ip::address::from_string(addressPort.getAddress().toString()), addressPort.getPort()); socket_.async_connect( endpoint, boost::bind(&BoostConnection::handleConnectFinished, shared_from_this(), boost::asio::placeholders::error)); @@ -108,7 +107,7 @@ void BoostConnection::doWrite(const SafeByteArray& data) { } void BoostConnection::handleConnectFinished(const boost::system::error_code& error) { - SWIFT_LOG(debug) << "Connect finished: " << error << std::endl; + SWIFT_LOG(debug) << "Connect finished: " << error; if (!error) { eventLoop->postEvent(boost::bind(boost::ref(onConnectFinished), false), shared_from_this()); doRead(); @@ -127,7 +126,7 @@ void BoostConnection::doRead() { } void BoostConnection::handleSocketRead(const boost::system::error_code& error, size_t bytesTransferred) { - SWIFT_LOG(debug) << "Socket read " << error << std::endl; + SWIFT_LOG(debug) << "Socket read " << error; if (!error) { readBuffer_->resize(bytesTransferred); eventLoop->postEvent(boost::bind(boost::ref(onDataRead), readBuffer_), shared_from_this()); @@ -142,7 +141,7 @@ void BoostConnection::handleSocketRead(const boost::system::error_code& error, s } void BoostConnection::handleDataWritten(const boost::system::error_code& error) { - SWIFT_LOG(debug) << "Data written " << error << std::endl; + SWIFT_LOG(debug) << "Data written " << error; if (!error) { eventLoop->postEvent(boost::ref(onDataWritten), shared_from_this()); } diff --git a/Swiften/Network/BoostConnectionServer.cpp b/Swiften/Network/BoostConnectionServer.cpp index 34b5799..dc05172 100644 --- a/Swiften/Network/BoostConnectionServer.cpp +++ b/Swiften/Network/BoostConnectionServer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -19,10 +19,10 @@ 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() { @@ -37,16 +37,16 @@ boost::optional<BoostConnectionServer::Error> BoostConnectionServer::tryStart() assert(!acceptor_); boost::asio::ip::tcp::endpoint endpoint; if (address_.isValid()) { - endpoint = boost::asio::ip::tcp::endpoint(address_.getRawAddress(), boost::numeric_cast<unsigned short>(port_)); + endpoint = boost::asio::ip::tcp::endpoint(address_.getRawAddress(), port_); } else { - endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), boost::numeric_cast<unsigned short>(port_)); + endpoint = boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), port_); } acceptor_ = new boost::asio::ip::tcp::acceptor(*ioService_, endpoint); if (endpoint.protocol() == boost::asio::ip::tcp::v6()) { boost::system::error_code ec; acceptor_->set_option(boost::asio::ip::v6_only(false), ec); - SWIFT_LOG_ASSERT(ec, warning) << "IPv4/IPv6 dual-stack support is not supported on this platform." << std::endl; + SWIFT_LOG_ASSERT(ec, warning) << "IPv4/IPv6 dual-stack support is not supported on this platform."; } acceptNextConnection(); } @@ -58,6 +58,9 @@ boost::optional<BoostConnectionServer::Error> BoostConnectionServer::tryStart() return UnknownError; } } + catch (const boost::numeric::bad_numeric_cast&) { + return UnknownError; + } return boost::optional<Error>(); } 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,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -23,11 +23,11 @@ namespace Swift { 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)); } @@ -40,8 +40,8 @@ namespace Swift { 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(); @@ -49,7 +49,7 @@ namespace Swift { 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 @@ -19,11 +19,11 @@ 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 @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -25,9 +25,9 @@ namespace Swift { 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; diff --git a/Swiften/Network/BoostNetworkFactories.cpp b/Swiften/Network/BoostNetworkFactories.cpp index 9fef73c..13a7960 100644 --- a/Swiften/Network/BoostNetworkFactories.cpp +++ b/Swiften/Network/BoostNetworkFactories.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -44,9 +44,9 @@ BoostNetworkFactories::BoostNetworkFactories(EventLoop* eventLoop, std::shared_p idnConverter = PlatformIDNConverter::create(); #ifdef USE_UNBOUND // TODO: What to do about idnConverter. - domainNameResolver = new UnboundDomainNameResolver(idnConverter, ioServiceThread.getIOService(), eventLoop); + domainNameResolver = new UnboundDomainNameResolver(idnConverter.get(), ioServiceThread.getIOService(), eventLoop); #else - domainNameResolver = new PlatformDomainNameResolver(idnConverter, eventLoop); + domainNameResolver = new PlatformDomainNameResolver(idnConverter.get(), eventLoop); #endif cryptoProvider = PlatformCryptoProvider::create(); } @@ -54,7 +54,6 @@ BoostNetworkFactories::BoostNetworkFactories(EventLoop* eventLoop, std::shared_p BoostNetworkFactories::~BoostNetworkFactories() { delete cryptoProvider; delete domainNameResolver; - delete idnConverter; delete proxyProvider; delete tlsFactories; delete xmlParserFactory; diff --git a/Swiften/Network/BoostNetworkFactories.h b/Swiften/Network/BoostNetworkFactories.h index 2bf8d33..33a3584 100644 --- a/Swiften/Network/BoostNetworkFactories.h +++ b/Swiften/Network/BoostNetworkFactories.h @@ -1,11 +1,13 @@ /* - * Copyright (c) 2010-2017 Isode Limited. + * Copyright (c) 2010-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ #pragma once +#include <memory> + #include <Swiften/Base/API.h> #include <Swiften/Network/BoostIOServiceThread.h> #include <Swiften/Network/NetworkFactories.h> @@ -68,7 +70,7 @@ namespace Swift { } virtual IDNConverter* getIDNConverter() const override { - return idnConverter; + return idnConverter.get(); } virtual CryptoProvider* getCryptoProvider() const override { @@ -87,7 +89,7 @@ namespace Swift { PlatformTLSFactories* tlsFactories; ProxyProvider* proxyProvider; EventLoop* eventLoop; - IDNConverter* idnConverter; + std::unique_ptr<IDNConverter> idnConverter; CryptoProvider* cryptoProvider; }; } diff --git a/Swiften/Network/ChainedConnector.cpp b/Swiften/Network/ChainedConnector.cpp index ea55db3..a9210ba 100644 --- a/Swiften/Network/ChainedConnector.cpp +++ b/Swiften/Network/ChainedConnector.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -18,7 +18,7 @@ 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, @@ -45,7 +45,7 @@ void ChainedConnector::setTimeoutMilliseconds(int milliseconds) { } void ChainedConnector::start() { - SWIFT_LOG(debug) << "Starting queued connector for " << hostname << std::endl; + SWIFT_LOG(debug) << "Starting queued connector for " << hostname; connectionFactoryQueue = std::deque<ConnectionFactory*>(connectionFactories.begin(), connectionFactories.end()); tryNextConnectionFactory(); @@ -63,12 +63,12 @@ void ChainedConnector::stop() { void ChainedConnector::tryNextConnectionFactory() { assert(!currentConnector); if (connectionFactoryQueue.empty()) { - SWIFT_LOG(debug) << "No more connection factories" << std::endl; + SWIFT_LOG(debug) << "No more connection factories"; finish(std::shared_ptr<Connection>(), lastError); } else { ConnectionFactory* connectionFactory = connectionFactoryQueue.front(); - SWIFT_LOG(debug) << "Trying next connection factory: " << typeid(*connectionFactory).name() << std::endl; + SWIFT_LOG(debug) << "Trying next connection factory: " << typeid(*connectionFactory).name(); connectionFactoryQueue.pop_front(); currentConnector = Connector::create(hostname, port, serviceLookupPrefix, resolver, connectionFactory, timerFactory); currentConnector->setTimeoutMilliseconds(timeoutMilliseconds); @@ -78,7 +78,7 @@ void ChainedConnector::tryNextConnectionFactory() { } void ChainedConnector::handleConnectorFinished(std::shared_ptr<Connection> connection, std::shared_ptr<Error> error) { - SWIFT_LOG(debug) << "Connector finished" << std::endl; + SWIFT_LOG(debug) << "Connector finished"; currentConnector->onConnectFinished.disconnect(boost::bind(&ChainedConnector::handleConnectorFinished, this, _1, _2)); lastError = error; currentConnector.reset(); 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,5 +1,5 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -26,7 +26,7 @@ namespace Swift { 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); @@ -42,7 +42,7 @@ namespace Swift { private: std::string hostname; - int port; + unsigned short port; boost::optional<std::string> serviceLookupPrefix; DomainNameResolver* resolver; std::vector<ConnectionFactory*> connectionFactories; 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 @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -24,8 +24,8 @@ namespace Swift { 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 457d8a9..e27b95d 100644 --- a/Swiften/Network/Connector.cpp +++ b/Swiften/Network/Connector.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -17,7 +17,7 @@ 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) { @@ -25,17 +25,17 @@ void Connector::setTimeoutMilliseconds(int milliseconds) { } void Connector::start() { - SWIFT_LOG(debug) << "Starting connector for " << hostname << std::endl; + SWIFT_LOG(debug) << "Starting connector for " << hostname; assert(!currentConnection); assert(!serviceQuery); assert(!timer); - queriedAllServices = false; auto hostAddress = HostAddress::fromString(hostname); if (timeoutMilliseconds > 0) { timer = timerFactory->createTimer(timeoutMilliseconds); timer->onTick.connect(boost::bind(&Connector::handleTimeout, shared_from_this())); } if (serviceLookupPrefix) { + queriedAllServices = false; serviceQuery = resolver->createServiceQuery(*serviceLookupPrefix, hostname); serviceQuery->onResult.connect(boost::bind(&Connector::handleServiceQueryResult, shared_from_this(), _1)); serviceQuery->run(); @@ -66,7 +66,7 @@ void Connector::queryAddress(const std::string& hostname) { } void Connector::handleServiceQueryResult(const std::vector<DomainNameServiceQuery::Result>& result) { - SWIFT_LOG(debug) << result.size() << " SRV result(s)" << std::endl; + SWIFT_LOG(debug) << result.size() << " SRV result(s)"; serviceQueryResults = std::deque<DomainNameServiceQuery::Result>(result.begin(), result.end()); serviceQuery.reset(); if (!serviceQueryResults.empty()) { @@ -77,23 +77,23 @@ void Connector::handleServiceQueryResult(const std::vector<DomainNameServiceQuer void Connector::tryNextServiceOrFallback() { if (queriedAllServices) { - SWIFT_LOG(debug) << "Queried all services" << std::endl; + SWIFT_LOG(debug) << "Queried all services"; finish(std::shared_ptr<Connection>()); } else if (serviceQueryResults.empty()) { - SWIFT_LOG(debug) << "Falling back on A resolution" << std::endl; + SWIFT_LOG(debug) << "Falling back on A resolution"; // Fall back on simple address resolving queriedAllServices = true; queryAddress(hostname); } else { - SWIFT_LOG(debug) << "Querying next address" << std::endl; + SWIFT_LOG(debug) << "Querying next address"; queryAddress(serviceQueryResults.front().hostname); } } void Connector::handleAddressQueryResult(const std::vector<HostAddress>& addresses, boost::optional<DomainNameResolveError> error) { - SWIFT_LOG(debug) << addresses.size() << " addresses" << std::endl; + SWIFT_LOG(debug) << addresses.size() << " addresses"; addressQuery.reset(); if (error || addresses.empty()) { if (!serviceQueryResults.empty()) { @@ -110,7 +110,7 @@ void Connector::handleAddressQueryResult(const std::vector<HostAddress>& address void Connector::tryNextAddress() { if (addressQueryResults.empty()) { - SWIFT_LOG(debug) << "Done trying addresses. Moving on." << std::endl; + SWIFT_LOG(debug) << "Done trying addresses. Moving on."; // Done trying all addresses. Move on to the next host. if (!serviceQueryResults.empty()) { serviceQueryResults.pop_front(); @@ -118,11 +118,11 @@ void Connector::tryNextAddress() { tryNextServiceOrFallback(); } else { - SWIFT_LOG(debug) << "Trying next address" << std::endl; + SWIFT_LOG(debug) << "Trying next address"; 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; } @@ -133,7 +133,7 @@ void Connector::tryNextAddress() { void Connector::tryConnect(const HostAddressPort& target) { assert(!currentConnection); - SWIFT_LOG(debug) << "Trying to connect to " << target.getAddress().toString() << ":" << target.getPort() << std::endl; + SWIFT_LOG(debug) << "Trying to connect to " << target.getAddress().toString() << ":" << target.getPort(); currentConnection = connectionFactory->createConnection(); currentConnection->onConnectFinished.connect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1)); currentConnection->connect(target); @@ -143,11 +143,18 @@ void Connector::tryConnect(const HostAddressPort& target) { } void Connector::handleConnectionConnectFinished(bool error) { - SWIFT_LOG(debug) << "ConnectFinished: " << (error ? "error" : "success") << std::endl; + SWIFT_LOG(debug) << "ConnectFinished: " << (error ? "error" : "success"); if (timer) { timer->stop(); timer.reset(); } + if (!currentConnection) { + // We've hit a race condition where multiple finisheds were on the eventloop queue at once. + // This is particularly likely on macOS where the hourly momentary wakeup while asleep + // can cause both a timeout and an onConnectFinished to be queued sequentially (SWIFT-232). + // Let the first one process as normal, but ignore the second. + return; + } currentConnection->onConnectFinished.disconnect(boost::bind(&Connector::handleConnectionConnectFinished, shared_from_this(), _1)); if (error) { currentConnection.reset(); @@ -188,7 +195,8 @@ void Connector::finish(std::shared_ptr<Connection> connection) { } void Connector::handleTimeout() { - SWIFT_LOG(debug) << "Timeout" << std::endl; + SWIFT_LOG(debug) << "Timeout"; + SWIFT_LOG_ASSERT(currentConnection, error) << "Connection not valid but triggered a timeout"; handleConnectionConnectFinished(true); } 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,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -30,7 +30,7 @@ namespace Swift { 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)); } @@ -46,7 +46,7 @@ namespace Swift { 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); @@ -63,7 +63,7 @@ namespace Swift { private: std::string hostname; - int port; + unsigned short port; boost::optional<std::string> serviceLookupPrefix; DomainNameResolver* resolver; ConnectionFactory* connectionFactory; diff --git a/Swiften/Network/DomainNameServiceQuery.cpp b/Swiften/Network/DomainNameServiceQuery.cpp index 708bbce..5784dd7 100644 --- a/Swiften/Network/DomainNameServiceQuery.cpp +++ b/Swiften/Network/DomainNameServiceQuery.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -11,15 +11,11 @@ #include <iterator> #include <numeric> -#include <boost/lambda/bind.hpp> -#include <boost/lambda/lambda.hpp> #include <boost/numeric/conversion/cast.hpp> -#include <boost/typeof/typeof.hpp> #include <Swiften/Base/RandomGenerator.h> using namespace Swift; -namespace lambda = boost::lambda; namespace { struct ResultPriorityComparator { @@ -43,19 +39,25 @@ void DomainNameServiceQuery::sortResults(std::vector<DomainNameServiceQuery::Res std::vector<DomainNameServiceQuery::Result>::iterator next = std::upper_bound(i, queries.end(), *i, comparator); if (std::distance(i, next) > 1) { std::vector<int> weights; - std::transform(i, next, std::back_inserter(weights), - /* easy hack to account for '0' weights getting at least some weight */ - lambda::bind(&Result::weight, lambda::_1) + 1); - for (int j = 0; j < boost::numeric_cast<int>(weights.size() - 1); ++j) { - std::vector<int> cumulativeWeights; - std::partial_sum( - weights.begin() + j, - weights.end(), - std::back_inserter(cumulativeWeights)); - int randomNumber = generator.generateRandomInteger(cumulativeWeights.back()); - BOOST_AUTO(selectedIndex, std::lower_bound(cumulativeWeights.begin(), cumulativeWeights.end(), randomNumber) - cumulativeWeights.begin()); - std::swap(i[j], i[j + selectedIndex]); - std::swap(weights.begin()[j], weights.begin()[j + selectedIndex]); + std::transform(i, next, std::back_inserter(weights), [](const DomainNameServiceQuery::Result& result) { + /* easy hack to account for '0' weights getting at least some weight */ + return result.weight + 1; + }); + try { + for (int j = 0; j < boost::numeric_cast<int>(weights.size()) - 1; ++j) { + std::vector<int> cumulativeWeights; + std::partial_sum( + weights.begin() + j, + weights.end(), + std::back_inserter(cumulativeWeights)); + int randomNumber = generator.generateRandomInteger(cumulativeWeights.back()); + auto selectedIndex = std::lower_bound(cumulativeWeights.begin(), cumulativeWeights.end(), randomNumber) - cumulativeWeights.begin(); + std::swap(i[j], i[j + selectedIndex]); + std::swap(weights.begin()[j], weights.begin()[j + selectedIndex]); + } + } + catch (const boost::numeric::bad_numeric_cast&) { + // In the unlikely event of weights.size() being too large, use the list as-is. } } i = next; diff --git a/Swiften/Network/DomainNameServiceQuery.h b/Swiften/Network/DomainNameServiceQuery.h index b27f32e..1631b99 100644 --- a/Swiften/Network/DomainNameServiceQuery.h +++ b/Swiften/Network/DomainNameServiceQuery.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -24,9 +24,9 @@ namespace Swift { 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; }; 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,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -17,8 +17,8 @@ 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 { 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,5 +1,5 @@ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -20,11 +20,11 @@ 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); } diff --git a/Swiften/Network/EnvironmentProxyProvider.cpp b/Swiften/Network/EnvironmentProxyProvider.cpp index 8edb136..6fbf373 100644 --- a/Swiften/Network/EnvironmentProxyProvider.cpp +++ b/Swiften/Network/EnvironmentProxyProvider.cpp @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2016 Isode Limited. + * Copyright (c) 2016-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -17,6 +17,8 @@ #include <iostream> +#include <boost/numeric/conversion/cast.hpp> + #include <Swiften/Base/Log.h> namespace Swift { @@ -24,7 +26,7 @@ namespace Swift { EnvironmentProxyProvider::EnvironmentProxyProvider() { socksProxy = getFromEnv("all_proxy", "socks"); httpProxy = getFromEnv("http_proxy", "http"); - SWIFT_LOG(debug) << "Environment: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl; + SWIFT_LOG(debug) << "Environment: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString(); } HostAddressPort EnvironmentProxyProvider::getHTTPConnectProxy() const { @@ -38,7 +40,7 @@ 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); @@ -46,7 +48,11 @@ HostAddressPort EnvironmentProxyProvider::getFromEnv(const char* envVarName, std 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(':')); } diff --git a/Swiften/Network/GConfProxyProvider.cpp b/Swiften/Network/GConfProxyProvider.cpp index eade450..a2f8adc 100644 --- a/Swiften/Network/GConfProxyProvider.cpp +++ b/Swiften/Network/GConfProxyProvider.cpp @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2016-2017 Isode Limited. + * Copyright (c) 2016-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -21,6 +21,8 @@ extern "C" { #include <gconf/gconf-client.h> } +#include <boost/numeric/conversion/cast.hpp> + #include <Swiften/Base/Log.h> namespace Swift { @@ -37,7 +39,7 @@ GConfProxyProvider::GConfProxyProvider() { socksProxy = getFromGConf("/system/proxy/socks_host", "/system/proxy/socks_port"); httpProxy = getFromGConf("/system/http_proxy/host", "/system/http_proxy/port"); - SWIFT_LOG(debug) << "GConf: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString() << std::endl; + SWIFT_LOG(debug) << "GConf: SOCKS5 => " << socksProxy.toString() << "; HTTP Connect => " << httpProxy.toString(); } HostAddressPort GConfProxyProvider::getHTTPConnectProxy() const { @@ -50,13 +52,17 @@ HostAddressPort GConfProxyProvider::getSOCKS5Proxy() const { 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); diff --git a/Swiften/Network/HTTPConnectProxiedConnection.cpp b/Swiften/Network/HTTPConnectProxiedConnection.cpp index b5e521b..e63b8e2 100644 --- a/Swiften/Network/HTTPConnectProxiedConnection.cpp +++ b/Swiften/Network/HTTPConnectProxiedConnection.cpp @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -36,7 +36,7 @@ HTTPConnectProxiedConnection::HTTPConnectProxiedConnection( 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), @@ -77,7 +77,7 @@ void HTTPConnectProxiedConnection::initializeProxy() { nextHTTPRequestHeaders_.clear(); } append(data, createSafeByteArray("\r\n")); - SWIFT_LOG(debug) << "HTTP Proxy send headers: " << byteArrayToString(ByteArray(data.begin(), data.end())) << std::endl; + SWIFT_LOG(debug) << "HTTP Proxy send headers: " << byteArrayToString(ByteArray(data.begin(), data.end())); write(data); } @@ -111,7 +111,7 @@ void HTTPConnectProxiedConnection::sendHTTPRequest(const std::string& statusLine void HTTPConnectProxiedConnection::handleProxyInitializeData(std::shared_ptr<SafeByteArray> data) { std::string dataString = byteArrayToString(ByteArray(data->begin(), data->end())); - SWIFT_LOG(debug) << data << std::endl; + SWIFT_LOG(debug) << data; httpResponseBuffer_.append(dataString); std::string statusLine; @@ -141,17 +141,17 @@ void HTTPConnectProxiedConnection::handleProxyInitializeData(std::shared_ptr<Saf if (tmp.size() > 1) { try { int status = boost::lexical_cast<int>(tmp[1]); - SWIFT_LOG(debug) << "Proxy Status: " << status << std::endl; + SWIFT_LOG(debug) << "Proxy Status: " << status; if (status / 100 == 2) { // all 2XX states are OK setProxyInitializeFinished(true); } else { - SWIFT_LOG(debug) << "HTTP Proxy returned an error: " << httpResponseBuffer_ << std::endl; + SWIFT_LOG(debug) << "HTTP Proxy returned an error: " << httpResponseBuffer_; setProxyInitializeFinished(false); } } catch (boost::bad_lexical_cast&) { - SWIFT_LOG(warning) << "Unexpected response: " << tmp[1] << std::endl; + SWIFT_LOG(warning) << "Unexpected response: " << tmp[1]; setProxyInitializeFinished(false); } } 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 @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2011-2017 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -30,14 +30,14 @@ namespace Swift { 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); 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,5 +1,5 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -16,11 +16,11 @@ 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() { 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,5 +1,5 @@ /* - * Copyright (c) 2012-2017 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -24,8 +24,8 @@ namespace Swift { 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(); @@ -34,7 +34,7 @@ namespace Swift { ConnectionFactory* connectionFactory_; TimerFactory* timerFactory_; std::string proxyHost_; - int proxyPort_; + unsigned short proxyPort_; SafeString authID_; SafeString authPassword_; std::shared_ptr<HTTPTrafficFilter> httpTrafficFilter_; diff --git a/Swiften/Network/HostAddress.cpp b/Swiften/Network/HostAddress.cpp index 6eca80b..e82f433 100644 --- a/Swiften/Network/HostAddress.cpp +++ b/Swiften/Network/HostAddress.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -43,7 +43,7 @@ std::string HostAddress::toString() const { addressString = address_.to_string(errorCode); if (errorCode) { - SWIFT_LOG(debug) << "error: " << errorCode.message() << std::endl; + SWIFT_LOG(debug) << "error: " << errorCode.message(); } return addressString; diff --git a/Swiften/Network/HostAddress.h b/Swiften/Network/HostAddress.h index e4ddffb..7a22cf4 100644 --- a/Swiften/Network/HostAddress.h +++ b/Swiften/Network/HostAddress.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -27,6 +27,10 @@ namespace Swift { return address_ == o.address_; } + bool operator<(const HostAddress& o) const { + return address_ < o.address_; + } + bool isValid() const; bool isLocalhost() const; diff --git a/Swiften/Network/HostAddressPort.cpp b/Swiften/Network/HostAddressPort.cpp index 76c276e..248be2d 100644 --- a/Swiften/Network/HostAddressPort.cpp +++ b/Swiften/Network/HostAddressPort.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -10,7 +10,7 @@ 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) { @@ -21,7 +21,7 @@ HostAddressPort::HostAddressPort(const boost::asio::ip::tcp::endpoint& endpoint) std::string HostAddressPort::toString() const { std::string portAsString; try { - portAsString = boost::lexical_cast<std::string>(getPort()); + portAsString = std::to_string(getPort()); } catch (boost::bad_lexical_cast&) { } return getAddress().toString() + ":" + portAsString; diff --git a/Swiften/Network/HostAddressPort.h b/Swiften/Network/HostAddressPort.h index e42e1d1..759af01 100644 --- a/Swiften/Network/HostAddressPort.h +++ b/Swiften/Network/HostAddressPort.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -14,14 +14,14 @@ 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_; } @@ -29,6 +29,13 @@ namespace Swift { return address_ == o.address_ && port_ == o.port_; } + bool operator<(const HostAddressPort& o) const { + if (address_ < o.address_) { + return true; + } + return address_ == o.address_ && port_ < o.port_; + } + bool isValid() const { return address_.isValid() && port_ > 0; } @@ -37,6 +44,6 @@ namespace Swift { 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 @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2013-2016 Isode Limited. + * Copyright (c) 2013-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -40,13 +40,15 @@ static HostAddressPort getFromDictionary(CFDictionaryRef dict, CFStringRef enabl 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)); diff --git a/Swiften/Network/MiniUPnPInterface.cpp b/Swiften/Network/MiniUPnPInterface.cpp index dbe8bcd..8425c77 100644 --- a/Swiften/Network/MiniUPnPInterface.cpp +++ b/Swiften/Network/MiniUPnPInterface.cpp @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -14,8 +14,6 @@ #include <memory> -#include <boost/lexical_cast.hpp> - #include <miniupnpc.h> #include <upnpcommands.h> #include <upnperrors.h> @@ -73,16 +71,16 @@ boost::optional<HostAddress> MiniUPnPInterface::getPublicIP() { } } -boost::optional<NATPortMapping> MiniUPnPInterface::addPortForward(int actualLocalPort, int actualPublicPort) { +boost::optional<NATPortMapping> MiniUPnPInterface::addPortForward(unsigned short actualLocalPort, unsigned short actualPublicPort) { if (!p->isValid) { return boost::optional<NATPortMapping>(); } NATPortMapping mapping(actualLocalPort, actualPublicPort, NATPortMapping::TCP); - std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort()); - std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort()); - std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds()); + std::string publicPort = std::to_string(mapping.getPublicPort()); + std::string localPort = std::to_string(mapping.getLocalPort()); + std::string leaseSeconds = std::to_string(mapping.getLeaseInSeconds()); int ret = UPNP_AddPortMapping( p->urls.controlURL, @@ -107,9 +105,9 @@ bool MiniUPnPInterface::removePortForward(const NATPortMapping& mapping) { return false; } - std::string publicPort = boost::lexical_cast<std::string>(mapping.getPublicPort()); - std::string localPort = boost::lexical_cast<std::string>(mapping.getLocalPort()); - std::string leaseSeconds = boost::lexical_cast<std::string>(mapping.getLeaseInSeconds()); + std::string publicPort = std::to_string(mapping.getPublicPort()); + std::string localPort = std::to_string(mapping.getLocalPort()); + std::string leaseSeconds = std::to_string(mapping.getLeaseInSeconds()); int ret = UPNP_DeletePortMapping(p->urls.controlURL, p->data.first.servicetype, publicPort.c_str(), mapping.getProtocol() == NATPortMapping::TCP ? "TCP" : "UDP", nullptr); return ret == UPNPCOMMAND_SUCCESS; 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,5 +1,5 @@ /* - * 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. */ @@ -23,7 +23,7 @@ namespace Swift { 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: diff --git a/Swiften/Network/NATPMPInterface.cpp b/Swiften/Network/NATPMPInterface.cpp index 5e0b3b3..e20fecd 100644 --- a/Swiften/Network/NATPMPInterface.cpp +++ b/Swiften/Network/NATPMPInterface.cpp @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -14,8 +14,6 @@ #include <memory> -#include <boost/numeric/conversion/cast.hpp> - #include <Swiften/Base/Log.h> // This has to be included after the previous headers, because of WIN32 macro @@ -44,7 +42,7 @@ bool NATPMPInterface::isAvailable() { boost::optional<HostAddress> NATPMPInterface::getPublicIP() { if (sendpublicaddressrequest(&p->natpmp) < 0) { - SWIFT_LOG(debug) << "Failed to send NAT-PMP public address request!" << std::endl; + SWIFT_LOG(debug) << "Failed to send NAT-PMP public address request!"; return boost::optional<HostAddress>(); } @@ -69,20 +67,20 @@ boost::optional<HostAddress> NATPMPInterface::getPublicIP() { return boost::optional<HostAddress>(HostAddress(reinterpret_cast<const unsigned char*>(&(response.pnu.publicaddress.addr)), 4)); } else { - SWIFT_LOG(debug) << "Inavlid NAT-PMP response." << std::endl; + SWIFT_LOG(debug) << "Inavlid NAT-PMP response."; return boost::optional<HostAddress>(); } } -boost::optional<NATPortMapping> NATPMPInterface::addPortForward(int localPort, int publicPort) { +boost::optional<NATPortMapping> NATPMPInterface::addPortForward(unsigned short localPort, unsigned short publicPort) { NATPortMapping mapping(localPort, publicPort, NATPortMapping::TCP); if (sendnewportmappingrequest( &p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, - boost::numeric_cast<uint16_t>(mapping.getLocalPort()), - boost::numeric_cast<uint16_t>(mapping.getPublicPort()), - boost::numeric_cast<uint32_t>(mapping.getLeaseInSeconds())) < 0) { - SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl; + mapping.getLocalPort(), + mapping.getPublicPort(), + mapping.getLeaseInSeconds()) < 0) { + SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!"; return boost::optional<NATPortMapping>(); } @@ -104,18 +102,18 @@ boost::optional<NATPortMapping> NATPMPInterface::addPortForward(int localPort, i } while(false /*r == NATPMP_TRYAGAIN*/); if (r == 0) { - NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, boost::numeric_cast<int>(response.pnu.newportmapping.lifetime)); + NATPortMapping result(response.pnu.newportmapping.privateport, response.pnu.newportmapping.mappedpublicport, NATPortMapping::TCP, response.pnu.newportmapping.lifetime); return result; } else { - SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl; + SWIFT_LOG(debug) << "Invalid NAT-PMP response."; return boost::optional<NATPortMapping>(); } } bool NATPMPInterface::removePortForward(const NATPortMapping& mapping) { - if (sendnewportmappingrequest(&p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, 0, 0, boost::numeric_cast<uint32_t>(mapping.getLocalPort())) < 0) { - SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!" << std::endl; + if (sendnewportmappingrequest(&p->natpmp, mapping.getProtocol() == NATPortMapping::TCP ? NATPMP_PROTOCOL_TCP : NATPMP_PROTOCOL_UDP, mapping.getLocalPort(), 0, 0) < 0) { + SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!"; return false; } @@ -135,7 +133,7 @@ bool NATPMPInterface::removePortForward(const NATPortMapping& mapping) { return true; } else { - SWIFT_LOG(debug) << "Invalid NAT-PMP response." << std::endl; + SWIFT_LOG(debug) << "Invalid NAT-PMP response."; return false; } } 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,5 +1,5 @@ /* - * 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. */ @@ -23,7 +23,7 @@ namespace Swift { 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: diff --git a/Swiften/Network/NATPortMapping.h b/Swiften/Network/NATPortMapping.h index ff8fde3..bf0fb1c 100644 --- a/Swiften/Network/NATPortMapping.h +++ b/Swiften/Network/NATPortMapping.h @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2015 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -23,16 +23,16 @@ namespace Swift { UDP }; - NATPortMapping(int localPort, int publicPort, Protocol protocol = TCP, int leaseInSeconds = 60 * 60 * 24) : + NATPortMapping(unsigned short localPort, unsigned short publicPort, Protocol protocol = TCP, uint32_t leaseInSeconds = 60 * 60 * 24) : publicPort(publicPort), localPort(localPort), protocol(protocol), leaseInSeconds(leaseInSeconds) { } - int getPublicPort() const { + unsigned short getPublicPort() const { return publicPort; } - int getLocalPort() const { + unsigned short getLocalPort() const { return localPort; } @@ -40,14 +40,14 @@ namespace Swift { return protocol; } - int getLeaseInSeconds() const { + uint32_t getLeaseInSeconds() const { return leaseInSeconds; } private: - int publicPort; - int localPort; + unsigned short publicPort; + unsigned short localPort; Protocol protocol; - int leaseInSeconds; + uint32_t leaseInSeconds; }; } diff --git a/Swiften/Network/NATTraversalInterface.h b/Swiften/Network/NATTraversalInterface.h index ea9ed6a..1655eb6 100644 --- a/Swiften/Network/NATTraversalInterface.h +++ b/Swiften/Network/NATTraversalInterface.h @@ -1,5 +1,5 @@ /* - * 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. */ @@ -19,7 +19,7 @@ namespace Swift { 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 @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -26,8 +26,8 @@ namespace Swift { UDP }; - unsigned int publicPort; - unsigned int localPort; + unsigned short publicPort; + unsigned short localPort; Protocol protocol; unsigned long leaseInSeconds; }; 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,5 +1,5 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -20,7 +20,7 @@ namespace Swift { 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 @@ -21,7 +21,7 @@ namespace Swift { return boost::optional<HostAddress>(); } - virtual boost::optional<NATPortMapping> addPortForward(int, int) { + virtual boost::optional<NATPortMapping> addPortForward(unsigned short, unsigned short) { return boost::optional<NATPortMapping>(); } 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,5 +1,5 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -72,11 +72,11 @@ std::shared_ptr<NATTraversalGetPublicIPRequest> NullNATTraverser::createGetPubli 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,5 +1,5 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -16,8 +16,8 @@ namespace Swift { 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..2ff14e1 100644 --- a/Swiften/Network/PlatformDomainNameServiceQuery.cpp +++ b/Swiften/Network/PlatformDomainNameServiceQuery.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -58,7 +58,7 @@ void PlatformDomainNameServiceQuery::runBlocking() { return; } - SWIFT_LOG(debug) << "Querying " << service << std::endl; + SWIFT_LOG(debug) << "Querying " << service; std::vector<DomainNameServiceQuery::Result> records; @@ -97,7 +97,7 @@ void PlatformDomainNameServiceQuery::runBlocking() { response.resize(NS_PACKETSZ); int responseLength = res_query(const_cast<char*>(service.c_str()), ns_c_in, ns_t_srv, reinterpret_cast<u_char*>(vecptr(response)), response.size()); if (responseLength == -1) { - SWIFT_LOG(debug) << "Error" << std::endl; + SWIFT_LOG(debug) << "Error"; emitError(); return; } @@ -129,35 +129,42 @@ void PlatformDomainNameServiceQuery::runBlocking() { 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()); diff --git a/Swiften/Network/PlatformNATTraversalWorker.cpp b/Swiften/Network/PlatformNATTraversalWorker.cpp index f56de0b..5431379 100644 --- a/Swiften/Network/PlatformNATTraversalWorker.cpp +++ b/Swiften/Network/PlatformNATTraversalWorker.cpp @@ -84,7 +84,7 @@ 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() { @@ -99,12 +99,12 @@ class PlatformNATTraversalForwardPortRequest : public NATTraversalForwardPortReq } 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 { @@ -157,7 +157,7 @@ NATTraversalInterface* PlatformNATTraversalWorker::getNATTraversalInterface() co miniUPnPInterface = new MiniUPnPInterface(); miniUPnPSupported = miniUPnPInterface->isAvailable(); } - SWIFT_LOG(debug) << "UPnP NAT traversal supported: " << miniUPnPSupported << std::endl; + SWIFT_LOG(debug) << "UPnP NAT traversal supported: " << static_cast<bool>(miniUPnPSupported); if (miniUPnPSupported) { return miniUPnPInterface; } @@ -168,7 +168,7 @@ NATTraversalInterface* PlatformNATTraversalWorker::getNATTraversalInterface() co natPMPInterface = new NATPMPInterface(); natPMPSupported = natPMPInterface->isAvailable(); } - SWIFT_LOG(debug) << "NAT-PMP NAT traversal supported: " << natPMPSupported << std::endl; + SWIFT_LOG(debug) << "NAT-PMP NAT traversal supported: " << static_cast<bool>(natPMPSupported); if (natPMPSupported) { return natPMPInterface; } @@ -181,11 +181,11 @@ std::shared_ptr<NATTraversalGetPublicIPRequest> PlatformNATTraversalWorker::crea 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); } 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 @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2016-2017 Isode Limited. + * Copyright (c) 2016-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -44,8 +44,8 @@ namespace Swift { 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; diff --git a/Swiften/Network/ProxiedConnection.cpp b/Swiften/Network/ProxiedConnection.cpp index aa6c4d2..0c5cda6 100644 --- a/Swiften/Network/ProxiedConnection.cpp +++ b/Swiften/Network/ProxiedConnection.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012-2016 Isode Limited. + * Copyright (c) 2012-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -20,7 +20,7 @@ ProxiedConnection::ProxiedConnection( ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, - int proxyPort) : + unsigned short proxyPort) : resolver_(resolver), connectionFactory_(connectionFactory), timerFactory_(timerFactory), @@ -37,7 +37,7 @@ ProxiedConnection::~ProxiedConnection() { connection_->onDisconnected.disconnect(boost::bind(&ProxiedConnection::handleDisconnected, shared_from_this(), _1)); } if (connected_) { - SWIFT_LOG(warning) << "Connection was still established." << std::endl; + SWIFT_LOG(warning) << "Connection was still established."; } } 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,5 +1,5 @@ /* - * Copyright (c) 2012-2017 Isode Limited. + * Copyright (c) 2012-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -20,7 +20,7 @@ namespace Swift { 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(); @@ -55,7 +55,7 @@ namespace Swift { 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..c76b6e6 100644 --- a/Swiften/Network/SOCKS5ProxiedConnection.cpp +++ b/Swiften/Network/SOCKS5ProxiedConnection.cpp @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2014-2016 Isode Limited. + * Copyright (c) 2014-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -27,7 +27,7 @@ SOCKS5ProxiedConnection::SOCKS5ProxiedConnection( ConnectionFactory* connectionFactory, TimerFactory* timerFactory, const std::string& proxyHost, - int proxyPort) : + unsigned short proxyPort) : ProxiedConnection(resolver, connectionFactory, timerFactory, proxyHost, proxyPort), proxyState_(Initial) { } @@ -50,7 +50,7 @@ void SOCKS5ProxiedConnection::handleProxyInitializeData(std::shared_ptr<SafeByte assert(rawAddress.is_v4() || rawAddress.is_v6()); if (proxyState_ == ProxyAuthenticating) { - SWIFT_LOG(debug) << "ProxyAuthenticating response received, reply with the connect BYTEs" << std::endl; + SWIFT_LOG(debug) << "ProxyAuthenticating response received, reply with the connect BYTEs"; unsigned char choosenMethod = static_cast<unsigned char> ((*data)[1]); if ((*data)[0] == 0x05 && choosenMethod != 0xFF) { switch(choosenMethod) { // use the correct Method @@ -79,7 +79,7 @@ void SOCKS5ProxiedConnection::handleProxyInitializeData(std::shared_ptr<SafeByte return; } catch(...) { - SWIFT_LOG(error) << "exception caught" << std::endl; + SWIFT_LOG(error) << "exception caught"; } write(socksConnect); break; @@ -92,8 +92,8 @@ void SOCKS5ProxiedConnection::handleProxyInitializeData(std::shared_ptr<SafeByte setProxyInitializeFinished(false); } else if (proxyState_ == ProxyConnecting) { - SWIFT_LOG(debug) << "Connect response received, check if successfully." << std::endl; - SWIFT_LOG(debug) << "Errorbyte: 0x" << std::hex << static_cast<int> ((*data)[1]) << std::dec << std::endl; + SWIFT_LOG(debug) << "Connect response received, check if successfully."; + SWIFT_LOG(debug) << "Errorbyte: 0x" << std::hex << static_cast<int> ((*data)[1]) << std::dec; /* data.at(1) can be one of the following: @@ -109,11 +109,11 @@ void SOCKS5ProxiedConnection::handleProxyInitializeData(std::shared_ptr<SafeByte 0x09 bis 0xFF unassigned */ if ((*data)[0] == 0x05 && (*data)[1] == 0x0) { - SWIFT_LOG(debug) << "Successfully connected the server via the proxy." << std::endl; + SWIFT_LOG(debug) << "Successfully connected the server via the proxy."; setProxyInitializeFinished(true); } else { - SWIFT_LOG(error) << "SOCKS Proxy returned an error: " << std::hex << (*data)[1] << std::endl; + SWIFT_LOG(error) << "SOCKS Proxy returned an error: " << std::hex << (*data)[1]; setProxyInitializeFinished(false); } } 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 @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -24,12 +24,12 @@ namespace Swift { 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); 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 @@ -16,7 +16,7 @@ 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() { 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 @@ -5,7 +5,7 @@ */ /* - * Copyright (c) 2015-2016 Isode Limited. + * Copyright (c) 2015-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -23,7 +23,7 @@ namespace Swift { 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(); @@ -32,6 +32,6 @@ namespace Swift { ConnectionFactory* connectionFactory_; TimerFactory* timerFactory_; std::string proxyHost_; - int proxyPort_; + unsigned short proxyPort_; }; } diff --git a/Swiften/Network/StaticDomainNameResolver.cpp b/Swiften/Network/StaticDomainNameResolver.cpp index 95b3dd9..eca6687 100644 --- a/Swiften/Network/StaticDomainNameResolver.cpp +++ b/Swiften/Network/StaticDomainNameResolver.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -50,6 +50,10 @@ namespace { if (!resolver->getIsResponsive()) { return; } + if (auto address = HostAddress::fromString(host)) { + // IP Literals should resolve to themselves + resolver->addAddress(host, *address); + } StaticDomainNameResolver::AddressesMap::const_iterator i = resolver->getAddresses().find(host); if (i != resolver->getAddresses().end()) { eventLoop->postEvent( @@ -98,14 +102,14 @@ void StaticDomainNameResolver::addService(const std::string& service, const Doma void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, const HostAddressPort& address) { static int hostid = 0; - std::string hostname(std::string("host-") + boost::lexical_cast<std::string>(hostid)); + std::string hostname(std::string("host-") + std::to_string(hostid)); hostid++; addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, address.getPort(), 0, 0)); addAddress(hostname, address.getAddress()); } -void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, const std::string& hostname, int port) { +void StaticDomainNameResolver::addXMPPClientService(const std::string& domain, const std::string& hostname, unsigned short port) { addService("_xmpp-client._tcp." + domain, ServiceQuery::Result(hostname, port, 0, 0)); } 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,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -31,7 +31,7 @@ namespace Swift { 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/TLSConnection.cpp b/Swiften/Network/TLSConnection.cpp index 7c293d1..82bf114 100644 --- a/Swiften/Network/TLSConnection.cpp +++ b/Swiften/Network/TLSConnection.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -32,7 +32,6 @@ TLSConnection::~TLSConnection() { connection->onDataRead.disconnect(boost::bind(&TLSConnection::handleRawDataRead, this, _1)); connection->onDataWritten.disconnect(boost::bind(&TLSConnection::handleRawDataWritten, this)); connection->onDisconnected.disconnect(boost::bind(&TLSConnection::handleRawDisconnected, this, _1)); - delete context; } void TLSConnection::handleTLSConnectFinished(bool error) { @@ -71,7 +70,7 @@ HostAddressPort TLSConnection::getRemoteAddress() const { } TLSContext* TLSConnection::getTLSContext() const { - return context; + return context.get(); } void TLSConnection::handleRawConnectFinished(bool error) { diff --git a/Swiften/Network/TLSConnection.h b/Swiften/Network/TLSConnection.h index 0c395d1..1ab1ec6 100644 --- a/Swiften/Network/TLSConnection.h +++ b/Swiften/Network/TLSConnection.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011-2016 Isode Limited. + * Copyright (c) 2011-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -46,7 +46,7 @@ namespace Swift { void handleTLSDataForApplication(const SafeByteArray& data); private: - TLSContext* context; + std::unique_ptr<TLSContext> context; Connection::ref connection; }; } diff --git a/Swiften/Network/UnboundDomainNameResolver.cpp b/Swiften/Network/UnboundDomainNameResolver.cpp index 1df6b8f..21bc697 100644 --- a/Swiften/Network/UnboundDomainNameResolver.cpp +++ b/Swiften/Network/UnboundDomainNameResolver.cpp @@ -64,7 +64,7 @@ class UnboundDomainNameServiceQuery : public DomainNameServiceQuery, public Unbo 1 /* CLASS IN (internet) */, helper, UnboundDomainNameResolver::unbound_callback_wrapper, NULL); if(retval != 0) { - SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval) << std::endl; + SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval); delete helper; } } @@ -73,7 +73,7 @@ class UnboundDomainNameServiceQuery : public DomainNameServiceQuery, public Unbo std::vector<DomainNameServiceQuery::Result> serviceRecords; if(err != 0) { - SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err) << std::endl; + SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err); } else { if(result->havedata) { ldns_pkt* replyPacket = 0; @@ -105,7 +105,7 @@ class UnboundDomainNameServiceQuery : public DomainNameServiceQuery, public Unbo serviceRecord.hostname = std::string(reinterpret_cast<char*>(ldns_buffer_at(buffer, 0))); serviceRecords.push_back(serviceRecord); - SWIFT_LOG(debug) << "hostname " << serviceRecord.hostname << " added" << std::endl; + SWIFT_LOG(debug) << "hostname " << serviceRecord.hostname << " added"; } } if (replyPacket) ldns_pkt_free(replyPacket); @@ -137,7 +137,7 @@ class UnboundDomainNameAddressQuery : public DomainNameAddressQuery, public Unbo 1 /* CLASS IN (internet) */, helper, UnboundDomainNameResolver::unbound_callback_wrapper, NULL); if(retval != 0) { - SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval) << std::endl; + SWIFT_LOG(debug) << "resolve error: " << ub_strerror(retval); delete helper; } } @@ -145,10 +145,10 @@ class UnboundDomainNameAddressQuery : public DomainNameAddressQuery, public Unbo void handleResult(int err, struct ub_result* result) { std::vector<HostAddress> addresses; boost::optional<DomainNameResolveError> error; - SWIFT_LOG(debug) << "Result for: " << name << std::endl; + SWIFT_LOG(debug) << "Result for: " << name; if(err != 0) { - SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err) << std::endl; + SWIFT_LOG(debug) << "resolve error: " << ub_strerror(err); error = DomainNameResolveError(); } else { if(result->havedata) { @@ -156,13 +156,13 @@ class UnboundDomainNameAddressQuery : public DomainNameAddressQuery, public Unbo char address[100]; const char* addressStr = 0; if ((addressStr = inet_ntop(AF_INET, result->data[i], address, 100))) { - SWIFT_LOG(debug) << "IPv4 address: " << addressStr << std::endl; + SWIFT_LOG(debug) << "IPv4 address: " << addressStr; addresses.push_back(HostAddress(std::string(addressStr))); } else if ((addressStr = inet_ntop(AF_INET6, result->data[i], address, 100))) { - SWIFT_LOG(debug) << "IPv6 address: " << addressStr << std::endl; + SWIFT_LOG(debug) << "IPv6 address: " << addressStr; addresses.push_back(HostAddress(std::string(addressStr))); } else { - SWIFT_LOG(debug) << "inet_ntop() failed" << std::endl; + SWIFT_LOG(debug) << "inet_ntop() failed"; error = DomainNameResolveError(); } } @@ -182,7 +182,7 @@ class UnboundDomainNameAddressQuery : public DomainNameAddressQuery, public Unbo UnboundDomainNameResolver::UnboundDomainNameResolver(IDNConverter* idnConverter, std::shared_ptr<boost::asio::io_service> ioService, EventLoop* eventLoop) : idnConverter(idnConverter), ioService(ioService), ubDescriptior(*ioService), eventLoop(eventLoop) { ubContext = ub_ctx_create(); if(!ubContext) { - SWIFT_LOG(debug) << "could not create unbound context" << std::endl; + SWIFT_LOG(debug) << "could not create unbound context"; } eventOwner = std::make_shared<EventOwner>(); @@ -192,11 +192,11 @@ UnboundDomainNameResolver::UnboundDomainNameResolver(IDNConverter* idnConverter, /* read /etc/resolv.conf for DNS proxy settings (from DHCP) */ if( (ret=ub_ctx_resolvconf(ubContext, const_cast<char*>("/etc/resolv.conf"))) != 0) { - SWIFT_LOG(error) << "error reading resolv.conf: " << ub_strerror(ret) << ". errno says: " << strerror(errno) << std::endl; + SWIFT_LOG(error) << "error reading resolv.conf: " << ub_strerror(ret) << ". errno says: " << strerror(errno); } /* read /etc/hosts for locally supplied host addresses */ if( (ret=ub_ctx_hosts(ubContext, const_cast<char*>("/etc/hosts"))) != 0) { - SWIFT_LOG(error) << "error reading hosts: " << ub_strerror(ret) << ". errno says: " << strerror(errno) << std::endl; + SWIFT_LOG(error) << "error reading hosts: " << ub_strerror(ret) << ". errno says: " << strerror(errno); } ubDescriptior.assign(ub_fd(ubContext)); @@ -231,7 +231,7 @@ void UnboundDomainNameResolver::processData() { if (ub_poll(ubContext)) { int ret = ub_process(ubContext); if(ret != 0) { - SWIFT_LOG(debug) << "resolve error: " << ub_strerror(ret) << std::endl; + SWIFT_LOG(debug) << "resolve error: " << ub_strerror(ret); } } } diff --git a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp index 5d6fedd..4aeaf24 100644 --- a/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp +++ b/Swiften/Network/UnitTest/BOSHConnectionPoolTest.cpp @@ -194,7 +194,7 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture { CPPUNIT_ASSERT_EQUAL(st(2), connectionFactory->connections.size()); /* 0 was waiting for response, open and send on 1 */ CPPUNIT_ASSERT_EQUAL(st(4), boshDataWritten.size()); /* data */ c1 = connectionFactory->connections[1]; - std::string fullBody = "<body rid='" + boost::lexical_cast<std::string>(rid) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'><blah/></body>"; /* check empty write */ + std::string fullBody = "<body rid='" + std::to_string(rid) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'><blah/></body>"; /* check empty write */ CPPUNIT_ASSERT_EQUAL(fullBody, lastBody()); CPPUNIT_ASSERT(c0->pending); CPPUNIT_ASSERT(c1->pending); @@ -310,7 +310,7 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture { readResponse("<body></body>", c0); eventLoop->processEvents(); CPPUNIT_ASSERT_EQUAL(st(3), boshDataWritten.size()); - std::string fullBody = "<body rid='" + boost::lexical_cast<std::string>(initialRID + 2) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'></body>"; + std::string fullBody = "<body rid='" + std::to_string(initialRID + 2) + "' sid='" + sid + "' xmlns='http://jabber.org/protocol/httpbind'></body>"; std::string response = boshDataWritten[2]; size_t bodyPosition = response.find("\r\n\r\n"); CPPUNIT_ASSERT_EQUAL(fullBody, response.substr(bodyPosition+4)); @@ -427,7 +427,7 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture { "Access-Control-Allow-Headers: Content-Type\r\n" "Content-Length: ")); connection->onDataRead(data1); - std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size()))); + std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(std::to_string(response.size()))); connection->onDataRead(data2); std::shared_ptr<SafeByteArray> data3 = std::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n")); connection->onDataRead(data3); @@ -440,7 +440,7 @@ class BOSHConnectionPoolTest : public CppUnit::TestFixture { std::string result = "POST /" + path + " HTTP/1.1\r\n" + "Host: " + to + ":" + port + "\r\n" + "Content-Type: text/xml; charset=utf-8\r\n" - + "Content-Length: " + boost::lexical_cast<std::string>(body.size()) + "\r\n\r\n" + + "Content-Length: " + std::to_string(body.size()) + "\r\n\r\n" + body; return result; } diff --git a/Swiften/Network/UnitTest/BOSHConnectionTest.cpp b/Swiften/Network/UnitTest/BOSHConnectionTest.cpp index e34cb96..17d8333 100644 --- a/Swiften/Network/UnitTest/BOSHConnectionTest.cpp +++ b/Swiften/Network/UnitTest/BOSHConnectionTest.cpp @@ -318,7 +318,7 @@ class BOSHConnectionTest : public CppUnit::TestFixture { "Access-Control-Allow-Headers: Content-Type\r\n" "Content-Length: ")); connection->onDataRead(data1); - std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(boost::lexical_cast<std::string>(response.size()))); + std::shared_ptr<SafeByteArray> data2 = std::make_shared<SafeByteArray>(createSafeByteArray(std::to_string(response.size()))); connection->onDataRead(data2); std::shared_ptr<SafeByteArray> data3 = std::make_shared<SafeByteArray>(createSafeByteArray("\r\n\r\n")); connection->onDataRead(data3); diff --git a/Swiften/Network/UnitTest/ConnectorTest.cpp b/Swiften/Network/UnitTest/ConnectorTest.cpp index 8524439..065911d 100644 --- a/Swiften/Network/UnitTest/ConnectorTest.cpp +++ b/Swiften/Network/UnitTest/ConnectorTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -26,6 +26,7 @@ class ConnectorTest : public CppUnit::TestFixture { CPPUNIT_TEST(testConnect); CPPUNIT_TEST(testConnect_NoServiceLookups); CPPUNIT_TEST(testConnect_NoServiceLookups_DefaultPort); + CPPUNIT_TEST(testConnect_OnlyLiteral); CPPUNIT_TEST(testConnect_FirstAddressHostFails); CPPUNIT_TEST(testConnect_NoSRVHost); CPPUNIT_TEST(testConnect_NoHosts); @@ -91,7 +92,7 @@ class ConnectorTest : public CppUnit::TestFixture { } 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()); @@ -102,7 +103,7 @@ class ConnectorTest : public CppUnit::TestFixture { CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); CPPUNIT_ASSERT(connections[0]); CPPUNIT_ASSERT(host3.getAddress() == (*(connections[0]->hostAddressPort)).getAddress()); - CPPUNIT_ASSERT_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)); } @@ -119,6 +120,21 @@ class ConnectorTest : public CppUnit::TestFixture { CPPUNIT_ASSERT(!std::dynamic_pointer_cast<DomainNameResolveError>(error)); } + void testConnect_OnlyLiteral() { + auto testling = Connector::create("1.1.1.1", 1234, boost::none, resolver, connectionFactory, timerFactory); + testling->onConnectFinished.connect(boost::bind(&ConnectorTest::handleConnectorFinished, this, _1, _2)); + + auto address1 = HostAddress::fromString("1.1.1.1").get(); + connectionFactory->failingPorts.push_back(HostAddressPort(address1, 1234)); + + testling->start(); + eventLoop->processEvents(); + + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connections.size())); + CPPUNIT_ASSERT(!connections[0]); + CPPUNIT_ASSERT_EQUAL(1, static_cast<int>(connectionFactory->createdConnections.size())); + } + void testConnect_FirstAddressHostFails() { Connector::ref testling(createConnector()); @@ -312,7 +328,7 @@ class ConnectorTest : public CppUnit::TestFixture { 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; @@ -356,12 +372,15 @@ class ConnectorTest : public CppUnit::TestFixture { } std::shared_ptr<Connection> createConnection() { - return std::make_shared<MockConnection>(failingPorts, isResponsive, eventLoop); + auto connection = std::make_shared<MockConnection>(failingPorts, isResponsive, eventLoop); + createdConnections.push_back(connection); + return connection; } EventLoop* eventLoop; bool isResponsive; std::vector<HostAddressPort> failingPorts; + std::vector<std::shared_ptr<MockConnection>> createdConnections; }; private: diff --git a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp index 1a160b7..e9268b0 100644 --- a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp +++ b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2019 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -37,7 +37,7 @@ namespace { virtual std::vector<std::pair<std::string, std::string> > filterHTTPResponseHeader(const std::string& /* statusLine */, const std::vector<std::pair<std::string, std::string> >& response) { filterResponses.push_back(response); - SWIFT_LOG(debug) << std::endl; + SWIFT_LOG(debug); return filterResponseReturn; } @@ -409,7 +409,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture { std::shared_ptr<Connection> createConnection() { std::shared_ptr<MockConnection> connection = std::make_shared<MockConnection>(failingPorts, eventLoop); connections.push_back(connection); - SWIFT_LOG(debug) << "new connection created" << std::endl; + SWIFT_LOG(debug) << "new connection created"; return connection; } @@ -421,7 +421,7 @@ class HTTPConnectProxiedConnectionTest : public CppUnit::TestFixture { private: std::string proxyHost; HostAddressPort proxyHostAddress; - int proxyPort; + unsigned short proxyPort; HostAddressPort host; DummyEventLoop* eventLoop; StaticDomainNameResolver* resolver; diff --git a/Swiften/Network/UnitTest/HostAddressTest.cpp b/Swiften/Network/UnitTest/HostAddressTest.cpp index 226346b..bd345a7 100644 --- a/Swiften/Network/UnitTest/HostAddressTest.cpp +++ b/Swiften/Network/UnitTest/HostAddressTest.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010-2016 Isode Limited. + * Copyright (c) 2010-2018 Isode Limited. * All rights reserved. * See the COPYING file for more information. */ @@ -10,6 +10,7 @@ #include <cppunit/extensions/TestFactoryRegistry.h> #include <Swiften/Network/HostAddress.h> +#include <Swiften/Network/HostAddressPort.h> using namespace Swift; @@ -21,6 +22,7 @@ class HostAddressTest : public CppUnit::TestFixture { CPPUNIT_TEST(testToString); CPPUNIT_TEST(testToString_IPv6); CPPUNIT_TEST(testToString_Invalid); + CPPUNIT_TEST(testComparison); CPPUNIT_TEST_SUITE_END(); public: @@ -62,6 +64,32 @@ class HostAddressTest : public CppUnit::TestFixture { CPPUNIT_ASSERT_EQUAL(std::string("0.0.0.0"), testling.toString()); } + + void testComparison() { + auto ha127_0_0_1 = *HostAddress::fromString("127.0.0.1"); + auto ha127_0_0_2 = *HostAddress::fromString("127.0.0.2"); + auto ha127_0_1_0 = *HostAddress::fromString("127.0.1.0"); + + CPPUNIT_ASSERT(ha127_0_0_1 < ha127_0_0_2); + CPPUNIT_ASSERT(ha127_0_0_2 < ha127_0_1_0); + CPPUNIT_ASSERT(!(ha127_0_0_1 < ha127_0_0_1)); + CPPUNIT_ASSERT(!(ha127_0_0_2 < ha127_0_0_1)); + CPPUNIT_ASSERT(!(ha127_0_0_2 == ha127_0_0_1)); + CPPUNIT_ASSERT(ha127_0_0_1 == ha127_0_0_1); + + auto hap_127_0_0_1__1 = HostAddressPort(ha127_0_0_1, 1); + auto hap_127_0_0_1__2 = HostAddressPort(ha127_0_0_1, 2); + auto hap_127_0_0_2__1 = HostAddressPort(ha127_0_0_2, 1); + auto hap_127_0_0_2__2 = HostAddressPort(ha127_0_0_2, 2); + + CPPUNIT_ASSERT(hap_127_0_0_1__1 < hap_127_0_0_1__2); + CPPUNIT_ASSERT(!(hap_127_0_0_1__1 < hap_127_0_0_1__1)); + CPPUNIT_ASSERT(!(hap_127_0_0_1__1 == hap_127_0_0_1__2)); + CPPUNIT_ASSERT(hap_127_0_0_1__1 == hap_127_0_0_1__1); + CPPUNIT_ASSERT(!(hap_127_0_0_1__2 == hap_127_0_0_1__1)); + CPPUNIT_ASSERT(hap_127_0_0_1__2 < hap_127_0_0_2__1); + CPPUNIT_ASSERT(hap_127_0_0_2__1 < hap_127_0_0_2__2); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(HostAddressTest); diff --git a/Swiften/Network/WindowsProxyProvider.cpp b/Swiften/Network/WindowsProxyProvider.cpp index 78bd72f..13fdb25 100644 --- a/Swiften/Network/WindowsProxyProvider.cpp +++ b/Swiften/Network/WindowsProxyProvider.cpp @@ -17,6 +17,7 @@ #include <stdlib.h> #include <boost/lexical_cast.hpp> +#include <boost/numeric/conversion/cast.hpp> #include <windows.h> @@ -51,7 +52,7 @@ WindowsProxyProvider::WindowsProxyProvider() for(auto&& proxy : proxies) { if(proxy.find('=') != std::string::npos) { protocolAndProxy = String::getSplittedAtFirst(proxy, '='); - SWIFT_LOG(debug) << "Found proxy: " << protocolAndProxy.first << " => " << protocolAndProxy.second << std::endl; + SWIFT_LOG(debug) << "Found proxy: " << protocolAndProxy.first << " => " << protocolAndProxy.second; if(protocolAndProxy.first.compare("socks") == 0) { socksProxy = getAsHostAddressPort(protocolAndProxy.second); } @@ -77,15 +78,15 @@ HostAddressPort WindowsProxyProvider::getAsHostAddressPort(std::string proxy) { 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; + SWIFT_LOG(error) << "Exception occured while parsing windows proxy \"getHostAddressPort\"."; } return ret; |