summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
Diffstat (limited to 'Swiften')
-rw-r--r--Swiften/Avatars/CombinedAvatarProvider.cpp8
-rw-r--r--Swiften/Avatars/VCardUpdateAvatarManager.cpp10
-rw-r--r--Swiften/Base/DateTime.cpp4
-rw-r--r--Swiften/Base/Log.cpp41
-rw-r--r--Swiften/Base/Log.h14
-rw-r--r--Swiften/Base/UnitTest/LogTest.cpp49
-rw-r--r--Swiften/Chat/ChatStateTracker.cpp2
-rw-r--r--Swiften/Client/ClientSession.cpp22
-rw-r--r--Swiften/Client/ClientSessionStanzaChannel.cpp4
-rw-r--r--Swiften/Client/CoreClient.cpp32
-rw-r--r--Swiften/Component/ComponentSessionStanzaChannel.cpp4
-rw-r--r--Swiften/Component/CoreComponent.cpp4
-rw-r--r--Swiften/Disco/CapsManager.cpp4
-rw-r--r--Swiften/Disco/DiscoServiceWalker.cpp18
-rw-r--r--Swiften/Elements/JingleFileTransferFileInfo.h2
-rw-r--r--Swiften/Elements/StreamError.h2
-rw-r--r--Swiften/Elements/StreamInitiationFileInfo.h2
-rw-r--r--Swiften/Entity/PayloadPersister.cpp6
-rw-r--r--Swiften/EventLoop/BoostASIOEventLoop.cpp4
-rw-r--r--Swiften/EventLoop/Cocoa/CocoaEventLoop.mm4
-rw-r--r--Swiften/EventLoop/DummyEventLoop.cpp6
-rw-r--r--Swiften/EventLoop/EventLoop.cpp25
-rw-r--r--Swiften/EventLoop/EventLoop.h11
-rw-r--r--Swiften/EventLoop/Qt/QtEventLoop.h4
-rw-r--r--Swiften/EventLoop/SimpleEventLoop.cpp4
-rw-r--r--Swiften/EventLoop/SingleThreadedEventLoop.cpp4
-rw-r--r--Swiften/EventLoop/UnitTest/EventLoopTest.cpp13
-rw-r--r--Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp2
-rw-r--r--Swiften/Examples/SendFile/ReceiveFile.cpp4
-rw-r--r--Swiften/FileTransfer/DefaultFileTransferTransporter.cpp12
-rw-r--r--Swiften/FileTransfer/FailingTransportSession.cpp4
-rw-r--r--Swiften/FileTransfer/FileTransferManagerImpl.cpp4
-rw-r--r--Swiften/FileTransfer/IncomingJingleFileTransfer.cpp68
-rw-r--r--Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp4
-rw-r--r--Swiften/FileTransfer/JingleFileTransfer.cpp50
-rw-r--r--Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp6
-rw-r--r--Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp62
-rw-r--r--Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp8
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp34
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp12
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp6
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp30
-rw-r--r--Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp24
-rw-r--r--Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp6
-rw-r--r--Swiften/IDN/PlatformIDNConverter.cpp10
-rw-r--r--Swiften/IDN/PlatformIDNConverter.h6
-rw-r--r--Swiften/JID/JID.cpp70
-rw-r--r--Swiften/JID/JID.h6
-rw-r--r--Swiften/JID/UnitTest/JIDTest.cpp51
-rw-r--r--Swiften/Jingle/AbstractJingleSessionListener.cpp16
-rw-r--r--Swiften/Jingle/JingleResponder.cpp8
-rw-r--r--Swiften/Jingle/JingleSessionImpl.cpp6
-rw-r--r--Swiften/Jingle/JingleSessionManager.cpp4
-rw-r--r--Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp4
-rw-r--r--Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h8
-rw-r--r--Swiften/LinkLocal/LinkLocalServiceInfo.cpp4
-rw-r--r--Swiften/Network/BOSHConnection.cpp16
-rw-r--r--Swiften/Network/BOSHConnection.h2
-rw-r--r--Swiften/Network/BOSHConnectionPool.cpp4
-rw-r--r--Swiften/Network/BoostConnection.cpp8
-rw-r--r--Swiften/Network/BoostConnectionServer.cpp4
-rw-r--r--Swiften/Network/BoostNetworkFactories.cpp7
-rw-r--r--Swiften/Network/BoostNetworkFactories.h8
-rw-r--r--Swiften/Network/ChainedConnector.cpp10
-rw-r--r--Swiften/Network/Connector.cpp26
-rw-r--r--Swiften/Network/EnvironmentProxyProvider.cpp4
-rw-r--r--Swiften/Network/GConfProxyProvider.cpp4
-rw-r--r--Swiften/Network/HTTPConnectProxiedConnection.cpp12
-rw-r--r--Swiften/Network/HostAddress.cpp4
-rw-r--r--Swiften/Network/NATPMPInterface.cpp14
-rw-r--r--Swiften/Network/PlatformDomainNameServiceQuery.cpp6
-rw-r--r--Swiften/Network/PlatformNATTraversalWorker.cpp4
-rw-r--r--Swiften/Network/ProxiedConnection.cpp4
-rw-r--r--Swiften/Network/SOCKS5ProxiedConnection.cpp14
-rw-r--r--Swiften/Network/UnboundDomainNameResolver.cpp26
-rw-r--r--Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp6
-rw-r--r--Swiften/Network/WindowsProxyProvider.cpp4
-rw-r--r--Swiften/Parser/Attribute.h8
-rw-r--r--Swiften/Parser/AttributeMap.cpp4
-rw-r--r--Swiften/Parser/AttributeMap.h1
-rw-r--r--Swiften/Parser/ExpatParser.cpp80
-rw-r--r--Swiften/Parser/ExpatParser.h2
-rw-r--r--Swiften/Parser/IQParser.cpp4
-rw-r--r--Swiften/Parser/LibXMLParser.cpp78
-rw-r--r--Swiften/Parser/LibXMLParser.h5
-rw-r--r--Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h2
-rw-r--r--Swiften/Parser/PlatformXMLParserFactory.cpp6
-rw-r--r--Swiften/Parser/PlatformXMLParserFactory.h2
-rw-r--r--Swiften/Parser/PresenceParser.cpp4
-rw-r--r--Swiften/Parser/StreamErrorParser.cpp6
-rw-r--r--Swiften/Parser/UnitTest/AttributeMapTest.cpp17
-rw-r--r--Swiften/Parser/UnitTest/XMLParserTest.cpp147
-rw-r--r--Swiften/Parser/XMLParser.cpp2
-rw-r--r--Swiften/Parser/XMLParser.h7
-rw-r--r--Swiften/Parser/XMLParserClient.cpp11
-rw-r--r--Swiften/Parser/XMLParserClient.h18
-rw-r--r--Swiften/Parser/XMLParserFactory.h2
-rw-r--r--Swiften/QA/TLSTest/CertificateTest.cpp69
-rw-r--r--Swiften/QA/TLSTest/certificateChain.pem49
-rw-r--r--Swiften/QA/TLSTest/privateKey.pem40
-rw-r--r--Swiften/Roster/XMPPRosterController.cpp4
-rw-r--r--Swiften/SASL/WindowsAuthentication.cpp34
-rw-r--r--Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp24
-rw-r--r--Swiften/SASL/WindowsServicePrincipalName.cpp20
-rw-r--r--Swiften/SConscript1
-rw-r--r--Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp6
-rw-r--r--Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.cpp4
-rw-r--r--Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp10
-rw-r--r--Swiften/Serializer/StanzaSerializer.cpp4
-rw-r--r--Swiften/Serializer/StreamErrorSerializer.cpp2
-rw-r--r--Swiften/Serializer/XMPPSerializer.cpp4
-rw-r--r--Swiften/StreamManagement/StanzaAckRequester.cpp4
-rw-r--r--Swiften/StreamStack/WhitespacePingLayer.cpp4
-rw-r--r--Swiften/TLS/CAPICertificate.cpp26
-rw-r--r--Swiften/TLS/CertificateFactory.cpp4
-rw-r--r--Swiften/TLS/CertificateFactory.h2
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp12
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificate.h2
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp14
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h2
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContext.cpp367
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContext.h13
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp10
-rw-r--r--Swiften/TLS/OpenSSL/OpenSSLContextFactory.h2
-rw-r--r--Swiften/TLS/Schannel/SchannelContext.cpp12
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportContext.mm70
-rw-r--r--Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp4
-rw-r--r--Swiften/TLS/ServerIdentityVerifier.cpp12
-rw-r--r--Swiften/TLS/ServerIdentityVerifier.h3
-rw-r--r--Swiften/TLS/TLSContext.cpp2
-rw-r--r--Swiften/TLS/TLSContext.h4
-rw-r--r--Swiften/TLS/TLSOptions.h54
-rw-r--r--Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp52
133 files changed, 1711 insertions, 660 deletions
diff --git a/Swiften/Avatars/CombinedAvatarProvider.cpp b/Swiften/Avatars/CombinedAvatarProvider.cpp
index 465512f..ba6e6be 100644
--- a/Swiften/Avatars/CombinedAvatarProvider.cpp
+++ b/Swiften/Avatars/CombinedAvatarProvider.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.
*/
@@ -39,17 +39,17 @@ void CombinedAvatarProvider::handleAvatarChanged(const JID& jid) {
}
boost::optional<std::string> newHash = getCombinedAvatarAndCache(jid);
if (newHash != oldHash) {
- SWIFT_LOG(debug) << "Avatar changed: " << jid << ": " << oldHash << " -> " << (newHash ? newHash.get() : "NULL") << std::endl;
+ SWIFT_LOG(debug) << "Avatar changed: " << jid << ": " << oldHash << " -> " << (newHash ? newHash.get() : "NULL");
onAvatarChanged(jid);
}
}
boost::optional<std::string> CombinedAvatarProvider::getCombinedAvatarAndCache(const JID& jid) const {
- SWIFT_LOG(debug) << "JID: " << jid << std::endl;
+ SWIFT_LOG(debug) << "JID: " << jid;
boost::optional<std::string> hash;
for (size_t i = 0; i < providers.size() && !hash; ++i) {
hash = providers[i]->getAvatarHash(jid);
- SWIFT_LOG(debug) << "Provider " << providers[i] << ": " << (hash ? hash.get() : "NULL") << std::endl;
+ SWIFT_LOG(debug) << "Provider " << providers[i] << ": " << (hash ? hash.get() : "NULL");
}
if (hash) {
avatars[jid] = *hash;
diff --git a/Swiften/Avatars/VCardUpdateAvatarManager.cpp b/Swiften/Avatars/VCardUpdateAvatarManager.cpp
index 349af2f..d04c13c 100644
--- a/Swiften/Avatars/VCardUpdateAvatarManager.cpp
+++ b/Swiften/Avatars/VCardUpdateAvatarManager.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -33,13 +33,13 @@ void VCardUpdateAvatarManager::handlePresenceReceived(std::shared_ptr<Presence>
}
JID from = getAvatarJID(presence->getFrom());
if (update->getPhotoHash().size() != 40) {
- SWIFT_LOG(debug) << "Invalid vCard avatar photo hash length. Must be hex-encoded SHA-1, i.e. 40 characters." << std::endl;
+ SWIFT_LOG(debug) << "Invalid vCard avatar photo hash length. Must be hex-encoded SHA-1, i.e. 40 characters.";
return;
}
if (getAvatarHash(from) == update->getPhotoHash()) {
return;
}
- SWIFT_LOG(debug) << "Updated hash: " << from << " -> " << update->getPhotoHash() << std::endl;
+ SWIFT_LOG(debug) << "Updated hash: " << from << " -> " << update->getPhotoHash();
if (avatarStorage_->hasAvatar(update->getPhotoHash())) {
setAvatarHash(from, update->getPhotoHash());
}
@@ -50,7 +50,7 @@ void VCardUpdateAvatarManager::handlePresenceReceived(std::shared_ptr<Presence>
void VCardUpdateAvatarManager::handleVCardChanged(const JID& from, VCard::ref vCard) {
if (!vCard) {
- SWIFT_LOG(debug) << "Missing element: " << from << ": null vcard payload" << std::endl;
+ SWIFT_LOG(debug) << "Missing element: " << from << ": null vcard payload";
return;
}
@@ -67,7 +67,7 @@ void VCardUpdateAvatarManager::handleVCardChanged(const JID& from, VCard::ref vC
}
void VCardUpdateAvatarManager::setAvatarHash(const JID& from, const std::string& hash) {
- SWIFT_LOG(debug) << "Updating hash: " << from << " -> " << hash << std::endl;
+ SWIFT_LOG(debug) << "Updating hash: " << from << " -> " << hash;
avatarHashes_[from] = hash;
onAvatarChanged(from);
}
diff --git a/Swiften/Base/DateTime.cpp b/Swiften/Base/DateTime.cpp
index 4443566..23b3b84 100644
--- a/Swiften/Base/DateTime.cpp
+++ b/Swiften/Base/DateTime.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.
*/
@@ -40,7 +40,7 @@ std::string dateTimeToLocalString(const boost::posix_time::ptime& time) {
localString = boost::posix_time::to_simple_string(boost::date_time::c_local_adjustor<boost::posix_time::ptime>::utc_to_local(time));
}
catch(std::out_of_range& exception) {
- SWIFT_LOG(debug) << exception.what() << std::endl;
+ SWIFT_LOG(debug) << exception.what();
}
return localString;
}
diff --git a/Swiften/Base/Log.cpp b/Swiften/Base/Log.cpp
index 9b16531..b6f1851 100644
--- a/Swiften/Base/Log.cpp
+++ b/Swiften/Base/Log.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2015 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -17,6 +17,7 @@ namespace Swift {
static Log::Severity logLevel = Log::warning;
std::unique_ptr<FILE, Log::LogFileClose> Log::logfile;
+Log::Callback Log::logCallback;
Log::Log() {
}
@@ -26,24 +27,38 @@ Log::~Log() {
__android_log_print(ANDROID_LOG_VERBOSE, "Swift", stream.str().c_str(), 1);
#else
// Using stdio for thread safety (POSIX file i/o calls are guaranteed to be atomic)
- if (logfile) {
- fwrite(stream.str().c_str(), sizeof(char), stream.str().size(), logfile.get());
- fflush(logfile.get());
+ if (logCallback) {
+ logCallback(severity_, std::move(file_), line_, std::move(function_), stream.str());
}
else {
- fwrite(stream.str().c_str(), sizeof(char), stream.str().size(), stderr);
- fflush(stderr);
+ stream << std::endl;
+ if (logfile) {
+ fwrite(stream.str().c_str(), sizeof(char), stream.str().size(), logfile.get());
+ fflush(logfile.get());
+ }
+ else {
+ fwrite(stream.str().c_str(), sizeof(char), stream.str().size(), stderr);
+ fflush(stderr);
+ }
}
#endif
}
std::ostringstream& Log::getStream(
- Severity /*severity*/,
- const std::string& severityString,
- const std::string& file,
+ Severity severity,
+ std::string severityString,
+ std::string file,
int line,
- const std::string& function) {
- stream << "[" << severityString << "] " << file << ":" << line << " " << function << ": ";
+ std::string function) {
+ if (logCallback) {
+ severity_ = severity;
+ file_ = std::move(file);
+ line_ = line;
+ function_ = std::move(function);
+ }
+ else {
+ stream << "[" << severityString << "] " << file << ":" << line << " " << function << ": ";
+ }
return stream;
}
@@ -61,4 +76,8 @@ void Log::setLogFile(const std::string& fileName) {
}
}
+void Log::setLogCallback(Callback callback) {
+ Log::logCallback = callback;
+}
+
}
diff --git a/Swiften/Base/Log.h b/Swiften/Base/Log.h
index e3e04a5..255e478 100644
--- a/Swiften/Base/Log.h
+++ b/Swiften/Base/Log.h
@@ -7,6 +7,7 @@
#pragma once
#include <cstdio>
+#include <functional>
#include <memory>
#include <sstream>
@@ -18,20 +19,22 @@ namespace Swift {
enum Severity {
error, warning, info, debug
};
+ using Callback = std::function<void(Severity severity, std::string file, int line, std::string function, std::string message)>;
Log();
~Log();
std::ostringstream& getStream(
Severity severity,
- const std::string& severityString,
- const std::string& file,
+ std::string severityString,
+ std::string file,
int line,
- const std::string& function);
+ std::string function);
static Severity getLogLevel();
static void setLogLevel(Severity level);
static void setLogFile(const std::string& fileName);
+ static void setLogCallback(Callback callback);
private:
struct LogFileClose {
@@ -43,6 +46,11 @@ namespace Swift {
};
std::ostringstream stream;
static std::unique_ptr<FILE, LogFileClose> logfile;
+ static Callback logCallback;
+ Severity severity_;
+ std::string file_;
+ int line_;
+ std::string function_;
};
}
diff --git a/Swiften/Base/UnitTest/LogTest.cpp b/Swiften/Base/UnitTest/LogTest.cpp
new file mode 100644
index 0000000..5d710db
--- /dev/null
+++ b/Swiften/Base/UnitTest/LogTest.cpp
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2019 Isode Limited.
+ * All rights reserved.
+ * See the COPYING file for more information.
+ */
+
+#include <vector>
+
+#include <boost/algorithm/string/predicate.hpp>
+
+#include <gtest/gtest.h>
+
+#include <Swiften/Base/Log.h>
+
+using namespace Swift;
+
+struct LogEntry {
+ LogEntry(Log::Severity severity, std::string file, int line, std::string function, std::string message) : severity(severity), file(std::move(file)), line(line), function(std::move(function)), message(std::move(message)) {}
+
+ Log::Severity severity;
+ std::string file;
+ int line;
+ std::string function;
+ std::string message;
+};
+
+// Helper class to set the logging callback. Using this class to set it will ensure the
+// logCallback is reset to empty (its default state) after each test.
+class LogCallbackSetter {
+public:
+ LogCallbackSetter(Log::Callback callback) {
+ Log::setLogCallback(callback);
+ }
+ ~LogCallbackSetter() {
+ Log::setLogCallback({});
+ }
+};
+
+TEST(LogTest, testCallback) {
+ std::vector<LogEntry> logEntries;
+ LogCallbackSetter callbackSetter = {[&](Log::Severity severity, const std::string& file, int line, const std::string& function, const std::string& message) {
+ logEntries.emplace_back(severity, file, line, function, message);
+ }};
+
+ SWIFT_LOG(error) << "An error";
+ ASSERT_EQ(1, logEntries.size());
+ ASSERT_EQ(Log::error, logEntries[0].severity);
+ ASSERT_EQ("An error", logEntries[0].message);
+}
diff --git a/Swiften/Chat/ChatStateTracker.cpp b/Swiften/Chat/ChatStateTracker.cpp
index 25ecd1c..839f47d 100644
--- a/Swiften/Chat/ChatStateTracker.cpp
+++ b/Swiften/Chat/ChatStateTracker.cpp
@@ -17,7 +17,7 @@ void ChatStateTracker::handleMessageReceived(std::shared_ptr<Message> message) {
}
std::shared_ptr<ChatState> statePayload = message->getPayload<ChatState>();
if (statePayload) {
- changeState(statePayload->getChatState());;
+ changeState(statePayload->getChatState());
}
}
diff --git a/Swiften/Client/ClientSession.cpp b/Swiften/Client/ClientSession.cpp
index bb9be58..1114336 100644
--- a/Swiften/Client/ClientSession.cpp
+++ b/Swiften/Client/ClientSession.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.
*/
@@ -88,7 +88,7 @@ ClientSession::ClientSession(
authenticationPort(-1) {
#ifdef SWIFTEN_PLATFORM_WIN32
if (WindowsRegistry::isFIPSEnabled()) {
- SWIFT_LOG(info) << "Windows is running in FIPS-140 mode. Some authentication methods will be unavailable." << std::endl;
+ SWIFT_LOG(info) << "Windows is running in FIPS-140 mode. Some authentication methods will be unavailable.";
}
#endif
}
@@ -122,7 +122,7 @@ void ClientSession::sendStanza(std::shared_ptr<Stanza> stanza) {
}
void ClientSession::handleStreamStart(const ProtocolHeader&) {
- CHECK_STATE_OR_RETURN(State::WaitingForStreamStart);
+ CHECK_STATE_OR_RETURN(State::WaitingForStreamStart)
state = State::Negotiating;
}
@@ -214,7 +214,7 @@ void ClientSession::handleElement(std::shared_ptr<ToplevelElement> element) {
}
}
else if (StreamFeatures* streamFeatures = dynamic_cast<StreamFeatures*>(element.get())) {
- CHECK_STATE_OR_RETURN(State::Negotiating);
+ CHECK_STATE_OR_RETURN(State::Negotiating)
if (streamFeatures->hasStartTLS() && stream->supportsTLSEncryption() && useTLS != NeverUseTLS) {
state = State::WaitingForEncrypt;
@@ -320,7 +320,7 @@ void ClientSession::handleElement(std::shared_ptr<ToplevelElement> element) {
}
}
else if (std::dynamic_pointer_cast<Compressed>(element)) {
- CHECK_STATE_OR_RETURN(State::Compressing);
+ CHECK_STATE_OR_RETURN(State::Compressing)
state = State::WaitingForStreamStart;
stream->addZLibCompression();
stream->resetXMPPParser();
@@ -343,7 +343,7 @@ void ClientSession::handleElement(std::shared_ptr<ToplevelElement> element) {
continueSessionInitialization();
}
else if (AuthChallenge* challenge = dynamic_cast<AuthChallenge*>(element.get())) {
- CHECK_STATE_OR_RETURN(State::Authenticating);
+ CHECK_STATE_OR_RETURN(State::Authenticating)
assert(authenticator);
if (authenticator->setChallenge(challenge->getValue())) {
stream->writeElement(std::make_shared<AuthResponse>(authenticator->getResponse()));
@@ -361,7 +361,7 @@ void ClientSession::handleElement(std::shared_ptr<ToplevelElement> element) {
}
}
else if (AuthSuccess* authSuccess = dynamic_cast<AuthSuccess*>(element.get())) {
- CHECK_STATE_OR_RETURN(State::Authenticating);
+ CHECK_STATE_OR_RETURN(State::Authenticating)
assert(authenticator);
if (!authenticator->setChallenge(authSuccess->getValue())) {
finishSession(Error::ServerVerificationFailedError);
@@ -378,7 +378,7 @@ void ClientSession::handleElement(std::shared_ptr<ToplevelElement> element) {
finishSession(Error::AuthenticationFailedError);
}
else if (dynamic_cast<TLSProceed*>(element.get())) {
- CHECK_STATE_OR_RETURN(State::WaitingForEncrypt);
+ CHECK_STATE_OR_RETURN(State::WaitingForEncrypt)
state = State::Encrypting;
stream->addTLSEncryption();
}
@@ -433,7 +433,7 @@ void ClientSession::sendCredentials(const SafeByteArray& password) {
void ClientSession::handleTLSEncrypted() {
if (!std::dynamic_pointer_cast<BOSHSessionStream>(stream)) {
- CHECK_STATE_OR_RETURN(State::Encrypting);
+ CHECK_STATE_OR_RETURN(State::Encrypting)
}
std::vector<Certificate::ref> certificateChain = stream->getPeerCertificateChain();
@@ -531,7 +531,7 @@ void ClientSession::finish() {
finishSession(std::shared_ptr<Error>());
}
else {
- SWIFT_LOG(warning) << "Session already finished or finishing." << std::endl;
+ SWIFT_LOG(warning) << "Session already finished or finishing.";
}
}
@@ -544,7 +544,7 @@ void ClientSession::finishSession(std::shared_ptr<Swift::Error> error) {
error_ = error;
}
else {
- SWIFT_LOG(warning) << "Session finished twice" << std::endl;
+ SWIFT_LOG(warning) << "Session finished twice";
}
assert(stream->isOpen());
if (stanzaAckResponder_) {
diff --git a/Swiften/Client/ClientSessionStanzaChannel.cpp b/Swiften/Client/ClientSessionStanzaChannel.cpp
index f48b306..6a5d07d 100644
--- a/Swiften/Client/ClientSessionStanzaChannel.cpp
+++ b/Swiften/Client/ClientSessionStanzaChannel.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.
*/
@@ -49,7 +49,7 @@ std::string ClientSessionStanzaChannel::getNewIQID() {
void ClientSessionStanzaChannel::send(std::shared_ptr<Stanza> stanza) {
if (!isAvailable()) {
- SWIFT_LOG(warning) << "Client: Trying to send a stanza while disconnected." << std::endl;
+ SWIFT_LOG(warning) << "Client: Trying to send a stanza while disconnected.";
return;
}
session->sendStanza(stanza);
diff --git a/Swiften/Client/CoreClient.cpp b/Swiften/Client/CoreClient.cpp
index ccde0c2..7579bca 100644
--- a/Swiften/Client/CoreClient.cpp
+++ b/Swiften/Client/CoreClient.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -69,21 +69,21 @@ void CoreClient::connect(const ClientOptions& o) {
HostAddressPort systemHTTPConnectProxy = networkFactories->getProxyProvider()->getHTTPConnectProxy();
switch (o.proxyType) {
case ClientOptions::NoProxy:
- SWIFT_LOG(debug) << " without a proxy" << std::endl;
+ SWIFT_LOG(debug) << " without a proxy";
break;
case ClientOptions::SystemConfiguredProxy:
- SWIFT_LOG(debug) << " with a system configured proxy" << std::endl;
+ SWIFT_LOG(debug) << " with a system configured proxy";
if (systemSOCKS5Proxy.isValid()) {
- SWIFT_LOG(debug) << "Found SOCK5 Proxy: " << systemSOCKS5Proxy.getAddress().toString() << ":" << systemSOCKS5Proxy.getPort() << std::endl;
+ SWIFT_LOG(debug) << "Found SOCK5 Proxy: " << systemSOCKS5Proxy.getAddress().toString() << ":" << systemSOCKS5Proxy.getPort();
proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemSOCKS5Proxy.getAddress().toString(), systemSOCKS5Proxy.getPort()));
}
if (systemHTTPConnectProxy.isValid()) {
- SWIFT_LOG(debug) << "Found HTTPConnect Proxy: " << systemHTTPConnectProxy.getAddress().toString() << ":" << systemHTTPConnectProxy.getPort() << std::endl;
+ SWIFT_LOG(debug) << "Found HTTPConnect Proxy: " << systemHTTPConnectProxy.getAddress().toString() << ":" << systemHTTPConnectProxy.getPort();
proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), systemHTTPConnectProxy.getAddress().toString(), systemHTTPConnectProxy.getPort()));
}
break;
case ClientOptions::SOCKS5Proxy: {
- SWIFT_LOG(debug) << " with manual configured SOCKS5 proxy" << std::endl;
+ SWIFT_LOG(debug) << " with manual configured SOCKS5 proxy";
std::string proxyHostname = o.manualProxyHostname.empty() ? systemSOCKS5Proxy.getAddress().toString() : o.manualProxyHostname;
auto proxyPort = systemSOCKS5Proxy.getPort();
if (o.manualProxyPort != -1) {
@@ -91,18 +91,18 @@ void CoreClient::connect(const ClientOptions& o) {
proxyPort = boost::numeric_cast<unsigned short>(o.manualProxyPort);
}
catch (const boost::numeric::bad_numeric_cast& e) {
- SWIFT_LOG(warning) << "Manual proxy port " << o.manualProxyPort << " is invalid: " << e.what() << std::endl;
+ SWIFT_LOG(warning) << "Manual proxy port " << o.manualProxyPort << " is invalid: " << e.what();
onDisconnected(boost::optional<ClientError>(ClientError::ConnectionError));
return;
}
}
- SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl;
+ SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort;
proxyConnectionFactories.push_back(new SOCKS5ProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort));
useDirectConnection = false;
break;
}
case ClientOptions::HTTPConnectProxy: {
- SWIFT_LOG(debug) << " with manual configured HTTPConnect proxy" << std::endl;
+ SWIFT_LOG(debug) << " with manual configured HTTPConnect proxy";
std::string proxyHostname = o.manualProxyHostname.empty() ? systemHTTPConnectProxy.getAddress().toString() : o.manualProxyHostname;
unsigned short proxyPort = systemHTTPConnectProxy.getPort();
if (o.manualProxyPort != -1) {
@@ -110,12 +110,12 @@ void CoreClient::connect(const ClientOptions& o) {
proxyPort = boost::numeric_cast<unsigned short>(o.manualProxyPort);
}
catch (const boost::numeric::bad_numeric_cast& e) {
- SWIFT_LOG(warning) << "Manual proxy port " << o.manualProxyPort << " is invalid: " << e.what() << std::endl;
+ SWIFT_LOG(warning) << "Manual proxy port " << o.manualProxyPort << " is invalid: " << e.what();
onDisconnected(boost::optional<ClientError>(ClientError::ConnectionError));
return;
}
}
- SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort << std::endl;
+ SWIFT_LOG(debug) << "Proxy: " << proxyHostname << ":" << proxyPort;
proxyConnectionFactories.push_back(new HTTPConnectProxiedConnectionFactory(networkFactories->getDomainNameResolver(), networkFactories->getConnectionFactory(), networkFactories->getTimerFactory(), proxyHostname, proxyPort, o.httpTrafficFilter));
useDirectConnection = false;
break;
@@ -134,7 +134,7 @@ void CoreClient::connect(const ClientOptions& o) {
port = boost::numeric_cast<unsigned short>(o.manualPort);
}
catch (const boost::numeric::bad_numeric_cast& e) {
- SWIFT_LOG(warning) << "Invalid manual port " << o.manualPort << ": " << e.what() << std::endl;
+ SWIFT_LOG(warning) << "Invalid manual port " << o.manualPort << ": " << e.what();
onDisconnected(boost::optional<ClientError>(ClientError::ConnectionError));
return;
}
@@ -174,7 +174,7 @@ void CoreClient::connect(const ClientOptions& o) {
sessionStream_->onDataRead.connect(boost::bind(&CoreClient::handleDataRead, this, _1));
sessionStream_->onDataWritten.connect(boost::bind(&CoreClient::handleDataWritten, this, _1));
if (certificate_ && !certificate_->isNull()) {
- SWIFT_LOG(debug) << "set certificate" << std::endl;
+ SWIFT_LOG(debug) << "set certificate";
sessionStream_->setTLSCertificate(certificate_);
}
boshSessionStream_->open();
@@ -423,7 +423,7 @@ void CoreClient::sendPresence(std::shared_ptr<Presence> presence) {
void CoreClient::sendData(const std::string& data) {
if (!sessionStream_) {
- SWIFT_LOG(warning) << "Client: Trying to send data while disconnected." << std::endl;
+ SWIFT_LOG(warning) << "Client: Trying to send data while disconnected.";
return;
}
sessionStream_->writeData(data);
@@ -507,11 +507,11 @@ void CoreClient::resetSession() {
void CoreClient::forceReset() {
if (connector_) {
- SWIFT_LOG(warning) << "Client not disconnected properly: Connector still active" << std::endl;
+ SWIFT_LOG(warning) << "Client not disconnected properly: Connector still active";
resetConnector();
}
if (sessionStream_ || connection_) {
- SWIFT_LOG(warning) << "Client not disconnected properly: Session still active" << std::endl;
+ SWIFT_LOG(warning) << "Client not disconnected properly: Session still active";
resetSession();
}
}
diff --git a/Swiften/Component/ComponentSessionStanzaChannel.cpp b/Swiften/Component/ComponentSessionStanzaChannel.cpp
index e4bf231..deac8b2 100644
--- a/Swiften/Component/ComponentSessionStanzaChannel.cpp
+++ b/Swiften/Component/ComponentSessionStanzaChannel.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2017 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -47,7 +47,7 @@ std::string ComponentSessionStanzaChannel::getNewIQID() {
void ComponentSessionStanzaChannel::send(std::shared_ptr<Stanza> stanza) {
if (!isAvailable()) {
- SWIFT_LOG(warning) << "Component: Trying to send a stanza while disconnected." << std::endl;
+ SWIFT_LOG(warning) << "Component: Trying to send a stanza while disconnected.";
return;
}
session->sendStanza(stanza);
diff --git a/Swiften/Component/CoreComponent.cpp b/Swiften/Component/CoreComponent.cpp
index 2d91c9c..ef7d3a4 100644
--- a/Swiften/Component/CoreComponent.cpp
+++ b/Swiften/Component/CoreComponent.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -33,7 +33,7 @@ CoreComponent::CoreComponent(const JID& jid, const std::string& secret, NetworkF
CoreComponent::~CoreComponent() {
if (session_ || connection_) {
- SWIFT_LOG(warning) << "Component not disconnected properly" << std::endl;
+ SWIFT_LOG(warning) << "Component not disconnected properly";
}
delete iqRouter_;
diff --git a/Swiften/Disco/CapsManager.cpp b/Swiften/Disco/CapsManager.cpp
index 794cf74..2b8fb7d 100644
--- a/Swiften/Disco/CapsManager.cpp
+++ b/Swiften/Disco/CapsManager.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.
*/
@@ -53,7 +53,7 @@ void CapsManager::handleDiscoInfoReceived(const JID& from, const std::string& ha
requestedDiscoInfos.erase(hash);
if (error || !discoInfo || CapsInfoGenerator("", crypto).generateCapsInfo(*discoInfo.get()).getVersion() != hash) {
if (warnOnInvalidHash && !error && discoInfo) {
- SWIFT_LOG(warning) << "Caps from " << from.toString() << " do not verify" << std::endl;
+ SWIFT_LOG(warning) << "Caps from " << from.toString() << " do not verify";
}
failingCaps.insert(std::make_pair(from, hash));
std::map<std::string, std::set< std::pair<JID, std::string> > >::iterator i = fallbacks.find(hash);
diff --git a/Swiften/Disco/DiscoServiceWalker.cpp b/Swiften/Disco/DiscoServiceWalker.cpp
index a3f95d2..7332e63 100644
--- a/Swiften/Disco/DiscoServiceWalker.cpp
+++ b/Swiften/Disco/DiscoServiceWalker.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 @@ DiscoServiceWalker::DiscoServiceWalker(const JID& service, IQRouter* iqRouter, s
}
void DiscoServiceWalker::beginWalk() {
- SWIFT_LOG(debug) << "Starting walk to " << service_ << std::endl;
+ SWIFT_LOG(debug) << "Starting walk to " << service_;
assert(!active_);
assert(servicesBeingSearched_.empty());
active_ = true;
@@ -26,7 +26,7 @@ void DiscoServiceWalker::beginWalk() {
void DiscoServiceWalker::endWalk() {
if (active_) {
- SWIFT_LOG(debug) << "Ending walk to " << service_ << std::endl;
+ SWIFT_LOG(debug) << "Ending walk to " << service_;
for (auto&& request : pendingDiscoInfoRequests_) {
request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request));
}
@@ -39,7 +39,7 @@ void DiscoServiceWalker::endWalk() {
}
void DiscoServiceWalker::walkNode(const JID& jid) {
- SWIFT_LOG(debug) << "Walking node " << jid << std::endl;
+ SWIFT_LOG(debug) << "Walking node " << jid;
servicesBeingSearched_.insert(jid);
searchedServices_.insert(jid);
GetDiscoInfoRequest::ref discoInfoRequest = GetDiscoInfoRequest::create(jid, iqRouter_);
@@ -54,7 +54,7 @@ void DiscoServiceWalker::handleDiscoInfoResponse(std::shared_ptr<DiscoInfo> info
return;
}
- SWIFT_LOG(debug) << "Disco info response from " << request->getReceiver() << std::endl;
+ SWIFT_LOG(debug) << "Disco info response from " << request->getReceiver();
request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoInfoResponse, this, _1, _2, request));
pendingDiscoInfoRequests_.erase(request);
@@ -90,7 +90,7 @@ void DiscoServiceWalker::handleDiscoItemsResponse(std::shared_ptr<DiscoItems> it
return;
}
- SWIFT_LOG(debug) << "Received disco items from " << request->getReceiver() << std::endl;
+ SWIFT_LOG(debug) << "Received disco items from " << request->getReceiver();
request->onResponse.disconnect(boost::bind(&DiscoServiceWalker::handleDiscoItemsResponse, this, _1, _2, request));
pendingDiscoItemsRequests_.erase(request);
if (error) {
@@ -103,7 +103,7 @@ void DiscoServiceWalker::handleDiscoItemsResponse(std::shared_ptr<DiscoItems> it
* but I've never seen one in the wild, and it's an easy fix for not looping.
*/
if (std::find(searchedServices_.begin(), searchedServices_.end(), item.getJID()) == searchedServices_.end()) { /* Don't recurse infinitely */
- SWIFT_LOG(debug) << "Received disco item " << item.getJID() << std::endl;
+ SWIFT_LOG(debug) << "Received disco item " << item.getJID();
walkNode(item.getJID());
}
}
@@ -112,12 +112,12 @@ void DiscoServiceWalker::handleDiscoItemsResponse(std::shared_ptr<DiscoItems> it
}
void DiscoServiceWalker::handleDiscoError(const JID& jid, ErrorPayload::ref /*error*/) {
- SWIFT_LOG(debug) << "Disco error from " << jid << std::endl;
+ SWIFT_LOG(debug) << "Disco error from " << jid;
markNodeCompleted(jid);
}
void DiscoServiceWalker::markNodeCompleted(const JID& jid) {
- SWIFT_LOG(debug) << "Node completed " << jid << std::endl;
+ SWIFT_LOG(debug) << "Node completed " << jid;
servicesBeingSearched_.erase(jid);
/* All results are in */
if (servicesBeingSearched_.empty()) {
diff --git a/Swiften/Elements/JingleFileTransferFileInfo.h b/Swiften/Elements/JingleFileTransferFileInfo.h
index 9fd8756..0e8ccd4 100644
--- a/Swiften/Elements/JingleFileTransferFileInfo.h
+++ b/Swiften/Elements/JingleFileTransferFileInfo.h
@@ -36,7 +36,7 @@ namespace Swift {
public:
void setName(const std::string& name) {
- name_ = name;;
+ name_ = name;
}
const std::string& getName() const {
diff --git a/Swiften/Elements/StreamError.h b/Swiften/Elements/StreamError.h
index aa294fd..6dda15c 100644
--- a/Swiften/Elements/StreamError.h
+++ b/Swiften/Elements/StreamError.h
@@ -27,7 +27,6 @@ namespace Swift {
ImproperAddressing,
InternalServerError,
InvalidFrom,
- InvalidID,
InvalidNamespace,
InvalidXML,
NotAuthorized,
@@ -41,6 +40,7 @@ namespace Swift {
SystemShutdown,
UndefinedCondition,
UnsupportedEncoding,
+ UnsupportedFeature,
UnsupportedStanzaType,
UnsupportedVersion
};
diff --git a/Swiften/Elements/StreamInitiationFileInfo.h b/Swiften/Elements/StreamInitiationFileInfo.h
index f2dc5b9..773814f 100644
--- a/Swiften/Elements/StreamInitiationFileInfo.h
+++ b/Swiften/Elements/StreamInitiationFileInfo.h
@@ -26,7 +26,7 @@ public:
name(name), description(description), size(size), hash(hash), date(date), algo(algo), supportsRangeRequests(false), rangeOffset(0) {}
void setName(const std::string& name) {
- this->name = name;;
+ this->name = name;
}
const std::string& getName() const {
diff --git a/Swiften/Entity/PayloadPersister.cpp b/Swiften/Entity/PayloadPersister.cpp
index 3fd246c..fe51d86 100644
--- a/Swiften/Entity/PayloadPersister.cpp
+++ b/Swiften/Entity/PayloadPersister.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.
*/
@@ -34,7 +34,7 @@ void PayloadPersister::savePayload(std::shared_ptr<Payload> payload, const boost
file.close();
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << e.what() << std::endl;
+ SWIFT_LOG(error) << e.what();
}
}
@@ -50,7 +50,7 @@ std::shared_ptr<Payload> PayloadPersister::loadPayload(const boost::filesystem::
}
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << e.what() << std::endl;
+ SWIFT_LOG(error) << e.what();
}
return std::shared_ptr<Payload>();
}
diff --git a/Swiften/EventLoop/BoostASIOEventLoop.cpp b/Swiften/EventLoop/BoostASIOEventLoop.cpp
index 30143b9..45dd4a2 100644
--- a/Swiften/EventLoop/BoostASIOEventLoop.cpp
+++ b/Swiften/EventLoop/BoostASIOEventLoop.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015-2016 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -23,7 +23,7 @@ void BoostASIOEventLoop::handleASIOEvent() {
std::unique_lock<std::recursive_mutex> lock(isEventInASIOEventLoopMutex_);
isEventInASIOEventLoop_ = false;
}
- handleNextEvents();
+ handleNextEvent();
}
void BoostASIOEventLoop::eventPosted() {
diff --git a/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm b/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm
index b8ab621..39dc7ec 100644
--- a/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm
+++ b/Swiften/EventLoop/Cocoa/CocoaEventLoop.mm
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015-2016 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -23,7 +23,7 @@ void CocoaEventLoop::handleNextCocoaEvent() {
std::unique_lock<std::recursive_mutex> lock(isEventInCocoaEventLoopMutex_);
isEventInCocoaEventLoop_ = false;
}
- handleNextEvents();
+ handleNextEvent();
}
void CocoaEventLoop::eventPosted() {
diff --git a/Swiften/EventLoop/DummyEventLoop.cpp b/Swiften/EventLoop/DummyEventLoop.cpp
index 4dfbac3..234ba7a 100644
--- a/Swiften/EventLoop/DummyEventLoop.cpp
+++ b/Swiften/EventLoop/DummyEventLoop.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.
*/
@@ -15,14 +15,14 @@ DummyEventLoop::DummyEventLoop() {
DummyEventLoop::~DummyEventLoop() {
if (hasEvents()) {
- SWIFT_LOG(warning) << "DummyEventLoop: Unhandled events at destruction time" << std::endl;
+ SWIFT_LOG(warning) << "DummyEventLoop: Unhandled events at destruction time";
}
}
void DummyEventLoop::processEvents() {
while(hasEvents()) {
hasEvents_ = false;
- handleNextEvents();
+ handleNextEvent();
}
}
diff --git a/Swiften/EventLoop/EventLoop.cpp b/Swiften/EventLoop/EventLoop.cpp
index f6af699..1852f3f 100644
--- a/Swiften/EventLoop/EventLoop.cpp
+++ b/Swiften/EventLoop/EventLoop.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -22,10 +22,10 @@ inline void invokeCallback(const Event& event) {
event.callback();
}
catch (const std::exception& e) {
- SWIFT_LOG(error) << "Uncaught exception in event loop: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "Uncaught exception in event loop: " << e.what();
}
catch (...) {
- SWIFT_LOG(error) << "Uncaught non-exception in event loop" << std::endl;
+ SWIFT_LOG(error) << "Uncaught non-exception in event loop";
}
}
@@ -35,9 +35,8 @@ EventLoop::EventLoop() : nextEventID_(0), handlingEvents_(false) {
EventLoop::~EventLoop() {
}
-void EventLoop::handleNextEvents() {
- const int eventsBatched = 100;
- // If handleNextEvents is already in progress, e.g. in case of a recursive call due to
+void EventLoop::handleNextEvent() {
+ // If handleNextEvent is already in progress, e.g. in case of a recursive call due to
// the event loop implementation, then do no handle further events. Instead call
// eventPosted() to continue event handling later.
bool callEventPosted = handlingEvents_;
@@ -45,19 +44,17 @@ void EventLoop::handleNextEvents() {
handlingEvents_ = true;
std::unique_lock<std::recursive_mutex> lock(removeEventsMutex_);
{
- std::vector<Event> nextEvents;
+ boost::optional<Event> nextEvent;
{
- std::unique_lock<std::recursive_mutex> lock(eventsMutex_);
- for (int n = 0; ((n < eventsBatched) && !events_.empty()); n++) {
- nextEvents.push_back(events_.front());
+ std::unique_lock<std::recursive_mutex> eventsLock(eventsMutex_);
+ if (!events_.empty()) {
+ nextEvent = events_.front();
events_.pop_front();
}
callEventPosted = !events_.empty();
}
- if (!nextEvents.empty()) {
- for (const auto& event : nextEvents) {
- invokeCallback(event);
- }
+ if (nextEvent) {
+ invokeCallback(*nextEvent);
}
}
handlingEvents_ = false;
diff --git a/Swiften/EventLoop/EventLoop.h b/Swiften/EventLoop/EventLoop.h
index 06b9fbb..f61b9bc 100644
--- a/Swiften/EventLoop/EventLoop.h
+++ b/Swiften/EventLoop/EventLoop.h
@@ -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,21 +43,20 @@ namespace Swift {
protected:
/**
- * The \ref handleNextEvents method is called by an implementation of the abstract \ref EventLoop class
+ * The \ref handleNextEvent method is called by an implementation of the abstract \ref EventLoop class
* at any point after the virtual \ref eventPosted method has been called.
* This method does not block, except for short-time synchronization.
- * It can process multiple events before it reutrns.
* If called recursively, the event queue is not further processed. Instead, \ref eventPosted
* is called to notify the implementing event loop of the non-empty event queue.
- * It is recommended to not call \ref handleNextEvents inside an event posted to the event loop
+ * It is recommended to not call \ref handleNextEvent inside an event posted to the event loop
* as this can lead to an infinite loop.
*/
- void handleNextEvents();
+ void handleNextEvent();
/**
* The \ref eventPosted virtual method serves as notification for when events are still available in the queue.
* It is called after the first event is posted to an empty queue or after an event has been handled in
- * \ref handleNextEvents and there are still remaining events in the queue.
+ * \ref handleNextEvent and there are still remaining events in the queue.
*/
virtual void eventPosted() = 0;
diff --git a/Swiften/EventLoop/Qt/QtEventLoop.h b/Swiften/EventLoop/Qt/QtEventLoop.h
index b1644c2..cf374ab 100644
--- a/Swiften/EventLoop/Qt/QtEventLoop.h
+++ b/Swiften/EventLoop/Qt/QtEventLoop.h
@@ -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.
*/
@@ -38,7 +38,7 @@ namespace Swift {
std::unique_lock<std::recursive_mutex> lock(isEventInQtEventLoopMutex_);
isEventInQtEventLoop_ = false;
}
- handleNextEvents();
+ handleNextEvent();
//event->deleteLater(); FIXME: Leak?
return true;
}
diff --git a/Swiften/EventLoop/SimpleEventLoop.cpp b/Swiften/EventLoop/SimpleEventLoop.cpp
index cac04e4..745fadb 100644
--- a/Swiften/EventLoop/SimpleEventLoop.cpp
+++ b/Swiften/EventLoop/SimpleEventLoop.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.
*/
@@ -34,7 +34,7 @@ void SimpleEventLoop::doRun(bool breakAfterEvents) {
}
void SimpleEventLoop::runOnce() {
- handleNextEvents();
+ handleNextEvent();
}
void SimpleEventLoop::stop() {
diff --git a/Swiften/EventLoop/SingleThreadedEventLoop.cpp b/Swiften/EventLoop/SingleThreadedEventLoop.cpp
index 0542f37..89b4460 100644
--- a/Swiften/EventLoop/SingleThreadedEventLoop.cpp
+++ b/Swiften/EventLoop/SingleThreadedEventLoop.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.
*/
@@ -43,7 +43,7 @@ void SingleThreadedEventLoop::handleEvents() {
std::lock_guard<std::mutex> lock(eventAvailableMutex_);
eventAvailable_ = false;
}
- handleNextEvents();
+ handleNextEvent();
}
void SingleThreadedEventLoop::stop() {
diff --git a/Swiften/EventLoop/UnitTest/EventLoopTest.cpp b/Swiften/EventLoop/UnitTest/EventLoopTest.cpp
index 00a4376..26c56d3 100644
--- a/Swiften/EventLoop/UnitTest/EventLoopTest.cpp
+++ b/Swiften/EventLoop/UnitTest/EventLoopTest.cpp
@@ -23,6 +23,7 @@ class EventLoopTest : public CppUnit::TestFixture {
CPPUNIT_TEST(testPost);
CPPUNIT_TEST(testRemove);
CPPUNIT_TEST(testHandleEvent_Recursive);
+ CPPUNIT_TEST(testHandleEvent_FirstEventRemovesSecondEvent);
CPPUNIT_TEST_SUITE_END();
public:
@@ -74,6 +75,18 @@ class EventLoopTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(1, events_[1]);
}
+ void testHandleEvent_FirstEventRemovesSecondEvent() {
+ DummyEventLoop testling;
+ auto eventOwner = std::make_shared<MyEventOwner>();
+ auto secondEventFired = false;
+
+ testling.postEvent([&](){ testling.removeEventsFromOwner(eventOwner); }, eventOwner);
+ testling.postEvent([&](){ secondEventFired = true; }, eventOwner);
+ testling.processEvents();
+
+ CPPUNIT_ASSERT_EQUAL(false, secondEventFired);
+ }
+
private:
struct MyEventOwner : public EventOwner {};
void logEvent(int i) {
diff --git a/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp b/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp
index 607038f..cc783c6 100644
--- a/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp
+++ b/Swiften/Examples/ConnectivityTest/ConnectivityTest.cpp
@@ -77,7 +77,7 @@ int main(int argc, char* argv[]) {
ClientXMLTracer* tracer = new ClientXMLTracer(client);
client->onConnected.connect(&handleConnected);
errorConnection = client->onDisconnected.connect(&handleDisconnected);
- std::cout << "Connecting to JID " << jid << " with timeout " << timeout << "ms on host: "; ;
+ std::cout << "Connecting to JID " << jid << " with timeout " << timeout << "ms on host: ";
if (!connectHost.empty()) {
std::cout << connectHost << std::endl;
ClientOptions options;
diff --git a/Swiften/Examples/SendFile/ReceiveFile.cpp b/Swiften/Examples/SendFile/ReceiveFile.cpp
index 193c1b7..d641662 100644
--- a/Swiften/Examples/SendFile/ReceiveFile.cpp
+++ b/Swiften/Examples/SendFile/ReceiveFile.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.
*/
@@ -80,7 +80,7 @@ class FileReceiver {
}
void handleIncomingFileTransfer(IncomingFileTransfer::ref transfer) {
- SWIFT_LOG(debug) << "foo" << std::endl;
+ SWIFT_LOG(debug) << "foo";
incomingFileTransfers.push_back(transfer);
std::shared_ptr<FileWriteBytestream> out = std::make_shared<FileWriteBytestream>("out");
transfer->onFinished.connect(boost::bind(&FileReceiver::handleFileTransferFinished, this, _1, out));
diff --git a/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp b/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
index c6987c0..ae3d7e0 100644
--- a/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
+++ b/Swiften/FileTransfer/DefaultFileTransferTransporter.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013-2016 Isode Limited.
+ * Copyright (c) 2013-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -133,7 +133,7 @@ void DefaultFileTransferTransporter::handleActivateProxySessionResult(const std:
void DefaultFileTransferTransporter::startActivatingProxy(const JID& proxyServiceJID) {
// activate proxy
- SWIFT_LOG(debug) << "Start activating proxy " << proxyServiceJID.toString() << " with sid = " << s5bSessionID << "." << std::endl;
+ SWIFT_LOG(debug) << "Start activating proxy " << proxyServiceJID.toString() << " with sid = " << s5bSessionID << ".";
S5BProxyRequest::ref proxyRequest = std::make_shared<S5BProxyRequest>();
proxyRequest->setSID(s5bSessionID);
proxyRequest->setActivate(role == Initiator ? responder : initiator);
@@ -207,7 +207,7 @@ std::shared_ptr<TransportSession> DefaultFileTransferTransporter::createLocalCan
transportSession = std::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream);
}
else {
- SWIFT_LOG(error) << "Failed obtaining proxy session with candidate JID " << candidate.jid << " and dstAddr " << getLocalCandidateSOCKS5DstAddr() << "." << std::endl;
+ SWIFT_LOG(error) << "Failed obtaining proxy session with candidate JID " << candidate.jid << " and dstAddr " << getLocalCandidateSOCKS5DstAddr() << ".";
}
}
@@ -234,7 +234,7 @@ std::shared_ptr<TransportSession> DefaultFileTransferTransporter::createLocalCan
transportSession = std::make_shared<S5BTransportSession<SOCKS5BytestreamClientSession> >(proxySession, stream);
}
else {
- SWIFT_LOG(error) << "Failed obtaining proxy session with candidate JID " << candidate.jid << " and dstAddr " << getLocalCandidateSOCKS5DstAddr() << "." << std::endl;
+ SWIFT_LOG(error) << "Failed obtaining proxy session with candidate JID " << candidate.jid << " and dstAddr " << getLocalCandidateSOCKS5DstAddr() << ".";
}
}
@@ -255,11 +255,11 @@ std::string DefaultFileTransferTransporter::getSOCKS5DstAddr() const {
std::string result;
if (role == Initiator) {
result = getInitiatorCandidateSOCKS5DstAddr();
- SWIFT_LOG(debug) << "Initiator S5B DST.ADDR = " << s5bSessionID << " + " << initiator.toString() << " + " << responder.toString() << " : " << result << std::endl;
+ SWIFT_LOG(debug) << "Initiator S5B DST.ADDR = " << s5bSessionID << " + " << initiator.toString() << " + " << responder.toString() << " : " << result;
}
else {
result = getResponderCandidateSOCKS5DstAddr();
- SWIFT_LOG(debug) << "Responder S5B DST.ADDR = " << s5bSessionID << " + " << responder.toString() << " + " << initiator.toString() << " : " << result << std::endl;
+ SWIFT_LOG(debug) << "Responder S5B DST.ADDR = " << s5bSessionID << " + " << responder.toString() << " + " << initiator.toString() << " : " << result;
}
return result;
}
diff --git a/Swiften/FileTransfer/FailingTransportSession.cpp b/Swiften/FileTransfer/FailingTransportSession.cpp
index d1eb6a6..b9c79a0 100644
--- a/Swiften/FileTransfer/FailingTransportSession.cpp
+++ b/Swiften/FileTransfer/FailingTransportSession.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016 Isode Limited.
+ * Copyright (c) 2016-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,7 +14,7 @@ FailingTransportSession::~FailingTransportSession() {
}
void FailingTransportSession::start() {
- SWIFT_LOG(error) << "Trying to start failing transport." << std::endl;
+ SWIFT_LOG(error) << "Trying to start failing transport.";
onFinished(FileTransferError(FileTransferError::PeerError));
}
diff --git a/Swiften/FileTransfer/FileTransferManagerImpl.cpp b/Swiften/FileTransfer/FileTransferManagerImpl.cpp
index 05dd3bb..98eb50e 100644
--- a/Swiften/FileTransfer/FileTransferManagerImpl.cpp
+++ b/Swiften/FileTransfer/FileTransferManagerImpl.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013-2016 Isode Limited.
+ * Copyright (c) 2013-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -156,7 +156,7 @@ OutgoingFileTransfer::ref FileTransferManagerImpl::createOutgoingFileTransfer(
}
}
else {
- SWIFT_LOG(warning) << "No entity capabilities information for " << receipient.toString() << std::endl;
+ SWIFT_LOG(warning) << "No entity capabilities information for " << receipient.toString();
}
return outgoingFTManager->createOutgoingFileTransfer(iqRouter->getJID(), receipient, bytestream, fileInfo, options);
diff --git a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp b/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
index d5de5e4..7c46c60 100644
--- a/Swiften/FileTransfer/IncomingJingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/IncomingJingleFileTransfer.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.
*/
@@ -67,8 +67,8 @@ IncomingJingleFileTransfer::~IncomingJingleFileTransfer() {
void IncomingJingleFileTransfer::accept(
std::shared_ptr<WriteBytestream> stream,
const FileTransferOptions& options) {
- SWIFT_LOG(debug) << std::endl;
- if (state != Initial) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+ SWIFT_LOG(debug);
+ if (state != Initial) { SWIFT_LOG(warning) << "Incorrect state"; return; }
assert(!this->stream);
this->stream = stream;
@@ -85,7 +85,7 @@ void IncomingJingleFileTransfer::accept(
JingleS5BTransportPayload::ref s5bTransport = initialContent->getTransport<JingleS5BTransportPayload>();
JingleIBBTransportPayload::ref ibbTransport = initialContent->getTransport<JingleIBBTransportPayload>();
if (s5bTransport) {
- SWIFT_LOG(debug) << "Got S5B transport as initial payload." << std::endl;
+ SWIFT_LOG(debug) << "Got S5B transport as initial payload.";
setTransporter(transporterFactory->createResponderTransporter(
getInitiator(), getResponder(), s5bTransport->getSessionID(), options));
transporter->addRemoteCandidates(s5bTransport->getCandidates(), s5bTransport->getDstAddr());
@@ -93,7 +93,7 @@ void IncomingJingleFileTransfer::accept(
transporter->startGeneratingLocalCandidates();
}
else if (ibbTransport && options.isInBandAllowed()) {
- SWIFT_LOG(debug) << "Got IBB transport as initial payload." << std::endl;
+ SWIFT_LOG(debug) << "Got IBB transport as initial payload.";
setTransporter(transporterFactory->createResponderTransporter(
getInitiator(), getResponder(), ibbTransport->getSessionID(), options));
@@ -112,7 +112,7 @@ void IncomingJingleFileTransfer::accept(
}
void IncomingJingleFileTransfer::cancel() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
terminate(state == Initial ? JinglePayload::Reason::Decline : JinglePayload::Reason::Cancel);
}
@@ -120,8 +120,8 @@ void IncomingJingleFileTransfer::handleLocalTransportCandidatesGenerated(
const std::string& s5bSessionID,
const std::vector<JingleS5BTransportPayload::Candidate>& candidates,
const std::string& dstAddr) {
- SWIFT_LOG(debug) << std::endl;
- if (state != GeneratingInitialLocalCandidates) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+ SWIFT_LOG(debug);
+ if (state != GeneratingInitialLocalCandidates) { SWIFT_LOG(warning) << "Incorrect state"; return; }
fillCandidateMap(localCandidates, candidates);
@@ -140,11 +140,11 @@ void IncomingJingleFileTransfer::handleLocalTransportCandidatesGenerated(
void IncomingJingleFileTransfer::handleSessionInfoReceived(JinglePayload::ref jinglePayload) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
JingleFileTransferHash::ref transferHash = jinglePayload->getPayload<JingleFileTransferHash>();
if (transferHash) {
- SWIFT_LOG(debug) << "Received hash information." << std::endl;
+ SWIFT_LOG(debug) << "Received hash information.";
waitOnHashTimer->stop();
if (transferHash->getFileInfo().getHashes().find("sha-1") != transferHash->getFileInfo().getHashes().end()) {
hashes["sha-1"] = transferHash->getFileInfo().getHash("sha-1").get();
@@ -157,16 +157,16 @@ void IncomingJingleFileTransfer::handleSessionInfoReceived(JinglePayload::ref ji
}
}
else {
- SWIFT_LOG(debug) << "Ignoring unknown session info" << std::endl;
+ SWIFT_LOG(debug) << "Ignoring unknown session info";
}
}
void IncomingJingleFileTransfer::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) {
- SWIFT_LOG(debug) << std::endl;
- if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+ SWIFT_LOG(debug);
+ if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state"; return; }
if (state == Finished) {
- SWIFT_LOG(debug) << "Already terminated" << std::endl;
+ SWIFT_LOG(debug) << "Already terminated";
return;
}
@@ -187,21 +187,21 @@ void IncomingJingleFileTransfer::checkHashAndTerminate() {
terminate(JinglePayload::Reason::Success);
}
else {
- SWIFT_LOG(warning) << "Hash verification failed" << std::endl;
+ SWIFT_LOG(warning) << "Hash verification failed";
terminate(JinglePayload::Reason::MediaError);
}
}
void IncomingJingleFileTransfer::checkIfAllDataReceived() {
if (receivedBytes == getFileSizeInBytes()) {
- SWIFT_LOG(debug) << "All data received." << std::endl;
+ SWIFT_LOG(debug) << "All data received.";
bool hashInfoAvailable = false;
for (const auto& hashElement : hashes) {
hashInfoAvailable |= !hashElement.second.empty();
}
if (!hashInfoAvailable) {
- SWIFT_LOG(debug) << "No hash information yet. Waiting a while on hash info." << std::endl;
+ SWIFT_LOG(debug) << "No hash information yet. Waiting a while on hash info.";
setState(WaitingForHash);
waitOnHashTimer->start();
}
@@ -210,7 +210,7 @@ void IncomingJingleFileTransfer::checkIfAllDataReceived() {
}
}
else if (receivedBytes > getFileSizeInBytes()) {
- SWIFT_LOG(debug) << "We got more than we could handle!" << std::endl;
+ SWIFT_LOG(debug) << "We got more than we could handle!";
terminate(JinglePayload::Reason::MediaError);
}
}
@@ -225,15 +225,15 @@ void IncomingJingleFileTransfer::handleWriteStreamDataReceived(
void IncomingJingleFileTransfer::handleTransportReplaceReceived(
const JingleContentID& content, JingleTransportPayload::ref transport) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
if (state != WaitingForFallbackOrTerminate) {
- SWIFT_LOG(warning) << "Incorrect state" << std::endl;
+ SWIFT_LOG(warning) << "Incorrect state";
return;
}
JingleIBBTransportPayload::ref ibbTransport;
if (options.isInBandAllowed() && (ibbTransport = std::dynamic_pointer_cast<JingleIBBTransportPayload>(transport))) {
- SWIFT_LOG(debug) << "transport replaced with IBB" << std::endl;
+ SWIFT_LOG(debug) << "transport replaced with IBB";
startTransferring(transporter->createIBBReceiveSession(
ibbTransport->getSessionID(),
@@ -242,7 +242,7 @@ void IncomingJingleFileTransfer::handleTransportReplaceReceived(
session->sendTransportAccept(content, ibbTransport);
}
else {
- SWIFT_LOG(debug) << "Unknown replace transport" << std::endl;
+ SWIFT_LOG(debug) << "Unknown replace transport";
session->sendTransportReject(content, transport);
}
}
@@ -253,25 +253,25 @@ JingleContentID IncomingJingleFileTransfer::getContentID() const {
bool IncomingJingleFileTransfer::verifyData() {
if (hashes.empty()) {
- SWIFT_LOG(debug) << "no verification possible, skipping" << std::endl;
+ SWIFT_LOG(debug) << "no verification possible, skipping";
return true;
}
if (hashes.find("sha-1") != hashes.end()) {
- SWIFT_LOG(debug) << "Verify SHA-1 hash: " << (hashes["sha-1"] == hashCalculator->getSHA1Hash()) << std::endl;
+ SWIFT_LOG(debug) << "Verify SHA-1 hash: " << (hashes["sha-1"] == hashCalculator->getSHA1Hash());
return hashes["sha-1"] == hashCalculator->getSHA1Hash();
}
else if (hashes.find("md5") != hashes.end()) {
- SWIFT_LOG(debug) << "Verify MD5 hash: " << (hashes["md5"] == hashCalculator->getMD5Hash()) << std::endl;
+ SWIFT_LOG(debug) << "Verify MD5 hash: " << (hashes["md5"] == hashCalculator->getMD5Hash());
return hashes["md5"] == hashCalculator->getMD5Hash();
}
else {
- SWIFT_LOG(debug) << "Unknown hash, skipping" << std::endl;
+ SWIFT_LOG(debug) << "Unknown hash, skipping";
return true;
}
}
void IncomingJingleFileTransfer::handleWaitOnHashTimerTicked() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
waitOnHashTimer->stop();
terminate(JinglePayload::Reason::Success);
}
@@ -285,14 +285,14 @@ const JID& IncomingJingleFileTransfer::getRecipient() const {
}
void IncomingJingleFileTransfer::setState(State state) {
- SWIFT_LOG(debug) << state << std::endl;
+ SWIFT_LOG(debug) << state;
this->state = state;
onStateChanged(FileTransfer::State(getExternalState(state)));
}
void IncomingJingleFileTransfer::setFinishedState(
FileTransfer::State::Type type, const boost::optional<FileTransferError>& error) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
this->state = Finished;
onStateChanged(type);
onFinished(error);
@@ -340,7 +340,7 @@ void IncomingJingleFileTransfer::stopAll() {
transportSession->stop();
transportSession.reset();
break;
- case Finished: SWIFT_LOG(warning) << "Already finished" << std::endl; break;
+ case Finished: SWIFT_LOG(warning) << "Already finished"; break;
}
if (state != Initial) {
removeTransporter();
@@ -356,7 +356,7 @@ void IncomingJingleFileTransfer::fallback() {
}
void IncomingJingleFileTransfer::startTransferViaRemoteCandidate() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
if (ourCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
setState(WaitingForPeerProxyActivate);
@@ -367,7 +367,7 @@ void IncomingJingleFileTransfer::startTransferViaRemoteCandidate() {
}
void IncomingJingleFileTransfer::startTransferViaLocalCandidate() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
if (theirCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
setState(WaitingForLocalProxyActivate);
@@ -379,7 +379,7 @@ void IncomingJingleFileTransfer::startTransferViaLocalCandidate() {
}
void IncomingJingleFileTransfer::startTransferring(std::shared_ptr<TransportSession> transportSession) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
this->transportSession = transportSession;
transferFinishedConnection = transportSession->onFinished.connect(
@@ -409,7 +409,7 @@ std::shared_ptr<TransportSession> IncomingJingleFileTransfer::createRemoteCandid
}
void IncomingJingleFileTransfer::terminate(JinglePayload::Reason::Type reason) {
- SWIFT_LOG(debug) << reason << std::endl;
+ SWIFT_LOG(debug) << reason;
if (state != Finished) {
session->sendTerminate(reason);
diff --git a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
index f177304..faddcb9 100644
--- a/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
+++ b/Swiften/FileTransfer/IncrementalBytestreamHashCalculator.cpp
@@ -64,12 +64,12 @@ ByteArray IncrementalBytestreamHashCalculator::getMD5Hash() {
std::string IncrementalBytestreamHashCalculator::getSHA1String() {
assert(sha1Hasher);
- return Hexify::hexify(getSHA1Hash());;
+ return Hexify::hexify(getSHA1Hash());
}
std::string IncrementalBytestreamHashCalculator::getMD5String() {
assert(md5Hasher);
- return Hexify::hexify(getMD5Hash());;
+ return Hexify::hexify(getMD5Hash());
}
}
diff --git a/Swiften/FileTransfer/JingleFileTransfer.cpp b/Swiften/FileTransfer/JingleFileTransfer.cpp
index cc1cd1c..3d05db9 100644
--- a/Swiften/FileTransfer/JingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/JingleFileTransfer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013-2018 Isode Limited.
+ * Copyright (c) 2013-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -78,7 +78,7 @@ boost::optional<FileTransferError> JingleFileTransfer::getFileTransferError(Jing
void JingleFileTransfer::handleRemoteTransportCandidateSelectFinished(
const std::string& s5bSessionID, const boost::optional<JingleS5BTransportPayload::Candidate>& candidate) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
ourCandidateChoice = candidate;
ourCandidateSelectFinished = true;
@@ -98,42 +98,42 @@ void JingleFileTransfer::handleRemoteTransportCandidateSelectFinished(
// decide on candidates according to http://xmpp.org/extensions/xep-0260.html#complete
void JingleFileTransfer::decideOnCandidates() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
if (!ourCandidateSelectFinished || !theirCandidateSelectFinished) {
- SWIFT_LOG(debug) << "Can't make a decision yet!" << std::endl;
+ SWIFT_LOG(debug) << "Can't make a decision yet!";
return;
}
if (!ourCandidateChoice && !theirCandidateChoice) {
- SWIFT_LOG(debug) << "No candidates succeeded." << std::endl;
+ SWIFT_LOG(debug) << "No candidates succeeded.";
fallback();
}
else if (ourCandidateChoice && !theirCandidateChoice) {
- SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << "." << std::endl;
+ SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << ".";
startTransferViaRemoteCandidate();
}
else if (theirCandidateChoice && !ourCandidateChoice) {
- SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << "." << std::endl;
+ SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << ".";
startTransferViaLocalCandidate();
}
else {
SWIFT_LOG(debug) << "Choosing between candidates "
<< ourCandidateChoice->cid << "(" << ourCandidateChoice->priority << ")" << " and "
- << theirCandidateChoice->cid << "(" << theirCandidateChoice->priority << ")" << std::endl;
+ << theirCandidateChoice->cid << "(" << theirCandidateChoice->priority << ")";
if (ourCandidateChoice->priority > theirCandidateChoice->priority) {
- SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << "." << std::endl;
+ SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << ".";
startTransferViaRemoteCandidate();
}
else if (ourCandidateChoice->priority < theirCandidateChoice->priority) {
- SWIFT_LOG(debug) << "Start transfer using local candidate:" << theirCandidateChoice.get().cid << "." << std::endl;
+ SWIFT_LOG(debug) << "Start transfer using local candidate:" << theirCandidateChoice.get().cid << ".";
startTransferViaLocalCandidate();
}
else {
if (hasPriorityOnCandidateTie()) {
- SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid << std::endl;
+ SWIFT_LOG(debug) << "Start transfer using remote candidate: " << ourCandidateChoice.get().cid;
startTransferViaRemoteCandidate();
}
else {
- SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid << std::endl;
+ SWIFT_LOG(debug) << "Start transfer using local candidate: " << theirCandidateChoice.get().cid;
startTransferViaLocalCandidate();
}
}
@@ -142,11 +142,11 @@ void JingleFileTransfer::decideOnCandidates() {
void JingleFileTransfer::handleProxyActivateFinished(
const std::string& s5bSessionID, ErrorPayload::ref error) {
- SWIFT_LOG(debug) << std::endl;
- if (!isWaitingForLocalProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+ SWIFT_LOG(debug);
+ if (!isWaitingForLocalProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state"; return; }
if (error) {
- SWIFT_LOG(debug) << "Error activating proxy" << std::endl;
+ SWIFT_LOG(debug) << "Error activating proxy";
JingleS5BTransportPayload::ref proxyError = std::make_shared<JingleS5BTransportPayload>();
proxyError->setSessionID(s5bSessionID);
proxyError->setProxyError(true);
@@ -164,18 +164,18 @@ void JingleFileTransfer::handleProxyActivateFinished(
void JingleFileTransfer::handleTransportInfoReceived(
const JingleContentID& /* contentID */, JingleTransportPayload::ref transport) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
if (JingleS5BTransportPayload::ref s5bPayload = std::dynamic_pointer_cast<JingleS5BTransportPayload>(transport)) {
if (s5bPayload->hasCandidateError() || !s5bPayload->getCandidateUsed().empty()) {
- SWIFT_LOG(debug) << "Received candidate decision from peer" << std::endl;
- if (!isTryingCandidates()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+ SWIFT_LOG(debug) << "Received candidate decision from peer";
+ if (!isTryingCandidates()) { SWIFT_LOG(warning) << "Incorrect state"; return; }
theirCandidateSelectFinished = true;
if (!s5bPayload->hasCandidateError()) {
auto theirCandidate = localCandidates.find(s5bPayload->getCandidateUsed());
if (theirCandidate == localCandidates.end()) {
- SWIFT_LOG(warning) << "Got invalid candidate" << std::endl;
+ SWIFT_LOG(warning) << "Got invalid candidate";
terminate(JinglePayload::Reason::GeneralError);
return;
}
@@ -184,27 +184,27 @@ void JingleFileTransfer::handleTransportInfoReceived(
decideOnCandidates();
}
else if (!s5bPayload->getActivated().empty()) {
- SWIFT_LOG(debug) << "Received peer activate from peer" << std::endl;
- if (!isWaitingForPeerProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+ SWIFT_LOG(debug) << "Received peer activate from peer";
+ if (!isWaitingForPeerProxyActivate()) { SWIFT_LOG(warning) << "Incorrect state"; return; }
if (ourCandidateChoice->cid == s5bPayload->getActivated()) {
startTransferring(createRemoteCandidateSession());
}
else {
- SWIFT_LOG(warning) << "ourCandidateChoice doesn't match activated proxy candidate!" << std::endl;
+ SWIFT_LOG(warning) << "ourCandidateChoice doesn't match activated proxy candidate!";
terminate(JinglePayload::Reason::GeneralError);
}
}
else if (s5bPayload->hasProxyError()) {
- SWIFT_LOG(debug) << "Received proxy error. Trying to fall back to IBB." << std::endl;
+ SWIFT_LOG(debug) << "Received proxy error. Trying to fall back to IBB.";
fallback();
}
else {
- SWIFT_LOG(debug) << "Ignoring unknown info" << std::endl;
+ SWIFT_LOG(debug) << "Ignoring unknown info";
}
}
else {
- SWIFT_LOG(debug) << "Ignoring unknown info" << std::endl;
+ SWIFT_LOG(debug) << "Ignoring unknown info";
}
}
diff --git a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
index 834a401..7cb4cbb 100644
--- a/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
+++ b/Swiften/FileTransfer/LocalJingleTransportCandidateGenerator.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013-2016 Isode Limited.
+ * Copyright (c) 2013-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -45,7 +45,7 @@ LocalJingleTransportCandidateGenerator::LocalJingleTransportCandidateGenerator(
}
LocalJingleTransportCandidateGenerator::~LocalJingleTransportCandidateGenerator() {
- SWIFT_LOG_ASSERT(!s5bServerInitializeRequest, warning) << std::endl;
+ SWIFT_LOG_ASSERT(!s5bServerInitializeRequest, warning);
}
void LocalJingleTransportCandidateGenerator::start() {
@@ -98,7 +98,7 @@ void LocalJingleTransportCandidateGenerator::handleS5BServerInitialized(bool suc
}
}
else {
- SWIFT_LOG(warning) << "Unable to start SOCKS5 server" << std::endl;
+ SWIFT_LOG(warning) << "Unable to start SOCKS5 server";
if (s5bServerResourceUser_) {
s5bServerResourceUser_->onSuccessfulInitialized.disconnect(boost::bind(&LocalJingleTransportCandidateGenerator::handleS5BServerInitialized, this, _1));
}
diff --git a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
index 367fc97..57a18a8 100644
--- a/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
+++ b/Swiften/FileTransfer/OutgoingJingleFileTransfer.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013-2016 Isode Limited.
+ * Copyright (c) 2013-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -87,9 +87,9 @@ OutgoingJingleFileTransfer::~OutgoingJingleFileTransfer() {
}
void OutgoingJingleFileTransfer::start() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
if (state != Initial) {
- SWIFT_LOG(warning) << "Incorrect state" << std::endl;
+ SWIFT_LOG(warning) << "Incorrect state";
return;
}
@@ -109,7 +109,7 @@ void OutgoingJingleFileTransfer::cancel() {
}
void OutgoingJingleFileTransfer::terminate(JinglePayload::Reason::Type reason) {
- SWIFT_LOG(debug) << reason << std::endl;
+ SWIFT_LOG(debug) << reason;
if (state != Initial && state != GeneratingInitialLocalCandidates && state != Finished) {
session->sendTerminate(reason);
@@ -122,8 +122,8 @@ void OutgoingJingleFileTransfer::handleSessionAcceptReceived(
const JingleContentID&,
JingleDescription::ref,
JingleTransportPayload::ref transportPayload) {
- SWIFT_LOG(debug) << std::endl;
- if (state != WaitingForAccept) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+ SWIFT_LOG(debug);
+ if (state != WaitingForAccept) { SWIFT_LOG(warning) << "Incorrect state"; return; }
if (JingleS5BTransportPayload::ref s5bPayload = std::dynamic_pointer_cast<JingleS5BTransportPayload>(transportPayload)) {
transporter->addRemoteCandidates(s5bPayload->getCandidates(), s5bPayload->getDstAddr());
@@ -134,14 +134,14 @@ void OutgoingJingleFileTransfer::handleSessionAcceptReceived(
startTransferring(transporter->createIBBSendSession(ibbPayload->getSessionID(), ibbPayload->getBlockSize().get_value_or(DEFAULT_BLOCK_SIZE), stream));
}
else {
- SWIFT_LOG(debug) << "Unknown transport payload. Falling back." << std::endl;
+ SWIFT_LOG(debug) << "Unknown transport payload. Falling back.";
fallback();
}
}
void OutgoingJingleFileTransfer::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason> reason) {
- SWIFT_LOG(debug) << std::endl;
- if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; }
+ SWIFT_LOG(debug);
+ if (state == Finished) { SWIFT_LOG(warning) << "Incorrect state: " << state; return; }
stopAll();
if (state == WaitForTermination) {
@@ -162,26 +162,26 @@ void OutgoingJingleFileTransfer::handleSessionTerminateReceived(boost::optional<
}
void OutgoingJingleFileTransfer::handleTransportAcceptReceived(const JingleContentID&, JingleTransportPayload::ref transport) {
- SWIFT_LOG(debug) << std::endl;
- if (state != FallbackRequested) { SWIFT_LOG(warning) << "Incorrect state" << std::endl; return; }
+ SWIFT_LOG(debug);
+ if (state != FallbackRequested) { SWIFT_LOG(warning) << "Incorrect state"; return; }
if (JingleIBBTransportPayload::ref ibbPayload = std::dynamic_pointer_cast<JingleIBBTransportPayload>(transport)) {
startTransferring(transporter->createIBBSendSession(ibbPayload->getSessionID(), ibbPayload->getBlockSize().get_value_or(DEFAULT_BLOCK_SIZE), stream));
}
else {
- SWIFT_LOG(debug) << "Unknown transport replacement" << std::endl;
+ SWIFT_LOG(debug) << "Unknown transport replacement";
terminate(JinglePayload::Reason::FailedTransport);
}
}
void OutgoingJingleFileTransfer::handleTransportRejectReceived(const JingleContentID &, std::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
terminate(JinglePayload::Reason::UnsupportedTransports);
}
void OutgoingJingleFileTransfer::sendSessionInfoHash() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
JingleFileTransferHash::ref hashElement = std::make_shared<JingleFileTransferHash>();
hashElement->getFileInfo().addHash(HashElement("sha-1", hashCalculator->getSHA1Hash()));
@@ -191,8 +191,8 @@ void OutgoingJingleFileTransfer::sendSessionInfoHash() {
void OutgoingJingleFileTransfer::handleLocalTransportCandidatesGenerated(
const std::string& s5bSessionID, const std::vector<JingleS5BTransportPayload::Candidate>& candidates, const std::string& dstAddr) {
- SWIFT_LOG(debug) << std::endl;
- if (state != GeneratingInitialLocalCandidates) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; }
+ SWIFT_LOG(debug);
+ if (state != GeneratingInitialLocalCandidates) { SWIFT_LOG(warning) << "Incorrect state: " << state; return; }
fillCandidateMap(localCandidates, candidates);
@@ -203,7 +203,7 @@ void OutgoingJingleFileTransfer::handleLocalTransportCandidatesGenerated(
JingleTransportPayload::ref transport;
if (candidates.empty()) {
- SWIFT_LOG(debug) << "no S5B candidates generated. Send IBB transport candidate." << std::endl;
+ SWIFT_LOG(debug) << "no S5B candidates generated. Send IBB transport candidate.";
JingleIBBTransportPayload::ref ibbTransport = std::make_shared<JingleIBBTransportPayload>();
ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE);
ibbTransport->setSessionID(idGenerator->generateID());
@@ -216,7 +216,7 @@ void OutgoingJingleFileTransfer::handleLocalTransportCandidatesGenerated(
s5bTransport->setDstAddr(dstAddr);
for (auto&& candidate : candidates) {
s5bTransport->addCandidate(candidate);
- SWIFT_LOG(debug) << "\t" << "S5B candidate: " << candidate.hostPort.toString() << std::endl;
+ SWIFT_LOG(debug) << "\t" << "S5B candidate: " << candidate.hostPort.toString();
}
transport = s5bTransport;
}
@@ -226,7 +226,7 @@ void OutgoingJingleFileTransfer::handleLocalTransportCandidatesGenerated(
void OutgoingJingleFileTransfer::fallback() {
if (options.isInBandAllowed()) {
- SWIFT_LOG(debug) << "Trying to fallback to IBB transport." << std::endl;
+ SWIFT_LOG(debug) << "Trying to fallback to IBB transport.";
JingleIBBTransportPayload::ref ibbTransport = std::make_shared<JingleIBBTransportPayload>();
ibbTransport->setBlockSize(DEFAULT_BLOCK_SIZE);
ibbTransport->setSessionID(idGenerator->generateID());
@@ -234,14 +234,14 @@ void OutgoingJingleFileTransfer::fallback() {
session->sendTransportReplace(contentID, ibbTransport);
}
else {
- SWIFT_LOG(debug) << "Fallback to IBB transport not allowed." << std::endl;
+ SWIFT_LOG(debug) << "Fallback to IBB transport not allowed.";
terminate(JinglePayload::Reason::ConnectivityError);
}
}
void OutgoingJingleFileTransfer::handleTransferFinished(boost::optional<FileTransferError> error) {
- SWIFT_LOG(debug) << std::endl;
- if (state != Transferring) { SWIFT_LOG(warning) << "Incorrect state: " << state << std::endl; return; }
+ SWIFT_LOG(debug);
+ if (state != Transferring) { SWIFT_LOG(warning) << "Incorrect state: " << state; return; }
if (error) {
terminate(JinglePayload::Reason::ConnectivityError);
@@ -256,7 +256,7 @@ void OutgoingJingleFileTransfer::handleTransferFinished(boost::optional<FileTran
}
void OutgoingJingleFileTransfer::startTransferring(std::shared_ptr<TransportSession> transportSession) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
this->transportSession = transportSession;
processedBytesConnection = transportSession->onBytesSent.connect(
@@ -269,14 +269,14 @@ void OutgoingJingleFileTransfer::startTransferring(std::shared_ptr<TransportSess
void OutgoingJingleFileTransfer::setInternalState(State state) {
- SWIFT_LOG(debug) << state << std::endl;
+ SWIFT_LOG(debug) << state;
this->state = state;
setState(FileTransfer::State(getExternalState(state)));
}
void OutgoingJingleFileTransfer::setFinishedState(
FileTransfer::State::Type type, const boost::optional<FileTransferError>& error) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
this->state = Finished;
onStateChanged(type);
onFinished(error);
@@ -301,9 +301,9 @@ FileTransfer::State::Type OutgoingJingleFileTransfer::getExternalState(State sta
}
void OutgoingJingleFileTransfer::stopAll() {
- SWIFT_LOG(debug) << state << std::endl;
+ SWIFT_LOG(debug) << state;
switch (state) {
- case Initial: SWIFT_LOG(warning) << "Not yet started" << std::endl; break;
+ case Initial: SWIFT_LOG(warning) << "Not yet started"; break;
case GeneratingInitialLocalCandidates: transporter->stopGeneratingLocalCandidates(); break;
case WaitingForAccept: break;
case TryingCandidates: transporter->stopTryingRemoteCandidates(); break;
@@ -320,7 +320,7 @@ void OutgoingJingleFileTransfer::stopAll() {
break;
case WaitForTermination:
break;
- case Finished: SWIFT_LOG(warning) << "Already finished" << std::endl; break;
+ case Finished: SWIFT_LOG(warning) << "Already finished"; break;
}
if (state != Initial) {
removeTransporter();
@@ -328,7 +328,7 @@ void OutgoingJingleFileTransfer::stopAll() {
}
void OutgoingJingleFileTransfer::startTransferViaRemoteCandidate() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
if (ourCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
setInternalState(WaitingForPeerProxyActivate);
@@ -340,7 +340,7 @@ void OutgoingJingleFileTransfer::startTransferViaRemoteCandidate() {
}
void OutgoingJingleFileTransfer::startTransferViaLocalCandidate() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
if (theirCandidateChoice->type == JingleS5BTransportPayload::Candidate::ProxyType) {
setInternalState(WaitingForLocalProxyActivate);
@@ -400,7 +400,7 @@ std::shared_ptr<TransportSession> OutgoingJingleFileTransfer::createRemoteCandid
void OutgoingJingleFileTransfer::handleWaitForRemoteTerminationTimeout() {
assert(state == WaitForTermination);
- SWIFT_LOG(warning) << "Other party did not terminate session. Terminate it now." << std::endl;
+ SWIFT_LOG(warning) << "Other party did not terminate session. Terminate it now.";
waitForRemoteTermination->stop();
terminate(JinglePayload::Reason::MediaError);
}
diff --git a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
index 56013ca..4023be3 100644
--- a/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
+++ b/Swiften/FileTransfer/RemoteJingleTransportCandidateSelector.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013-2016 Isode Limited.
+ * Copyright (c) 2013-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -56,14 +56,14 @@ void RemoteJingleTransportCandidateSelector::stopSelectingCandidate() {
void RemoteJingleTransportCandidateSelector::tryNextCandidate() {
if (candidates.empty()) {
- SWIFT_LOG(debug) << "No more candidates" << std::endl;
+ SWIFT_LOG(debug) << "No more candidates";
onCandidateSelectFinished(
boost::optional<JingleS5BTransportPayload::Candidate>(), std::shared_ptr<SOCKS5BytestreamClientSession>());
}
else {
lastCandidate = candidates.top();
candidates.pop();
- SWIFT_LOG(debug) << "Trying candidate " << lastCandidate.cid << std::endl;
+ SWIFT_LOG(debug) << "Trying candidate " << lastCandidate.cid;
if ((lastCandidate.type == JingleS5BTransportPayload::Candidate::DirectType && options.isDirectAllowed()) ||
(lastCandidate.type == JingleS5BTransportPayload::Candidate::AssistedType && options.isAssistedAllowed()) ||
(lastCandidate.type == JingleS5BTransportPayload::Candidate::ProxyType && options.isProxiedAllowed())) {
@@ -75,7 +75,7 @@ void RemoteJingleTransportCandidateSelector::tryNextCandidate() {
s5bSession->start();
}
else {
- SWIFT_LOG(debug) << "Can't handle this type of candidate" << std::endl;
+ SWIFT_LOG(debug) << "Can't handle this type of candidate";
tryNextCandidate();
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
index 5ddd32b..a3f0dab 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamClientSession.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2013-2016 Isode Limited.
+ * Copyright (c) 2013-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -49,7 +49,7 @@ SOCKS5BytestreamClientSession::~SOCKS5BytestreamClientSession() {
void SOCKS5BytestreamClientSession::start() {
assert(state == Initial);
- SWIFT_LOG(debug) << "Trying to connect via TCP to " << addressPort.toString() << "." << std::endl;
+ SWIFT_LOG(debug) << "Trying to connect via TCP to " << addressPort.toString() << ".";
weFailedTimeout->start();
connectFinishedConnection = connection->onConnectFinished.connect(
boost::bind(&SOCKS5BytestreamClientSession::handleConnectFinished, this, _1));
@@ -57,7 +57,7 @@ void SOCKS5BytestreamClientSession::start() {
}
void SOCKS5BytestreamClientSession::stop() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
if (state < Ready) {
weFailedTimeout->stop();
}
@@ -70,7 +70,7 @@ void SOCKS5BytestreamClientSession::stop() {
}
void SOCKS5BytestreamClientSession::process() {
- SWIFT_LOG(debug) << "unprocessedData.size(): " << unprocessedData.size() << std::endl;
+ SWIFT_LOG(debug) << "unprocessedData.size(): " << unprocessedData.size();
ByteArray bndAddress;
switch(state) {
case Initial:
@@ -124,19 +124,19 @@ void SOCKS5BytestreamClientSession::process() {
}
unprocessedData.clear();
state = Ready;
- SWIFT_LOG(debug) << "session ready" << std::endl;
+ SWIFT_LOG(debug) << "session ready";
// issue ready signal so the bytestream can be used for reading or writing
weFailedTimeout->stop();
onSessionReady(false);
break;
case Ready:
- SWIFT_LOG(debug) << "Received further data in Ready state." << std::endl;
+ SWIFT_LOG(debug) << "Received further data in Ready state.";
break;
case Reading:
case Writing:
case Finished:
- SWIFT_LOG(debug) << "Unexpected receive of data. Current state: " << state << std::endl;
- SWIFT_LOG(debug) << "Data: " << Hexify::hexify(unprocessedData) << std::endl;
+ SWIFT_LOG(debug) << "Unexpected receive of data. Current state: " << state;
+ SWIFT_LOG(debug) << "Data: " << Hexify::hexify(unprocessedData);
unprocessedData.clear();
//assert(false);
}
@@ -150,7 +150,7 @@ void SOCKS5BytestreamClientSession::hello() {
}
void SOCKS5BytestreamClientSession::authenticate() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
SafeByteArray header = createSafeByteArray("\x05\x01\x00\x03", 4);
SafeByteArray message = header;
append(message, createSafeByteArray(boost::numeric_cast<char>(destination.size())));
@@ -168,7 +168,7 @@ void SOCKS5BytestreamClientSession::startReceiving(std::shared_ptr<WriteBytestre
writeBytestream->write(unprocessedData);
unprocessedData.clear();
} else {
- SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl;
+ SWIFT_LOG(debug) << "Session isn't ready for transfer yet!";
}
}
@@ -180,7 +180,7 @@ void SOCKS5BytestreamClientSession::startSending(std::shared_ptr<ReadBytestream>
boost::bind(&SOCKS5BytestreamClientSession::sendData, this));
sendData();
} else {
- SWIFT_LOG(debug) << "Session isn't ready for transfer yet!" << std::endl;
+ SWIFT_LOG(debug) << "Session isn't ready for transfer yet!";
}
}
@@ -205,7 +205,7 @@ void SOCKS5BytestreamClientSession::sendData() {
}
void SOCKS5BytestreamClientSession::finish(bool error) {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
if (state < Ready) {
weFailedTimeout->stop();
}
@@ -227,10 +227,10 @@ void SOCKS5BytestreamClientSession::finish(bool error) {
void SOCKS5BytestreamClientSession::handleConnectFinished(bool error) {
connectFinishedConnection.disconnect();
if (error) {
- SWIFT_LOG(debug) << "Failed to connect via TCP to " << addressPort.toString() << "." << std::endl;
+ SWIFT_LOG(debug) << "Failed to connect via TCP to " << addressPort.toString() << ".";
finish(true);
} else {
- SWIFT_LOG(debug) << "Successfully connected via TCP" << addressPort.toString() << "." << std::endl;
+ SWIFT_LOG(debug) << "Successfully connected via TCP" << addressPort.toString() << ".";
disconnectedConnection = connection->onDisconnected.connect(
boost::bind(&SOCKS5BytestreamClientSession::handleDisconnected, this, _1));
dataReadConnection = connection->onDataRead.connect(
@@ -242,7 +242,7 @@ void SOCKS5BytestreamClientSession::handleConnectFinished(bool error) {
}
void SOCKS5BytestreamClientSession::handleDataRead(std::shared_ptr<SafeByteArray> data) {
- SWIFT_LOG(debug) << "state: " << state << " data.size() = " << data->size() << std::endl;
+ SWIFT_LOG(debug) << "state: " << state << " data.size() = " << data->size();
if (state != Reading) {
append(unprocessedData, *data);
process();
@@ -254,14 +254,14 @@ void SOCKS5BytestreamClientSession::handleDataRead(std::shared_ptr<SafeByteArray
}
void SOCKS5BytestreamClientSession::handleDisconnected(const boost::optional<Connection::Error>& error) {
- SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl;
+ SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error");
if (error) {
finish(true);
}
}
void SOCKS5BytestreamClientSession::handleWeFailedTimeout() {
- SWIFT_LOG(debug) << "Failed due to timeout!" << std::endl;
+ SWIFT_LOG(debug) << "Failed due to timeout!";
finish(true);
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
index cd4cfaa..72c4d41 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxiesManager.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015-2016 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -46,7 +46,7 @@ SOCKS5BytestreamProxiesManager::~SOCKS5BytestreamProxiesManager() {
void SOCKS5BytestreamProxiesManager::addS5BProxy(S5BProxyRequest::ref proxy) {
if (proxy) {
- SWIFT_LOG_ASSERT(HostAddress::fromString(proxy->getStreamHost().get().host), warning) << std::endl;
+ SWIFT_LOG_ASSERT(HostAddress::fromString(proxy->getStreamHost().get().host), warning);
if (!localS5BProxies_) {
localS5BProxies_ = std::vector<S5BProxyRequest::ref>();
}
@@ -62,7 +62,7 @@ const boost::optional<std::vector<S5BProxyRequest::ref> >& SOCKS5BytestreamProxi
}
void SOCKS5BytestreamProxiesManager::connectToProxies(const std::string& sessionID) {
- SWIFT_LOG(debug) << "session ID: " << sessionID << std::endl;
+ SWIFT_LOG(debug) << "session ID: " << sessionID;
ProxyJIDClientSessionVector clientSessions;
if (localS5BProxies_) {
@@ -71,7 +71,7 @@ void SOCKS5BytestreamProxiesManager::connectToProxies(const std::string& session
if (proxyHostAddress) {
std::shared_ptr<Connection> conn = connectionFactory_->createConnection();
HostAddressPort addressPort = HostAddressPort(proxyHostAddress.get(), proxy->getStreamHost().get().port);
- SWIFT_LOG_ASSERT(addressPort.isValid(), warning) << std::endl;
+ SWIFT_LOG_ASSERT(addressPort.isValid(), warning);
std::shared_ptr<SOCKS5BytestreamClientSession> session = std::make_shared<SOCKS5BytestreamClientSession>(conn, addressPort, sessionID, timerFactory_);
JID proxyJid = proxy->getStreamHost().get().jid;
clientSessions.push_back(std::pair<JID, std::shared_ptr<SOCKS5BytestreamClientSession> >(proxyJid, session));
@@ -103,7 +103,7 @@ std::shared_ptr<SOCKS5BytestreamClientSession> SOCKS5BytestreamProxiesManager::g
i->second->stop();
}
}
- SWIFT_LOG_ASSERT(activeSession, warning) << "No active session with matching ID found." << std::endl;
+ SWIFT_LOG_ASSERT(activeSession, warning) << "No active session with matching ID found.";
proxySessions_.erase(sessionID);
@@ -144,7 +144,7 @@ void SOCKS5BytestreamProxiesManager::handleNameLookupResult(const std::vector<Ho
}
else {
if (addresses.empty()) {
- SWIFT_LOG(warning) << "S5B proxy hostname does not resolve." << std::endl;
+ SWIFT_LOG(warning) << "S5B proxy hostname does not resolve.";
}
else {
// generate proxy per returned address
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
index 90c42dd..1efc54a 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamProxyFinder.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015-2016 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -71,10 +71,10 @@ void SOCKS5BytestreamProxyFinder::handleProxyResponse(std::shared_ptr<GenericReq
requester->onResponse.disconnect(boost::bind(&SOCKS5BytestreamProxyFinder::handleProxyResponse, this, requester, _1, _2));
pendingRequests.erase(requester);
if (error) {
- SWIFT_LOG(debug) << "ERROR" << std::endl;
+ SWIFT_LOG(debug) << "ERROR";
} else {
if (request) {
- SWIFT_LOG(debug) << "add request" << std::endl;
+ SWIFT_LOG(debug) << "add request";
proxyHosts.push_back(request);
}
}
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
index a6b75da..7fc1388 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerManager.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2018 Isode Limited.
+ * Copyright (c) 2012-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -48,12 +48,12 @@ SOCKS5BytestreamServerManager::SOCKS5BytestreamServerManager(
}
SOCKS5BytestreamServerManager::~SOCKS5BytestreamServerManager() {
- SWIFT_LOG_ASSERT(!connectionServer, warning) << std::endl;
- SWIFT_LOG_ASSERT(!getPublicIPRequest, warning) << std::endl;
- SWIFT_LOG_ASSERT(!forwardPortRequest, warning) << std::endl;
- SWIFT_LOG_ASSERT(state == Start, warning) << std::endl;
+ SWIFT_LOG_ASSERT(!connectionServer, warning);
+ SWIFT_LOG_ASSERT(!getPublicIPRequest, warning);
+ SWIFT_LOG_ASSERT(!forwardPortRequest, warning);
+ SWIFT_LOG_ASSERT(state == Start, warning);
if (portMapping && !unforwardPortRequest) {
- SWIFT_LOG(warning) << "Port forwarding still alive. Trying to remove it now." << std::endl;
+ SWIFT_LOG(warning) << "Port forwarding still alive. Trying to remove it now.";
unforwardPortRequest = natTraverser->createRemovePortForwardingRequest(portMapping.get().getLocalPort(), portMapping.get().getPublicPort());
unforwardPortRequest->start();
}
@@ -116,25 +116,25 @@ void SOCKS5BytestreamServerManager::initialize() {
assert(!connectionServer);
unsigned short port;
for (port = LISTEN_PORTS_BEGIN; port < LISTEN_PORTS_END; ++port) {
- SWIFT_LOG(debug) << "Trying to start server on port " << port << std::endl;
+ SWIFT_LOG(debug) << "Trying to start server on port " << port;
connectionServer = connectionServerFactory->createConnectionServer(HostAddress::fromString("::").get(), port);
boost::optional<ConnectionServer::Error> error = connectionServer->tryStart();
if (!error) {
break;
}
else if (*error != ConnectionServer::Conflict) {
- SWIFT_LOG(debug) << "Error starting server" << std::endl;
+ SWIFT_LOG(debug) << "Error starting server";
onInitialized(false);
return;
}
connectionServer.reset();
}
if (!connectionServer) {
- SWIFT_LOG(debug) << "Unable to find an open port" << std::endl;
+ SWIFT_LOG(debug) << "Unable to find an open port";
onInitialized(false);
return;
}
- SWIFT_LOG(debug) << "Server started succesfully" << std::endl;
+ SWIFT_LOG(debug) << "Server started succesfully";
connectionServerPort = port;
// Start bytestream server. Should actually happen before the connectionserver is started
@@ -211,10 +211,10 @@ void SOCKS5BytestreamServerManager::stop() {
void SOCKS5BytestreamServerManager::handleGetPublicIPResult(boost::optional<HostAddress> address) {
if (address) {
- SWIFT_LOG(debug) << "Public IP discovered as " << address.get().toString() << "." << std::endl;
+ SWIFT_LOG(debug) << "Public IP discovered as " << address.get().toString() << ".";
}
else {
- SWIFT_LOG(debug) << "No public IP discoverable." << std::endl;
+ SWIFT_LOG(debug) << "No public IP discoverable.";
}
publicAddress = address;
@@ -225,10 +225,10 @@ void SOCKS5BytestreamServerManager::handleGetPublicIPResult(boost::optional<Host
void SOCKS5BytestreamServerManager::handleForwardPortResult(boost::optional<NATPortMapping> mapping) {
if (mapping) {
- SWIFT_LOG(debug) << "Mapping port was successful." << std::endl;
+ SWIFT_LOG(debug) << "Mapping port was successful.";
}
else {
- SWIFT_LOG(debug) << "Mapping port has failed." << std::endl;
+ SWIFT_LOG(debug) << "Mapping port has failed.";
}
portMapping = mapping;
@@ -243,7 +243,7 @@ void SOCKS5BytestreamServerManager::handleUnforwardPortResult(boost::optional<bo
portMapping.reset();
}
else {
- SWIFT_LOG(warning) << "Failed to remove port forwarding." << std::endl;
+ SWIFT_LOG(warning) << "Failed to remove port forwarding.";
}
attemptedPortMapping_ = false;
unforwardPortRequest.reset();
diff --git a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
index 0fd40bf..a4ab751 100644
--- a/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
+++ b/Swiften/FileTransfer/SOCKS5BytestreamServerSession.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -33,13 +33,13 @@ SOCKS5BytestreamServerSession::SOCKS5BytestreamServerSession(
SOCKS5BytestreamServerSession::~SOCKS5BytestreamServerSession() {
if (state != Finished && state != Initial) {
- SWIFT_LOG(warning) << "SOCKS5BytestreamServerSession unfinished" << std::endl;
+ SWIFT_LOG(warning) << "SOCKS5BytestreamServerSession unfinished";
finish();
}
}
void SOCKS5BytestreamServerSession::start() {
- SWIFT_LOG(debug) << std::endl;
+ SWIFT_LOG(debug);
dataReadConnection = connection->onDataRead.connect(
boost::bind(&SOCKS5BytestreamServerSession::handleDataRead, this, _1));
state = WaitingForAuthentication;
@@ -50,7 +50,7 @@ void SOCKS5BytestreamServerSession::stop() {
}
void SOCKS5BytestreamServerSession::startSending(std::shared_ptr<ReadBytestream> stream) {
- if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; }
+ if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!"; return; }
readBytestream = stream;
state = WritingData;
@@ -62,7 +62,7 @@ void SOCKS5BytestreamServerSession::startSending(std::shared_ptr<ReadBytestream>
}
void SOCKS5BytestreamServerSession::startReceiving(std::shared_ptr<WriteBytestream> stream) {
- if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!" << std::endl; return; }
+ if (state != ReadyForTransfer) { SWIFT_LOG(debug) << "Not ready for transfer!"; return; }
writeBytestream = stream;
state = ReadingData;
@@ -93,7 +93,7 @@ void SOCKS5BytestreamServerSession::handleDataAvailable() {
}
void SOCKS5BytestreamServerSession::handleDisconnected(const boost::optional<Connection::Error>& error) {
- SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error") << std::endl;
+ SWIFT_LOG(debug) << (error ? (error == Connection::ReadError ? "Read Error" : "Write Error") : "No Error");
finish(error ? boost::optional<FileTransferError>(FileTransferError::PeerError) : boost::optional<FileTransferError>());
}
@@ -109,7 +109,7 @@ void SOCKS5BytestreamServerSession::process() {
if (i == 2 + authCount) {
// Authentication message is complete
if (i != unprocessedData.size()) {
- SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl;
+ SWIFT_LOG(debug) << "Junk after authentication mechanism";
}
unprocessedData.clear();
connection->write(createSafeByteArray("\x05\x00", 2));
@@ -130,7 +130,7 @@ void SOCKS5BytestreamServerSession::process() {
i += 2;
if (i <= unprocessedData.size()) {
if (i != unprocessedData.size()) {
- SWIFT_LOG(debug) << "Junk after authentication mechanism" << std::endl;
+ SWIFT_LOG(debug) << "Junk after authentication mechanism";
}
unprocessedData.clear();
streamID = byteArrayToString(requestID);
@@ -142,18 +142,18 @@ void SOCKS5BytestreamServerSession::process() {
result.push_back(boost::numeric_cast<unsigned char>(requestID.size()));
}
catch (const boost::numeric::bad_numeric_cast& e) {
- SWIFT_LOG(warning) << "SOCKS5 request ID is too long (" << requestID.size() << "): " << e.what() << std::endl;
+ SWIFT_LOG(warning) << "SOCKS5 request ID is too long (" << requestID.size() << "): " << e.what();
finish();
return;
}
append(result, concat(requestID, createByteArray("\x00\x00", 2)));
if (!hasBytestream) {
- SWIFT_LOG(debug) << "Readstream or Wrtiestream with ID " << streamID << " not found!" << std::endl;
+ SWIFT_LOG(debug) << "Readstream or Wrtiestream with ID " << streamID << " not found!";
connection->write(result);
finish(boost::optional<FileTransferError>(FileTransferError::PeerError));
}
else {
- SWIFT_LOG(debug) << "Found stream. Sent OK." << std::endl;
+ SWIFT_LOG(debug) << "Found stream. Sent OK.";
connection->write(result);
state = ReadyForTransfer;
}
@@ -185,7 +185,7 @@ void SOCKS5BytestreamServerSession::sendData() {
}
void SOCKS5BytestreamServerSession::finish(const boost::optional<FileTransferError>& error) {
- SWIFT_LOG(debug) << "state: " << state << std::endl;
+ SWIFT_LOG(debug) << "state: " << state;
if (state == Finished) {
return;
}
diff --git a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
index 80667b6..fad02da 100644
--- a/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
+++ b/Swiften/FileTransfer/UnitTest/SOCKS5BytestreamClientSessionTest.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015-2016 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -238,7 +238,7 @@ private:
std::shared_ptr<SafeByteArray> dataToSend;
//ByteArray failingData = Hexify::unhexify("8417947d1d305c72c11520ea7d2c6e787396705e72c312c6ccc3f66613d7cae1b91b7ab48e8b59a17d559c15fb51");
//append(dataToSend, failingData);
- //SWIFT_LOG(debug) << "hexed: " << Hexify::hexify(failingData) << std::endl;
+ //SWIFT_LOG(debug) << "hexed: " << Hexify::hexify(failingData);
do {
ByteArray rndArray = generateRandomByteArray(correctData->size());
dataToSend = createSafeByteArrayRef(vecptr(rndArray), rndArray.size());
@@ -255,7 +255,7 @@ private:
void handleConnectionDataWritten(const SafeByteArray& data) {
append(unprocessedInput, data);
- //SWIFT_LOG(debug) << "unprocessedInput (" << unprocessedInput.size() << "): " << Hexify::hexify(unprocessedInput) << std::endl;
+ //SWIFT_LOG(debug) << "unprocessedInput (" << unprocessedInput.size() << "): " << Hexify::hexify(unprocessedInput);
}
void handleSessionReady(bool error) {
diff --git a/Swiften/IDN/PlatformIDNConverter.cpp b/Swiften/IDN/PlatformIDNConverter.cpp
index c6104fb..3564bb9 100644
--- a/Swiften/IDN/PlatformIDNConverter.cpp
+++ b/Swiften/IDN/PlatformIDNConverter.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2018 Isode Limited.
+ * Copyright (c) 2012-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -13,16 +13,16 @@
namespace Swift {
-IDNConverter* PlatformIDNConverter::create() {
+std::unique_ptr<IDNConverter> PlatformIDNConverter::create() {
#if defined(HAVE_LIBIDN)
- return new LibIDNConverter();
+ return std::make_unique<LibIDNConverter>();
#elif defined(HAVE_ICU)
- return new ICUConverter();
+ return std::make_unique<ICUConverter>();
#else
#if defined(NEED_IDN)
#error "No IDN implementation"
#else
- return nullptr;
+ return {};
#endif
#endif
}
diff --git a/Swiften/IDN/PlatformIDNConverter.h b/Swiften/IDN/PlatformIDNConverter.h
index 704f7a7..3b9a275 100644
--- a/Swiften/IDN/PlatformIDNConverter.h
+++ b/Swiften/IDN/PlatformIDNConverter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012 Isode Limited.
+ * Copyright (c) 2012-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -8,10 +8,12 @@
#include <Swiften/Base/API.h>
+#include <memory>
+
namespace Swift {
class IDNConverter;
namespace PlatformIDNConverter {
- SWIFTEN_API IDNConverter* create();
+ SWIFTEN_API std::unique_ptr<IDNConverter> create();
}
}
diff --git a/Swiften/JID/JID.cpp b/Swiften/JID/JID.cpp
index fff88e9..eb72014 100644
--- a/Swiften/JID/JID.cpp
+++ b/Swiften/JID/JID.cpp
@@ -13,6 +13,7 @@
#include <Swiften/Base/String.h>
#include <Swiften/IDN/IDNConverter.h>
#include <Swiften/JID/JID.h>
+#include <Swiften/Network/HostAddress.h>
#ifndef SWIFTEN_JID_NO_DEFAULT_IDN_CONVERTER
#include <memory>
@@ -71,6 +72,33 @@ JID::JID(const std::string& node, const std::string& domain, const std::string&
nameprepAndSetComponents(node, domain, resource);
}
+JID::JID(const JID& other) {
+ this->operator=(other);
+}
+
+JID::JID(JID&& other) {
+ this->operator=(std::move(other));
+}
+
+JID& JID::operator=(const JID& other) {
+ valid_ = other.valid_;
+ node_ = other.node_;
+ domain_ = other.domain_;
+ hasResource_ = other.hasResource_;
+ resource_ = other.resource_;
+ return *this;
+}
+
+JID& JID::operator=(JID&& other) {
+ valid_ = other.valid_;
+ other.valid_ = false;
+ node_ = std::move(other.node_);
+ domain_ = std::move(other.domain_);
+ hasResource_ = other.hasResource_;
+ resource_ = std::move(other.resource_);
+ return *this;
+}
+
void JID::initializeFromString(const std::string& jid) {
if (String::beginsWith(jid, '@')) {
valid_ = false;
@@ -97,14 +125,49 @@ void JID::initializeFromString(const std::string& jid) {
}
}
+void JID::setComponents(const std::string& node, const std::string& domain, const std::string& resource) {
+ domain_ = domain;
+ try {
+ node_ = idnConverter->getStringPrepared(node, IDNConverter::XMPPNodePrep);
+ resource_ = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep);
+ }
+ catch (...) {
+ valid_ = false;
+ return;
+ }
+}
void JID::nameprepAndSetComponents(const std::string& node, const std::string& domain, const std::string& resource) {
- if (domain.empty() || !idnConverter->getIDNAEncoded(domain)) {
+ if (domain.empty() || (hasResource_ && resource.empty())) {
valid_ = false;
return;
}
- if (hasResource_ && resource.empty()) {
+ // Handling IPv6 addresses according to RFC 3986 rules
+ // saying that they are enclosed in square brackets
+ // which we have to remove when passing to HostAddress
+ if (domain.size() > 2 && domain.front() == '[' && domain.back() == ']') {
+ auto inner = std::string(domain.begin() + 1, domain.end() - 1);
+ auto hostAddress = HostAddress::fromString(inner);
+ if (hostAddress && hostAddress->isValid()) {
+ setComponents(node, domain, resource);
+ return;
+ }
+ }
+
+ const auto isAnyOfNonNumericAndNotDot = std::any_of(std::begin(domain), std::end(domain), [](char c) {return !::isdigit(c) && c != '.'; });
+ const auto isDomainAllNumeric = std::all_of(std::begin(domain), std::end(domain), [](char c) {return ::isdigit(c) ; });
+
+ //Prevent Windows validating non-dotted integers as OK if it can unpack them
+ if (!isAnyOfNonNumericAndNotDot && !isDomainAllNumeric) {
+ auto hostAddress = HostAddress::fromString(domain);
+ if (hostAddress && hostAddress->isValid()) {
+ setComponents(node, domain, resource);
+ return;
+ }
+ }
+
+ if (!isAnyOfNonNumericAndNotDot || !idnConverter->getIDNAEncoded(domain)) {
valid_ = false;
return;
}
@@ -118,7 +181,8 @@ void JID::nameprepAndSetComponents(const std::string& node, const std::string& d
domain_ = idnConverter->getStringPrepared(domain, IDNConverter::NamePrep);
}
resource_ = idnConverter->getStringPrepared(resource, IDNConverter::XMPPResourcePrep);
- } catch (...) {
+ }
+ catch (...) {
valid_ = false;
return;
}
diff --git a/Swiften/JID/JID.h b/Swiften/JID/JID.h
index dc92f53..aecc7cb 100644
--- a/Swiften/JID/JID.h
+++ b/Swiften/JID/JID.h
@@ -75,6 +75,11 @@ namespace Swift {
*/
JID(const std::string& node, const std::string& domain, const std::string& resource);
+ JID(const JID& other);
+ JID(JID&& other);
+ JID& operator=(const JID& other);
+ JID& operator=(JID&& other);
+
/**
* @return Is a correctly-formatted JID.
*/
@@ -184,6 +189,7 @@ namespace Swift {
private:
void nameprepAndSetComponents(const std::string& node, const std::string& domain, const std::string& resource);
+ void setComponents(const std::string& node, const std::string& domain, const std::string& resource);
void initializeFromString(const std::string&);
private:
diff --git a/Swiften/JID/UnitTest/JIDTest.cpp b/Swiften/JID/UnitTest/JIDTest.cpp
index 0753fb5..fc7583f 100644
--- a/Swiften/JID/UnitTest/JIDTest.cpp
+++ b/Swiften/JID/UnitTest/JIDTest.cpp
@@ -24,6 +24,7 @@ class JIDTest : public CppUnit::TestFixture
CPPUNIT_TEST(testConstructorWithString_OnlyDomainDotStrippedOff);
CPPUNIT_TEST(testConstructorWithString_InvalidOnlyDomainSingleDot);
CPPUNIT_TEST(testConstructorWithString_InvalidDomain);
+ CPPUNIT_TEST(testConstructorWithString_InvalidDomainOnlyDigits);
CPPUNIT_TEST(testConstructorWithString_InvalidDomainEmptyLabel);
CPPUNIT_TEST(testConstructorWithString_UpperCaseNode);
CPPUNIT_TEST(testConstructorWithString_UpperCaseDomain);
@@ -71,6 +72,12 @@ class JIDTest : public CppUnit::TestFixture
CPPUNIT_TEST(testGetUnescapedNode);
CPPUNIT_TEST(testGetUnescapedNode_XEP106Examples);
CPPUNIT_TEST(testStringPrepFailures);
+ CPPUNIT_TEST(testConstructorWithString_DomainIPv4);
+ CPPUNIT_TEST(testConstructorWithString_DomainNOTIPv4);
+ CPPUNIT_TEST(testConstructorWithString_ValidDomainNOTIPv4);
+ CPPUNIT_TEST(testConstructorWithString_DomainIPv6);
+ CPPUNIT_TEST(testConstructorWithString_DomainInvalidIPv6);
+ CPPUNIT_TEST(testConstructorWithString_DomainIPv6NoBrackets);
CPPUNIT_TEST_SUITE_END();
public:
@@ -156,6 +163,10 @@ class JIDTest : public CppUnit::TestFixture
CPPUNIT_ASSERT(!JID("foo@bar,baz").isValid());
}
+ void testConstructorWithString_InvalidDomainOnlyDigits() {
+ CPPUNIT_ASSERT(!JID("1234").isValid());
+ }
+
void testConstructorWithString_InvalidDomainEmptyLabel() {
CPPUNIT_ASSERT(!JID("foo@bar..").isValid());
}
@@ -492,6 +503,46 @@ class JIDTest : public CppUnit::TestFixture
CPPUNIT_ASSERT_EQUAL(std::string("c:\\cool stuff"), JID("c\\3a\\cool\\20stuff@example.com").getUnescapedNode());
CPPUNIT_ASSERT_EQUAL(std::string("c:\\5commas"), JID("c\\3a\\5c5commas@example.com").getUnescapedNode());
}
+
+ void testConstructorWithString_DomainIPv4() {
+ JID testling("foo@192.34.12.1/resource");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("192.34.12.1"), testling.getDomain());
+ CPPUNIT_ASSERT_EQUAL(std::string("resource"), testling.getResource());
+ CPPUNIT_ASSERT(!testling.isBare());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
+
+ void testConstructorWithString_DomainNOTIPv4() {
+ JID testling("foo@500.34.12.1/resource");
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
+
+ void testConstructorWithString_ValidDomainNOTIPv4() {
+ JID testling("foo@500.34.12.1a/resource");
+ CPPUNIT_ASSERT(testling.isValid());
+ }
+
+ void testConstructorWithString_DomainIPv6() {
+ JID testling("foo@[fe80::a857:33ff:febd:3580]/resource");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("foo"), testling.getNode());
+ CPPUNIT_ASSERT_EQUAL(std::string("[fe80::a857:33ff:febd:3580]"), testling.getDomain());
+ CPPUNIT_ASSERT_EQUAL(std::string("resource"), testling.getResource());
+ CPPUNIT_ASSERT(!testling.isBare());
+ CPPUNIT_ASSERT(testling.isValid());
+ }
+
+ void testConstructorWithString_DomainInvalidIPv6() {
+ JID testling("foo@[1111::a1111:1111:111!:!!!!]/resource");
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
+
+ void testConstructorWithString_DomainIPv6NoBrackets() {
+ JID testling("foo@fe80::a857:33ff:febd:3580/resource");
+ CPPUNIT_ASSERT(!testling.isValid());
+ }
};
CPPUNIT_TEST_SUITE_REGISTRATION(JIDTest);
diff --git a/Swiften/Jingle/AbstractJingleSessionListener.cpp b/Swiften/Jingle/AbstractJingleSessionListener.cpp
index 20edf15..56d2e92 100644
--- a/Swiften/Jingle/AbstractJingleSessionListener.cpp
+++ b/Swiften/Jingle/AbstractJingleSessionListener.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013-2016 Isode Limited.
+ * Copyright (c) 2013-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,31 +11,31 @@
using namespace Swift;
void AbstractJingleSessionListener::handleSessionAcceptReceived(const JingleContentID&, std::shared_ptr<JingleDescription>, std::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented";
}
void AbstractJingleSessionListener::handleSessionInfoReceived(std::shared_ptr<JinglePayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented";
}
void AbstractJingleSessionListener::handleSessionTerminateReceived(boost::optional<JinglePayload::Reason>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented";
}
void AbstractJingleSessionListener::handleTransportAcceptReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented";
}
void AbstractJingleSessionListener::handleTransportInfoReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented";
}
void AbstractJingleSessionListener::handleTransportRejectReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented";
}
void AbstractJingleSessionListener::handleTransportReplaceReceived(const JingleContentID&, std::shared_ptr<JingleTransportPayload>) {
- SWIFT_LOG(warning) << "Unimplemented" << std::endl;
+ SWIFT_LOG(warning) << "Unimplemented";
}
void AbstractJingleSessionListener::handleTransportInfoAcknowledged(const std::string&) {
diff --git a/Swiften/Jingle/JingleResponder.cpp b/Swiften/Jingle/JingleResponder.cpp
index 09bb234..af9808e 100644
--- a/Swiften/Jingle/JingleResponder.cpp
+++ b/Swiften/Jingle/JingleResponder.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.
*/
@@ -32,17 +32,17 @@ bool JingleResponder::handleSetRequest(const JID& from, const JID& to, const std
JingleSessionImpl::ref session = std::make_shared<JingleSessionImpl>(payload->getInitiator(), from, payload->getSessionID(), router);
sessionManager->handleIncomingSession(from, to, session, payload->getContents());
} else {
- SWIFT_LOG(debug) << "Unable to create Jingle session due to initiator not being a full JID." << std::endl;
+ SWIFT_LOG(debug) << "Unable to create Jingle session due to initiator not being a full JID.";
}
}
}
else {
JingleSessionImpl::ref session;
if (payload->getInitiator().isValid()) {
- SWIFT_LOG(debug) << "Lookup session by initiator." << std::endl;
+ SWIFT_LOG(debug) << "Lookup session by initiator.";
session = sessionManager->getSession(payload->getInitiator(), payload->getSessionID());
} else {
- SWIFT_LOG(debug) << "Lookup session by from attribute." << std::endl;
+ SWIFT_LOG(debug) << "Lookup session by from attribute.";
session = sessionManager->getSession(from, payload->getSessionID());
}
if (session) {
diff --git a/Swiften/Jingle/JingleSessionImpl.cpp b/Swiften/Jingle/JingleSessionImpl.cpp
index 06aa039..b4c5d03 100644
--- a/Swiften/Jingle/JingleSessionImpl.cpp
+++ b/Swiften/Jingle/JingleSessionImpl.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.
*/
@@ -23,7 +23,7 @@
namespace Swift {
JingleSessionImpl::JingleSessionImpl(const JID& initiator, const JID& peerJID, const std::string& id, IQRouter* router) : JingleSession(initiator, id), iqRouter(router), peerJID(peerJID) {
- SWIFT_LOG(debug) << "initiator: " << initiator << ", peerJID: " << peerJID << std::endl;
+ SWIFT_LOG(debug) << "initiator: " << initiator << ", peerJID: " << peerJID;
}
void JingleSessionImpl::handleIncomingAction(JinglePayload::ref action) {
@@ -38,7 +38,7 @@ void JingleSessionImpl::handleIncomingAction(JinglePayload::ref action) {
JingleContentPayload::ref content = action->getPayload<JingleContentPayload>();
if (!content) {
- SWIFT_LOG(debug) << "no content payload!" << std::endl;
+ SWIFT_LOG(debug) << "no content payload!";
return;
}
JingleContentID contentID(content->getName(), content->getCreator());
diff --git a/Swiften/Jingle/JingleSessionManager.cpp b/Swiften/Jingle/JingleSessionManager.cpp
index f7ed58e..083554a 100644
--- a/Swiften/Jingle/JingleSessionManager.cpp
+++ b/Swiften/Jingle/JingleSessionManager.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.
*/
@@ -38,7 +38,7 @@ void JingleSessionManager::removeIncomingSessionHandler(IncomingJingleSessionHan
void JingleSessionManager::registerOutgoingSession(const JID& initiator, JingleSessionImpl::ref session) {
sessions.insert(std::make_pair(JIDSession(initiator, session->getID()), session));
- SWIFT_LOG(debug) << "Added session " << session->getID() << " for initiator " << initiator.toString() << std::endl;
+ SWIFT_LOG(debug) << "Added session " << session->getID() << " for initiator " << initiator.toString();
}
void JingleSessionManager::handleIncomingSession(const JID& initiator, const JID& recipient, JingleSessionImpl::ref session, const std::vector<JingleContentPayload::ref>& contents) {
diff --git a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp
index 08de722..262add3 100644
--- a/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.cpp
+++ b/Swiften/LinkLocal/DNSSD/Avahi/AvahiResolveHostnameQuery.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.
*/
@@ -15,7 +15,7 @@
namespace Swift {
AvahiResolveHostnameQuery::AvahiResolveHostnameQuery(const std::string& hostname, int, std::shared_ptr<AvahiQuerier> querier, EventLoop* eventLoop) : AvahiQuery(querier, eventLoop), hostname(hostname) {
- SWIFT_LOG(debug) << "Resolving hostname " << hostname << std::endl;
+ SWIFT_LOG(debug) << "Resolving hostname " << hostname;
}
void AvahiResolveHostnameQuery::run() {
diff --git a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h
index 9eb8cd9..cc95d64 100644
--- a/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h
+++ b/Swiften/LinkLocal/DNSSD/Bonjour/BonjourRegisterQuery.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -26,7 +26,7 @@ namespace Swift {
recordSize = boost::numeric_cast<unsigned short>(txtRecord.size());
}
catch (const boost::numeric::bad_numeric_cast&) {
- SWIFT_LOG(warning) << "Bonjour TXT record is too long (" << txtRecord.size() << " bytes), not registring service" << std::endl;
+ SWIFT_LOG(warning) << "Bonjour TXT record is too long (" << txtRecord.size() << " bytes), not registring service";
return;
}
DNSServiceErrorType result = DNSServiceRegister(
@@ -34,7 +34,7 @@ namespace Swift {
recordSize, vecptr(txtRecord),
&BonjourRegisterQuery::handleServiceRegisteredStatic, this);
if (result != kDNSServiceErr_NoError) {
- SWIFT_LOG(warning) << "Failed to register Bonjour service" << std::endl;
+ SWIFT_LOG(warning) << "Failed to register Bonjour service";
sdRef = nullptr;
}
}
@@ -58,7 +58,7 @@ namespace Swift {
DNSServiceUpdateRecord(sdRef, nullptr, 0, boost::numeric_cast<unsigned short>(txtRecord.size()), vecptr(txtRecord), 0);
}
catch (const boost::numeric::bad_numeric_cast&) {
- SWIFT_LOG(warning) << "Bonjour TXT record is too long (" << txtRecord.size() << " bytes), not updating service record" << std::endl;
+ SWIFT_LOG(warning) << "Bonjour TXT record is too long (" << txtRecord.size() << " bytes), not updating service record";
}
}
diff --git a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp
index 914fab4..5e529fd 100644
--- a/Swiften/LinkLocal/LinkLocalServiceInfo.cpp
+++ b/Swiften/LinkLocal/LinkLocalServiceInfo.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -49,7 +49,7 @@ boost::optional<ByteArray> LinkLocalServiceInfo::toTXTRecord() const {
return result;
}
catch (const std::exception& e) {
- SWIFT_LOG(warning) << "Failed to create TXT record for link local service info: " << e.what() << std::endl;
+ SWIFT_LOG(warning) << "Failed to create TXT record for link local service info: " << e.what();
return boost::none;
}
}
diff --git a/Swiften/Network/BOSHConnection.cpp b/Swiften/Network/BOSHConnection.cpp
index aaec9f2..1312a3e 100644
--- a/Swiften/Network/BOSHConnection.cpp
+++ b/Swiften/Network/BOSHConnection.cpp
@@ -74,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) {
- SWIFT_LOG(debug) << (error ? error->getMessage() : "Unknown TLS error") << std::endl;
+ SWIFT_LOG(debug) << (error ? error->getMessage() : "Unknown TLS error");
}
void BOSHConnection::writeData(const SafeByteArray& data) {
@@ -123,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 {
@@ -211,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) {
@@ -275,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 551363d..6ae6bf6 100644
--- a/Swiften/Network/BoostConnection.cpp
+++ b/Swiften/Network/BoostConnection.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -107,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();
@@ -126,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());
@@ -141,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 8db9656..dc05172 100644
--- a/Swiften/Network/BoostConnectionServer.cpp
+++ b/Swiften/Network/BoostConnectionServer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -46,7 +46,7 @@ boost::optional<BoostConnectionServer::Error> BoostConnectionServer::tryStart()
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();
}
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 94899ad..a9210ba 100644
--- a/Swiften/Network/ChainedConnector.cpp
+++ b/Swiften/Network/ChainedConnector.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2011-2018 Isode Limited.
+ * Copyright (c) 2011-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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/Connector.cpp b/Swiften/Network/Connector.cpp
index a0e6b23..e27b95d 100644
--- a/Swiften/Network/Connector.cpp
+++ b/Swiften/Network/Connector.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -25,7 +25,7 @@ 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);
@@ -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,7 +118,7 @@ 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();
@@ -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,7 +143,7 @@ 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();
@@ -195,8 +195,8 @@ void Connector::finish(std::shared_ptr<Connection> connection) {
}
void Connector::handleTimeout() {
- SWIFT_LOG(debug) << "Timeout" << std::endl;
- SWIFT_LOG_ASSERT(currentConnection, error) << "Connection not valid but triggered a 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/EnvironmentProxyProvider.cpp b/Swiften/Network/EnvironmentProxyProvider.cpp
index 65cf4ff..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.
*/
@@ -26,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 {
diff --git a/Swiften/Network/GConfProxyProvider.cpp b/Swiften/Network/GConfProxyProvider.cpp
index 7c31868..a2f8adc 100644
--- a/Swiften/Network/GConfProxyProvider.cpp
+++ b/Swiften/Network/GConfProxyProvider.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2016-2018 Isode Limited.
+ * Copyright (c) 2016-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -39,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 {
diff --git a/Swiften/Network/HTTPConnectProxiedConnection.cpp b/Swiften/Network/HTTPConnectProxiedConnection.cpp
index 8eba49e..e63b8e2 100644
--- a/Swiften/Network/HTTPConnectProxiedConnection.cpp
+++ b/Swiften/Network/HTTPConnectProxiedConnection.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2011-2018 Isode Limited.
+ * Copyright (c) 2011-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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/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/NATPMPInterface.cpp b/Swiften/Network/NATPMPInterface.cpp
index 0c33c1f..e20fecd 100644
--- a/Swiften/Network/NATPMPInterface.cpp
+++ b/Swiften/Network/NATPMPInterface.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2018 Isode Limited.
+ * Copyright (c) 2014-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -42,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>();
}
@@ -67,7 +67,7 @@ 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>();
}
}
@@ -80,7 +80,7 @@ boost::optional<NATPortMapping> NATPMPInterface::addPortForward(unsigned short l
mapping.getLocalPort(),
mapping.getPublicPort(),
mapping.getLeaseInSeconds()) < 0) {
- SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!" << std::endl;
+ SWIFT_LOG(debug) << "Failed to send NAT-PMP port forwarding request!";
return boost::optional<NATPortMapping>();
}
@@ -106,14 +106,14 @@ boost::optional<NATPortMapping> NATPMPInterface::addPortForward(unsigned short l
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, mapping.getLocalPort(), 0, 0) < 0) {
- SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!" << std::endl;
+ SWIFT_LOG(debug) << "Failed to send NAT-PMP remove forwarding request!";
return false;
}
@@ -133,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/PlatformDomainNameServiceQuery.cpp b/Swiften/Network/PlatformDomainNameServiceQuery.cpp
index f884500..2ff14e1 100644
--- a/Swiften/Network/PlatformDomainNameServiceQuery.cpp
+++ b/Swiften/Network/PlatformDomainNameServiceQuery.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 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;
}
diff --git a/Swiften/Network/PlatformNATTraversalWorker.cpp b/Swiften/Network/PlatformNATTraversalWorker.cpp
index 041ad2d..5431379 100644
--- a/Swiften/Network/PlatformNATTraversalWorker.cpp
+++ b/Swiften/Network/PlatformNATTraversalWorker.cpp
@@ -157,7 +157,7 @@ NATTraversalInterface* PlatformNATTraversalWorker::getNATTraversalInterface() co
miniUPnPInterface = new MiniUPnPInterface();
miniUPnPSupported = miniUPnPInterface->isAvailable();
}
- SWIFT_LOG(debug) << "UPnP NAT traversal supported: " << static_cast<bool>(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: " << static_cast<bool>(natPMPSupported) << std::endl;
+ SWIFT_LOG(debug) << "NAT-PMP NAT traversal supported: " << static_cast<bool>(natPMPSupported);
if (natPMPSupported) {
return natPMPInterface;
}
diff --git a/Swiften/Network/ProxiedConnection.cpp b/Swiften/Network/ProxiedConnection.cpp
index 4c97e31..0c5cda6 100644
--- a/Swiften/Network/ProxiedConnection.cpp
+++ b/Swiften/Network/ProxiedConnection.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012-2018 Isode Limited.
+ * Copyright (c) 2012-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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/SOCKS5ProxiedConnection.cpp b/Swiften/Network/SOCKS5ProxiedConnection.cpp
index d7036f2..c76b6e6 100644
--- a/Swiften/Network/SOCKS5ProxiedConnection.cpp
+++ b/Swiften/Network/SOCKS5ProxiedConnection.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2018 Isode Limited.
+ * Copyright (c) 2014-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -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/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/HTTPConnectProxiedConnectionTest.cpp b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
index 065d015..e9268b0 100644
--- a/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
+++ b/Swiften/Network/UnitTest/HTTPConnectProxiedConnectionTest.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 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;
}
diff --git a/Swiften/Network/WindowsProxyProvider.cpp b/Swiften/Network/WindowsProxyProvider.cpp
index 9a60bb4..13fdb25 100644
--- a/Swiften/Network/WindowsProxyProvider.cpp
+++ b/Swiften/Network/WindowsProxyProvider.cpp
@@ -52,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);
}
@@ -86,7 +86,7 @@ HostAddressPort WindowsProxyProvider::getAsHostAddressPort(std::string proxy) {
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;
diff --git a/Swiften/Parser/Attribute.h b/Swiften/Parser/Attribute.h
index f54317e..07e63b4 100644
--- a/Swiften/Parser/Attribute.h
+++ b/Swiften/Parser/Attribute.h
@@ -14,6 +14,9 @@ namespace Swift {
Attribute(const std::string& name, const std::string& ns) : name(name), ns(ns) {
}
+ Attribute(const std::string& name, const std::string& ns, const std::string& prefix) : name(name), ns(ns), prefix(prefix) {
+ }
+
const std::string& getName() const {
return name;
}
@@ -22,6 +25,10 @@ namespace Swift {
return ns;
}
+ const std::string& getPrefix() const {
+ return prefix;
+ }
+
bool operator==(const Attribute& o) const {
return o.name == name && o.ns == ns;
}
@@ -29,5 +36,6 @@ namespace Swift {
private:
std::string name;
std::string ns;
+ std::string prefix;
};
}
diff --git a/Swiften/Parser/AttributeMap.cpp b/Swiften/Parser/AttributeMap.cpp
index f6767de..7814a64 100644
--- a/Swiften/Parser/AttributeMap.cpp
+++ b/Swiften/Parser/AttributeMap.cpp
@@ -54,3 +54,7 @@ boost::optional<std::string> AttributeMap::getAttributeValue(const std::string&
void AttributeMap::addAttribute(const std::string& name, const std::string& ns, const std::string& value) {
attributes.push_back(Entry(Attribute(name, ns), value));
}
+
+void AttributeMap::addAttribute(const std::string& name, const std::string& ns, const std::string& prefix, const std::string& value) {
+ attributes.push_back(Entry(Attribute(name, ns, prefix), value));
+}
diff --git a/Swiften/Parser/AttributeMap.h b/Swiften/Parser/AttributeMap.h
index 804d6aa..26d5826 100644
--- a/Swiften/Parser/AttributeMap.h
+++ b/Swiften/Parser/AttributeMap.h
@@ -43,6 +43,7 @@ namespace Swift {
boost::optional<std::string> getAttributeValue(const std::string&) const;
void addAttribute(const std::string& name, const std::string& ns, const std::string& value);
+ void addAttribute(const std::string& name, const std::string& ns, const std::string& prefix, const std::string& value);
const std::vector<Entry>& getEntries() const {
return attributes;
diff --git a/Swiften/Parser/ExpatParser.cpp b/Swiften/Parser/ExpatParser.cpp
index e4e66f2..32d4f53 100644
--- a/Swiften/Parser/ExpatParser.cpp
+++ b/Swiften/Parser/ExpatParser.cpp
@@ -11,6 +11,8 @@
#include <memory>
#include <string>
+#include <boost/algorithm/string.hpp>
+
#include <expat.h>
#include <Swiften/Base/String.h>
@@ -18,6 +20,33 @@
#pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
+namespace {
+struct XmlInfo {
+ std::string prefix;
+ std::string uri;
+ std::string name;
+};
+
+XmlInfo splitExpatInfo(const std::string& s, char sep) {
+ // name
+ // uri|name
+ // uri|name|prefix
+ std::vector<std::string> v;
+ boost::split(v, s, [sep](char c) {return c == sep; });
+ switch (v.size()) {
+ case 1:
+ return{ "", "", std::move(v[0]) };
+ case 2:
+ return{ "", std::move(v[0]), std::move(v[1]) };
+ case 3:
+ return{ std::move(v[2]), std::move(v[0]), std::move(v[1]) };
+ default:
+ return{ "", "", "" };
+ }
+}
+}
+
+
namespace Swift {
static const char NAMESPACE_SEPARATOR = '\x01';
@@ -27,33 +56,24 @@ struct ExpatParser::Private {
};
static void handleStartElement(void* parser, const XML_Char* name, const XML_Char** attributes) {
- std::pair<std::string,std::string> nsTagPair = String::getSplittedAtFirst(name, NAMESPACE_SEPARATOR);
- if (nsTagPair.second == "") {
- nsTagPair.second = nsTagPair.first;
- nsTagPair.first = "";
- }
+ auto elemInfo = splitExpatInfo(name, NAMESPACE_SEPARATOR);
+
AttributeMap attributeValues;
const XML_Char** currentAttribute = attributes;
while (*currentAttribute) {
- std::pair<std::string,std::string> nsAttributePair = String::getSplittedAtFirst(*currentAttribute, NAMESPACE_SEPARATOR);
- if (nsAttributePair.second == "") {
- nsAttributePair.second = nsAttributePair.first;
- nsAttributePair.first = "";
- }
- attributeValues.addAttribute(nsAttributePair.second, nsAttributePair.first, std::string(*(currentAttribute+1)));
+ auto attribInfo = splitExpatInfo(*currentAttribute, NAMESPACE_SEPARATOR);
+ attributeValues.addAttribute(attribInfo.name, attribInfo.uri, attribInfo.prefix, std::string(*(currentAttribute+1)));
currentAttribute += 2;
}
- static_cast<XMLParser*>(parser)->getClient()->handleStartElement(nsTagPair.second, nsTagPair.first, attributeValues);
+ auto* client = static_cast<XMLParser*>(parser)->getClient();
+ client->handleStartElementPrefix(elemInfo.prefix, elemInfo.uri, elemInfo.name, attributeValues);
+ client->handleStartElement(elemInfo.name, elemInfo.uri, attributeValues);
}
static void handleEndElement(void* parser, const XML_Char* name) {
- std::pair<std::string,std::string> nsTagPair = String::getSplittedAtFirst(name, NAMESPACE_SEPARATOR);
- if (nsTagPair.second == "") {
- nsTagPair.second = nsTagPair.first;
- nsTagPair.first = "";
- }
- static_cast<XMLParser*>(parser)->getClient()->handleEndElement(nsTagPair.second, nsTagPair.first);
+ auto elemInfo = splitExpatInfo(name, NAMESPACE_SEPARATOR);
+ static_cast<XMLParser*>(parser)->getClient()->handleEndElement(elemInfo.name, elemInfo.uri);
}
static void handleCharacterData(void* parser, const XML_Char* data, int len) {
@@ -64,18 +84,40 @@ static void handleCharacterData(void* parser, const XML_Char* data, int len) {
static void handleXMLDeclaration(void*, const XML_Char*, const XML_Char*, int) {
}
+static void handleNamespaceDeclaration(void* parser, const XML_Char* prefix, const XML_Char* uri) {
+ static_cast<XMLParser*>(parser)->getClient()->handleNamespaceDeclaration(std::string(prefix ? prefix : ""), std::string(uri ? uri : ""));
+}
+
static void handleEntityDeclaration(void* parser, const XML_Char*, int, const XML_Char*, int, const XML_Char*, const XML_Char*, const XML_Char*, const XML_Char*) {
static_cast<ExpatParser*>(parser)->stopParser();
}
+static void handleComment(void* parser, const XML_Char* /*data*/) {
+ if (!static_cast<ExpatParser*>(parser)->allowsComments()) {
+ static_cast<ExpatParser*>(parser)->stopParser();
+ }
+}
+
+static void handleProcessingInstruction(void* parser, const XML_Char* /*target*/, const XML_Char* /*data*/) {
+ static_cast<ExpatParser*>(parser)->stopParser();
+}
+
+static void handleDoctypeDeclaration(void* parser, const XML_Char* /*doctypeName*/, const XML_Char* /*sysid*/, const XML_Char* /*pubid*/, int /*has_internal_subset*/) {
+ static_cast<ExpatParser*>(parser)->stopParser();
+}
-ExpatParser::ExpatParser(XMLParserClient* client) : XMLParser(client), p(new Private()) {
+ExpatParser::ExpatParser(XMLParserClient* client, bool allowComments) : XMLParser(client, allowComments), p(new Private()) {
p->parser_ = XML_ParserCreateNS("UTF-8", NAMESPACE_SEPARATOR);
+ XML_SetReturnNSTriplet(p->parser_, true);
XML_SetUserData(p->parser_, this);
XML_SetElementHandler(p->parser_, handleStartElement, handleEndElement);
XML_SetCharacterDataHandler(p->parser_, handleCharacterData);
XML_SetXmlDeclHandler(p->parser_, handleXMLDeclaration);
XML_SetEntityDeclHandler(p->parser_, handleEntityDeclaration);
+ XML_SetNamespaceDeclHandler(p->parser_, handleNamespaceDeclaration, nullptr);
+ XML_SetCommentHandler(p->parser_, handleComment);
+ XML_SetProcessingInstructionHandler(p->parser_, handleProcessingInstruction);
+ XML_SetDoctypeDeclHandler(p->parser_, handleDoctypeDeclaration, nullptr);
}
ExpatParser::~ExpatParser() {
diff --git a/Swiften/Parser/ExpatParser.h b/Swiften/Parser/ExpatParser.h
index 7583339..34d790d 100644
--- a/Swiften/Parser/ExpatParser.h
+++ b/Swiften/Parser/ExpatParser.h
@@ -16,7 +16,7 @@
namespace Swift {
class SWIFTEN_API ExpatParser : public XMLParser, public boost::noncopyable {
public:
- ExpatParser(XMLParserClient* client);
+ ExpatParser(XMLParserClient* client, bool allowComments = false);
~ExpatParser();
bool parse(const std::string& data, bool finalData = false);
diff --git a/Swiften/Parser/IQParser.cpp b/Swiften/Parser/IQParser.cpp
index 5cfae34..363f7ec 100644
--- a/Swiften/Parser/IQParser.cpp
+++ b/Swiften/Parser/IQParser.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.
*/
@@ -32,7 +32,7 @@ void IQParser::handleStanzaAttributes(const AttributeMap& attributes) {
getStanzaGeneric()->setType(IQ::Error);
}
else {
- SWIFT_LOG(warning) << "Unknown IQ type: " << *type << std::endl;
+ SWIFT_LOG(warning) << "Unknown IQ type: " << *type;
getStanzaGeneric()->setType(IQ::Get);
}
}
diff --git a/Swiften/Parser/LibXMLParser.cpp b/Swiften/Parser/LibXMLParser.cpp
index c9f3a07..32b91a1 100644
--- a/Swiften/Parser/LibXMLParser.cpp
+++ b/Swiften/Parser/LibXMLParser.cpp
@@ -17,6 +17,12 @@
#include <Swiften/Base/Log.h>
#include <Swiften/Parser/XMLParserClient.h>
+namespace {
+std::string asString(const unsigned char* s) {
+ return s ? std::string(reinterpret_cast<const char*>(s)) : std::string();
+}
+}
+
namespace Swift {
struct LibXMLParser::Private {
@@ -24,29 +30,39 @@ struct LibXMLParser::Private {
xmlParserCtxtPtr context_;
};
-static void handleStartElement(void* parser, const xmlChar* name, const xmlChar*, const xmlChar* xmlns, int, const xmlChar**, int nbAttributes, int nbDefaulted, const xmlChar ** attributes) {
+static void handleStartElement(void* parser, const xmlChar* name, const xmlChar* prefix, const xmlChar* xmlns, int nbNamespaces, const xmlChar** namespaces, int nbAttributes, int nbDefaulted, const xmlChar ** attributes) {
AttributeMap attributeValues;
if (nbDefaulted != 0) {
// Just because i don't understand what this means yet :-)
- SWIFT_LOG(error) << "Unexpected nbDefaulted on XML element" << std::endl;
+ SWIFT_LOG(error) << "Unexpected nbDefaulted on XML element";
}
for (int i = 0; i < nbAttributes*5; i += 5) {
- std::string attributeNS = "";
- if (attributes[i+2]) {
- attributeNS = std::string(reinterpret_cast<const char*>(attributes[i+2]));
- }
+ std::string attributeName = asString(attributes[i]);
+ std::string attributePrefix = asString(attributes[i+1]);
+ std::string attributeNS = asString(attributes[i+2]);
assert(attributes[i+4] >= attributes[i+3]);
attributeValues.addAttribute(
- std::string(reinterpret_cast<const char*>(attributes[i])),
+ attributeName,
attributeNS,
+ attributePrefix,
std::string(reinterpret_cast<const char*>(attributes[i+3]),
static_cast<size_t>(attributes[i+4]-attributes[i+3])));
}
- static_cast<XMLParser*>(parser)->getClient()->handleStartElement(reinterpret_cast<const char*>(name), (xmlns ? reinterpret_cast<const char*>(xmlns) : std::string()), attributeValues);
+ auto* client = static_cast<XMLParser*>(parser)->getClient();
+ for (auto i = 0; i < nbNamespaces * 2; i += 2) {
+ const auto prefix = asString(namespaces[i]);
+ const auto uri = asString(namespaces[i + 1]);
+ client->handleNamespaceDeclaration(prefix, uri);
+ }
+ auto nameStr = asString(name);
+ auto xmlsnsStr = asString(xmlns);
+ auto prefixStr = asString(prefix);
+ client->handleStartElementPrefix(prefixStr, xmlsnsStr, nameStr, attributeValues);
+ client->handleStartElement(nameStr, xmlsnsStr, attributeValues);
}
static void handleEndElement(void *parser, const xmlChar* name, const xmlChar*, const xmlChar* xmlns) {
- static_cast<XMLParser*>(parser)->getClient()->handleEndElement(reinterpret_cast<const char*>(name), (xmlns ? reinterpret_cast<const char*>(xmlns) : std::string()));
+ static_cast<XMLParser*>(parser)->getClient()->handleEndElement(asString(name), asString(xmlns));
}
static void handleCharacterData(void* parser, const xmlChar* data, int len) {
@@ -54,6 +70,24 @@ static void handleCharacterData(void* parser, const xmlChar* data, int len) {
static_cast<XMLParser*>(parser)->getClient()->handleCharacterData(std::string(reinterpret_cast<const char*>(data), static_cast<size_t>(len)));
}
+static void handleComment(void* parser, const xmlChar* /*data*/) {
+ if (!static_cast<LibXMLParser*>(parser)->allowsComments()) {
+ static_cast<LibXMLParser*>(parser)->stopParser();
+ }
+}
+
+static void handleEntityDeclaration(void * parser, const xmlChar* /*name*/, int /*type*/, const xmlChar* /*publicId*/, const xmlChar* /*systemId*/, xmlChar* /*content*/) {
+ static_cast<LibXMLParser*>(parser)->stopParser();
+}
+
+static void handleProcessingInstruction(void* parser, const xmlChar* /*target*/, const xmlChar* /*data*/) {
+ static_cast<LibXMLParser*>(parser)->stopParser();
+}
+
+static void handleExternalSubset(void* parser, const xmlChar * /*name*/, const xmlChar * /*ExternalID*/, const xmlChar * /*SystemID*/) {
+ static_cast<LibXMLParser*>(parser)->stopParser();
+}
+
static void handleError(void*, const char* /*m*/, ... ) {
/*
va_list args;
@@ -66,12 +100,20 @@ static void handleError(void*, const char* /*m*/, ... ) {
static void handleWarning(void*, const char*, ... ) {
}
+static void handleGenericError(void*, const char*, ... ) {
+}
+
+static void handleStructuredError(void*, xmlErrorPtr) {
+}
+
bool LibXMLParser::initialized = false;
-LibXMLParser::LibXMLParser(XMLParserClient* client) : XMLParser(client), p(new Private()) {
+LibXMLParser::LibXMLParser(XMLParserClient* client, bool allowComments) : XMLParser(client, allowComments), p(new Private()) {
// Initialize libXML for multithreaded applications
if (!initialized) {
xmlInitParser();
+ xmlSetGenericErrorFunc(nullptr, handleGenericError);
+ xmlSetStructuredErrorFunc(nullptr, handleStructuredError);
initialized = true;
}
@@ -82,6 +124,10 @@ LibXMLParser::LibXMLParser(XMLParserClient* client) : XMLParser(client), p(new P
p->handler_.characters = &handleCharacterData;
p->handler_.warning = &handleWarning;
p->handler_.error = &handleError;
+ p->handler_.comment = &handleComment;
+ p->handler_.entityDecl = &handleEntityDeclaration;
+ p->handler_.processingInstruction = &handleProcessingInstruction;
+ p->handler_.externalSubset = &handleExternalSubset;
p->context_ = xmlCreatePushParserCtxt(&p->handler_, this, nullptr, 0, nullptr);
xmlCtxtUseOptions(p->context_, XML_PARSE_NOENT);
@@ -98,11 +144,12 @@ bool LibXMLParser::parse(const std::string& data, bool finalData) {
if (data.size() > std::numeric_limits<int>::max()) {
return false;
}
- if (xmlParseChunk(p->context_, data.c_str(), static_cast<int>(data.size()), finalData) == XML_ERR_OK) {
+ auto error = xmlParseChunk(p->context_, data.c_str(), static_cast<int>(data.size()), finalData);
+ if (error == XML_ERR_OK) {
return true;
}
- xmlError* error = xmlCtxtGetLastError(p->context_);
- if (error->code == XML_WAR_NS_URI || error->code == XML_WAR_NS_URI_RELATIVE) {
+ if (stopped_) return false;
+ if (error == XML_WAR_NS_URI || error == XML_WAR_NS_URI_RELATIVE) {
xmlCtxtResetLastError(p->context_);
p->context_->errNo = XML_ERR_OK;
return true;
@@ -110,4 +157,9 @@ bool LibXMLParser::parse(const std::string& data, bool finalData) {
return false;
}
+void LibXMLParser::stopParser() {
+ stopped_ = true;
+ xmlStopParser(p->context_);
+}
+
}
diff --git a/Swiften/Parser/LibXMLParser.h b/Swiften/Parser/LibXMLParser.h
index a863867..e21770d 100644
--- a/Swiften/Parser/LibXMLParser.h
+++ b/Swiften/Parser/LibXMLParser.h
@@ -19,13 +19,16 @@ namespace Swift {
*/
class LibXMLParser : public XMLParser, public boost::noncopyable {
public:
- LibXMLParser(XMLParserClient* client);
+ LibXMLParser(XMLParserClient* client, bool allowComments = false);
virtual ~LibXMLParser();
bool parse(const std::string& data, bool finalData = false);
+ void stopParser();
+
private:
static bool initialized;
+ bool stopped_ = false;
struct Private;
const std::unique_ptr<Private> p;
diff --git a/Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h b/Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h
index dcdbffa..8f9e0e1 100644
--- a/Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h
+++ b/Swiften/Parser/PayloadParsers/UnitTest/PayloadsParserTester.h
@@ -19,7 +19,7 @@ namespace Swift {
class PayloadsParserTester : public XMLParserClient {
public:
PayloadsParserTester() : level(0) {
- xmlParser = PlatformXMLParserFactory().createXMLParser(this);
+ xmlParser = PlatformXMLParserFactory().createXMLParser(this, false);
}
bool parse(const std::string& data) {
diff --git a/Swiften/Parser/PlatformXMLParserFactory.cpp b/Swiften/Parser/PlatformXMLParserFactory.cpp
index bf66734..a424aca 100644
--- a/Swiften/Parser/PlatformXMLParserFactory.cpp
+++ b/Swiften/Parser/PlatformXMLParserFactory.cpp
@@ -20,11 +20,11 @@ namespace Swift {
PlatformXMLParserFactory::PlatformXMLParserFactory() {
}
-std::unique_ptr<XMLParser> PlatformXMLParserFactory::createXMLParser(XMLParserClient* client) {
+std::unique_ptr<XMLParser> PlatformXMLParserFactory::createXMLParser(XMLParserClient* client, bool allowComments) {
#ifdef HAVE_LIBXML
- return std::make_unique<LibXMLParser>(client);
+ return std::make_unique<LibXMLParser>(client, allowComments);
#else
- return std::make_unique<ExpatParser>(client);
+ return std::make_unique<ExpatParser>(client, allowComments);
#endif
}
diff --git a/Swiften/Parser/PlatformXMLParserFactory.h b/Swiften/Parser/PlatformXMLParserFactory.h
index fa3ca19..d72a513 100644
--- a/Swiften/Parser/PlatformXMLParserFactory.h
+++ b/Swiften/Parser/PlatformXMLParserFactory.h
@@ -14,6 +14,6 @@ namespace Swift {
public:
PlatformXMLParserFactory();
- virtual std::unique_ptr<XMLParser> createXMLParser(XMLParserClient*);
+ virtual std::unique_ptr<XMLParser> createXMLParser(XMLParserClient*, bool allowComments = false);
};
}
diff --git a/Swiften/Parser/PresenceParser.cpp b/Swiften/Parser/PresenceParser.cpp
index 0235a12..f73e9d8 100644
--- a/Swiften/Parser/PresenceParser.cpp
+++ b/Swiften/Parser/PresenceParser.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.
*/
@@ -41,7 +41,7 @@ void PresenceParser::handleStanzaAttributes(const AttributeMap& attributes) {
getStanzaGeneric()->setType(Presence::Error);
}
else {
- SWIFT_LOG(error) << "Unknown Presence type: " << *type << std::endl;
+ SWIFT_LOG(error) << "Unknown Presence type: " << *type;
getStanzaGeneric()->setType(Presence::Available);
}
}
diff --git a/Swiften/Parser/StreamErrorParser.cpp b/Swiften/Parser/StreamErrorParser.cpp
index 64e0681..e89af58 100644
--- a/Swiften/Parser/StreamErrorParser.cpp
+++ b/Swiften/Parser/StreamErrorParser.cpp
@@ -48,9 +48,6 @@ void StreamErrorParser::handleEndElement(const std::string& element, const std::
else if(element == "invalid-from") {
getElementGeneric()->setType(StreamError::InvalidFrom);
}
- else if(element == "invalid-id") {
- getElementGeneric()->setType(StreamError::InvalidID);
- }
else if(element == "invalid-namespace") {
getElementGeneric()->setType(StreamError::InvalidNamespace);
}
@@ -90,6 +87,9 @@ void StreamErrorParser::handleEndElement(const std::string& element, const std::
else if(element == "unsupported-encoding") {
getElementGeneric()->setType(StreamError::UnsupportedEncoding);
}
+ else if(element == "unsupported-feature") {
+ getElementGeneric()->setType(StreamError::UnsupportedFeature);
+ }
else if(element == "unsupported-stanza-type") {
getElementGeneric()->setType(StreamError::UnsupportedStanzaType);
}
diff --git a/Swiften/Parser/UnitTest/AttributeMapTest.cpp b/Swiften/Parser/UnitTest/AttributeMapTest.cpp
index 4529eac..d9335c1 100644
--- a/Swiften/Parser/UnitTest/AttributeMapTest.cpp
+++ b/Swiften/Parser/UnitTest/AttributeMapTest.cpp
@@ -15,6 +15,7 @@ class AttributeMapTest : public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(AttributeMapTest);
CPPUNIT_TEST(testGetAttribute_Namespaced);
+ CPPUNIT_TEST(testGetAttribute_Namespaced_Prefix);
CPPUNIT_TEST(testGetBoolAttribute_True);
CPPUNIT_TEST(testGetBoolAttribute_1);
CPPUNIT_TEST(testGetBoolAttribute_False);
@@ -34,6 +35,22 @@ class AttributeMapTest : public CppUnit::TestFixture
CPPUNIT_ASSERT_EQUAL(std::string("en"), testling.getAttribute("lang", "http://www.w3.org/XML/1998/namespace"));
}
+ void testGetAttribute_Namespaced_Prefix() {
+ AttributeMap testling;
+ testling.addAttribute("lang", "", "prefix", "nl");
+ testling.addAttribute("lang", "http://www.w3.org/XML/1998/namespace", "prefix", "en");
+ testling.addAttribute("lang", "", "prefix", "fr");
+
+ CPPUNIT_ASSERT_EQUAL(std::string("en"), testling.getAttribute("lang", "http://www.w3.org/XML/1998/namespace"));
+ const auto& entries = testling.getEntries();
+ auto it = std::find_if(entries.begin(), entries.end(), [](const AttributeMap::Entry& e) {
+ return e.getValue() == "en";
+ });
+ const bool found = it != entries.end();
+ CPPUNIT_ASSERT_EQUAL(true, found);
+ CPPUNIT_ASSERT_EQUAL(std::string("prefix"), it->getAttribute().getPrefix());
+ }
+
void testGetBoolAttribute_True() {
AttributeMap testling;
testling.addAttribute("foo", "", "true");
diff --git a/Swiften/Parser/UnitTest/XMLParserTest.cpp b/Swiften/Parser/UnitTest/XMLParserTest.cpp
index 9e9012b..89229c9 100644
--- a/Swiften/Parser/UnitTest/XMLParserTest.cpp
+++ b/Swiften/Parser/UnitTest/XMLParserTest.cpp
@@ -6,6 +6,7 @@
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
+#include <unordered_map>
#include <vector>
#include <string>
@@ -34,10 +35,17 @@ class XMLParserTest : public CppUnit::TestFixture {
CPPUNIT_TEST(testParse_WhitespaceInAttribute);
CPPUNIT_TEST(testParse_AttributeWithoutNamespace);
CPPUNIT_TEST(testParse_AttributeWithNamespace);
+ CPPUNIT_TEST(testParse_AttributeWithNamespaceNoPrefix);
CPPUNIT_TEST(testParse_BillionLaughs);
CPPUNIT_TEST(testParse_InternalEntity);
//CPPUNIT_TEST(testParse_UndefinedPrefix);
//CPPUNIT_TEST(testParse_UndefinedAttributePrefix);
+ CPPUNIT_TEST(testParse_AllowCommentsInXML);
+ CPPUNIT_TEST(testParse_DisallowCommentsInXML);
+ CPPUNIT_TEST(testParse_Doctype);
+ CPPUNIT_TEST(testParse_ProcessingInstructions);
+ CPPUNIT_TEST(testParse_ProcessingPrefixedElement);
+ CPPUNIT_TEST(testParse_InvalidlyEncodedInput);
CPPUNIT_TEST_SUITE_END();
public:
@@ -61,6 +69,9 @@ class XMLParserTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[1].data);
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), client_.events[1].attributes.getEntries().size());
CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[1].ns);
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[1].namespaces.size());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[1].namespaces.count(""));
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[1].namespaces[""]);
CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[2].type);
CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[2].data);
@@ -85,10 +96,13 @@ class XMLParserTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(std::string("query"), client_.events[0].data);
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), client_.events[0].attributes.getEntries().size());
CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[0].ns);
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].namespaces.size());
+ CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[0].namespaces[""]);
CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
CPPUNIT_ASSERT_EQUAL(std::string("name"), client_.events[1].data);
CPPUNIT_ASSERT_EQUAL(std::string("jabber:iq:version"), client_.events[1].ns);
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), client_.events[1].namespaces.size());
CPPUNIT_ASSERT_EQUAL(Client::CharacterData, client_.events[2].type);
CPPUNIT_ASSERT_EQUAL(std::string("Swift"), client_.events[2].data);
@@ -161,6 +175,8 @@ class XMLParserTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
CPPUNIT_ASSERT_EQUAL(std::string("x"), client_.events[0].data);
CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[0].ns);
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].namespaces.size());
+ CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[0].namespaces["p"]);
CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
CPPUNIT_ASSERT_EQUAL(std::string("y"), client_.events[1].data);
@@ -176,7 +192,7 @@ class XMLParserTest : public CppUnit::TestFixture {
}
void testParse_UnhandledXML() {
- ParserType testling(&client_);
+ ParserType testling(&client_, true);
CPPUNIT_ASSERT(testling.parse("<iq><!-- Testing --></iq>"));
@@ -251,6 +267,7 @@ class XMLParserTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
CPPUNIT_ASSERT_EQUAL(std::string("attr"), client_.events[0].attributes.getEntries()[0].getAttribute().getName());
CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[0].attributes.getEntries()[0].getAttribute().getNamespace());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[0].attributes.getEntries()[0].getAttribute().getPrefix());
}
void testParse_AttributeWithNamespace() {
@@ -262,6 +279,25 @@ class XMLParserTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
CPPUNIT_ASSERT_EQUAL(std::string("attr"), client_.events[0].attributes.getEntries()[0].getAttribute().getName());
CPPUNIT_ASSERT_EQUAL(std::string("http://swift.im/f"), client_.events[0].attributes.getEntries()[0].getAttribute().getNamespace());
+ CPPUNIT_ASSERT_EQUAL(std::string("f"), client_.events[0].attributes.getEntries()[0].getAttribute().getPrefix());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), client_.events[0].namespaces.size());
+ CPPUNIT_ASSERT_EQUAL(std::string("http://swift.im"), client_.events[0].namespaces[""]);
+ CPPUNIT_ASSERT_EQUAL(std::string("http://swift.im/f"), client_.events[0].namespaces["f"]);
+ }
+
+ void testParse_AttributeWithNamespaceNoPrefix() {
+ ParserType testling(&client_);
+
+ CPPUNIT_ASSERT(testling.parse(
+ "<query xmlns='http://swift.im' xmlns:f='http://swift.im/f' attr='3'/>"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
+ CPPUNIT_ASSERT_EQUAL(std::string("attr"), client_.events[0].attributes.getEntries()[0].getAttribute().getName());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[0].attributes.getEntries()[0].getAttribute().getNamespace());
+ CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[0].attributes.getEntries()[0].getAttribute().getPrefix());
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), client_.events[0].namespaces.size());
+ CPPUNIT_ASSERT_EQUAL(std::string("http://swift.im"), client_.events[0].namespaces[""]);
+ CPPUNIT_ASSERT_EQUAL(std::string("http://swift.im/f"), client_.events[0].namespaces["f"]);
}
void testParse_BillionLaughs() {
@@ -301,6 +337,7 @@ class XMLParserTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
CPPUNIT_ASSERT_EQUAL(std::string("foo:bar"), client_.events[0].data);
CPPUNIT_ASSERT_EQUAL(std::string(""), client_.events[0].ns);
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(0), client_.events[0].namespaces.size());
CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[1].type);
CPPUNIT_ASSERT_EQUAL(std::string("bla"), client_.events[1].data);
@@ -318,48 +355,136 @@ class XMLParserTest : public CppUnit::TestFixture {
void testParse_UndefinedAttributePrefix() {
ParserType testling(&client_);
- CPPUNIT_ASSERT(testling.parse(
- "<foo bar:baz='bla'/>"));
+ CPPUNIT_ASSERT(testling.parse("<foo bar:baz='bla'/>"));
CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), client_.events[0].attributes.getEntries().size());
CPPUNIT_ASSERT_EQUAL(std::string("bar:baz"), client_.events[0].attributes.getEntries()[0].getAttribute().getName());
}
+ void testParse_AllowCommentsInXML() {
+ ParserType testling(&client_, true);
+
+ CPPUNIT_ASSERT(testling.parse("<message><!-- Some More Comments Testing --></message>"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), client_.events.size());
+
+ CPPUNIT_ASSERT_EQUAL(Client::StartElement, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), client_.events[0].data);
+
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), client_.events[1].data);
+ }
+
+ void testParse_DisallowCommentsInXML() {
+ ParserType testling(&client_);
+
+ CPPUNIT_ASSERT(!testling.parse("<message><!-- Some More Comments Testing --></message>"));
+ }
+
+ void testParse_Doctype() {
+ ParserType testling(&client_);
+
+ CPPUNIT_ASSERT(!testling.parse("<!DOCTYPE greeting SYSTEM \"hello.dtd\">"));
+ }
+
+ void testParse_ProcessingInstructions() {
+ ParserType testling(&client_);
+
+ CPPUNIT_ASSERT(!testling.parse("<?xml-stylesheet type=\"text/xsl\" href=\"Sample.xsl\"?>"));
+ }
+
+ void testParse_ProcessingPrefixedElement() {
+ client_.testingStartElementPrefix = true;
+ ParserType testling(&client_);
+
+ CPPUNIT_ASSERT(testling.parse("<prefix:message xmlns='uri' xmlns:prefix='uriPrefix'/>"));
+
+ CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(2), client_.events.size());
+
+ CPPUNIT_ASSERT_EQUAL(Client::StartElementPrefix, client_.events[0].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), client_.events[0].data);
+ CPPUNIT_ASSERT_EQUAL(std::string("uriPrefix"), client_.events[0].ns);
+ CPPUNIT_ASSERT_EQUAL(std::string("prefix"), client_.events[0].prefix);
+
+ CPPUNIT_ASSERT_EQUAL(Client::EndElement, client_.events[1].type);
+ CPPUNIT_ASSERT_EQUAL(std::string("message"), client_.events[1].data);
+ CPPUNIT_ASSERT_EQUAL(std::string("uriPrefix"), client_.events[1].ns);
+ }
+
+ void testParse_InvalidlyEncodedInput() {
+ ParserType testling(&client_);
+
+ // The following input was generated by a fuzzer, and triggered a crash in the LibXML2 parser because
+ // some types of error (buffer I/O errors, for instance) will not update the error in the parser context,
+ // and the code used to rely on that error always being set if parsing failed.
+ // This particular input will trick the parser into believing the encoding is UTF-16LE, which eventually will lead
+ // to two invalid encodings, followed by an I/O error. The latter will end parsing without updating the
+ // error in the parsing context, which used to trigger a crash.
+ testling.parse(std::string("<\0?\0\x80q type='get' id='aab9a'<<query xmlns='jabber:iq:roster'/>\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9b\x9br:i><quq:private'><storage xml s='s'\x00\x10</query></iq>", 271));
+ testling.parse("<iq type='get'\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e\x9e to='ad5d8d2b25' ext='ca cs min@wonderland.t' id='aabda'><vCard xmlnr='vcard-temp'/>O/iq>");
+ testling.parse("<\xff\xff\xff\x7fype:'get' to='won\x84" "erland.lit' id='aabea'><tuery xmlns='\xd8Vtp://jabber.org/p\x88ot\x8b" "col/disco#info'/>abber.org/protocol/disco#Nnfo'/></iq>");
+ }
+
private:
class Client : public XMLParserClient {
public:
- enum Type { StartElement, EndElement, CharacterData };
+ using NamespaceMap = std::unordered_map<std::string /* prefix */, std::string /* uri */>;
+ enum Type { StartElement, StartElementPrefix, EndElement, CharacterData, NamespaceDefined };
struct Event {
Event(
Type type,
const std::string& data,
const std::string& ns,
- const AttributeMap& attributes)
- : type(type), data(data), ns(ns), attributes(attributes) {}
+ const std::string& prefix,
+ const AttributeMap& attributes,
+ NamespaceMap namespaces)
+ : type(type), data(data), ns(ns), prefix(prefix), attributes(attributes), namespaces(std::move(namespaces)) {}
+ Event(
+ Type type,
+ const std::string& data,
+ const std::string& ns,
+ const AttributeMap& attributes,
+ NamespaceMap namespaces = {})
+ : Event(type, data, ns, {}, attributes, std::move(namespaces)) {}
Event(Type type, const std::string& data, const std::string& ns = std::string())
- : type(type), data(data), ns(ns) {}
+ : Event(type, data, ns, "", AttributeMap(), NamespaceMap()) {}
Type type;
std::string data;
std::string ns;
+ std::string prefix;
AttributeMap attributes;
+ NamespaceMap namespaces;
};
Client() {}
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) {
- events.push_back(Event(StartElement, element, ns, attributes));
+ void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) override {
+ if (testingStartElementPrefix) return;
+ events.push_back(Event(StartElement, element, ns, attributes, std::move(namespaces_)));
+ }
+
+ void handleStartElementPrefix(const std::string& prefix, const std::string& uri, const std::string& name, const AttributeMap&) override {
+ if (!testingStartElementPrefix) return;
+ events.push_back(Event(StartElementPrefix, name, uri, prefix, AttributeMap(), NamespaceMap()));
}
- virtual void handleEndElement(const std::string& element, const std::string& ns) {
+ void handleEndElement(const std::string& element, const std::string& ns) override {
events.push_back(Event(EndElement, element, ns));
}
- virtual void handleCharacterData(const std::string& data) {
+ void handleCharacterData(const std::string& data) override {
events.push_back(Event(CharacterData, data));
}
+ void handleNamespaceDeclaration(const std::string& prefix, const std::string& uri) override {
+ namespaces_[prefix] = uri;
+ }
+
std::vector<Event> events;
+ bool testingStartElementPrefix = false;
+ private:
+ NamespaceMap namespaces_;
} client_;
};
diff --git a/Swiften/Parser/XMLParser.cpp b/Swiften/Parser/XMLParser.cpp
index 8e92fe4..8a0799f 100644
--- a/Swiften/Parser/XMLParser.cpp
+++ b/Swiften/Parser/XMLParser.cpp
@@ -8,7 +8,7 @@
namespace Swift {
-XMLParser::XMLParser(XMLParserClient* client) : client_(client) {
+XMLParser::XMLParser(XMLParserClient* client, bool allowComments) : client_(client), allowComments_(allowComments){
}
XMLParser::~XMLParser() {
diff --git a/Swiften/Parser/XMLParser.h b/Swiften/Parser/XMLParser.h
index ad79b2d..3b09d22 100644
--- a/Swiften/Parser/XMLParser.h
+++ b/Swiften/Parser/XMLParser.h
@@ -15,7 +15,7 @@ namespace Swift {
class SWIFTEN_API XMLParser {
public:
- XMLParser(XMLParserClient* client);
+ XMLParser(XMLParserClient* client, bool allowComments = false);
virtual ~XMLParser();
virtual bool parse(const std::string& data, bool finalData = false) = 0;
@@ -24,7 +24,12 @@ namespace Swift {
return client_;
}
+ bool allowsComments() const {
+ return allowComments_;
+ }
+
private:
XMLParserClient* client_;
+ const bool allowComments_ = false;
};
}
diff --git a/Swiften/Parser/XMLParserClient.cpp b/Swiften/Parser/XMLParserClient.cpp
index 6dc6db6..6698900 100644
--- a/Swiften/Parser/XMLParserClient.cpp
+++ b/Swiften/Parser/XMLParserClient.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -11,5 +11,14 @@ namespace Swift {
XMLParserClient::~XMLParserClient() {
}
+void XMLParserClient::handleStartElement(const std::string&, const std::string&, const AttributeMap&) {
+}
+
+void XMLParserClient::handleStartElementPrefix(const std::string&, const std::string&, const std::string&, const AttributeMap&) {
+}
+
+void XMLParserClient::handleNamespaceDeclaration(const std::string&, const std::string&) {
+}
+
}
diff --git a/Swiften/Parser/XMLParserClient.h b/Swiften/Parser/XMLParserClient.h
index e4346f6..2f0bc9e 100644
--- a/Swiften/Parser/XMLParserClient.h
+++ b/Swiften/Parser/XMLParserClient.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -14,8 +14,22 @@ namespace Swift {
public:
virtual ~XMLParserClient();
- virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes) = 0;
+ /**
+ * Client will have to implement only one of the following methods depending on whether
+ * he is interested in processing the element prefix or not.
+ */
+ virtual void handleStartElement(const std::string& element, const std::string& ns, const AttributeMap& attributes);
+ virtual void handleStartElementPrefix(const std::string& prefix, const std::string& uri, const std::string& element, const AttributeMap& attributes);
+
virtual void handleEndElement(const std::string& element, const std::string& ns) = 0;
virtual void handleCharacterData(const std::string& data) = 0;
+
+ /**
+ * Signal that a namespace prefix has been declared
+ * This callback might be called multiple times for a single element,
+ * and will trigger before the corresponding \ref handleStartElement
+ * is called.
+ */
+ virtual void handleNamespaceDeclaration(const std::string& prefix, const std::string& uri);
};
}
diff --git a/Swiften/Parser/XMLParserFactory.h b/Swiften/Parser/XMLParserFactory.h
index 595512b..ae3c90e 100644
--- a/Swiften/Parser/XMLParserFactory.h
+++ b/Swiften/Parser/XMLParserFactory.h
@@ -18,6 +18,6 @@ namespace Swift {
public:
virtual ~XMLParserFactory();
- virtual std::unique_ptr<XMLParser> createXMLParser(XMLParserClient*) = 0;
+ virtual std::unique_ptr<XMLParser> createXMLParser(XMLParserClient*, bool allowComments = false) = 0;
};
}
diff --git a/Swiften/QA/TLSTest/CertificateTest.cpp b/Swiften/QA/TLSTest/CertificateTest.cpp
index 02ec0f8..463ef9e 100644
--- a/Swiften/QA/TLSTest/CertificateTest.cpp
+++ b/Swiften/QA/TLSTest/CertificateTest.cpp
@@ -15,6 +15,9 @@
#include <Swiften/Base/ByteArray.h>
#include <Swiften/TLS/CertificateFactory.h>
+#include <Swiften/TLS/TLSContext.h>
+#include <Swiften/TLS/PlatformTLSFactories.h>
+#include <Swiften/TLS/TLSContextFactory.h>
#include <SwifTools/Application/PlatformApplicationPathProvider.h>
@@ -30,13 +33,21 @@ class CertificateTest : public CppUnit::TestFixture {
CPPUNIT_TEST(testGetSRVNames);
CPPUNIT_TEST(testGetDNSNames);
CPPUNIT_TEST(testGetXMPPAddresses);
+ CPPUNIT_TEST(testCreateCertificateChain);
+ CPPUNIT_TEST(testCreateTlsContext);
+ CPPUNIT_TEST(testCreateTlsContextDisableSystemTAs);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() {
pathProvider = std::make_unique<PlatformApplicationPathProvider>("FileReadBytestreamTest");
readByteArrayFromFile(certificateData, (pathProvider->getExecutableDir() / "jabber_org.crt"));
+ readByteArrayFromFile(chainData, (pathProvider->getExecutableDir() / "certificateChain.pem"));
+ readByteArrayFromFile(keyData, (pathProvider->getExecutableDir() / "privateKey.pem"));
certificateFactory = std::unique_ptr<CertificateFactory>(new CERTIFICATE_FACTORY());
+
+ PlatformTLSFactories* tlsFactories_ = new PlatformTLSFactories();
+ tlsContextFactory_ = tlsFactories_->getTLSContextFactory();
}
void testConstructFromDER() {
@@ -88,10 +99,68 @@ class CertificateTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT_EQUAL(std::string("*.jabber.org"), testling->getXMPPAddresses()[0]);
}
+ void testCreateCertificateChain() {
+ // The input chain contains a 2-certificate chain:
+ // the first certificate has:
+ // a subject of "O=messaging,CN=Mixer Messaging Configuration,CN=badger.isode.net"
+ // an issuer of "O=messaging, CN=New Messaging CA"
+ // the second certificate has:
+ // a subject of "O=messaging, CN=New Messaging CA"
+ // an issuer of "O=messaging, CN=New Messaging CA"
+ // i.e. it is a self-signed certificate
+ std::vector<std::shared_ptr<Certificate>> chain = certificateFactory->createCertificateChain(chainData);
+ CPPUNIT_ASSERT_EQUAL(2,static_cast<int>(chain.size()));
+ CPPUNIT_ASSERT_EQUAL(std::string("Mixer Messaging Configuration"), chain[0]->getCommonNames()[0]);
+ CPPUNIT_ASSERT_EQUAL(std::string("badger.isode.net"), chain[0]->getCommonNames()[1]);
+ CPPUNIT_ASSERT_EQUAL(std::string("New Messaging CA"), chain[1]->getCommonNames()[0]);
+ }
+
+ void testCreateTlsContext() {
+ // Create 2-certificate chain as in previous test
+ std::vector<std::shared_ptr<Certificate>> chain = certificateFactory->createCertificateChain(chainData);
+ CPPUNIT_ASSERT_EQUAL(2,static_cast<int>(chain.size()));
+
+ // Load private key from string
+ PrivateKey::ref key = certificateFactory->createPrivateKey(Swift::createSafeByteArray(keyData));
+ CPPUNIT_ASSERT(key);
+
+ const TLSOptions options;
+ auto context = tlsContextFactory_->createTLSContext(options, TLSContext::Mode::Server);
+ CPPUNIT_ASSERT(context);
+
+ context->setCertificateChain(chain);
+ context->setPrivateKey(key);
+ }
+
+ /**
+ * This test does not actually verify that use of system TAs has been disabled, it just provides
+ * a convenient mechanism for testing via a debugger.
+ **/
+ void testCreateTlsContextDisableSystemTAs() {
+ // Create 2-certificate chain as in previous test
+ std::vector<std::shared_ptr<Certificate>> chain = certificateFactory->createCertificateChain(chainData);
+ CPPUNIT_ASSERT_EQUAL(2,static_cast<int>(chain.size()));
+
+ // Load private key from string
+ PrivateKey::ref key = certificateFactory->createPrivateKey(Swift::createSafeByteArray(keyData));
+ CPPUNIT_ASSERT(key);
+
+ // Turn off use of system TAs
+ TLSOptions options;
+ options.ignoreSystemTrustAnchors = true;
+ auto context = tlsContextFactory_->createTLSContext(options, TLSContext::Mode::Server);
+ CPPUNIT_ASSERT(context);
+
+ context->setCertificateChain(chain);
+ context->setPrivateKey(key);
+ }
private:
std::unique_ptr<PlatformApplicationPathProvider> pathProvider;
ByteArray certificateData;
+ ByteArray chainData;
+ ByteArray keyData;
std::unique_ptr<CertificateFactory> certificateFactory;
+ TLSContextFactory* tlsContextFactory_;
};
#ifdef HAVE_OPENSSL
diff --git a/Swiften/QA/TLSTest/certificateChain.pem b/Swiften/QA/TLSTest/certificateChain.pem
new file mode 100644
index 0000000..cb3c0fb
--- /dev/null
+++ b/Swiften/QA/TLSTest/certificateChain.pem
@@ -0,0 +1,49 @@
+-----BEGIN CERTIFICATE-----
+MIIFFTCCA/2gAwIBAgIKXmMION+1bnZpIzANBgkqhkiG9w0BAQsFADAvMRIwEAYD
+VQQKEwltZXNzYWdpbmcxGTAXBgNVBAMTEE5ldyBNZXNzYWdpbmcgQ0EwHhcNMTkw
+NzI5MTAxMjMxWhcNMjAwNzI5MTAxMjMxWjBXMRIwEAYDVQQKEwltZXNzYWdpbmcx
+JjAkBgNVBAMTHU1peGVyIE1lc3NhZ2luZyBDb25maWd1cmF0aW9uMRkwFwYDVQQD
+ExBiYWRnZXIuaXNvZGUubmV0MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKC
+AYEAt42TMYe9oO4K6XmvST4kiy4cG+nmVDCtZRfAfF/A+1GQXTZ8OfLbPF5noLIF
+f1Jj6fBDA2HiKoLQWfNnIklNEzgPbOREuAuCe660sW1JzJFr5O5qYyf6bHKkYmRr
+CGHJ3G5kkXZOW3MhczPNHrTIUSL7lYLMZAcyWStkhgBy7lBuYtgDEXbdRH8OGgly
+XC39AAU93y7ynw6W3SorU6h9cwvS0Ho8KVemCXoE38WLeSrIw1ks+Kf1YQopg9O3
+2SkXp6Z9elG5Wk5Rh0L0H2XHnAvmodr9TW6rtrPkJZfLL+NfcnGtI6QKnvL8EhYG
+d+XiPOV8jyGAFRC1Be72wlF29Rw20zdoD3kAdeqBLWfL8H9mnQpebEIDj8Lmahub
++W4uuUqCG8NuY43lGJzJni9CFWvhD7ss1yVGz84zqRHu5iXNDncWH2luJT1gXvFW
+6mxcfe+AwSiZ8PrhDQZBfTyx7ob4Ozdc1d59XTPyckj2msnCo2ayg+jKaViDd4vz
+nNwhAgMBAAGjggGJMIIBhTAbBgNVHREEFDASghBiYWRnZXIuaXNvZGUubmV0MA4G
+A1UdDwEB/wQEAwIF4DAMBgNVHRMBAf8EAjAAMHQGA1UdHwRtMGswaaBnoGWGY2xk
+YXA6Ly9kaWFib2xvLmlzb2RlLm5ldDoxOTM4OS9jbj1OZXclMjBNZXNzYWdpbmcl
+MjBDQSxvPW1lc3NhZ2luZz9jZXJ0aWZpY2F0ZVJldm9jYXRpb25MaXN0O2JpbmFy
+eTCBkQYIKwYBBQUHAQEEgYQwgYEwfwYIKwYBBQUHMAKGc2xkYXA6Ly9kaWFib2xv
+Lmlzb2RlLm5ldDoxOTM4OS9jbj1OZXclMjBNZXNzYWdpbmclMjBDQSxvPW1lc3Nh
+Z2luZz9jQUNlcnRpZmljYXRlO2JpbmFyeSxjcm9zc0NlcnRpZmljYXRlUGFpcjti
+aW5hcnkwHQYDVR0OBBYEFFjf69BczlDoKiSBSvxCr9sy0OJ2MB8GA1UdIwQYMBaA
+FJvoU0Lwg8vVCEmEMoKy29zFo/Y7MA0GCSqGSIb3DQEBCwUAA4IBAQCS4zLVH98S
+Cl4gsmTkxM+lBsdzQ18ymA6p9ZRXGmJ405C9rN7um9XnbWwOHO6ach7zie2GxWLp
+KOYKjX/5Pjt7mPwG8eKepPAxDenzKw5TocjscR9VxBsym0oEkWHPQG+xSqySQGUw
+/5QoGy6v06yE8CZ7BKHPh91Jy7IjIDBxWaEtTAPyuH4i4DnsmA0/xSrJ7ez6g399
+YgqDnBInC63bYv5IDD1CmEr/0boBWpsOf50OC6JVhaPLAldwTAxLSOMBJ4q4onXC
+ZqDHY3EMRtwYEffNg9ZorXJwLmU3Lq/R3B9lC22XNPDFj/bZ5RpwVFtuN5HfeZzO
+aPbNoa0Nf+QB
+-----END CERTIFICATE-----
+-----BEGIN CERTIFICATE-----
+MIIDJDCCAgygAwIBAgIKSm7KkUZOigMk9zANBgkqhkiG9w0BAQsFADAvMRIwEAYD
+VQQKEwltZXNzYWdpbmcxGTAXBgNVBAMTEE5ldyBNZXNzYWdpbmcgQ0EwHhcNMTYw
+MTI2MTU1MTU2WhcNMjYwMTI2MTU1MTU2WjAvMRIwEAYDVQQKEwltZXNzYWdpbmcx
+GTAXBgNVBAMTEE5ldyBNZXNzYWdpbmcgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IB
+DwAwggEKAoIBAQDgcuX1s8EvO8GDHx7vSW9oeDnLUBx5E48Vb2qcJVc34ik1j6ZV
+d8/+tzmyy/BskFbaOJ0KD5XYOoI8TJtu28lASWZj1vAEZkfrDdBbKeb1BQhShMt2
+ICgzp7l4ubwd6rqCGHpD/f12RVhSlU3y6TniaK62a9RwJOpL/wvnCcJLPjaTw8om
+EY62EyUP+FymUbo3Rb3aWLM7avHl1/32pyzUgRzvZR63hlMHnlE5Sgc84j9KMwJH
+k+mCyXIGPc+yhL33ljR63Eoiqynyk0HPU6pWai1WKuSv6zMDPwnNaJA3VpLNUHsd
+eVe1GyOmPFePnhRPZYfC+Dk8lxDUmZfNFKZlAgMBAAGjQjBAMA4GA1UdDwEB/wQE
+AwIBBjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBSb6FNC8IPL1QhJhDKCstvc
+xaP2OzANBgkqhkiG9w0BAQsFAAOCAQEApgA5oupwTS2Ylt9mhS/TDX9wzR0DqnC5
+t9skgU9B/1MnzgqEMKGmuhRBiqDyr0jsPegBFI/CpTdIpakpSUrIvBTZADzkrkI+
+3k2jnpEv0vodaFIHQonDysq5h4bXsCSdSprdhiUa1GKFtnJ92Ro/2Uaw5UcqFPCg
+7kj7RmRVlAIynUAT81cefQww0HBFPN9SdBEpp6YP4P1u1x8GV0Bfq93r4G5jkiHN
+dA6xejk7RZK4mTH+K2aFpWoHCqMr7RAzV5UiXis4cFAmtv+5K/G7eazNx0Y+ODo4
+fweh+xW+dOXuP1lzW4DzwhEf/8tgFgI0jIvscPgdgHY7t9SQRJPYQQ==
+-----END CERTIFICATE-----
diff --git a/Swiften/QA/TLSTest/privateKey.pem b/Swiften/QA/TLSTest/privateKey.pem
new file mode 100644
index 0000000..5769000
--- /dev/null
+++ b/Swiften/QA/TLSTest/privateKey.pem
@@ -0,0 +1,40 @@
+-----BEGIN PRIVATE KEY-----
+MIIG/wIBADANBgkqhkiG9w0BAQEFAASCBukwggblAgEAAoIBgQDu1QdEBrcWj+D/
+rkmh++QSu2f0qlJ6Re8dEBtbqpxLiyYZ5IeaLts9szXabfSTchdJr/d0IyHfHQFS
+MGXDphKRaNnV5r//XuojUtorPyGe0DnZR2mp8S9adD7WxNjQLSQabr8PPPW8jrTx
+eJyIvYToLs9lx1IIDcr/3ZTuhBe2FK3Q173M5GF36Jb4yKWLPIfJ6auZjO5G9LZF
+3o2vVWxfc7ESnXvf3sAcWQPR08/ud0vLa3W3A8dC0XGk4BbE32cxvSuzWPHZd257
+HiHIW5pKLZXSMTu7fVNzBzDlo8BYQ5kad1ic+hhyIHBwTUO0Hz3EYP+9FG3TNG84
+65K9EeN3/Qw2P9468GHWAXqlzKFiIGikxYHGwvGd0CdegHtZ/TwIgVvpIDp6XB6U
+ez/TYPEiMCqX8TCIQi8FU3obEouMoPMHKM8vzQdSItZtPn6gD16M4xKdMm6fbvCD
+1okdcrWQnZo72pp8cfpS87KhP5z1ec9B/Wqysh4nrO35v8LXH60CAwEAAQKCAYEA
+jPDUJ9XaqAriWaBtvZTbpB5KG72DjLrGgB0oN/E36PDF3FPbniZ2pTOj3TI0OesD
+SS351uSAsZz5UZpUA6B2pq78llllBnvpqkzTiN/ppEH3UXzuIya8riGZj758wGVT
+P/II+CIeVlbU+wcVQTCuRSKSq9pzU2NoX5RQtmznXUFYzbzzOf2wc0WkCk7GOqPO
+8l3eMXBUkTUKd7L9Y/ICUVYBsh2To6pdLp1tPp9DvtNRvEq/HfCx34GgEg9YAHhg
+1rcPhh71M+TLYHznl5r/Jm1kIVrP3zyr1Bm5DDgZLE3GTN/oFumgXQyFCPyslup1
+gdZzS6W+fbeKxoPzjPOhzHVUxVZ/yqJH1xa1gs4ECQ4QXxdnr7yY1H5k5S8dabO5
+bEvXP+tH95HcAtAbvoRt+NC+xIJ39d6X7X2c4TPLoMIxDxmbEOCi9sg+4Ws+7E2s
+a/01fTZFT+lzuGBdp9Zz/tltDrwfYD0V+Q7qO0o/nJPINI+alAWlqQia00ZyZr4V
+AoHBAPxwCls99/LUzY7IJc0TV3ukk3sFi3rt58u8BE4+RaCtmgPMDj1l+EnaY9RW
+IOj91ECZ8+a23elNPZOkXKuYuJmJIpjOogOMM8r+Q4WF87xoRcdcjPh+PBat66HZ
++8mbm0VQ98cjxs0/kTRRayzz7UG9Onf1PhFfnw55sbMGItVssRDi9lRZJdSRU+CC
+qyAt8TUEH0lo+8AKbRn7xW4VHiD0hmLKDi4F713QLCPgmNlPQ/C60FTIRYS18gzK
+ARhuzwKBwQDyM9YiiFFQ3irGKtbj9W3bDHNmMl9YOHMYVXJAvh83Zcp80qRsShtw
+n3mV3vcVI+KNeZtKFUrJIYNTspNBP/w8U4lGGW+7tAt0dd0WY9m3ygnZg0GOHoaC
+uUusGicZR7FgbYlJzCiRhFhWcFyh0VOrm/k7OjznAvwfWbRKrlLvQdrWrLj7dyN3
+8n9lArq9ZxXJLpBXDUJ1R+F+hPIIIRKeYF2ULUFNE0U9Pj7SVTT7L7jPMWKnrVJh
+U4/hVAEHyMMCgcB4hCTtmpAdZmscl4E0ft9tMA0Y1nTYo2veYEzN7fzf0QGOfoTt
+2xjGaXTvko7zrPsAPH+szfDzyOR08Cst4SOAaXAS89N1TiIL74fc3y6V7FIj85N5
+rwqQ6UdtZdxHS/q9BQLGF9Z5drej+proQywqDmUzj+mp8bTF/GNRzMQkkFeYcEKZ
+0lW1PgyFStzX6BcX8HffXDeUX2Xm2cRP4dUYdqUR1NUgM8UrTI9GMZvHY4hUDVwY
+neRSj2qXoHkVaRECgcEArilkM9S+VF5Nd85aU/WqFzeuy7AxK2j8KmVXEQMlw1oo
+7vUxUsU/Ug77CTAZkFQLlxv49J629kZo/wiMJwFxyZdwQL4NwHXJPud6IZ2Pcz+P
+MZ/WxfFhXCMOLSVpNB5/iA18CVsLWQhH1XBay+mQNvijkVlhbeSRk6GXqZQNAwrh
+6Divk/Opx5jSzrnVulikK9SV6mMYhOk5VxcWS44sq0I0SFb6fAf9Y/qchfbLcExy
+olqqzFQvxtilv6v+SbCtAoHBAOXPUQ7VVuQZo4HA+CaQRYgQjGMxo4jeGiqrUAaX
+b+MpUjU7VxiSrfH3wFxCuMfW7dfQJKp7BAG8PCNzP1eW3+LhPkRSPAT0nwk/bQ5E
+N/n6NBqwsJFoTqueS0qDVdPichwKGvnIrraHSVeMeHZNv+TQdMjmTJ5AfBNCal9b
+7EPTFQO0Tj4GAB77fVRzewyVB+qXccoD2Gts9aWbY9FVGyhkvRenL7CcbgrzLZvt
+php/1crfbWtZ/3Nwz6L8LEdZHA==
+-----END PRIVATE KEY-----
diff --git a/Swiften/Roster/XMPPRosterController.cpp b/Swiften/Roster/XMPPRosterController.cpp
index 8ee9755..2b98b53 100644
--- a/Swiften/Roster/XMPPRosterController.cpp
+++ b/Swiften/Roster/XMPPRosterController.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.
*/
@@ -66,7 +66,7 @@ void XMPPRosterController::handleRosterReceived(std::shared_ptr<RosterPayload> r
xmppRoster_->addContact(item.getJID(), item.getName(), item.getGroups(), item.getSubscription());
}
else {
- SWIFT_LOG(error) << "Stored invalid roster item" << std::endl;
+ SWIFT_LOG(error) << "Stored invalid roster item";
}
}
}
diff --git a/Swiften/SASL/WindowsAuthentication.cpp b/Swiften/SASL/WindowsAuthentication.cpp
index b86381b..f951fac 100644
--- a/Swiften/SASL/WindowsAuthentication.cpp
+++ b/Swiften/SASL/WindowsAuthentication.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015-2016 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -16,14 +16,14 @@
#define ASSIGN_ERROR(status, errorCode) \
{ \
errorCode = std::make_shared<boost::system::error_code>(status, boost::system::system_category()); \
- SWIFT_LOG(debug) << std::hex << "status: 0x" << status << ": " << errorCode->message() << std::endl; \
+ SWIFT_LOG(debug) << std::hex << "status: 0x" << status << ": " << errorCode->message(); \
}
#define ASSIGN_SEC_ERROR(status, errorCode) \
{ \
if (status == SEC_E_OK) \
{ \
- SWIFT_LOG(debug) << "success" << std::endl; \
+ SWIFT_LOG(debug) << "success"; \
} \
else { \
ASSIGN_ERROR(status, errorCode); \
@@ -46,14 +46,14 @@ std::shared_ptr<boost::system::error_code> getUserNameEx(std::string& userName,
std::size_t position;
userName = convertWStringToString(std::wstring(vecptr(value), length));
- SWIFT_LOG(debug) << "User Name: " << userName << std::endl;
+ SWIFT_LOG(debug) << "User Name: " << userName;
position = userName.find("\\");
clientName = userName.substr(position + 1);
- SWIFT_LOG(debug) << "Client name: " << clientName << std::endl;
+ SWIFT_LOG(debug) << "Client name: " << clientName;
serverName = userName.substr(0, position);
- SWIFT_LOG(debug) << "Server name: " << serverName << std::endl;
+ SWIFT_LOG(debug) << "Server name: " << serverName;
break;
}
@@ -161,7 +161,7 @@ std::shared_ptr<boost::system::error_code> initializeSecurityContext(const boost
}
if ((status == SEC_E_OK) || (status == SEC_I_COMPLETE_AND_CONTINUE) || (status == SEC_I_COMPLETE_NEEDED) || (status == SEC_I_CONTINUE_NEEDED)) {
outputToken = createSafeByteArray (static_cast<unsigned char *>(outputTokenBuffer.pvBuffer), outputTokenBuffer.cbBuffer);
- SWIFT_LOG(debug) << "outputToken.size(): " << outputToken.size() << std::endl;
+ SWIFT_LOG(debug) << "outputToken.size(): " << outputToken.size();
freeContextBuffer(outputTokenBuffer.pvBuffer);
return std::shared_ptr<boost::system::error_code>(); /* success */
@@ -229,7 +229,7 @@ std::shared_ptr<boost::system::error_code> decryptMessage(const PCtxtHandle cont
messageBuffer[1].cbBuffer = 0;
messageBuffer[1].pvBuffer = NULL;
- SWIFT_LOG(debug) << "inputMessage.size(): " << inputMessage.size() << std::endl;
+ SWIFT_LOG(debug) << "inputMessage.size(): " << inputMessage.size();
status = DecryptMessage(
contextHandle,
@@ -239,13 +239,13 @@ std::shared_ptr<boost::system::error_code> decryptMessage(const PCtxtHandle cont
ASSIGN_SEC_ERROR(status, errorCode);
if (status == SEC_E_OK) {
if (qualityOfProtection == SECQOP_WRAP_NO_ENCRYPT) {
- SWIFT_LOG(debug) << "Message was signed only" << std::endl;
+ SWIFT_LOG(debug) << "Message was signed only";
}
else {
- SWIFT_LOG(debug) << "Message was encrypted" << std::endl;
+ SWIFT_LOG(debug) << "Message was encrypted";
}
- SWIFT_LOG(debug) << "messageBuffer[1].cbBuffer: " << messageBuffer[1].cbBuffer << std::endl;
+ SWIFT_LOG(debug) << "messageBuffer[1].cbBuffer: " << messageBuffer[1].cbBuffer;
decrypted = createSafeByteArray (static_cast<unsigned char *>(messageBuffer[1].pvBuffer), messageBuffer[1].cbBuffer);
}
@@ -281,9 +281,9 @@ std::shared_ptr<boost::system::error_code> encryptMessage(const PCtxtHandle cont
messageBuffer[2].cbBuffer = sizes.cbBlockSize;
messageBuffer[2].pvBuffer = vecptr(blockSize);
- SWIFT_LOG(debug) << "sizes.cbSecurityTrailer: " << sizes.cbSecurityTrailer << std::endl;
- SWIFT_LOG(debug) << "inputMessage.size(): " << inputMessage.size() << std::endl;
- SWIFT_LOG(debug) << "sizes.cbBlockSize: " << sizes.cbBlockSize << std::endl;
+ SWIFT_LOG(debug) << "sizes.cbSecurityTrailer: " << sizes.cbSecurityTrailer;
+ SWIFT_LOG(debug) << "inputMessage.size(): " << inputMessage.size();
+ SWIFT_LOG(debug) << "sizes.cbBlockSize: " << sizes.cbBlockSize;
status = EncryptMessage(
contextHandle,
@@ -294,9 +294,9 @@ std::shared_ptr<boost::system::error_code> encryptMessage(const PCtxtHandle cont
if (status == SEC_E_OK) {
unsigned char* pointer;
- SWIFT_LOG(debug) << "messageBuffer[0].cbBuffer: " << messageBuffer[0].cbBuffer << std::endl;
- SWIFT_LOG(debug) << "messageBuffer[1].cbBuffer: " << messageBuffer[1].cbBuffer << std::endl;
- SWIFT_LOG(debug) << "messageBuffer[2].cbBuffer: " << messageBuffer[2].cbBuffer << std::endl;
+ SWIFT_LOG(debug) << "messageBuffer[0].cbBuffer: " << messageBuffer[0].cbBuffer;
+ SWIFT_LOG(debug) << "messageBuffer[1].cbBuffer: " << messageBuffer[1].cbBuffer;
+ SWIFT_LOG(debug) << "messageBuffer[2].cbBuffer: " << messageBuffer[2].cbBuffer;
output.resize(messageBuffer[0].cbBuffer + messageBuffer[1].cbBuffer + messageBuffer[2].cbBuffer);
pointer = vecptr(output);
diff --git a/Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp b/Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp
index aae437f..10e8c89 100644
--- a/Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp
+++ b/Swiften/SASL/WindowsGSSAPIClientAuthenticator.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015-2016 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -44,7 +44,7 @@ WindowsGSSAPIClientAuthenticator::~WindowsGSSAPIClientAuthenticator() {
}
boost::optional<SafeByteArray> WindowsGSSAPIClientAuthenticator::getResponse() const {
- SWIFT_LOG(debug) << "response_.size(): " << response_.size() << std::endl;
+ SWIFT_LOG(debug) << "response_.size(): " << response_.size();
return response_;
}
@@ -56,7 +56,7 @@ bool WindowsGSSAPIClientAuthenticator::setChallenge(const boost::optional<ByteAr
}
else if (step_ == SecurityLayerNegotiation) {
if (!challengeData) {
- SWIFT_LOG(debug) << "Empty message received from the server" << std::endl;
+ SWIFT_LOG(debug) << "Empty message received from the server";
error_ = true;
return false;
}
@@ -68,7 +68,7 @@ bool WindowsGSSAPIClientAuthenticator::setChallenge(const boost::optional<ByteAr
}
if (challenge.size() != 4) {
- SWIFT_LOG(debug) << "Token received from the server of incorrect length: " << challenge.size() << std::endl;
+ SWIFT_LOG(debug) << "Token received from the server of incorrect length: " << challenge.size();
error_ = true;
return false;
}
@@ -77,14 +77,14 @@ bool WindowsGSSAPIClientAuthenticator::setChallenge(const boost::optional<ByteAr
unsigned char serverSecurityLayer = challengePointer[0];
if (serverSecurityLayer == 0) {
- SWIFT_LOG(debug) << "Server supports unknown security layer, assuming no security layer" << std::endl;
+ SWIFT_LOG(debug) << "Server supports unknown security layer, assuming no security layer";
serverSecurityLayer = SECURITY_LAYER_NONE;
}
else if (serverSecurityLayer == SECURITY_LAYER_NONE) {
- SWIFT_LOG(debug) << "Server supports no security layer" << std::endl;
+ SWIFT_LOG(debug) << "Server supports no security layer";
}
else {
- SWIFT_LOG(debug) << "Server supports security layer" << std::endl;
+ SWIFT_LOG(debug) << "Server supports security layer";
}
unsigned int serverMaximumBuffer = (challengePointer[1] << 16) |
@@ -92,7 +92,7 @@ bool WindowsGSSAPIClientAuthenticator::setChallenge(const boost::optional<ByteAr
(challengePointer[3] << 0);
if ((serverSecurityLayer == SECURITY_LAYER_NONE) && (serverMaximumBuffer != 0)) {
- SWIFT_LOG(debug) << "Server supports no security layer but has maximum buffer size" << serverMaximumBuffer << std::endl;
+ SWIFT_LOG(debug) << "Server supports no security layer but has maximum buffer size" << serverMaximumBuffer;
error_ = true;
return false;
}
@@ -158,7 +158,7 @@ void WindowsGSSAPIClientAuthenticator::buildSecurityContext(const boost::optiona
}
if (contextSupported & ISC_REQ_MUTUAL_AUTH == 0) {
- SWIFT_LOG(debug) << "Mutual authentication not supported" << std::endl;
+ SWIFT_LOG(debug) << "Mutual authentication not supported";
error_ = true;
return;
}
@@ -181,14 +181,14 @@ void WindowsGSSAPIClientAuthenticator::buildSecurityContext(const boost::optiona
}
userName_ = names.sUserName;
- SWIFT_LOG(debug) << "User name: " << userName_ << std::endl;
+ SWIFT_LOG(debug) << "User name: " << userName_;
std::size_t position = userName_.find("\\");
clientName_ = userName_.substr(position + 1);
- SWIFT_LOG(debug) << "Client name: " << clientName_ << std::endl;
+ SWIFT_LOG(debug) << "Client name: " << clientName_;
serverName_ = userName_.substr(0, position);
- SWIFT_LOG(debug) << "Server name: " << serverName_ << std::endl;
+ SWIFT_LOG(debug) << "Server name: " << serverName_;
freeContextBuffer(names.sUserName);
step_ = SecurityLayerNegotiation;
diff --git a/Swiften/SASL/WindowsServicePrincipalName.cpp b/Swiften/SASL/WindowsServicePrincipalName.cpp
index 419395c..6c87925 100644
--- a/Swiften/SASL/WindowsServicePrincipalName.cpp
+++ b/Swiften/SASL/WindowsServicePrincipalName.cpp
@@ -64,7 +64,7 @@ std::string WindowsServicePrincipalName::toString() {
firstCall = false;
}
- SWIFT_LOG(debug) << "SPN: " << str << std::endl;
+ SWIFT_LOG(debug) << "SPN: " << str;
return str;
}
@@ -72,17 +72,17 @@ DWORD WindowsServicePrincipalName::dsMakeSpn(DWORD* length, wchar_t* value) {
DWORD status;
#ifdef UNICODE
- SWIFT_LOG(debug) << "UNICODE is defined" << std::endl;
+ SWIFT_LOG(debug) << "UNICODE is defined";
#else
- SWIFT_LOG(debug) << "UNICODE is not defined" << std::endl;
+ SWIFT_LOG(debug) << "UNICODE is not defined";
#endif
- SWIFT_LOG(debug) << "serviceClass_: " << convertWStringToString(serviceClass_.c_str()) << std::endl;
- SWIFT_LOG(debug) << "serviceName_: " << convertWStringToString(serviceName_.c_str()) << std::endl;
- SWIFT_LOG(debug) << "instanceName_: " << convertWStringToString(instanceName_.c_str()) << std::endl;
- SWIFT_LOG(debug) << "referrer_: " << convertWStringToString(referrer_.c_str()) << std::endl;
- SWIFT_LOG(debug) << "instancePort_: " << instancePort_ << std::endl;
- SWIFT_LOG(debug) << "length: " << *length << std::endl;
+ SWIFT_LOG(debug) << "serviceClass_: " << convertWStringToString(serviceClass_.c_str());
+ SWIFT_LOG(debug) << "serviceName_: " << convertWStringToString(serviceName_.c_str());
+ SWIFT_LOG(debug) << "instanceName_: " << convertWStringToString(instanceName_.c_str());
+ SWIFT_LOG(debug) << "referrer_: " << convertWStringToString(referrer_.c_str());
+ SWIFT_LOG(debug) << "instancePort_: " << instancePort_;
+ SWIFT_LOG(debug) << "length: " << *length;
/* Call the Unicode function because that is recommended:
https://msdn.microsoft.com/en-us/library/windows/desktop/ff381407%28v=vs.85%29.aspx */
@@ -97,7 +97,7 @@ https://msdn.microsoft.com/en-us/library/windows/desktop/ff381407%28v=vs.85%29.a
if (status != ERROR_SUCCESS) {
boost::system::error_code errorCode(status, boost::system::system_category());
- SWIFT_LOG(debug) << std::hex << "status: 0x" << status << ": " << errorCode.message() << std::endl;
+ SWIFT_LOG(debug) << std::hex << "status: 0x" << status << ": " << errorCode.message();
}
return status;
diff --git a/Swiften/SConscript b/Swiften/SConscript
index 5705113..7ea7355 100644
--- a/Swiften/SConscript
+++ b/Swiften/SConscript
@@ -383,6 +383,7 @@ if env["SCONS_STAGE"] == "build" :
File("Avatars/UnitTest/CombinedAvatarProviderTest.cpp"),
File("Avatars/UnitTest/AvatarManagerImplTest.cpp"),
File("Base/UnitTest/IDGeneratorTest.cpp"),
+ File("Base/UnitTest/LogTest.cpp"),
File("Base/UnitTest/LRUCacheTest.cpp"),
File("Base/UnitTest/SimpleIDGeneratorTest.cpp"),
File("Base/UnitTest/StringTest.cpp"),
diff --git a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
index aaac757..566d556 100644
--- a/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/JinglePayloadSerializer.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015-2016 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -93,7 +93,7 @@ std::string JinglePayloadSerializer::actionToString(JinglePayload::Action action
case JinglePayload::TransportReplace:
return "transport-replace";
case JinglePayload::UnknownAction:
- SWIFT_LOG(warning) << "Serializing unknown action value." << std::endl;
+ SWIFT_LOG(warning) << "Serializing unknown action value.";
return "";
}
assert(false);
@@ -103,7 +103,7 @@ std::string JinglePayloadSerializer::actionToString(JinglePayload::Action action
std::string JinglePayloadSerializer::reasonTypeToString(JinglePayload::Reason::Type type) const {
switch(type) {
case JinglePayload::Reason::UnknownType:
- SWIFT_LOG(warning) << "Unknown jingle reason type!" << std::endl;
+ SWIFT_LOG(warning) << "Unknown jingle reason type!";
return "";
case JinglePayload::Reason::AlternativeSession:
return "alternative-session";
diff --git a/Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.cpp b/Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.cpp
index 6e78a8d..128aac7 100644
--- a/Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/ReferencePayloadSerializer.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2018 Isode Limited.
+ * Copyright (c) 2018-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -44,7 +44,7 @@ std::string ReferencePayloadSerializer::serializePayload(ReferencePayload::ref r
element.addNode(std::make_shared<XMLRawTextNode>(serializer->serialize(payload)));
}
else {
- SWIFT_LOG(warning) << "Could not find serializer for " << typeid(*(payload.get())).name() << std::endl;
+ SWIFT_LOG(warning) << "Could not find serializer for " << typeid(*(payload.get())).name();
}
}
}
diff --git a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp
index 4743089..f38f5b7 100644
--- a/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.cpp
+++ b/Swiften/Serializer/PayloadSerializers/WhiteboardSerializer.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.
*/
@@ -67,7 +67,7 @@ namespace Swift {
element->setAttribute("height", std::to_string(rect.getHeight()));
element->setAttribute("id", rect.getID());
element->setAttribute("stroke", rect.getPenColor().toHex());
- element->setAttribute("fill", rect.getBrushColor().toHex());;
+ element->setAttribute("fill", rect.getBrushColor().toHex());
element->setAttribute("stroke-width", std::to_string(rect.getPenWidth()));
element->setAttribute("opacity", alphaToOpacity(rect.getPenColor().getAlpha()));
element->setAttribute("fill-opacity", alphaToOpacity(rect.getBrushColor().getAlpha()));
@@ -80,7 +80,7 @@ namespace Swift {
try {
element->setAttribute("id", polygon.getID());
element->setAttribute("stroke", polygon.getPenColor().toHex());
- element->setAttribute("fill", polygon.getBrushColor().toHex());;
+ element->setAttribute("fill", polygon.getBrushColor().toHex());
element->setAttribute("stroke-width", std::to_string(polygon.getPenWidth()));
element->setAttribute("opacity", alphaToOpacity(polygon.getPenColor().getAlpha()));
element->setAttribute("fill-opacity", alphaToOpacity(polygon.getBrushColor().getAlpha()));
@@ -117,7 +117,7 @@ namespace Swift {
element->setAttribute("ry", std::to_string(ellipse.getRY()));
element->setAttribute("id", ellipse.getID());
element->setAttribute("stroke", ellipse.getPenColor().toHex());
- element->setAttribute("fill", ellipse.getBrushColor().toHex());;
+ element->setAttribute("fill", ellipse.getBrushColor().toHex());
element->setAttribute("stroke-width", std::to_string(ellipse.getPenWidth()));
element->setAttribute("opacity", alphaToOpacity(ellipse.getPenColor().getAlpha()));
element->setAttribute("fill-opacity", alphaToOpacity(ellipse.getBrushColor().getAlpha()));
@@ -199,7 +199,7 @@ namespace Swift {
case WhiteboardPayload::SessionTerminate:
return "session-terminate";
case WhiteboardPayload::UnknownType:
- SWIFT_LOG(warning) << "Serializing unknown action value." << std::endl;
+ SWIFT_LOG(warning) << "Serializing unknown action value.";
return "";
}
assert(false);
diff --git a/Swiften/Serializer/StanzaSerializer.cpp b/Swiften/Serializer/StanzaSerializer.cpp
index 3de706d..d4231c5 100644
--- a/Swiften/Serializer/StanzaSerializer.cpp
+++ b/Swiften/Serializer/StanzaSerializer.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.
*/
@@ -53,7 +53,7 @@ SafeByteArray StanzaSerializer::serialize(std::shared_ptr<ToplevelElement> eleme
serializedPayloads += serializer->serialize(payload);
}
else {
- SWIFT_LOG(warning) << "Could not find serializer for " << typeid(*(payload.get())).name() << std::endl;
+ SWIFT_LOG(warning) << "Could not find serializer for " << typeid(*(payload.get())).name();
}
}
serializedPayloads = String::sanitizeXMPPString(serializedPayloads);
diff --git a/Swiften/Serializer/StreamErrorSerializer.cpp b/Swiften/Serializer/StreamErrorSerializer.cpp
index 66a71ca..684e8fe 100644
--- a/Swiften/Serializer/StreamErrorSerializer.cpp
+++ b/Swiften/Serializer/StreamErrorSerializer.cpp
@@ -30,7 +30,6 @@ SafeByteArray StreamErrorSerializer::serialize(std::shared_ptr<ToplevelElement>
case StreamError::ImproperAddressing: typeTag = "improper-addressing"; break;
case StreamError::InternalServerError: typeTag = "internal-server-error"; break;
case StreamError::InvalidFrom: typeTag = "invalid-from"; break;
- case StreamError::InvalidID: typeTag = "invalid-id"; break;
case StreamError::InvalidNamespace: typeTag = "invalid-namespace"; break;
case StreamError::InvalidXML: typeTag = "invalid-xml"; break;
case StreamError::NotAuthorized: typeTag = "not-authorized"; break;
@@ -44,6 +43,7 @@ SafeByteArray StreamErrorSerializer::serialize(std::shared_ptr<ToplevelElement>
case StreamError::SystemShutdown: typeTag = "system-shutdown"; break;
case StreamError::UndefinedCondition: typeTag = "undefined-condition"; break;
case StreamError::UnsupportedEncoding: typeTag = "unsupported-encoding"; break;
+ case StreamError::UnsupportedFeature: typeTag = "unsupported-feature"; break;
case StreamError::UnsupportedStanzaType: typeTag = "unsupported-stanza-type"; break;
case StreamError::UnsupportedVersion: typeTag = "unsupported-version"; break;
}
diff --git a/Swiften/Serializer/XMPPSerializer.cpp b/Swiften/Serializer/XMPPSerializer.cpp
index 9cde777..7a003fb 100644
--- a/Swiften/Serializer/XMPPSerializer.cpp
+++ b/Swiften/Serializer/XMPPSerializer.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.
*/
@@ -89,7 +89,7 @@ SafeByteArray XMPPSerializer::serializeElement(std::shared_ptr<ToplevelElement>
return (*i)->serialize(element);
}
else {
- SWIFT_LOG(warning) << "Could not find serializer for " << typeid(*(element.get())).name() << std::endl;
+ SWIFT_LOG(warning) << "Could not find serializer for " << typeid(*(element.get())).name();
return createSafeByteArray("");
}
}
diff --git a/Swiften/StreamManagement/StanzaAckRequester.cpp b/Swiften/StreamManagement/StanzaAckRequester.cpp
index a0f5b70..c71803a 100644
--- a/Swiften/StreamManagement/StanzaAckRequester.cpp
+++ b/Swiften/StreamManagement/StanzaAckRequester.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -28,7 +28,7 @@ void StanzaAckRequester::handleAckReceived(unsigned int handledStanzasCount) {
unsigned int i = lastHandledStanzasCount;
while (i != handledStanzasCount) {
if (unackedStanzas.empty()) {
- SWIFT_LOG(warning) << "Server acked more stanzas than we sent" << std::endl;
+ SWIFT_LOG(warning) << "Server acked more stanzas than we sent";
break;
}
std::shared_ptr<Stanza> ackedStanza = unackedStanzas.front();
diff --git a/Swiften/StreamStack/WhitespacePingLayer.cpp b/Swiften/StreamStack/WhitespacePingLayer.cpp
index 9a473f3..7c8301e 100644
--- a/Swiften/StreamStack/WhitespacePingLayer.cpp
+++ b/Swiften/StreamStack/WhitespacePingLayer.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.
*/
@@ -22,7 +22,7 @@ WhitespacePingLayer::WhitespacePingLayer(TimerFactory* timerFactory) : isActive(
}
WhitespacePingLayer::~WhitespacePingLayer() {
- SWIFT_LOG_ASSERT(!isActive, debug) << "WhitespacePingLayer still active at destruction." << std::endl;
+ SWIFT_LOG_ASSERT(!isActive, debug) << "WhitespacePingLayer still active at destruction.";
if (isActive) {
timer->stop();
}
diff --git a/Swiften/TLS/CAPICertificate.cpp b/Swiften/TLS/CAPICertificate.cpp
index f10ad47..526b535 100644
--- a/Swiften/TLS/CAPICertificate.cpp
+++ b/Swiften/TLS/CAPICertificate.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.
*/
@@ -22,7 +22,7 @@
#define DEBUG_SCARD_STATUS(function, status) \
{ \
std::shared_ptr<boost::system::error_code> errorCode = std::make_shared<boost::system::error_code>(status, boost::system::system_category()); \
- SWIFT_LOG(debug) << std::hex << function << ": status: 0x" << status << ": " << errorCode->message() << std::endl; \
+ SWIFT_LOG(debug) << std::hex << function << ": status: 0x" << status << ": " << errorCode->message(); \
}
namespace Swift {
@@ -44,7 +44,7 @@ CAPICertificate::CAPICertificate(const std::string& capiUri, TimerFactory* timer
}
CAPICertificate::~CAPICertificate() {
- SWIFT_LOG(debug) << "Destroying the CAPICertificate" << std::endl;
+ SWIFT_LOG(debug) << "Destroying the CAPICertificate";
if (smartCardTimer_) {
smartCardTimer_->stop();
smartCardTimer_->onTick.disconnect(boost::bind(&CAPICertificate::handleSmartCardTimerTick, this));
@@ -53,7 +53,7 @@ CAPICertificate::~CAPICertificate() {
if (certStoreHandle_) {
if (CertCloseStore(certStoreHandle_, 0) == FALSE) {
- SWIFT_LOG(debug) << "Failed to close the certificate store handle" << std::endl;
+ SWIFT_LOG(debug) << "Failed to close the certificate store handle";
}
}
@@ -161,7 +161,7 @@ void CAPICertificate::setUri(const std::string& capiUri) {
CERT_KEY_PROV_INFO_PROP_ID,
NULL,
&len)) {
- SWIFT_LOG(error) << "Error while retrieving context properties" << std::endl;
+ SWIFT_LOG(error) << "Error while retrieving context properties";
return;
}
@@ -287,25 +287,25 @@ bool CAPICertificate::checkIfSmartCardPresent() {
switch (dwState) {
case SCARD_ABSENT:
- SWIFT_LOG(debug) << "Card absent." << std::endl;
+ SWIFT_LOG(debug) << "Card absent.";
break;
case SCARD_PRESENT:
- SWIFT_LOG(debug) << "Card present." << std::endl;
+ SWIFT_LOG(debug) << "Card present.";
break;
case SCARD_SWALLOWED:
- SWIFT_LOG(debug) << "Card swallowed." << std::endl;
+ SWIFT_LOG(debug) << "Card swallowed.";
break;
case SCARD_POWERED:
- SWIFT_LOG(debug) << "Card has power." << std::endl;
+ SWIFT_LOG(debug) << "Card has power.";
break;
case SCARD_NEGOTIABLE:
- SWIFT_LOG(debug) << "Card reset and waiting PTS negotiation." << std::endl;
+ SWIFT_LOG(debug) << "Card reset and waiting PTS negotiation.";
break;
case SCARD_SPECIFIC:
- SWIFT_LOG(debug) << "Card has specific communication protocols set." << std::endl;
+ SWIFT_LOG(debug) << "Card has specific communication protocols set.";
break;
default:
- SWIFT_LOG(debug) << "Unknown or unexpected card state." << std::endl;
+ SWIFT_LOG(debug) << "Unknown or unexpected card state.";
break;
}
@@ -332,7 +332,7 @@ bool CAPICertificate::checkIfSmartCardPresent() {
void CAPICertificate::handleSmartCardTimerTick() {
bool poll = checkIfSmartCardPresent();
if (lastPollingResult_ && !poll) {
- SWIFT_LOG(debug) << "CAPI Certificate detected that the certificate card was removed" << std::endl;
+ SWIFT_LOG(debug) << "CAPI Certificate detected that the certificate card was removed";
onCertificateCardRemoved();
}
lastPollingResult_ = poll;
diff --git a/Swiften/TLS/CertificateFactory.cpp b/Swiften/TLS/CertificateFactory.cpp
index aaf27d9..d4db3f4 100644
--- a/Swiften/TLS/CertificateFactory.cpp
+++ b/Swiften/TLS/CertificateFactory.cpp
@@ -23,9 +23,9 @@ namespace Swift {
CertificateFactory::~CertificateFactory() {
}
-std::vector<std::unique_ptr<Certificate>> CertificateFactory::createCertificateChain(const ByteArray& /* data */) {
+std::vector<std::shared_ptr<Certificate>> CertificateFactory::createCertificateChain(const ByteArray& /* data */) {
assert(false);
- return std::vector<std::unique_ptr<Certificate>>();
+ return std::vector<std::shared_ptr<Certificate>>();
}
PrivateKey::ref CertificateFactory::createPrivateKey(const SafeByteArray& data, boost::optional<SafeByteArray> password) {
diff --git a/Swiften/TLS/CertificateFactory.h b/Swiften/TLS/CertificateFactory.h
index 619031c..873c36b 100644
--- a/Swiften/TLS/CertificateFactory.h
+++ b/Swiften/TLS/CertificateFactory.h
@@ -19,7 +19,7 @@ namespace Swift {
virtual ~CertificateFactory();
virtual Certificate* createCertificateFromDER(const ByteArray& der) = 0;
- virtual std::vector<std::unique_ptr<Certificate>> createCertificateChain(const ByteArray& data);
+ virtual std::vector<std::shared_ptr<Certificate>> createCertificateChain(const ByteArray& data);
PrivateKey::ref createPrivateKey(const SafeByteArray& data, boost::optional<SafeByteArray> password = boost::optional<SafeByteArray>());
};
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp
index 8d2d965..66b650d 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificate.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.
*/
@@ -32,11 +32,19 @@ OpenSSLCertificate::OpenSSLCertificate(const ByteArray& der) {
#endif
cert = std::shared_ptr<X509>(d2i_X509(nullptr, &p, der.size()), X509_free);
if (!cert) {
- SWIFT_LOG(warning) << "Error creating certificate from DER data" << std::endl;
+// SWIFT_LOG(warning) << "Error creating certificate from DER data";
}
parse();
}
+void OpenSSLCertificate::incrementReferenceCount() const {
+#if OPENSSL_VERSION_NUMBER >= 0x10100000L
+ X509_up_ref(cert.get());
+#else
+ CRYPTO_add(&(cert.get()->references), 1, CRYPTO_LOCK_EVP_PKEY);
+#endif
+}
+
ByteArray OpenSSLCertificate::toDER() const {
ByteArray result;
if (!cert) {
diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificate.h b/Swiften/TLS/OpenSSL/OpenSSLCertificate.h
index 186caea..64da82a 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificate.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificate.h
@@ -45,6 +45,8 @@ namespace Swift {
return cert;
}
+ void incrementReferenceCount() const;
+
private:
void parse();
diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp
index 5eb626b..73058a5 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp
@@ -7,6 +7,7 @@
#include <Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h>
#include <openssl/pem.h>
+#include <openssl/err.h>
namespace Swift {
@@ -20,8 +21,8 @@ Certificate* OpenSSLCertificateFactory::createCertificateFromDER(const ByteArray
return new OpenSSLCertificate(der);
}
-std::vector<std::unique_ptr<Certificate>> OpenSSLCertificateFactory::createCertificateChain(const ByteArray& data) {
- std::vector<std::unique_ptr<Certificate>> certificateChain;
+std::vector<std::shared_ptr<Certificate>> OpenSSLCertificateFactory::createCertificateChain(const ByteArray& data) {
+ std::vector<std::shared_ptr<Certificate>> certificateChain;
if (data.size() > std::numeric_limits<int>::max()) {
return certificateChain;
@@ -35,15 +36,20 @@ std::vector<std::unique_ptr<Certificate>> OpenSSLCertificateFactory::createCerti
auto x509certFromPEM = PEM_read_bio_X509(bio.get(), &openSSLCert, nullptr, nullptr);
if (x509certFromPEM && openSSLCert) {
std::shared_ptr<X509> x509Cert(openSSLCert, X509_free);
- certificateChain.emplace_back(std::make_unique<OpenSSLCertificate>(x509Cert));
+ certificateChain.emplace_back(std::make_shared<OpenSSLCertificate>(x509Cert));
openSSLCert = nullptr;
while ((x509certFromPEM = PEM_read_bio_X509(bio.get(), &openSSLCert, nullptr, nullptr)) != nullptr) {
std::shared_ptr<X509> x509Cert(openSSLCert, X509_free);
- certificateChain.emplace_back(std::make_unique<OpenSSLCertificate>(x509Cert));
+ certificateChain.emplace_back(std::make_shared<OpenSSLCertificate>(x509Cert));
openSSLCert = nullptr;
}
}
+ // Clear any (expected) errors which resulted from PEM parsing
+ // If we don't do this, any existing TLS context will detect these
+ // spurious errors and fail to work
+ ERR_clear_error();
+
return certificateChain;
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h
index 48e9b2c..a6974c8 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.h
@@ -16,6 +16,6 @@ namespace Swift {
virtual ~OpenSSLCertificateFactory() override final;
virtual Certificate* createCertificateFromDER(const ByteArray& der) override final;
- virtual std::vector<std::unique_ptr<Certificate>> createCertificateChain(const ByteArray& data) override final;
+ virtual std::vector<std::shared_ptr<Certificate>> createCertificateChain(const ByteArray& data) override final;
};
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
index 5692e74..86b0504 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp
@@ -42,6 +42,14 @@ namespace Swift {
static const int MAX_FINISHED_SIZE = 4096;
static const int SSL_READ_BUFFERSIZE = 8192;
+#define SSL_DEFAULT_VERIFY_DEPTH 5
+
+// Callback function declarations for certificate verification
+extern "C" {
+ static int certVerifyCallback(X509_STORE_CTX *store_ctx, void*);
+ static int verifyCallback(int preverify_ok, X509_STORE_CTX *ctx);
+}
+
static void freeX509Stack(STACK_OF(X509)* stack) {
sk_X509_free(stack);
}
@@ -90,7 +98,7 @@ namespace {
}
}
-OpenSSLContext::OpenSSLContext(Mode mode) : mode_(mode), state_(State::Start) {
+OpenSSLContext::OpenSSLContext(const TLSOptions& options, Mode mode) : mode_(mode), state_(State::Start) {
ensureLibraryInitialized();
context_ = createSSL_CTX(mode_);
SSL_CTX_set_options(context_.get(), SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
@@ -113,52 +121,58 @@ OpenSSLContext::OpenSSLContext(Mode mode) : mode_(mode), state_(State::Start) {
// TODO: implement OCSP support
// TODO: handle OCSP stapling see https://www.rfc-editor.org/rfc/rfc4366.txt
- // Load system certs
+
+ // Default for ignoreSystemTrustAnchors is false, i.e. load System TAs by default,
+ // to preserve previous behaviour
+ if (!options.ignoreSystemTrustAnchors) {
+ // Load system certs
#if defined(SWIFTEN_PLATFORM_WINDOWS)
- X509_STORE* store = SSL_CTX_get_cert_store(context_.get());
- HCERTSTORE systemStore = CertOpenSystemStore(0, "ROOT");
- if (systemStore) {
- PCCERT_CONTEXT certContext = NULL;
- while (true) {
- certContext = CertFindCertificateInStore(systemStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, NULL, certContext);
- if (!certContext) {
- break;
- }
- OpenSSLCertificate cert(createByteArray(certContext->pbCertEncoded, certContext->cbCertEncoded));
- if (store && cert.getInternalX509()) {
- X509_STORE_add_cert(store, cert.getInternalX509().get());
+ X509_STORE* store = SSL_CTX_get_cert_store(context_.get());
+ HCERTSTORE systemStore = CertOpenSystemStore(0, "ROOT");
+ if (systemStore) {
+ PCCERT_CONTEXT certContext = nullptr;
+ while (true) {
+ certContext = CertFindCertificateInStore(systemStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, CERT_FIND_ANY, nullptr, certContext);
+ if (!certContext) {
+ break;
+ }
+ OpenSSLCertificate cert(createByteArray(certContext->pbCertEncoded, certContext->cbCertEncoded));
+ if (store && cert.getInternalX509()) {
+ X509_STORE_add_cert(store, cert.getInternalX509().get());
+ }
}
}
- }
#elif !defined(SWIFTEN_PLATFORM_MACOSX)
- SSL_CTX_set_default_verify_paths(context_.get());
+ SSL_CTX_set_default_verify_paths(context_.get());
#elif defined(SWIFTEN_PLATFORM_MACOSX) && !defined(SWIFTEN_PLATFORM_IPHONE)
- // On Mac OS X 10.5 (OpenSSL < 0.9.8), OpenSSL does not automatically look in the system store.
- // On Mac OS X 10.6 (OpenSSL >= 0.9.8), OpenSSL *does* look in the system store to determine trust.
- // However, if there is a certificate error, it will always emit the "Invalid CA" error if we didn't add
- // the certificates first. See
- // http://opensource.apple.com/source/OpenSSL098/OpenSSL098-27/src/crypto/x509/x509_vfy_apple.c
- // to understand why. We therefore add all certs from the system store ourselves.
- X509_STORE* store = SSL_CTX_get_cert_store(context_.get());
- CFArrayRef anchorCertificates;
- if (SecTrustCopyAnchorCertificates(&anchorCertificates) == 0) {
- for (int i = 0; i < CFArrayGetCount(anchorCertificates); ++i) {
- SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(const_cast<void*>(CFArrayGetValueAtIndex(anchorCertificates, i)));
- CSSM_DATA certCSSMData;
- if (SecCertificateGetData(cert, &certCSSMData) != 0 || certCSSMData.Length == 0) {
- continue;
- }
- std::vector<unsigned char> certData;
- certData.resize(certCSSMData.Length);
- memcpy(&certData[0], certCSSMData.Data, certCSSMData.Length);
- OpenSSLCertificate certificate(certData);
- if (store && certificate.getInternalX509()) {
- X509_STORE_add_cert(store, certificate.getInternalX509().get());
+ // On Mac OS X 10.5 (OpenSSL < 0.9.8), OpenSSL does not automatically look in the system store.
+ // On Mac OS X 10.6 (OpenSSL >= 0.9.8), OpenSSL *does* look in the system store to determine trust.
+ // However, if there is a certificate error, it will always emit the "Invalid CA" error if we didn't add
+ // the certificates first. See
+ // http://opensource.apple.com/source/OpenSSL098/OpenSSL098-27/src/crypto/x509/x509_vfy_apple.c
+ // to understand why. We therefore add all certs from the system store ourselves.
+ X509_STORE* store = SSL_CTX_get_cert_store(context_.get());
+ CFArrayRef anchorCertificates;
+ if (SecTrustCopyAnchorCertificates(&anchorCertificates) == 0) {
+ for (int i = 0; i < CFArrayGetCount(anchorCertificates); ++i) {
+ SecCertificateRef cert = reinterpret_cast<SecCertificateRef>(const_cast<void*>(CFArrayGetValueAtIndex(anchorCertificates, i)));
+ CSSM_DATA certCSSMData;
+ if (SecCertificateGetData(cert, &certCSSMData) != 0 || certCSSMData.Length == 0) {
+ continue;
+ }
+ std::vector<unsigned char> certData;
+ certData.resize(certCSSMData.Length);
+ memcpy(&certData[0], certCSSMData.Data, certCSSMData.Length);
+ OpenSSLCertificate certificate(certData);
+ if (store && certificate.getInternalX509()) {
+ X509_STORE_add_cert(store, certificate.getInternalX509().get());
+ }
}
+ CFRelease(anchorCertificates);
}
- CFRelease(anchorCertificates);
- }
#endif
+ }
+ configure(options);
}
OpenSSLContext::~OpenSSLContext() {
@@ -175,6 +189,241 @@ void OpenSSLContext::initAndSetBIOs() {
SSL_set_bio(handle_.get(), readBIO_, writeBIO_);
}
+// This callback is called by OpenSSL when a client certificate needs to be verified.
+// In turn, this calls the verification callback which the user
+// of this OpenSSLContext has configured (if any).
+static int certVerifyCallback(X509_STORE_CTX* store_ctx, void* arg)
+{
+ OpenSSLContext* context = static_cast<OpenSSLContext *>(arg);
+
+ // Need to stash store_ctx pointer for use within verification
+ context->setX509StoreContext(store_ctx);
+
+ int ret;
+
+ // This callback shouldn't have been set up if the context doesn't
+ // have a verifyCertCallback set, but it doesn't hurt to double check
+ std::function<int (const TLSContext *)> cb = context->getVerifyCertCallback();
+ if (cb != nullptr) {
+ ret = cb(static_cast<const OpenSSLContext*>(context));
+ } else {
+ SWIFT_LOG(debug) << "certVerifyCallback called but context.verifyCertCallback is unset";
+ ret = 0;
+ }
+
+ context->setX509StoreContext(nullptr);
+ return ret;
+}
+
+// Convenience function to generate a text representation
+// of an X509 Name. This information is only used for logging.
+static std::string X509_NAME_to_text(X509_NAME* name)
+{
+ std::string nameString;
+
+ if (!name) {
+ return nameString;
+ }
+
+ std::unique_ptr<BIO, decltype(&BIO_free)> io(BIO_new(BIO_s_mem()), &BIO_free);
+ int r = X509_NAME_print_ex(io.get(), name, 0, XN_FLAG_RFC2253);
+ BIO_write(io.get(), "\0", 1);
+
+ if (r > 0) {
+ BUF_MEM* ptr = nullptr;
+ BIO_get_mem_ptr(io.get(), &ptr);
+ nameString = ptr->data;
+ }
+
+ return nameString;
+}
+
+// Check depth of certificate chain
+static int verifyCallback(int preverifyOk, X509_STORE_CTX* ctx)
+{
+ // Retrieve the pointer to the SSL of the connection currently treated
+ // and the application specific data stored into the SSL object.
+
+ int err = X509_STORE_CTX_get_error(ctx);
+ int depth = X509_STORE_CTX_get_error_depth(ctx);
+
+ SSL* ssl = static_cast<SSL*>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
+ SSL_CTX* sslctx = ssl ? SSL_get_SSL_CTX(ssl) : nullptr;
+ if (!sslctx) {
+ SWIFT_LOG(debug) << "verifyCallback: internal error";
+ return preverifyOk;
+ }
+
+ if (SSL_CTX_get_verify_mode(sslctx) == SSL_VERIFY_NONE) {
+ SWIFT_LOG(debug) << "verifyCallback: no verification required";
+ // No verification requested
+ return 1;
+ }
+
+ X509* errCert = X509_STORE_CTX_get_current_cert(ctx);
+ std::string subjectString;
+ if (errCert) {
+ X509_NAME* subjectName = X509_get_subject_name(errCert);
+ subjectString = X509_NAME_to_text(subjectName);
+ }
+
+ // Catch a too long certificate chain. The depth limit set using
+ // SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so
+ // that whenever the "depth>verify_depth" condition is met, we
+ // have violated the limit and want to log this error condition.
+ // We must do it here, because the CHAIN_TOO_LONG error would not
+ // be found explicitly; only errors introduced by cutting off the
+ // additional certificates would be logged.
+ if (depth >= SSL_CTX_get_verify_depth(sslctx)) {
+ preverifyOk = 0;
+ err = X509_V_ERR_CERT_CHAIN_TOO_LONG;
+ X509_STORE_CTX_set_error(ctx, err);
+ }
+
+ if (!preverifyOk) {
+ std::string issuerString;
+ if (errCert) {
+ X509_NAME* issuerName = X509_get_issuer_name(errCert);
+ issuerString = X509_NAME_to_text(issuerName);
+ }
+ SWIFT_LOG(debug) << "verifyCallback: verification error " <<
+ X509_verify_cert_error_string(err) << " depth: " <<
+ depth << " issuer: " << ((issuerString.length() > 0) ? issuerString : "<unknown>");
+ } else {
+ SWIFT_LOG(debug) << "verifyCallback: SSL depth: " << depth << " Subject: " <<
+ ((subjectString.length() > 0) ? subjectString : "<>");
+ }
+ // Always return "OK", as check on verification status
+ // will be performed once TLS handshake has completed,
+ // by calling OpenSSLContext::getVerificationErrorTypeForResult() to
+ // get the value set via X509_STORE_CTX_set_error() above.
+ return 1;
+}
+
+bool OpenSSLContext::configure(const TLSOptions &options)
+{
+ if (options.cipherSuites) {
+ std::string cipherSuites = *(options.cipherSuites);
+ if (SSL_CTX_set_cipher_list(context_.get(), cipherSuites.c_str()) != 1 ) {
+ SWIFT_LOG(debug) << "Failed to set cipher-suites";
+ return false;
+ }
+ }
+
+ if (options.context) {
+ const auto& contextId = *options.context;
+
+ if (SSL_CTX_set_session_id_context(context_.get(),
+ reinterpret_cast<const unsigned char *>(contextId.c_str()),
+ contextId.length()) != 1) {
+ SWIFT_LOG(debug) << "Failed to set context-id";
+ return false;
+ }
+ }
+
+ if (options.sessionCacheTimeout) {
+ int scto = *options.sessionCacheTimeout;
+ if (scto <= 0) {
+ SWIFT_LOG(debug) << "Invalid value for session-cache-timeout";
+ return false;
+ }
+ (void)SSL_CTX_set_timeout(context_.get(), scto);
+ if (SSL_CTX_get_timeout(context_.get()) != scto) {
+ SWIFT_LOG(debug) << "Failed to set session-cache-timeout";
+ return false;
+ }
+ }
+
+ if (options.verifyCertificateCallback) {
+ verifyCertCallback = *options.verifyCertificateCallback;
+ } else {
+ verifyCertCallback = nullptr;
+ }
+
+ if (options.verifyMode) {
+ TLSOptions::VerifyMode verify_mode = *options.verifyMode;
+ int mode;
+ switch (verify_mode) {
+ case TLSOptions::VerifyMode::None:
+ mode = SSL_VERIFY_NONE;
+ break;
+ case TLSOptions::VerifyMode::Required:
+ mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE;
+ break;
+ case TLSOptions::VerifyMode::Optional:
+ mode = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE;
+ break;
+ }
+
+ // Set up default certificate chain verification depth - may be overridden below
+ SSL_CTX_set_verify_depth(context_.get(), SSL_DEFAULT_VERIFY_DEPTH + 1);
+
+ // Set callbacks up
+ SSL_CTX_set_verify(context_.get(), mode, verifyCallback);
+
+ // Only set up certificate verification callback if a user callback has
+ // been configured via the TLSOptions
+ if (verifyCertCallback != nullptr) {
+ SSL_CTX_set_cert_verify_callback(context_.get(), certVerifyCallback, this);
+ }
+ }
+
+ if (options.verifyDepth) {
+ int depth = *options.verifyDepth;
+ if (depth <= 0) {
+ SWIFT_LOG(debug) << "Invalid value for verify-depth";
+ return false;
+ }
+
+ // Increase depth limit by one, so that verifyCallback() will log it
+ SSL_CTX_set_verify_depth(context_.get(), depth + 1);
+ }
+
+ auto updateOptionIfPresent = [this](boost::optional<bool> option, int flag) {
+ if (option) {
+ if (*option) {
+ SSL_CTX_set_options(context_.get(), flag);
+ }
+ else {
+ SSL_CTX_clear_options(context_.get(), flag);
+ }
+ }
+ };
+ updateOptionIfPresent(options.workaroundMicrosoftSessID, SSL_OP_MICROSOFT_SESS_ID_BUG);
+ updateOptionIfPresent(options.workaroundNetscapeChallenge, SSL_OP_NETSCAPE_CHALLENGE_BUG);
+ updateOptionIfPresent(options.workaroundNetscapeReuseCipherChange, SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG);
+ updateOptionIfPresent(options.workaroundSSLRef2ReuseCertType, SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG);
+ updateOptionIfPresent(options.workaroundMicrosoftBigSSLv3Buffer, SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER);
+ updateOptionIfPresent(options.workaroundSSLeay080ClientDH, SSL_OP_SSLEAY_080_CLIENT_DH_BUG);
+ updateOptionIfPresent(options.workaroundTLSD5, SSL_OP_TLS_D5_BUG);
+ updateOptionIfPresent(options.workaroundTLSBlockPadding, SSL_OP_TLS_BLOCK_PADDING_BUG);
+ updateOptionIfPresent(options.workaroundDontInsertEmptyFragments, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
+ updateOptionIfPresent(options.workaroundAll, SSL_OP_ALL);
+ updateOptionIfPresent(options.suppressSSLv2, SSL_OP_NO_SSLv2);
+ updateOptionIfPresent(options.suppressSSLv3, SSL_OP_NO_SSLv3);
+ updateOptionIfPresent(options.suppressTLSv1, SSL_OP_NO_TLSv1);
+ updateOptionIfPresent(options.disableTLSRollBackBug, SSL_OP_TLS_ROLLBACK_BUG);
+ updateOptionIfPresent(options.singleDHUse, SSL_OP_SINGLE_DH_USE);
+
+ if (options.trustAnchors) {
+ // Add any additional Trust Anchors which are present in the TLSOptions
+ X509_STORE* store = SSL_CTX_get_cert_store(context_.get());
+
+ if (store) {
+ for (auto& certificate : *options.trustAnchors) {
+ auto openSSLCert = dynamic_cast<OpenSSLCertificate*>(certificate.get());
+ if (openSSLCert && openSSLCert->getInternalX509()) {
+ X509_STORE_add_cert(store, openSSLCert->getInternalX509().get());
+ // Don't need to increment reference count as X509_STORE_add_cert does thiS
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+
void OpenSSLContext::accept() {
assert(mode_ == Mode::Server);
handle_ = std::unique_ptr<SSL>(SSL_new(context_.get()));
@@ -342,9 +591,9 @@ void OpenSSLContext::sendPendingDataToApplication() {
}
}
-bool OpenSSLContext::setCertificateChain(std::vector<std::unique_ptr<Certificate>>&& certificateChain) {
+bool OpenSSLContext::setCertificateChain(const std::vector<std::shared_ptr<Certificate>>& certificateChain) {
if (certificateChain.size() == 0) {
- SWIFT_LOG(warning) << "Trying to load empty certificate chain." << std::endl;
+ SWIFT_LOG(debug) << "Trying to load empty certificate chain.";
return false;
}
@@ -354,6 +603,7 @@ bool OpenSSLContext::setCertificateChain(std::vector<std::unique_ptr<Certificate
return false;
}
+ // This increments the reference count on the X509 certificate automatically
if (SSL_CTX_use_certificate(context_.get(), openSSLCert->getInternalX509().get()) != 1) {
return false;
}
@@ -364,11 +614,13 @@ bool OpenSSLContext::setCertificateChain(std::vector<std::unique_ptr<Certificate
if (!openSSLCert) {
return false;
}
+
if (SSL_CTX_add_extra_chain_cert(context_.get(), openSSLCert->getInternalX509().get()) != 1) {
- SWIFT_LOG(warning) << "Trying to load empty certificate chain." << std::endl;
+ SWIFT_LOG(debug) << "Trying to load empty certificate chain.";
return false;
}
- certificate->release();
+ // Have to manually increment reference count as SSL_CTX_add_extra_chain_cert does not do so
+ openSSLCert->incrementReferenceCount();
}
}
@@ -414,16 +666,17 @@ bool OpenSSLContext::setPrivateKey(const PrivateKey::ref& privateKey) {
safePassword.push_back(0);
password = safePassword.data();
}
- auto resultKey = PEM_read_bio_PrivateKey(bio.get(), nullptr, empty_or_preset_password_cb, password);
+ // Make sure resultKey is tidied up by wrapping it in a shared_ptr
+ auto resultKey = std::shared_ptr<EVP_PKEY>(PEM_read_bio_PrivateKey(bio.get(), nullptr, empty_or_preset_password_cb, password), EVP_PKEY_free);
if (resultKey) {
if (handle_) {
- auto result = SSL_use_PrivateKey(handle_.get(), resultKey);;
+ auto result = SSL_use_PrivateKey(handle_.get(), resultKey.get());
if (result != 1) {
return false;
}
}
else {
- auto result = SSL_CTX_use_PrivateKey(context_.get(), resultKey);
+ auto result = SSL_CTX_use_PrivateKey(context_.get(), resultKey.get());
if (result != 1) {
return false;
}
@@ -486,7 +739,7 @@ bool OpenSSLContext::setDiffieHellmanParameters(const ByteArray& parametersInOpe
if (bio) {
BIO_write(bio.get(), vecptr(parametersInOpenSslDer), parametersInOpenSslDer.size());
auto result = 0L;
- if (auto dhparams = d2i_DHparams_bio(bio.get(), NULL)) {
+ if (auto dhparams = d2i_DHparams_bio(bio.get(), nullptr)) {
if (handle_) {
result = SSL_set_tmp_dh(handle_.get(), dhparams);
}
@@ -502,13 +755,33 @@ bool OpenSSLContext::setDiffieHellmanParameters(const ByteArray& parametersInOpe
std::vector<Certificate::ref> OpenSSLContext::getPeerCertificateChain() const {
std::vector<Certificate::ref> result;
+
+ // When this context is a server, the peer (client) certificate
+ // is obtained via SSL_get_peer_certificate, and any other
+ // certificates set by the peer are available via SSL_get_peer_cert_chain.
+ // When this context is a client, all of the server's certificates are
+ // obtained using SSL_get_peer_cert_chain
+ if (mode_ == Mode::Server) {
+ auto cert = SSL_get_peer_certificate(handle_.get());
+ if (cert) {
+ // Do not need to copy the returned cert as SSL_get_peer_certificate
+ // increments the reference count on the certificate
+ std::shared_ptr<X509> x509Cert(cert, X509_free);
+ Certificate::ref cert = std::make_shared<OpenSSLCertificate>(x509Cert);
+ result.push_back(cert);
+ }
+ }
+
STACK_OF(X509)* chain = SSL_get_peer_cert_chain(handle_.get());
for (int i = 0; i < sk_X509_num(chain); ++i) {
+ // Here we do need to copy the returned cert, since SSL_get_peer_cert_chain
+ // does not increment the reference count on each certificate
std::shared_ptr<X509> x509Cert(X509_dup(sk_X509_value(chain, i)), X509_free);
Certificate::ref cert = std::make_shared<OpenSSLCertificate>(x509Cert);
result.push_back(cert);
}
+
return result;
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContext.h b/Swiften/TLS/OpenSSL/OpenSSLContext.h
index c18a6f4..8eb5758 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContext.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLContext.h
@@ -16,6 +16,7 @@
#include <Swiften/Base/ByteArray.h>
#include <Swiften/TLS/CertificateWithKey.h>
#include <Swiften/TLS/TLSContext.h>
+#include <Swiften/TLS/TLSOptions.h>
namespace std {
template<>
@@ -38,14 +39,14 @@ namespace std {
namespace Swift {
class OpenSSLContext : public TLSContext, boost::noncopyable {
public:
- OpenSSLContext(Mode mode);
+ OpenSSLContext(const TLSOptions& options, Mode mode);
virtual ~OpenSSLContext() override final;
void accept() override final;
void connect() override final;
void connect(const std::string& requestHostname) override final;
- bool setCertificateChain(std::vector<std::unique_ptr<Certificate>>&& certificateChain) override final;
+ bool setCertificateChain(const std::vector<std::shared_ptr<Certificate>>& certificateChain) override final;
bool setPrivateKey(const PrivateKey::ref& privateKey) override final;
bool setClientCertificate(CertificateWithKey::ref cert) override final;
void setAbortTLSHandshake(bool abort) override final;
@@ -60,7 +61,11 @@ namespace Swift {
virtual ByteArray getFinishMessage() const override final;
virtual ByteArray getPeerFinishMessage() const override final;
+ void setX509StoreContext(X509_STORE_CTX *ptr) { x509_store_ctx = ptr; }
+ std::function<int (const TLSContext *)> getVerifyCertCallback() { return verifyCertCallback; }
+
private:
+ bool configure(const TLSOptions& options);
static void ensureLibraryInitialized();
static int handleServerNameCallback(SSL *ssl, int *ad, void *arg);
static CertificateVerificationError::Type getVerificationErrorTypeForResult(int);
@@ -81,5 +86,7 @@ namespace Swift {
BIO* readBIO_ = nullptr;
BIO* writeBIO_ = nullptr;
bool abortTLSHandshake_ = false;
- };
+ X509_STORE_CTX *x509_store_ctx = nullptr;
+ std::function<int (const TLSContext *)> verifyCertCallback = nullptr;
+ };
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
index a9ba5ab..e332ca8 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
+++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -21,8 +21,8 @@ bool OpenSSLContextFactory::canCreate() const {
return true;
}
-std::unique_ptr<TLSContext> OpenSSLContextFactory::createTLSContext(const TLSOptions&, TLSContext::Mode mode) {
- return std::unique_ptr<TLSContext>(new OpenSSLContext(mode));
+std::unique_ptr<TLSContext> OpenSSLContextFactory::createTLSContext(const TLSOptions& options, TLSContext::Mode mode) {
+ return std::make_unique<OpenSSLContext>(options, mode);
}
ByteArray OpenSSLContextFactory::convertDHParametersFromPEMToDER(const std::string& dhParametersInPEM) {
@@ -47,14 +47,14 @@ ByteArray OpenSSLContextFactory::convertDHParametersFromPEMToDER(const std::stri
void OpenSSLContextFactory::setCheckCertificateRevocation(bool check) {
if (check) {
- SWIFT_LOG(warning) << "CRL Checking not supported for OpenSSL" << std::endl;
+ SWIFT_LOG(warning) << "CRL Checking not supported for OpenSSL";
assert(false);
}
}
void OpenSSLContextFactory::setDisconnectOnCardRemoval(bool check) {
if (check) {
- SWIFT_LOG(warning) << "Smart cards not supported for OpenSSL" << std::endl;
+ SWIFT_LOG(warning) << "Smart cards not supported for OpenSSL";
}
}
diff --git a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
index 95a2b0c..834e479 100644
--- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
+++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010-2018 Isode Limited.
+ * Copyright (c) 2010-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
diff --git a/Swiften/TLS/Schannel/SchannelContext.cpp b/Swiften/TLS/Schannel/SchannelContext.cpp
index c07d009..722fb4a 100644
--- a/Swiften/TLS/Schannel/SchannelContext.cpp
+++ b/Swiften/TLS/Schannel/SchannelContext.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2012-2016 Isode Limited.
+ * Copyright (c) 2012-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -40,10 +40,10 @@ SchannelContext::SchannelContext(bool tls1_0Workaround) : state_(Start), secCont
//------------------------------------------------------------------------
SchannelContext::~SchannelContext() {
- SWIFT_LOG(debug) << "Destroying SchannelContext" << std::endl;
+ SWIFT_LOG(debug) << "Destroying SchannelContext";
if (myCertStore_) {
if (CertCloseStore(myCertStore_, 0) == FALSE) {
- SWIFT_LOG(debug) << "Failed to close the certificate store" << std::endl;
+ SWIFT_LOG(debug) << "Failed to close the certificate store";
}
}
}
@@ -52,7 +52,7 @@ SchannelContext::~SchannelContext() {
void SchannelContext::determineStreamSizes() {
if (QueryContextAttributes(contextHandle_, SECPKG_ATTR_STREAM_SIZES, &streamSizes_) != SEC_E_OK) {
- SWIFT_LOG(debug) << "QueryContextAttributes failed to determinate the stream size" << std::endl;
+ SWIFT_LOG(debug) << "QueryContextAttributes failed to determinate the stream size";
}
}
@@ -653,7 +653,7 @@ std::vector<Certificate::ref> SchannelContext::getPeerCertificateChain() const {
SECURITY_STATUS status = QueryContextAttributes(contextHandle_, SECPKG_ATTR_REMOTE_CERT_CONTEXT, pServerCert.Reset());
if (status != SEC_E_OK) {
- SWIFT_LOG(debug) << "Error while Querying the Certificate Chain" << std::endl;
+ SWIFT_LOG(debug) << "Error while Querying the Certificate Chain";
return certificateChain;
}
certificateChain.push_back(std::make_shared<SchannelCertificate>(pServerCert));
@@ -688,7 +688,7 @@ ByteArray SchannelContext::getFinishMessage() const {
return createByteArray(((unsigned char*) bindings.Bindings) + bindings.Bindings->dwApplicationDataOffset + 11 /* tls-unique:*/, bindings.Bindings->cbApplicationDataLength - 11);
}
else {
- SWIFT_LOG(debug) << "Error while retrieving Finish Message" << std::endl;
+ SWIFT_LOG(debug) << "Error while retrieving Finish Message";
}
return ByteArray();
diff --git a/Swiften/TLS/SecureTransport/SecureTransportContext.mm b/Swiften/TLS/SecureTransport/SecureTransportContext.mm
index 1ed636b..b4f7842 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportContext.mm
+++ b/Swiften/TLS/SecureTransport/SecureTransportContext.mm
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015-2016 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -72,14 +72,14 @@ CFArrayRef CreateClientCertificateChainAsCFArrayRef(CertificateWithKey::ref key)
break;
case errSecAuthFailed:
// Password did not work for decoding the certificate.
- SWIFT_LOG(warning) << "Invalid password." << std::endl;
+ SWIFT_LOG(warning) << "Invalid password.";
break;
case errSecDecode:
// Other decoding error.
- SWIFT_LOG(warning) << "PKCS12 decoding error." << std::endl;
+ SWIFT_LOG(warning) << "PKCS12 decoding error.";
break;
default:
- SWIFT_LOG(warning) << "Unknown error." << std::endl;
+ SWIFT_LOG(warning) << "Unknown error.";
}
if (securityError != errSecSuccess) {
@@ -110,20 +110,20 @@ SecureTransportContext::SecureTransportContext(bool checkCertificateRevocation)
// set IO callbacks
error = SSLSetIOFuncs(sslContext_.get(), &SecureTransportContext::SSLSocketReadCallback, &SecureTransportContext::SSLSocketWriteCallback);
if (error != noErr) {
- SWIFT_LOG(error) << "Unable to set IO functions to SSL context." << std::endl;
+ SWIFT_LOG(error) << "Unable to set IO functions to SSL context.";
sslContext_.reset();
}
error = SSLSetConnection(sslContext_.get(), this);
if (error != noErr) {
- SWIFT_LOG(error) << "Unable to set connection to SSL context." << std::endl;
+ SWIFT_LOG(error) << "Unable to set connection to SSL context.";
sslContext_.reset();
}
error = SSLSetSessionOption(sslContext_.get(), kSSLSessionOptionBreakOnServerAuth, true);
if (error != noErr) {
- SWIFT_LOG(error) << "Unable to set kSSLSessionOptionBreakOnServerAuth on session." << std::endl;
+ SWIFT_LOG(error) << "Unable to set kSSLSessionOptionBreakOnServerAuth on session.";
sslContext_.reset();
}
}
@@ -154,19 +154,19 @@ std::string SecureTransportContext::stateToString(State state) {
}
void SecureTransportContext::setState(State newState) {
- SWIFT_LOG(debug) << "Switch state from " << stateToString(state_) << " to " << stateToString(newState) << "." << std::endl;
+ SWIFT_LOG(debug) << "Switch state from " << stateToString(state_) << " to " << stateToString(newState) << ".";
state_ = newState;
}
void SecureTransportContext::connect() {
- SWIFT_LOG_ASSERT(state_ == None, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
+ SWIFT_LOG_ASSERT(state_ == None, error) << "current state '" << stateToString(state_) << " invalid.";
if (clientCertificate_) {
CFArrayRef certs = CreateClientCertificateChainAsCFArrayRef(clientCertificate_);
if (certs) {
std::shared_ptr<CFArray> certRefs(certs, CFRelease);
OSStatus result = SSLSetCertificate(sslContext_.get(), certRefs.get());
if (result != noErr) {
- SWIFT_LOG(error) << "SSLSetCertificate failed with error " << result << "." << std::endl;
+ SWIFT_LOG(error) << "SSLSetCertificate failed with error " << result << ".";
}
}
}
@@ -174,23 +174,23 @@ void SecureTransportContext::connect() {
}
void SecureTransportContext::processHandshake() {
- SWIFT_LOG_ASSERT(state_ == None || state_ == Handshake, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
+ SWIFT_LOG_ASSERT(state_ == None || state_ == Handshake, error) << "current state '" << stateToString(state_) << " invalid.";
OSStatus error = SSLHandshake(sslContext_.get());
if (error == errSSLWouldBlock) {
setState(Handshake);
}
else if (error == noErr) {
- SWIFT_LOG(debug) << "TLS handshake successful." << std::endl;
+ SWIFT_LOG(debug) << "TLS handshake successful.";
setState(HandshakeDone);
onConnected();
}
else if (error == errSSLPeerAuthCompleted) {
- SWIFT_LOG(debug) << "Received server certificate. Start verification." << std::endl;
+ SWIFT_LOG(debug) << "Received server certificate. Start verification.";
setState(Handshake);
verifyServerCertificate();
}
else {
- SWIFT_LOG(debug) << "Error returned from SSLHandshake call is " << error << "." << std::endl;
+ SWIFT_LOG(debug) << "Error returned from SSLHandshake call is " << error << ".";
fatalError(nativeToTLSError(error), std::make_shared<CertificateVerificationError>());
}
}
@@ -226,13 +226,13 @@ void SecureTransportContext::verifyServerCertificate() {
OSStatus cssmResult = 0;
switch(trustResult) {
case kSecTrustResultUnspecified:
- SWIFT_LOG(warning) << "Successful implicit validation. Result unspecified." << std::endl;
+ SWIFT_LOG(warning) << "Successful implicit validation. Result unspecified.";
break;
case kSecTrustResultProceed:
- SWIFT_LOG(warning) << "Validation resulted in explicitly trusted." << std::endl;
+ SWIFT_LOG(warning) << "Validation resulted in explicitly trusted.";
break;
case kSecTrustResultRecoverableTrustFailure:
- SWIFT_LOG(warning) << "recoverable trust failure" << std::endl;
+ SWIFT_LOG(warning) << "recoverable trust failure";
error = SecTrustGetCssmResultCode(trust, &cssmResult);
if (error == errSecSuccess) {
verificationError_ = CSSMErrorToVerificationError(cssmResult);
@@ -304,8 +304,8 @@ bool SecureTransportContext::setClientCertificate(CertificateWithKey::ref cert)
}
void SecureTransportContext::handleDataFromNetwork(const SafeByteArray& data) {
- SWIFT_LOG(debug) << std::endl;
- SWIFT_LOG_ASSERT(state_ == HandshakeDone || state_ == Handshake, error) << "current state '" << stateToString(state_) << " invalid." << std::endl;
+ SWIFT_LOG(debug);
+ SWIFT_LOG_ASSERT(state_ == HandshakeDone || state_ == Handshake, error) << "current state '" << stateToString(state_) << " invalid.";
append(readingBuffer_, data);
@@ -332,7 +332,7 @@ void SecureTransportContext::handleDataFromNetwork(const SafeByteArray& data) {
break;
}
else {
- SWIFT_LOG(error) << "SSLRead failed with error " << error << ", read bytes: " << bytesRead << "." << std::endl;
+ SWIFT_LOG(error) << "SSLRead failed with error " << error << ", read bytes: " << bytesRead << ".";
fatalError(std::make_shared<TLSError>(), std::make_shared<CertificateVerificationError>());
return;
}
@@ -347,7 +347,7 @@ void SecureTransportContext::handleDataFromNetwork(const SafeByteArray& data) {
}
break;
case Error:
- SWIFT_LOG(debug) << "Igoring received data in error state." << std::endl;
+ SWIFT_LOG(debug) << "Igoring received data in error state.";
break;
}
}
@@ -358,13 +358,13 @@ void SecureTransportContext::handleDataFromApplication(const SafeByteArray& data
OSStatus error = SSLWrite(sslContext_.get(), data.data(), data.size(), &processedBytes);
switch(error) {
case errSSLWouldBlock:
- SWIFT_LOG(warning) << "Unexpected because the write callback does not block." << std::endl;
+ SWIFT_LOG(warning) << "Unexpected because the write callback does not block.";
return;
case errSSLClosedGraceful:
case noErr:
return;
default:
- SWIFT_LOG(warning) << "SSLWrite returned error code: " << error << ", processed bytes: " << processedBytes << std::endl;
+ SWIFT_LOG(warning) << "SSLWrite returned error code: " << error << ", processed bytes: " << processedBytes;
fatalError(std::make_shared<TLSError>(), std::shared_ptr<CertificateVerificationError>());
}
}
@@ -376,7 +376,7 @@ std::vector<Certificate::ref> SecureTransportContext::getPeerCertificateChain()
typedef boost::remove_pointer<SecTrustRef>::type SecTrust;
std::shared_ptr<SecTrust> securityTrust;
- SecTrustRef secTrust = nullptr;;
+ SecTrustRef secTrust = nullptr;
OSStatus error = SSLCopyPeerTrust(sslContext_.get(), &secTrust);
if (error == noErr) {
securityTrust = std::shared_ptr<SecTrust>(secTrust, CFRelease);
@@ -390,7 +390,7 @@ std::vector<Certificate::ref> SecureTransportContext::getPeerCertificateChain()
}
}
else {
- SWIFT_LOG(warning) << "Failed to obtain peer trust structure; error = " << error << "." << std::endl;
+ SWIFT_LOG(warning) << "Failed to obtain peer trust structure; error = " << error << ".";
}
}
@@ -402,7 +402,7 @@ CertificateVerificationError::ref SecureTransportContext::getPeerCertificateVeri
}
ByteArray SecureTransportContext::getFinishMessage() const {
- SWIFT_LOG(warning) << "Access to TLS handshake finish message is not part of OS X Secure Transport APIs." << std::endl;
+ SWIFT_LOG(warning) << "Access to TLS handshake finish message is not part of OS X Secure Transport APIs.";
return ByteArray();
}
@@ -453,42 +453,42 @@ std::shared_ptr<CertificateVerificationError> SecureTransportContext::CSSMErrorT
std::shared_ptr<CertificateVerificationError> error;
switch(resultCode) {
case CSSMERR_TP_NOT_TRUSTED:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_NOT_TRUSTED" << std::endl;
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_NOT_TRUSTED";
error = std::make_shared<CertificateVerificationError>(CertificateVerificationError::Untrusted);
break;
case CSSMERR_TP_CERT_NOT_VALID_YET:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_NOT_VALID_YET" << std::endl;
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_NOT_VALID_YET";
error = std::make_shared<CertificateVerificationError>(CertificateVerificationError::NotYetValid);
break;
case CSSMERR_TP_CERT_EXPIRED:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_EXPIRED" << std::endl;
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_EXPIRED";
error = std::make_shared<CertificateVerificationError>(CertificateVerificationError::Expired);
break;
case CSSMERR_TP_CERT_REVOKED:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_REVOKED" << std::endl;
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_CERT_REVOKED";
error = std::make_shared<CertificateVerificationError>(CertificateVerificationError::Revoked);
break;
case CSSMERR_TP_VERIFY_ACTION_FAILED:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_VERIFY_ACTION_FAILED" << std::endl;
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_TP_VERIFY_ACTION_FAILED";
break;
case CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK" << std::endl;
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_INCOMPLETE_REVOCATION_CHECK";
if (checkCertificateRevocation_) {
error = std::make_shared<CertificateVerificationError>(CertificateVerificationError::RevocationCheckFailed);
}
break;
case CSSMERR_APPLETP_OCSP_UNAVAILABLE:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_OCSP_UNAVAILABLE" << std::endl;
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_OCSP_UNAVAILABLE";
if (checkCertificateRevocation_) {
error = std::make_shared<CertificateVerificationError>(CertificateVerificationError::RevocationCheckFailed);
}
break;
case CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE:
- SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE" << std::endl;
+ SWIFT_LOG(debug) << "CSSM result code: CSSMERR_APPLETP_SSL_BAD_EXT_KEY_USE";
error = std::make_shared<CertificateVerificationError>(CertificateVerificationError::InvalidPurpose);
break;
default:
- SWIFT_LOG(warning) << "unhandled CSSM error: " << resultCode << ", CSSM_TP_BASE_TP_ERROR: " << CSSM_TP_BASE_TP_ERROR << std::endl;
+ SWIFT_LOG(warning) << "unhandled CSSM error: " << resultCode << ", CSSM_TP_BASE_TP_ERROR: " << CSSM_TP_BASE_TP_ERROR;
error = std::make_shared<CertificateVerificationError>(CertificateVerificationError::UnknownError);
break;
}
diff --git a/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp b/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp
index cc10987..ac399e1 100644
--- a/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp
+++ b/Swiften/TLS/SecureTransport/SecureTransportContextFactory.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015-2018 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -39,7 +39,7 @@ void SecureTransportContextFactory::setCheckCertificateRevocation(bool b) {
void SecureTransportContextFactory::setDisconnectOnCardRemoval(bool b) {
disconnectOnCardRemoval_ = b;
if (disconnectOnCardRemoval_) {
- SWIFT_LOG(warning) << "Smart cards have not been tested yet" << std::endl;
+ SWIFT_LOG(warning) << "Smart cards have not been tested yet";
}
}
diff --git a/Swiften/TLS/ServerIdentityVerifier.cpp b/Swiften/TLS/ServerIdentityVerifier.cpp
index 226e94b..18ea2aa 100644
--- a/Swiften/TLS/ServerIdentityVerifier.cpp
+++ b/Swiften/TLS/ServerIdentityVerifier.cpp
@@ -12,7 +12,7 @@
namespace Swift {
-ServerIdentityVerifier::ServerIdentityVerifier(const JID& jid, IDNConverter* idnConverter) : domainValid(false) {
+ServerIdentityVerifier::ServerIdentityVerifier(const JID& jid, IDNConverter* idnConverter, bool checkServer) : domainValid(false), checkServer_(checkServer) {
domain = jid.getDomain();
boost::optional<std::string> domainResult = idnConverter->getIDNAEncoded(domain);
if (!!domainResult) {
@@ -36,12 +36,14 @@ bool ServerIdentityVerifier::certificateVerifies(Certificate::ref certificate) {
}
hasSAN |= !dnsNames.empty();
+ std::string prefix = (checkServer_) ? "_xmpp-server." : "_xmpp-client.";
+
// SRV names
std::vector<std::string> srvNames = certificate->getSRVNames();
for (const auto& srvName : srvNames) {
// Only match SRV names that begin with the service; this isn't required per
// spec, but we're being purist about this.
- if (boost::starts_with(srvName, "_xmpp-client.") && matchesDomain(srvName.substr(std::string("_xmpp-client.").size(), srvName.npos))) {
+ if (boost::starts_with(srvName, prefix) && matchesDomain(srvName.substr(prefix.size(), srvName.npos))) {
return true;
}
}
@@ -80,15 +82,15 @@ bool ServerIdentityVerifier::matchesDomain(const std::string& s) const {
if (dotIndex != matchDomain.npos) {
matchDomain = matchDomain.substr(dotIndex + 1, matchDomain.npos);
}
- return matchString == matchDomain;
+ return boost::iequals(matchString, matchDomain);
}
else {
- return s == encodedDomain;
+ return boost::iequals(s, encodedDomain);
}
}
bool ServerIdentityVerifier::matchesAddress(const std::string& s) const {
- return s == domain;
+ return boost::iequals(s, domain);
}
}
diff --git a/Swiften/TLS/ServerIdentityVerifier.h b/Swiften/TLS/ServerIdentityVerifier.h
index f40c683..f2cf46f 100644
--- a/Swiften/TLS/ServerIdentityVerifier.h
+++ b/Swiften/TLS/ServerIdentityVerifier.h
@@ -18,7 +18,7 @@ namespace Swift {
class SWIFTEN_API ServerIdentityVerifier {
public:
- ServerIdentityVerifier(const JID& jid, IDNConverter* idnConverter);
+ ServerIdentityVerifier(const JID& jid, IDNConverter* idnConverter, bool checkServer=false);
bool certificateVerifies(Certificate::ref);
@@ -30,5 +30,6 @@ namespace Swift {
std::string domain;
std::string encodedDomain;
bool domainValid;
+ bool checkServer_;
};
}
diff --git a/Swiften/TLS/TLSContext.cpp b/Swiften/TLS/TLSContext.cpp
index 666ea7f..fd31c2d 100644
--- a/Swiften/TLS/TLSContext.cpp
+++ b/Swiften/TLS/TLSContext.cpp
@@ -21,7 +21,7 @@ void TLSContext::connect(const std::string& /* serverName */) {
assert(false);
}
-bool TLSContext::setCertificateChain(std::vector<std::unique_ptr<Certificate>>&& /* certificateChain */) {
+bool TLSContext::setCertificateChain(const std::vector<std::shared_ptr<Certificate>>& /* certificateChain */) {
assert(false);
return false;
}
diff --git a/Swiften/TLS/TLSContext.h b/Swiften/TLS/TLSContext.h
index 003069f..f2dbdce 100644
--- a/Swiften/TLS/TLSContext.h
+++ b/Swiften/TLS/TLSContext.h
@@ -28,7 +28,7 @@ namespace Swift {
virtual void connect() = 0;
virtual void connect(const std::string& serverName);
- virtual bool setCertificateChain(std::vector<std::unique_ptr<Certificate>>&& /* certificateChain */);
+ virtual bool setCertificateChain(const std::vector<std::shared_ptr<Certificate>>& /* certificateChain */);
virtual bool setPrivateKey(const PrivateKey::ref& /* privateKey */);
virtual bool setClientCertificate(CertificateWithKey::ref cert) = 0;
@@ -50,7 +50,7 @@ namespace Swift {
virtual ByteArray getFinishMessage() const = 0;
virtual ByteArray getPeerFinishMessage() const;
- public:
+ public:
enum class Mode {
Client,
Server
diff --git a/Swiften/TLS/TLSOptions.h b/Swiften/TLS/TLSOptions.h
index dd7e920..e3faaf9 100644
--- a/Swiften/TLS/TLSOptions.h
+++ b/Swiften/TLS/TLSOptions.h
@@ -7,8 +7,11 @@
#pragma once
namespace Swift {
+ class TLSContext;
+ class Certificate;
- struct TLSOptions {
+ class TLSOptions {
+ public:
TLSOptions() : schannelTLS1_0Workaround(false) {
}
@@ -21,5 +24,54 @@ namespace Swift {
*/
bool schannelTLS1_0Workaround;
+ /**
+ * OpenSSL configuration flags
+ */
+ boost::optional<bool> workaroundMicrosoftSessID;
+ boost::optional<bool> workaroundNetscapeChallenge;
+ boost::optional<bool> workaroundNetscapeReuseCipherChange;
+ boost::optional<bool> workaroundSSLRef2ReuseCertType;
+ boost::optional<bool> workaroundMicrosoftBigSSLv3Buffer;
+ boost::optional<bool> workaroundSSLeay080ClientDH;
+ boost::optional<bool> workaroundTLSD5;
+ boost::optional<bool> workaroundTLSBlockPadding;
+ boost::optional<bool> workaroundDontInsertEmptyFragments;
+ boost::optional<bool> workaroundAll;
+ boost::optional<bool> suppressSSLv2;
+ boost::optional<bool> suppressSSLv3;
+ boost::optional<bool> suppressTLSv1;
+ boost::optional<bool> disableTLSRollBackBug;
+ boost::optional<bool> singleDHUse;
+
+ /**
+ * Other OpenSSL configuration items
+ */
+ boost::optional<std::string> cipherSuites;
+ boost::optional<std::string> context;
+ boost::optional<int> sessionCacheTimeout;
+ boost::optional<int> verifyDepth;
+
+ enum class VerifyMode {
+ None,
+ Required,
+ Optional
+ };
+ boost::optional<VerifyMode> verifyMode;
+
+ /**
+ * Callback for certificate verification
+ */
+
+ boost::optional<std::function<int(const TLSContext *)>> verifyCertificateCallback;
+
+ /**
+ * Allows specification of application-specific Trust Anchors
+ */
+ boost::optional<std::vector<std::shared_ptr<Certificate>>> trustAnchors;
+
+ /**
+ * Turns off automatic loading of system Trust Anchors
+ */
+ bool ignoreSystemTrustAnchors = false;
};
}
diff --git a/Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp b/Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp
index 30fe423..47f3db2 100644
--- a/Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp
+++ b/Swiften/TLS/UnitTest/ServerIdentityVerifierTest.cpp
@@ -35,6 +35,8 @@ class ServerIdentityVerifierTest : public CppUnit::TestFixture {
CPPUNIT_TEST(testCertificateVerifies_WithMatchingInternationalXmppAddr);
CPPUNIT_TEST(testCertificateVerifies_WithMatchingCNWithoutSAN);
CPPUNIT_TEST(testCertificateVerifies_WithMatchingCNWithSAN);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingSRVNameWithServerExpected);
+ CPPUNIT_TEST(testCertificateVerifies_WithMatchingSRVNameWithClientUnexpected);
CPPUNIT_TEST_SUITE_END();
public:
@@ -58,6 +60,14 @@ class ServerIdentityVerifierTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
}
+ void testCertificateVerifies_WithMatchingDNSNameMixedCase() {
+ ServerIdentityVerifier testling(JID("foo@baR.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addDNSName("Bar.com");
+
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
+
void testCertificateVerifies_WithSecondMatchingDNSName() {
ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
SimpleCertificate::ref certificate(new SimpleCertificate());
@@ -131,6 +141,24 @@ class ServerIdentityVerifierTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
}
+ void testCertificateVerifies_WithMatchingSRVNameWithServerExpected() {
+ // Server-mode test which gets cert with "xmpp-server" SRV name
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get(), true);
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addSRVName("_xmpp-server.bar.com");
+
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
+
+ void testCertificateVerifies_WithMatchingSRVNameWithClientUnexpected() {
+ // Server-mode test which gets cert with "xmpp-client" SRV name
+ ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get(), true);
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addSRVName("_xmpp-client.bar.com");
+
+ CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
+ }
+
void testCertificateVerifies_WithMatchingXmppAddr() {
ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
SimpleCertificate::ref certificate(new SimpleCertificate());
@@ -139,6 +167,14 @@ class ServerIdentityVerifierTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
}
+ void testCertificateVerifies_WithMatchingXmppAddrMixedCase() {
+ ServerIdentityVerifier testling(JID("foo@baR.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addXMPPAddress("bAr.com");
+
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
+
void testCertificateVerifies_WithMatchingXmppAddrWithWildcard() {
ServerIdentityVerifier testling(JID("foo@im.bar.com/baz"), idnConverter.get());
SimpleCertificate::ref certificate(new SimpleCertificate());
@@ -147,6 +183,14 @@ class ServerIdentityVerifierTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
}
+ void testCertificateVerifies_WithMatchingXmppAddrWithWildcardMixedCase() {
+ ServerIdentityVerifier testling(JID("foo@im.bAr.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addXMPPAddress("*.baR.com");
+
+ CPPUNIT_ASSERT(!testling.certificateVerifies(certificate));
+ }
+
void testCertificateVerifies_WithMatchingInternationalXmppAddr() {
ServerIdentityVerifier testling(JID("foo@tron\xc3\xa7.com/baz"), idnConverter.get());
SimpleCertificate::ref certificate(new SimpleCertificate());
@@ -155,6 +199,14 @@ class ServerIdentityVerifierTest : public CppUnit::TestFixture {
CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
}
+ void testCertificateVerifies_WithMatchingInternationalXmppAddrMixedCase() {
+ ServerIdentityVerifier testling(JID("foo@tRon\xc3\xa7.com/baz"), idnConverter.get());
+ SimpleCertificate::ref certificate(new SimpleCertificate());
+ certificate->addXMPPAddress("trOn\xc3\xa7.com");
+
+ CPPUNIT_ASSERT(testling.certificateVerifies(certificate));
+ }
+
void testCertificateVerifies_WithMatchingCNWithoutSAN() {
ServerIdentityVerifier testling(JID("foo@bar.com/baz"), idnConverter.get());
SimpleCertificate::ref certificate(new SimpleCertificate());