summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--3rdParty/CppUnit/src/COPYING2
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/Asserter.h117
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/Message.h12
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/Portability.h24
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/Protector.h2
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/SynchronizedObject.h12
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/TestAssert.h228
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/TestCaller.h31
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/TestPath.h11
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/TestResult.h8
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/TestResultCollector.h11
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/TestSuite.h6
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/TextTestResult.h2
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/XmlOutputter.h10
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/config-auto.h161
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/config/SelectDllLoader.h7
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/config/config-msvc6.h21
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/extensions/ExceptionTestCaseDecorator.h4
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/extensions/HelperMacros.h24
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/extensions/TestCaseDecorator.h9
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/extensions/TestFactoryRegistry.h9
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/extensions/TestNamer.h27
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/extensions/TestSuiteBuilderContext.h19
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/extensions/TypeInfoHelper.h6
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/portability/CppUnitDeque.h25
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/portability/CppUnitMap.h29
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/portability/CppUnitSet.h28
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/portability/CppUnitVector.h25
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/tools/StringHelper.h45
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/tools/StringTools.h4
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/tools/XmlElement.h6
-rw-r--r--3rdParty/CppUnit/src/include/cppunit/ui/text/TextTestRunner.h6
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/Asserter.cpp119
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/BriefTestProgressListener.cpp2
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/DefaultProtector.cpp2
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/Exception.cpp8
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/Message.cpp16
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/Protector.cpp4
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/ProtectorChain.cpp9
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/ProtectorChain.h8
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/ProtectorContext.h7
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/SourceLine.cpp1
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/TestCase.cpp2
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/TestFactoryRegistry.cpp6
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/TestNamer.cpp14
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/TestPath.cpp4
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/TestResult.cpp6
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/TestResultCollector.cpp3
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/TestSuite.cpp3
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/TestSuiteBuilderContext.cpp1
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/TextTestProgressListener.cpp2
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/TypeInfoHelper.cpp27
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/XmlDocument.cpp2
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/XmlElement.cpp5
-rw-r--r--3rdParty/CppUnit/src/src/cppunit/XmlOutputter.cpp5
-rw-r--r--3rdParty/Expat/SConscript60
-rw-r--r--3rdParty/Expat/src/ascii.h32
-rw-r--r--3rdParty/Expat/src/asciitab.h32
-rw-r--r--3rdParty/Expat/src/expat.h37
-rw-r--r--3rdParty/Expat/src/expat_external.h92
-rw-r--r--3rdParty/Expat/src/iasciitab.h32
-rw-r--r--3rdParty/Expat/src/internal.h36
-rw-r--r--3rdParty/Expat/src/latin1tab.h32
-rw-r--r--3rdParty/Expat/src/loadlibrary.c143
-rw-r--r--3rdParty/Expat/src/nametab.h32
-rw-r--r--3rdParty/Expat/src/siphash.h81
-rw-r--r--3rdParty/Expat/src/utf8tab.h33
-rw-r--r--3rdParty/Expat/src/winconfig.h41
-rw-r--r--3rdParty/Expat/src/xmlparse.c3201
-rw-r--r--3rdParty/Expat/src/xmlrole.c62
-rw-r--r--3rdParty/Expat/src/xmlrole.h32
-rw-r--r--3rdParty/Expat/src/xmltok.c103
-rw-r--r--3rdParty/Expat/src/xmltok.h37
-rw-r--r--3rdParty/Expat/src/xmltok_impl.c132
-rw-r--r--3rdParty/Expat/src/xmltok_impl.h31
-rw-r--r--3rdParty/Expat/src/xmltok_ns.c33
-rwxr-xr-xBuildTools/InstallSwiftDependencies.sh4
-rw-r--r--BuildTools/SCons/SConscript.boot1
-rw-r--r--QA/Checker/checker.cpp4
-rw-r--r--Slimber/Server.cpp4
-rw-r--r--Sluift/ElementConvertors/DOMElementConvertor.cpp2
-rw-r--r--Sluift/ElementConvertors/DefaultElementConvertor.cpp4
-rw-r--r--SwifTools/Application/ApplicationPathProvider.cpp4
-rw-r--r--SwifTools/Application/MacOSXApplicationPathProvider.cpp4
-rw-r--r--SwifTools/Application/UnixApplicationPathProvider.cpp4
-rw-r--r--SwifTools/AutoUpdater/SparkleAutoUpdater.mm4
-rw-r--r--SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.mm6
-rw-r--r--SwifTools/CrashReporter.cpp4
-rw-r--r--SwifTools/HunspellChecker.cpp4
-rw-r--r--SwifTools/Notifier/NotificationCenterNotifier.mm4
-rw-r--r--Swift/Controllers/AccountController.cpp34
-rw-r--r--Swift/Controllers/Chat/ChatController.cpp12
-rw-r--r--Swift/Controllers/Chat/ChatsManager.cpp12
-rw-r--r--Swift/Controllers/Chat/MUCSearchController.cpp12
-rw-r--r--Swift/Controllers/FileTransfer/FileTransferController.cpp6
-rw-r--r--Swift/Controllers/Highlighting/HighlightManager.cpp4
-rw-r--r--Swift/Controllers/Settings/XMLSettingsProvider.cpp18
-rw-r--r--Swift/Controllers/StatusCache.cpp8
-rw-r--r--Swift/Controllers/Storages/AvatarFileStorage.cpp14
-rw-r--r--Swift/Controllers/Storages/CertificateFileStorage.cpp6
-rw-r--r--Swift/Packaging/Debian/Dockerfile.package.in3
-rw-r--r--Swift/QtUI/CAPICertificateSelector.cpp12
-rw-r--r--Swift/QtUI/QtAboutWidget.cpp4
-rw-r--r--Swift/QtUI/QtScaledAvatarCache.cpp8
-rw-r--r--Swift/QtUI/QtSpellCheckerWindow.cpp4
-rw-r--r--Swift/QtUI/QtSwift.cpp40
-rw-r--r--Swift/QtUI/QtTextEdit.cpp4
-rw-r--r--Swift/QtUI/QtUIFactory.cpp6
-rw-r--r--Swift/QtUI/QtWebKitChatView.cpp18
-rw-r--r--Swift/QtUI/Roster/QtFilterWidget.cpp2
-rw-r--r--Swift/QtUI/Trellis/QtDynamicGridLayout.cpp8
-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
244 files changed, 5275 insertions, 2885 deletions
diff --git a/3rdParty/CppUnit/src/COPYING b/3rdParty/CppUnit/src/COPYING
index b1e3f5a..0a41847 100644
--- a/3rdParty/CppUnit/src/COPYING
+++ b/3rdParty/CppUnit/src/COPYING
@@ -2,7 +2,7 @@
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
diff --git a/3rdParty/CppUnit/src/include/cppunit/Asserter.h b/3rdParty/CppUnit/src/include/cppunit/Asserter.h
index 94dadaa..3321b87 100644
--- a/3rdParty/CppUnit/src/include/cppunit/Asserter.h
+++ b/3rdParty/CppUnit/src/include/cppunit/Asserter.h
@@ -42,17 +42,24 @@ class Message;
* CPPUNIT_SOURCELINE() )
* \endcode
*/
+
+#if defined __GNUC__
+# define NORETURN __attribute__((noreturn))
+#else
+# define NORETURN
+#endif
+
struct Asserter
{
/*! \brief Throws a Exception with the specified message and location.
*/
- static void CPPUNIT_API fail( const Message &message,
+ NORETURN static void CPPUNIT_API fail( const Message &message,
const SourceLine &sourceLine = SourceLine() );
/*! \brief Throws a Exception with the specified message and location.
* \deprecated Use fail( Message, SourceLine ) instead.
*/
- static void CPPUNIT_API fail( std::string message,
+ NORETURN static void CPPUNIT_API fail( std::string message,
const SourceLine &sourceLine = SourceLine() );
/*! \brief Throws a Exception with the specified message and location.
@@ -76,16 +83,55 @@ struct Asserter
std::string message,
const SourceLine &sourceLine = SourceLine() );
- /*! \brief Returns a expected value string for a message.
+ /*! \brief Returns a expected value string for a message, case equal than
* Typically used to create 'not equal' message, or to check that a message
* contains the expected content when writing unit tests for your custom
* assertions.
*
* \param expectedValue String that represents the expected value.
* \return \a expectedValue prefixed with "Expected: ".
+ * \deprecated Use makeExpectedEqual instead
* \see makeActual().
*/
static std::string CPPUNIT_API makeExpected( const std::string &expectedValue );
+ /*! \brief Returns a expected value string for a message, case equal than
+ * Typically used to create 'not equal' message, or to check that a message
+ * contains the expected content when writing unit tests for your custom
+ * assertions.
+ *
+ * \param expectedValue String that represents the expected value.
+ * \return \a expectedValue prefixed with "Expected: ".
+ * \see makeActual().
+ */
+ static std::string CPPUNIT_API makeExpectedEqual( const std::string &expectedValue );
+ /*! \brief Returns a expected value string for a message, case less than.
+ *
+ * \param expectedValue String that represents the expected value.
+ * \return \a expectedValue prefixed with "Expected less than: ".
+ * \see makeExpectedEqual().
+ */
+ static std::string CPPUNIT_API makeExpectedLess( const std::string &expectedValue );
+ /*! \brief Returns a expected value string for a message, case less or equal than.
+ *
+ * \param expectedValue String that represents the expected value.
+ * \return \a expectedValue prefixed with "Expected: ".
+ * \see makeExpectedEqual().
+ */
+ static std::string CPPUNIT_API makeExpectedLessEqual( const std::string &expectedValue );
+ /*! \brief Returns a expected value string for a message, case greater than.
+ *
+ * \param expectedValue String that represents the expected value.
+ * \return \a expectedValue prefixed with "Expected: ".
+ * \see makeExpectedEqual().
+ */
+ static std::string CPPUNIT_API makeExpectedGreater( const std::string &expectedValue );
+ /*! \brief Returns a expected value string for a message, greater or equal than.
+ *
+ * \param expectedValue String that represents the expected value.
+ * \return \a expectedValue prefixed with "Expected: ".
+ * \see makeExpectedEqual().
+ */
+ static std::string CPPUNIT_API makeExpectedGreaterEqual( const std::string &expectedValue );
/*! \brief Returns an actual value string for a message.
* Typically used to create 'not equal' message, or to check that a message
@@ -98,11 +144,19 @@ struct Asserter
*/
static std::string CPPUNIT_API makeActual( const std::string &actualValue );
+ /*!
+ * \deprecated Use makeMessage instead
+ */
static Message CPPUNIT_API makeNotEqualMessage( const std::string &expectedValue,
const std::string &actualValue,
const AdditionalMessage &additionalMessage = AdditionalMessage(),
const std::string &shortDescription = "equality assertion failed");
+ static Message CPPUNIT_API makeMessage( const std::string &expectedValue,
+ const std::string &actualValue,
+ const std::string &shortDescription,
+ const AdditionalMessage &additionalMessage = AdditionalMessage());
+
/*! \brief Throws an Exception with the specified message and location.
* \param expected Text describing the expected value.
* \param actual Text describing the actual value.
@@ -111,13 +165,68 @@ struct Asserter
* what are the differences between the expected and actual value.
* \param shortDescription Short description for the failure message.
*/
- static void CPPUNIT_API failNotEqual( std::string expected,
+ NORETURN static void CPPUNIT_API failNotEqual( std::string expected,
std::string actual,
const SourceLine &sourceLine,
const AdditionalMessage &additionalMessage = AdditionalMessage(),
std::string shortDescription = "equality assertion failed" );
/*! \brief Throws an Exception with the specified message and location.
+ * \param expected Text describing the expected value.
+ * \param actual Text describing the actual value.
+ * \param sourceLine Location of the assertion.
+ * \param additionalMessage Additional message. Usually used to report
+ * what are the differences between the expected and actual value.
+ * \param shortDescription Short description for the failure message.
+ */
+ static void CPPUNIT_API failNotLess( std::string expected,
+ std::string actual,
+ const SourceLine &sourceLine,
+ const AdditionalMessage &additionalMessage = AdditionalMessage(),
+ std::string shortDescription = "less assertion failed" );
+
+ /*! \brief Throws an Exception with the specified message and location.
+ * \param expected Text describing the expected value.
+ * \param actual Text describing the actual value.
+ * \param sourceLine Location of the assertion.
+ * \param additionalMessage Additional message. Usually used to report
+ * what are the differences between the expected and actual value.
+ * \param shortDescription Short description for the failure message.
+ */
+ static void CPPUNIT_API failNotGreater( std::string expected,
+ std::string actual,
+ const SourceLine &sourceLine,
+ const AdditionalMessage &additionalMessage = AdditionalMessage(),
+ std::string shortDescription = "greater assertion failed" );
+
+ /*! \brief Throws an Exception with the specified message and location.
+ * \param expected Text describing the expected value.
+ * \param actual Text describing the actual value.
+ * \param sourceLine Location of the assertion.
+ * \param additionalMessage Additional message. Usually used to report
+ * what are the differences between the expected and actual value.
+ * \param shortDescription Short description for the failure message.
+ */
+ static void CPPUNIT_API failNotLessEqual( std::string expected,
+ std::string actual,
+ const SourceLine &sourceLine,
+ const AdditionalMessage &additionalMessage = AdditionalMessage(),
+ std::string shortDescription = "less equal assertion failed" );
+
+ /*! \brief Throws an Exception with the specified message and location.
+ * \param expected Text describing the expected value.
+ * \param actual Text describing the actual value.
+ * \param sourceLine Location of the assertion.
+ * \param additionalMessage Additional message. Usually used to report
+ * what are the differences between the expected and actual value.
+ * \param shortDescription Short description for the failure message.
+ */
+ static void CPPUNIT_API failNotGreaterEqual( std::string expected,
+ std::string actual,
+ const SourceLine &sourceLine,
+ const AdditionalMessage &additionalMessage = AdditionalMessage(),
+ std::string shortDescription = "greater equal assertion failed" ); /*! \brief Throws an Exception with the specified message and location.
+
* \param shouldFail if \c true then the exception is thrown. Otherwise
* nothing happen.
* \param expected Text describing the expected value.
diff --git a/3rdParty/CppUnit/src/include/cppunit/Message.h b/3rdParty/CppUnit/src/include/cppunit/Message.h
index 1ae51cc..c3d8d92 100644
--- a/3rdParty/CppUnit/src/include/cppunit/Message.h
+++ b/3rdParty/CppUnit/src/include/cppunit/Message.h
@@ -8,17 +8,13 @@
#pragma warning( disable: 4251 ) // X needs to have dll-interface to be used by clients of class Z
#endif
-#include <cppunit/portability/CppUnitDeque.h>
+#include <deque>
#include <string>
CPPUNIT_NS_BEGIN
-#if CPPUNIT_NEED_DLL_DECL
-// template class CPPUNIT_API std::deque<std::string>;
-#endif
-
/*! \brief Message associated to an Exception.
* \ingroup CreatingNewAssertions
* A message is composed of two items:
@@ -38,7 +34,7 @@ CPPUNIT_NS_BEGIN
class CPPUNIT_API Message
{
public:
- Message();
+ Message() {};
// Ensure thread-safe copy by detaching the string.
Message( const Message &other );
@@ -57,6 +53,8 @@ public:
const std::string &detail2,
const std::string &detail3 );
+ virtual ~Message();
+
Message &operator =( const Message &other );
/*! \brief Returns the short description.
@@ -141,7 +139,7 @@ public:
private:
std::string m_shortDescription;
- typedef CppUnitDeque<std::string> Details;
+ typedef std::deque<std::string> Details;
Details m_details;
};
diff --git a/3rdParty/CppUnit/src/include/cppunit/Portability.h b/3rdParty/CppUnit/src/include/cppunit/Portability.h
index ddf0316..d7c4c11 100644
--- a/3rdParty/CppUnit/src/include/cppunit/Portability.h
+++ b/3rdParty/CppUnit/src/include/cppunit/Portability.h
@@ -20,7 +20,7 @@
// Version number of package
#ifndef CPPUNIT_VERSION
-#define CPPUNIT_VERSION "1.12.0"
+#define CPPUNIT_VERSION "1.14.0"
#endif
#include <cppunit/config/CppUnitApi.h> // define CPPUNIT_API & CPPUNIT_NEED_DLL_DECL
@@ -61,20 +61,6 @@
# endif // !defined(CPPUNIT_NO_STD_NAMESPACE)
#endif // !defined(CPPUNIT_HAVE_NAMESPACES)
-/* Define CPPUNIT_STD_NEED_ALLOCATOR to 1 if you need to specify
- * the allocator you used when instantiating STL container. Typically
- * used for compilers that do not support template default parameter.
- * CPPUNIT_STD_ALLOCATOR will be used as the allocator. Default is
- * std::allocator. On some compilers, you may need to change this to
- * std::allocator<T>.
- */
-#if CPPUNIT_STD_NEED_ALLOCATOR
-# if !defined(CPPUNIT_STD_ALLOCATOR)
-# define CPPUNIT_STD_ALLOCATOR std::allocator
-# endif // !defined(CPPUNIT_STD_ALLOCATOR)
-#endif // defined(CPPUNIT_STD_NEED_ALLOCATOR)
-
-
// Compiler error location format for CompilerOutputter
// If not define, assumes that it's gcc
// See class CompilerOutputter for format.
@@ -162,11 +148,17 @@
/// \internal
#define _CPPUNIT_DO_JOIN2( symbol1, symbol2 ) symbol1##symbol2
+/// \internal Unique suffix for variable name. Can be overridden in platform specific
+/// config-*.h. Default to line number.
+#ifndef CPPUNIT_UNIQUE_COUNTER
+# define CPPUNIT_UNIQUE_COUNTER __LINE__
+#endif
+
/*! Adds the line number to the specified string to create a unique identifier.
* \param prefix Prefix added to the line number to create a unique identifier.
* \see CPPUNIT_TEST_SUITE_REGISTRATION for an example of usage.
*/
-#define CPPUNIT_MAKE_UNIQUE_NAME( prefix ) CPPUNIT_JOIN( prefix, __LINE__ )
+#define CPPUNIT_MAKE_UNIQUE_NAME( prefix ) CPPUNIT_JOIN( prefix, CPPUNIT_UNIQUE_COUNTER )
/*! Defines wrap colunm for %CppUnit. Used by CompilerOuputter.
*/
diff --git a/3rdParty/CppUnit/src/include/cppunit/Protector.h b/3rdParty/CppUnit/src/include/cppunit/Protector.h
index d14e75f..c6d2e7c 100644
--- a/3rdParty/CppUnit/src/include/cppunit/Protector.h
+++ b/3rdParty/CppUnit/src/include/cppunit/Protector.h
@@ -84,6 +84,8 @@ public:
~ProtectorGuard();
private:
+ ProtectorGuard( const ProtectorGuard& ); /* not copyable */
+ ProtectorGuard& operator=( const ProtectorGuard& ); /* not assignable */
TestResult *m_result;
};
diff --git a/3rdParty/CppUnit/src/include/cppunit/SynchronizedObject.h b/3rdParty/CppUnit/src/include/cppunit/SynchronizedObject.h
index 0f7d094..59c3cbb 100644
--- a/3rdParty/CppUnit/src/include/cppunit/SynchronizedObject.h
+++ b/3rdParty/CppUnit/src/include/cppunit/SynchronizedObject.h
@@ -50,15 +50,21 @@ protected:
public:
ExclusiveZone( SynchronizationObject *syncObject )
- : m_syncObject( syncObject )
+ : m_syncObject( syncObject )
{
- m_syncObject->lock();
+ m_syncObject->lock();
}
~ExclusiveZone()
{
- m_syncObject->unlock ();
+ m_syncObject->unlock ();
}
+ private:
+ /// Prevents the use of the copy constructor.
+ ExclusiveZone( const ExclusiveZone& );
+
+ /// Prevents the use of the copy operator.
+ ExclusiveZone& operator=( const ExclusiveZone& );
};
virtual void setSynchronizationObject( SynchronizationObject *syncObject );
diff --git a/3rdParty/CppUnit/src/include/cppunit/TestAssert.h b/3rdParty/CppUnit/src/include/cppunit/TestAssert.h
index f74797b..bb29ac0 100644
--- a/3rdParty/CppUnit/src/include/cppunit/TestAssert.h
+++ b/3rdParty/CppUnit/src/include/cppunit/TestAssert.h
@@ -5,14 +5,20 @@
#include <cppunit/Exception.h>
#include <cppunit/Asserter.h>
#include <cppunit/portability/Stream.h>
+#include <cppunit/tools/StringHelper.h>
#include <stdio.h>
#include <float.h> // For struct assertion_traits<double>
+// Work around "passing 'T' chooses 'int' over 'unsigned int'" warnings when T
+// is an enum type:
+#if defined __GNUC__ && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6))
+#pragma GCC system_header
+#endif
-CPPUNIT_NS_BEGIN
+CPPUNIT_NS_BEGIN
-/*! \brief Traits used by CPPUNIT_ASSERT_EQUAL().
+/*! \brief Traits used by CPPUNIT_ASSERT* macros.
*
* Here is an example of specialising these traits:
*
@@ -24,7 +30,17 @@ CPPUNIT_NS_BEGIN
* {
* return x == y;
* }
- *
+ *
+ * static bool less( const std::string& x, const std::string& y )
+ * {
+ * return x < y;
+ * }
+ *
+ * static bool lessEqual( const std::string& x, const std::string& y )
+ * {
+ * return x <= y;
+ * }
+ *
* static std::string toString( const std::string& x )
* {
* std::string text = '"' + x + '"'; // adds quote around the string to see whitespace
@@ -43,15 +59,22 @@ struct assertion_traits
return x == y;
}
+ static bool less( const T& x, const T& y )
+ {
+ return x < y;
+ }
+
+ static bool lessEqual( const T& x, const T& y )
+ {
+ return x <= y;
+ }
+
static std::string toString( const T& x )
{
- OStringStream ost;
- ost << x;
- return ost.str();
+ return CPPUNIT_NS::StringHelper::toString(x);
}
};
-
/*! \brief Traits used by CPPUNIT_ASSERT_DOUBLES_EQUAL().
*
* This specialisation from @c struct @c assertion_traits<> ensures that
@@ -68,6 +91,16 @@ struct assertion_traits<double>
return x == y;
}
+ static bool less( double x, double y )
+ {
+ return x < y;
+ }
+
+ static bool lessEqual( double x, double y )
+ {
+ return x <= y;
+ }
+
static std::string toString( double x )
{
#ifdef DBL_DIG
@@ -118,6 +151,82 @@ void CPPUNIT_API assertDoubleEquals( double expected,
const std::string &message );
+/*! \brief (Implementation) Asserts that an object is less than another one of the same type
+ * Use CPPUNIT_ASSERT_LESS, CPPUNIT_ASSERT_GREATER instead of this function.
+ * \sa assertion_traits, Asserter::failNotLess().
+ */
+template <class T>
+void assertLess( const T& expected,
+ const T& actual,
+ SourceLine sourceLine,
+ const std::string& message )
+{
+ if ( !assertion_traits<T>::less(actual,expected) )
+ {
+ Asserter::failNotLess( assertion_traits<T>::toString(expected),
+ assertion_traits<T>::toString(actual),
+ sourceLine,
+ message );
+ }
+}
+
+
+/*! \brief (Implementation) Asserts that an object is less than another one of the same type
+ * Use CPPUNIT_ASSERT_LESS, CPPUNIT_ASSERT_GREATER instead of this function.
+ * \sa assertion_traits, Asserter::failNotLess().
+ */
+template <class T>
+void assertGreater( const T& expected,
+ const T& actual,
+ SourceLine sourceLine,
+ const std::string& message )
+{
+ if ( !assertion_traits<T>::less(expected,actual) )
+ {
+ Asserter::failNotGreater( assertion_traits<T>::toString(expected),
+ assertion_traits<T>::toString(actual),
+ sourceLine,
+ message );
+ }
+}
+
+/*! \brief (Implementation) Asserts that two objects of the same type are equals.
+ * Use CPPUNIT_ASSERT_LESSEQUAL, CPPUNIT_ASSERT_GREATEREQUAL instead of this function.
+ * \sa assertion_traits, Asserter::failNotLessEqual().
+ */
+template <class T>
+void assertLessEqual( const T& expected,
+ const T& actual,
+ SourceLine sourceLine,
+ const std::string& message )
+{
+ if ( !assertion_traits<T>::lessEqual(actual,expected) )
+ {
+ Asserter::failNotLessEqual( assertion_traits<T>::toString(expected),
+ assertion_traits<T>::toString(actual),
+ sourceLine,
+ message );
+ }
+}
+
+/*! \brief (Implementation) Asserts that two objects of the same type are equals.
+ * Use CPPUNIT_ASSERT_LESSEQUAL, CPPUNIT_ASSERT_GREATEREQUAL instead of this function.
+ * \sa assertion_traits, Asserter::failNotLessEqual().
+ */
+template <class T>
+void assertGreaterEqual( const T& expected,
+ const T& actual,
+ SourceLine sourceLine,
+ const std::string& message )
+{
+ if ( !assertion_traits<T>::lessEqual(expected,actual) )
+ {
+ Asserter::failNotGreaterEqual( assertion_traits<T>::toString(expected),
+ assertion_traits<T>::toString(actual),
+ sourceLine,
+ message );
+ }
+}
/* A set of macros which allow us to get the line number
* and file name at the point of an error.
* Just goes to show that preprocessors do have some
@@ -217,6 +326,109 @@ void CPPUNIT_API assertDoubleEquals( double expected,
(message) ) )
#endif
+/** Asserts that actual is less than expected, provides additional message on failure.
+ * \ingroup Assertions
+ *
+ * Less and string representation can be defined with
+ * an appropriate assertion_traits class.
+ *
+ * A diagnostic is printed if actual is less than expected.
+ * The message is printed in addition to the expected and actual value
+ * to provide additional information.
+ *
+ * Requirement for \a expected and \a actual parameters:
+ * - They are exactly of the same type
+ * - They are serializable into a std::strstream using operator <<.
+ * - They can be compared using operator <.
+ *
+ * The last two requirements (serialization and comparison) can be
+ * removed by specializing the CppUnit::assertion_traits.
+ *
+ * \sa CPPUNIT_ASSERT_GREATER
+ */
+#define CPPUNIT_ASSERT_LESS(expected, actual) \
+ ( CPPUNIT_NS::assertLess( (expected), \
+ (actual), \
+ CPPUNIT_SOURCELINE(), \
+ "" ) )
+
+/** Asserts that actual is greater than expected, provides additional message on failure.
+ * \ingroup Assertions
+ *
+ * String representation can be defined with
+ * an appropriate assertion_traits class. For comparison assertLess is used.
+ *
+ * A diagnostic is printed if actual is less than expected.
+ * The message is printed in addition to the expected and actual value
+ * to provide additional information.
+ *
+ * Requirement for \a expected and \a actual parameters:
+ * - They are exactly of the same type
+ * - They are serializable into a std::strstream using operator <<.
+ * - They can be compared using operator<.
+ *
+ * The last two requirements (serialization and comparison) can be
+ * removed by specializing the CppUnit::assertion_traits.
+ *
+ * \sa CPPUNIT_ASSERT_LESS
+ */
+#define CPPUNIT_ASSERT_GREATER(expected, actual) \
+ ( CPPUNIT_NS::assertGreater( (expected), \
+ (actual), \
+ CPPUNIT_SOURCELINE(), \
+ "" ) )
+
+/** Asserts that actual is less or equal than expected, provides additional message on failure.
+ * \ingroup Assertions
+ *
+ * LessEqual and string representation can be defined with
+ * an appropriate assertion_traits class.
+ *
+ * A diagnostic is printed if actual is greater than expected.
+ * The message is printed in addition to the expected and actual value
+ * to provide additional information.
+ *
+ * Requirement for \a expected and \a actual parameters:
+ * - They are exactly of the same type
+ * - They are serializable into a std::strstream using operator <<.
+ * - They can be compared using operator <=.
+ *
+ * The last two requirements (serialization and comparison) can be
+ * removed by specializing the CppUnit::assertion_traits.
+ *
+ * \sa CPPUNIT_ASSERT_GREATEREQUAL
+ */
+#define CPPUNIT_ASSERT_LESSEQUAL(expected, actual) \
+ ( CPPUNIT_NS::assertLessEqual( (expected), \
+ (actual), \
+ CPPUNIT_SOURCELINE(), \
+ "" ) )
+
+/** Asserts that actual is greater than expected, provides additional message on failure.
+ * \ingroup Assertions
+ *
+ * String representation can be defined with
+ * an appropriate assertion_traits class. For comparison assertLess is used.
+ *
+ * A diagnostic is printed if actual is less than expected.
+ * The message is printed in addition to the expected and actual value
+ * to provide additional information.
+ *
+ * Requirement for \a expected and \a actual parameters:
+ * - They are exactly of the same type
+ * - They are serializable into a std::strstream using operator <<.
+ * - They can be compared using operator<=.
+ *
+ * The last two requirements (serialization and comparison) can be
+ * removed by specializing the CppUnit::assertion_traits.
+ *
+ * \sa CPPUNIT_ASSERT_LESSEQUAL
+ */
+#define CPPUNIT_ASSERT_GREATEREQUAL(expected, actual) \
+ ( CPPUNIT_NS::assertGreaterEqual( (expected), \
+ (actual), \
+ CPPUNIT_SOURCELINE(), \
+ "" ) )
/*! \brief Macro for primitive double value comparisons.
* \ingroup Assertions
*
@@ -263,7 +475,7 @@ void CPPUNIT_API assertDoubleEquals( double expected,
// implementation detail
-#if CPPUNIT_USE_TYPEINFO_NAME
+#if defined(CPPUNIT_USE_TYPEINFO_NAME)
#define CPPUNIT_EXTRACT_EXCEPTION_TYPE_( exception, no_rtti_message ) \
CPPUNIT_NS::TypeInfoHelper::getClassName( typeid(exception) )
#else
diff --git a/3rdParty/CppUnit/src/include/cppunit/TestCaller.h b/3rdParty/CppUnit/src/include/cppunit/TestCaller.h
index dc4d82e..fbf3902 100644
--- a/3rdParty/CppUnit/src/include/cppunit/TestCaller.h
+++ b/3rdParty/CppUnit/src/include/cppunit/TestCaller.h
@@ -4,8 +4,10 @@
#include <cppunit/Exception.h>
#include <cppunit/TestCase.h>
+#include <functional>
-#if CPPUNIT_USE_TYPEINFO_NAME
+
+#if defined(CPPUNIT_USE_TYPEINFO_NAME)
# include <cppunit/extensions/TypeInfoHelper.h>
#endif
@@ -33,7 +35,7 @@ struct ExpectedExceptionTraits
{
static void expectedException()
{
-#if CPPUNIT_USE_TYPEINFO_NAME
+#if defined(CPPUNIT_USE_TYPEINFO_NAME)
throw Exception( Message(
"expected exception not thrown",
"Expected exception type: " +
@@ -116,7 +118,7 @@ public:
TestCase( name ),
m_ownFixture( true ),
m_fixture( new Fixture() ),
- m_test( test )
+ m_test_function( std::bind(test, m_fixture) )
{
}
@@ -133,7 +135,7 @@ public:
TestCase( name ),
m_ownFixture( false ),
m_fixture( &fixture ),
- m_test( test )
+ m_test_function( std::bind(test, &fixture) )
{
}
@@ -150,9 +152,17 @@ public:
TestCase( name ),
m_ownFixture( true ),
m_fixture( fixture ),
- m_test( test )
+ m_test_function( std::bind(test, fixture) )
{
}
+
+ TestCaller(std::string name, std::function<void()> test_function, Fixture* fixture):
+ TestCase(name),
+ m_ownFixture(true),
+ m_fixture(fixture),
+ m_test_function(test_function)
+ {
+ }
~TestCaller()
{
@@ -162,14 +172,7 @@ public:
void runTest()
{
-// try {
- (m_fixture->*m_test)();
-// }
-// catch ( ExpectedException & ) {
-// return;
-// }
-
-// ExpectedExceptionTraits<ExpectedException>::expectedException();
+ m_test_function();
}
void setUp()
@@ -194,7 +197,7 @@ private:
private:
bool m_ownFixture;
Fixture *m_fixture;
- TestMethod m_test;
+ std::function<void()> m_test_function;
};
diff --git a/3rdParty/CppUnit/src/include/cppunit/TestPath.h b/3rdParty/CppUnit/src/include/cppunit/TestPath.h
index c3c851c..8934479 100644
--- a/3rdParty/CppUnit/src/include/cppunit/TestPath.h
+++ b/3rdParty/CppUnit/src/include/cppunit/TestPath.h
@@ -8,7 +8,7 @@
#pragma warning( disable: 4251 ) // X needs to have dll-interface to be used by clients of class Z
#endif
-#include <cppunit/portability/CppUnitDeque.h>
+#include <deque>
#include <string>
CPPUNIT_NS_BEGIN
@@ -16,11 +16,6 @@ CPPUNIT_NS_BEGIN
class Test;
-#if CPPUNIT_NEED_DLL_DECL
-// template class CPPUNIT_API std::deque<Test *>;
-#endif
-
-
/*! \brief A List of Test representing a path to access a Test.
* \ingroup ExecutingTest
*
@@ -174,7 +169,7 @@ protected:
void checkIndexValid( int index ) const;
/// A list of test names.
- typedef CppUnitDeque<std::string> PathTestNames;
+ typedef std::deque<std::string> PathTestNames;
/*! \brief Splits a path string into its test name components.
* \param pathAsString Path string created with toString().
@@ -199,7 +194,7 @@ protected:
PathTestNames &testNames );
protected:
- typedef CppUnitDeque<Test *> Tests;
+ typedef std::deque<Test *> Tests;
Tests m_tests;
};
diff --git a/3rdParty/CppUnit/src/include/cppunit/TestResult.h b/3rdParty/CppUnit/src/include/cppunit/TestResult.h
index e7e1050..aabd80b 100644
--- a/3rdParty/CppUnit/src/include/cppunit/TestResult.h
+++ b/3rdParty/CppUnit/src/include/cppunit/TestResult.h
@@ -9,7 +9,7 @@
#endif
#include <cppunit/SynchronizedObject.h>
-#include <cppunit/portability/CppUnitDeque.h>
+#include <deque>
#include <string>
CPPUNIT_NS_BEGIN
@@ -24,10 +24,6 @@ class TestFailure;
class TestListener;
-#if CPPUNIT_NEED_DLL_DECL
-// template class CPPUNIT_API std::deque<TestListener *>;
-#endif
-
/*! \brief Manages TestListener.
* \ingroup TrackingTestExecution
*
@@ -133,7 +129,7 @@ protected:
virtual void endTestRun( Test *test );
protected:
- typedef CppUnitDeque<TestListener *> TestListeners;
+ typedef std::deque<TestListener *> TestListeners;
TestListeners m_listeners;
ProtectorChain *m_protectorChain;
bool m_stop;
diff --git a/3rdParty/CppUnit/src/include/cppunit/TestResultCollector.h b/3rdParty/CppUnit/src/include/cppunit/TestResultCollector.h
index 01b0a54..b78c978 100644
--- a/3rdParty/CppUnit/src/include/cppunit/TestResultCollector.h
+++ b/3rdParty/CppUnit/src/include/cppunit/TestResultCollector.h
@@ -9,16 +9,11 @@
#endif
#include <cppunit/TestSuccessListener.h>
-#include <cppunit/portability/CppUnitDeque.h>
+#include <deque>
CPPUNIT_NS_BEGIN
-#if CPPUNIT_NEED_DLL_DECL
-// template class CPPUNIT_API std::deque<TestFailure *>;
-// template class CPPUNIT_API std::deque<Test *>;
-#endif
-
/*! \brief Collects test result.
* \ingroup WritingTestResult
@@ -36,8 +31,8 @@ CPPUNIT_NS_BEGIN
class CPPUNIT_API TestResultCollector : public TestSuccessListener
{
public:
- typedef CppUnitDeque<TestFailure *> TestFailures;
- typedef CppUnitDeque<Test *> Tests;
+ typedef std::deque<TestFailure *> TestFailures;
+ typedef std::deque<Test *> Tests;
/*! Constructs a TestResultCollector object.
diff --git a/3rdParty/CppUnit/src/include/cppunit/TestSuite.h b/3rdParty/CppUnit/src/include/cppunit/TestSuite.h
index 2b9cd8d..63c0a6b 100644
--- a/3rdParty/CppUnit/src/include/cppunit/TestSuite.h
+++ b/3rdParty/CppUnit/src/include/cppunit/TestSuite.h
@@ -9,7 +9,7 @@
#endif
#include <cppunit/TestComposite.h>
-#include <cppunit/portability/CppUnitVector.h>
+#include <vector>
CPPUNIT_NS_BEGIN
@@ -56,7 +56,7 @@ public:
* TestComposite interface instead.
* \return Reference on a vector that contains the tests of the suite.
*/
- const CppUnitVector<Test *> &getTests() const;
+ const std::vector<Test *> &getTests() const;
/*! Destroys all the tests of the suite.
*/
@@ -67,7 +67,7 @@ public:
Test *doGetChildTestAt( int index ) const;
private:
- CppUnitVector<Test *> m_tests;
+ std::vector<Test *> m_tests;
};
diff --git a/3rdParty/CppUnit/src/include/cppunit/TextTestResult.h b/3rdParty/CppUnit/src/include/cppunit/TextTestResult.h
index e7b1fa3..63937b0 100644
--- a/3rdParty/CppUnit/src/include/cppunit/TextTestResult.h
+++ b/3rdParty/CppUnit/src/include/cppunit/TextTestResult.h
@@ -26,6 +26,8 @@ public:
virtual void addFailure( const TestFailure &failure );
virtual void startTest( Test *test );
virtual void print( OStream &stream );
+
+ using TestResult::addFailure;
};
/** insertion operator for easy output */
diff --git a/3rdParty/CppUnit/src/include/cppunit/XmlOutputter.h b/3rdParty/CppUnit/src/include/cppunit/XmlOutputter.h
index 0de9676..2bf9411 100644
--- a/3rdParty/CppUnit/src/include/cppunit/XmlOutputter.h
+++ b/3rdParty/CppUnit/src/include/cppunit/XmlOutputter.h
@@ -9,8 +9,8 @@
#endif
#include <cppunit/Outputter.h>
-#include <cppunit/portability/CppUnitDeque.h>
-#include <cppunit/portability/CppUnitMap.h>
+#include <deque>
+#include <map>
#include <cppunit/portability/Stream.h>
@@ -46,7 +46,7 @@ public:
*/
XmlOutputter( TestResultCollector *result,
OStream &stream,
- std::string encoding = std::string("ISO-8859-1") );
+ const std::string& encoding = std::string("ISO-8859-1") );
/// Destructor.
virtual ~XmlOutputter();
@@ -85,7 +85,7 @@ public:
*/
virtual void setStandalone( bool standalone );
- typedef CppUnitMap<Test *,TestFailure*, std::less<Test*> > FailedTests;
+ typedef std::map<Test *,TestFailure*, std::less<Test*> > FailedTests;
/*! \brief Sets the root element and adds its children.
*
@@ -137,7 +137,7 @@ protected:
virtual void fillFailedTestsMap( FailedTests &failedTests );
protected:
- typedef CppUnitDeque<XmlOutputterHook *> Hooks;
+ typedef std::deque<XmlOutputterHook *> Hooks;
TestResultCollector *m_result;
OStream &m_stream;
diff --git a/3rdParty/CppUnit/src/include/cppunit/config-auto.h b/3rdParty/CppUnit/src/include/cppunit/config-auto.h
deleted file mode 100644
index 58b3d6e..0000000
--- a/3rdParty/CppUnit/src/include/cppunit/config-auto.h
+++ /dev/null
@@ -1,161 +0,0 @@
-#ifndef _INCLUDE_CPPUNIT_CONFIG_AUTO_H
-#define _INCLUDE_CPPUNIT_CONFIG_AUTO_H 1
-
-/* include/cppunit/config-auto.h. Generated automatically at end of configure. */
-/* config/config.h. Generated by configure. */
-/* config/config.h.in. Generated from configure.in by autoheader. */
-
-/* define if library uses std::string::compare(string,pos,n) */
-/* #undef CPPUNIT_FUNC_STRING_COMPARE_STRING_FIRST */
-
-
-#define CPPUNIT_HAVE_CPP_CAST
-
-/* define if the library defines strstream */
-#ifndef CPPUNIT_HAVE_CLASS_STRSTREAM
-#define CPPUNIT_HAVE_CLASS_STRSTREAM 1
-#endif
-
-/* Define to 1 if you have the <cmath> header file. */
-#ifndef CPPUNIT_HAVE_CMATH
-#define CPPUNIT_HAVE_CMATH 1
-#endif
-
-/* Define if you have the GNU dld library. */
-/* #undef CPPUNIT_HAVE_DLD */
-
-/* Define to 1 if you have the `dlerror' function. */
-#ifndef CPPUNIT_HAVE_DLERROR
-#define CPPUNIT_HAVE_DLERROR 1
-#endif
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#ifndef CPPUNIT_HAVE_DLFCN_H
-#define CPPUNIT_HAVE_DLFCN_H 1
-#endif
-
-/* define if the compiler supports GCC C++ ABI name demangling */
-#ifndef CPPUNIT_HAVE_GCC_ABI_DEMANGLE
-#define CPPUNIT_HAVE_GCC_ABI_DEMANGLE 1
-#endif
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#ifndef CPPUNIT_HAVE_INTTYPES_H
-#define CPPUNIT_HAVE_INTTYPES_H 1
-#endif
-
-/* Define if you have the libdl library or equivalent. */
-#ifndef CPPUNIT_HAVE_LIBDL
-#define CPPUNIT_HAVE_LIBDL 1
-#endif
-
-/* Define to 1 if you have the <memory.h> header file. */
-#ifndef CPPUNIT_HAVE_MEMORY_H
-#define CPPUNIT_HAVE_MEMORY_H 1
-#endif
-
-/* define to 1 if the compiler implements namespaces */
-#ifndef CPPUNIT_HAVE_NAMESPACES
-#define CPPUNIT_HAVE_NAMESPACES 1
-#endif
-
-/* define if the compiler supports Run-Time Type Identification */
-#ifndef CPPUNIT_HAVE_RTTI
-#define CPPUNIT_HAVE_RTTI 1
-#endif
-
-/* Define if you have the shl_load function. */
-/* #undef CPPUNIT_HAVE_SHL_LOAD */
-
-/* define if the compiler has stringstream */
-#ifndef CPPUNIT_HAVE_SSTREAM
-#define CPPUNIT_HAVE_SSTREAM 1
-#endif
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#ifndef CPPUNIT_HAVE_STDINT_H
-#define CPPUNIT_HAVE_STDINT_H 1
-#endif
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#ifndef CPPUNIT_HAVE_STDLIB_H
-#define CPPUNIT_HAVE_STDLIB_H 1
-#endif
-
-/* Define to 1 if you have the <strings.h> header file. */
-#ifndef CPPUNIT_HAVE_STRINGS_H
-#define CPPUNIT_HAVE_STRINGS_H 1
-#endif
-
-/* Define to 1 if you have the <string.h> header file. */
-#ifndef CPPUNIT_HAVE_STRING_H
-#define CPPUNIT_HAVE_STRING_H 1
-#endif
-
-/* Define to 1 if you have the <strstream> header file. */
-#ifndef CPPUNIT_HAVE_STRSTREAM
-#define CPPUNIT_HAVE_STRSTREAM 1
-#endif
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#ifndef CPPUNIT_HAVE_SYS_STAT_H
-#define CPPUNIT_HAVE_SYS_STAT_H 1
-#endif
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#ifndef CPPUNIT_HAVE_SYS_TYPES_H
-#define CPPUNIT_HAVE_SYS_TYPES_H 1
-#endif
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#ifndef CPPUNIT_HAVE_UNISTD_H
-#define CPPUNIT_HAVE_UNISTD_H 1
-#endif
-
-/* Name of package */
-#ifndef CPPUNIT_PACKAGE
-#define CPPUNIT_PACKAGE "cppunit"
-#endif
-
-/* Define to the address where bug reports for this package should be sent. */
-#ifndef CPPUNIT_PACKAGE_BUGREPORT
-#define CPPUNIT_PACKAGE_BUGREPORT ""
-#endif
-
-/* Define to the full name of this package. */
-#ifndef CPPUNIT_PACKAGE_NAME
-#define CPPUNIT_PACKAGE_NAME ""
-#endif
-
-/* Define to the full name and version of this package. */
-#ifndef CPPUNIT_PACKAGE_STRING
-#define CPPUNIT_PACKAGE_STRING ""
-#endif
-
-/* Define to the one symbol short name of this package. */
-#ifndef CPPUNIT_PACKAGE_TARNAME
-#define CPPUNIT_PACKAGE_TARNAME ""
-#endif
-
-/* Define to the version of this package. */
-#ifndef CPPUNIT_PACKAGE_VERSION
-#define CPPUNIT_PACKAGE_VERSION ""
-#endif
-
-/* Define to 1 if you have the ANSI C header files. */
-#ifndef CPPUNIT_STDC_HEADERS
-#define CPPUNIT_STDC_HEADERS 1
-#endif
-
-/* Define to 1 to use type_info::name() for class names */
-#ifndef CPPUNIT_USE_TYPEINFO_NAME
-#define CPPUNIT_USE_TYPEINFO_NAME CPPUNIT_HAVE_RTTI
-#endif
-
-/* Version number of package */
-#ifndef CPPUNIT_VERSION
-#define CPPUNIT_VERSION "1.12.0"
-#endif
-
-/* _INCLUDE_CPPUNIT_CONFIG_AUTO_H */
-#endif
diff --git a/3rdParty/CppUnit/src/include/cppunit/config/SelectDllLoader.h b/3rdParty/CppUnit/src/include/cppunit/config/SelectDllLoader.h
index dc1c011..9f8c0d6 100644
--- a/3rdParty/CppUnit/src/include/cppunit/config/SelectDllLoader.h
+++ b/3rdParty/CppUnit/src/include/cppunit/config/SelectDllLoader.h
@@ -15,9 +15,6 @@
* CPPUNIT_HAVE_WIN32_DLL_LOADER
* If defined, Win32 implementation of DynamicLibraryManager will be used.
*
- * CPPUNIT_HAVE_BEOS_DLL_LOADER
- * If defined, BeOs implementation of DynamicLibraryManager will be used.
- *
* CPPUNIT_HAVE_UNIX_DLL_LOADER
* If defined, Unix implementation (dlfcn.h) of DynamicLibraryManager will be used.
*/
@@ -50,10 +47,6 @@
#undef CPPUNIT_PLUGIN_EXPORT
#define CPPUNIT_PLUGIN_EXPORT extern "C" __declspec(dllexport)
-// Is BeOS platform ?
-#elif defined(__BEOS__)
-#define CPPUNIT_HAVE_BEOS_DLL_LOADER 1
-
// Is Unix platform and have shl_load() (hp-ux)
#elif defined(CPPUNIT_HAVE_SHL_LOAD)
#define CPPUNIT_HAVE_UNIX_SHL_LOADER 1
diff --git a/3rdParty/CppUnit/src/include/cppunit/config/config-msvc6.h b/3rdParty/CppUnit/src/include/cppunit/config/config-msvc6.h
index d688171..0edc059 100644
--- a/3rdParty/CppUnit/src/include/cppunit/config/config-msvc6.h
+++ b/3rdParty/CppUnit/src/include/cppunit/config/config-msvc6.h
@@ -30,20 +30,6 @@
#define CPPUNIT_HAVE_NAMESPACES 1
#endif
-/* define if the compiler supports Run-Time Type Identification */
-#ifndef CPPUNIT_HAVE_RTTI
-# ifdef _CPPRTTI // Defined by the compiler option /GR
-# define CPPUNIT_HAVE_RTTI 1
-# else
-# define CPPUNIT_HAVE_RTTI 0
-# endif
-#endif
-
-/* Define to 1 to use type_info::name() for class names */
-#ifndef CPPUNIT_USE_TYPEINFO_NAME
-#define CPPUNIT_USE_TYPEINFO_NAME CPPUNIT_HAVE_RTTI
-#endif
-
#define CPPUNIT_HAVE_SSTREAM 1
/* Name of package */
@@ -73,11 +59,12 @@
// Uncomment to turn on STL wrapping => use this to test compilation.
// This will make CppUnit subclass std::vector & co to provide default
// parameter.
-/*#define CPPUNIT_STD_NEED_ALLOCATOR 1
-#define CPPUNIT_STD_ALLOCATOR std::allocator<T>
-//#define CPPUNIT_NO_NAMESPACE 1
+/*#define CPPUNIT_NO_NAMESPACE 1
*/
+#if _MSC_VER >= 1300 // VS 7.0
+#define CPPUNIT_UNIQUE_COUNTER __COUNTER__
+#endif // if _MSC_VER >= 1300 // VS 7.0
/* _INCLUDE_CPPUNIT_CONFIG_MSVC6_H */
#endif
diff --git a/3rdParty/CppUnit/src/include/cppunit/extensions/ExceptionTestCaseDecorator.h b/3rdParty/CppUnit/src/include/cppunit/extensions/ExceptionTestCaseDecorator.h
index 9c816ad..a3f2b3e 100644
--- a/3rdParty/CppUnit/src/include/cppunit/extensions/ExceptionTestCaseDecorator.h
+++ b/3rdParty/CppUnit/src/include/cppunit/extensions/ExceptionTestCaseDecorator.h
@@ -76,7 +76,7 @@ public:
// Moved outside the try{} statement to handle the case where the
// expected exception type is Exception (expecting assertion failure).
-#if CPPUNIT_USE_TYPEINFO_NAME
+#if defined(CPPUNIT_USE_TYPEINFO_NAME)
throw Exception( Message(
"expected exception not thrown",
"Expected exception type: " +
@@ -92,7 +92,7 @@ private:
*
* Should be overriden to check the exception.
*/
- virtual void checkException( ExpectedExceptionType &e )
+ virtual void checkException( ExpectedExceptionType & )
{
}
};
diff --git a/3rdParty/CppUnit/src/include/cppunit/extensions/HelperMacros.h b/3rdParty/CppUnit/src/include/cppunit/extensions/HelperMacros.h
index 12431e4..4c30319 100644
--- a/3rdParty/CppUnit/src/include/cppunit/extensions/HelperMacros.h
+++ b/3rdParty/CppUnit/src/include/cppunit/extensions/HelperMacros.h
@@ -166,17 +166,18 @@
#define CPPUNIT_TEST_SUITE_END() \
} \
\
+public: \
static CPPUNIT_NS::TestSuite *suite() \
{ \
const CPPUNIT_NS::TestNamer &namer = getTestNamer__(); \
- std::auto_ptr<CPPUNIT_NS::TestSuite> suite( \
- new CPPUNIT_NS::TestSuite( namer.getFixtureName() )); \
+ std::unique_ptr<CPPUNIT_NS::TestSuite> guard( \
+ new CPPUNIT_NS::TestSuite( namer.getFixtureName() )); \
CPPUNIT_NS::ConcretTestFixtureFactory<TestFixtureType> factory; \
- CPPUNIT_NS::TestSuiteBuilderContextBase context( *suite.get(), \
+ CPPUNIT_NS::TestSuiteBuilderContextBase context( *guard.get(), \
namer, \
factory ); \
TestFixtureType::addTestsToSuite( context ); \
- return suite.release(); \
+ return guard.release(); \
} \
private: /* dummy typedef so that the macro can still end with ';'*/ \
typedef int CppUnitDummyTypedefForSemiColonEnding__
@@ -300,6 +301,17 @@
&TestFixtureType::testMethod, \
context.makeFixture() ) ) )
+#define CPPUNIT_TEST_PARAMETERIZED( testMethod, ... ) \
+ for (auto& i : __VA_ARGS__) \
+ { \
+ TestFixtureType* fixture = context.makeFixture(); \
+ CPPUNIT_TEST_SUITE_ADD_TEST( \
+ ( new CPPUNIT_NS::TestCaller<TestFixtureType>( \
+ context.getTestNameFor(#testMethod, i), \
+ std::bind(&TestFixtureType::testMethod, fixture, i), \
+ fixture))); \
+ }
+
/*! \brief Add a test which fail if the specified exception is not caught.
*
* Example:
@@ -308,13 +320,13 @@
* #include <vector>
* class MyTest : public CppUnit::TestFixture {
* CPPUNIT_TEST_SUITE( MyTest );
- * CPPUNIT_TEST_EXCEPTION( testVectorAtThrow, std::invalid_argument );
+ * CPPUNIT_TEST_EXCEPTION( testVectorAtThrow, std::out_of_range );
* CPPUNIT_TEST_SUITE_END();
* public:
* void testVectorAtThrow()
* {
* std::vector<int> v;
- * v.at( 1 ); // must throw exception std::invalid_argument
+ * v.at( 1 ); // must throw exception std::out_of_range
* }
* };
* \endcode
diff --git a/3rdParty/CppUnit/src/include/cppunit/extensions/TestCaseDecorator.h b/3rdParty/CppUnit/src/include/cppunit/extensions/TestCaseDecorator.h
index 3a15ba9..effde25 100644
--- a/3rdParty/CppUnit/src/include/cppunit/extensions/TestCaseDecorator.h
+++ b/3rdParty/CppUnit/src/include/cppunit/extensions/TestCaseDecorator.h
@@ -13,7 +13,7 @@ CPPUNIT_NS_BEGIN
* of a test class without subclassing the test. Instead, one can
* subclass the decorater and use it to wrap the test class.
*
- * Does not assume ownership of the test it decorates
+ * Assumes ownership of the test it decorates
*/
class CPPUNIT_API TestCaseDecorator : public TestCase
{
@@ -31,6 +31,13 @@ public:
protected:
TestCase *m_test;
+
+private:
+
+ //prevent the creation of copy c'tor and operator=
+ TestCaseDecorator( const TestCaseDecorator& );
+ TestCaseDecorator& operator=( const TestCaseDecorator& );
+
};
diff --git a/3rdParty/CppUnit/src/include/cppunit/extensions/TestFactoryRegistry.h b/3rdParty/CppUnit/src/include/cppunit/extensions/TestFactoryRegistry.h
index fc8723e..9d10c94 100644
--- a/3rdParty/CppUnit/src/include/cppunit/extensions/TestFactoryRegistry.h
+++ b/3rdParty/CppUnit/src/include/cppunit/extensions/TestFactoryRegistry.h
@@ -8,7 +8,7 @@
#pragma warning( disable: 4251) // X needs to have dll-interface to be used by clients of class Z
#endif
-#include <cppunit/portability/CppUnitSet.h>
+#include <set>
#include <cppunit/extensions/TestFactory.h>
#include <string>
@@ -17,11 +17,6 @@ CPPUNIT_NS_BEGIN
class TestSuite;
-#if CPPUNIT_NEED_DLL_DECL
-// template class CPPUNIT_API std::set<TestFactory *>;
-#endif
-
-
/*! \brief Registry for TestFactory.
* \ingroup CreatingTestSuite
*
@@ -165,7 +160,7 @@ private:
void operator =( const TestFactoryRegistry &copy );
private:
- typedef CppUnitSet<TestFactory *, std::less<TestFactory*> > Factories;
+ typedef std::set<TestFactory *, std::less<TestFactory*> > Factories;
Factories m_factories;
std::string m_name;
diff --git a/3rdParty/CppUnit/src/include/cppunit/extensions/TestNamer.h b/3rdParty/CppUnit/src/include/cppunit/extensions/TestNamer.h
index 5a6471c..0c8fb31 100644
--- a/3rdParty/CppUnit/src/include/cppunit/extensions/TestNamer.h
+++ b/3rdParty/CppUnit/src/include/cppunit/extensions/TestNamer.h
@@ -3,20 +3,16 @@
#include <cppunit/Portability.h>
#include <string>
+#include <cppunit/tools/StringHelper.h>
-#if CPPUNIT_HAVE_RTTI
-# include <typeinfo>
-#endif
+#include <typeinfo>
/*! \def CPPUNIT_TESTNAMER_DECL( variableName, FixtureType )
* \brief Declares a TestNamer.
*
- * Declares a TestNamer for the specified type, using RTTI if enabled, otherwise
- * using macro string expansion.
- *
- * RTTI is used if CPPUNIT_USE_TYPEINFO_NAME is defined and not null.
+ * Declares a TestNamer for the specified type
*
* \code
* void someMethod()
@@ -29,19 +25,11 @@
* \relates TestNamer
* \see TestNamer
*/
-#if CPPUNIT_USE_TYPEINFO_NAME
# define CPPUNIT_TESTNAMER_DECL( variableName, FixtureType ) \
CPPUNIT_NS::TestNamer variableName( typeid(FixtureType) )
-#else
-# define CPPUNIT_TESTNAMER_DECL( variableName, FixtureType ) \
- CPPUNIT_NS::TestNamer variableName( std::string(#FixtureType) )
-#endif
-
-
CPPUNIT_NS_BEGIN
-
/*! \brief Names a test or a fixture suite.
*
* TestNamer is usually instantiated using CPPUNIT_TESTNAMER_DECL.
@@ -50,12 +38,10 @@ CPPUNIT_NS_BEGIN
class CPPUNIT_API TestNamer
{
public:
-#if CPPUNIT_HAVE_RTTI
/*! \brief Constructs a namer using the fixture's type-info.
* \param typeInfo Type-info of the fixture type. Use to name the fixture suite.
*/
TestNamer( const std::type_info &typeInfo );
-#endif
/*! \brief Constructs a namer using the specified fixture name.
* \param fixtureName Name of the fixture suite. Usually extracted using a macro.
@@ -78,11 +64,16 @@ public:
*/
virtual std::string getTestNameFor( const std::string &testMethodName ) const;
+ template<typename E>
+ std::string getTestNameFor( const std::string& testMethodName, const E& val) const
+ {
+ return getTestNameFor(testMethodName) + " with parameter: " + CPPUNIT_NS::StringHelper::toString(val);
+ }
+
protected:
std::string m_fixtureName;
};
-
CPPUNIT_NS_END
#endif // CPPUNIT_EXTENSIONS_TESTNAMER_H
diff --git a/3rdParty/CppUnit/src/include/cppunit/extensions/TestSuiteBuilderContext.h b/3rdParty/CppUnit/src/include/cppunit/extensions/TestSuiteBuilderContext.h
index db26926..72bfa70 100644
--- a/3rdParty/CppUnit/src/include/cppunit/extensions/TestSuiteBuilderContext.h
+++ b/3rdParty/CppUnit/src/include/cppunit/extensions/TestSuiteBuilderContext.h
@@ -2,7 +2,7 @@
#define CPPUNIT_HELPER_TESTSUITEBUILDERCONTEXT_H
#include <cppunit/Portability.h>
-#include <cppunit/portability/CppUnitMap.h>
+#include <map>
#include <string>
#if CPPUNIT_NEED_DLL_DECL
@@ -62,6 +62,21 @@ public:
*/
std::string getTestNameFor( const std::string &testMethodName ) const;
+ /*! \brief Returns the name of the test for the specified method with the corresponding parameter.
+ *
+ * \param testMethodName Name (including a parameter) of the method that implements a test.
+ * \return A string that is the concatenation of the test fixture name
+ * (returned by getFixtureName()), \a testMethodName,
+ * separated using '::' and the parameter. This provides a fairly unique name for a given
+ * test. The parameter must be convertable to std::string through operator<<
+ * or a specialization of CPPUNIT_NS::StringHelper::toString needs to exist.
+ */
+ template<typename T>
+ std::string getTestNameFor( const std::string &testMethodName, const T& value ) const
+ {
+ return m_namer.getTestNameFor(testMethodName, value);
+ }
+
/*! \brief Adds property pair.
* \param key PropertyKey string to add.
* \param value PropertyValue string to add.
@@ -81,7 +96,7 @@ protected:
// shared std::map in dll bug in VC6.
// See http://www.dinkumware.com/vc_fixes.html for detail.
typedef std::pair<std::string,std::string> Property;
- typedef CppUnitVector<Property> Properties;
+ typedef std::vector<Property> Properties;
TestSuite &m_suite;
const TestNamer &m_namer;
diff --git a/3rdParty/CppUnit/src/include/cppunit/extensions/TypeInfoHelper.h b/3rdParty/CppUnit/src/include/cppunit/extensions/TypeInfoHelper.h
index c0ecdbc..1adec83 100644
--- a/3rdParty/CppUnit/src/include/cppunit/extensions/TypeInfoHelper.h
+++ b/3rdParty/CppUnit/src/include/cppunit/extensions/TypeInfoHelper.h
@@ -3,14 +3,11 @@
#include <cppunit/Portability.h>
-#if CPPUNIT_HAVE_RTTI
-
#include <typeinfo>
#include <string>
CPPUNIT_NS_BEGIN
-
/**! \brief Helper to use type_info.
*/
class CPPUNIT_API TypeInfoHelper
@@ -25,9 +22,6 @@ CPPUNIT_NS_BEGIN
static std::string getClassName( const std::type_info &info );
};
-
CPPUNIT_NS_END
-#endif // CPPUNIT_HAVE_RTTI
-
#endif // CPPUNIT_TYPEINFOHELPER_H
diff --git a/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitDeque.h b/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitDeque.h
deleted file mode 100644
index bbab21f..0000000
--- a/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitDeque.h
+++ /dev/null
@@ -1,25 +0,0 @@
-#ifndef CPPUNIT_PORTABILITY_CPPUNITDEQUE_H
-#define CPPUNIT_PORTABILITY_CPPUNITDEQUE_H
-
-// The technic used is similar to the wrapper of STLPort.
-
-#include <cppunit/Portability.h>
-#include <deque>
-
-
-#if CPPUNIT_STD_NEED_ALLOCATOR
-
-template<class T>
-class CppUnitDeque : public std::deque<T,CPPUNIT_STD_ALLOCATOR>
-{
-public:
-};
-
-#else // CPPUNIT_STD_NEED_ALLOCATOR
-
-#define CppUnitDeque std::deque
-
-#endif
-
-#endif // CPPUNIT_PORTABILITY_CPPUNITDEQUE_H
-
diff --git a/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitMap.h b/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitMap.h
deleted file mode 100644
index 0cdc723..0000000
--- a/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitMap.h
+++ /dev/null
@@ -1,29 +0,0 @@
-#ifndef CPPUNIT_PORTABILITY_CPPUNITMAP_H
-#define CPPUNIT_PORTABILITY_CPPUNITMAP_H
-
-// The technic used is similar to the wrapper of STLPort.
-
-#include <cppunit/Portability.h>
-#include <functional>
-#include <map>
-
-
-#if CPPUNIT_STD_NEED_ALLOCATOR
-
-template<class Key, class T>
-class CppUnitMap : public std::map<Key
- ,T
- ,std::less<Key>
- ,CPPUNIT_STD_ALLOCATOR>
-{
-public:
-};
-
-#else // CPPUNIT_STD_NEED_ALLOCATOR
-
-#define CppUnitMap std::map
-
-#endif
-
-#endif // CPPUNIT_PORTABILITY_CPPUNITMAP_H
-
diff --git a/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitSet.h b/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitSet.h
deleted file mode 100644
index 18b8662..0000000
--- a/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitSet.h
+++ /dev/null
@@ -1,28 +0,0 @@
-#ifndef CPPUNIT_PORTABILITY_CPPUNITSET_H
-#define CPPUNIT_PORTABILITY_CPPUNITSET_H
-
-// The technic used is similar to the wrapper of STLPort.
-
-#include <cppunit/Portability.h>
-#include <functional>
-#include <set>
-
-
-#if CPPUNIT_STD_NEED_ALLOCATOR
-
-template<class T>
-class CppUnitSet : public std::set<T
- ,std::less<T>
- ,CPPUNIT_STD_ALLOCATOR>
-{
-public:
-};
-
-#else // CPPUNIT_STD_NEED_ALLOCATOR
-
-#define CppUnitSet std::set
-
-#endif
-
-#endif // CPPUNIT_PORTABILITY_CPPUNITSET_H
-
diff --git a/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitVector.h b/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitVector.h
deleted file mode 100644
index 6666a63..0000000
--- a/3rdParty/CppUnit/src/include/cppunit/portability/CppUnitVector.h
+++ /dev/null
@@ -1,25 +0,0 @@
-#ifndef CPPUNIT_PORTABILITY_CPPUNITVECTOR_H
-#define CPPUNIT_PORTABILITY_CPPUNITVECTOR_H
-
-// The technic used is similar to the wrapper of STLPort.
-
-#include <cppunit/Portability.h>
-#include <vector>
-
-
-#if CPPUNIT_STD_NEED_ALLOCATOR
-
-template<class T>
-class CppUnitVector : public std::vector<T,CPPUNIT_STD_ALLOCATOR>
-{
-public:
-};
-
-#else // CPPUNIT_STD_NEED_ALLOCATOR
-
-#define CppUnitVector std::vector
-
-#endif
-
-#endif // CPPUNIT_PORTABILITY_CPPUNITVECTOR_H
-
diff --git a/3rdParty/CppUnit/src/include/cppunit/tools/StringHelper.h b/3rdParty/CppUnit/src/include/cppunit/tools/StringHelper.h
new file mode 100644
index 0000000..3301045
--- /dev/null
+++ b/3rdParty/CppUnit/src/include/cppunit/tools/StringHelper.h
@@ -0,0 +1,45 @@
+#ifndef CPPUNIT_TOOLS_STRINGHELPER_H
+#define CPPUNIT_TOOLS_STRINGHELPER_H
+
+#include <cppunit/Portability.h>
+#include <cppunit/portability/Stream.h>
+#include <string>
+#include <type_traits>
+
+
+CPPUNIT_NS_BEGIN
+
+
+/*! \brief Methods for converting values to strings. Replaces CPPUNIT_NS::StringTools::toString
+ */
+namespace StringHelper
+{
+
+// work around to handle C++11 enum class correctly. We need an own conversion to std::string
+// as there is no implicit coversion to int for enum class.
+
+template<typename T>
+typename std::enable_if<!std::is_enum<T>::value, std::string>::type toString(const T& x)
+{
+ OStringStream ost;
+ ost << x;
+
+ return ost.str();
+}
+
+template<typename T>
+typename std::enable_if<std::is_enum<T>::value, std::string>::type toString(const T& x)
+{
+ OStringStream ost;
+ ost << static_cast<typename std::underlying_type<T>::type>(x);
+
+ return ost.str();
+}
+
+}
+
+
+CPPUNIT_NS_END
+
+#endif // CPPUNIT_TOOLS_STRINGHELPER_H
+
diff --git a/3rdParty/CppUnit/src/include/cppunit/tools/StringTools.h b/3rdParty/CppUnit/src/include/cppunit/tools/StringTools.h
index 7a6b6d7..d08c6e0 100644
--- a/3rdParty/CppUnit/src/include/cppunit/tools/StringTools.h
+++ b/3rdParty/CppUnit/src/include/cppunit/tools/StringTools.h
@@ -3,7 +3,7 @@
#include <cppunit/Portability.h>
#include <string>
-#include <cppunit/portability/CppUnitVector.h>
+#include <vector>
CPPUNIT_NS_BEGIN
@@ -14,7 +14,7 @@ CPPUNIT_NS_BEGIN
struct StringTools
{
- typedef CppUnitVector<std::string> Strings;
+ typedef std::vector<std::string> Strings;
static std::string CPPUNIT_API toString( int value );
diff --git a/3rdParty/CppUnit/src/include/cppunit/tools/XmlElement.h b/3rdParty/CppUnit/src/include/cppunit/tools/XmlElement.h
index 0b36bd2..70e21f8 100644
--- a/3rdParty/CppUnit/src/include/cppunit/tools/XmlElement.h
+++ b/3rdParty/CppUnit/src/include/cppunit/tools/XmlElement.h
@@ -8,7 +8,7 @@
#pragma warning( disable: 4251 ) // X needs to have dll-interface to be used by clients of class Z
#endif
-#include <cppunit/portability/CppUnitDeque.h>
+#include <deque>
#include <string>
@@ -131,10 +131,10 @@ private:
std::string m_name;
std::string m_content;
- typedef CppUnitDeque<Attribute> Attributes;
+ typedef std::deque<Attribute> Attributes;
Attributes m_attributes;
- typedef CppUnitDeque<XmlElement *> Elements;
+ typedef std::deque<XmlElement *> Elements;
Elements m_elements;
};
diff --git a/3rdParty/CppUnit/src/include/cppunit/ui/text/TextTestRunner.h b/3rdParty/CppUnit/src/include/cppunit/ui/text/TextTestRunner.h
index 86da4d4..6250166 100644
--- a/3rdParty/CppUnit/src/include/cppunit/ui/text/TextTestRunner.h
+++ b/3rdParty/CppUnit/src/include/cppunit/ui/text/TextTestRunner.h
@@ -86,6 +86,12 @@ protected:
virtual void wait( bool doWait );
virtual void printResult( bool doPrintResult );
+private:
+ // prohibit copying
+ TextTestRunner( const TextTestRunner& );
+ // prohibit copying
+ TextTestRunner& operator=( const TextTestRunner& );
+
TestResultCollector *m_result;
TestResult *m_eventManager;
Outputter *m_outputter;
diff --git a/3rdParty/CppUnit/src/src/cppunit/Asserter.cpp b/3rdParty/CppUnit/src/src/cppunit/Asserter.cpp
index a9cf95c..79fcb2e 100644
--- a/3rdParty/CppUnit/src/src/cppunit/Asserter.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/Asserter.cpp
@@ -6,6 +6,7 @@
CPPUNIT_NS_BEGIN
+// coverity[+kill]
void
Asserter::fail( std::string message,
const SourceLine &sourceLine )
@@ -13,7 +14,7 @@ Asserter::fail( std::string message,
fail( Message( "assertion failed", message ), sourceLine );
}
-
+// coverity[+kill]
void
Asserter::fail( const Message &message,
const SourceLine &sourceLine )
@@ -40,13 +41,41 @@ Asserter::failIf( bool shouldFail,
failIf( shouldFail, Message( "assertion failed", message ), sourceLine );
}
-
std::string
Asserter::makeExpected( const std::string &expectedValue )
{
return "Expected: " + expectedValue;
}
+std::string
+Asserter::makeExpectedEqual( const std::string &expectedValue )
+{
+ return "Expected: " + expectedValue;
+}
+
+std::string
+Asserter::makeExpectedLess( const std::string& expectedValue )
+{
+ return "Expected less than: " + expectedValue;
+}
+
+std::string
+Asserter::makeExpectedLessEqual( const std::string& expectedValue )
+{
+ return "Expected less or equal than: " + expectedValue;
+}
+
+std::string
+Asserter::makeExpectedGreater( const std::string& expectedValue )
+{
+ return "Expected greater than: " + expectedValue;
+}
+
+std::string
+Asserter::makeExpectedGreaterEqual( const std::string& expectedValue )
+{
+ return "Expected greater or equal than: " + expectedValue;
+}
std::string
Asserter::makeActual( const std::string &actualValue )
@@ -55,18 +84,28 @@ Asserter::makeActual( const std::string &actualValue )
}
+Message
+Asserter::makeMessage( const std::string& expectedMessage,
+ const std::string& actualMessage,
+ const std::string& shortDescription,
+ const AdditionalMessage& additionalMessage)
+{
+ Message message( shortDescription,
+ expectedMessage,
+ actualMessage );
+ message.addDetail( additionalMessage );
+
+ return message;
+}
+
+
Message
Asserter::makeNotEqualMessage( const std::string &expectedValue,
const std::string &actualValue,
const AdditionalMessage &additionalMessage,
const std::string &shortDescription )
{
- Message message( shortDescription,
- makeExpected( expectedValue ),
- makeActual( actualValue ) );
- message.addDetail( additionalMessage );
-
- return message;
+ return makeMessage(makeExpectedEqual(expectedValue), makeActual(actualValue), shortDescription, additionalMessage);
}
@@ -77,15 +116,71 @@ Asserter::failNotEqual( std::string expected,
const AdditionalMessage &additionalMessage,
std::string shortDescription )
{
- fail( makeNotEqualMessage( expected,
- actual,
- additionalMessage,
- shortDescription ),
+ fail( makeMessage( makeExpectedEqual(expected),
+ makeActual(actual),
+ shortDescription,
+ additionalMessage ),
+ sourceLine );
+}
+
+
+void
+Asserter::failNotLess( std::string expected,
+ std::string actual,
+ const SourceLine &sourceLine,
+ const AdditionalMessage &additionalMessage,
+ std::string shortDescription )
+{
+ fail( makeMessage( makeExpectedLess(expected),
+ makeActual(actual),
+ shortDescription,
+ additionalMessage),
sourceLine );
}
void
+Asserter::failNotGreater( std::string expected,
+ std::string actual,
+ const SourceLine &sourceLine,
+ const AdditionalMessage &additionalMessage,
+ std::string shortDescription )
+{
+ fail( makeMessage( makeExpectedGreater(expected),
+ makeActual(actual),
+ shortDescription,
+ additionalMessage),
+ sourceLine );
+}
+
+void
+Asserter::failNotLessEqual( std::string expected,
+ std::string actual,
+ const SourceLine &sourceLine,
+ const AdditionalMessage &additionalMessage,
+ std::string shortDescription )
+{
+ fail( makeMessage( makeExpectedLessEqual(expected),
+ makeActual(actual),
+ shortDescription,
+ additionalMessage ),
+ sourceLine );
+}
+
+void
+Asserter::failNotGreaterEqual( std::string expected,
+ std::string actual,
+ const SourceLine &sourceLine,
+ const AdditionalMessage &additionalMessage,
+ std::string shortDescription )
+{
+ fail( makeMessage( makeExpectedGreaterEqual(expected),
+ makeActual(actual),
+ shortDescription,
+ additionalMessage ),
+ sourceLine );
+}
+void
Asserter::failNotEqualIf( bool shouldFail,
std::string expected,
std::string actual,
diff --git a/3rdParty/CppUnit/src/src/cppunit/BriefTestProgressListener.cpp b/3rdParty/CppUnit/src/src/cppunit/BriefTestProgressListener.cpp
index 120e6d5..4ea8d35 100644
--- a/3rdParty/CppUnit/src/src/cppunit/BriefTestProgressListener.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/BriefTestProgressListener.cpp
@@ -37,7 +37,7 @@ BriefTestProgressListener::addFailure( const TestFailure &failure )
void
-BriefTestProgressListener::endTest( Test *)
+BriefTestProgressListener::endTest( Test * )
{
if ( !m_lastTestFailed )
stdCOut() << " : OK";
diff --git a/3rdParty/CppUnit/src/src/cppunit/DefaultProtector.cpp b/3rdParty/CppUnit/src/src/cppunit/DefaultProtector.cpp
index 6fb306b..fa6ac87 100644
--- a/3rdParty/CppUnit/src/src/cppunit/DefaultProtector.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/DefaultProtector.cpp
@@ -21,7 +21,7 @@ DefaultProtector::protect( const Functor &functor,
catch ( std::exception &e )
{
std::string shortDescription( "uncaught exception of type " );
-#if CPPUNIT_USE_TYPEINFO_NAME
+#if defined(CPPUNIT_USE_TYPEINFO_NAME)
shortDescription += TypeInfoHelper::getClassName( typeid(e) );
#else
shortDescription += "std::exception (or derived).";
diff --git a/3rdParty/CppUnit/src/src/cppunit/Exception.cpp b/3rdParty/CppUnit/src/src/cppunit/Exception.cpp
index 3bbe24b..6685480 100644
--- a/3rdParty/CppUnit/src/src/cppunit/Exception.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/Exception.cpp
@@ -19,20 +19,20 @@ const long Exception::UNKNOWNLINENUMBER = -1;
Exception::Exception( const Exception &other )
: std::exception( other )
+ , m_message(other.m_message)
+ , m_sourceLine(other.m_sourceLine)
+ , m_whatMessage(other.m_whatMessage)
{
- m_message = other.m_message;
- m_sourceLine = other.m_sourceLine;
}
-
Exception::Exception( const Message &message,
const SourceLine &sourceLine )
: m_message( message )
, m_sourceLine( sourceLine )
+ , m_whatMessage()
{
}
-
#ifdef CPPUNIT_ENABLE_SOURCELINE_DEPRECATED
Exception::Exception( std::string message,
long lineNumber,
diff --git a/3rdParty/CppUnit/src/src/cppunit/Message.cpp b/3rdParty/CppUnit/src/src/cppunit/Message.cpp
index 9d6a0e9..ad2efd9 100644
--- a/3rdParty/CppUnit/src/src/cppunit/Message.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/Message.cpp
@@ -4,19 +4,16 @@
CPPUNIT_NS_BEGIN
-
-Message::Message()
-{
-}
-
Message::Message( const Message &other )
+ : m_shortDescription()
+ , m_details()
{
*this = other;
}
-
Message::Message( const std::string &shortDescription )
: m_shortDescription( shortDescription )
+ , m_details()
{
}
@@ -24,6 +21,7 @@ Message::Message( const std::string &shortDescription )
Message::Message( const std::string &shortDescription,
const std::string &detail1 )
: m_shortDescription( shortDescription )
+ , m_details()
{
addDetail( detail1 );
}
@@ -33,6 +31,7 @@ Message::Message( const std::string &shortDescription,
const std::string &detail1,
const std::string &detail2 )
: m_shortDescription( shortDescription )
+ , m_details()
{
addDetail( detail1, detail2 );
}
@@ -43,10 +42,15 @@ Message::Message( const std::string &shortDescription,
const std::string &detail2,
const std::string &detail3 )
: m_shortDescription( shortDescription )
+ , m_details()
{
addDetail( detail1, detail2, detail3 );
}
+Message::~Message()
+{
+}
+
Message &
Message::operator =( const Message &other )
{
diff --git a/3rdParty/CppUnit/src/src/cppunit/Protector.cpp b/3rdParty/CppUnit/src/src/cppunit/Protector.cpp
index 5c171ec..99188bb 100644
--- a/3rdParty/CppUnit/src/src/cppunit/Protector.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/Protector.cpp
@@ -21,7 +21,7 @@ void
Protector::reportError( const ProtectorContext &context,
const Exception &error ) const
{
- std::auto_ptr<Exception> actualError( error.clone() );
+ std::unique_ptr<Exception> actualError( error.clone() );
actualError->setMessage( actualMessage( actualError->message(), context ) );
context.m_result->addError( context.m_test,
actualError.release() );
@@ -42,7 +42,7 @@ void
Protector::reportFailure( const ProtectorContext &context,
const Exception &failure ) const
{
- std::auto_ptr<Exception> actualFailure( failure.clone() );
+ std::unique_ptr<Exception> actualFailure( failure.clone() );
actualFailure->setMessage( actualMessage( actualFailure->message(), context ) );
context.m_result->addFailure( context.m_test,
actualFailure.release() );
diff --git a/3rdParty/CppUnit/src/src/cppunit/ProtectorChain.cpp b/3rdParty/CppUnit/src/src/cppunit/ProtectorChain.cpp
index f528341..db7744a 100644
--- a/3rdParty/CppUnit/src/src/cppunit/ProtectorChain.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/ProtectorChain.cpp
@@ -21,11 +21,20 @@ public:
}
private:
+ // disable copying
+ ProtectFunctor( const ProtectFunctor& );
+ // disable copying
+ ProtectFunctor& operator=( const ProtectFunctor& );
+
Protector *m_protector;
const Functor &m_functor;
const ProtectorContext &m_context;
};
+ProtectorChain::ProtectorChain()
+ : m_protectors(0)
+{
+}
ProtectorChain::~ProtectorChain()
{
diff --git a/3rdParty/CppUnit/src/src/cppunit/ProtectorChain.h b/3rdParty/CppUnit/src/src/cppunit/ProtectorChain.h
index 711b56f..9123782 100644
--- a/3rdParty/CppUnit/src/src/cppunit/ProtectorChain.h
+++ b/3rdParty/CppUnit/src/src/cppunit/ProtectorChain.h
@@ -2,7 +2,7 @@
#define CPPUNIT_PROTECTORCHAIN_H
#include <cppunit/Protector.h>
-#include <cppunit/portability/CppUnitDeque.h>
+#include <deque>
#if CPPUNIT_NEED_DLL_DECL
#pragma warning( push )
@@ -19,6 +19,8 @@ CPPUNIT_NS_BEGIN
class CPPUNIT_API ProtectorChain : public Protector
{
public:
+ ProtectorChain();
+
~ProtectorChain();
void push( Protector *protector );
@@ -34,10 +36,10 @@ private:
class ProtectFunctor;
private:
- typedef CppUnitDeque<Protector *> Protectors;
+ typedef std::deque<Protector *> Protectors;
Protectors m_protectors;
- typedef CppUnitDeque<Functor *> Functors;
+ typedef std::deque<Functor *> Functors;
};
diff --git a/3rdParty/CppUnit/src/src/cppunit/ProtectorContext.h b/3rdParty/CppUnit/src/src/cppunit/ProtectorContext.h
index c3d496c..4957e05 100644
--- a/3rdParty/CppUnit/src/src/cppunit/ProtectorContext.h
+++ b/3rdParty/CppUnit/src/src/cppunit/ProtectorContext.h
@@ -26,6 +26,13 @@ public:
{
}
+private:
+ /// disable copy construction
+ ProtectorContext( const ProtectorContext& );
+ /// disable assignment
+ ProtectorContext& operator=(const ProtectorContext&);
+
+public:
Test *m_test;
TestResult *m_result;
std::string m_shortDescription;
diff --git a/3rdParty/CppUnit/src/src/cppunit/SourceLine.cpp b/3rdParty/CppUnit/src/src/cppunit/SourceLine.cpp
index dfadae3..ecc9558 100644
--- a/3rdParty/CppUnit/src/src/cppunit/SourceLine.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/SourceLine.cpp
@@ -5,6 +5,7 @@ CPPUNIT_NS_BEGIN
SourceLine::SourceLine() :
+ m_fileName(),
m_lineNumber( -1 )
{
}
diff --git a/3rdParty/CppUnit/src/src/cppunit/TestCase.cpp b/3rdParty/CppUnit/src/src/cppunit/TestCase.cpp
index 13c0525..431a0c5 100644
--- a/3rdParty/CppUnit/src/src/cppunit/TestCase.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/TestCase.cpp
@@ -5,7 +5,7 @@
#include <cppunit/TestResult.h>
#include <stdexcept>
-#if CPPUNIT_USE_TYPEINFO_NAME
+#if defined(CPPUNIT_USE_TYPEINFO_NAME)
# include <typeinfo>
#endif
diff --git a/3rdParty/CppUnit/src/src/cppunit/TestFactoryRegistry.cpp b/3rdParty/CppUnit/src/src/cppunit/TestFactoryRegistry.cpp
index 3457da3..f1623cc 100644
--- a/3rdParty/CppUnit/src/src/cppunit/TestFactoryRegistry.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/TestFactoryRegistry.cpp
@@ -1,6 +1,6 @@
#include <cppunit/config/SourcePrefix.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
-#include <cppunit/portability/CppUnitMap.h>
+#include <map>
#include <cppunit/TestSuite.h>
#include <assert.h>
@@ -12,7 +12,7 @@ CPPUNIT_NS_BEGIN
class TestFactoryRegistryList
{
private:
- typedef CppUnitMap<std::string, TestFactoryRegistry *, std::less<std::string> > Registries;
+ typedef std::map<std::string, TestFactoryRegistry *, std::less<std::string> > Registries;
Registries m_registries;
enum State {
@@ -50,6 +50,7 @@ private:
public:
TestFactoryRegistryList()
+ : m_registries()
{
stateFlag( exist );
}
@@ -83,6 +84,7 @@ public:
TestFactoryRegistry::TestFactoryRegistry( std::string name ) :
+ m_factories(),
m_name( name )
{
}
diff --git a/3rdParty/CppUnit/src/src/cppunit/TestNamer.cpp b/3rdParty/CppUnit/src/src/cppunit/TestNamer.cpp
index eec9be9..1eb6c5f 100644
--- a/3rdParty/CppUnit/src/src/cppunit/TestNamer.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/TestNamer.cpp
@@ -1,44 +1,34 @@
#include <cppunit/extensions/TestNamer.h>
#include <cppunit/extensions/TypeInfoHelper.h>
+#include <cppunit/tools/StringHelper.h>
#include <string>
-
CPPUNIT_NS_BEGIN
-
-#if CPPUNIT_HAVE_RTTI
TestNamer::TestNamer( const std::type_info &typeInfo )
+ : m_fixtureName( TypeInfoHelper::getClassName( typeInfo ) )
{
- m_fixtureName = TypeInfoHelper::getClassName( typeInfo );
}
-#endif
-
TestNamer::TestNamer( const std::string &fixtureName )
: m_fixtureName( fixtureName )
{
}
-
TestNamer::~TestNamer()
{
}
-
std::string
TestNamer::getFixtureName() const
{
return m_fixtureName;
}
-
std::string
TestNamer::getTestNameFor( const std::string &testMethodName ) const
{
return getFixtureName() + "::" + testMethodName;
}
-
-
-
CPPUNIT_NS_END
diff --git a/3rdParty/CppUnit/src/src/cppunit/TestPath.cpp b/3rdParty/CppUnit/src/src/cppunit/TestPath.cpp
index a2783a2..5affffb 100644
--- a/3rdParty/CppUnit/src/src/cppunit/TestPath.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/TestPath.cpp
@@ -8,11 +8,13 @@ CPPUNIT_NS_BEGIN
TestPath::TestPath()
+ : m_tests()
{
}
TestPath::TestPath( Test *root )
+ : m_tests()
{
add( root );
}
@@ -21,6 +23,7 @@ TestPath::TestPath( Test *root )
TestPath::TestPath( const TestPath &other,
int indexFirst,
int count )
+ : m_tests()
{
int countAdjustment = 0;
if ( indexFirst < 0 )
@@ -42,6 +45,7 @@ TestPath::TestPath( const TestPath &other,
TestPath::TestPath( Test *searchRoot,
const std::string &pathAsString )
+ : m_tests()
{
PathTestNames testNames;
diff --git a/3rdParty/CppUnit/src/src/cppunit/TestResult.cpp b/3rdParty/CppUnit/src/src/cppunit/TestResult.cpp
index 6be19f1..ad880bc 100644
--- a/3rdParty/CppUnit/src/src/cppunit/TestResult.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/TestResult.cpp
@@ -3,6 +3,7 @@
#include <cppunit/TestListener.h>
#include <cppunit/TestResult.h>
#include <cppunit/tools/Algorithm.h>
+#include <cppunit/portability/Stream.h>
#include <algorithm>
#include "DefaultProtector.h"
#include "ProtectorChain.h"
@@ -13,7 +14,8 @@ CPPUNIT_NS_BEGIN
TestResult::TestResult( SynchronizationObject *syncObject )
: SynchronizedObject( syncObject )
- , m_protectorChain( new ProtectorChain() )
+ , m_listeners()
+ , m_protectorChain( new ProtectorChain )
, m_stop( false )
{
m_protectorChain->push( new DefaultProtector() );
@@ -22,6 +24,8 @@ TestResult::TestResult( SynchronizationObject *syncObject )
TestResult::~TestResult()
{
+ stdCOut().flush();
+ stdCErr().flush();
delete m_protectorChain;
}
diff --git a/3rdParty/CppUnit/src/src/cppunit/TestResultCollector.cpp b/3rdParty/CppUnit/src/src/cppunit/TestResultCollector.cpp
index 4371c50..73f81da 100644
--- a/3rdParty/CppUnit/src/src/cppunit/TestResultCollector.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/TestResultCollector.cpp
@@ -7,6 +7,9 @@ CPPUNIT_NS_BEGIN
TestResultCollector::TestResultCollector( SynchronizationObject *syncObject )
: TestSuccessListener( syncObject )
+ , m_tests()
+ , m_failures()
+ , m_testErrors(0)
{
reset();
}
diff --git a/3rdParty/CppUnit/src/src/cppunit/TestSuite.cpp b/3rdParty/CppUnit/src/src/cppunit/TestSuite.cpp
index 8dd2ea6..b5d6db3 100644
--- a/3rdParty/CppUnit/src/src/cppunit/TestSuite.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/TestSuite.cpp
@@ -8,6 +8,7 @@ CPPUNIT_NS_BEGIN
/// Default constructor
TestSuite::TestSuite( std::string name )
: TestComposite( name )
+ , m_tests()
{
}
@@ -39,7 +40,7 @@ TestSuite::addTest( Test *test )
}
-const CppUnitVector<Test *> &
+const std::vector<Test *> &
TestSuite::getTests() const
{
return m_tests;
diff --git a/3rdParty/CppUnit/src/src/cppunit/TestSuiteBuilderContext.cpp b/3rdParty/CppUnit/src/src/cppunit/TestSuiteBuilderContext.cpp
index ff71b52..5e4347e 100644
--- a/3rdParty/CppUnit/src/src/cppunit/TestSuiteBuilderContext.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/TestSuiteBuilderContext.cpp
@@ -13,6 +13,7 @@ TestSuiteBuilderContextBase::TestSuiteBuilderContextBase(
: m_suite( suite )
, m_namer( namer )
, m_factory( factory )
+ , m_properties()
{
}
diff --git a/3rdParty/CppUnit/src/src/cppunit/TextTestProgressListener.cpp b/3rdParty/CppUnit/src/src/cppunit/TextTestProgressListener.cpp
index 5bbe768..ea4fb17 100644
--- a/3rdParty/CppUnit/src/src/cppunit/TextTestProgressListener.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/TextTestProgressListener.cpp
@@ -20,6 +20,7 @@ void
TextTestProgressListener::startTest( Test * )
{
stdCOut() << ".";
+ stdCOut().flush();
}
@@ -27,6 +28,7 @@ void
TextTestProgressListener::addFailure( const TestFailure &failure )
{
stdCOut() << ( failure.isError() ? "E" : "F" );
+ stdCOut().flush();
}
diff --git a/3rdParty/CppUnit/src/src/cppunit/TypeInfoHelper.cpp b/3rdParty/CppUnit/src/src/cppunit/TypeInfoHelper.cpp
index 2febac6..aa24a80 100644
--- a/3rdParty/CppUnit/src/src/cppunit/TypeInfoHelper.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/TypeInfoHelper.cpp
@@ -1,19 +1,16 @@
#include <cppunit/Portability.h>
#include <cppunit/extensions/TypeInfoHelper.h>
-#include <stdlib.h>
-
-#if CPPUNIT_HAVE_RTTI
#include <string>
#if CPPUNIT_HAVE_GCC_ABI_DEMANGLE
+#include <cstdlib>
#include <cxxabi.h>
#endif
CPPUNIT_NS_BEGIN
-
std::string
TypeInfoHelper::getClassName( const std::type_info &info )
{
@@ -22,10 +19,21 @@ TypeInfoHelper::getClassName( const std::type_info &info )
int status = 0;
char* c_name = 0;
- c_name = abi::__cxa_demangle( info.name(), 0, 0, &status );
-
- std::string name( c_name );
- free( c_name );
+ const char* c_origName = info.name();
+ if(c_origName[0] == '*')
+ ++c_origName;
+ c_name = abi::__cxa_demangle( c_origName, 0, 0, &status );
+
+ std::string name;
+ if(c_name)
+ {
+ name = std::string( c_name );
+ free( c_name );
+ }
+ else
+ {
+ name = std::string( c_origName );
+ }
#else // CPPUNIT_HAVE_GCC_ABI_DEMANGLE
@@ -48,7 +56,4 @@ TypeInfoHelper::getClassName( const std::type_info &info )
return name;
}
-
CPPUNIT_NS_END
-
-#endif // CPPUNIT_HAVE_RTTI
diff --git a/3rdParty/CppUnit/src/src/cppunit/XmlDocument.cpp b/3rdParty/CppUnit/src/src/cppunit/XmlDocument.cpp
index 31f9115..4b09769 100644
--- a/3rdParty/CppUnit/src/src/cppunit/XmlDocument.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/XmlDocument.cpp
@@ -5,7 +5,6 @@
CPPUNIT_NS_BEGIN
-
XmlDocument::XmlDocument( const std::string &encoding,
const std::string &styleSheet )
: m_styleSheet( styleSheet )
@@ -15,7 +14,6 @@ XmlDocument::XmlDocument( const std::string &encoding,
setEncoding( encoding );
}
-
XmlDocument::~XmlDocument()
{
delete m_rootElement;
diff --git a/3rdParty/CppUnit/src/src/cppunit/XmlElement.cpp b/3rdParty/CppUnit/src/src/cppunit/XmlElement.cpp
index f930ad4..b16d2fe 100644
--- a/3rdParty/CppUnit/src/src/cppunit/XmlElement.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/XmlElement.cpp
@@ -10,6 +10,8 @@ XmlElement::XmlElement( std::string elementName,
std::string content )
: m_name( elementName )
, m_content( content )
+ , m_attributes()
+ , m_elements()
{
}
@@ -17,6 +19,9 @@ XmlElement::XmlElement( std::string elementName,
XmlElement::XmlElement( std::string elementName,
int numericContent )
: m_name( elementName )
+ , m_content()
+ , m_attributes()
+ , m_elements()
{
setContent( numericContent );
}
diff --git a/3rdParty/CppUnit/src/src/cppunit/XmlOutputter.cpp b/3rdParty/CppUnit/src/src/cppunit/XmlOutputter.cpp
index c605e33..e1cb690 100644
--- a/3rdParty/CppUnit/src/src/cppunit/XmlOutputter.cpp
+++ b/3rdParty/CppUnit/src/src/cppunit/XmlOutputter.cpp
@@ -15,10 +15,13 @@ CPPUNIT_NS_BEGIN
XmlOutputter::XmlOutputter( TestResultCollector *result,
OStream &stream,
- std::string encoding )
+ const std::string& encoding )
: m_result( result )
, m_stream( stream )
+ , m_encoding( encoding )
+ , m_styleSheet()
, m_xml( new XmlDocument( encoding ) )
+ , m_hooks()
{
}
diff --git a/3rdParty/Expat/SConscript b/3rdParty/Expat/SConscript
index 56949aa..9a0cecd 100644
--- a/3rdParty/Expat/SConscript
+++ b/3rdParty/Expat/SConscript
@@ -8,6 +8,12 @@ if env.get("EXPAT_BUNDLED", False) :
"LIBPATH": [Dir(".")],
}
+ def checkBuilds(context, message, source):
+ context.Message(message)
+ result = context.TryLink(source, '.cpp')
+ context.Result(result)
+ return result
+
if env["SCONS_STAGE"] == "build" :
myenv = env.Clone()
myenv.Append(CPPDEFINES = ["XML_STATIC", "HAVE_EXPAT_CONFIG_H"])
@@ -22,8 +28,58 @@ if env.get("EXPAT_BUNDLED", False) :
myenv.Append(CPPDEFINES = ["HAVE_MEMMOVE"])
conf.Finish()
+ if env["PLATFORM"] != "win32" :
+ conf = Configure(conf_env, custom_tests = { "CheckBuilds" : checkBuilds})
+ if conf.CheckBuilds('Checking for C function getrandom()... ',
+ """
+ #include <stdlib.h> /* for NULL */
+ #include <sys/random.h>
+ int main() {
+ return getrandom(NULL, 0U, 0U);
+ }
+ """):
+ myenv.Append(CPPDEFINES = ["HAVE_GETRANDOM"])
+ elif conf.CheckBuilds('Checking for syscall SYS_getrandom... ',
+ """
+ #include <stdlib.h> /* for NULL */
+ #include <unistd.h> /* for syscall */
+ #include <sys/syscall.h> /* for SYS_getrandom */
+ int main() {
+ syscall(SYS_getrandom, NULL, 0, 0);
+ return 0;
+ }
+ """):
+ myenv.Append(CPPDEFINES = ["HAVE_SYSCALL_GETRANDOM"])
+ elif conf.CheckBuilds('Checking for arc4random_buf... ',
+ """
+ #include <stdlib.h> /* for arc4random_buf on BSD, for NULL */
+ #if defined(HAVE_LIBBSD)
+ # include <bsd/stdlib.h>
+ #endif
+ int main() {
+ arc4random_buf(NULL, 0U);
+ return 0;
+ }
+ """):
+ myenv.Append(CPPDEFINES = ["HAVE_ARC4RANDOM_BUF"])
+ elif conf.CheckBuilds('Checking for arc4random... ',
+ """
+ #if defined(HAVE_LIBBSD)
+ # include <bsd/stdlib.h>
+ #else
+ # include <stdlib.h>
+ #endif
+ int main() {
+ arc4random();
+ return 0;
+ }
+ """):
+ myenv.Append(CPPDEFINES = ["HAVE_ARC4RANDOM"])
+ conf.Finish()
+
env["EXPAT_OBJECTS"] = myenv.SwiftenObject([
"src/xmltok.c",
"src/xmlparse.c",
- "src/xmlrole.c"
- ])
+ "src/xmlrole.c",
+ "src/loadlibrary.c",
+ ]) \ No newline at end of file
diff --git a/3rdParty/Expat/src/ascii.h b/3rdParty/Expat/src/ascii.h
index d10530b..c3587e5 100644
--- a/3rdParty/Expat/src/ascii.h
+++ b/3rdParty/Expat/src/ascii.h
@@ -1,5 +1,33 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#define ASCII_A 0x41
diff --git a/3rdParty/Expat/src/asciitab.h b/3rdParty/Expat/src/asciitab.h
index 79a15c2..2f59fd9 100644
--- a/3rdParty/Expat/src/asciitab.h
+++ b/3rdParty/Expat/src/asciitab.h
@@ -1,5 +1,33 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* 0x00 */ BT_NONXML, BT_NONXML, BT_NONXML, BT_NONXML,
diff --git a/3rdParty/Expat/src/expat.h b/3rdParty/Expat/src/expat.h
index 28b0f95..c050f1d 100644
--- a/3rdParty/Expat/src/expat.h
+++ b/3rdParty/Expat/src/expat.h
@@ -1,5 +1,33 @@
-/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef Expat_INCLUDED
@@ -24,7 +52,6 @@ extern "C" {
struct XML_ParserStruct;
typedef struct XML_ParserStruct *XML_Parser;
-/* Should this be defined using stdbool.h when C99 is available? */
typedef unsigned char XML_Bool;
#define XML_TRUE ((XML_Bool) 1)
#define XML_FALSE ((XML_Bool) 0)
@@ -237,7 +264,7 @@ XML_ParserCreate_MM(const XML_Char *encoding,
const XML_Char *namespaceSeparator);
/* Prepare a parser object to be re-used. This is particularly
- valuable when memory allocation overhead is disproportionatly high,
+ valuable when memory allocation overhead is disproportionately high,
such as when a large number of small documnents need to be parsed.
All handlers are cleared from the parser, except for the
unknownEncodingHandler. The parser's external state is re-initialized
@@ -1049,7 +1076,7 @@ XML_GetFeatureList(void);
*/
#define XML_MAJOR_VERSION 2
#define XML_MINOR_VERSION 2
-#define XML_MICRO_VERSION 1
+#define XML_MICRO_VERSION 7
#ifdef __cplusplus
}
diff --git a/3rdParty/Expat/src/expat_external.h b/3rdParty/Expat/src/expat_external.h
index 892eb4b..875225d 100644
--- a/3rdParty/Expat/src/expat_external.h
+++ b/3rdParty/Expat/src/expat_external.h
@@ -1,5 +1,33 @@
-/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef Expat_External_INCLUDED
@@ -8,7 +36,7 @@
/* External API definitions */
#if defined(_MSC_EXTENSIONS) && !defined(__BEOS__) && !defined(__CYGWIN__)
-#define XML_USE_MSC_EXTENSIONS 1
+# define XML_USE_MSC_EXTENSIONS 1
#endif
/* Expat tries very hard to make the API boundary very specifically
@@ -34,11 +62,11 @@
system headers may assume the cdecl convention.
*/
#ifndef XMLCALL
-#if defined(_MSC_VER)
-#define XMLCALL __cdecl
-#elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER)
-#define XMLCALL __attribute__((cdecl))
-#else
+# if defined(_MSC_VER)
+# define XMLCALL __cdecl
+# elif defined(__GNUC__) && defined(__i386) && !defined(__INTEL_COMPILER)
+# define XMLCALL __attribute__((cdecl))
+# else
/* For any platform which uses this definition and supports more than
one calling convention, we need to extend this definition to
declare the convention used on that platform, if it's possible to
@@ -49,41 +77,45 @@
pre-processor and how to specify the same calling convention as the
platform's malloc() implementation.
*/
-#define XMLCALL
-#endif
+# define XMLCALL
+# endif
#endif /* not defined XMLCALL */
#if !defined(XML_STATIC) && !defined(XMLIMPORT)
-#ifndef XML_BUILDING_EXPAT
+# ifndef XML_BUILDING_EXPAT
/* using Expat from an application */
-#ifdef XML_USE_MSC_EXTENSIONS
-#define XMLIMPORT __declspec(dllimport)
-#endif
+# ifdef XML_USE_MSC_EXTENSIONS
+# define XMLIMPORT __declspec(dllimport)
+# endif
-#endif
+# endif
#endif /* not defined XML_STATIC */
-#if !defined(XMLIMPORT) && defined(__GNUC__) && (__GNUC__ >= 4)
-#define XMLIMPORT __attribute__ ((visibility ("default")))
+#ifndef XML_ENABLE_VISIBILITY
+# define XML_ENABLE_VISIBILITY 0
+#endif
+
+#if !defined(XMLIMPORT) && XML_ENABLE_VISIBILITY
+# define XMLIMPORT __attribute__ ((visibility ("default")))
#endif
/* If we didn't define it above, define it away: */
#ifndef XMLIMPORT
-#define XMLIMPORT
+# define XMLIMPORT
#endif
#if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96))
-#define XML_ATTR_MALLOC __attribute__((__malloc__))
+# define XML_ATTR_MALLOC __attribute__((__malloc__))
#else
-#define XML_ATTR_MALLOC
+# define XML_ATTR_MALLOC
#endif
#if defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
-#define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x)))
+# define XML_ATTR_ALLOC_SIZE(x) __attribute__((__alloc_size__(x)))
#else
-#define XML_ATTR_ALLOC_SIZE(x)
+# define XML_ATTR_ALLOC_SIZE(x)
#endif
#define XMLPARSEAPI(type) XMLIMPORT type XMLCALL
@@ -93,33 +125,35 @@ extern "C" {
#endif
#ifdef XML_UNICODE_WCHAR_T
-# define XML_UNICODE
+# ifndef XML_UNICODE
+# define XML_UNICODE
+# endif
# if defined(__SIZEOF_WCHAR_T__) && (__SIZEOF_WCHAR_T__ != 2)
# error "sizeof(wchar_t) != 2; Need -fshort-wchar for both Expat and libc"
# endif
#endif
#ifdef XML_UNICODE /* Information is UTF-16 encoded. */
-#ifdef XML_UNICODE_WCHAR_T
+# ifdef XML_UNICODE_WCHAR_T
typedef wchar_t XML_Char;
typedef wchar_t XML_LChar;
-#else
+# else
typedef unsigned short XML_Char;
typedef char XML_LChar;
-#endif /* XML_UNICODE_WCHAR_T */
+# endif /* XML_UNICODE_WCHAR_T */
#else /* Information is UTF-8 encoded. */
typedef char XML_Char;
typedef char XML_LChar;
#endif /* XML_UNICODE */
#ifdef XML_LARGE_SIZE /* Use large integers for file/stream positions. */
-#if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
+# if defined(XML_USE_MSC_EXTENSIONS) && _MSC_VER < 1400
typedef __int64 XML_Index;
typedef unsigned __int64 XML_Size;
-#else
+# else
typedef long long XML_Index;
typedef unsigned long long XML_Size;
-#endif
+# endif
#else
typedef long XML_Index;
typedef unsigned long XML_Size;
diff --git a/3rdParty/Expat/src/iasciitab.h b/3rdParty/Expat/src/iasciitab.h
index 24a1d5c..ce4a4bf 100644
--- a/3rdParty/Expat/src/iasciitab.h
+++ b/3rdParty/Expat/src/iasciitab.h
@@ -1,5 +1,33 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* Like asciitab.h, except that 0xD has code BT_S rather than BT_CR */
diff --git a/3rdParty/Expat/src/internal.h b/3rdParty/Expat/src/internal.h
index 94cb98e..dc4ef0c 100644
--- a/3rdParty/Expat/src/internal.h
+++ b/3rdParty/Expat/src/internal.h
@@ -18,6 +18,35 @@
Note: Use of these macros is based on judgement, not hard rules,
and therefore subject to change.
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#if defined(__GNUC__) && defined(__i386__) && !defined(__MINGW32__)
@@ -86,8 +115,13 @@ extern "C" {
#endif
+#ifdef XML_ENABLE_VISIBILITY
+#if XML_ENABLE_VISIBILITY
+__attribute__ ((visibility ("default")))
+#endif
+#endif
void
-align_limit_to_full_utf8_characters(const char * from, const char ** fromLimRef);
+_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef);
#ifdef __cplusplus
diff --git a/3rdParty/Expat/src/latin1tab.h b/3rdParty/Expat/src/latin1tab.h
index 53c25d7..95dfa52 100644
--- a/3rdParty/Expat/src/latin1tab.h
+++ b/3rdParty/Expat/src/latin1tab.h
@@ -1,5 +1,33 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/* 0x80 */ BT_OTHER, BT_OTHER, BT_OTHER, BT_OTHER,
diff --git a/3rdParty/Expat/src/loadlibrary.c b/3rdParty/Expat/src/loadlibrary.c
new file mode 100644
index 0000000..35fdf98
--- /dev/null
+++ b/3rdParty/Expat/src/loadlibrary.c
@@ -0,0 +1,143 @@
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2016 - 2017, Steve Holme, <steve_holme@hotmail.com>.
+ * Copyright (C) 2017, Expat development team
+ *
+ * All rights reserved.
+ * Licensed under the MIT license:
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
+ * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
+ * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ * Except as contained in this notice, the name of a copyright holder shall
+ * not be used in advertising or otherwise to promote the sale, use or other
+ * dealings in this Software without prior written authorization of the
+ * copyright holder.
+ *
+ ***************************************************************************/
+
+#if defined(_WIN32)
+
+#include <windows.h>
+#include <tchar.h>
+
+
+HMODULE _Expat_LoadLibrary(LPCTSTR filename);
+
+
+#if !defined(LOAD_WITH_ALTERED_SEARCH_PATH)
+#define LOAD_WITH_ALTERED_SEARCH_PATH 0x00000008
+#endif
+
+#if !defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
+#define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
+#endif
+
+/* We use our own typedef here since some headers might lack these */
+typedef HMODULE (APIENTRY *LOADLIBRARYEX_FN)(LPCTSTR, HANDLE, DWORD);
+
+/* See function definitions in winbase.h */
+#ifdef UNICODE
+# ifdef _WIN32_WCE
+# define LOADLIBARYEX L"LoadLibraryExW"
+# else
+# define LOADLIBARYEX "LoadLibraryExW"
+# endif
+#else
+# define LOADLIBARYEX "LoadLibraryExA"
+#endif
+
+
+/*
+ * _Expat_LoadLibrary()
+ *
+ * This is used to dynamically load DLLs using the most secure method available
+ * for the version of Windows that we are running on.
+ *
+ * Parameters:
+ *
+ * filename [in] - The filename or full path of the DLL to load. If only the
+ * filename is passed then the DLL will be loaded from the
+ * Windows system directory.
+ *
+ * Returns the handle of the module on success; otherwise NULL.
+ */
+HMODULE _Expat_LoadLibrary(LPCTSTR filename)
+{
+ HMODULE hModule = NULL;
+ LOADLIBRARYEX_FN pLoadLibraryEx = NULL;
+
+ /* Get a handle to kernel32 so we can access it's functions at runtime */
+ HMODULE hKernel32 = GetModuleHandle(TEXT("kernel32"));
+ if(!hKernel32)
+ return NULL; /* LCOV_EXCL_LINE */
+
+ /* Attempt to find LoadLibraryEx() which is only available on Windows 2000
+ and above */
+ pLoadLibraryEx = (LOADLIBRARYEX_FN) GetProcAddress(hKernel32, LOADLIBARYEX);
+
+ /* Detect if there's already a path in the filename and load the library if
+ there is. Note: Both back slashes and forward slashes have been supported
+ since the earlier days of DOS at an API level although they are not
+ supported by command prompt */
+ if(_tcspbrk(filename, TEXT("\\/"))) {
+ /** !checksrc! disable BANNEDFUNC 1 **/
+ hModule = pLoadLibraryEx ?
+ pLoadLibraryEx(filename, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) :
+ LoadLibrary(filename);
+ }
+ /* Detect if KB2533623 is installed, as LOAD_LIBARY_SEARCH_SYSTEM32 is only
+ supported on Windows Vista, Windows Server 2008, Windows 7 and Windows
+ Server 2008 R2 with this patch or natively on Windows 8 and above */
+ else if(pLoadLibraryEx && GetProcAddress(hKernel32, "AddDllDirectory")) {
+ /* Load the DLL from the Windows system directory */
+ hModule = pLoadLibraryEx(filename, NULL, LOAD_LIBRARY_SEARCH_SYSTEM32);
+ }
+ else {
+ /* Attempt to get the Windows system path */
+ UINT systemdirlen = GetSystemDirectory(NULL, 0);
+ if(systemdirlen) {
+ /* Allocate space for the full DLL path (Room for the null terminator
+ is included in systemdirlen) */
+ size_t filenamelen = _tcslen(filename);
+ TCHAR *path = malloc(sizeof(TCHAR) * (systemdirlen + 1 + filenamelen));
+ if(path && GetSystemDirectory(path, systemdirlen)) {
+ /* Calculate the full DLL path */
+ _tcscpy(path + _tcslen(path), TEXT("\\"));
+ _tcscpy(path + _tcslen(path), filename);
+
+ /* Load the DLL from the Windows system directory */
+ /** !checksrc! disable BANNEDFUNC 1 **/
+ hModule = pLoadLibraryEx ?
+ pLoadLibraryEx(path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH) :
+ LoadLibrary(path);
+
+ }
+ free(path);
+ }
+ }
+
+ return hModule;
+}
+
+#else /* defined(_WIN32) */
+
+/* ISO C requires a translation unit to contain at least one declaration
+ [-Wempty-translation-unit] */
+typedef int _TRANSLATION_UNIT_LOAD_LIBRARY_C_NOT_EMTPY;
+
+#endif /* defined(_WIN32) */
diff --git a/3rdParty/Expat/src/nametab.h b/3rdParty/Expat/src/nametab.h
index b05e62c..bfa2bd3 100644
--- a/3rdParty/Expat/src/nametab.h
+++ b/3rdParty/Expat/src/nametab.h
@@ -1,3 +1,35 @@
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
+
static const unsigned namingBitmap[] = {
0x00000000, 0x00000000, 0x00000000, 0x00000000,
0x00000000, 0x00000000, 0x00000000, 0x00000000,
diff --git a/3rdParty/Expat/src/siphash.h b/3rdParty/Expat/src/siphash.h
index 23b56d2..4d6786d 100644
--- a/3rdParty/Expat/src/siphash.h
+++ b/3rdParty/Expat/src/siphash.h
@@ -2,9 +2,8 @@
* siphash.h - SipHash-2-4 in a single header file
* --------------------------------------------------------------------------
* Derived by William Ahern from the reference implementation[1] published[2]
- * by Jean-Philippe Aumasson and Daniel J. Berstein. Licensed in kind.
* by Jean-Philippe Aumasson and Daniel J. Berstein.
- * Minimal changes by Sebastian Pipping on top, details below.
+ * Minimal changes by Sebastian Pipping and Victor Stinner on top, see below.
* Licensed under the CC0 Public Domain Dedication license.
*
* 1. https://www.131002.net/siphash/siphash24.c
@@ -12,14 +11,31 @@
* --------------------------------------------------------------------------
* HISTORY:
*
- * 2017-06-10 (Sebastian Pipping)
+ * 2018-07-08 (Anton Maklakov)
+ * - Add "fall through" markers for GCC's -Wimplicit-fallthrough
+ *
+ * 2017-11-03 (Sebastian Pipping)
+ * - Hide sip_tobin and sip_binof unless SIPHASH_TOBIN macro is defined
+ *
+ * 2017-07-25 (Vadim Zeitlin)
+ * - Fix use of SIPHASH_MAIN macro
+ *
+ * 2017-07-05 (Sebastian Pipping)
+ * - Use _SIP_ULL macro to not require a C++11 compiler if compiled as C++
+ * - Add const qualifiers at two places
+ * - Ensure <=80 characters line length (assuming tab width 4)
+ *
+ * 2017-06-23 (Victor Stinner)
+ * - Address Win64 compile warnings
+ *
+ * 2017-06-18 (Sebastian Pipping)
* - Clarify license note in the header
* - Address C89 issues:
* - Stop using inline keyword (and let compiler decide)
- * - Turn integer suffix ULL to UL
* - Replace _Bool by int
* - Turn macro siphash24 into a function
* - Address invalid conversion (void pointer) by explicit cast
+ * - Address lack of stdint.h for Visual Studio 2003 to 2008
* - Always expose sip24_valid (for self-tests)
*
* 2012-11-04 - Born. (William Ahern)
@@ -76,7 +92,23 @@
#define SIPHASH_H
#include <stddef.h> /* size_t */
-#include <stdint.h> /* uint64_t uint32_t uint8_t */
+
+#if defined(_WIN32) && defined(_MSC_VER) && (_MSC_VER < 1600)
+ /* For vs2003/7.1 up to vs2008/9.0; _MSC_VER 1600 is vs2010/10.0 */
+ typedef unsigned __int8 uint8_t;
+ typedef unsigned __int32 uint32_t;
+ typedef unsigned __int64 uint64_t;
+#else
+ #include <stdint.h> /* uint64_t uint32_t uint8_t */
+#endif
+
+
+/*
+ * Workaround to not require a C++11 compiler for using ULL suffix
+ * if this code is included and compiled as C++; related GCC warning is:
+ * warning: use of C++11 long long integer constant [-Wlong-long]
+ */
+#define _SIP_ULL(high, low) (((uint64_t)high << 32) | low)
#define SIP_ROTL(x, b) (uint64_t)(((x) << (b)) | ( (x) >> (64 - (b))))
@@ -125,6 +157,8 @@ static struct sipkey *sip_tokey(struct sipkey *key, const void *src) {
} /* sip_tokey() */
+#ifdef SIPHASH_TOBIN
+
#define sip_binof(v) sip_tobin((unsigned char[8]){ 0 }, (v))
static void *sip_tobin(void *dst, uint64_t u64) {
@@ -132,6 +166,8 @@ static void *sip_tobin(void *dst, uint64_t u64) {
return dst;
} /* sip_tobin() */
+#endif /* SIPHASH_TOBIN */
+
static void sip_round(struct siphash *H, const int rounds) {
int i;
@@ -158,11 +194,12 @@ static void sip_round(struct siphash *H, const int rounds) {
} /* sip_round() */
-static struct siphash *sip24_init(struct siphash *H, const struct sipkey *key) {
- H->v0 = 0x736f6d6570736575UL ^ key->k[0];
- H->v1 = 0x646f72616e646f6dUL ^ key->k[1];
- H->v2 = 0x6c7967656e657261UL ^ key->k[0];
- H->v3 = 0x7465646279746573UL ^ key->k[1];
+static struct siphash *sip24_init(struct siphash *H,
+ const struct sipkey *key) {
+ H->v0 = _SIP_ULL(0x736f6d65U, 0x70736575U) ^ key->k[0];
+ H->v1 = _SIP_ULL(0x646f7261U, 0x6e646f6dU) ^ key->k[1];
+ H->v2 = _SIP_ULL(0x6c796765U, 0x6e657261U) ^ key->k[0];
+ H->v3 = _SIP_ULL(0x74656462U, 0x79746573U) ^ key->k[1];
H->p = H->buf;
H->c = 0;
@@ -173,7 +210,8 @@ static struct siphash *sip24_init(struct siphash *H, const struct sipkey *key) {
#define sip_endof(a) (&(a)[sizeof (a) / sizeof *(a)])
-static struct siphash *sip24_update(struct siphash *H, const void *src, size_t len) {
+static struct siphash *sip24_update(struct siphash *H, const void *src,
+ size_t len) {
const unsigned char *p = (const unsigned char *)src, *pe = p + len;
uint64_t m;
@@ -198,17 +236,24 @@ static struct siphash *sip24_update(struct siphash *H, const void *src, size_t l
static uint64_t sip24_final(struct siphash *H) {
- char left = H->p - H->buf;
+ const char left = (char)(H->p - H->buf);
uint64_t b = (H->c + left) << 56;
switch (left) {
case 7: b |= (uint64_t)H->buf[6] << 48;
+ /* fall through */
case 6: b |= (uint64_t)H->buf[5] << 40;
+ /* fall through */
case 5: b |= (uint64_t)H->buf[4] << 32;
+ /* fall through */
case 4: b |= (uint64_t)H->buf[3] << 24;
+ /* fall through */
case 3: b |= (uint64_t)H->buf[2] << 16;
+ /* fall through */
case 2: b |= (uint64_t)H->buf[1] << 8;
+ /* fall through */
case 1: b |= (uint64_t)H->buf[0] << 0;
+ /* fall through */
case 0: break;
}
@@ -222,7 +267,8 @@ static uint64_t sip24_final(struct siphash *H) {
} /* sip24_final() */
-static uint64_t siphash24(const void *src, size_t len, const struct sipkey *key) {
+static uint64_t siphash24(const void *src, size_t len,
+ const struct sipkey *key) {
struct siphash state = SIPHASH_INITIALIZER;
return sip24_final(sip24_update(sip24_init(&state, key), src, len));
} /* siphash24() */
@@ -310,10 +356,11 @@ static int sip24_valid(void) {
struct sipkey k;
size_t i;
- sip_tokey(&k, "\000\001\002\003\004\005\006\007\010\011\012\013\014\015\016\017");
+ sip_tokey(&k, "\000\001\002\003\004\005\006\007\010\011"
+ "\012\013\014\015\016\017");
for (i = 0; i < sizeof in; ++i) {
- in[i] = i;
+ in[i] = (unsigned char)i;
if (siphash24(in, i, &k) != SIP_U8TO64_LE(vectors[i]))
return 0;
@@ -323,12 +370,12 @@ static int sip24_valid(void) {
} /* sip24_valid() */
-#if SIPHASH_MAIN
+#ifdef SIPHASH_MAIN
#include <stdio.h>
int main(void) {
- int ok = sip24_valid();
+ const int ok = sip24_valid();
if (ok)
puts("OK");
diff --git a/3rdParty/Expat/src/utf8tab.h b/3rdParty/Expat/src/utf8tab.h
index 7bb3e77..fa0bed6 100644
--- a/3rdParty/Expat/src/utf8tab.h
+++ b/3rdParty/Expat/src/utf8tab.h
@@ -1,7 +1,34 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
-*/
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
+*/
/* 0x80 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
/* 0x84 */ BT_TRAIL, BT_TRAIL, BT_TRAIL, BT_TRAIL,
diff --git a/3rdParty/Expat/src/winconfig.h b/3rdParty/Expat/src/winconfig.h
index 9bf014d..28a043c 100644
--- a/3rdParty/Expat/src/winconfig.h
+++ b/3rdParty/Expat/src/winconfig.h
@@ -1,10 +1,33 @@
-/*================================================================
-** Copyright 2000, Clark Cooper
-** All rights reserved.
-**
-** This is free software. You are permitted to copy, distribute, or modify
-** it under the terms of the MIT/X license (contained in the COPYING file
-** with this distribution.)
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef WINCONFIG_H
@@ -30,10 +53,6 @@
/* we will assume all Windows platforms are little endian */
#define BYTEORDER 1234
-/* Windows has memmove() available. */
-#define HAVE_MEMMOVE
-
-
#endif /* !defined(HAVE_EXPAT_CONFIG_H) */
diff --git a/3rdParty/Expat/src/xmlparse.c b/3rdParty/Expat/src/xmlparse.c
index 76f078e..02a11ae 100644
--- a/3rdParty/Expat/src/xmlparse.c
+++ b/3rdParty/Expat/src/xmlparse.c
@@ -1,10 +1,38 @@
-/* Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
-
- 77fea421d361dca90041d0040ecf1dca651167fadf2af79e990e35168d70d933 (2.2.1+)
+/* 69df5be70289a11fb834869ce4a91c23c1d9dd04baffcbd10e86742d149a080c (2.2.7+)
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
-#define _GNU_SOURCE /* syscall prototype */
+#if !defined(_GNU_SOURCE)
+# define _GNU_SOURCE 1 /* syscall prototype */
+#endif
#include <stddef.h>
#include <string.h> /* memset(), memcpy() */
@@ -19,6 +47,8 @@
#include <sys/time.h> /* gettimeofday() */
#include <sys/types.h> /* getpid() */
#include <unistd.h> /* getpid() */
+#include <fcntl.h> /* O_RDONLY */
+#include <errno.h>
#endif
#define XML_BUILDING_EXPAT 1
@@ -33,6 +63,54 @@
#include "expat.h"
#include "siphash.h"
+#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
+# if defined(HAVE_GETRANDOM)
+# include <sys/random.h> /* getrandom */
+# else
+# include <unistd.h> /* syscall */
+# include <sys/syscall.h> /* SYS_getrandom */
+# endif
+# if ! defined(GRND_NONBLOCK)
+# define GRND_NONBLOCK 0x0001
+# endif /* defined(GRND_NONBLOCK) */
+#endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
+
+#if defined(HAVE_LIBBSD) \
+ && (defined(HAVE_ARC4RANDOM_BUF) || defined(HAVE_ARC4RANDOM))
+# include <bsd/stdlib.h>
+#endif
+
+#if defined(_WIN32) && !defined(LOAD_LIBRARY_SEARCH_SYSTEM32)
+# define LOAD_LIBRARY_SEARCH_SYSTEM32 0x00000800
+#endif
+
+#if !defined(HAVE_GETRANDOM) && !defined(HAVE_SYSCALL_GETRANDOM) \
+ && !defined(HAVE_ARC4RANDOM_BUF) && !defined(HAVE_ARC4RANDOM) \
+ && !defined(XML_DEV_URANDOM) \
+ && !defined(_WIN32) \
+ && !defined(XML_POOR_ENTROPY)
+# error \
+ You do not have support for any sources of high quality entropy \
+ enabled. For end user security, that is probably not what you want. \
+ \
+ Your options include: \
+ * Linux + glibc >=2.25 (getrandom): HAVE_GETRANDOM, \
+ * Linux + glibc <2.25 (syscall SYS_getrandom): HAVE_SYSCALL_GETRANDOM, \
+ * BSD / macOS >=10.7 (arc4random_buf): HAVE_ARC4RANDOM_BUF, \
+ * BSD / macOS <10.7 (arc4random): HAVE_ARC4RANDOM, \
+ * libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF + HAVE_LIBBSD, \
+ * libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, \
+ * Linux / BSD / macOS (/dev/urandom): XML_DEV_URANDOM \
+ * Windows (RtlGenRandom): _WIN32. \
+ \
+ If insist on not using any of these, bypass this error by defining \
+ XML_POOR_ENTROPY; you have been warned. \
+ \
+ If you have reasons to patch this detection code away or need changes \
+ to the build system, please open a bug. Thank you!
+#endif
+
+
#ifdef XML_UNICODE
#define XML_ENCODE_MAX XML_UTF16_ENCODE_MAX
#define XmlConvert XmlUtf16Convert
@@ -83,14 +161,8 @@ typedef char ICHAR;
/* Round up n to be a multiple of sz, where sz is a power of 2. */
#define ROUND_UP(n, sz) (((n) + ((sz) - 1)) & ~((sz) - 1))
-/* Handle the case where memmove() doesn't exist. */
-#ifndef HAVE_MEMMOVE
-#ifdef HAVE_BCOPY
-#define memmove(d,s,l) bcopy((s),(d),(l))
-#else
-#error memmove does not exist on this platform, nor is a substitute available
-#endif /* HAVE_BCOPY */
-#endif /* HAVE_MEMMOVE */
+/* Do safe (NULL-aware) pointer arithmetic */
+#define EXPAT_SAFE_PTR_DIFF(p, q) (((p) && (q)) ? ((p) - (q)) : 0)
#include "internal.h"
#include "xmltok.h"
@@ -392,7 +464,7 @@ setContext(XML_Parser parser, const XML_Char *context);
static void FASTCALL normalizePublicId(XML_Char *s);
static DTD * dtdCreate(const XML_Memory_Handling_Suite *ms);
-/* do not call if parentParser != NULL */
+/* do not call if m_parentParser != NULL */
static void dtdReset(DTD *p, const XML_Memory_Handling_Suite *ms);
static void
dtdDestroy(DTD *p, XML_Bool isDocEntity, const XML_Memory_Handling_Suite *ms);
@@ -436,6 +508,9 @@ static ELEMENT_TYPE *
getElementType(XML_Parser parser, const ENCODING *enc,
const char *ptr, const char *end);
+static XML_Char *copyString(const XML_Char *s,
+ const XML_Memory_Handling_Suite *memsuite);
+
static unsigned long generate_hash_secret_salt(XML_Parser parser);
static XML_Bool startParsing(XML_Parser parser);
@@ -461,7 +536,7 @@ parserInit(XML_Parser parser, const XML_Char *encodingName);
: ((*((pool)->ptr)++ = c), 1))
struct XML_ParserStruct {
- /* The first member must be userData so that the XML_GetUserData
+ /* The first member must be m_userData so that the XML_GetUserData
macro works. */
void *m_userData;
void *m_handlerArg;
@@ -471,7 +546,7 @@ struct XML_ParserStruct {
const char *m_bufferPtr;
/* past last character to be parsed */
char *m_bufferEnd;
- /* allocated end of buffer */
+ /* allocated end of m_buffer */
const char *m_bufferLim;
XML_Index m_parseEndByteIndex;
const char *m_parseEndPtr;
@@ -563,113 +638,10 @@ struct XML_ParserStruct {
unsigned long m_hash_secret_salt;
};
-#define MALLOC(s) (parser->m_mem.malloc_fcn((s)))
-#define REALLOC(p,s) (parser->m_mem.realloc_fcn((p),(s)))
-#define FREE(p) (parser->m_mem.free_fcn((p)))
-
-#define userData (parser->m_userData)
-#define handlerArg (parser->m_handlerArg)
-#define startElementHandler (parser->m_startElementHandler)
-#define endElementHandler (parser->m_endElementHandler)
-#define characterDataHandler (parser->m_characterDataHandler)
-#define processingInstructionHandler \
- (parser->m_processingInstructionHandler)
-#define commentHandler (parser->m_commentHandler)
-#define startCdataSectionHandler \
- (parser->m_startCdataSectionHandler)
-#define endCdataSectionHandler (parser->m_endCdataSectionHandler)
-#define defaultHandler (parser->m_defaultHandler)
-#define startDoctypeDeclHandler (parser->m_startDoctypeDeclHandler)
-#define endDoctypeDeclHandler (parser->m_endDoctypeDeclHandler)
-#define unparsedEntityDeclHandler \
- (parser->m_unparsedEntityDeclHandler)
-#define notationDeclHandler (parser->m_notationDeclHandler)
-#define startNamespaceDeclHandler \
- (parser->m_startNamespaceDeclHandler)
-#define endNamespaceDeclHandler (parser->m_endNamespaceDeclHandler)
-#define notStandaloneHandler (parser->m_notStandaloneHandler)
-#define externalEntityRefHandler \
- (parser->m_externalEntityRefHandler)
-#define externalEntityRefHandlerArg \
- (parser->m_externalEntityRefHandlerArg)
-#define internalEntityRefHandler \
- (parser->m_internalEntityRefHandler)
-#define skippedEntityHandler (parser->m_skippedEntityHandler)
-#define unknownEncodingHandler (parser->m_unknownEncodingHandler)
-#define elementDeclHandler (parser->m_elementDeclHandler)
-#define attlistDeclHandler (parser->m_attlistDeclHandler)
-#define entityDeclHandler (parser->m_entityDeclHandler)
-#define xmlDeclHandler (parser->m_xmlDeclHandler)
-#define encoding (parser->m_encoding)
-#define initEncoding (parser->m_initEncoding)
-#define internalEncoding (parser->m_internalEncoding)
-#define unknownEncodingMem (parser->m_unknownEncodingMem)
-#define unknownEncodingData (parser->m_unknownEncodingData)
-#define unknownEncodingHandlerData \
- (parser->m_unknownEncodingHandlerData)
-#define unknownEncodingRelease (parser->m_unknownEncodingRelease)
-#define protocolEncodingName (parser->m_protocolEncodingName)
-#define ns (parser->m_ns)
-#define ns_triplets (parser->m_ns_triplets)
-#define prologState (parser->m_prologState)
-#define processor (parser->m_processor)
-#define errorCode (parser->m_errorCode)
-#define eventPtr (parser->m_eventPtr)
-#define eventEndPtr (parser->m_eventEndPtr)
-#define positionPtr (parser->m_positionPtr)
-#define position (parser->m_position)
-#define openInternalEntities (parser->m_openInternalEntities)
-#define freeInternalEntities (parser->m_freeInternalEntities)
-#define defaultExpandInternalEntities \
- (parser->m_defaultExpandInternalEntities)
-#define tagLevel (parser->m_tagLevel)
-#define buffer (parser->m_buffer)
-#define bufferPtr (parser->m_bufferPtr)
-#define bufferEnd (parser->m_bufferEnd)
-#define parseEndByteIndex (parser->m_parseEndByteIndex)
-#define parseEndPtr (parser->m_parseEndPtr)
-#define bufferLim (parser->m_bufferLim)
-#define dataBuf (parser->m_dataBuf)
-#define dataBufEnd (parser->m_dataBufEnd)
-#define _dtd (parser->m_dtd)
-#define curBase (parser->m_curBase)
-#define declEntity (parser->m_declEntity)
-#define doctypeName (parser->m_doctypeName)
-#define doctypeSysid (parser->m_doctypeSysid)
-#define doctypePubid (parser->m_doctypePubid)
-#define declAttributeType (parser->m_declAttributeType)
-#define declNotationName (parser->m_declNotationName)
-#define declNotationPublicId (parser->m_declNotationPublicId)
-#define declElementType (parser->m_declElementType)
-#define declAttributeId (parser->m_declAttributeId)
-#define declAttributeIsCdata (parser->m_declAttributeIsCdata)
-#define declAttributeIsId (parser->m_declAttributeIsId)
-#define freeTagList (parser->m_freeTagList)
-#define freeBindingList (parser->m_freeBindingList)
-#define inheritedBindings (parser->m_inheritedBindings)
-#define tagStack (parser->m_tagStack)
-#define atts (parser->m_atts)
-#define attsSize (parser->m_attsSize)
-#define nSpecifiedAtts (parser->m_nSpecifiedAtts)
-#define idAttIndex (parser->m_idAttIndex)
-#define nsAtts (parser->m_nsAtts)
-#define nsAttsVersion (parser->m_nsAttsVersion)
-#define nsAttsPower (parser->m_nsAttsPower)
-#define attInfo (parser->m_attInfo)
-#define tempPool (parser->m_tempPool)
-#define temp2Pool (parser->m_temp2Pool)
-#define groupConnector (parser->m_groupConnector)
-#define groupSize (parser->m_groupSize)
-#define namespaceSeparator (parser->m_namespaceSeparator)
-#define parentParser (parser->m_parentParser)
-#define ps_parsing (parser->m_parsingStatus.parsing)
-#define ps_finalBuffer (parser->m_parsingStatus.finalBuffer)
-#ifdef XML_DTD
-#define isParamEntity (parser->m_isParamEntity)
-#define useForeignDTD (parser->m_useForeignDTD)
-#define paramEntityParsing (parser->m_paramEntityParsing)
-#endif /* XML_DTD */
-#define hash_secret_salt (parser->m_hash_secret_salt)
+#define MALLOC(parser, s) (parser->m_mem.malloc_fcn((s)))
+#define REALLOC(parser, p, s) (parser->m_mem.realloc_fcn((p),(s)))
+#define FREE(parser, p) (parser->m_mem.free_fcn((p)))
+
XML_Parser XMLCALL
XML_ParserCreate(const XML_Char *encodingName)
@@ -695,22 +667,17 @@ static const XML_Char implicitContext[] = {
};
-#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
-# include <errno.h>
+/* To avoid warnings about unused functions: */
+#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
-# if defined(HAVE_GETRANDOM)
-# include <sys/random.h> /* getrandom */
-# else
-# include <unistd.h> /* syscall */
-# include <sys/syscall.h> /* SYS_getrandom */
-# endif
+#if defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
/* Obtain entropy on Linux 3.17+ */
static int
-writeRandomBytes_getrandom(void * target, size_t count) {
+writeRandomBytes_getrandom_nonblock(void * target, size_t count) {
int success = 0; /* full count bytes written? */
size_t bytesWrittenTotal = 0;
- const unsigned int getrandomFlags = 0;
+ const unsigned int getrandomFlags = GRND_NONBLOCK;
do {
void * const currentTarget = (void*)((char*)target + bytesWrittenTotal);
@@ -728,7 +695,7 @@ writeRandomBytes_getrandom(void * target, size_t count) {
if (bytesWrittenTotal >= count)
success = 1;
}
- } while (! success && (errno == EINTR || errno == EAGAIN));
+ } while (! success && (errno == EINTR));
return success;
}
@@ -736,12 +703,69 @@ writeRandomBytes_getrandom(void * target, size_t count) {
#endif /* defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM) */
+#if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
+
+/* Extract entropy from /dev/urandom */
+static int
+writeRandomBytes_dev_urandom(void * target, size_t count) {
+ int success = 0; /* full count bytes written? */
+ size_t bytesWrittenTotal = 0;
+
+ const int fd = open("/dev/urandom", O_RDONLY);
+ if (fd < 0) {
+ return 0;
+ }
+
+ do {
+ void * const currentTarget = (void*)((char*)target + bytesWrittenTotal);
+ const size_t bytesToWrite = count - bytesWrittenTotal;
+
+ const ssize_t bytesWrittenMore = read(fd, currentTarget, bytesToWrite);
+
+ if (bytesWrittenMore > 0) {
+ bytesWrittenTotal += bytesWrittenMore;
+ if (bytesWrittenTotal >= count)
+ success = 1;
+ }
+ } while (! success && (errno == EINTR));
+
+ close(fd);
+ return success;
+}
+
+#endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
+
+#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
+
+
+#if defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF)
+
+static void
+writeRandomBytes_arc4random(void * target, size_t count) {
+ size_t bytesWrittenTotal = 0;
+
+ while (bytesWrittenTotal < count) {
+ const uint32_t random32 = arc4random();
+ size_t i = 0;
+
+ for (; (i < sizeof(random32)) && (bytesWrittenTotal < count);
+ i++, bytesWrittenTotal++) {
+ const uint8_t random8 = (uint8_t)(random32 >> (i * 8));
+ ((uint8_t *)target)[bytesWrittenTotal] = random8;
+ }
+ }
+}
+
+#endif /* defined(HAVE_ARC4RANDOM) && ! defined(HAVE_ARC4RANDOM_BUF) */
+
+
#ifdef _WIN32
typedef BOOLEAN (APIENTRY *RTLGENRANDOM_FUNC)(PVOID, ULONG);
+HMODULE _Expat_LoadLibrary(LPCTSTR filename); /* see loadlibrary.c */
/* Obtain entropy on Windows XP / Windows Server 2003 and later.
- * Hint on RtlGenRandom and the following article from libsodioum.
+ * Hint on RtlGenRandom and the following article from libsodium.
*
* Michael Howard: Cryptographically Secure Random number on Windows without using CryptoAPI
* https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/
@@ -749,7 +773,7 @@ typedef BOOLEAN (APIENTRY *RTLGENRANDOM_FUNC)(PVOID, ULONG);
static int
writeRandomBytes_RtlGenRandom(void * target, size_t count) {
int success = 0; /* full count bytes written? */
- const HMODULE advapi32 = LoadLibrary("ADVAPI32.DLL");
+ const HMODULE advapi32 = _Expat_LoadLibrary(TEXT("ADVAPI32.DLL"));
if (advapi32) {
const RTLGENRANDOM_FUNC RtlGenRandom
@@ -768,6 +792,8 @@ writeRandomBytes_RtlGenRandom(void * target, size_t count) {
#endif /* _WIN32 */
+#if ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM)
+
static unsigned long
gather_time_entropy(void)
{
@@ -780,16 +806,20 @@ gather_time_entropy(void)
int gettimeofday_res;
gettimeofday_res = gettimeofday(&tv, NULL);
+
+#if defined(NDEBUG)
+ (void)gettimeofday_res;
+#else
assert (gettimeofday_res == 0);
+#endif /* defined(NDEBUG) */
/* Microseconds time is <20 bits entropy */
return tv.tv_usec;
#endif
}
-#if defined(HAVE_ARC4RANDOM_BUF) && defined(HAVE_LIBBSD)
-# include <bsd/stdlib.h>
-#endif
+#endif /* ! defined(HAVE_ARC4RANDOM_BUF) && ! defined(HAVE_ARC4RANDOM) */
+
static unsigned long
ENTROPY_DEBUG(const char * label, unsigned long entropy) {
@@ -808,10 +838,14 @@ generate_hash_secret_salt(XML_Parser parser)
{
unsigned long entropy;
(void)parser;
-#if defined(HAVE_ARC4RANDOM_BUF) || defined(__CloudABI__)
- (void)gather_time_entropy;
+
+ /* "Failproof" high quality providers: */
+#if defined(HAVE_ARC4RANDOM_BUF)
arc4random_buf(&entropy, sizeof(entropy));
return ENTROPY_DEBUG("arc4random_buf", entropy);
+#elif defined(HAVE_ARC4RANDOM)
+ writeRandomBytes_arc4random((void *)&entropy, sizeof(entropy));
+ return ENTROPY_DEBUG("arc4random", entropy);
#else
/* Try high quality providers first .. */
#ifdef _WIN32
@@ -819,10 +853,15 @@ generate_hash_secret_salt(XML_Parser parser)
return ENTROPY_DEBUG("RtlGenRandom", entropy);
}
#elif defined(HAVE_GETRANDOM) || defined(HAVE_SYSCALL_GETRANDOM)
- if (writeRandomBytes_getrandom((void *)&entropy, sizeof(entropy))) {
+ if (writeRandomBytes_getrandom_nonblock((void *)&entropy, sizeof(entropy))) {
return ENTROPY_DEBUG("getrandom", entropy);
}
#endif
+#if ! defined(_WIN32) && defined(XML_DEV_URANDOM)
+ if (writeRandomBytes_dev_urandom((void *)&entropy, sizeof(entropy))) {
+ return ENTROPY_DEBUG("/dev/urandom", entropy);
+ }
+#endif /* ! defined(_WIN32) && defined(XML_DEV_URANDOM) */
/* .. and self-made low quality for backup: */
/* Process ID is 0 bits entropy if attacker has local access */
@@ -833,7 +872,7 @@ generate_hash_secret_salt(XML_Parser parser)
return ENTROPY_DEBUG("fallback(4)", entropy * 2147483647);
} else {
return ENTROPY_DEBUG("fallback(8)",
- entropy * (unsigned long)2305843009213693951);
+ entropy * (unsigned long)2305843009213693951ULL);
}
#endif
}
@@ -849,9 +888,9 @@ static XML_Bool /* only valid for root parser */
startParsing(XML_Parser parser)
{
/* hash functions must be initialized before setContext() is called */
- if (hash_secret_salt == 0)
- hash_secret_salt = generate_hash_secret_salt(parser);
- if (ns) {
+ if (parser->m_hash_secret_salt == 0)
+ parser->m_hash_secret_salt = generate_hash_secret_salt(parser);
+ if (parser->m_ns) {
/* implicit context only set for root parser, since child
parsers (i.e. external entity parsers) will inherit it
*/
@@ -901,83 +940,85 @@ parserCreate(const XML_Char *encodingName,
if (!parser)
return parser;
- buffer = NULL;
- bufferLim = NULL;
+ parser->m_buffer = NULL;
+ parser->m_bufferLim = NULL;
- attsSize = INIT_ATTS_SIZE;
- atts = (ATTRIBUTE *)MALLOC(attsSize * sizeof(ATTRIBUTE));
- if (atts == NULL) {
- FREE(parser);
+ parser->m_attsSize = INIT_ATTS_SIZE;
+ parser->m_atts = (ATTRIBUTE *)MALLOC(parser, parser->m_attsSize * sizeof(ATTRIBUTE));
+ if (parser->m_atts == NULL) {
+ FREE(parser, parser);
return NULL;
}
#ifdef XML_ATTR_INFO
- attInfo = (XML_AttrInfo*)MALLOC(attsSize * sizeof(XML_AttrInfo));
- if (attInfo == NULL) {
- FREE(atts);
- FREE(parser);
+ parser->m_attInfo = (XML_AttrInfo*)MALLOC(parser, parser->m_attsSize * sizeof(XML_AttrInfo));
+ if (parser->m_attInfo == NULL) {
+ FREE(parser, parser->m_atts);
+ FREE(parser, parser);
return NULL;
}
#endif
- dataBuf = (XML_Char *)MALLOC(INIT_DATA_BUF_SIZE * sizeof(XML_Char));
- if (dataBuf == NULL) {
- FREE(atts);
+ parser->m_dataBuf = (XML_Char *)MALLOC(parser, INIT_DATA_BUF_SIZE * sizeof(XML_Char));
+ if (parser->m_dataBuf == NULL) {
+ FREE(parser, parser->m_atts);
#ifdef XML_ATTR_INFO
- FREE(attInfo);
+ FREE(parser, parser->m_attInfo);
#endif
- FREE(parser);
+ FREE(parser, parser);
return NULL;
}
- dataBufEnd = dataBuf + INIT_DATA_BUF_SIZE;
+ parser->m_dataBufEnd = parser->m_dataBuf + INIT_DATA_BUF_SIZE;
if (dtd)
- _dtd = dtd;
+ parser->m_dtd = dtd;
else {
- _dtd = dtdCreate(&parser->m_mem);
- if (_dtd == NULL) {
- FREE(dataBuf);
- FREE(atts);
+ parser->m_dtd = dtdCreate(&parser->m_mem);
+ if (parser->m_dtd == NULL) {
+ FREE(parser, parser->m_dataBuf);
+ FREE(parser, parser->m_atts);
#ifdef XML_ATTR_INFO
- FREE(attInfo);
+ FREE(parser, parser->m_attInfo);
#endif
- FREE(parser);
+ FREE(parser, parser);
return NULL;
}
}
- freeBindingList = NULL;
- freeTagList = NULL;
- freeInternalEntities = NULL;
+ parser->m_freeBindingList = NULL;
+ parser->m_freeTagList = NULL;
+ parser->m_freeInternalEntities = NULL;
+
+ parser->m_groupSize = 0;
+ parser->m_groupConnector = NULL;
- groupSize = 0;
- groupConnector = NULL;
+ parser->m_unknownEncodingHandler = NULL;
+ parser->m_unknownEncodingHandlerData = NULL;
- unknownEncodingHandler = NULL;
- unknownEncodingHandlerData = NULL;
+ parser->m_namespaceSeparator = ASCII_EXCL;
+ parser->m_ns = XML_FALSE;
+ parser->m_ns_triplets = XML_FALSE;
- namespaceSeparator = ASCII_EXCL;
- ns = XML_FALSE;
- ns_triplets = XML_FALSE;
+ parser->m_nsAtts = NULL;
+ parser->m_nsAttsVersion = 0;
+ parser->m_nsAttsPower = 0;
- nsAtts = NULL;
- nsAttsVersion = 0;
- nsAttsPower = 0;
+ parser->m_protocolEncodingName = NULL;
- poolInit(&tempPool, &(parser->m_mem));
- poolInit(&temp2Pool, &(parser->m_mem));
+ poolInit(&parser->m_tempPool, &(parser->m_mem));
+ poolInit(&parser->m_temp2Pool, &(parser->m_mem));
parserInit(parser, encodingName);
- if (encodingName && !protocolEncodingName) {
+ if (encodingName && !parser->m_protocolEncodingName) {
XML_ParserFree(parser);
return NULL;
}
if (nameSep) {
- ns = XML_TRUE;
- internalEncoding = XmlGetInternalEncodingNS();
- namespaceSeparator = *nameSep;
+ parser->m_ns = XML_TRUE;
+ parser->m_internalEncoding = XmlGetInternalEncodingNS();
+ parser->m_namespaceSeparator = *nameSep;
}
else {
- internalEncoding = XmlGetInternalEncoding();
+ parser->m_internalEncoding = XmlGetInternalEncoding();
}
return parser;
@@ -986,85 +1027,85 @@ parserCreate(const XML_Char *encodingName,
static void
parserInit(XML_Parser parser, const XML_Char *encodingName)
{
- processor = prologInitProcessor;
- XmlPrologStateInit(&prologState);
- protocolEncodingName = (encodingName != NULL
- ? poolCopyString(&tempPool, encodingName)
- : NULL);
- curBase = NULL;
- XmlInitEncoding(&initEncoding, &encoding, 0);
- userData = NULL;
- handlerArg = NULL;
- startElementHandler = NULL;
- endElementHandler = NULL;
- characterDataHandler = NULL;
- processingInstructionHandler = NULL;
- commentHandler = NULL;
- startCdataSectionHandler = NULL;
- endCdataSectionHandler = NULL;
- defaultHandler = NULL;
- startDoctypeDeclHandler = NULL;
- endDoctypeDeclHandler = NULL;
- unparsedEntityDeclHandler = NULL;
- notationDeclHandler = NULL;
- startNamespaceDeclHandler = NULL;
- endNamespaceDeclHandler = NULL;
- notStandaloneHandler = NULL;
- externalEntityRefHandler = NULL;
- externalEntityRefHandlerArg = parser;
- skippedEntityHandler = NULL;
- elementDeclHandler = NULL;
- attlistDeclHandler = NULL;
- entityDeclHandler = NULL;
- xmlDeclHandler = NULL;
- bufferPtr = buffer;
- bufferEnd = buffer;
- parseEndByteIndex = 0;
- parseEndPtr = NULL;
- declElementType = NULL;
- declAttributeId = NULL;
- declEntity = NULL;
- doctypeName = NULL;
- doctypeSysid = NULL;
- doctypePubid = NULL;
- declAttributeType = NULL;
- declNotationName = NULL;
- declNotationPublicId = NULL;
- declAttributeIsCdata = XML_FALSE;
- declAttributeIsId = XML_FALSE;
- memset(&position, 0, sizeof(POSITION));
- errorCode = XML_ERROR_NONE;
- eventPtr = NULL;
- eventEndPtr = NULL;
- positionPtr = NULL;
- openInternalEntities = NULL;
- defaultExpandInternalEntities = XML_TRUE;
- tagLevel = 0;
- tagStack = NULL;
- inheritedBindings = NULL;
- nSpecifiedAtts = 0;
- unknownEncodingMem = NULL;
- unknownEncodingRelease = NULL;
- unknownEncodingData = NULL;
- parentParser = NULL;
- ps_parsing = XML_INITIALIZED;
+ parser->m_processor = prologInitProcessor;
+ XmlPrologStateInit(&parser->m_prologState);
+ if (encodingName != NULL) {
+ parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
+ }
+ parser->m_curBase = NULL;
+ XmlInitEncoding(&parser->m_initEncoding, &parser->m_encoding, 0);
+ parser->m_userData = NULL;
+ parser->m_handlerArg = NULL;
+ parser->m_startElementHandler = NULL;
+ parser->m_endElementHandler = NULL;
+ parser->m_characterDataHandler = NULL;
+ parser->m_processingInstructionHandler = NULL;
+ parser->m_commentHandler = NULL;
+ parser->m_startCdataSectionHandler = NULL;
+ parser->m_endCdataSectionHandler = NULL;
+ parser->m_defaultHandler = NULL;
+ parser->m_startDoctypeDeclHandler = NULL;
+ parser->m_endDoctypeDeclHandler = NULL;
+ parser->m_unparsedEntityDeclHandler = NULL;
+ parser->m_notationDeclHandler = NULL;
+ parser->m_startNamespaceDeclHandler = NULL;
+ parser->m_endNamespaceDeclHandler = NULL;
+ parser->m_notStandaloneHandler = NULL;
+ parser->m_externalEntityRefHandler = NULL;
+ parser->m_externalEntityRefHandlerArg = parser;
+ parser->m_skippedEntityHandler = NULL;
+ parser->m_elementDeclHandler = NULL;
+ parser->m_attlistDeclHandler = NULL;
+ parser->m_entityDeclHandler = NULL;
+ parser->m_xmlDeclHandler = NULL;
+ parser->m_bufferPtr = parser->m_buffer;
+ parser->m_bufferEnd = parser->m_buffer;
+ parser->m_parseEndByteIndex = 0;
+ parser->m_parseEndPtr = NULL;
+ parser->m_declElementType = NULL;
+ parser->m_declAttributeId = NULL;
+ parser->m_declEntity = NULL;
+ parser->m_doctypeName = NULL;
+ parser->m_doctypeSysid = NULL;
+ parser->m_doctypePubid = NULL;
+ parser->m_declAttributeType = NULL;
+ parser->m_declNotationName = NULL;
+ parser->m_declNotationPublicId = NULL;
+ parser->m_declAttributeIsCdata = XML_FALSE;
+ parser->m_declAttributeIsId = XML_FALSE;
+ memset(&parser->m_position, 0, sizeof(POSITION));
+ parser->m_errorCode = XML_ERROR_NONE;
+ parser->m_eventPtr = NULL;
+ parser->m_eventEndPtr = NULL;
+ parser->m_positionPtr = NULL;
+ parser->m_openInternalEntities = NULL;
+ parser->m_defaultExpandInternalEntities = XML_TRUE;
+ parser->m_tagLevel = 0;
+ parser->m_tagStack = NULL;
+ parser->m_inheritedBindings = NULL;
+ parser->m_nSpecifiedAtts = 0;
+ parser->m_unknownEncodingMem = NULL;
+ parser->m_unknownEncodingRelease = NULL;
+ parser->m_unknownEncodingData = NULL;
+ parser->m_parentParser = NULL;
+ parser->m_parsingStatus.parsing = XML_INITIALIZED;
#ifdef XML_DTD
- isParamEntity = XML_FALSE;
- useForeignDTD = XML_FALSE;
- paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
+ parser->m_isParamEntity = XML_FALSE;
+ parser->m_useForeignDTD = XML_FALSE;
+ parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#endif
- hash_secret_salt = 0;
+ parser->m_hash_secret_salt = 0;
}
-/* moves list of bindings to freeBindingList */
+/* moves list of bindings to m_freeBindingList */
static void FASTCALL
moveToFreeBindingList(XML_Parser parser, BINDING *bindings)
{
while (bindings) {
BINDING *b = bindings;
bindings = bindings->nextTagBinding;
- b->nextTagBinding = freeBindingList;
- freeBindingList = b;
+ b->nextTagBinding = parser->m_freeBindingList;
+ parser->m_freeBindingList = b;
}
}
@@ -1077,34 +1118,36 @@ XML_ParserReset(XML_Parser parser, const XML_Char *encodingName)
if (parser == NULL)
return XML_FALSE;
- if (parentParser)
+ if (parser->m_parentParser)
return XML_FALSE;
- /* move tagStack to freeTagList */
- tStk = tagStack;
+ /* move m_tagStack to m_freeTagList */
+ tStk = parser->m_tagStack;
while (tStk) {
TAG *tag = tStk;
tStk = tStk->parent;
- tag->parent = freeTagList;
+ tag->parent = parser->m_freeTagList;
moveToFreeBindingList(parser, tag->bindings);
tag->bindings = NULL;
- freeTagList = tag;
+ parser->m_freeTagList = tag;
}
- /* move openInternalEntities to freeInternalEntities */
- openEntityList = openInternalEntities;
+ /* move m_openInternalEntities to m_freeInternalEntities */
+ openEntityList = parser->m_openInternalEntities;
while (openEntityList) {
OPEN_INTERNAL_ENTITY *openEntity = openEntityList;
openEntityList = openEntity->next;
- openEntity->next = freeInternalEntities;
- freeInternalEntities = openEntity;
- }
- moveToFreeBindingList(parser, inheritedBindings);
- FREE(unknownEncodingMem);
- if (unknownEncodingRelease)
- unknownEncodingRelease(unknownEncodingData);
- poolClear(&tempPool);
- poolClear(&temp2Pool);
+ openEntity->next = parser->m_freeInternalEntities;
+ parser->m_freeInternalEntities = openEntity;
+ }
+ moveToFreeBindingList(parser, parser->m_inheritedBindings);
+ FREE(parser, parser->m_unknownEncodingMem);
+ if (parser->m_unknownEncodingRelease)
+ parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
+ poolClear(&parser->m_tempPool);
+ poolClear(&parser->m_temp2Pool);
+ FREE(parser, (void *)parser->m_protocolEncodingName);
+ parser->m_protocolEncodingName = NULL;
parserInit(parser, encodingName);
- dtdReset(_dtd, &parser->m_mem);
+ dtdReset(parser->m_dtd, &parser->m_mem);
return XML_TRUE;
}
@@ -1117,13 +1160,19 @@ XML_SetEncoding(XML_Parser parser, const XML_Char *encodingName)
XXX There's no way for the caller to determine which of the
XXX possible error cases caused the XML_STATUS_ERROR return.
*/
- if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
+ if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return XML_STATUS_ERROR;
+
+ /* Get rid of any previous encoding name */
+ FREE(parser, (void *)parser->m_protocolEncodingName);
+
if (encodingName == NULL)
- protocolEncodingName = NULL;
+ /* No new encoding name */
+ parser->m_protocolEncodingName = NULL;
else {
- protocolEncodingName = poolCopyString(&tempPool, encodingName);
- if (!protocolEncodingName)
+ /* Copy the new encoding name into allocated memory */
+ parser->m_protocolEncodingName = copyString(encodingName, &(parser->m_mem));
+ if (!parser->m_protocolEncodingName)
return XML_STATUS_ERROR;
}
return XML_STATUS_OK;
@@ -1180,44 +1229,44 @@ XML_ExternalEntityParserCreate(XML_Parser oldParser,
return NULL;
/* Stash the original parser contents on the stack */
- oldDtd = _dtd;
- oldStartElementHandler = startElementHandler;
- oldEndElementHandler = endElementHandler;
- oldCharacterDataHandler = characterDataHandler;
- oldProcessingInstructionHandler = processingInstructionHandler;
- oldCommentHandler = commentHandler;
- oldStartCdataSectionHandler = startCdataSectionHandler;
- oldEndCdataSectionHandler = endCdataSectionHandler;
- oldDefaultHandler = defaultHandler;
- oldUnparsedEntityDeclHandler = unparsedEntityDeclHandler;
- oldNotationDeclHandler = notationDeclHandler;
- oldStartNamespaceDeclHandler = startNamespaceDeclHandler;
- oldEndNamespaceDeclHandler = endNamespaceDeclHandler;
- oldNotStandaloneHandler = notStandaloneHandler;
- oldExternalEntityRefHandler = externalEntityRefHandler;
- oldSkippedEntityHandler = skippedEntityHandler;
- oldUnknownEncodingHandler = unknownEncodingHandler;
- oldElementDeclHandler = elementDeclHandler;
- oldAttlistDeclHandler = attlistDeclHandler;
- oldEntityDeclHandler = entityDeclHandler;
- oldXmlDeclHandler = xmlDeclHandler;
- oldDeclElementType = declElementType;
-
- oldUserData = userData;
- oldHandlerArg = handlerArg;
- oldDefaultExpandInternalEntities = defaultExpandInternalEntities;
- oldExternalEntityRefHandlerArg = externalEntityRefHandlerArg;
+ oldDtd = parser->m_dtd;
+ oldStartElementHandler = parser->m_startElementHandler;
+ oldEndElementHandler = parser->m_endElementHandler;
+ oldCharacterDataHandler = parser->m_characterDataHandler;
+ oldProcessingInstructionHandler = parser->m_processingInstructionHandler;
+ oldCommentHandler = parser->m_commentHandler;
+ oldStartCdataSectionHandler = parser->m_startCdataSectionHandler;
+ oldEndCdataSectionHandler = parser->m_endCdataSectionHandler;
+ oldDefaultHandler = parser->m_defaultHandler;
+ oldUnparsedEntityDeclHandler = parser->m_unparsedEntityDeclHandler;
+ oldNotationDeclHandler = parser->m_notationDeclHandler;
+ oldStartNamespaceDeclHandler = parser->m_startNamespaceDeclHandler;
+ oldEndNamespaceDeclHandler = parser->m_endNamespaceDeclHandler;
+ oldNotStandaloneHandler = parser->m_notStandaloneHandler;
+ oldExternalEntityRefHandler = parser->m_externalEntityRefHandler;
+ oldSkippedEntityHandler = parser->m_skippedEntityHandler;
+ oldUnknownEncodingHandler = parser->m_unknownEncodingHandler;
+ oldElementDeclHandler = parser->m_elementDeclHandler;
+ oldAttlistDeclHandler = parser->m_attlistDeclHandler;
+ oldEntityDeclHandler = parser->m_entityDeclHandler;
+ oldXmlDeclHandler = parser->m_xmlDeclHandler;
+ oldDeclElementType = parser->m_declElementType;
+
+ oldUserData = parser->m_userData;
+ oldHandlerArg = parser->m_handlerArg;
+ oldDefaultExpandInternalEntities = parser->m_defaultExpandInternalEntities;
+ oldExternalEntityRefHandlerArg = parser->m_externalEntityRefHandlerArg;
#ifdef XML_DTD
- oldParamEntityParsing = paramEntityParsing;
- oldInEntityValue = prologState.inEntityValue;
+ oldParamEntityParsing = parser->m_paramEntityParsing;
+ oldInEntityValue = parser->m_prologState.inEntityValue;
#endif
- oldns_triplets = ns_triplets;
+ oldns_triplets = parser->m_ns_triplets;
/* Note that the new parser shares the same hash secret as the old
parser, so that dtdCopy and copyEntityTable can lookup values
from hash tables associated with either parser without us having
to worry which hash secrets each table has.
*/
- oldhash_secret_salt = hash_secret_salt;
+ oldhash_secret_salt = parser->m_hash_secret_salt;
#ifdef XML_DTD
if (!context)
@@ -1229,9 +1278,9 @@ XML_ExternalEntityParserCreate(XML_Parser oldParser,
here. This makes this function more painful to follow than it
would be otherwise.
*/
- if (ns) {
+ if (parser->m_ns) {
XML_Char tmp[2];
- *tmp = namespaceSeparator;
+ *tmp = parser->m_namespaceSeparator;
parser = parserCreate(encodingName, &parser->m_mem, tmp, newDtd);
}
else {
@@ -1241,62 +1290,62 @@ XML_ExternalEntityParserCreate(XML_Parser oldParser,
if (!parser)
return NULL;
- startElementHandler = oldStartElementHandler;
- endElementHandler = oldEndElementHandler;
- characterDataHandler = oldCharacterDataHandler;
- processingInstructionHandler = oldProcessingInstructionHandler;
- commentHandler = oldCommentHandler;
- startCdataSectionHandler = oldStartCdataSectionHandler;
- endCdataSectionHandler = oldEndCdataSectionHandler;
- defaultHandler = oldDefaultHandler;
- unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
- notationDeclHandler = oldNotationDeclHandler;
- startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
- endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
- notStandaloneHandler = oldNotStandaloneHandler;
- externalEntityRefHandler = oldExternalEntityRefHandler;
- skippedEntityHandler = oldSkippedEntityHandler;
- unknownEncodingHandler = oldUnknownEncodingHandler;
- elementDeclHandler = oldElementDeclHandler;
- attlistDeclHandler = oldAttlistDeclHandler;
- entityDeclHandler = oldEntityDeclHandler;
- xmlDeclHandler = oldXmlDeclHandler;
- declElementType = oldDeclElementType;
- userData = oldUserData;
+ parser->m_startElementHandler = oldStartElementHandler;
+ parser->m_endElementHandler = oldEndElementHandler;
+ parser->m_characterDataHandler = oldCharacterDataHandler;
+ parser->m_processingInstructionHandler = oldProcessingInstructionHandler;
+ parser->m_commentHandler = oldCommentHandler;
+ parser->m_startCdataSectionHandler = oldStartCdataSectionHandler;
+ parser->m_endCdataSectionHandler = oldEndCdataSectionHandler;
+ parser->m_defaultHandler = oldDefaultHandler;
+ parser->m_unparsedEntityDeclHandler = oldUnparsedEntityDeclHandler;
+ parser->m_notationDeclHandler = oldNotationDeclHandler;
+ parser->m_startNamespaceDeclHandler = oldStartNamespaceDeclHandler;
+ parser->m_endNamespaceDeclHandler = oldEndNamespaceDeclHandler;
+ parser->m_notStandaloneHandler = oldNotStandaloneHandler;
+ parser->m_externalEntityRefHandler = oldExternalEntityRefHandler;
+ parser->m_skippedEntityHandler = oldSkippedEntityHandler;
+ parser->m_unknownEncodingHandler = oldUnknownEncodingHandler;
+ parser->m_elementDeclHandler = oldElementDeclHandler;
+ parser->m_attlistDeclHandler = oldAttlistDeclHandler;
+ parser->m_entityDeclHandler = oldEntityDeclHandler;
+ parser->m_xmlDeclHandler = oldXmlDeclHandler;
+ parser->m_declElementType = oldDeclElementType;
+ parser->m_userData = oldUserData;
if (oldUserData == oldHandlerArg)
- handlerArg = userData;
+ parser->m_handlerArg = parser->m_userData;
else
- handlerArg = parser;
+ parser->m_handlerArg = parser;
if (oldExternalEntityRefHandlerArg != oldParser)
- externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
- defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
- ns_triplets = oldns_triplets;
- hash_secret_salt = oldhash_secret_salt;
- parentParser = oldParser;
+ parser->m_externalEntityRefHandlerArg = oldExternalEntityRefHandlerArg;
+ parser->m_defaultExpandInternalEntities = oldDefaultExpandInternalEntities;
+ parser->m_ns_triplets = oldns_triplets;
+ parser->m_hash_secret_salt = oldhash_secret_salt;
+ parser->m_parentParser = oldParser;
#ifdef XML_DTD
- paramEntityParsing = oldParamEntityParsing;
- prologState.inEntityValue = oldInEntityValue;
+ parser->m_paramEntityParsing = oldParamEntityParsing;
+ parser->m_prologState.inEntityValue = oldInEntityValue;
if (context) {
#endif /* XML_DTD */
- if (!dtdCopy(oldParser, _dtd, oldDtd, &parser->m_mem)
+ if (!dtdCopy(oldParser, parser->m_dtd, oldDtd, &parser->m_mem)
|| !setContext(parser, context)) {
XML_ParserFree(parser);
return NULL;
}
- processor = externalEntityInitProcessor;
+ parser->m_processor = externalEntityInitProcessor;
#ifdef XML_DTD
}
else {
- /* The DTD instance referenced by _dtd is shared between the document's
+ /* The DTD instance referenced by parser->m_dtd is shared between the document's
root parser and external PE parsers, therefore one does not need to
call setContext. In addition, one also *must* not call setContext,
because this would overwrite existing prefix->binding pointers in
- _dtd with ones that get destroyed with the external PE parser.
+ parser->m_dtd with ones that get destroyed with the external PE parser.
This would leave those prefixes with dangling pointers.
*/
- isParamEntity = XML_TRUE;
- XmlPrologStateInitExternalEntity(&prologState);
- processor = externalParEntInitProcessor;
+ parser->m_isParamEntity = XML_TRUE;
+ XmlPrologStateInitExternalEntity(&parser->m_prologState);
+ parser->m_processor = externalParEntInitProcessor;
}
#endif /* XML_DTD */
return parser;
@@ -1310,8 +1359,8 @@ destroyBindings(BINDING *bindings, XML_Parser parser)
if (!b)
break;
bindings = b->nextTagBinding;
- FREE(b->uri);
- FREE(b);
+ FREE(parser, b->uri);
+ FREE(parser, b);
}
}
@@ -1322,69 +1371,70 @@ XML_ParserFree(XML_Parser parser)
OPEN_INTERNAL_ENTITY *entityList;
if (parser == NULL)
return;
- /* free tagStack and freeTagList */
- tagList = tagStack;
+ /* free m_tagStack and m_freeTagList */
+ tagList = parser->m_tagStack;
for (;;) {
TAG *p;
if (tagList == NULL) {
- if (freeTagList == NULL)
+ if (parser->m_freeTagList == NULL)
break;
- tagList = freeTagList;
- freeTagList = NULL;
+ tagList = parser->m_freeTagList;
+ parser->m_freeTagList = NULL;
}
p = tagList;
tagList = tagList->parent;
- FREE(p->buf);
+ FREE(parser, p->buf);
destroyBindings(p->bindings, parser);
- FREE(p);
+ FREE(parser, p);
}
- /* free openInternalEntities and freeInternalEntities */
- entityList = openInternalEntities;
+ /* free m_openInternalEntities and m_freeInternalEntities */
+ entityList = parser->m_openInternalEntities;
for (;;) {
OPEN_INTERNAL_ENTITY *openEntity;
if (entityList == NULL) {
- if (freeInternalEntities == NULL)
+ if (parser->m_freeInternalEntities == NULL)
break;
- entityList = freeInternalEntities;
- freeInternalEntities = NULL;
+ entityList = parser->m_freeInternalEntities;
+ parser->m_freeInternalEntities = NULL;
}
openEntity = entityList;
entityList = entityList->next;
- FREE(openEntity);
+ FREE(parser, openEntity);
}
- destroyBindings(freeBindingList, parser);
- destroyBindings(inheritedBindings, parser);
- poolDestroy(&tempPool);
- poolDestroy(&temp2Pool);
+ destroyBindings(parser->m_freeBindingList, parser);
+ destroyBindings(parser->m_inheritedBindings, parser);
+ poolDestroy(&parser->m_tempPool);
+ poolDestroy(&parser->m_temp2Pool);
+ FREE(parser, (void *)parser->m_protocolEncodingName);
#ifdef XML_DTD
/* external parameter entity parsers share the DTD structure
parser->m_dtd with the root parser, so we must not destroy it
*/
- if (!isParamEntity && _dtd)
+ if (!parser->m_isParamEntity && parser->m_dtd)
#else
- if (_dtd)
+ if (parser->m_dtd)
#endif /* XML_DTD */
- dtdDestroy(_dtd, (XML_Bool)!parentParser, &parser->m_mem);
- FREE((void *)atts);
+ dtdDestroy(parser->m_dtd, (XML_Bool)!parser->m_parentParser, &parser->m_mem);
+ FREE(parser, (void *)parser->m_atts);
#ifdef XML_ATTR_INFO
- FREE((void *)attInfo);
+ FREE(parser, (void *)parser->m_attInfo);
#endif
- FREE(groupConnector);
- FREE(buffer);
- FREE(dataBuf);
- FREE(nsAtts);
- FREE(unknownEncodingMem);
- if (unknownEncodingRelease)
- unknownEncodingRelease(unknownEncodingData);
- FREE(parser);
+ FREE(parser, parser->m_groupConnector);
+ FREE(parser, parser->m_buffer);
+ FREE(parser, parser->m_dataBuf);
+ FREE(parser, parser->m_nsAtts);
+ FREE(parser, parser->m_unknownEncodingMem);
+ if (parser->m_unknownEncodingRelease)
+ parser->m_unknownEncodingRelease(parser->m_unknownEncodingData);
+ FREE(parser, parser);
}
void XMLCALL
XML_UseParserAsHandlerArg(XML_Parser parser)
{
if (parser != NULL)
- handlerArg = parser;
+ parser->m_handlerArg = parser;
}
enum XML_Error XMLCALL
@@ -1394,9 +1444,9 @@ XML_UseForeignDTD(XML_Parser parser, XML_Bool useDTD)
return XML_ERROR_INVALID_ARGUMENT;
#ifdef XML_DTD
/* block after XML_Parse()/XML_ParseBuffer() has been called */
- if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
+ if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING;
- useForeignDTD = useDTD;
+ parser->m_useForeignDTD = useDTD;
return XML_ERROR_NONE;
#else
return XML_ERROR_FEATURE_REQUIRES_XML_DTD;
@@ -1409,9 +1459,9 @@ XML_SetReturnNSTriplet(XML_Parser parser, int do_nst)
if (parser == NULL)
return;
/* block after XML_Parse()/XML_ParseBuffer() has been called */
- if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
+ if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return;
- ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
+ parser->m_ns_triplets = do_nst ? XML_TRUE : XML_FALSE;
}
void XMLCALL
@@ -1419,10 +1469,10 @@ XML_SetUserData(XML_Parser parser, void *p)
{
if (parser == NULL)
return;
- if (handlerArg == userData)
- handlerArg = userData = p;
+ if (parser->m_handlerArg == parser->m_userData)
+ parser->m_handlerArg = parser->m_userData = p;
else
- userData = p;
+ parser->m_userData = p;
}
enum XML_Status XMLCALL
@@ -1431,13 +1481,13 @@ XML_SetBase(XML_Parser parser, const XML_Char *p)
if (parser == NULL)
return XML_STATUS_ERROR;
if (p) {
- p = poolCopyString(&_dtd->pool, p);
+ p = poolCopyString(&parser->m_dtd->pool, p);
if (!p)
return XML_STATUS_ERROR;
- curBase = p;
+ parser->m_curBase = p;
}
else
- curBase = NULL;
+ parser->m_curBase = NULL;
return XML_STATUS_OK;
}
@@ -1446,7 +1496,7 @@ XML_GetBase(XML_Parser parser)
{
if (parser == NULL)
return NULL;
- return curBase;
+ return parser->m_curBase;
}
int XMLCALL
@@ -1454,7 +1504,7 @@ XML_GetSpecifiedAttributeCount(XML_Parser parser)
{
if (parser == NULL)
return -1;
- return nSpecifiedAtts;
+ return parser->m_nSpecifiedAtts;
}
int XMLCALL
@@ -1462,7 +1512,7 @@ XML_GetIdAttributeIndex(XML_Parser parser)
{
if (parser == NULL)
return -1;
- return idAttIndex;
+ return parser->m_idAttIndex;
}
#ifdef XML_ATTR_INFO
@@ -1471,7 +1521,7 @@ XML_GetAttributeInfo(XML_Parser parser)
{
if (parser == NULL)
return NULL;
- return attInfo;
+ return parser->m_attInfo;
}
#endif
@@ -1482,22 +1532,22 @@ XML_SetElementHandler(XML_Parser parser,
{
if (parser == NULL)
return;
- startElementHandler = start;
- endElementHandler = end;
+ parser->m_startElementHandler = start;
+ parser->m_endElementHandler = end;
}
void XMLCALL
XML_SetStartElementHandler(XML_Parser parser,
XML_StartElementHandler start) {
if (parser != NULL)
- startElementHandler = start;
+ parser->m_startElementHandler = start;
}
void XMLCALL
XML_SetEndElementHandler(XML_Parser parser,
XML_EndElementHandler end) {
if (parser != NULL)
- endElementHandler = end;
+ parser->m_endElementHandler = end;
}
void XMLCALL
@@ -1505,7 +1555,7 @@ XML_SetCharacterDataHandler(XML_Parser parser,
XML_CharacterDataHandler handler)
{
if (parser != NULL)
- characterDataHandler = handler;
+ parser->m_characterDataHandler = handler;
}
void XMLCALL
@@ -1513,7 +1563,7 @@ XML_SetProcessingInstructionHandler(XML_Parser parser,
XML_ProcessingInstructionHandler handler)
{
if (parser != NULL)
- processingInstructionHandler = handler;
+ parser->m_processingInstructionHandler = handler;
}
void XMLCALL
@@ -1521,7 +1571,7 @@ XML_SetCommentHandler(XML_Parser parser,
XML_CommentHandler handler)
{
if (parser != NULL)
- commentHandler = handler;
+ parser->m_commentHandler = handler;
}
void XMLCALL
@@ -1531,22 +1581,22 @@ XML_SetCdataSectionHandler(XML_Parser parser,
{
if (parser == NULL)
return;
- startCdataSectionHandler = start;
- endCdataSectionHandler = end;
+ parser->m_startCdataSectionHandler = start;
+ parser->m_endCdataSectionHandler = end;
}
void XMLCALL
XML_SetStartCdataSectionHandler(XML_Parser parser,
XML_StartCdataSectionHandler start) {
if (parser != NULL)
- startCdataSectionHandler = start;
+ parser->m_startCdataSectionHandler = start;
}
void XMLCALL
XML_SetEndCdataSectionHandler(XML_Parser parser,
XML_EndCdataSectionHandler end) {
if (parser != NULL)
- endCdataSectionHandler = end;
+ parser->m_endCdataSectionHandler = end;
}
void XMLCALL
@@ -1555,8 +1605,8 @@ XML_SetDefaultHandler(XML_Parser parser,
{
if (parser == NULL)
return;
- defaultHandler = handler;
- defaultExpandInternalEntities = XML_FALSE;
+ parser->m_defaultHandler = handler;
+ parser->m_defaultExpandInternalEntities = XML_FALSE;
}
void XMLCALL
@@ -1565,8 +1615,8 @@ XML_SetDefaultHandlerExpand(XML_Parser parser,
{
if (parser == NULL)
return;
- defaultHandler = handler;
- defaultExpandInternalEntities = XML_TRUE;
+ parser->m_defaultHandler = handler;
+ parser->m_defaultExpandInternalEntities = XML_TRUE;
}
void XMLCALL
@@ -1576,22 +1626,22 @@ XML_SetDoctypeDeclHandler(XML_Parser parser,
{
if (parser == NULL)
return;
- startDoctypeDeclHandler = start;
- endDoctypeDeclHandler = end;
+ parser->m_startDoctypeDeclHandler = start;
+ parser->m_endDoctypeDeclHandler = end;
}
void XMLCALL
XML_SetStartDoctypeDeclHandler(XML_Parser parser,
XML_StartDoctypeDeclHandler start) {
if (parser != NULL)
- startDoctypeDeclHandler = start;
+ parser->m_startDoctypeDeclHandler = start;
}
void XMLCALL
XML_SetEndDoctypeDeclHandler(XML_Parser parser,
XML_EndDoctypeDeclHandler end) {
if (parser != NULL)
- endDoctypeDeclHandler = end;
+ parser->m_endDoctypeDeclHandler = end;
}
void XMLCALL
@@ -1599,7 +1649,7 @@ XML_SetUnparsedEntityDeclHandler(XML_Parser parser,
XML_UnparsedEntityDeclHandler handler)
{
if (parser != NULL)
- unparsedEntityDeclHandler = handler;
+ parser->m_unparsedEntityDeclHandler = handler;
}
void XMLCALL
@@ -1607,7 +1657,7 @@ XML_SetNotationDeclHandler(XML_Parser parser,
XML_NotationDeclHandler handler)
{
if (parser != NULL)
- notationDeclHandler = handler;
+ parser->m_notationDeclHandler = handler;
}
void XMLCALL
@@ -1617,22 +1667,22 @@ XML_SetNamespaceDeclHandler(XML_Parser parser,
{
if (parser == NULL)
return;
- startNamespaceDeclHandler = start;
- endNamespaceDeclHandler = end;
+ parser->m_startNamespaceDeclHandler = start;
+ parser->m_endNamespaceDeclHandler = end;
}
void XMLCALL
XML_SetStartNamespaceDeclHandler(XML_Parser parser,
XML_StartNamespaceDeclHandler start) {
if (parser != NULL)
- startNamespaceDeclHandler = start;
+ parser->m_startNamespaceDeclHandler = start;
}
void XMLCALL
XML_SetEndNamespaceDeclHandler(XML_Parser parser,
XML_EndNamespaceDeclHandler end) {
if (parser != NULL)
- endNamespaceDeclHandler = end;
+ parser->m_endNamespaceDeclHandler = end;
}
void XMLCALL
@@ -1640,7 +1690,7 @@ XML_SetNotStandaloneHandler(XML_Parser parser,
XML_NotStandaloneHandler handler)
{
if (parser != NULL)
- notStandaloneHandler = handler;
+ parser->m_notStandaloneHandler = handler;
}
void XMLCALL
@@ -1648,7 +1698,7 @@ XML_SetExternalEntityRefHandler(XML_Parser parser,
XML_ExternalEntityRefHandler handler)
{
if (parser != NULL)
- externalEntityRefHandler = handler;
+ parser->m_externalEntityRefHandler = handler;
}
void XMLCALL
@@ -1657,9 +1707,9 @@ XML_SetExternalEntityRefHandlerArg(XML_Parser parser, void *arg)
if (parser == NULL)
return;
if (arg)
- externalEntityRefHandlerArg = (XML_Parser)arg;
+ parser->m_externalEntityRefHandlerArg = (XML_Parser)arg;
else
- externalEntityRefHandlerArg = parser;
+ parser->m_externalEntityRefHandlerArg = parser;
}
void XMLCALL
@@ -1667,7 +1717,7 @@ XML_SetSkippedEntityHandler(XML_Parser parser,
XML_SkippedEntityHandler handler)
{
if (parser != NULL)
- skippedEntityHandler = handler;
+ parser->m_skippedEntityHandler = handler;
}
void XMLCALL
@@ -1677,8 +1727,8 @@ XML_SetUnknownEncodingHandler(XML_Parser parser,
{
if (parser == NULL)
return;
- unknownEncodingHandler = handler;
- unknownEncodingHandlerData = data;
+ parser->m_unknownEncodingHandler = handler;
+ parser->m_unknownEncodingHandlerData = data;
}
void XMLCALL
@@ -1686,7 +1736,7 @@ XML_SetElementDeclHandler(XML_Parser parser,
XML_ElementDeclHandler eldecl)
{
if (parser != NULL)
- elementDeclHandler = eldecl;
+ parser->m_elementDeclHandler = eldecl;
}
void XMLCALL
@@ -1694,7 +1744,7 @@ XML_SetAttlistDeclHandler(XML_Parser parser,
XML_AttlistDeclHandler attdecl)
{
if (parser != NULL)
- attlistDeclHandler = attdecl;
+ parser->m_attlistDeclHandler = attdecl;
}
void XMLCALL
@@ -1702,14 +1752,14 @@ XML_SetEntityDeclHandler(XML_Parser parser,
XML_EntityDeclHandler handler)
{
if (parser != NULL)
- entityDeclHandler = handler;
+ parser->m_entityDeclHandler = handler;
}
void XMLCALL
XML_SetXmlDeclHandler(XML_Parser parser,
XML_XmlDeclHandler handler) {
if (parser != NULL)
- xmlDeclHandler = handler;
+ parser->m_xmlDeclHandler = handler;
}
int XMLCALL
@@ -1719,10 +1769,10 @@ XML_SetParamEntityParsing(XML_Parser parser,
if (parser == NULL)
return 0;
/* block after XML_Parse()/XML_ParseBuffer() has been called */
- if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
+ if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return 0;
#ifdef XML_DTD
- paramEntityParsing = peParsing;
+ parser->m_paramEntityParsing = peParsing;
return 1;
#else
return peParsing == XML_PARAM_ENTITY_PARSING_NEVER;
@@ -1738,9 +1788,9 @@ XML_SetHashSalt(XML_Parser parser,
if (parser->m_parentParser)
return XML_SetHashSalt(parser->m_parentParser, hash_salt);
/* block after XML_Parse()/XML_ParseBuffer() has been called */
- if (ps_parsing == XML_PARSING || ps_parsing == XML_SUSPENDED)
+ if (parser->m_parsingStatus.parsing == XML_PARSING || parser->m_parsingStatus.parsing == XML_SUSPENDED)
return 0;
- hash_secret_salt = hash_salt;
+ parser->m_hash_secret_salt = hash_salt;
return 1;
}
@@ -1748,88 +1798,103 @@ enum XML_Status XMLCALL
XML_Parse(XML_Parser parser, const char *s, int len, int isFinal)
{
if ((parser == NULL) || (len < 0) || ((s == NULL) && (len != 0))) {
- errorCode = XML_ERROR_INVALID_ARGUMENT;
+ if (parser != NULL)
+ parser->m_errorCode = XML_ERROR_INVALID_ARGUMENT;
return XML_STATUS_ERROR;
}
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
- errorCode = XML_ERROR_SUSPENDED;
+ parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
case XML_FINISHED:
- errorCode = XML_ERROR_FINISHED;
+ parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
case XML_INITIALIZED:
- if (parentParser == NULL && !startParsing(parser)) {
- errorCode = XML_ERROR_NO_MEMORY;
+ if (parser->m_parentParser == NULL && !startParsing(parser)) {
+ parser->m_errorCode = XML_ERROR_NO_MEMORY;
return XML_STATUS_ERROR;
}
+ /* fall through */
default:
- ps_parsing = XML_PARSING;
+ parser->m_parsingStatus.parsing = XML_PARSING;
}
if (len == 0) {
- ps_finalBuffer = (XML_Bool)isFinal;
+ parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
if (!isFinal)
return XML_STATUS_OK;
- positionPtr = bufferPtr;
- parseEndPtr = bufferEnd;
+ parser->m_positionPtr = parser->m_bufferPtr;
+ parser->m_parseEndPtr = parser->m_bufferEnd;
/* If data are left over from last buffer, and we now know that these
data are the final chunk of input, then we have to check them again
to detect errors based on that fact.
*/
- errorCode = processor(parser, bufferPtr, parseEndPtr, &bufferPtr);
+ parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
- if (errorCode == XML_ERROR_NONE) {
- switch (ps_parsing) {
+ if (parser->m_errorCode == XML_ERROR_NONE) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
- XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position);
- positionPtr = bufferPtr;
+ /* It is hard to be certain, but it seems that this case
+ * cannot occur. This code is cleaning up a previous parse
+ * with no new data (since len == 0). Changing the parsing
+ * state requires getting to execute a handler function, and
+ * there doesn't seem to be an opportunity for that while in
+ * this circumstance.
+ *
+ * Given the uncertainty, we retain the code but exclude it
+ * from coverage tests.
+ *
+ * LCOV_EXCL_START
+ */
+ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
+ parser->m_positionPtr = parser->m_bufferPtr;
return XML_STATUS_SUSPENDED;
+ /* LCOV_EXCL_STOP */
case XML_INITIALIZED:
case XML_PARSING:
- ps_parsing = XML_FINISHED;
+ parser->m_parsingStatus.parsing = XML_FINISHED;
/* fall through */
default:
return XML_STATUS_OK;
}
}
- eventEndPtr = eventPtr;
- processor = errorProcessor;
+ parser->m_eventEndPtr = parser->m_eventPtr;
+ parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
#ifndef XML_CONTEXT_BYTES
- else if (bufferPtr == bufferEnd) {
+ else if (parser->m_bufferPtr == parser->m_bufferEnd) {
const char *end;
int nLeftOver;
enum XML_Status result;
/* Detect overflow (a+b > MAX <==> b > MAX-a) */
- if (len > ((XML_Size)-1) / 2 - parseEndByteIndex) {
- errorCode = XML_ERROR_NO_MEMORY;
- eventPtr = eventEndPtr = NULL;
- processor = errorProcessor;
+ if (len > ((XML_Size)-1) / 2 - parser->m_parseEndByteIndex) {
+ parser->m_errorCode = XML_ERROR_NO_MEMORY;
+ parser->m_eventPtr = parser->m_eventEndPtr = NULL;
+ parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
- parseEndByteIndex += len;
- positionPtr = s;
- ps_finalBuffer = (XML_Bool)isFinal;
+ parser->m_parseEndByteIndex += len;
+ parser->m_positionPtr = s;
+ parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
- errorCode = processor(parser, s, parseEndPtr = s + len, &end);
+ parser->m_errorCode = parser->m_processor(parser, s, parser->m_parseEndPtr = s + len, &end);
- if (errorCode != XML_ERROR_NONE) {
- eventEndPtr = eventPtr;
- processor = errorProcessor;
+ if (parser->m_errorCode != XML_ERROR_NONE) {
+ parser->m_eventEndPtr = parser->m_eventPtr;
+ parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
else {
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (isFinal) {
- ps_parsing = XML_FINISHED;
+ parser->m_parsingStatus.parsing = XML_FINISHED;
return XML_STATUS_OK;
}
/* fall through */
@@ -1838,35 +1903,33 @@ XML_Parse(XML_Parser parser, const char *s, int len, int isFinal)
}
}
- XmlUpdatePosition(encoding, positionPtr, end, &position);
+ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, end, &parser->m_position);
nLeftOver = s + len - end;
if (nLeftOver) {
- if (buffer == NULL || nLeftOver > bufferLim - buffer) {
+ if (parser->m_buffer == NULL || nLeftOver > parser->m_bufferLim - parser->m_buffer) {
/* avoid _signed_ integer overflow */
char *temp = NULL;
const int bytesToAllocate = (int)((unsigned)len * 2U);
if (bytesToAllocate > 0) {
- temp = (buffer == NULL
- ? (char *)MALLOC(bytesToAllocate)
- : (char *)REALLOC(buffer, bytesToAllocate));
+ temp = (char *)REALLOC(parser, parser->m_buffer, bytesToAllocate);
}
if (temp == NULL) {
- errorCode = XML_ERROR_NO_MEMORY;
- eventPtr = eventEndPtr = NULL;
- processor = errorProcessor;
+ parser->m_errorCode = XML_ERROR_NO_MEMORY;
+ parser->m_eventPtr = parser->m_eventEndPtr = NULL;
+ parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
- buffer = temp;
- bufferLim = buffer + bytesToAllocate;
+ parser->m_buffer = temp;
+ parser->m_bufferLim = parser->m_buffer + bytesToAllocate;
}
- memcpy(buffer, end, nLeftOver);
+ memcpy(parser->m_buffer, end, nLeftOver);
}
- bufferPtr = buffer;
- bufferEnd = buffer + nLeftOver;
- positionPtr = bufferPtr;
- parseEndPtr = bufferEnd;
- eventPtr = bufferPtr;
- eventEndPtr = bufferPtr;
+ parser->m_bufferPtr = parser->m_buffer;
+ parser->m_bufferEnd = parser->m_buffer + nLeftOver;
+ parser->m_positionPtr = parser->m_bufferPtr;
+ parser->m_parseEndPtr = parser->m_bufferEnd;
+ parser->m_eventPtr = parser->m_bufferPtr;
+ parser->m_eventEndPtr = parser->m_bufferPtr;
return result;
}
#endif /* not defined XML_CONTEXT_BYTES */
@@ -1889,53 +1952,54 @@ XML_ParseBuffer(XML_Parser parser, int len, int isFinal)
if (parser == NULL)
return XML_STATUS_ERROR;
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
- errorCode = XML_ERROR_SUSPENDED;
+ parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
case XML_FINISHED:
- errorCode = XML_ERROR_FINISHED;
+ parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
case XML_INITIALIZED:
- if (parentParser == NULL && !startParsing(parser)) {
- errorCode = XML_ERROR_NO_MEMORY;
+ if (parser->m_parentParser == NULL && !startParsing(parser)) {
+ parser->m_errorCode = XML_ERROR_NO_MEMORY;
return XML_STATUS_ERROR;
}
+ /* fall through */
default:
- ps_parsing = XML_PARSING;
+ parser->m_parsingStatus.parsing = XML_PARSING;
}
- start = bufferPtr;
- positionPtr = start;
- bufferEnd += len;
- parseEndPtr = bufferEnd;
- parseEndByteIndex += len;
- ps_finalBuffer = (XML_Bool)isFinal;
+ start = parser->m_bufferPtr;
+ parser->m_positionPtr = start;
+ parser->m_bufferEnd += len;
+ parser->m_parseEndPtr = parser->m_bufferEnd;
+ parser->m_parseEndByteIndex += len;
+ parser->m_parsingStatus.finalBuffer = (XML_Bool)isFinal;
- errorCode = processor(parser, start, parseEndPtr, &bufferPtr);
+ parser->m_errorCode = parser->m_processor(parser, start, parser->m_parseEndPtr, &parser->m_bufferPtr);
- if (errorCode != XML_ERROR_NONE) {
- eventEndPtr = eventPtr;
- processor = errorProcessor;
+ if (parser->m_errorCode != XML_ERROR_NONE) {
+ parser->m_eventEndPtr = parser->m_eventPtr;
+ parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
else {
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
if (isFinal) {
- ps_parsing = XML_FINISHED;
+ parser->m_parsingStatus.parsing = XML_FINISHED;
return result;
}
default: ; /* should not happen */
}
}
- XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position);
- positionPtr = bufferPtr;
+ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
+ parser->m_positionPtr = parser->m_bufferPtr;
return result;
}
@@ -1945,52 +2009,59 @@ XML_GetBuffer(XML_Parser parser, int len)
if (parser == NULL)
return NULL;
if (len < 0) {
- errorCode = XML_ERROR_NO_MEMORY;
+ parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
- errorCode = XML_ERROR_SUSPENDED;
+ parser->m_errorCode = XML_ERROR_SUSPENDED;
return NULL;
case XML_FINISHED:
- errorCode = XML_ERROR_FINISHED;
+ parser->m_errorCode = XML_ERROR_FINISHED;
return NULL;
default: ;
}
- if (len > bufferLim - bufferEnd) {
+ if (len > EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferEnd)) {
#ifdef XML_CONTEXT_BYTES
int keep;
#endif /* defined XML_CONTEXT_BYTES */
/* Do not invoke signed arithmetic overflow: */
- int neededSize = (int) ((unsigned)len + (unsigned)(bufferEnd - bufferPtr));
+ int neededSize = (int) ((unsigned)len +
+ (unsigned)EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd,
+ parser->m_bufferPtr));
if (neededSize < 0) {
- errorCode = XML_ERROR_NO_MEMORY;
+ parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
#ifdef XML_CONTEXT_BYTES
- keep = (int)(bufferPtr - buffer);
+ keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
if (keep > XML_CONTEXT_BYTES)
keep = XML_CONTEXT_BYTES;
neededSize += keep;
#endif /* defined XML_CONTEXT_BYTES */
- if (neededSize <= bufferLim - buffer) {
+ if (neededSize <= EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_buffer)) {
#ifdef XML_CONTEXT_BYTES
- if (keep < bufferPtr - buffer) {
- int offset = (int)(bufferPtr - buffer) - keep;
- memmove(buffer, &buffer[offset], bufferEnd - bufferPtr + keep);
- bufferEnd -= offset;
- bufferPtr -= offset;
+ if (keep < EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer)) {
+ int offset = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer) - keep;
+ /* The buffer pointers cannot be NULL here; we have at least some bytes in the buffer */
+ memmove(parser->m_buffer, &parser->m_buffer[offset], parser->m_bufferEnd - parser->m_bufferPtr + keep);
+ parser->m_bufferEnd -= offset;
+ parser->m_bufferPtr -= offset;
}
#else
- memmove(buffer, bufferPtr, bufferEnd - bufferPtr);
- bufferEnd = buffer + (bufferEnd - bufferPtr);
- bufferPtr = buffer;
+ if (parser->m_buffer && parser->m_bufferPtr) {
+ memmove(parser->m_buffer, parser->m_bufferPtr,
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
+ parser->m_bufferEnd = parser->m_buffer +
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
+ parser->m_bufferPtr = parser->m_buffer;
+ }
#endif /* not defined XML_CONTEXT_BYTES */
}
else {
char *newBuf;
- int bufferSize = (int)(bufferLim - bufferPtr);
+ int bufferSize = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferLim, parser->m_bufferPtr);
if (bufferSize == 0)
bufferSize = INIT_BUFFER_SIZE;
do {
@@ -1998,43 +2069,52 @@ XML_GetBuffer(XML_Parser parser, int len)
bufferSize = (int) (2U * (unsigned) bufferSize);
} while (bufferSize < neededSize && bufferSize > 0);
if (bufferSize <= 0) {
- errorCode = XML_ERROR_NO_MEMORY;
+ parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
- newBuf = (char *)MALLOC(bufferSize);
+ newBuf = (char *)MALLOC(parser, bufferSize);
if (newBuf == 0) {
- errorCode = XML_ERROR_NO_MEMORY;
+ parser->m_errorCode = XML_ERROR_NO_MEMORY;
return NULL;
}
- bufferLim = newBuf + bufferSize;
+ parser->m_bufferLim = newBuf + bufferSize;
#ifdef XML_CONTEXT_BYTES
- if (bufferPtr) {
- int keep = (int)(bufferPtr - buffer);
+ if (parser->m_bufferPtr) {
+ int keep = (int)EXPAT_SAFE_PTR_DIFF(parser->m_bufferPtr, parser->m_buffer);
if (keep > XML_CONTEXT_BYTES)
keep = XML_CONTEXT_BYTES;
- memcpy(newBuf, &bufferPtr[-keep], bufferEnd - bufferPtr + keep);
- FREE(buffer);
- buffer = newBuf;
- bufferEnd = buffer + (bufferEnd - bufferPtr) + keep;
- bufferPtr = buffer + keep;
+ memcpy(newBuf, &parser->m_bufferPtr[-keep],
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep);
+ FREE(parser, parser->m_buffer);
+ parser->m_buffer = newBuf;
+ parser->m_bufferEnd = parser->m_buffer +
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr) + keep;
+ parser->m_bufferPtr = parser->m_buffer + keep;
}
else {
- bufferEnd = newBuf + (bufferEnd - bufferPtr);
- bufferPtr = buffer = newBuf;
+ /* This must be a brand new buffer with no data in it yet */
+ parser->m_bufferEnd = newBuf;
+ parser->m_bufferPtr = parser->m_buffer = newBuf;
}
#else
- if (bufferPtr) {
- memcpy(newBuf, bufferPtr, bufferEnd - bufferPtr);
- FREE(buffer);
+ if (parser->m_bufferPtr) {
+ memcpy(newBuf, parser->m_bufferPtr,
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr));
+ FREE(parser, parser->m_buffer);
+ parser->m_bufferEnd = newBuf +
+ EXPAT_SAFE_PTR_DIFF(parser->m_bufferEnd, parser->m_bufferPtr);
+ }
+ else {
+ /* This must be a brand new buffer with no data in it yet */
+ parser->m_bufferEnd = newBuf;
}
- bufferEnd = newBuf + (bufferEnd - bufferPtr);
- bufferPtr = buffer = newBuf;
+ parser->m_bufferPtr = parser->m_buffer = newBuf;
#endif /* not defined XML_CONTEXT_BYTES */
}
- eventPtr = eventEndPtr = NULL;
- positionPtr = NULL;
+ parser->m_eventPtr = parser->m_eventEndPtr = NULL;
+ parser->m_positionPtr = NULL;
}
- return bufferEnd;
+ return parser->m_bufferEnd;
}
enum XML_Status XMLCALL
@@ -2042,29 +2122,29 @@ XML_StopParser(XML_Parser parser, XML_Bool resumable)
{
if (parser == NULL)
return XML_STATUS_ERROR;
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
if (resumable) {
- errorCode = XML_ERROR_SUSPENDED;
+ parser->m_errorCode = XML_ERROR_SUSPENDED;
return XML_STATUS_ERROR;
}
- ps_parsing = XML_FINISHED;
+ parser->m_parsingStatus.parsing = XML_FINISHED;
break;
case XML_FINISHED:
- errorCode = XML_ERROR_FINISHED;
+ parser->m_errorCode = XML_ERROR_FINISHED;
return XML_STATUS_ERROR;
default:
if (resumable) {
#ifdef XML_DTD
- if (isParamEntity) {
- errorCode = XML_ERROR_SUSPEND_PE;
+ if (parser->m_isParamEntity) {
+ parser->m_errorCode = XML_ERROR_SUSPEND_PE;
return XML_STATUS_ERROR;
}
#endif
- ps_parsing = XML_SUSPENDED;
+ parser->m_parsingStatus.parsing = XML_SUSPENDED;
}
else
- ps_parsing = XML_FINISHED;
+ parser->m_parsingStatus.parsing = XML_FINISHED;
}
return XML_STATUS_OK;
}
@@ -2076,36 +2156,36 @@ XML_ResumeParser(XML_Parser parser)
if (parser == NULL)
return XML_STATUS_ERROR;
- if (ps_parsing != XML_SUSPENDED) {
- errorCode = XML_ERROR_NOT_SUSPENDED;
+ if (parser->m_parsingStatus.parsing != XML_SUSPENDED) {
+ parser->m_errorCode = XML_ERROR_NOT_SUSPENDED;
return XML_STATUS_ERROR;
}
- ps_parsing = XML_PARSING;
+ parser->m_parsingStatus.parsing = XML_PARSING;
- errorCode = processor(parser, bufferPtr, parseEndPtr, &bufferPtr);
+ parser->m_errorCode = parser->m_processor(parser, parser->m_bufferPtr, parser->m_parseEndPtr, &parser->m_bufferPtr);
- if (errorCode != XML_ERROR_NONE) {
- eventEndPtr = eventPtr;
- processor = errorProcessor;
+ if (parser->m_errorCode != XML_ERROR_NONE) {
+ parser->m_eventEndPtr = parser->m_eventPtr;
+ parser->m_processor = errorProcessor;
return XML_STATUS_ERROR;
}
else {
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
result = XML_STATUS_SUSPENDED;
break;
case XML_INITIALIZED:
case XML_PARSING:
- if (ps_finalBuffer) {
- ps_parsing = XML_FINISHED;
+ if (parser->m_parsingStatus.finalBuffer) {
+ parser->m_parsingStatus.parsing = XML_FINISHED;
return result;
}
default: ;
}
}
- XmlUpdatePosition(encoding, positionPtr, bufferPtr, &position);
- positionPtr = bufferPtr;
+ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_bufferPtr, &parser->m_position);
+ parser->m_positionPtr = parser->m_bufferPtr;
return result;
}
@@ -2123,7 +2203,7 @@ XML_GetErrorCode(XML_Parser parser)
{
if (parser == NULL)
return XML_ERROR_INVALID_ARGUMENT;
- return errorCode;
+ return parser->m_errorCode;
}
XML_Index XMLCALL
@@ -2131,8 +2211,8 @@ XML_GetCurrentByteIndex(XML_Parser parser)
{
if (parser == NULL)
return -1;
- if (eventPtr)
- return (XML_Index)(parseEndByteIndex - (parseEndPtr - eventPtr));
+ if (parser->m_eventPtr)
+ return (XML_Index)(parser->m_parseEndByteIndex - (parser->m_parseEndPtr - parser->m_eventPtr));
return -1;
}
@@ -2141,8 +2221,8 @@ XML_GetCurrentByteCount(XML_Parser parser)
{
if (parser == NULL)
return 0;
- if (eventEndPtr && eventPtr)
- return (int)(eventEndPtr - eventPtr);
+ if (parser->m_eventEndPtr && parser->m_eventPtr)
+ return (int)(parser->m_eventEndPtr - parser->m_eventPtr);
return 0;
}
@@ -2152,12 +2232,12 @@ XML_GetInputContext(XML_Parser parser, int *offset, int *size)
#ifdef XML_CONTEXT_BYTES
if (parser == NULL)
return NULL;
- if (eventPtr && buffer) {
+ if (parser->m_eventPtr && parser->m_buffer) {
if (offset != NULL)
- *offset = (int)(eventPtr - buffer);
+ *offset = (int)(parser->m_eventPtr - parser->m_buffer);
if (size != NULL)
- *size = (int)(bufferEnd - buffer);
- return buffer;
+ *size = (int)(parser->m_bufferEnd - parser->m_buffer);
+ return parser->m_buffer;
}
#else
(void)parser;
@@ -2172,11 +2252,11 @@ XML_GetCurrentLineNumber(XML_Parser parser)
{
if (parser == NULL)
return 0;
- if (eventPtr && eventPtr >= positionPtr) {
- XmlUpdatePosition(encoding, positionPtr, eventPtr, &position);
- positionPtr = eventPtr;
+ if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
+ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position);
+ parser->m_positionPtr = parser->m_eventPtr;
}
- return position.lineNumber + 1;
+ return parser->m_position.lineNumber + 1;
}
XML_Size XMLCALL
@@ -2184,18 +2264,18 @@ XML_GetCurrentColumnNumber(XML_Parser parser)
{
if (parser == NULL)
return 0;
- if (eventPtr && eventPtr >= positionPtr) {
- XmlUpdatePosition(encoding, positionPtr, eventPtr, &position);
- positionPtr = eventPtr;
+ if (parser->m_eventPtr && parser->m_eventPtr >= parser->m_positionPtr) {
+ XmlUpdatePosition(parser->m_encoding, parser->m_positionPtr, parser->m_eventPtr, &parser->m_position);
+ parser->m_positionPtr = parser->m_eventPtr;
}
- return position.columnNumber;
+ return parser->m_position.columnNumber;
}
void XMLCALL
XML_FreeContentModel(XML_Parser parser, XML_Content *model)
{
if (parser != NULL)
- FREE(model);
+ FREE(parser, model);
}
void * XMLCALL
@@ -2203,7 +2283,7 @@ XML_MemMalloc(XML_Parser parser, size_t size)
{
if (parser == NULL)
return NULL;
- return MALLOC(size);
+ return MALLOC(parser, size);
}
void * XMLCALL
@@ -2211,14 +2291,14 @@ XML_MemRealloc(XML_Parser parser, void *ptr, size_t size)
{
if (parser == NULL)
return NULL;
- return REALLOC(ptr, size);
+ return REALLOC(parser, ptr, size);
}
void XMLCALL
XML_MemFree(XML_Parser parser, void *ptr)
{
if (parser != NULL)
- FREE(ptr);
+ FREE(parser, ptr);
}
void XMLCALL
@@ -2226,65 +2306,110 @@ XML_DefaultCurrent(XML_Parser parser)
{
if (parser == NULL)
return;
- if (defaultHandler) {
- if (openInternalEntities)
+ if (parser->m_defaultHandler) {
+ if (parser->m_openInternalEntities)
reportDefault(parser,
- internalEncoding,
- openInternalEntities->internalEventPtr,
- openInternalEntities->internalEventEndPtr);
+ parser->m_internalEncoding,
+ parser->m_openInternalEntities->internalEventPtr,
+ parser->m_openInternalEntities->internalEventEndPtr);
else
- reportDefault(parser, encoding, eventPtr, eventEndPtr);
+ reportDefault(parser, parser->m_encoding, parser->m_eventPtr, parser->m_eventEndPtr);
}
}
const XML_LChar * XMLCALL
XML_ErrorString(enum XML_Error code)
{
- static const XML_LChar* const message[] = {
- 0,
- XML_L("out of memory"),
- XML_L("syntax error"),
- XML_L("no element found"),
- XML_L("not well-formed (invalid token)"),
- XML_L("unclosed token"),
- XML_L("partial character"),
- XML_L("mismatched tag"),
- XML_L("duplicate attribute"),
- XML_L("junk after document element"),
- XML_L("illegal parameter entity reference"),
- XML_L("undefined entity"),
- XML_L("recursive entity reference"),
- XML_L("asynchronous entity"),
- XML_L("reference to invalid character number"),
- XML_L("reference to binary entity"),
- XML_L("reference to external entity in attribute"),
- XML_L("XML or text declaration not at start of entity"),
- XML_L("unknown encoding"),
- XML_L("encoding specified in XML declaration is incorrect"),
- XML_L("unclosed CDATA section"),
- XML_L("error in processing external entity reference"),
- XML_L("document is not standalone"),
- XML_L("unexpected parser state - please send a bug report"),
- XML_L("entity declared in parameter entity"),
- XML_L("requested feature requires XML_DTD support in Expat"),
- XML_L("cannot change setting once parsing has begun"),
- XML_L("unbound prefix"),
- XML_L("must not undeclare prefix"),
- XML_L("incomplete markup in parameter entity"),
- XML_L("XML declaration not well-formed"),
- XML_L("text declaration not well-formed"),
- XML_L("illegal character(s) in public id"),
- XML_L("parser suspended"),
- XML_L("parser not suspended"),
- XML_L("parsing aborted"),
- XML_L("parsing finished"),
- XML_L("cannot suspend in external parameter entity"),
- XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name"),
- XML_L("reserved prefix (xmlns) must not be declared or undeclared"),
- XML_L("prefix must not be bound to one of the reserved namespace names")
- };
- if (code > 0 && code < sizeof(message)/sizeof(message[0]))
- return message[code];
+ switch (code) {
+ case XML_ERROR_NONE:
+ return NULL;
+ case XML_ERROR_NO_MEMORY:
+ return XML_L("out of memory");
+ case XML_ERROR_SYNTAX:
+ return XML_L("syntax error");
+ case XML_ERROR_NO_ELEMENTS:
+ return XML_L("no element found");
+ case XML_ERROR_INVALID_TOKEN:
+ return XML_L("not well-formed (invalid token)");
+ case XML_ERROR_UNCLOSED_TOKEN:
+ return XML_L("unclosed token");
+ case XML_ERROR_PARTIAL_CHAR:
+ return XML_L("partial character");
+ case XML_ERROR_TAG_MISMATCH:
+ return XML_L("mismatched tag");
+ case XML_ERROR_DUPLICATE_ATTRIBUTE:
+ return XML_L("duplicate attribute");
+ case XML_ERROR_JUNK_AFTER_DOC_ELEMENT:
+ return XML_L("junk after document element");
+ case XML_ERROR_PARAM_ENTITY_REF:
+ return XML_L("illegal parameter entity reference");
+ case XML_ERROR_UNDEFINED_ENTITY:
+ return XML_L("undefined entity");
+ case XML_ERROR_RECURSIVE_ENTITY_REF:
+ return XML_L("recursive entity reference");
+ case XML_ERROR_ASYNC_ENTITY:
+ return XML_L("asynchronous entity");
+ case XML_ERROR_BAD_CHAR_REF:
+ return XML_L("reference to invalid character number");
+ case XML_ERROR_BINARY_ENTITY_REF:
+ return XML_L("reference to binary entity");
+ case XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF:
+ return XML_L("reference to external entity in attribute");
+ case XML_ERROR_MISPLACED_XML_PI:
+ return XML_L("XML or text declaration not at start of entity");
+ case XML_ERROR_UNKNOWN_ENCODING:
+ return XML_L("unknown encoding");
+ case XML_ERROR_INCORRECT_ENCODING:
+ return XML_L("encoding specified in XML declaration is incorrect");
+ case XML_ERROR_UNCLOSED_CDATA_SECTION:
+ return XML_L("unclosed CDATA section");
+ case XML_ERROR_EXTERNAL_ENTITY_HANDLING:
+ return XML_L("error in processing external entity reference");
+ case XML_ERROR_NOT_STANDALONE:
+ return XML_L("document is not standalone");
+ case XML_ERROR_UNEXPECTED_STATE:
+ return XML_L("unexpected parser state - please send a bug report");
+ case XML_ERROR_ENTITY_DECLARED_IN_PE:
+ return XML_L("entity declared in parameter entity");
+ case XML_ERROR_FEATURE_REQUIRES_XML_DTD:
+ return XML_L("requested feature requires XML_DTD support in Expat");
+ case XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING:
+ return XML_L("cannot change setting once parsing has begun");
+ /* Added in 1.95.7. */
+ case XML_ERROR_UNBOUND_PREFIX:
+ return XML_L("unbound prefix");
+ /* Added in 1.95.8. */
+ case XML_ERROR_UNDECLARING_PREFIX:
+ return XML_L("must not undeclare prefix");
+ case XML_ERROR_INCOMPLETE_PE:
+ return XML_L("incomplete markup in parameter entity");
+ case XML_ERROR_XML_DECL:
+ return XML_L("XML declaration not well-formed");
+ case XML_ERROR_TEXT_DECL:
+ return XML_L("text declaration not well-formed");
+ case XML_ERROR_PUBLICID:
+ return XML_L("illegal character(s) in public id");
+ case XML_ERROR_SUSPENDED:
+ return XML_L("parser suspended");
+ case XML_ERROR_NOT_SUSPENDED:
+ return XML_L("parser not suspended");
+ case XML_ERROR_ABORTED:
+ return XML_L("parsing aborted");
+ case XML_ERROR_FINISHED:
+ return XML_L("parsing finished");
+ case XML_ERROR_SUSPEND_PE:
+ return XML_L("cannot suspend in external parameter entity");
+ /* Added in 2.0.0. */
+ case XML_ERROR_RESERVED_PREFIX_XML:
+ return XML_L("reserved prefix (xml) must not be undeclared or bound to another namespace name");
+ case XML_ERROR_RESERVED_PREFIX_XMLNS:
+ return XML_L("reserved prefix (xmlns) must not be declared or undeclared");
+ case XML_ERROR_RESERVED_NAMESPACE_URI:
+ return XML_L("prefix must not be bound to one of the reserved namespace names");
+ /* Added in 2.2.5. */
+ case XML_ERROR_INVALID_ARGUMENT: /* Constant added in 2.2.1, already */
+ return XML_L("invalid argument");
+ }
return NULL;
}
@@ -2367,12 +2492,12 @@ XML_GetFeatureList(void)
static XML_Bool
storeRawNames(XML_Parser parser)
{
- TAG *tag = tagStack;
+ TAG *tag = parser->m_tagStack;
while (tag) {
int bufSize;
int nameLen = sizeof(XML_Char) * (tag->name.strLen + 1);
char *rawNameBuf = tag->buf + nameLen;
- /* Stop if already stored. Since tagStack is a stack, we can stop
+ /* Stop if already stored. Since m_tagStack is a stack, we can stop
at the first entry that has already been copied; everything
below it in the stack is already been accounted for in a
previous call to this function.
@@ -2384,7 +2509,7 @@ storeRawNames(XML_Parser parser)
*/
bufSize = nameLen + ROUND_UP(tag->rawNameLength, sizeof(XML_Char));
if (bufSize > tag->bufEnd - tag->buf) {
- char *temp = (char *)REALLOC(tag->buf, bufSize);
+ char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
if (temp == NULL)
return XML_FALSE;
/* if tag->name.str points to tag->buf (only when namespace
@@ -2415,8 +2540,8 @@ contentProcessor(XML_Parser parser,
const char *end,
const char **endPtr)
{
- enum XML_Error result = doContent(parser, 0, encoding, start, end,
- endPtr, (XML_Bool)!ps_finalBuffer);
+ enum XML_Error result = doContent(parser, 0, parser->m_encoding, start, end,
+ endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result == XML_ERROR_NONE) {
if (!storeRawNames(parser))
return XML_ERROR_NO_MEMORY;
@@ -2433,7 +2558,7 @@ externalEntityInitProcessor(XML_Parser parser,
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
- processor = externalEntityInitProcessor2;
+ parser->m_processor = externalEntityInitProcessor2;
return externalEntityInitProcessor2(parser, start, end, endPtr);
}
@@ -2444,7 +2569,7 @@ externalEntityInitProcessor2(XML_Parser parser,
const char **endPtr)
{
const char *next = start; /* XmlContentTok doesn't always set the last arg */
- int tok = XmlContentTok(encoding, start, end, &next);
+ int tok = XmlContentTok(parser->m_encoding, start, end, &next);
switch (tok) {
case XML_TOK_BOM:
/* If we are at the end of the buffer, this would cause the next stage,
@@ -2452,28 +2577,28 @@ externalEntityInitProcessor2(XML_Parser parser,
doContent (by detecting XML_TOK_NONE) without processing any xml text
declaration - causing the error XML_ERROR_MISPLACED_XML_PI in doContent.
*/
- if (next == end && !ps_finalBuffer) {
+ if (next == end && !parser->m_parsingStatus.finalBuffer) {
*endPtr = next;
return XML_ERROR_NONE;
}
start = next;
break;
case XML_TOK_PARTIAL:
- if (!ps_finalBuffer) {
+ if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
- eventPtr = start;
+ parser->m_eventPtr = start;
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
- if (!ps_finalBuffer) {
+ if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
- eventPtr = start;
+ parser->m_eventPtr = start;
return XML_ERROR_PARTIAL_CHAR;
}
- processor = externalEntityInitProcessor3;
+ parser->m_processor = externalEntityInitProcessor3;
return externalEntityInitProcessor3(parser, start, end, endPtr);
}
@@ -2485,9 +2610,9 @@ externalEntityInitProcessor3(XML_Parser parser,
{
int tok;
const char *next = start; /* XmlContentTok doesn't always set the last arg */
- eventPtr = start;
- tok = XmlContentTok(encoding, start, end, &next);
- eventEndPtr = next;
+ parser->m_eventPtr = start;
+ tok = XmlContentTok(parser->m_encoding, start, end, &next);
+ parser->m_eventEndPtr = next;
switch (tok) {
case XML_TOK_XML_DECL:
@@ -2496,7 +2621,7 @@ externalEntityInitProcessor3(XML_Parser parser,
result = processXmlDecl(parser, 1, start, next);
if (result != XML_ERROR_NONE)
return result;
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*endPtr = next;
return XML_ERROR_NONE;
@@ -2508,20 +2633,20 @@ externalEntityInitProcessor3(XML_Parser parser,
}
break;
case XML_TOK_PARTIAL:
- if (!ps_finalBuffer) {
+ if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
- if (!ps_finalBuffer) {
+ if (!parser->m_parsingStatus.finalBuffer) {
*endPtr = start;
return XML_ERROR_NONE;
}
return XML_ERROR_PARTIAL_CHAR;
}
- processor = externalEntityContentProcessor;
- tagLevel = 1;
+ parser->m_processor = externalEntityContentProcessor;
+ parser->m_tagLevel = 1;
return externalEntityContentProcessor(parser, start, end, endPtr);
}
@@ -2531,8 +2656,8 @@ externalEntityContentProcessor(XML_Parser parser,
const char *end,
const char **endPtr)
{
- enum XML_Error result = doContent(parser, 1, encoding, start, end,
- endPtr, (XML_Bool)!ps_finalBuffer);
+ enum XML_Error result = doContent(parser, 1, parser->m_encoding, start, end,
+ endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result == XML_ERROR_NONE) {
if (!storeRawNames(parser))
return XML_ERROR_NO_MEMORY;
@@ -2550,17 +2675,17 @@ doContent(XML_Parser parser,
XML_Bool haveMore)
{
/* save one level of indirection */
- DTD * const dtd = _dtd;
+ DTD * const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
- if (enc == encoding) {
- eventPP = &eventPtr;
- eventEndPP = &eventEndPtr;
+ if (enc == parser->m_encoding) {
+ eventPP = &parser->m_eventPtr;
+ eventEndPP = &parser->m_eventEndPtr;
}
else {
- eventPP = &(openInternalEntities->internalEventPtr);
- eventEndPP = &(openInternalEntities->internalEventEndPtr);
+ eventPP = &(parser->m_openInternalEntities->internalEventPtr);
+ eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
*eventPP = s;
@@ -2575,18 +2700,18 @@ doContent(XML_Parser parser,
return XML_ERROR_NONE;
}
*eventEndPP = end;
- if (characterDataHandler) {
+ if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
- characterDataHandler(handlerArg, &c, 1);
+ parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
}
- else if (defaultHandler)
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, end);
/* We are at the end of the final buffer, should we check for
XML_SUSPENDED, XML_FINISHED?
*/
if (startTagLevel == 0)
return XML_ERROR_NO_ELEMENTS;
- if (tagLevel != startTagLevel)
+ if (parser->m_tagLevel != startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
*nextPtr = end;
return XML_ERROR_NONE;
@@ -2596,7 +2721,7 @@ doContent(XML_Parser parser,
return XML_ERROR_NONE;
}
if (startTagLevel > 0) {
- if (tagLevel != startTagLevel)
+ if (parser->m_tagLevel != startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
*nextPtr = s;
return XML_ERROR_NONE;
@@ -2625,9 +2750,9 @@ doContent(XML_Parser parser,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (ch) {
- if (characterDataHandler)
- characterDataHandler(handlerArg, &ch, 1);
- else if (defaultHandler)
+ if (parser->m_characterDataHandler)
+ parser->m_characterDataHandler(parser->m_handlerArg, &ch, 1);
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
@@ -2649,9 +2774,9 @@ doContent(XML_Parser parser,
return XML_ERROR_ENTITY_DECLARED_IN_PE;
}
else if (!entity) {
- if (skippedEntityHandler)
- skippedEntityHandler(handlerArg, name, 0);
- else if (defaultHandler)
+ if (parser->m_skippedEntityHandler)
+ parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
@@ -2661,10 +2786,10 @@ doContent(XML_Parser parser,
return XML_ERROR_BINARY_ENTITY_REF;
if (entity->textPtr) {
enum XML_Error result;
- if (!defaultExpandInternalEntities) {
- if (skippedEntityHandler)
- skippedEntityHandler(handlerArg, entity->name, 0);
- else if (defaultHandler)
+ if (!parser->m_defaultExpandInternalEntities) {
+ if (parser->m_skippedEntityHandler)
+ parser->m_skippedEntityHandler(parser->m_handlerArg, entity->name, 0);
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
@@ -2672,22 +2797,22 @@ doContent(XML_Parser parser,
if (result != XML_ERROR_NONE)
return result;
}
- else if (externalEntityRefHandler) {
+ else if (parser->m_externalEntityRefHandler) {
const XML_Char *context;
entity->open = XML_TRUE;
context = getContext(parser);
entity->open = XML_FALSE;
if (!context)
return XML_ERROR_NO_MEMORY;
- if (!externalEntityRefHandler(externalEntityRefHandlerArg,
+ if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
context,
entity->base,
entity->systemId,
entity->publicId))
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
- poolDiscard(&tempPool);
+ poolDiscard(&parser->m_tempPool);
}
- else if (defaultHandler)
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
}
@@ -2698,29 +2823,29 @@ doContent(XML_Parser parser,
TAG *tag;
enum XML_Error result;
XML_Char *toPtr;
- if (freeTagList) {
- tag = freeTagList;
- freeTagList = freeTagList->parent;
+ if (parser->m_freeTagList) {
+ tag = parser->m_freeTagList;
+ parser->m_freeTagList = parser->m_freeTagList->parent;
}
else {
- tag = (TAG *)MALLOC(sizeof(TAG));
+ tag = (TAG *)MALLOC(parser, sizeof(TAG));
if (!tag)
return XML_ERROR_NO_MEMORY;
- tag->buf = (char *)MALLOC(INIT_TAG_BUF_SIZE);
+ tag->buf = (char *)MALLOC(parser, INIT_TAG_BUF_SIZE);
if (!tag->buf) {
- FREE(tag);
+ FREE(parser, tag);
return XML_ERROR_NO_MEMORY;
}
tag->bufEnd = tag->buf + INIT_TAG_BUF_SIZE;
}
tag->bindings = NULL;
- tag->parent = tagStack;
- tagStack = tag;
+ tag->parent = parser->m_tagStack;
+ parser->m_tagStack = tag;
tag->name.localPart = NULL;
tag->name.prefix = NULL;
tag->rawName = s + enc->minBytesPerChar;
tag->rawNameLength = XmlNameLength(enc, tag->rawName);
- ++tagLevel;
+ ++parser->m_tagLevel;
{
const char *rawNameEnd = tag->rawName + tag->rawNameLength;
const char *fromPtr = tag->rawName;
@@ -2738,7 +2863,7 @@ doContent(XML_Parser parser,
}
bufSize = (int)(tag->bufEnd - tag->buf) << 1;
{
- char *temp = (char *)REALLOC(tag->buf, bufSize);
+ char *temp = (char *)REALLOC(parser, tag->buf, bufSize);
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
tag->buf = temp;
@@ -2752,12 +2877,12 @@ doContent(XML_Parser parser,
result = storeAtts(parser, enc, s, &(tag->name), &(tag->bindings));
if (result)
return result;
- if (startElementHandler)
- startElementHandler(handlerArg, tag->name.str,
- (const XML_Char **)atts);
- else if (defaultHandler)
+ if (parser->m_startElementHandler)
+ parser->m_startElementHandler(parser->m_handlerArg, tag->name.str,
+ (const XML_Char **)parser->m_atts);
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
- poolClear(&tempPool);
+ poolClear(&parser->m_tempPool);
break;
}
case XML_TOK_EMPTY_ELEMENT_NO_ATTS:
@@ -2769,45 +2894,49 @@ doContent(XML_Parser parser,
BINDING *bindings = NULL;
XML_Bool noElmHandlers = XML_TRUE;
TAG_NAME name;
- name.str = poolStoreString(&tempPool, enc, rawName,
+ name.str = poolStoreString(&parser->m_tempPool, enc, rawName,
rawName + XmlNameLength(enc, rawName));
if (!name.str)
return XML_ERROR_NO_MEMORY;
- poolFinish(&tempPool);
+ poolFinish(&parser->m_tempPool);
result = storeAtts(parser, enc, s, &name, &bindings);
if (result != XML_ERROR_NONE) {
freeBindings(parser, bindings);
return result;
}
- poolFinish(&tempPool);
- if (startElementHandler) {
- startElementHandler(handlerArg, name.str, (const XML_Char **)atts);
+ poolFinish(&parser->m_tempPool);
+ if (parser->m_startElementHandler) {
+ parser->m_startElementHandler(parser->m_handlerArg, name.str, (const XML_Char **)parser->m_atts);
noElmHandlers = XML_FALSE;
}
- if (endElementHandler) {
- if (startElementHandler)
+ if (parser->m_endElementHandler) {
+ if (parser->m_startElementHandler)
*eventPP = *eventEndPP;
- endElementHandler(handlerArg, name.str);
+ parser->m_endElementHandler(parser->m_handlerArg, name.str);
noElmHandlers = XML_FALSE;
}
- if (noElmHandlers && defaultHandler)
+ if (noElmHandlers && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
- poolClear(&tempPool);
+ poolClear(&parser->m_tempPool);
freeBindings(parser, bindings);
}
- if (tagLevel == 0)
- return epilogProcessor(parser, next, end, nextPtr);
+ if ((parser->m_tagLevel == 0) && (parser->m_parsingStatus.parsing != XML_FINISHED)) {
+ if (parser->m_parsingStatus.parsing == XML_SUSPENDED)
+ parser->m_processor = epilogProcessor;
+ else
+ return epilogProcessor(parser, next, end, nextPtr);
+ }
break;
case XML_TOK_END_TAG:
- if (tagLevel == startTagLevel)
+ if (parser->m_tagLevel == startTagLevel)
return XML_ERROR_ASYNC_ENTITY;
else {
int len;
const char *rawName;
- TAG *tag = tagStack;
- tagStack = tag->parent;
- tag->parent = freeTagList;
- freeTagList = tag;
+ TAG *tag = parser->m_tagStack;
+ parser->m_tagStack = tag->parent;
+ tag->parent = parser->m_freeTagList;
+ parser->m_freeTagList = tag;
rawName = s + enc->minBytesPerChar*2;
len = XmlNameLength(enc, rawName);
if (len != tag->rawNameLength
@@ -2815,13 +2944,13 @@ doContent(XML_Parser parser,
*eventPP = rawName;
return XML_ERROR_TAG_MISMATCH;
}
- --tagLevel;
- if (endElementHandler) {
+ --parser->m_tagLevel;
+ if (parser->m_endElementHandler) {
const XML_Char *localPart;
const XML_Char *prefix;
XML_Char *uri;
localPart = tag->name.localPart;
- if (ns && localPart) {
+ if (parser->m_ns && localPart) {
/* localPart and prefix may have been overwritten in
tag->name.str, since this points to the binding->uri
buffer which gets re-used; so we have to add them again
@@ -2830,26 +2959,26 @@ doContent(XML_Parser parser,
/* don't need to check for space - already done in storeAtts() */
while (*localPart) *uri++ = *localPart++;
prefix = (XML_Char *)tag->name.prefix;
- if (ns_triplets && prefix) {
- *uri++ = namespaceSeparator;
+ if (parser->m_ns_triplets && prefix) {
+ *uri++ = parser->m_namespaceSeparator;
while (*prefix) *uri++ = *prefix++;
}
*uri = XML_T('\0');
}
- endElementHandler(handlerArg, tag->name.str);
+ parser->m_endElementHandler(parser->m_handlerArg, tag->name.str);
}
- else if (defaultHandler)
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
while (tag->bindings) {
BINDING *b = tag->bindings;
- if (endNamespaceDeclHandler)
- endNamespaceDeclHandler(handlerArg, b->prefix->name);
+ if (parser->m_endNamespaceDeclHandler)
+ parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
tag->bindings = tag->bindings->nextTagBinding;
- b->nextTagBinding = freeBindingList;
- freeBindingList = b;
+ b->nextTagBinding = parser->m_freeBindingList;
+ parser->m_freeBindingList = b;
b->prefix->binding = b->prevPrefixBinding;
}
- if (tagLevel == 0)
+ if (parser->m_tagLevel == 0)
return epilogProcessor(parser, next, end, nextPtr);
}
break;
@@ -2858,30 +2987,30 @@ doContent(XML_Parser parser,
int n = XmlCharRefNumber(enc, s);
if (n < 0)
return XML_ERROR_BAD_CHAR_REF;
- if (characterDataHandler) {
+ if (parser->m_characterDataHandler) {
XML_Char buf[XML_ENCODE_MAX];
- characterDataHandler(handlerArg, buf, XmlEncode(n, (ICHAR *)buf));
+ parser->m_characterDataHandler(parser->m_handlerArg, buf, XmlEncode(n, (ICHAR *)buf));
}
- else if (defaultHandler)
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
}
break;
case XML_TOK_XML_DECL:
return XML_ERROR_MISPLACED_XML_PI;
case XML_TOK_DATA_NEWLINE:
- if (characterDataHandler) {
+ if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
- characterDataHandler(handlerArg, &c, 1);
+ parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
}
- else if (defaultHandler)
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
case XML_TOK_CDATA_SECT_OPEN:
{
enum XML_Error result;
- if (startCdataSectionHandler)
- startCdataSectionHandler(handlerArg);
-#if 0
+ if (parser->m_startCdataSectionHandler)
+ parser->m_startCdataSectionHandler(parser->m_handlerArg);
+/* BEGIN disabled code */
/* Suppose you doing a transformation on a document that involves
changing only the character data. You set up a defaultHandler
and a characterDataHandler. The defaultHandler simply copies
@@ -2894,16 +3023,16 @@ doContent(XML_Parser parser,
However, now we have a start/endCdataSectionHandler, so it seems
easier to let the user deal with this.
*/
- else if (characterDataHandler)
- characterDataHandler(handlerArg, dataBuf, 0);
-#endif
- else if (defaultHandler)
+ else if (0 && parser->m_characterDataHandler)
+ parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0);
+/* END disabled code */
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
result = doCdataSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (!next) {
- processor = cdataSectionProcessor;
+ parser->m_processor = cdataSectionProcessor;
return result;
}
}
@@ -2913,19 +3042,19 @@ doContent(XML_Parser parser,
*nextPtr = s;
return XML_ERROR_NONE;
}
- if (characterDataHandler) {
+ if (parser->m_characterDataHandler) {
if (MUST_CONVERT(enc, s)) {
- ICHAR *dataPtr = (ICHAR *)dataBuf;
- XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd);
- characterDataHandler(handlerArg, dataBuf,
- (int)(dataPtr - (ICHAR *)dataBuf));
+ ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
+ XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
+ parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf,
+ (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
}
else
- characterDataHandler(handlerArg,
+ parser->m_characterDataHandler(parser->m_handlerArg,
(XML_Char *)s,
(int)((XML_Char *)end - (XML_Char *)s));
}
- else if (defaultHandler)
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, end);
/* We are at the end of the final buffer, should we check for
XML_SUSPENDED, XML_FINISHED?
@@ -2934,7 +3063,7 @@ doContent(XML_Parser parser,
*eventPP = end;
return XML_ERROR_NO_ELEMENTS;
}
- if (tagLevel != startTagLevel) {
+ if (parser->m_tagLevel != startTagLevel) {
*eventPP = end;
return XML_ERROR_ASYNC_ENTITY;
}
@@ -2942,26 +3071,26 @@ doContent(XML_Parser parser,
return XML_ERROR_NONE;
case XML_TOK_DATA_CHARS:
{
- XML_CharacterDataHandler charDataHandler = characterDataHandler;
+ XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
if (charDataHandler) {
if (MUST_CONVERT(enc, s)) {
for (;;) {
- ICHAR *dataPtr = (ICHAR *)dataBuf;
- const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd);
+ ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
+ const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = s;
- charDataHandler(handlerArg, dataBuf,
- (int)(dataPtr - (ICHAR *)dataBuf));
+ charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
+ (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
*eventPP = s;
}
}
else
- charDataHandler(handlerArg,
+ charDataHandler(parser->m_handlerArg,
(XML_Char *)s,
(int)((XML_Char *)next - (XML_Char *)s));
}
- else if (defaultHandler)
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
}
break;
@@ -2974,12 +3103,20 @@ doContent(XML_Parser parser,
return XML_ERROR_NO_MEMORY;
break;
default:
- if (defaultHandler)
+ /* All of the tokens produced by XmlContentTok() have their own
+ * explicit cases, so this default is not strictly necessary.
+ * However it is a useful safety net, so we retain the code and
+ * simply exclude it from the coverage tests.
+ *
+ * LCOV_EXCL_START
+ */
+ if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
+ /* LCOV_EXCL_STOP */
}
*eventPP = s = next;
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
@@ -2992,7 +3129,7 @@ doContent(XML_Parser parser,
}
/* This function does not call free() on the allocated memory, merely
- * moving it to the parser's freeBindingList where it can be freed or
+ * moving it to the parser's m_freeBindingList where it can be freed or
* reused as appropriate.
*/
static void
@@ -3001,15 +3138,15 @@ freeBindings(XML_Parser parser, BINDING *bindings)
while (bindings) {
BINDING *b = bindings;
- /* startNamespaceDeclHandler will have been called for this
+ /* m_startNamespaceDeclHandler will have been called for this
* binding in addBindings(), so call the end handler now.
*/
- if (endNamespaceDeclHandler)
- endNamespaceDeclHandler(handlerArg, b->prefix->name);
+ if (parser->m_endNamespaceDeclHandler)
+ parser->m_endNamespaceDeclHandler(parser->m_handlerArg, b->prefix->name);
bindings = bindings->nextTagBinding;
- b->nextTagBinding = freeBindingList;
- freeBindingList = b;
+ b->nextTagBinding = parser->m_freeBindingList;
+ parser->m_freeBindingList = b;
b->prefix->binding = b->prevPrefixBinding;
}
}
@@ -3029,7 +3166,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
const char *attStr, TAG_NAME *tagNamePtr,
BINDING **bindingsPtr)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
ELEMENT_TYPE *elementType;
int nDefaultAtts;
const XML_Char **appAtts; /* the attribute list for the application */
@@ -3052,39 +3189,43 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
sizeof(ELEMENT_TYPE));
if (!elementType)
return XML_ERROR_NO_MEMORY;
- if (ns && !setElementTypePrefix(parser, elementType))
+ if (parser->m_ns && !setElementTypePrefix(parser, elementType))
return XML_ERROR_NO_MEMORY;
}
nDefaultAtts = elementType->nDefaultAtts;
/* get the attributes from the tokenizer */
- n = XmlGetAttributes(enc, attStr, attsSize, atts);
- if (n + nDefaultAtts > attsSize) {
- int oldAttsSize = attsSize;
+ n = XmlGetAttributes(enc, attStr, parser->m_attsSize, parser->m_atts);
+ if (n + nDefaultAtts > parser->m_attsSize) {
+ int oldAttsSize = parser->m_attsSize;
ATTRIBUTE *temp;
#ifdef XML_ATTR_INFO
XML_AttrInfo *temp2;
#endif
- attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
- temp = (ATTRIBUTE *)REALLOC((void *)atts, attsSize * sizeof(ATTRIBUTE));
- if (temp == NULL)
+ parser->m_attsSize = n + nDefaultAtts + INIT_ATTS_SIZE;
+ temp = (ATTRIBUTE *)REALLOC(parser, (void *)parser->m_atts, parser->m_attsSize * sizeof(ATTRIBUTE));
+ if (temp == NULL) {
+ parser->m_attsSize = oldAttsSize;
return XML_ERROR_NO_MEMORY;
- atts = temp;
+ }
+ parser->m_atts = temp;
#ifdef XML_ATTR_INFO
- temp2 = (XML_AttrInfo *)REALLOC((void *)attInfo, attsSize * sizeof(XML_AttrInfo));
- if (temp2 == NULL)
+ temp2 = (XML_AttrInfo *)REALLOC(parser, (void *)parser->m_attInfo, parser->m_attsSize * sizeof(XML_AttrInfo));
+ if (temp2 == NULL) {
+ parser->m_attsSize = oldAttsSize;
return XML_ERROR_NO_MEMORY;
- attInfo = temp2;
+ }
+ parser->m_attInfo = temp2;
#endif
if (n > oldAttsSize)
- XmlGetAttributes(enc, attStr, n, atts);
+ XmlGetAttributes(enc, attStr, n, parser->m_atts);
}
- appAtts = (const XML_Char **)atts;
+ appAtts = (const XML_Char **)parser->m_atts;
for (i = 0; i < n; i++) {
- ATTRIBUTE *currAtt = &atts[i];
+ ATTRIBUTE *currAtt = &parser->m_atts[i];
#ifdef XML_ATTR_INFO
- XML_AttrInfo *currAttInfo = &attInfo[i];
+ XML_AttrInfo *currAttInfo = &parser->m_attInfo[i];
#endif
/* add the name and value to the attribute list */
ATTRIBUTE_ID *attId = getAttributeId(parser, enc, currAtt->name,
@@ -3093,25 +3234,25 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
if (!attId)
return XML_ERROR_NO_MEMORY;
#ifdef XML_ATTR_INFO
- currAttInfo->nameStart = parseEndByteIndex - (parseEndPtr - currAtt->name);
+ currAttInfo->nameStart = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->name);
currAttInfo->nameEnd = currAttInfo->nameStart +
XmlNameLength(enc, currAtt->name);
- currAttInfo->valueStart = parseEndByteIndex -
- (parseEndPtr - currAtt->valuePtr);
- currAttInfo->valueEnd = parseEndByteIndex - (parseEndPtr - currAtt->valueEnd);
+ currAttInfo->valueStart = parser->m_parseEndByteIndex -
+ (parser->m_parseEndPtr - currAtt->valuePtr);
+ currAttInfo->valueEnd = parser->m_parseEndByteIndex - (parser->m_parseEndPtr - currAtt->valueEnd);
#endif
/* Detect duplicate attributes by their QNames. This does not work when
namespace processing is turned on and different prefixes for the same
namespace are used. For this case we have a check further down.
*/
if ((attId->name)[-1]) {
- if (enc == encoding)
- eventPtr = atts[i].name;
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = parser->m_atts[i].name;
return XML_ERROR_DUPLICATE_ATTRIBUTE;
}
(attId->name)[-1] = 1;
appAtts[attIndex++] = attId->name;
- if (!atts[i].normalized) {
+ if (!parser->m_atts[i].normalized) {
enum XML_Error result;
XML_Bool isCdata = XML_TRUE;
@@ -3128,20 +3269,20 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
/* normalize the attribute value */
result = storeAttributeValue(parser, enc, isCdata,
- atts[i].valuePtr, atts[i].valueEnd,
- &tempPool);
+ parser->m_atts[i].valuePtr, parser->m_atts[i].valueEnd,
+ &parser->m_tempPool);
if (result)
return result;
- appAtts[attIndex] = poolStart(&tempPool);
- poolFinish(&tempPool);
+ appAtts[attIndex] = poolStart(&parser->m_tempPool);
+ poolFinish(&parser->m_tempPool);
}
else {
/* the value did not need normalizing */
- appAtts[attIndex] = poolStoreString(&tempPool, enc, atts[i].valuePtr,
- atts[i].valueEnd);
+ appAtts[attIndex] = poolStoreString(&parser->m_tempPool, enc, parser->m_atts[i].valuePtr,
+ parser->m_atts[i].valueEnd);
if (appAtts[attIndex] == 0)
return XML_ERROR_NO_MEMORY;
- poolFinish(&tempPool);
+ poolFinish(&parser->m_tempPool);
}
/* handle prefixed attribute names */
if (attId->prefix) {
@@ -3165,16 +3306,16 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
}
/* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
- nSpecifiedAtts = attIndex;
+ parser->m_nSpecifiedAtts = attIndex;
if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
for (i = 0; i < attIndex; i += 2)
if (appAtts[i] == elementType->idAtt->name) {
- idAttIndex = i;
+ parser->m_idAttIndex = i;
break;
}
}
else
- idAttIndex = -1;
+ parser->m_idAttIndex = -1;
/* do attribute defaulting */
for (i = 0; i < nDefaultAtts; i++) {
@@ -3208,29 +3349,33 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
i = 0;
if (nPrefixes) {
int j; /* hash table index */
- unsigned long version = nsAttsVersion;
- int nsAttsSize = (int)1 << nsAttsPower;
+ unsigned long version = parser->m_nsAttsVersion;
+ int nsAttsSize = (int)1 << parser->m_nsAttsPower;
+ unsigned char oldNsAttsPower = parser->m_nsAttsPower;
/* size of hash table must be at least 2 * (# of prefixed attributes) */
- if ((nPrefixes << 1) >> nsAttsPower) { /* true for nsAttsPower = 0 */
+ if ((nPrefixes << 1) >> parser->m_nsAttsPower) { /* true for m_nsAttsPower = 0 */
NS_ATT *temp;
/* hash table size must also be a power of 2 and >= 8 */
- while (nPrefixes >> nsAttsPower++);
- if (nsAttsPower < 3)
- nsAttsPower = 3;
- nsAttsSize = (int)1 << nsAttsPower;
- temp = (NS_ATT *)REALLOC(nsAtts, nsAttsSize * sizeof(NS_ATT));
- if (!temp)
+ while (nPrefixes >> parser->m_nsAttsPower++);
+ if (parser->m_nsAttsPower < 3)
+ parser->m_nsAttsPower = 3;
+ nsAttsSize = (int)1 << parser->m_nsAttsPower;
+ temp = (NS_ATT *)REALLOC(parser, parser->m_nsAtts, nsAttsSize * sizeof(NS_ATT));
+ if (!temp) {
+ /* Restore actual size of memory in m_nsAtts */
+ parser->m_nsAttsPower = oldNsAttsPower;
return XML_ERROR_NO_MEMORY;
- nsAtts = temp;
- version = 0; /* force re-initialization of nsAtts hash table */
+ }
+ parser->m_nsAtts = temp;
+ version = 0; /* force re-initialization of m_nsAtts hash table */
}
- /* using a version flag saves us from initializing nsAtts every time */
+ /* using a version flag saves us from initializing m_nsAtts every time */
if (!version) { /* initialize version flags when version wraps around */
version = INIT_ATTS_VERSION;
for (j = nsAttsSize; j != 0; )
- nsAtts[--j].version = version;
+ parser->m_nsAtts[--j].version = version;
}
- nsAttsVersion = --version;
+ parser->m_nsAttsVersion = --version;
/* expand prefixed names and check for duplicates */
for (; i < attIndex; i += 2) {
@@ -3247,15 +3392,32 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
((XML_Char *)s)[-1] = 0; /* clear flag */
id = (ATTRIBUTE_ID *)lookup(parser, &dtd->attributeIds, s, 0);
- if (!id || !id->prefix)
- return XML_ERROR_NO_MEMORY;
+ if (!id || !id->prefix) {
+ /* This code is walking through the appAtts array, dealing
+ * with (in this case) a prefixed attribute name. To be in
+ * the array, the attribute must have already been bound, so
+ * has to have passed through the hash table lookup once
+ * already. That implies that an entry for it already
+ * exists, so the lookup above will return a pointer to
+ * already allocated memory. There is no opportunaity for
+ * the allocator to fail, so the condition above cannot be
+ * fulfilled.
+ *
+ * Since it is difficult to be certain that the above
+ * analysis is complete, we retain the test and merely
+ * remove the code from coverage tests.
+ */
+ return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
+ }
b = id->prefix->binding;
- if (!b)
- return XML_ERROR_UNBOUND_PREFIX;
+ if (!b) {
+ //return XML_ERROR_UNBOUND_PREFIX;
+ continue;
+ }
for (j = 0; j < b->uriLen; j++) {
const XML_Char c = b->uri[j];
- if (!poolAppendChar(&tempPool, c))
+ if (!poolAppendChar(&parser->m_tempPool, c))
return XML_ERROR_NO_MEMORY;
}
@@ -3267,7 +3429,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
sip24_update(&sip_state, s, keylen(s) * sizeof(XML_Char));
do { /* copies null terminator */
- if (!poolAppendChar(&tempPool, *s))
+ if (!poolAppendChar(&parser->m_tempPool, *s))
return XML_ERROR_NO_MEMORY;
} while (*s++);
@@ -3279,40 +3441,40 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
unsigned char step = 0;
unsigned long mask = nsAttsSize - 1;
j = uriHash & mask; /* index into hash table */
- while (nsAtts[j].version == version) {
+ while (parser->m_nsAtts[j].version == version) {
/* for speed we compare stored hash values first */
- if (uriHash == nsAtts[j].hash) {
- const XML_Char *s1 = poolStart(&tempPool);
- const XML_Char *s2 = nsAtts[j].uriName;
+ if (uriHash == parser->m_nsAtts[j].hash) {
+ const XML_Char *s1 = poolStart(&parser->m_tempPool);
+ const XML_Char *s2 = parser->m_nsAtts[j].uriName;
/* s1 is null terminated, but not s2 */
for (; *s1 == *s2 && *s1 != 0; s1++, s2++);
if (*s1 == 0)
return XML_ERROR_DUPLICATE_ATTRIBUTE;
}
if (!step)
- step = PROBE_STEP(uriHash, mask, nsAttsPower);
+ step = PROBE_STEP(uriHash, mask, parser->m_nsAttsPower);
j < step ? (j += nsAttsSize - step) : (j -= step);
}
}
- if (ns_triplets) { /* append namespace separator and prefix */
- tempPool.ptr[-1] = namespaceSeparator;
+ if (parser->m_ns_triplets) { /* append namespace separator and prefix */
+ parser->m_tempPool.ptr[-1] = parser->m_namespaceSeparator;
s = b->prefix->name;
do {
- if (!poolAppendChar(&tempPool, *s))
+ if (!poolAppendChar(&parser->m_tempPool, *s))
return XML_ERROR_NO_MEMORY;
} while (*s++);
}
/* store expanded name in attribute list */
- s = poolStart(&tempPool);
- poolFinish(&tempPool);
+ s = poolStart(&parser->m_tempPool);
+ poolFinish(&parser->m_tempPool);
appAtts[i] = s;
/* fill empty slot with new version, uriName and hash value */
- nsAtts[j].version = version;
- nsAtts[j].hash = uriHash;
- nsAtts[j].uriName = s;
+ parser->m_nsAtts[j].version = version;
+ parser->m_nsAtts[j].hash = uriHash;
+ parser->m_nsAtts[j].uriName = s;
if (!--nPrefixes) {
i += 2;
@@ -3329,11 +3491,11 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
for (binding = *bindingsPtr; binding; binding = binding->nextTagBinding)
binding->attId->name[-1] = 0;
- if (!ns)
+ if (!parser->m_ns)
return XML_ERROR_NONE;
/* expand the element type name */
- if (elementType->prefix) {
+ if (elementType->prefix && elementType->prefix->binding) {
binding = elementType->prefix->binding;
if (!binding)
return XML_ERROR_UNBOUND_PREFIX;
@@ -3348,7 +3510,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
else
return XML_ERROR_NONE;
prefixLen = 0;
- if (ns_triplets && binding->prefix->name) {
+ if (parser->m_ns_triplets && binding->prefix->name) {
for (; binding->prefix->name[prefixLen++];)
; /* prefixLen includes null terminator */
}
@@ -3361,24 +3523,24 @@ storeAtts(XML_Parser parser, const ENCODING *enc,
n = i + binding->uriLen + prefixLen;
if (n > binding->uriAlloc) {
TAG *p;
- uri = (XML_Char *)MALLOC((n + EXPAND_SPARE) * sizeof(XML_Char));
+ uri = (XML_Char *)MALLOC(parser, (n + EXPAND_SPARE) * sizeof(XML_Char));
if (!uri)
return XML_ERROR_NO_MEMORY;
binding->uriAlloc = n + EXPAND_SPARE;
memcpy(uri, binding->uri, binding->uriLen * sizeof(XML_Char));
- for (p = tagStack; p; p = p->parent)
+ for (p = parser->m_tagStack; p; p = p->parent)
if (p->name.str == binding->uri)
p->name.str = uri;
- FREE(binding->uri);
+ FREE(parser, binding->uri);
binding->uri = uri;
}
- /* if namespaceSeparator != '\0' then uri includes it already */
+ /* if m_namespaceSeparator != '\0' then uri includes it already */
uri = binding->uri + binding->uriLen;
memcpy(uri, localPart, i * sizeof(XML_Char));
/* we always have a namespace separator between localPart and prefix */
if (prefixLen) {
uri += i - 1;
- *uri = namespaceSeparator; /* replace null terminator */
+ *uri = parser->m_namespaceSeparator; /* replace null terminator */
memcpy(uri + 1, binding->prefix->name, prefixLen * sizeof(XML_Char));
}
tagNamePtr->str = binding->uri;
@@ -3429,10 +3591,10 @@ addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
&& prefix->name[2] == XML_T(ASCII_l)) {
/* Not allowed to bind xmlns */
- if (prefix->name[3] == XML_T(ASCII_n)
+ /*if (prefix->name[3] == XML_T(ASCII_n)
&& prefix->name[4] == XML_T(ASCII_s)
&& prefix->name[5] == XML_T('\0'))
- return XML_ERROR_RESERVED_PREFIX_XMLNS;
+ return XML_ERROR_RESERVED_PREFIX_XMLNS;*/
if (prefix->name[3] == XML_T('\0'))
mustBeXML = XML_TRUE;
@@ -3449,55 +3611,55 @@ addBinding(XML_Parser parser, PREFIX *prefix, const ATTRIBUTE_ID *attId,
isXML = isXML && len == xmlLen;
isXMLNS = isXMLNS && len == xmlnsLen;
- if (mustBeXML != isXML)
+ /*if (mustBeXML != isXML)
return mustBeXML ? XML_ERROR_RESERVED_PREFIX_XML
- : XML_ERROR_RESERVED_NAMESPACE_URI;
+ : XML_ERROR_RESERVED_NAMESPACE_URI;*/
- if (isXMLNS)
- return XML_ERROR_RESERVED_NAMESPACE_URI;
+ /*if (isXMLNS)
+ return XML_ERROR_RESERVED_NAMESPACE_URI;*/
- if (namespaceSeparator)
+ if (parser->m_namespaceSeparator)
len++;
- if (freeBindingList) {
- b = freeBindingList;
+ if (parser->m_freeBindingList) {
+ b = parser->m_freeBindingList;
if (len > b->uriAlloc) {
- XML_Char *temp = (XML_Char *)REALLOC(b->uri,
+ XML_Char *temp = (XML_Char *)REALLOC(parser, b->uri,
sizeof(XML_Char) * (len + EXPAND_SPARE));
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
b->uri = temp;
b->uriAlloc = len + EXPAND_SPARE;
}
- freeBindingList = b->nextTagBinding;
+ parser->m_freeBindingList = b->nextTagBinding;
}
else {
- b = (BINDING *)MALLOC(sizeof(BINDING));
+ b = (BINDING *)MALLOC(parser, sizeof(BINDING));
if (!b)
return XML_ERROR_NO_MEMORY;
- b->uri = (XML_Char *)MALLOC(sizeof(XML_Char) * (len + EXPAND_SPARE));
+ b->uri = (XML_Char *)MALLOC(parser, sizeof(XML_Char) * (len + EXPAND_SPARE));
if (!b->uri) {
- FREE(b);
+ FREE(parser, b);
return XML_ERROR_NO_MEMORY;
}
b->uriAlloc = len + EXPAND_SPARE;
}
b->uriLen = len;
memcpy(b->uri, uri, len * sizeof(XML_Char));
- if (namespaceSeparator)
- b->uri[len - 1] = namespaceSeparator;
+ if (parser->m_namespaceSeparator)
+ b->uri[len - 1] = parser->m_namespaceSeparator;
b->prefix = prefix;
b->attId = attId;
b->prevPrefixBinding = prefix->binding;
/* NULL binding when default namespace undeclared */
- if (*uri == XML_T('\0') && prefix == &_dtd->defaultPrefix)
+ if (*uri == XML_T('\0') && prefix == &parser->m_dtd->defaultPrefix)
prefix->binding = NULL;
else
prefix->binding = b;
b->nextTagBinding = *bindingsPtr;
*bindingsPtr = b;
/* if attId == NULL then we are not starting a namespace scope */
- if (attId && startNamespaceDeclHandler)
- startNamespaceDeclHandler(handlerArg, prefix->name,
+ if (attId && parser->m_startNamespaceDeclHandler)
+ parser->m_startNamespaceDeclHandler(parser->m_handlerArg, prefix->name,
prefix->binding ? uri : 0);
return XML_ERROR_NONE;
}
@@ -3511,17 +3673,17 @@ cdataSectionProcessor(XML_Parser parser,
const char *end,
const char **endPtr)
{
- enum XML_Error result = doCdataSection(parser, encoding, &start, end,
- endPtr, (XML_Bool)!ps_finalBuffer);
+ enum XML_Error result = doCdataSection(parser, parser->m_encoding, &start, end,
+ endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result != XML_ERROR_NONE)
return result;
if (start) {
- if (parentParser) { /* we are parsing an external entity */
- processor = externalEntityContentProcessor;
+ if (parser->m_parentParser) { /* we are parsing an external entity */
+ parser->m_processor = externalEntityContentProcessor;
return externalEntityContentProcessor(parser, start, end, endPtr);
}
else {
- processor = contentProcessor;
+ parser->m_processor = contentProcessor;
return contentProcessor(parser, start, end, endPtr);
}
}
@@ -3542,14 +3704,14 @@ doCdataSection(XML_Parser parser,
const char *s = *startPtr;
const char **eventPP;
const char **eventEndPP;
- if (enc == encoding) {
- eventPP = &eventPtr;
+ if (enc == parser->m_encoding) {
+ eventPP = &parser->m_eventPtr;
*eventPP = s;
- eventEndPP = &eventEndPtr;
+ eventEndPP = &parser->m_eventEndPtr;
}
else {
- eventPP = &(openInternalEntities->internalEventPtr);
- eventEndPP = &(openInternalEntities->internalEventEndPtr);
+ eventPP = &(parser->m_openInternalEntities->internalEventPtr);
+ eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
*eventPP = s;
*startPtr = NULL;
@@ -3560,51 +3722,51 @@ doCdataSection(XML_Parser parser,
*eventEndPP = next;
switch (tok) {
case XML_TOK_CDATA_SECT_CLOSE:
- if (endCdataSectionHandler)
- endCdataSectionHandler(handlerArg);
-#if 0
+ if (parser->m_endCdataSectionHandler)
+ parser->m_endCdataSectionHandler(parser->m_handlerArg);
+/* BEGIN disabled code */
/* see comment under XML_TOK_CDATA_SECT_OPEN */
- else if (characterDataHandler)
- characterDataHandler(handlerArg, dataBuf, 0);
-#endif
- else if (defaultHandler)
+ else if (0 && parser->m_characterDataHandler)
+ parser->m_characterDataHandler(parser->m_handlerArg, parser->m_dataBuf, 0);
+/* END disabled code */
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
*startPtr = next;
*nextPtr = next;
- if (ps_parsing == XML_FINISHED)
+ if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
else
return XML_ERROR_NONE;
case XML_TOK_DATA_NEWLINE:
- if (characterDataHandler) {
+ if (parser->m_characterDataHandler) {
XML_Char c = 0xA;
- characterDataHandler(handlerArg, &c, 1);
+ parser->m_characterDataHandler(parser->m_handlerArg, &c, 1);
}
- else if (defaultHandler)
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
break;
case XML_TOK_DATA_CHARS:
{
- XML_CharacterDataHandler charDataHandler = characterDataHandler;
+ XML_CharacterDataHandler charDataHandler = parser->m_characterDataHandler;
if (charDataHandler) {
if (MUST_CONVERT(enc, s)) {
for (;;) {
- ICHAR *dataPtr = (ICHAR *)dataBuf;
- const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)dataBufEnd);
+ ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
+ const enum XML_Convert_Result convert_res = XmlConvert(enc, &s, next, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = next;
- charDataHandler(handlerArg, dataBuf,
- (int)(dataPtr - (ICHAR *)dataBuf));
+ charDataHandler(parser->m_handlerArg, parser->m_dataBuf,
+ (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
if ((convert_res == XML_CONVERT_COMPLETED) || (convert_res == XML_CONVERT_INPUT_INCOMPLETE))
break;
*eventPP = s;
}
}
else
- charDataHandler(handlerArg,
+ charDataHandler(parser->m_handlerArg,
(XML_Char *)s,
(int)((XML_Char *)next - (XML_Char *)s));
}
- else if (defaultHandler)
+ else if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
}
break;
@@ -3625,12 +3787,20 @@ doCdataSection(XML_Parser parser,
}
return XML_ERROR_UNCLOSED_CDATA_SECTION;
default:
+ /* Every token returned by XmlCdataSectionTok() has its own
+ * explicit case, so this default case will never be executed.
+ * We retain it as a safety net and exclude it from the coverage
+ * statistics.
+ *
+ * LCOV_EXCL_START
+ */
*eventPP = next;
return XML_ERROR_UNEXPECTED_STATE;
+ /* LCOV_EXCL_STOP */
}
*eventPP = s = next;
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
@@ -3653,12 +3823,12 @@ ignoreSectionProcessor(XML_Parser parser,
const char *end,
const char **endPtr)
{
- enum XML_Error result = doIgnoreSection(parser, encoding, &start, end,
- endPtr, (XML_Bool)!ps_finalBuffer);
+ enum XML_Error result = doIgnoreSection(parser, parser->m_encoding, &start, end,
+ endPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
if (result != XML_ERROR_NONE)
return result;
if (start) {
- processor = prologProcessor;
+ parser->m_processor = prologProcessor;
return prologProcessor(parser, start, end, endPtr);
}
return result;
@@ -3680,14 +3850,26 @@ doIgnoreSection(XML_Parser parser,
const char *s = *startPtr;
const char **eventPP;
const char **eventEndPP;
- if (enc == encoding) {
- eventPP = &eventPtr;
+ if (enc == parser->m_encoding) {
+ eventPP = &parser->m_eventPtr;
*eventPP = s;
- eventEndPP = &eventEndPtr;
+ eventEndPP = &parser->m_eventEndPtr;
}
else {
- eventPP = &(openInternalEntities->internalEventPtr);
- eventEndPP = &(openInternalEntities->internalEventEndPtr);
+ /* It's not entirely clear, but it seems the following two lines
+ * of code cannot be executed. The only occasions on which 'enc'
+ * is not 'encoding' are when this function is called
+ * from the internal entity processing, and IGNORE sections are an
+ * error in internal entities.
+ *
+ * Since it really isn't clear that this is true, we keep the code
+ * and just remove it from our coverage tests.
+ *
+ * LCOV_EXCL_START
+ */
+ eventPP = &(parser->m_openInternalEntities->internalEventPtr);
+ eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
+ /* LCOV_EXCL_STOP */
}
*eventPP = s;
*startPtr = NULL;
@@ -3695,11 +3877,11 @@ doIgnoreSection(XML_Parser parser,
*eventEndPP = next;
switch (tok) {
case XML_TOK_IGNORE_SECT:
- if (defaultHandler)
+ if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
*startPtr = next;
*nextPtr = next;
- if (ps_parsing == XML_FINISHED)
+ if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
else
return XML_ERROR_NONE;
@@ -3720,8 +3902,16 @@ doIgnoreSection(XML_Parser parser,
}
return XML_ERROR_SYNTAX; /* XML_ERROR_UNCLOSED_IGNORE_SECTION */
default:
+ /* All of the tokens that XmlIgnoreSectionTok() returns have
+ * explicit cases to handle them, so this default case is never
+ * executed. We keep it as a safety net anyway, and remove it
+ * from our test coverage statistics.
+ *
+ * LCOV_EXCL_START
+ */
*eventPP = next;
return XML_ERROR_UNEXPECTED_STATE;
+ /* LCOV_EXCL_STOP */
}
/* not reached */
}
@@ -3734,27 +3924,28 @@ initializeEncoding(XML_Parser parser)
const char *s;
#ifdef XML_UNICODE
char encodingBuf[128];
- if (!protocolEncodingName)
+ /* See comments abount `protoclEncodingName` in parserInit() */
+ if (!parser->m_protocolEncodingName)
s = NULL;
else {
int i;
- for (i = 0; protocolEncodingName[i]; i++) {
+ for (i = 0; parser->m_protocolEncodingName[i]; i++) {
if (i == sizeof(encodingBuf) - 1
- || (protocolEncodingName[i] & ~0x7f) != 0) {
+ || (parser->m_protocolEncodingName[i] & ~0x7f) != 0) {
encodingBuf[0] = '\0';
break;
}
- encodingBuf[i] = (char)protocolEncodingName[i];
+ encodingBuf[i] = (char)parser->m_protocolEncodingName[i];
}
encodingBuf[i] = '\0';
s = encodingBuf;
}
#else
- s = protocolEncodingName;
+ s = parser->m_protocolEncodingName;
#endif
- if ((ns ? XmlInitEncodingNS : XmlInitEncoding)(&initEncoding, &encoding, s))
+ if ((parser->m_ns ? XmlInitEncodingNS : XmlInitEncoding)(&parser->m_initEncoding, &parser->m_encoding, s))
return XML_ERROR_NONE;
- return handleUnknownEncoding(parser, protocolEncodingName);
+ return handleUnknownEncoding(parser, parser->m_protocolEncodingName);
}
static enum XML_Error
@@ -3768,13 +3959,13 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
const char *versionend;
const XML_Char *storedversion = NULL;
int standalone = -1;
- if (!(ns
+ if (!(parser->m_ns
? XmlParseXmlDeclNS
: XmlParseXmlDecl)(isGeneralTextEntity,
- encoding,
+ parser->m_encoding,
s,
next,
- &eventPtr,
+ &parser->m_eventPtr,
&version,
&versionend,
&encodingName,
@@ -3786,62 +3977,69 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
return XML_ERROR_XML_DECL;
}
if (!isGeneralTextEntity && standalone == 1) {
- _dtd->standalone = XML_TRUE;
+ parser->m_dtd->standalone = XML_TRUE;
#ifdef XML_DTD
- if (paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
- paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
+ if (parser->m_paramEntityParsing == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE)
+ parser->m_paramEntityParsing = XML_PARAM_ENTITY_PARSING_NEVER;
#endif /* XML_DTD */
}
- if (xmlDeclHandler) {
+ if (parser->m_xmlDeclHandler) {
if (encodingName != NULL) {
- storedEncName = poolStoreString(&temp2Pool,
- encoding,
+ storedEncName = poolStoreString(&parser->m_temp2Pool,
+ parser->m_encoding,
encodingName,
encodingName
- + XmlNameLength(encoding, encodingName));
+ + XmlNameLength(parser->m_encoding, encodingName));
if (!storedEncName)
return XML_ERROR_NO_MEMORY;
- poolFinish(&temp2Pool);
+ poolFinish(&parser->m_temp2Pool);
}
if (version) {
- storedversion = poolStoreString(&temp2Pool,
- encoding,
+ storedversion = poolStoreString(&parser->m_temp2Pool,
+ parser->m_encoding,
version,
- versionend - encoding->minBytesPerChar);
+ versionend - parser->m_encoding->minBytesPerChar);
if (!storedversion)
return XML_ERROR_NO_MEMORY;
}
- xmlDeclHandler(handlerArg, storedversion, storedEncName, standalone);
+ parser->m_xmlDeclHandler(parser->m_handlerArg, storedversion, storedEncName, standalone);
}
- else if (defaultHandler)
- reportDefault(parser, encoding, s, next);
- if (protocolEncodingName == NULL) {
+ else if (parser->m_defaultHandler)
+ reportDefault(parser, parser->m_encoding, s, next);
+ if (parser->m_protocolEncodingName == NULL) {
if (newEncoding) {
- if (newEncoding->minBytesPerChar != encoding->minBytesPerChar) {
- eventPtr = encodingName;
+ /* Check that the specified encoding does not conflict with what
+ * the parser has already deduced. Do we have the same number
+ * of bytes in the smallest representation of a character? If
+ * this is UTF-16, is it the same endianness?
+ */
+ if (newEncoding->minBytesPerChar != parser->m_encoding->minBytesPerChar
+ || (newEncoding->minBytesPerChar == 2 &&
+ newEncoding != parser->m_encoding)) {
+ parser->m_eventPtr = encodingName;
return XML_ERROR_INCORRECT_ENCODING;
}
- encoding = newEncoding;
+ parser->m_encoding = newEncoding;
}
else if (encodingName) {
enum XML_Error result;
if (!storedEncName) {
storedEncName = poolStoreString(
- &temp2Pool, encoding, encodingName,
- encodingName + XmlNameLength(encoding, encodingName));
+ &parser->m_temp2Pool, parser->m_encoding, encodingName,
+ encodingName + XmlNameLength(parser->m_encoding, encodingName));
if (!storedEncName)
return XML_ERROR_NO_MEMORY;
}
result = handleUnknownEncoding(parser, storedEncName);
- poolClear(&temp2Pool);
+ poolClear(&parser->m_temp2Pool);
if (result == XML_ERROR_UNKNOWN_ENCODING)
- eventPtr = encodingName;
+ parser->m_eventPtr = encodingName;
return result;
}
}
if (storedEncName || storedversion)
- poolClear(&temp2Pool);
+ poolClear(&parser->m_temp2Pool);
return XML_ERROR_NONE;
}
@@ -3849,7 +4047,7 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity,
static enum XML_Error
handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName)
{
- if (unknownEncodingHandler) {
+ if (parser->m_unknownEncodingHandler) {
XML_Encoding info;
int i;
for (i = 0; i < 256; i++)
@@ -3857,25 +4055,25 @@ handleUnknownEncoding(XML_Parser parser, const XML_Char *encodingName)
info.convert = NULL;
info.data = NULL;
info.release = NULL;
- if (unknownEncodingHandler(unknownEncodingHandlerData, encodingName,
+ if (parser->m_unknownEncodingHandler(parser->m_unknownEncodingHandlerData, encodingName,
&info)) {
ENCODING *enc;
- unknownEncodingMem = MALLOC(XmlSizeOfUnknownEncoding());
- if (!unknownEncodingMem) {
+ parser->m_unknownEncodingMem = MALLOC(parser, XmlSizeOfUnknownEncoding());
+ if (!parser->m_unknownEncodingMem) {
if (info.release)
info.release(info.data);
return XML_ERROR_NO_MEMORY;
}
- enc = (ns
+ enc = (parser->m_ns
? XmlInitUnknownEncodingNS
- : XmlInitUnknownEncoding)(unknownEncodingMem,
+ : XmlInitUnknownEncoding)(parser->m_unknownEncodingMem,
info.map,
info.convert,
info.data);
if (enc) {
- unknownEncodingData = info.data;
- unknownEncodingRelease = info.release;
- encoding = enc;
+ parser->m_unknownEncodingData = info.data;
+ parser->m_unknownEncodingRelease = info.release;
+ parser->m_encoding = enc;
return XML_ERROR_NONE;
}
}
@@ -3894,7 +4092,7 @@ prologInitProcessor(XML_Parser parser,
enum XML_Error result = initializeEncoding(parser);
if (result != XML_ERROR_NONE)
return result;
- processor = prologProcessor;
+ parser->m_processor = prologProcessor;
return prologProcessor(parser, s, end, nextPtr);
}
@@ -3912,14 +4110,14 @@ externalParEntInitProcessor(XML_Parser parser,
/* we know now that XML_Parse(Buffer) has been called,
so we consider the external parameter entity read */
- _dtd->paramEntityRead = XML_TRUE;
+ parser->m_dtd->paramEntityRead = XML_TRUE;
- if (prologState.inEntityValue) {
- processor = entityValueInitProcessor;
+ if (parser->m_prologState.inEntityValue) {
+ parser->m_processor = entityValueInitProcessor;
return entityValueInitProcessor(parser, s, end, nextPtr);
}
else {
- processor = externalParEntProcessor;
+ parser->m_processor = externalParEntProcessor;
return externalParEntProcessor(parser, s, end, nextPtr);
}
}
@@ -3933,13 +4131,13 @@ entityValueInitProcessor(XML_Parser parser,
int tok;
const char *start = s;
const char *next = start;
- eventPtr = start;
+ parser->m_eventPtr = start;
for (;;) {
- tok = XmlPrologTok(encoding, start, end, &next);
- eventEndPtr = next;
+ tok = XmlPrologTok(parser->m_encoding, start, end, &next);
+ parser->m_eventEndPtr = next;
if (tok <= 0) {
- if (!ps_finalBuffer && tok != XML_TOK_INVALID) {
+ if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
@@ -3955,24 +4153,23 @@ entityValueInitProcessor(XML_Parser parser,
break;
}
/* found end of entity value - can store it now */
- return storeEntityValue(parser, encoding, s, end);
+ return storeEntityValue(parser, parser->m_encoding, s, end);
}
else if (tok == XML_TOK_XML_DECL) {
enum XML_Error result;
result = processXmlDecl(parser, 0, start, next);
if (result != XML_ERROR_NONE)
return result;
- switch (ps_parsing) {
- case XML_SUSPENDED:
- *nextPtr = next;
- return XML_ERROR_NONE;
- case XML_FINISHED:
+ /* At this point, m_parsingStatus.parsing cannot be XML_SUSPENDED. For that
+ * to happen, a parameter entity parsing handler must have
+ * attempted to suspend the parser, which fails and raises an
+ * error. The parser can be aborted, but can't be suspended.
+ */
+ if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
- default:
- *nextPtr = next;
- }
+ *nextPtr = next;
/* stop scanning for text declaration - we found one */
- processor = entityValueProcessor;
+ parser->m_processor = entityValueProcessor;
return entityValueProcessor(parser, next, end, nextPtr);
}
/* If we are at the end of the buffer, this would cause XmlPrologTok to
@@ -3982,7 +4179,7 @@ entityValueInitProcessor(XML_Parser parser,
then, when this routine is entered the next time, XmlPrologTok will
return XML_TOK_INVALID, since the BOM is still in the buffer
*/
- else if (tok == XML_TOK_BOM && next == end && !ps_finalBuffer) {
+ else if (tok == XML_TOK_BOM && next == end && !parser->m_parsingStatus.finalBuffer) {
*nextPtr = next;
return XML_ERROR_NONE;
}
@@ -3995,7 +4192,7 @@ entityValueInitProcessor(XML_Parser parser,
return XML_ERROR_SYNTAX;
}
start = next;
- eventPtr = start;
+ parser->m_eventPtr = start;
}
}
@@ -4008,9 +4205,9 @@ externalParEntProcessor(XML_Parser parser,
const char *next = s;
int tok;
- tok = XmlPrologTok(encoding, s, end, &next);
+ tok = XmlPrologTok(parser->m_encoding, s, end, &next);
if (tok <= 0) {
- if (!ps_finalBuffer && tok != XML_TOK_INVALID) {
+ if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
@@ -4032,12 +4229,12 @@ externalParEntProcessor(XML_Parser parser,
*/
else if (tok == XML_TOK_BOM) {
s = next;
- tok = XmlPrologTok(encoding, s, end, &next);
+ tok = XmlPrologTok(parser->m_encoding, s, end, &next);
}
- processor = prologProcessor;
- return doProlog(parser, encoding, s, end, tok, next,
- nextPtr, (XML_Bool)!ps_finalBuffer);
+ parser->m_processor = prologProcessor;
+ return doProlog(parser, parser->m_encoding, s, end, tok, next,
+ nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
static enum XML_Error PTRCALL
@@ -4048,13 +4245,13 @@ entityValueProcessor(XML_Parser parser,
{
const char *start = s;
const char *next = s;
- const ENCODING *enc = encoding;
+ const ENCODING *enc = parser->m_encoding;
int tok;
for (;;) {
tok = XmlPrologTok(enc, start, end, &next);
if (tok <= 0) {
- if (!ps_finalBuffer && tok != XML_TOK_INVALID) {
+ if (!parser->m_parsingStatus.finalBuffer && tok != XML_TOK_INVALID) {
*nextPtr = s;
return XML_ERROR_NONE;
}
@@ -4085,9 +4282,9 @@ prologProcessor(XML_Parser parser,
const char **nextPtr)
{
const char *next = s;
- int tok = XmlPrologTok(encoding, s, end, &next);
- return doProlog(parser, encoding, s, end, tok, next,
- nextPtr, (XML_Bool)!ps_finalBuffer);
+ int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
+ return doProlog(parser, parser->m_encoding, s, end, tok, next,
+ nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
static enum XML_Error
@@ -4124,19 +4321,19 @@ doProlog(XML_Parser parser,
static const XML_Char enumValueStart[] = { ASCII_LPAREN, '\0' };
/* save one level of indirection */
- DTD * const dtd = _dtd;
+ DTD * const dtd = parser->m_dtd;
const char **eventPP;
const char **eventEndPP;
enum XML_Content_Quant quant;
- if (enc == encoding) {
- eventPP = &eventPtr;
- eventEndPP = &eventEndPtr;
+ if (enc == parser->m_encoding) {
+ eventPP = &parser->m_eventPtr;
+ eventEndPP = &parser->m_eventEndPtr;
}
else {
- eventPP = &(openInternalEntities->internalEventPtr);
- eventEndPP = &(openInternalEntities->internalEventEndPtr);
+ eventPP = &(parser->m_openInternalEntities->internalEventPtr);
+ eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
}
for (;;) {
@@ -4163,7 +4360,7 @@ doProlog(XML_Parser parser,
case XML_TOK_NONE:
#ifdef XML_DTD
/* for internal PE NOT referenced between declarations */
- if (enc != encoding && !openInternalEntities->betweenDecl) {
+ if (enc != parser->m_encoding && !parser->m_openInternalEntities->betweenDecl) {
*nextPtr = s;
return XML_ERROR_NONE;
}
@@ -4171,8 +4368,8 @@ doProlog(XML_Parser parser,
complete markup, not only for external PEs, but also for
internal PEs if the reference occurs between declarations.
*/
- if (isParamEntity || enc != encoding) {
- if (XmlTokenRole(&prologState, XML_TOK_NONE, end, end, enc)
+ if (parser->m_isParamEntity || enc != parser->m_encoding) {
+ if (XmlTokenRole(&parser->m_prologState, XML_TOK_NONE, end, end, enc)
== XML_ROLE_ERROR)
return XML_ERROR_INCOMPLETE_PE;
*nextPtr = s;
@@ -4186,34 +4383,34 @@ doProlog(XML_Parser parser,
break;
}
}
- role = XmlTokenRole(&prologState, tok, s, next, enc);
+ role = XmlTokenRole(&parser->m_prologState, tok, s, next, enc);
switch (role) {
case XML_ROLE_XML_DECL:
{
enum XML_Error result = processXmlDecl(parser, 0, s, next);
if (result != XML_ERROR_NONE)
return result;
- enc = encoding;
+ enc = parser->m_encoding;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_DOCTYPE_NAME:
- if (startDoctypeDeclHandler) {
- doctypeName = poolStoreString(&tempPool, enc, s, next);
- if (!doctypeName)
+ if (parser->m_startDoctypeDeclHandler) {
+ parser->m_doctypeName = poolStoreString(&parser->m_tempPool, enc, s, next);
+ if (!parser->m_doctypeName)
return XML_ERROR_NO_MEMORY;
- poolFinish(&tempPool);
- doctypePubid = NULL;
+ poolFinish(&parser->m_tempPool);
+ parser->m_doctypePubid = NULL;
handleDefault = XML_FALSE;
}
- doctypeSysid = NULL; /* always initialize to NULL */
+ parser->m_doctypeSysid = NULL; /* always initialize to NULL */
break;
case XML_ROLE_DOCTYPE_INTERNAL_SUBSET:
- if (startDoctypeDeclHandler) {
- startDoctypeDeclHandler(handlerArg, doctypeName, doctypeSysid,
- doctypePubid, 1);
- doctypeName = NULL;
- poolClear(&tempPool);
+ if (parser->m_startDoctypeDeclHandler) {
+ parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName, parser->m_doctypeSysid,
+ parser->m_doctypePubid, 1);
+ parser->m_doctypeName = NULL;
+ poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
@@ -4223,34 +4420,34 @@ doProlog(XML_Parser parser,
enum XML_Error result = processXmlDecl(parser, 1, s, next);
if (result != XML_ERROR_NONE)
return result;
- enc = encoding;
+ enc = parser->m_encoding;
handleDefault = XML_FALSE;
}
break;
#endif /* XML_DTD */
case XML_ROLE_DOCTYPE_PUBLIC_ID:
#ifdef XML_DTD
- useForeignDTD = XML_FALSE;
- declEntity = (ENTITY *)lookup(parser,
+ parser->m_useForeignDTD = XML_FALSE;
+ parser->m_declEntity = (ENTITY *)lookup(parser,
&dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
- if (!declEntity)
+ if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
- if (startDoctypeDeclHandler) {
+ if (parser->m_startDoctypeDeclHandler) {
XML_Char *pubId;
if (!XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
- pubId = poolStoreString(&tempPool, enc,
+ pubId = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!pubId)
return XML_ERROR_NO_MEMORY;
normalizePublicId(pubId);
- poolFinish(&tempPool);
- doctypePubid = pubId;
+ poolFinish(&parser->m_tempPool);
+ parser->m_doctypePubid = pubId;
handleDefault = XML_FALSE;
goto alreadyChecked;
}
@@ -4259,7 +4456,7 @@ doProlog(XML_Parser parser,
if (!XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
alreadyChecked:
- if (dtd->keepProcessing && declEntity) {
+ if (dtd->keepProcessing && parser->m_declEntity) {
XML_Char *tem = poolStoreString(&dtd->pool,
enc,
s + enc->minBytesPerChar,
@@ -4267,38 +4464,47 @@ doProlog(XML_Parser parser,
if (!tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
- declEntity->publicId = tem;
+ parser->m_declEntity->publicId = tem;
poolFinish(&dtd->pool);
- if (entityDeclHandler)
+ /* Don't suppress the default handler if we fell through from
+ * the XML_ROLE_DOCTYPE_PUBLIC_ID case.
+ */
+ if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_PUBLIC_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_DOCTYPE_CLOSE:
- if (doctypeName) {
- startDoctypeDeclHandler(handlerArg, doctypeName,
- doctypeSysid, doctypePubid, 0);
- poolClear(&tempPool);
+ if (parser->m_doctypeName) {
+ parser->m_startDoctypeDeclHandler(parser->m_handlerArg, parser->m_doctypeName,
+ parser->m_doctypeSysid, parser->m_doctypePubid, 0);
+ poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
- /* doctypeSysid will be non-NULL in the case of a previous
- XML_ROLE_DOCTYPE_SYSTEM_ID, even if startDoctypeDeclHandler
+ /* parser->m_doctypeSysid will be non-NULL in the case of a previous
+ XML_ROLE_DOCTYPE_SYSTEM_ID, even if parser->m_startDoctypeDeclHandler
was not set, indicating an external subset
*/
#ifdef XML_DTD
- if (doctypeSysid || useForeignDTD) {
+ if (parser->m_doctypeSysid || parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
- if (paramEntityParsing && externalEntityRefHandler) {
+ if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser,
&dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
- if (!entity)
- return XML_ERROR_NO_MEMORY;
- if (useForeignDTD)
- entity->base = curBase;
+ if (!entity) {
+ /* The external subset name "#" will have already been
+ * inserted into the hash table at the start of the
+ * external entity parsing, so no allocation will happen
+ * and lookup() cannot fail.
+ */
+ return XML_ERROR_NO_MEMORY; /* LCOV_EXCL_LINE */
+ }
+ if (parser->m_useForeignDTD)
+ entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
- if (!externalEntityRefHandler(externalEntityRefHandlerArg,
+ if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
@@ -4306,22 +4512,22 @@ doProlog(XML_Parser parser,
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (!dtd->standalone &&
- notStandaloneHandler &&
- !notStandaloneHandler(handlerArg))
+ parser->m_notStandaloneHandler &&
+ !parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
is no external subset and we must reset dtd->hasParamEntityRefs
*/
- else if (!doctypeSysid)
+ else if (!parser->m_doctypeSysid)
dtd->hasParamEntityRefs = hadParamEntityRefs;
/* end of DTD - no need to update dtd->keepProcessing */
}
- useForeignDTD = XML_FALSE;
+ parser->m_useForeignDTD = XML_FALSE;
}
#endif /* XML_DTD */
- if (endDoctypeDeclHandler) {
- endDoctypeDeclHandler(handlerArg);
+ if (parser->m_endDoctypeDeclHandler) {
+ parser->m_endDoctypeDeclHandler(parser->m_handlerArg);
handleDefault = XML_FALSE;
}
break;
@@ -4330,18 +4536,18 @@ doProlog(XML_Parser parser,
/* if there is no DOCTYPE declaration then now is the
last chance to read the foreign DTD
*/
- if (useForeignDTD) {
+ if (parser->m_useForeignDTD) {
XML_Bool hadParamEntityRefs = dtd->hasParamEntityRefs;
dtd->hasParamEntityRefs = XML_TRUE;
- if (paramEntityParsing && externalEntityRefHandler) {
+ if (parser->m_paramEntityParsing && parser->m_externalEntityRefHandler) {
ENTITY *entity = (ENTITY *)lookup(parser, &dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
if (!entity)
return XML_ERROR_NO_MEMORY;
- entity->base = curBase;
+ entity->base = parser->m_curBase;
dtd->paramEntityRead = XML_FALSE;
- if (!externalEntityRefHandler(externalEntityRefHandlerArg,
+ if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
@@ -4349,8 +4555,8 @@ doProlog(XML_Parser parser,
return XML_ERROR_EXTERNAL_ENTITY_HANDLING;
if (dtd->paramEntityRead) {
if (!dtd->standalone &&
- notStandaloneHandler &&
- !notStandaloneHandler(handlerArg))
+ parser->m_notStandaloneHandler &&
+ !parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
}
/* if we didn't read the foreign DTD then this means that there
@@ -4362,55 +4568,55 @@ doProlog(XML_Parser parser,
}
}
#endif /* XML_DTD */
- processor = contentProcessor;
+ parser->m_processor = contentProcessor;
return contentProcessor(parser, s, end, nextPtr);
case XML_ROLE_ATTLIST_ELEMENT_NAME:
- declElementType = getElementType(parser, enc, s, next);
- if (!declElementType)
+ parser->m_declElementType = getElementType(parser, enc, s, next);
+ if (!parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_NAME:
- declAttributeId = getAttributeId(parser, enc, s, next);
- if (!declAttributeId)
+ parser->m_declAttributeId = getAttributeId(parser, enc, s, next);
+ if (!parser->m_declAttributeId)
return XML_ERROR_NO_MEMORY;
- declAttributeIsCdata = XML_FALSE;
- declAttributeType = NULL;
- declAttributeIsId = XML_FALSE;
+ parser->m_declAttributeIsCdata = XML_FALSE;
+ parser->m_declAttributeType = NULL;
+ parser->m_declAttributeIsId = XML_FALSE;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_CDATA:
- declAttributeIsCdata = XML_TRUE;
- declAttributeType = atypeCDATA;
+ parser->m_declAttributeIsCdata = XML_TRUE;
+ parser->m_declAttributeType = atypeCDATA;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ID:
- declAttributeIsId = XML_TRUE;
- declAttributeType = atypeID;
+ parser->m_declAttributeIsId = XML_TRUE;
+ parser->m_declAttributeType = atypeID;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREF:
- declAttributeType = atypeIDREF;
+ parser->m_declAttributeType = atypeIDREF;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_IDREFS:
- declAttributeType = atypeIDREFS;
+ parser->m_declAttributeType = atypeIDREFS;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITY:
- declAttributeType = atypeENTITY;
+ parser->m_declAttributeType = atypeENTITY;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_ENTITIES:
- declAttributeType = atypeENTITIES;
+ parser->m_declAttributeType = atypeENTITIES;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKEN:
- declAttributeType = atypeNMTOKEN;
+ parser->m_declAttributeType = atypeNMTOKEN;
goto checkAttListDeclHandler;
case XML_ROLE_ATTRIBUTE_TYPE_NMTOKENS:
- declAttributeType = atypeNMTOKENS;
+ parser->m_declAttributeType = atypeNMTOKENS;
checkAttListDeclHandler:
- if (dtd->keepProcessing && attlistDeclHandler)
+ if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTRIBUTE_ENUM_VALUE:
case XML_ROLE_ATTRIBUTE_NOTATION_VALUE:
- if (dtd->keepProcessing && attlistDeclHandler) {
+ if (dtd->keepProcessing && parser->m_attlistDeclHandler) {
const XML_Char *prefix;
- if (declAttributeType) {
+ if (parser->m_declAttributeType) {
prefix = enumValueSep;
}
else {
@@ -4418,37 +4624,37 @@ doProlog(XML_Parser parser,
? notationPrefix
: enumValueStart);
}
- if (!poolAppendString(&tempPool, prefix))
+ if (!poolAppendString(&parser->m_tempPool, prefix))
return XML_ERROR_NO_MEMORY;
- if (!poolAppend(&tempPool, enc, s, next))
+ if (!poolAppend(&parser->m_tempPool, enc, s, next))
return XML_ERROR_NO_MEMORY;
- declAttributeType = tempPool.start;
+ parser->m_declAttributeType = parser->m_tempPool.start;
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_IMPLIED_ATTRIBUTE_VALUE:
case XML_ROLE_REQUIRED_ATTRIBUTE_VALUE:
if (dtd->keepProcessing) {
- if (!defineAttribute(declElementType, declAttributeId,
- declAttributeIsCdata, declAttributeIsId,
+ if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId,
+ parser->m_declAttributeIsCdata, parser->m_declAttributeIsId,
0, parser))
return XML_ERROR_NO_MEMORY;
- if (attlistDeclHandler && declAttributeType) {
- if (*declAttributeType == XML_T(ASCII_LPAREN)
- || (*declAttributeType == XML_T(ASCII_N)
- && declAttributeType[1] == XML_T(ASCII_O))) {
+ if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
+ if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
+ || (*parser->m_declAttributeType == XML_T(ASCII_N)
+ && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
- if (!poolAppendChar(&tempPool, XML_T(ASCII_RPAREN))
- || !poolAppendChar(&tempPool, XML_T('\0')))
+ if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
+ || !poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
- declAttributeType = tempPool.start;
- poolFinish(&tempPool);
+ parser->m_declAttributeType = parser->m_tempPool.start;
+ poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
- attlistDeclHandler(handlerArg, declElementType->name,
- declAttributeId->name, declAttributeType,
+ parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name,
+ parser->m_declAttributeId->name, parser->m_declAttributeType,
0, role == XML_ROLE_REQUIRED_ATTRIBUTE_VALUE);
- poolClear(&tempPool);
+ poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
@@ -4458,7 +4664,7 @@ doProlog(XML_Parser parser,
if (dtd->keepProcessing) {
const XML_Char *attVal;
enum XML_Error result =
- storeAttributeValue(parser, enc, declAttributeIsCdata,
+ storeAttributeValue(parser, enc, parser->m_declAttributeIsCdata,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar,
&dtd->pool);
@@ -4467,26 +4673,26 @@ doProlog(XML_Parser parser,
attVal = poolStart(&dtd->pool);
poolFinish(&dtd->pool);
/* ID attributes aren't allowed to have a default */
- if (!defineAttribute(declElementType, declAttributeId,
- declAttributeIsCdata, XML_FALSE, attVal, parser))
+ if (!defineAttribute(parser->m_declElementType, parser->m_declAttributeId,
+ parser->m_declAttributeIsCdata, XML_FALSE, attVal, parser))
return XML_ERROR_NO_MEMORY;
- if (attlistDeclHandler && declAttributeType) {
- if (*declAttributeType == XML_T(ASCII_LPAREN)
- || (*declAttributeType == XML_T(ASCII_N)
- && declAttributeType[1] == XML_T(ASCII_O))) {
+ if (parser->m_attlistDeclHandler && parser->m_declAttributeType) {
+ if (*parser->m_declAttributeType == XML_T(ASCII_LPAREN)
+ || (*parser->m_declAttributeType == XML_T(ASCII_N)
+ && parser->m_declAttributeType[1] == XML_T(ASCII_O))) {
/* Enumerated or Notation type */
- if (!poolAppendChar(&tempPool, XML_T(ASCII_RPAREN))
- || !poolAppendChar(&tempPool, XML_T('\0')))
+ if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_RPAREN))
+ || !poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_ERROR_NO_MEMORY;
- declAttributeType = tempPool.start;
- poolFinish(&tempPool);
+ parser->m_declAttributeType = parser->m_tempPool.start;
+ poolFinish(&parser->m_tempPool);
}
*eventEndPP = s;
- attlistDeclHandler(handlerArg, declElementType->name,
- declAttributeId->name, declAttributeType,
+ parser->m_attlistDeclHandler(parser->m_handlerArg, parser->m_declElementType->name,
+ parser->m_declAttributeId->name, parser->m_declAttributeType,
attVal,
role == XML_ROLE_FIXED_ATTRIBUTE_VALUE);
- poolClear(&tempPool);
+ poolClear(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
}
@@ -4496,18 +4702,18 @@ doProlog(XML_Parser parser,
enum XML_Error result = storeEntityValue(parser, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
- if (declEntity) {
- declEntity->textPtr = poolStart(&dtd->entityValuePool);
- declEntity->textLen = (int)(poolLength(&dtd->entityValuePool));
+ if (parser->m_declEntity) {
+ parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
+ parser->m_declEntity->textLen = (int)(poolLength(&dtd->entityValuePool));
poolFinish(&dtd->entityValuePool);
- if (entityDeclHandler) {
+ if (parser->m_entityDeclHandler) {
*eventEndPP = s;
- entityDeclHandler(handlerArg,
- declEntity->name,
- declEntity->is_param,
- declEntity->textPtr,
- declEntity->textLen,
- curBase, 0, 0, 0);
+ parser->m_entityDeclHandler(parser->m_handlerArg,
+ parser->m_declEntity->name,
+ parser->m_declEntity->is_param,
+ parser->m_declEntity->textPtr,
+ parser->m_declEntity->textLen,
+ parser->m_curBase, 0, 0, 0);
handleDefault = XML_FALSE;
}
}
@@ -4519,97 +4725,100 @@ doProlog(XML_Parser parser,
break;
case XML_ROLE_DOCTYPE_SYSTEM_ID:
#ifdef XML_DTD
- useForeignDTD = XML_FALSE;
+ parser->m_useForeignDTD = XML_FALSE;
#endif /* XML_DTD */
dtd->hasParamEntityRefs = XML_TRUE;
- if (startDoctypeDeclHandler) {
- doctypeSysid = poolStoreString(&tempPool, enc,
+ if (parser->m_startDoctypeDeclHandler) {
+ parser->m_doctypeSysid = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
- if (doctypeSysid == NULL)
+ if (parser->m_doctypeSysid == NULL)
return XML_ERROR_NO_MEMORY;
- poolFinish(&tempPool);
+ poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
#ifdef XML_DTD
else
- /* use externalSubsetName to make doctypeSysid non-NULL
- for the case where no startDoctypeDeclHandler is set */
- doctypeSysid = externalSubsetName;
+ /* use externalSubsetName to make parser->m_doctypeSysid non-NULL
+ for the case where no parser->m_startDoctypeDeclHandler is set */
+ parser->m_doctypeSysid = externalSubsetName;
#endif /* XML_DTD */
if (!dtd->standalone
#ifdef XML_DTD
- && !paramEntityParsing
+ && !parser->m_paramEntityParsing
#endif /* XML_DTD */
- && notStandaloneHandler
- && !notStandaloneHandler(handlerArg))
+ && parser->m_notStandaloneHandler
+ && !parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
#ifndef XML_DTD
break;
#else /* XML_DTD */
- if (!declEntity) {
- declEntity = (ENTITY *)lookup(parser,
+ if (!parser->m_declEntity) {
+ parser->m_declEntity = (ENTITY *)lookup(parser,
&dtd->paramEntities,
externalSubsetName,
sizeof(ENTITY));
- if (!declEntity)
+ if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
- declEntity->publicId = NULL;
+ parser->m_declEntity->publicId = NULL;
}
- /* fall through */
#endif /* XML_DTD */
+ /* fall through */
case XML_ROLE_ENTITY_SYSTEM_ID:
- if (dtd->keepProcessing && declEntity) {
- declEntity->systemId = poolStoreString(&dtd->pool, enc,
+ if (dtd->keepProcessing && parser->m_declEntity) {
+ parser->m_declEntity->systemId = poolStoreString(&dtd->pool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
- if (!declEntity->systemId)
+ if (!parser->m_declEntity->systemId)
return XML_ERROR_NO_MEMORY;
- declEntity->base = curBase;
+ parser->m_declEntity->base = parser->m_curBase;
poolFinish(&dtd->pool);
- if (entityDeclHandler)
+ /* Don't suppress the default handler if we fell through from
+ * the XML_ROLE_DOCTYPE_SYSTEM_ID case.
+ */
+ if (parser->m_entityDeclHandler && role == XML_ROLE_ENTITY_SYSTEM_ID)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_COMPLETE:
- if (dtd->keepProcessing && declEntity && entityDeclHandler) {
+ if (dtd->keepProcessing && parser->m_declEntity && parser->m_entityDeclHandler) {
*eventEndPP = s;
- entityDeclHandler(handlerArg,
- declEntity->name,
- declEntity->is_param,
+ parser->m_entityDeclHandler(parser->m_handlerArg,
+ parser->m_declEntity->name,
+ parser->m_declEntity->is_param,
0,0,
- declEntity->base,
- declEntity->systemId,
- declEntity->publicId,
+ parser->m_declEntity->base,
+ parser->m_declEntity->systemId,
+ parser->m_declEntity->publicId,
0);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_ENTITY_NOTATION_NAME:
- if (dtd->keepProcessing && declEntity) {
- declEntity->notation = poolStoreString(&dtd->pool, enc, s, next);
- if (!declEntity->notation)
+ if (dtd->keepProcessing && parser->m_declEntity) {
+ parser->m_declEntity->notation = poolStoreString(&dtd->pool, enc, s, next);
+ if (!parser->m_declEntity->notation)
return XML_ERROR_NO_MEMORY;
poolFinish(&dtd->pool);
- if (unparsedEntityDeclHandler) {
+ if (parser->m_unparsedEntityDeclHandler) {
*eventEndPP = s;
- unparsedEntityDeclHandler(handlerArg,
- declEntity->name,
- declEntity->base,
- declEntity->systemId,
- declEntity->publicId,
- declEntity->notation);
+ parser->m_unparsedEntityDeclHandler(parser->m_handlerArg,
+ parser->m_declEntity->name,
+ parser->m_declEntity->base,
+ parser->m_declEntity->systemId,
+ parser->m_declEntity->publicId,
+ parser->m_declEntity->notation);
handleDefault = XML_FALSE;
}
- else if (entityDeclHandler) {
+ else if (parser->m_entityDeclHandler) {
*eventEndPP = s;
- entityDeclHandler(handlerArg,
- declEntity->name,
+ parser->m_entityDeclHandler(parser->m_handlerArg,
+ parser->m_declEntity->name,
0,0,0,
- declEntity->base,
- declEntity->systemId,
- declEntity->publicId,
- declEntity->notation);
+ parser->m_declEntity->base,
+ parser->m_declEntity->systemId,
+ parser->m_declEntity->publicId,
+ parser->m_declEntity->notation);
handleDefault = XML_FALSE;
}
}
@@ -4617,36 +4826,36 @@ doProlog(XML_Parser parser,
case XML_ROLE_GENERAL_ENTITY_NAME:
{
if (XmlPredefinedEntityName(enc, s, next)) {
- declEntity = NULL;
+ parser->m_declEntity = NULL;
break;
}
if (dtd->keepProcessing) {
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (!name)
return XML_ERROR_NO_MEMORY;
- declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name,
+ parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->generalEntities, name,
sizeof(ENTITY));
- if (!declEntity)
+ if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
- if (declEntity->name != name) {
+ if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
- declEntity = NULL;
+ parser->m_declEntity = NULL;
}
else {
poolFinish(&dtd->pool);
- declEntity->publicId = NULL;
- declEntity->is_param = XML_FALSE;
+ parser->m_declEntity->publicId = NULL;
+ parser->m_declEntity->is_param = XML_FALSE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
- declEntity->is_internal = !(parentParser || openInternalEntities);
- if (entityDeclHandler)
+ parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities);
+ if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
}
else {
poolDiscard(&dtd->pool);
- declEntity = NULL;
+ parser->m_declEntity = NULL;
}
}
break;
@@ -4656,90 +4865,90 @@ doProlog(XML_Parser parser,
const XML_Char *name = poolStoreString(&dtd->pool, enc, s, next);
if (!name)
return XML_ERROR_NO_MEMORY;
- declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
+ parser->m_declEntity = (ENTITY *)lookup(parser, &dtd->paramEntities,
name, sizeof(ENTITY));
- if (!declEntity)
+ if (!parser->m_declEntity)
return XML_ERROR_NO_MEMORY;
- if (declEntity->name != name) {
+ if (parser->m_declEntity->name != name) {
poolDiscard(&dtd->pool);
- declEntity = NULL;
+ parser->m_declEntity = NULL;
}
else {
poolFinish(&dtd->pool);
- declEntity->publicId = NULL;
- declEntity->is_param = XML_TRUE;
+ parser->m_declEntity->publicId = NULL;
+ parser->m_declEntity->is_param = XML_TRUE;
/* if we have a parent parser or are reading an internal parameter
entity, then the entity declaration is not considered "internal"
*/
- declEntity->is_internal = !(parentParser || openInternalEntities);
- if (entityDeclHandler)
+ parser->m_declEntity->is_internal = !(parser->m_parentParser || parser->m_openInternalEntities);
+ if (parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
}
}
else {
poolDiscard(&dtd->pool);
- declEntity = NULL;
+ parser->m_declEntity = NULL;
}
#else /* not XML_DTD */
- declEntity = NULL;
+ parser->m_declEntity = NULL;
#endif /* XML_DTD */
break;
case XML_ROLE_NOTATION_NAME:
- declNotationPublicId = NULL;
- declNotationName = NULL;
- if (notationDeclHandler) {
- declNotationName = poolStoreString(&tempPool, enc, s, next);
- if (!declNotationName)
+ parser->m_declNotationPublicId = NULL;
+ parser->m_declNotationName = NULL;
+ if (parser->m_notationDeclHandler) {
+ parser->m_declNotationName = poolStoreString(&parser->m_tempPool, enc, s, next);
+ if (!parser->m_declNotationName)
return XML_ERROR_NO_MEMORY;
- poolFinish(&tempPool);
+ poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_PUBLIC_ID:
if (!XmlIsPublicId(enc, s, next, eventPP))
return XML_ERROR_PUBLICID;
- if (declNotationName) { /* means notationDeclHandler != NULL */
- XML_Char *tem = poolStoreString(&tempPool,
+ if (parser->m_declNotationName) { /* means m_notationDeclHandler != NULL */
+ XML_Char *tem = poolStoreString(&parser->m_tempPool,
enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!tem)
return XML_ERROR_NO_MEMORY;
normalizePublicId(tem);
- declNotationPublicId = tem;
- poolFinish(&tempPool);
+ parser->m_declNotationPublicId = tem;
+ poolFinish(&parser->m_tempPool);
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_NOTATION_SYSTEM_ID:
- if (declNotationName && notationDeclHandler) {
+ if (parser->m_declNotationName && parser->m_notationDeclHandler) {
const XML_Char *systemId
- = poolStoreString(&tempPool, enc,
+ = poolStoreString(&parser->m_tempPool, enc,
s + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!systemId)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
- notationDeclHandler(handlerArg,
- declNotationName,
- curBase,
+ parser->m_notationDeclHandler(parser->m_handlerArg,
+ parser->m_declNotationName,
+ parser->m_curBase,
systemId,
- declNotationPublicId);
+ parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
- poolClear(&tempPool);
+ poolClear(&parser->m_tempPool);
break;
case XML_ROLE_NOTATION_NO_SYSTEM_ID:
- if (declNotationPublicId && notationDeclHandler) {
+ if (parser->m_declNotationPublicId && parser->m_notationDeclHandler) {
*eventEndPP = s;
- notationDeclHandler(handlerArg,
- declNotationName,
- curBase,
+ parser->m_notationDeclHandler(parser->m_handlerArg,
+ parser->m_declNotationName,
+ parser->m_curBase,
0,
- declNotationPublicId);
+ parser->m_declNotationPublicId);
handleDefault = XML_FALSE;
}
- poolClear(&tempPool);
+ poolClear(&parser->m_tempPool);
break;
case XML_ROLE_ERROR:
switch (tok) {
@@ -4756,41 +4965,45 @@ doProlog(XML_Parser parser,
case XML_ROLE_IGNORE_SECT:
{
enum XML_Error result;
- if (defaultHandler)
+ if (parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
handleDefault = XML_FALSE;
result = doIgnoreSection(parser, enc, &next, end, nextPtr, haveMore);
if (result != XML_ERROR_NONE)
return result;
else if (!next) {
- processor = ignoreSectionProcessor;
+ parser->m_processor = ignoreSectionProcessor;
return result;
}
}
break;
#endif /* XML_DTD */
case XML_ROLE_GROUP_OPEN:
- if (prologState.level >= groupSize) {
- if (groupSize) {
- char *temp = (char *)REALLOC(groupConnector, groupSize *= 2);
- if (temp == NULL)
+ if (parser->m_prologState.level >= parser->m_groupSize) {
+ if (parser->m_groupSize) {
+ char *temp = (char *)REALLOC(parser, parser->m_groupConnector, parser->m_groupSize *= 2);
+ if (temp == NULL) {
+ parser->m_groupSize /= 2;
return XML_ERROR_NO_MEMORY;
- groupConnector = temp;
+ }
+ parser->m_groupConnector = temp;
if (dtd->scaffIndex) {
- int *temp = (int *)REALLOC(dtd->scaffIndex,
- groupSize * sizeof(int));
+ int *temp = (int *)REALLOC(parser, dtd->scaffIndex,
+ parser->m_groupSize * sizeof(int));
if (temp == NULL)
return XML_ERROR_NO_MEMORY;
dtd->scaffIndex = temp;
}
}
else {
- groupConnector = (char *)MALLOC(groupSize = 32);
- if (!groupConnector)
+ parser->m_groupConnector = (char *)MALLOC(parser, parser->m_groupSize = 32);
+ if (!parser->m_groupConnector) {
+ parser->m_groupSize = 0;
return XML_ERROR_NO_MEMORY;
+ }
}
}
- groupConnector[prologState.level] = 0;
+ parser->m_groupConnector[parser->m_prologState.level] = 0;
if (dtd->in_eldecl) {
int myindex = nextScaffoldPart(parser);
if (myindex < 0)
@@ -4798,37 +5011,37 @@ doProlog(XML_Parser parser,
dtd->scaffIndex[dtd->scaffLevel] = myindex;
dtd->scaffLevel++;
dtd->scaffold[myindex].type = XML_CTYPE_SEQ;
- if (elementDeclHandler)
+ if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
case XML_ROLE_GROUP_SEQUENCE:
- if (groupConnector[prologState.level] == ASCII_PIPE)
+ if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_PIPE)
return XML_ERROR_SYNTAX;
- groupConnector[prologState.level] = ASCII_COMMA;
- if (dtd->in_eldecl && elementDeclHandler)
+ parser->m_groupConnector[parser->m_prologState.level] = ASCII_COMMA;
+ if (dtd->in_eldecl && parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_GROUP_CHOICE:
- if (groupConnector[prologState.level] == ASCII_COMMA)
+ if (parser->m_groupConnector[parser->m_prologState.level] == ASCII_COMMA)
return XML_ERROR_SYNTAX;
if (dtd->in_eldecl
- && !groupConnector[prologState.level]
+ && !parser->m_groupConnector[parser->m_prologState.level]
&& (dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
!= XML_CTYPE_MIXED)
) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_CHOICE;
- if (elementDeclHandler)
+ if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
- groupConnector[prologState.level] = ASCII_PIPE;
+ parser->m_groupConnector[parser->m_prologState.level] = ASCII_PIPE;
break;
case XML_ROLE_PARAM_ENTITY_REF:
#ifdef XML_DTD
case XML_ROLE_INNER_PARAM_ENTITY_REF:
dtd->hasParamEntityRefs = XML_TRUE;
- if (!paramEntityParsing)
+ if (!parser->m_paramEntityParsing)
dtd->keepProcessing = dtd->standalone;
else {
const XML_Char *name;
@@ -4844,20 +5057,41 @@ doProlog(XML_Parser parser,
if yes, check that the entity exists, and that it is internal,
otherwise call the skipped entity handler
*/
- if (prologState.documentEntity &&
+ if (parser->m_prologState.documentEntity &&
(dtd->standalone
- ? !openInternalEntities
+ ? !parser->m_openInternalEntities
: !dtd->hasParamEntityRefs)) {
if (!entity)
return XML_ERROR_UNDEFINED_ENTITY;
- else if (!entity->is_internal)
- return XML_ERROR_ENTITY_DECLARED_IN_PE;
+ else if (!entity->is_internal) {
+ /* It's hard to exhaustively search the code to be sure,
+ * but there doesn't seem to be a way of executing the
+ * following line. There are two cases:
+ *
+ * If 'standalone' is false, the DTD must have no
+ * parameter entities or we wouldn't have passed the outer
+ * 'if' statement. That measn the only entity in the hash
+ * table is the external subset name "#" which cannot be
+ * given as a parameter entity name in XML syntax, so the
+ * lookup must have returned NULL and we don't even reach
+ * the test for an internal entity.
+ *
+ * If 'standalone' is true, it does not seem to be
+ * possible to create entities taking this code path that
+ * are not internal entities, so fail the test above.
+ *
+ * Because this analysis is very uncertain, the code is
+ * being left in place and merely removed from the
+ * coverage test statistics.
+ */
+ return XML_ERROR_ENTITY_DECLARED_IN_PE; /* LCOV_EXCL_LINE */
+ }
}
else if (!entity) {
dtd->keepProcessing = dtd->standalone;
/* cannot report skipped entities in declarations */
- if ((role == XML_ROLE_PARAM_ENTITY_REF) && skippedEntityHandler) {
- skippedEntityHandler(handlerArg, name, 1);
+ if ((role == XML_ROLE_PARAM_ENTITY_REF) && parser->m_skippedEntityHandler) {
+ parser->m_skippedEntityHandler(parser->m_handlerArg, name, 1);
handleDefault = XML_FALSE;
}
break;
@@ -4874,10 +5108,10 @@ doProlog(XML_Parser parser,
handleDefault = XML_FALSE;
break;
}
- if (externalEntityRefHandler) {
+ if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
- if (!externalEntityRefHandler(externalEntityRefHandlerArg,
+ if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
@@ -4899,17 +5133,17 @@ doProlog(XML_Parser parser,
}
#endif /* XML_DTD */
if (!dtd->standalone &&
- notStandaloneHandler &&
- !notStandaloneHandler(handlerArg))
+ parser->m_notStandaloneHandler &&
+ !parser->m_notStandaloneHandler(parser->m_handlerArg))
return XML_ERROR_NOT_STANDALONE;
break;
/* Element declaration stuff */
case XML_ROLE_ELEMENT_NAME:
- if (elementDeclHandler) {
- declElementType = getElementType(parser, enc, s, next);
- if (!declElementType)
+ if (parser->m_elementDeclHandler) {
+ parser->m_declElementType = getElementType(parser, enc, s, next);
+ if (!parser->m_declElementType)
return XML_ERROR_NO_MEMORY;
dtd->scaffLevel = 0;
dtd->scaffCount = 0;
@@ -4921,8 +5155,8 @@ doProlog(XML_Parser parser,
case XML_ROLE_CONTENT_ANY:
case XML_ROLE_CONTENT_EMPTY:
if (dtd->in_eldecl) {
- if (elementDeclHandler) {
- XML_Content * content = (XML_Content *) MALLOC(sizeof(XML_Content));
+ if (parser->m_elementDeclHandler) {
+ XML_Content * content = (XML_Content *) MALLOC(parser, sizeof(XML_Content));
if (!content)
return XML_ERROR_NO_MEMORY;
content->quant = XML_CQUANT_NONE;
@@ -4933,7 +5167,7 @@ doProlog(XML_Parser parser,
XML_CTYPE_ANY :
XML_CTYPE_EMPTY);
*eventEndPP = s;
- elementDeclHandler(handlerArg, declElementType->name, content);
+ parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, content);
handleDefault = XML_FALSE;
}
dtd->in_eldecl = XML_FALSE;
@@ -4944,7 +5178,7 @@ doProlog(XML_Parser parser,
if (dtd->in_eldecl) {
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel - 1]].type
= XML_CTYPE_MIXED;
- if (elementDeclHandler)
+ if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
@@ -4981,7 +5215,7 @@ doProlog(XML_Parser parser,
nameLen = 0;
for (; name[nameLen++]; );
dtd->contentStringLen += nameLen;
- if (elementDeclHandler)
+ if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
}
break;
@@ -4999,7 +5233,7 @@ doProlog(XML_Parser parser,
quant = XML_CQUANT_PLUS;
closeGroup:
if (dtd->in_eldecl) {
- if (elementDeclHandler)
+ if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
dtd->scaffLevel--;
dtd->scaffold[dtd->scaffIndex[dtd->scaffLevel]].quant = quant;
@@ -5009,7 +5243,7 @@ doProlog(XML_Parser parser,
if (!model)
return XML_ERROR_NO_MEMORY;
*eventEndPP = s;
- elementDeclHandler(handlerArg, declElementType->name, model);
+ parser->m_elementDeclHandler(parser->m_handlerArg, parser->m_declElementType->name, model);
}
dtd->in_eldecl = XML_FALSE;
dtd->contentStringLen = 0;
@@ -5036,31 +5270,31 @@ doProlog(XML_Parser parser,
}
break;
case XML_ROLE_DOCTYPE_NONE:
- if (startDoctypeDeclHandler)
+ if (parser->m_startDoctypeDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ENTITY_NONE:
- if (dtd->keepProcessing && entityDeclHandler)
+ if (dtd->keepProcessing && parser->m_entityDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_NOTATION_NONE:
- if (notationDeclHandler)
+ if (parser->m_notationDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ATTLIST_NONE:
- if (dtd->keepProcessing && attlistDeclHandler)
+ if (dtd->keepProcessing && parser->m_attlistDeclHandler)
handleDefault = XML_FALSE;
break;
case XML_ROLE_ELEMENT_NONE:
- if (elementDeclHandler)
+ if (parser->m_elementDeclHandler)
handleDefault = XML_FALSE;
break;
} /* end of big switch */
- if (handleDefault && defaultHandler)
+ if (handleDefault && parser->m_defaultHandler)
reportDefault(parser, enc, s, next);
- switch (ps_parsing) {
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
@@ -5080,18 +5314,18 @@ epilogProcessor(XML_Parser parser,
const char *end,
const char **nextPtr)
{
- processor = epilogProcessor;
- eventPtr = s;
+ parser->m_processor = epilogProcessor;
+ parser->m_eventPtr = s;
for (;;) {
const char *next = NULL;
- int tok = XmlPrologTok(encoding, s, end, &next);
- eventEndPtr = next;
+ int tok = XmlPrologTok(parser->m_encoding, s, end, &next);
+ parser->m_eventEndPtr = next;
switch (tok) {
/* report partial linebreak - it might be the last token */
case -XML_TOK_PROLOG_S:
- if (defaultHandler) {
- reportDefault(parser, encoding, s, next);
- if (ps_parsing == XML_FINISHED)
+ if (parser->m_defaultHandler) {
+ reportDefault(parser, parser->m_encoding, s, next);
+ if (parser->m_parsingStatus.parsing == XML_FINISHED)
return XML_ERROR_ABORTED;
}
*nextPtr = next;
@@ -5100,28 +5334,28 @@ epilogProcessor(XML_Parser parser,
*nextPtr = s;
return XML_ERROR_NONE;
case XML_TOK_PROLOG_S:
- if (defaultHandler)
- reportDefault(parser, encoding, s, next);
+ if (parser->m_defaultHandler)
+ reportDefault(parser, parser->m_encoding, s, next);
break;
case XML_TOK_PI:
- if (!reportProcessingInstruction(parser, encoding, s, next))
+ if (!reportProcessingInstruction(parser, parser->m_encoding, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_COMMENT:
- if (!reportComment(parser, encoding, s, next))
+ if (!reportComment(parser, parser->m_encoding, s, next))
return XML_ERROR_NO_MEMORY;
break;
case XML_TOK_INVALID:
- eventPtr = next;
+ parser->m_eventPtr = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
- if (!ps_finalBuffer) {
+ if (!parser->m_parsingStatus.finalBuffer) {
*nextPtr = s;
return XML_ERROR_NONE;
}
return XML_ERROR_UNCLOSED_TOKEN;
case XML_TOK_PARTIAL_CHAR:
- if (!ps_finalBuffer) {
+ if (!parser->m_parsingStatus.finalBuffer) {
*nextPtr = s;
return XML_ERROR_NONE;
}
@@ -5129,8 +5363,8 @@ epilogProcessor(XML_Parser parser,
default:
return XML_ERROR_JUNK_AFTER_DOC_ELEMENT;
}
- eventPtr = s = next;
- switch (ps_parsing) {
+ parser->m_eventPtr = s = next;
+ switch (parser->m_parsingStatus.parsing) {
case XML_SUSPENDED:
*nextPtr = next;
return XML_ERROR_NONE;
@@ -5150,21 +5384,21 @@ processInternalEntity(XML_Parser parser, ENTITY *entity,
enum XML_Error result;
OPEN_INTERNAL_ENTITY *openEntity;
- if (freeInternalEntities) {
- openEntity = freeInternalEntities;
- freeInternalEntities = openEntity->next;
+ if (parser->m_freeInternalEntities) {
+ openEntity = parser->m_freeInternalEntities;
+ parser->m_freeInternalEntities = openEntity->next;
}
else {
- openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(sizeof(OPEN_INTERNAL_ENTITY));
+ openEntity = (OPEN_INTERNAL_ENTITY *)MALLOC(parser, sizeof(OPEN_INTERNAL_ENTITY));
if (!openEntity)
return XML_ERROR_NO_MEMORY;
}
entity->open = XML_TRUE;
entity->processed = 0;
- openEntity->next = openInternalEntities;
- openInternalEntities = openEntity;
+ openEntity->next = parser->m_openInternalEntities;
+ parser->m_openInternalEntities = openEntity;
openEntity->entity = entity;
- openEntity->startTagLevel = tagLevel;
+ openEntity->startTagLevel = parser->m_tagLevel;
openEntity->betweenDecl = betweenDecl;
openEntity->internalEventPtr = NULL;
openEntity->internalEventEndPtr = NULL;
@@ -5175,26 +5409,26 @@ processInternalEntity(XML_Parser parser, ENTITY *entity,
#ifdef XML_DTD
if (entity->is_param) {
- int tok = XmlPrologTok(internalEncoding, textStart, textEnd, &next);
- result = doProlog(parser, internalEncoding, textStart, textEnd, tok,
+ int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
+ result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok,
next, &next, XML_FALSE);
}
else
#endif /* XML_DTD */
- result = doContent(parser, tagLevel, internalEncoding, textStart,
+ result = doContent(parser, parser->m_tagLevel, parser->m_internalEncoding, textStart,
textEnd, &next, XML_FALSE);
if (result == XML_ERROR_NONE) {
- if (textEnd != next && ps_parsing == XML_SUSPENDED) {
+ if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - textStart);
- processor = internalEntityProcessor;
+ parser->m_processor = internalEntityProcessor;
}
else {
entity->open = XML_FALSE;
- openInternalEntities = openEntity->next;
+ parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
- openEntity->next = freeInternalEntities;
- freeInternalEntities = openEntity;
+ openEntity->next = parser->m_freeInternalEntities;
+ parser->m_freeInternalEntities = openEntity;
}
}
return result;
@@ -5210,7 +5444,7 @@ internalEntityProcessor(XML_Parser parser,
const char *textStart, *textEnd;
const char *next;
enum XML_Error result;
- OPEN_INTERNAL_ENTITY *openEntity = openInternalEntities;
+ OPEN_INTERNAL_ENTITY *openEntity = parser->m_openInternalEntities;
if (!openEntity)
return XML_ERROR_UNEXPECTED_STATE;
@@ -5222,44 +5456,44 @@ internalEntityProcessor(XML_Parser parser,
#ifdef XML_DTD
if (entity->is_param) {
- int tok = XmlPrologTok(internalEncoding, textStart, textEnd, &next);
- result = doProlog(parser, internalEncoding, textStart, textEnd, tok,
+ int tok = XmlPrologTok(parser->m_internalEncoding, textStart, textEnd, &next);
+ result = doProlog(parser, parser->m_internalEncoding, textStart, textEnd, tok,
next, &next, XML_FALSE);
}
else
#endif /* XML_DTD */
- result = doContent(parser, openEntity->startTagLevel, internalEncoding,
+ result = doContent(parser, openEntity->startTagLevel, parser->m_internalEncoding,
textStart, textEnd, &next, XML_FALSE);
if (result != XML_ERROR_NONE)
return result;
- else if (textEnd != next && ps_parsing == XML_SUSPENDED) {
+ else if (textEnd != next && parser->m_parsingStatus.parsing == XML_SUSPENDED) {
entity->processed = (int)(next - (char *)entity->textPtr);
return result;
}
else {
entity->open = XML_FALSE;
- openInternalEntities = openEntity->next;
+ parser->m_openInternalEntities = openEntity->next;
/* put openEntity back in list of free instances */
- openEntity->next = freeInternalEntities;
- freeInternalEntities = openEntity;
+ openEntity->next = parser->m_freeInternalEntities;
+ parser->m_freeInternalEntities = openEntity;
}
#ifdef XML_DTD
if (entity->is_param) {
int tok;
- processor = prologProcessor;
- tok = XmlPrologTok(encoding, s, end, &next);
- return doProlog(parser, encoding, s, end, tok, next, nextPtr,
- (XML_Bool)!ps_finalBuffer);
+ parser->m_processor = prologProcessor;
+ tok = XmlPrologTok(parser->m_encoding, s, end, &next);
+ return doProlog(parser, parser->m_encoding, s, end, tok, next, nextPtr,
+ (XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
else
#endif /* XML_DTD */
{
- processor = contentProcessor;
+ parser->m_processor = contentProcessor;
/* see externalEntityContentProcessor vs contentProcessor */
- return doContent(parser, parentParser ? 1 : 0, encoding, s, end,
- nextPtr, (XML_Bool)!ps_finalBuffer);
+ return doContent(parser, parser->m_parentParser ? 1 : 0, parser->m_encoding, s, end,
+ nextPtr, (XML_Bool)!parser->m_parsingStatus.finalBuffer);
}
}
@@ -5269,7 +5503,7 @@ errorProcessor(XML_Parser parser,
const char *UNUSED_P(end),
const char **UNUSED_P(nextPtr))
{
- return errorCode;
+ return parser->m_errorCode;
}
static enum XML_Error
@@ -5293,7 +5527,7 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
const char *ptr, const char *end,
STRING_POOL *pool)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
for (;;) {
const char *next;
int tok = XmlAttributeValueTok(enc, ptr, end, &next);
@@ -5301,12 +5535,12 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
case XML_TOK_NONE:
return XML_ERROR_NONE;
case XML_TOK_INVALID:
- if (enc == encoding)
- eventPtr = next;
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = next;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_PARTIAL:
- if (enc == encoding)
- eventPtr = ptr;
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = ptr;
return XML_ERROR_INVALID_TOKEN;
case XML_TOK_CHAR_REF:
{
@@ -5314,8 +5548,8 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
int i;
int n = XmlCharRefNumber(enc, ptr);
if (n < 0) {
- if (enc == encoding)
- eventPtr = ptr;
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = ptr;
return XML_ERROR_BAD_CHAR_REF;
}
if (!isCdata
@@ -5323,11 +5557,15 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
&& (poolLength(pool) == 0 || poolLastChar(pool) == 0x20))
break;
n = XmlEncode(n, (ICHAR *)buf);
- if (!n) {
- if (enc == encoding)
- eventPtr = ptr;
- return XML_ERROR_BAD_CHAR_REF;
- }
+ /* The XmlEncode() functions can never return 0 here. That
+ * error return happens if the code point passed in is either
+ * negative or greater than or equal to 0x110000. The
+ * XmlCharRefNumber() functions will all return a number
+ * strictly less than 0x110000 or a negative value if an error
+ * occurred. The negative value is intercepted above, so
+ * XmlEncode() is never passed a value it might return an
+ * error for.
+ */
for (i = 0; i < n; i++) {
if (!poolAppendChar(pool, buf[i]))
return XML_ERROR_NO_MEMORY;
@@ -5361,25 +5599,25 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
return XML_ERROR_NO_MEMORY;
break;
}
- name = poolStoreString(&temp2Pool, enc,
+ name = poolStoreString(&parser->m_temp2Pool, enc,
ptr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!name)
return XML_ERROR_NO_MEMORY;
entity = (ENTITY *)lookup(parser, &dtd->generalEntities, name, 0);
- poolDiscard(&temp2Pool);
+ poolDiscard(&parser->m_temp2Pool);
/* First, determine if a check for an existing declaration is needed;
if yes, check that the entity exists, and that it is internal.
*/
if (pool == &dtd->pool) /* are we called from prolog? */
checkEntityDecl =
#ifdef XML_DTD
- prologState.documentEntity &&
+ parser->m_prologState.documentEntity &&
#endif /* XML_DTD */
(dtd->standalone
- ? !openInternalEntities
+ ? !parser->m_openInternalEntities
: !dtd->hasParamEntityRefs);
- else /* if (pool == &tempPool): we are called from content */
+ else /* if (pool == &parser->m_tempPool): we are called from content */
checkEntityDecl = !dtd->hasParamEntityRefs || dtd->standalone;
if (checkEntityDecl) {
if (!entity)
@@ -5389,37 +5627,55 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
}
else if (!entity) {
/* Cannot report skipped entity here - see comments on
- skippedEntityHandler.
- if (skippedEntityHandler)
- skippedEntityHandler(handlerArg, name, 0);
+ parser->m_skippedEntityHandler.
+ if (parser->m_skippedEntityHandler)
+ parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
*/
/* Cannot call the default handler because this would be
out of sync with the call to the startElementHandler.
- if ((pool == &tempPool) && defaultHandler)
+ if ((pool == &parser->m_tempPool) && parser->m_defaultHandler)
reportDefault(parser, enc, ptr, next);
*/
break;
}
if (entity->open) {
- if (enc == encoding)
- eventPtr = ptr;
+ if (enc == parser->m_encoding) {
+ /* It does not appear that this line can be executed.
+ *
+ * The "if (entity->open)" check catches recursive entity
+ * definitions. In order to be called with an open
+ * entity, it must have gone through this code before and
+ * been through the recursive call to
+ * appendAttributeValue() some lines below. That call
+ * sets the local encoding ("enc") to the parser's
+ * internal encoding (internal_utf8 or internal_utf16),
+ * which can never be the same as the principle encoding.
+ * It doesn't appear there is another code path that gets
+ * here with entity->open being TRUE.
+ *
+ * Since it is not certain that this logic is watertight,
+ * we keep the line and merely exclude it from coverage
+ * tests.
+ */
+ parser->m_eventPtr = ptr; /* LCOV_EXCL_LINE */
+ }
return XML_ERROR_RECURSIVE_ENTITY_REF;
}
if (entity->notation) {
- if (enc == encoding)
- eventPtr = ptr;
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = ptr;
return XML_ERROR_BINARY_ENTITY_REF;
}
if (!entity->textPtr) {
- if (enc == encoding)
- eventPtr = ptr;
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = ptr;
return XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF;
}
else {
enum XML_Error result;
const XML_Char *textEnd = entity->textPtr + entity->textLen;
entity->open = XML_TRUE;
- result = appendAttributeValue(parser, internalEncoding, isCdata,
+ result = appendAttributeValue(parser, parser->m_internalEncoding, isCdata,
(char *)entity->textPtr,
(char *)textEnd, pool);
entity->open = XML_FALSE;
@@ -5429,9 +5685,21 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
}
break;
default:
- if (enc == encoding)
- eventPtr = ptr;
+ /* The only token returned by XmlAttributeValueTok() that does
+ * not have an explicit case here is XML_TOK_PARTIAL_CHAR.
+ * Getting that would require an entity name to contain an
+ * incomplete XML character (e.g. \xE2\x82); however previous
+ * tokenisers will have already recognised and rejected such
+ * names before XmlAttributeValueTok() gets a look-in. This
+ * default case should be retained as a safety net, but the code
+ * excluded from coverage tests.
+ *
+ * LCOV_EXCL_START
+ */
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = ptr;
return XML_ERROR_UNEXPECTED_STATE;
+ /* LCOV_EXCL_STOP */
}
ptr = next;
}
@@ -5444,12 +5712,12 @@ storeEntityValue(XML_Parser parser,
const char *entityTextPtr,
const char *entityTextEnd)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
STRING_POOL *pool = &(dtd->entityValuePool);
enum XML_Error result = XML_ERROR_NONE;
#ifdef XML_DTD
- int oldInEntityValue = prologState.inEntityValue;
- prologState.inEntityValue = 1;
+ int oldInEntityValue = parser->m_prologState.inEntityValue;
+ parser->m_prologState.inEntityValue = 1;
#endif /* XML_DTD */
/* never return Null for the value argument in EntityDeclHandler,
since this would indicate an external entity; therefore we
@@ -5465,10 +5733,10 @@ storeEntityValue(XML_Parser parser,
switch (tok) {
case XML_TOK_PARAM_ENTITY_REF:
#ifdef XML_DTD
- if (isParamEntity || enc != encoding) {
+ if (parser->m_isParamEntity || enc != parser->m_encoding) {
const XML_Char *name;
ENTITY *entity;
- name = poolStoreString(&tempPool, enc,
+ name = poolStoreString(&parser->m_tempPool, enc,
entityTextPtr + enc->minBytesPerChar,
next - enc->minBytesPerChar);
if (!name) {
@@ -5476,28 +5744,28 @@ storeEntityValue(XML_Parser parser,
goto endEntityValue;
}
entity = (ENTITY *)lookup(parser, &dtd->paramEntities, name, 0);
- poolDiscard(&tempPool);
+ poolDiscard(&parser->m_tempPool);
if (!entity) {
/* not a well-formedness error - see XML 1.0: WFC Entity Declared */
/* cannot report skipped entity here - see comments on
- skippedEntityHandler
- if (skippedEntityHandler)
- skippedEntityHandler(handlerArg, name, 0);
+ parser->m_skippedEntityHandler
+ if (parser->m_skippedEntityHandler)
+ parser->m_skippedEntityHandler(parser->m_handlerArg, name, 0);
*/
dtd->keepProcessing = dtd->standalone;
goto endEntityValue;
}
if (entity->open) {
- if (enc == encoding)
- eventPtr = entityTextPtr;
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_RECURSIVE_ENTITY_REF;
goto endEntityValue;
}
if (entity->systemId) {
- if (externalEntityRefHandler) {
+ if (parser->m_externalEntityRefHandler) {
dtd->paramEntityRead = XML_FALSE;
entity->open = XML_TRUE;
- if (!externalEntityRefHandler(externalEntityRefHandlerArg,
+ if (!parser->m_externalEntityRefHandler(parser->m_externalEntityRefHandlerArg,
0,
entity->base,
entity->systemId,
@@ -5516,7 +5784,7 @@ storeEntityValue(XML_Parser parser,
else {
entity->open = XML_TRUE;
result = storeEntityValue(parser,
- internalEncoding,
+ parser->m_internalEncoding,
(char *)entity->textPtr,
(char *)(entity->textPtr
+ entity->textLen));
@@ -5529,7 +5797,7 @@ storeEntityValue(XML_Parser parser,
#endif /* XML_DTD */
/* In the internal subset, PE references are not legal
within markup declarations, e.g entity values in this case. */
- eventPtr = entityTextPtr;
+ parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_PARAM_ENTITY_REF;
goto endEntityValue;
case XML_TOK_NONE:
@@ -5558,18 +5826,21 @@ storeEntityValue(XML_Parser parser,
int i;
int n = XmlCharRefNumber(enc, entityTextPtr);
if (n < 0) {
- if (enc == encoding)
- eventPtr = entityTextPtr;
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_BAD_CHAR_REF;
goto endEntityValue;
}
n = XmlEncode(n, (ICHAR *)buf);
- if (!n) {
- if (enc == encoding)
- eventPtr = entityTextPtr;
- result = XML_ERROR_BAD_CHAR_REF;
- goto endEntityValue;
- }
+ /* The XmlEncode() functions can never return 0 here. That
+ * error return happens if the code point passed in is either
+ * negative or greater than or equal to 0x110000. The
+ * XmlCharRefNumber() functions will all return a number
+ * strictly less than 0x110000 or a negative value if an error
+ * occurred. The negative value is intercepted above, so
+ * XmlEncode() is never passed a value it might return an
+ * error for.
+ */
for (i = 0; i < n; i++) {
if (pool->end == pool->ptr && !poolGrow(pool)) {
result = XML_ERROR_NO_MEMORY;
@@ -5580,26 +5851,34 @@ storeEntityValue(XML_Parser parser,
}
break;
case XML_TOK_PARTIAL:
- if (enc == encoding)
- eventPtr = entityTextPtr;
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_INVALID_TOKEN;
goto endEntityValue;
case XML_TOK_INVALID:
- if (enc == encoding)
- eventPtr = next;
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = next;
result = XML_ERROR_INVALID_TOKEN;
goto endEntityValue;
default:
- if (enc == encoding)
- eventPtr = entityTextPtr;
+ /* This default case should be unnecessary -- all the tokens
+ * that XmlEntityValueTok() can return have their own explicit
+ * cases -- but should be retained for safety. We do however
+ * exclude it from the coverage statistics.
+ *
+ * LCOV_EXCL_START
+ */
+ if (enc == parser->m_encoding)
+ parser->m_eventPtr = entityTextPtr;
result = XML_ERROR_UNEXPECTED_STATE;
goto endEntityValue;
+ /* LCOV_EXCL_STOP */
}
entityTextPtr = next;
}
endEntityValue:
#ifdef XML_DTD
- prologState.inEntityValue = oldInEntityValue;
+ parser->m_prologState.inEntityValue = oldInEntityValue;
#endif /* XML_DTD */
return result;
}
@@ -5634,25 +5913,25 @@ reportProcessingInstruction(XML_Parser parser, const ENCODING *enc,
const XML_Char *target;
XML_Char *data;
const char *tem;
- if (!processingInstructionHandler) {
- if (defaultHandler)
+ if (!parser->m_processingInstructionHandler) {
+ if (parser->m_defaultHandler)
reportDefault(parser, enc, start, end);
return 1;
}
start += enc->minBytesPerChar * 2;
tem = start + XmlNameLength(enc, start);
- target = poolStoreString(&tempPool, enc, start, tem);
+ target = poolStoreString(&parser->m_tempPool, enc, start, tem);
if (!target)
return 0;
- poolFinish(&tempPool);
- data = poolStoreString(&tempPool, enc,
+ poolFinish(&parser->m_tempPool);
+ data = poolStoreString(&parser->m_tempPool, enc,
XmlSkipS(enc, tem),
end - enc->minBytesPerChar*2);
if (!data)
return 0;
normalizeLines(data);
- processingInstructionHandler(handlerArg, target, data);
- poolClear(&tempPool);
+ parser->m_processingInstructionHandler(parser->m_handlerArg, target, data);
+ poolClear(&parser->m_tempPool);
return 1;
}
@@ -5661,20 +5940,20 @@ reportComment(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end)
{
XML_Char *data;
- if (!commentHandler) {
- if (defaultHandler)
+ if (!parser->m_commentHandler) {
+ if (parser->m_defaultHandler)
reportDefault(parser, enc, start, end);
return 1;
}
- data = poolStoreString(&tempPool,
+ data = poolStoreString(&parser->m_tempPool,
enc,
start + enc->minBytesPerChar * 4,
end - enc->minBytesPerChar * 3);
if (!data)
return 0;
normalizeLines(data);
- commentHandler(handlerArg, data);
- poolClear(&tempPool);
+ parser->m_commentHandler(parser->m_handlerArg, data);
+ poolClear(&parser->m_tempPool);
return 1;
}
@@ -5686,24 +5965,41 @@ reportDefault(XML_Parser parser, const ENCODING *enc,
enum XML_Convert_Result convert_res;
const char **eventPP;
const char **eventEndPP;
- if (enc == encoding) {
- eventPP = &eventPtr;
- eventEndPP = &eventEndPtr;
+ if (enc == parser->m_encoding) {
+ eventPP = &parser->m_eventPtr;
+ eventEndPP = &parser->m_eventEndPtr;
}
else {
- eventPP = &(openInternalEntities->internalEventPtr);
- eventEndPP = &(openInternalEntities->internalEventEndPtr);
+ /* To get here, two things must be true; the parser must be
+ * using a character encoding that is not the same as the
+ * encoding passed in, and the encoding passed in must need
+ * conversion to the internal format (UTF-8 unless XML_UNICODE
+ * is defined). The only occasions on which the encoding passed
+ * in is not the same as the parser's encoding are when it is
+ * the internal encoding (e.g. a previously defined parameter
+ * entity, already converted to internal format). This by
+ * definition doesn't need conversion, so the whole branch never
+ * gets executed.
+ *
+ * For safety's sake we don't delete these lines and merely
+ * exclude them from coverage statistics.
+ *
+ * LCOV_EXCL_START
+ */
+ eventPP = &(parser->m_openInternalEntities->internalEventPtr);
+ eventEndPP = &(parser->m_openInternalEntities->internalEventEndPtr);
+ /* LCOV_EXCL_STOP */
}
do {
- ICHAR *dataPtr = (ICHAR *)dataBuf;
- convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)dataBufEnd);
+ ICHAR *dataPtr = (ICHAR *)parser->m_dataBuf;
+ convert_res = XmlConvert(enc, &s, end, &dataPtr, (ICHAR *)parser->m_dataBufEnd);
*eventEndPP = s;
- defaultHandler(handlerArg, dataBuf, (int)(dataPtr - (ICHAR *)dataBuf));
+ parser->m_defaultHandler(parser->m_handlerArg, parser->m_dataBuf, (int)(dataPtr - (ICHAR *)parser->m_dataBuf));
*eventPP = s;
} while ((convert_res != XML_CONVERT_COMPLETED) && (convert_res != XML_CONVERT_INPUT_INCOMPLETE));
}
else
- defaultHandler(handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s));
+ parser->m_defaultHandler(parser->m_handlerArg, (XML_Char *)s, (int)((XML_Char *)end - (XML_Char *)s));
}
@@ -5725,16 +6021,18 @@ defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
if (type->nDefaultAtts == type->allocDefaultAtts) {
if (type->allocDefaultAtts == 0) {
type->allocDefaultAtts = 8;
- type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(type->allocDefaultAtts
+ type->defaultAtts = (DEFAULT_ATTRIBUTE *)MALLOC(parser, type->allocDefaultAtts
* sizeof(DEFAULT_ATTRIBUTE));
- if (!type->defaultAtts)
+ if (!type->defaultAtts) {
+ type->allocDefaultAtts = 0;
return 0;
+ }
}
else {
DEFAULT_ATTRIBUTE *temp;
int count = type->allocDefaultAtts * 2;
temp = (DEFAULT_ATTRIBUTE *)
- REALLOC(type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE)));
+ REALLOC(parser, type->defaultAtts, (count * sizeof(DEFAULT_ATTRIBUTE)));
if (temp == NULL)
return 0;
type->allocDefaultAtts = count;
@@ -5754,7 +6052,7 @@ defineAttribute(ELEMENT_TYPE *type, ATTRIBUTE_ID *attId, XML_Bool isCdata,
static int
setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name;
for (name = elementType->name; *name; name++) {
if (*name == XML_T(ASCII_COLON)) {
@@ -5775,7 +6073,7 @@ setElementTypePrefix(XML_Parser parser, ELEMENT_TYPE *elementType)
else
poolDiscard(&dtd->pool);
elementType->prefix = prefix;
-
+ break;
}
}
return 1;
@@ -5785,7 +6083,7 @@ static ATTRIBUTE_ID *
getAttributeId(XML_Parser parser, const ENCODING *enc,
const char *start, const char *end)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
ATTRIBUTE_ID *id;
const XML_Char *name;
if (!poolAppendChar(&dtd->pool, XML_T('\0')))
@@ -5802,7 +6100,7 @@ getAttributeId(XML_Parser parser, const ENCODING *enc,
poolDiscard(&dtd->pool);
else {
poolFinish(&dtd->pool);
- if (!ns)
+ if (!parser->m_ns)
;
else if (name[0] == XML_T(ASCII_x)
&& name[1] == XML_T(ASCII_m)
@@ -5849,21 +6147,42 @@ getAttributeId(XML_Parser parser, const ENCODING *enc,
static const XML_Char *
getContext(XML_Parser parser)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
HASH_TABLE_ITER iter;
XML_Bool needSep = XML_FALSE;
if (dtd->defaultPrefix.binding) {
int i;
int len;
- if (!poolAppendChar(&tempPool, XML_T(ASCII_EQUALS)))
+ if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
return NULL;
len = dtd->defaultPrefix.binding->uriLen;
- if (namespaceSeparator)
+ if (parser->m_namespaceSeparator)
len--;
- for (i = 0; i < len; i++)
- if (!poolAppendChar(&tempPool, dtd->defaultPrefix.binding->uri[i]))
- return NULL;
+ for (i = 0; i < len; i++) {
+ if (!poolAppendChar(&parser->m_tempPool, dtd->defaultPrefix.binding->uri[i])) {
+ /* Because of memory caching, I don't believe this line can be
+ * executed.
+ *
+ * This is part of a loop copying the default prefix binding
+ * URI into the parser's temporary string pool. Previously,
+ * that URI was copied into the same string pool, with a
+ * terminating NUL character, as part of setContext(). When
+ * the pool was cleared, that leaves a block definitely big
+ * enough to hold the URI on the free block list of the pool.
+ * The URI copy in getContext() therefore cannot run out of
+ * memory.
+ *
+ * If the pool is used between the setContext() and
+ * getContext() calls, the worst it can do is leave a bigger
+ * block on the front of the free list. Given that this is
+ * all somewhat inobvious and program logic can be changed, we
+ * don't delete the line but we do exclude it from the test
+ * coverage statistics.
+ */
+ return NULL; /* LCOV_EXCL_LINE */
+ }
+ }
needSep = XML_TRUE;
}
@@ -5875,20 +6194,27 @@ getContext(XML_Parser parser)
PREFIX *prefix = (PREFIX *)hashTableIterNext(&iter);
if (!prefix)
break;
- if (!prefix->binding)
- continue;
- if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP))
+ if (!prefix->binding) {
+ /* This test appears to be (justifiable) paranoia. There does
+ * not seem to be a way of injecting a prefix without a binding
+ * that doesn't get errored long before this function is called.
+ * The test should remain for safety's sake, so we instead
+ * exclude the following line from the coverage statistics.
+ */
+ continue; /* LCOV_EXCL_LINE */
+ }
+ if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
return NULL;
for (s = prefix->name; *s; s++)
- if (!poolAppendChar(&tempPool, *s))
+ if (!poolAppendChar(&parser->m_tempPool, *s))
return NULL;
- if (!poolAppendChar(&tempPool, XML_T(ASCII_EQUALS)))
+ if (!poolAppendChar(&parser->m_tempPool, XML_T(ASCII_EQUALS)))
return NULL;
len = prefix->binding->uriLen;
- if (namespaceSeparator)
+ if (parser->m_namespaceSeparator)
len--;
for (i = 0; i < len; i++)
- if (!poolAppendChar(&tempPool, prefix->binding->uri[i]))
+ if (!poolAppendChar(&parser->m_tempPool, prefix->binding->uri[i]))
return NULL;
needSep = XML_TRUE;
}
@@ -5902,73 +6228,73 @@ getContext(XML_Parser parser)
break;
if (!e->open)
continue;
- if (needSep && !poolAppendChar(&tempPool, CONTEXT_SEP))
+ if (needSep && !poolAppendChar(&parser->m_tempPool, CONTEXT_SEP))
return NULL;
for (s = e->name; *s; s++)
- if (!poolAppendChar(&tempPool, *s))
+ if (!poolAppendChar(&parser->m_tempPool, *s))
return 0;
needSep = XML_TRUE;
}
- if (!poolAppendChar(&tempPool, XML_T('\0')))
+ if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return NULL;
- return tempPool.start;
+ return parser->m_tempPool.start;
}
static XML_Bool
setContext(XML_Parser parser, const XML_Char *context)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *s = context;
while (*context != XML_T('\0')) {
if (*s == CONTEXT_SEP || *s == XML_T('\0')) {
ENTITY *e;
- if (!poolAppendChar(&tempPool, XML_T('\0')))
+ if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
- e = (ENTITY *)lookup(parser, &dtd->generalEntities, poolStart(&tempPool), 0);
+ e = (ENTITY *)lookup(parser, &dtd->generalEntities, poolStart(&parser->m_tempPool), 0);
if (e)
e->open = XML_TRUE;
if (*s != XML_T('\0'))
s++;
context = s;
- poolDiscard(&tempPool);
+ poolDiscard(&parser->m_tempPool);
}
else if (*s == XML_T(ASCII_EQUALS)) {
PREFIX *prefix;
- if (poolLength(&tempPool) == 0)
+ if (poolLength(&parser->m_tempPool) == 0)
prefix = &dtd->defaultPrefix;
else {
- if (!poolAppendChar(&tempPool, XML_T('\0')))
+ if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
- prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&tempPool),
+ prefix = (PREFIX *)lookup(parser, &dtd->prefixes, poolStart(&parser->m_tempPool),
sizeof(PREFIX));
if (!prefix)
return XML_FALSE;
- if (prefix->name == poolStart(&tempPool)) {
+ if (prefix->name == poolStart(&parser->m_tempPool)) {
prefix->name = poolCopyString(&dtd->pool, prefix->name);
if (!prefix->name)
return XML_FALSE;
}
- poolDiscard(&tempPool);
+ poolDiscard(&parser->m_tempPool);
}
for (context = s + 1;
*context != CONTEXT_SEP && *context != XML_T('\0');
context++)
- if (!poolAppendChar(&tempPool, *context))
+ if (!poolAppendChar(&parser->m_tempPool, *context))
return XML_FALSE;
- if (!poolAppendChar(&tempPool, XML_T('\0')))
+ if (!poolAppendChar(&parser->m_tempPool, XML_T('\0')))
return XML_FALSE;
- if (addBinding(parser, prefix, NULL, poolStart(&tempPool),
- &inheritedBindings) != XML_ERROR_NONE)
+ if (addBinding(parser, prefix, NULL, poolStart(&parser->m_tempPool),
+ &parser->m_inheritedBindings) != XML_ERROR_NONE)
return XML_FALSE;
- poolDiscard(&tempPool);
+ poolDiscard(&parser->m_tempPool);
if (*context != XML_T('\0'))
++context;
s = context;
}
else {
- if (!poolAppendChar(&tempPool, *s))
+ if (!poolAppendChar(&parser->m_tempPool, *s))
return XML_FALSE;
s++;
}
@@ -6333,7 +6659,6 @@ hash(XML_Parser parser, KEY s)
{
struct siphash state;
struct sipkey key;
- (void)sip_tobin;
(void)sip24_valid;
copy_salt_to_sipkey(parser, &key);
sip24_init(&state, &key);
@@ -6547,8 +6872,20 @@ poolCopyString(STRING_POOL *pool, const XML_Char *s)
static const XML_Char *
poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n)
{
- if (!pool->ptr && !poolGrow(pool))
- return NULL;
+ if (!pool->ptr && !poolGrow(pool)) {
+ /* The following line is unreachable given the current usage of
+ * poolCopyStringN(). Currently it is called from exactly one
+ * place to copy the text of a simple general entity. By that
+ * point, the name of the entity is already stored in the pool, so
+ * pool->ptr cannot be NULL.
+ *
+ * If poolCopyStringN() is used elsewhere as it well might be,
+ * this line may well become executable again. Regardless, this
+ * sort of check shouldn't be removed lightly, so we just exclude
+ * it from the coverage statistics.
+ */
+ return NULL; /* LCOV_EXCL_LINE */
+ }
for (; n > 0; --n, s++) {
if (!poolAppendChar(pool, *s))
return NULL;
@@ -6641,8 +6978,19 @@ poolGrow(STRING_POOL *pool)
int blockSize = (int)((unsigned)(pool->end - pool->start)*2U);
size_t bytesToAllocate;
- if (blockSize < 0)
- return XML_FALSE;
+ /* NOTE: Needs to be calculated prior to calling `realloc`
+ to avoid dangling pointers: */
+ const ptrdiff_t offsetInsideBlock = pool->ptr - pool->start;
+
+ if (blockSize < 0) {
+ /* This condition traps a situation where either more than
+ * INT_MAX/2 bytes have already been allocated. This isn't
+ * readily testable, since it is unlikely that an average
+ * machine will have that much memory, so we exclude it from the
+ * coverage statistics.
+ */
+ return XML_FALSE; /* LCOV_EXCL_LINE */
+ }
bytesToAllocate = poolBytesToAllocateFor(blockSize);
if (bytesToAllocate == 0)
@@ -6654,7 +7002,7 @@ poolGrow(STRING_POOL *pool)
return XML_FALSE;
pool->blocks = temp;
pool->blocks->size = blockSize;
- pool->ptr = pool->blocks->s + (pool->ptr - pool->start);
+ pool->ptr = pool->blocks->s + offsetInsideBlock;
pool->start = pool->blocks->s;
pool->end = pool->start + blockSize;
}
@@ -6663,8 +7011,18 @@ poolGrow(STRING_POOL *pool)
int blockSize = (int)(pool->end - pool->start);
size_t bytesToAllocate;
- if (blockSize < 0)
- return XML_FALSE;
+ if (blockSize < 0) {
+ /* This condition traps a situation where either more than
+ * INT_MAX bytes have already been allocated (which is prevented
+ * by various pieces of program logic, not least this one, never
+ * mind the unlikelihood of actually having that much memory) or
+ * the pool control fields have been corrupted (which could
+ * conceivably happen in an extremely buggy user handler
+ * function). Either way it isn't readily testable, so we
+ * exclude it from the coverage statistics.
+ */
+ return XML_FALSE; /* LCOV_EXCL_LINE */
+ }
if (blockSize < INIT_BLOCK_SIZE)
blockSize = INIT_BLOCK_SIZE;
@@ -6699,12 +7057,12 @@ poolGrow(STRING_POOL *pool)
static int FASTCALL
nextScaffoldPart(XML_Parser parser)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
CONTENT_SCAFFOLD * me;
int next;
if (!dtd->scaffIndex) {
- dtd->scaffIndex = (int *)MALLOC(groupSize * sizeof(int));
+ dtd->scaffIndex = (int *)MALLOC(parser, parser->m_groupSize * sizeof(int));
if (!dtd->scaffIndex)
return -1;
dtd->scaffIndex[0] = 0;
@@ -6714,13 +7072,13 @@ nextScaffoldPart(XML_Parser parser)
CONTENT_SCAFFOLD *temp;
if (dtd->scaffold) {
temp = (CONTENT_SCAFFOLD *)
- REALLOC(dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
+ REALLOC(parser, dtd->scaffold, dtd->scaffSize * 2 * sizeof(CONTENT_SCAFFOLD));
if (temp == NULL)
return -1;
dtd->scaffSize *= 2;
}
else {
- temp = (CONTENT_SCAFFOLD *)MALLOC(INIT_SCAFFOLD_ELEMENTS
+ temp = (CONTENT_SCAFFOLD *)MALLOC(parser, INIT_SCAFFOLD_ELEMENTS
* sizeof(CONTENT_SCAFFOLD));
if (temp == NULL)
return -1;
@@ -6751,7 +7109,7 @@ build_node(XML_Parser parser,
XML_Content **contpos,
XML_Char **strpos)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
dest->type = dtd->scaffold[src_node].type;
dest->quant = dtd->scaffold[src_node].quant;
if (dest->type == XML_CTYPE_NAME) {
@@ -6785,14 +7143,14 @@ build_node(XML_Parser parser,
static XML_Content *
build_model (XML_Parser parser)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
XML_Content *ret;
XML_Content *cpos;
XML_Char * str;
int allocsize = (dtd->scaffCount * sizeof(XML_Content)
+ (dtd->contentStringLen * sizeof(XML_Char)));
- ret = (XML_Content *)MALLOC(allocsize);
+ ret = (XML_Content *)MALLOC(parser, allocsize);
if (!ret)
return NULL;
@@ -6809,7 +7167,7 @@ getElementType(XML_Parser parser,
const char *ptr,
const char *end)
{
- DTD * const dtd = _dtd; /* save one level of indirection */
+ DTD * const dtd = parser->m_dtd; /* save one level of indirection */
const XML_Char *name = poolStoreString(&dtd->pool, enc, ptr, end);
ELEMENT_TYPE *ret;
@@ -6827,3 +7185,26 @@ getElementType(XML_Parser parser,
}
return ret;
}
+
+static XML_Char *
+copyString(const XML_Char *s,
+ const XML_Memory_Handling_Suite *memsuite)
+{
+ int charsRequired = 0;
+ XML_Char *result;
+
+ /* First determine how long the string is */
+ while (s[charsRequired] != 0) {
+ charsRequired++;
+ }
+ /* Include the terminator */
+ charsRequired++;
+
+ /* Now allocate space for the copy */
+ result = memsuite->malloc_fcn(charsRequired * sizeof(XML_Char));
+ if (result == NULL)
+ return NULL;
+ /* Copy the original into place */
+ memcpy(result, s, charsRequired * sizeof(XML_Char));
+ return result;
+}
diff --git a/3rdParty/Expat/src/xmlrole.c b/3rdParty/Expat/src/xmlrole.c
index a7c5630..708507d 100644
--- a/3rdParty/Expat/src/xmlrole.c
+++ b/3rdParty/Expat/src/xmlrole.c
@@ -1,5 +1,33 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stddef.h>
@@ -170,7 +198,14 @@ prolog1(PROLOG_STATE *state,
case XML_TOK_COMMENT:
return XML_ROLE_COMMENT;
case XML_TOK_BOM:
- return XML_ROLE_NONE;
+ /* This case can never arise. To reach this role function, the
+ * parse must have passed through prolog0 and therefore have had
+ * some form of input, even if only a space. At that point, a
+ * byte order mark is no longer a valid character (though
+ * technically it should be interpreted as a non-breaking space),
+ * so will be rejected by the tokenizing stages.
+ */
+ return XML_ROLE_NONE; /* LCOV_EXCL_LINE */
case XML_TOK_DECL_OPEN:
if (!XmlNameMatchesAscii(enc,
ptr + 2 * MIN_BYTES_PER_CHAR(enc),
@@ -1285,6 +1320,26 @@ declClose(PROLOG_STATE *state,
return common(state, tok);
}
+/* This function will only be invoked if the internal logic of the
+ * parser has broken down. It is used in two cases:
+ *
+ * 1: When the XML prolog has been finished. At this point the
+ * processor (the parser level above these role handlers) should
+ * switch from prologProcessor to contentProcessor and reinitialise
+ * the handler function.
+ *
+ * 2: When an error has been detected (via common() below). At this
+ * point again the processor should be switched to errorProcessor,
+ * which will never call a handler.
+ *
+ * The result of this is that error() can only be called if the
+ * processor switch failed to happen, which is an internal error and
+ * therefore we shouldn't be able to provoke it simply by using the
+ * library. It is a necessary backstop, however, so we merely exclude
+ * it from the coverage statistics.
+ *
+ * LCOV_EXCL_START
+ */
static int PTRCALL
error(PROLOG_STATE *UNUSED_P(state),
int UNUSED_P(tok),
@@ -1294,6 +1349,7 @@ error(PROLOG_STATE *UNUSED_P(state),
{
return XML_ROLE_NONE;
}
+/* LCOV_EXCL_STOP */
static int FASTCALL
common(PROLOG_STATE *state, int tok)
diff --git a/3rdParty/Expat/src/xmlrole.h b/3rdParty/Expat/src/xmlrole.h
index 4dd9f06..e5f048e 100644
--- a/3rdParty/Expat/src/xmlrole.h
+++ b/3rdParty/Expat/src/xmlrole.h
@@ -1,5 +1,33 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef XmlRole_INCLUDED
diff --git a/3rdParty/Expat/src/xmltok.c b/3rdParty/Expat/src/xmltok.c
index cdf0720..6b415d8 100644
--- a/3rdParty/Expat/src/xmltok.c
+++ b/3rdParty/Expat/src/xmltok.c
@@ -1,8 +1,47 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stddef.h>
+#include <string.h> /* memcpy */
+
+#if defined(_MSC_VER) && (_MSC_VER <= 1700)
+ /* for vs2012/11.0/1700 and earlier Visual Studio compilers */
+# define bool int
+# define false 0
+# define true 1
+#else
+# include <stdbool.h>
+#endif
+
#ifdef _WIN32
#include "winconfig.h"
@@ -27,7 +66,6 @@
{ PREFIX(prologTok), PREFIX(contentTok), \
PREFIX(cdataSectionTok) IGNORE_SECTION_TOK_VTABLE }, \
{ PREFIX(attributeValueTok), PREFIX(entityValueTok) }, \
- PREFIX(sameName), \
PREFIX(nameMatchesAscii), \
PREFIX(nameLength), \
PREFIX(skipS), \
@@ -324,7 +362,7 @@ enum { /* UTF8_cvalN is value of masked first byte of N byte sequence */
};
void
-align_limit_to_full_utf8_characters(const char * from, const char ** fromLimRef)
+_INTERNAL_trim_to_complete_utf8_characters(const char * from, const char ** fromLimRef)
{
const char * fromLim = *fromLimRef;
size_t walked = 0;
@@ -363,22 +401,37 @@ utf8_toUtf8(const ENCODING *UNUSED_P(enc),
const char **fromP, const char *fromLim,
char **toP, const char *toLim)
{
- char *to;
- const char *from;
- const char *fromLimInitial = fromLim;
+ bool input_incomplete = false;
+ bool output_exhausted = false;
+
+ /* Avoid copying partial characters (due to limited space). */
+ const ptrdiff_t bytesAvailable = fromLim - *fromP;
+ const ptrdiff_t bytesStorable = toLim - *toP;
+ if (bytesAvailable > bytesStorable) {
+ fromLim = *fromP + bytesStorable;
+ output_exhausted = true;
+ }
- /* Avoid copying partial characters. */
- align_limit_to_full_utf8_characters(*fromP, &fromLim);
+ /* Avoid copying partial characters (from incomplete input). */
+ {
+ const char * const fromLimBefore = fromLim;
+ _INTERNAL_trim_to_complete_utf8_characters(*fromP, &fromLim);
+ if (fromLim < fromLimBefore) {
+ input_incomplete = true;
+ }
+ }
- for (to = *toP, from = *fromP; (from < fromLim) && (to < toLim); from++, to++)
- *to = *from;
- *fromP = from;
- *toP = to;
+ {
+ const ptrdiff_t bytesToCopy = fromLim - *fromP;
+ memcpy(*toP, *fromP, bytesToCopy);
+ *fromP += bytesToCopy;
+ *toP += bytesToCopy;
+ }
- if (fromLim < fromLimInitial)
- return XML_CONVERT_INPUT_INCOMPLETE;
- else if ((to == toLim) && (from < fromLim))
+ if (output_exhausted) /* needs to go first */
return XML_CONVERT_OUTPUT_EXHAUSTED;
+ else if (input_incomplete)
+ return XML_CONVERT_INPUT_INCOMPLETE;
else
return XML_CONVERT_COMPLETED;
}
@@ -1019,7 +1072,11 @@ streqci(const char *s1, const char *s2)
if (ASCII_a <= c1 && c1 <= ASCII_z)
c1 += ASCII_A - ASCII_a;
if (ASCII_a <= c2 && c2 <= ASCII_z)
- c2 += ASCII_A - ASCII_a;
+ /* The following line will never get executed. streqci() is
+ * only called from two places, both of which guarantee to put
+ * upper-case strings into s2.
+ */
+ c2 += ASCII_A - ASCII_a; /* LCOV_EXCL_LINE */
if (c1 != c2)
return 0;
if (!c1)
@@ -1291,7 +1348,7 @@ XmlUtf8Encode(int c, char *buf)
};
if (c < 0)
- return 0;
+ return 0; /* LCOV_EXCL_LINE: this case is always eliminated beforehand */
if (c < min2) {
buf[0] = (char)(c | UTF8_cval1);
return 1;
@@ -1314,7 +1371,7 @@ XmlUtf8Encode(int c, char *buf)
buf[3] = (char)((c & 0x3f) | 0x80);
return 4;
}
- return 0;
+ return 0; /* LCOV_EXCL_LINE: this case too is eliminated before calling */
}
int FASTCALL
@@ -1407,9 +1464,8 @@ unknown_toUtf8(const ENCODING *enc,
return XML_CONVERT_OUTPUT_EXHAUSTED;
(*fromP)++;
}
- do {
- *(*toP)++ = *utf8++;
- } while (--n != 0);
+ memcpy(*toP, utf8, n);
+ *toP += n;
}
}
@@ -1465,6 +1521,9 @@ XmlInitUnknownEncoding(void *mem,
else if (c < 0) {
if (c < -4)
return 0;
+ /* Multi-byte sequences need a converter function */
+ if (!convert)
+ return 0;
e->normal.type[i] = (unsigned char)(BT_LEAD2 - (c + 2));
e->utf8[i][0] = 0;
e->utf16[i] = 0;
diff --git a/3rdParty/Expat/src/xmltok.h b/3rdParty/Expat/src/xmltok.h
index 752007e..50926f3 100644
--- a/3rdParty/Expat/src/xmltok.h
+++ b/3rdParty/Expat/src/xmltok.h
@@ -1,5 +1,33 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/*
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef XmlTok_INCLUDED
@@ -139,9 +167,6 @@ enum XML_Convert_Result {
struct encoding {
SCANNER scanners[XML_N_STATES];
SCANNER literalScanners[XML_N_LITERAL_TYPES];
- int (PTRCALL *sameName)(const ENCODING *,
- const char *,
- const char *);
int (PTRCALL *nameMatchesAscii)(const ENCODING *,
const char *,
const char *,
@@ -232,8 +257,6 @@ struct encoding {
#define XmlEntityValueTok(enc, ptr, end, nextTokPtr) \
XmlLiteralTok(enc, XML_ENTITY_VALUE_LITERAL, ptr, end, nextTokPtr)
-#define XmlSameName(enc, ptr1, ptr2) (((enc)->sameName)(enc, ptr1, ptr2))
-
#define XmlNameMatchesAscii(enc, ptr1, end1, ptr2) \
(((enc)->nameMatchesAscii)(enc, ptr1, end1, ptr2))
diff --git a/3rdParty/Expat/src/xmltok_impl.c b/3rdParty/Expat/src/xmltok_impl.c
index 5f779c0..4d9ae7d 100644
--- a/3rdParty/Expat/src/xmltok_impl.c
+++ b/3rdParty/Expat/src/xmltok_impl.c
@@ -1,8 +1,35 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/* This file is included!
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
-/* This file is included! */
#ifdef XML_TOK_IMPL_C
#ifndef IS_INVALID_CHAR
@@ -47,6 +74,7 @@
*nextTokPtr = ptr; \
return XML_TOK_INVALID; \
} \
+ /* fall through */ \
case BT_NMSTRT: \
case BT_HEX: \
case BT_DIGIT: \
@@ -75,6 +103,7 @@
*nextTokPtr = ptr; \
return XML_TOK_INVALID; \
} \
+ /* fall through */ \
case BT_NMSTRT: \
case BT_HEX: \
ptr += MINBPC(enc); \
@@ -575,7 +604,7 @@ PREFIX(scanAtts)(const ENCODING *enc, const char *ptr, const char *end,
return XML_TOK_INVALID;
}
}
- /* fall through */
+ /* fall through */
case BT_EQUALS:
{
int open;
@@ -1198,8 +1227,14 @@ PREFIX(attributeValueTok)(const ENCODING *enc, const char *ptr,
const char *start;
if (ptr >= end)
return XML_TOK_NONE;
- else if (! HAS_CHAR(enc, ptr, end))
- return XML_TOK_PARTIAL;
+ else if (! HAS_CHAR(enc, ptr, end)) {
+ /* This line cannot be executed. The incoming data has already
+ * been tokenized once, so incomplete characters like this have
+ * already been eliminated from the input. Retaining the paranoia
+ * check is still valuable, however.
+ */
+ return XML_TOK_PARTIAL; /* LCOV_EXCL_LINE */
+ }
start = ptr;
while (HAS_CHAR(enc, ptr, end)) {
switch (BYTE_TYPE(enc, ptr)) {
@@ -1258,8 +1293,14 @@ PREFIX(entityValueTok)(const ENCODING *enc, const char *ptr,
const char *start;
if (ptr >= end)
return XML_TOK_NONE;
- else if (! HAS_CHAR(enc, ptr, end))
- return XML_TOK_PARTIAL;
+ else if (! HAS_CHAR(enc, ptr, end)) {
+ /* This line cannot be executed. The incoming data has already
+ * been tokenized once, so incomplete characters like this have
+ * already been eliminated from the input. Retaining the paranoia
+ * check is still valuable, however.
+ */
+ return XML_TOK_PARTIAL; /* LCOV_EXCL_LINE */
+ }
start = ptr;
while (HAS_CHAR(enc, ptr, end)) {
switch (BYTE_TYPE(enc, ptr)) {
@@ -1403,6 +1444,7 @@ PREFIX(isPublicId)(const ENCODING *enc, const char *ptr, const char *end,
case BT_NMSTRT:
if (!(BYTE_TO_ASCII(enc, ptr) & ~0x7f))
break;
+ /* fall through */
default:
switch (BYTE_TO_ASCII(enc, ptr)) {
case 0x24: /* $ */
@@ -1615,76 +1657,18 @@ PREFIX(predefinedEntityName)(const ENCODING *UNUSED_P(enc), const char *ptr,
}
static int PTRCALL
-PREFIX(sameName)(const ENCODING *enc, const char *ptr1, const char *ptr2)
-{
- for (;;) {
- switch (BYTE_TYPE(enc, ptr1)) {
-#define LEAD_CASE(n) \
- case BT_LEAD ## n: \
- if (*ptr1++ != *ptr2++) \
- return 0;
- LEAD_CASE(4) LEAD_CASE(3) LEAD_CASE(2)
-#undef LEAD_CASE
- /* fall through */
- if (*ptr1++ != *ptr2++)
- return 0;
- break;
- case BT_NONASCII:
- case BT_NMSTRT:
-#ifdef XML_NS
- case BT_COLON:
-#endif
- case BT_HEX:
- case BT_DIGIT:
- case BT_NAME:
- case BT_MINUS:
- if (*ptr2++ != *ptr1++)
- return 0;
- if (MINBPC(enc) > 1) {
- if (*ptr2++ != *ptr1++)
- return 0;
- if (MINBPC(enc) > 2) {
- if (*ptr2++ != *ptr1++)
- return 0;
- if (MINBPC(enc) > 3) {
- if (*ptr2++ != *ptr1++)
- return 0;
- }
- }
- }
- break;
- default:
- if (MINBPC(enc) == 1 && *ptr1 == *ptr2)
- return 1;
- switch (BYTE_TYPE(enc, ptr2)) {
- case BT_LEAD2:
- case BT_LEAD3:
- case BT_LEAD4:
- case BT_NONASCII:
- case BT_NMSTRT:
-#ifdef XML_NS
- case BT_COLON:
-#endif
- case BT_HEX:
- case BT_DIGIT:
- case BT_NAME:
- case BT_MINUS:
- return 0;
- default:
- return 1;
- }
- }
- }
- /* not reached */
-}
-
-static int PTRCALL
PREFIX(nameMatchesAscii)(const ENCODING *UNUSED_P(enc), const char *ptr1,
const char *end1, const char *ptr2)
{
for (; *ptr2; ptr1 += MINBPC(enc), ptr2++) {
- if (end1 - ptr1 < MINBPC(enc))
- return 0;
+ if (end1 - ptr1 < MINBPC(enc)) {
+ /* This line cannot be executed. The incoming data has already
+ * been tokenized once, so incomplete characters like this have
+ * already been eliminated from the input. Retaining the
+ * paranoia check is still valuable, however.
+ */
+ return 0; /* LCOV_EXCL_LINE */
+ }
if (!CHAR_MATCHES(enc, ptr1, *ptr2))
return 0;
}
diff --git a/3rdParty/Expat/src/xmltok_impl.h b/3rdParty/Expat/src/xmltok_impl.h
index da0ea60..a6420f4 100644
--- a/3rdParty/Expat/src/xmltok_impl.h
+++ b/3rdParty/Expat/src/xmltok_impl.h
@@ -1,6 +1,33 @@
/*
-Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
-See the file COPYING for copying permission.
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
enum {
diff --git a/3rdParty/Expat/src/xmltok_ns.c b/3rdParty/Expat/src/xmltok_ns.c
index c3b88fd..23d31e8 100644
--- a/3rdParty/Expat/src/xmltok_ns.c
+++ b/3rdParty/Expat/src/xmltok_ns.c
@@ -1,8 +1,35 @@
-/* Copyright (c) 1998, 1999 Thai Open Source Software Center Ltd
- See the file COPYING for copying permission.
+/* This file is included!
+ __ __ _
+ ___\ \/ /_ __ __ _| |_
+ / _ \\ /| '_ \ / _` | __|
+ | __// \| |_) | (_| | |_
+ \___/_/\_\ .__/ \__,_|\__|
+ |_| XML parser
+
+ Copyright (c) 1997-2000 Thai Open Source Software Center Ltd
+ Copyright (c) 2000-2017 Expat development team
+ Licensed under the MIT license:
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to permit
+ persons to whom the Software is furnished to do so, subject to the
+ following conditions:
+
+ The above copyright notice and this permission notice shall be included
+ in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
-/* This file is included! */
#ifdef XML_TOK_NS_C
const ENCODING *
diff --git a/BuildTools/InstallSwiftDependencies.sh b/BuildTools/InstallSwiftDependencies.sh
index 378f141..438e395 100755
--- a/BuildTools/InstallSwiftDependencies.sh
+++ b/BuildTools/InstallSwiftDependencies.sh
@@ -4,14 +4,14 @@
SYSTEM_NAME=$(uname)
-if [ "$SYSTEM_NAME" == "Linux" ]
+if [ "$SYSTEM_NAME" == "Linux" ]
then
# handle linux distributions
SYSTEM_DISTRO=$(lsb_release -i -s)
if [ "$SYSTEM_DISTRO" == "Debian" ]
then
sudo apt-get install build-essential pkg-config libssl-dev qt5-default libqt5x11extras5-dev libqt5webkit5-dev qtmultimedia5-dev qttools5-dev-tools qt5-image-formats-plugins libqt5svg5-dev libminiupnpc-dev libnatpmp-dev libhunspell-dev
- elif [ "$SYSTEM_DISTRO" == "Ubuntu" ] || [ "$SYSTEM_DISTRO" == "LinuxMint" ]
+ elif [ "$SYSTEM_DISTRO" == "Ubuntu" ] || [ "$SYSTEM_DISTRO" == "LinuxMint" ] || [ "$SYSTEM_DISTRO" == "neon" ]
then
sudo apt-get install build-essential pkg-config libssl-dev qt5-default libqt5x11extras5-dev libqt5webkit5-dev qtmultimedia5-dev qttools5-dev-tools qt5-image-formats-plugins libqt5svg5-dev libminiupnpc-dev libnatpmp-dev libhunspell-dev
elif [ "$SYSTEM_DISTRO" == "Arch" ]
diff --git a/BuildTools/SCons/SConscript.boot b/BuildTools/SCons/SConscript.boot
index 411fb7d..7b29c06 100644
--- a/BuildTools/SCons/SConscript.boot
+++ b/BuildTools/SCons/SConscript.boot
@@ -132,6 +132,7 @@ env_ENV = {
'PATH' : os.environ['PATH'],
'LD_LIBRARY_PATH' : os.environ.get("LD_LIBRARY_PATH", ""),
'TERM' : os.environ.get("TERM", ""),
+ 'SDKROOT' : os.environ.get("SDKROOT", ""),
}
if "MSVC_VERSION" in ARGUMENTS :
diff --git a/QA/Checker/checker.cpp b/QA/Checker/checker.cpp
index f4ec6f1..4d6a90e 100644
--- a/QA/Checker/checker.cpp
+++ b/QA/Checker/checker.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.
*/
@@ -141,7 +141,7 @@ int main(int argc, char* argv[]) {
googleTestWasSuccessful = RUN_ALL_TESTS() == 0 ? true : false;
} catch (const ::testing::internal::GoogleTestFailureException& e) {
googleTestWasSuccessful = false;
- SWIFT_LOG(error) << "GoogleTestFailureException was thrown: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "GoogleTestFailureException was thrown: " << e.what();
}
auto cppUnitWasSuccessful = result.wasSuccessful() ? true : false;
diff --git a/Slimber/Server.cpp b/Slimber/Server.cpp
index bfa34f5..7bb2ed9 100644
--- a/Slimber/Server.cpp
+++ b/Slimber/Server.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.
*/
@@ -306,7 +306,7 @@ void Server::handleLinkLocalElementReceived(std::shared_ptr<ToplevelElement> ele
void Server::handleConnectFinished(std::shared_ptr<LinkLocalConnector> connector, bool error) {
if (error) {
- SWIFT_LOG(warning) << "Error connecting" << std::endl;
+ SWIFT_LOG(warning) << "Error connecting";
// TODO: Send back queued stanzas
}
else {
diff --git a/Sluift/ElementConvertors/DOMElementConvertor.cpp b/Sluift/ElementConvertors/DOMElementConvertor.cpp
index 56b45aa..5e72cc8 100644
--- a/Sluift/ElementConvertors/DOMElementConvertor.cpp
+++ b/Sluift/ElementConvertors/DOMElementConvertor.cpp
@@ -185,7 +185,7 @@ boost::optional<std::string> DOMElementConvertor::convertToLua(
// Parse the payload again
ParserClient parserClient(L);
- std::shared_ptr<XMLParser> parser(parsers.createXMLParser(&parserClient));
+ std::shared_ptr<XMLParser> parser(parsers.createXMLParser(&parserClient, false));
bool result = parser->parse(serializedPayload);
assert(result);
diff --git a/Sluift/ElementConvertors/DefaultElementConvertor.cpp b/Sluift/ElementConvertors/DefaultElementConvertor.cpp
index 75e6706..d3d60ff 100644
--- a/Sluift/ElementConvertors/DefaultElementConvertor.cpp
+++ b/Sluift/ElementConvertors/DefaultElementConvertor.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.
*/
@@ -20,7 +20,7 @@ DefaultElementConvertor::~DefaultElementConvertor() {
}
std::shared_ptr<Element> DefaultElementConvertor::convertFromLua(lua_State*, int, const std::string& type) {
- SWIFT_LOG(warning) << "Unable to convert type '" << type << "'" << std::endl;
+ SWIFT_LOG(warning) << "Unable to convert type '" << type << "'";
return std::shared_ptr<Element>();
}
diff --git a/SwifTools/Application/ApplicationPathProvider.cpp b/SwifTools/Application/ApplicationPathProvider.cpp
index 8b952bb..77457ef 100644
--- a/SwifTools/Application/ApplicationPathProvider.cpp
+++ b/SwifTools/Application/ApplicationPathProvider.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.
*/
@@ -25,7 +25,7 @@ boost::filesystem::path ApplicationPathProvider::getProfileDir(const std::string
boost::filesystem::create_directory(result);
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << e.what() << std::endl;
+ SWIFT_LOG(error) << e.what();
}
return result;
}
diff --git a/SwifTools/Application/MacOSXApplicationPathProvider.cpp b/SwifTools/Application/MacOSXApplicationPathProvider.cpp
index 684d8b2..d7b99b9 100644
--- a/SwifTools/Application/MacOSXApplicationPathProvider.cpp
+++ b/SwifTools/Application/MacOSXApplicationPathProvider.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 @@ boost::filesystem::path MacOSXApplicationPathProvider::getDataDir() const {
boost::filesystem::create_directory(result);
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << e.what() << std::endl;
+ SWIFT_LOG(error) << e.what();
}
return result;
}
diff --git a/SwifTools/Application/UnixApplicationPathProvider.cpp b/SwifTools/Application/UnixApplicationPathProvider.cpp
index e455d23..a345766 100644
--- a/SwifTools/Application/UnixApplicationPathProvider.cpp
+++ b/SwifTools/Application/UnixApplicationPathProvider.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.
*/
@@ -54,7 +54,7 @@ boost::filesystem::path UnixApplicationPathProvider::getDataDir() const {
boost::filesystem::create_directories(dataPath);
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << "file system error: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "file system error: " << e.what();
}
return dataPath;
}
diff --git a/SwifTools/AutoUpdater/SparkleAutoUpdater.mm b/SwifTools/AutoUpdater/SparkleAutoUpdater.mm
index b4a4c05..274ab3c 100644
--- a/SwifTools/AutoUpdater/SparkleAutoUpdater.mm
+++ b/SwifTools/AutoUpdater/SparkleAutoUpdater.mm
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2017 Isode Limited.
+ * Copyright (c) 2016-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -46,7 +46,7 @@ SparkleAutoUpdater::SparkleAutoUpdater(const std::string& appcastFeed) : d(new P
SWIFT_LOG(debug) << (canDoSilentUpdates ?
"The current running user has enough permissions to do a silent update." :
- "The current running user has insufficient permissions to do a silent update.") << std::endl;
+ "The current running user has insufficient permissions to do a silent update.");
setAppcastFeed(appcastFeed);
}
diff --git a/SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.mm b/SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.mm
index be58355..b9294d9 100644
--- a/SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.mm
+++ b/SwifTools/AutoUpdater/SparkleAutoUpdaterDelegate.mm
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016-2017 Isode Limited.
+ * Copyright (c) 2016-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -49,7 +49,7 @@ using namespace Swift;
- (void)updater:(SUUpdater *)updater failedToDownloadUpdate:(SUAppcastItem *)item error:(NSError *)error {
(void)updater;
(void)item;
- SWIFT_LOG(error) << ns2StdString([error localizedDescription]) << std::endl;
+ SWIFT_LOG(error) << ns2StdString([error localizedDescription]);
onNewUpdateState(AutoUpdater::State::ErrorCheckingForUpdate);
}
@@ -71,7 +71,7 @@ using namespace Swift;
onNewUpdateState(AutoUpdater::State::NoUpdateAvailable);
}
else {
- SWIFT_LOG(error) << ns2StdString([error localizedDescription]) << std::endl;
+ SWIFT_LOG(error) << ns2StdString([error localizedDescription]);
onNewUpdateState(AutoUpdater::State::ErrorCheckingForUpdate);
}
}
diff --git a/SwifTools/CrashReporter.cpp b/SwifTools/CrashReporter.cpp
index bf637c8..b02e73b 100644
--- a/SwifTools/CrashReporter.cpp
+++ b/SwifTools/CrashReporter.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.
*/
@@ -46,7 +46,7 @@ CrashReporter::CrashReporter(const boost::filesystem::path& path, const std::str
boost::filesystem::create_directories(path);
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << "ERROR: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "ERROR: " << e.what();
}
}
diff --git a/SwifTools/HunspellChecker.cpp b/SwifTools/HunspellChecker.cpp
index 1de369b..019a4dc 100644
--- a/SwifTools/HunspellChecker.cpp
+++ b/SwifTools/HunspellChecker.cpp
@@ -84,12 +84,12 @@ bool HunspellChecker::isAutomaticallyDetectingLanguage() {
void HunspellChecker::setActiveLanguage(const std::string& language) {
auto dictionaries = detectedDictionaries();
if (dictionaries.find(language) != dictionaries.end()) {
- SWIFT_LOG(debug) << "Initialized Hunspell with dic,aff files " << dictionaries[language].dicPath << " , " << dictionaries[language].affPath << std::endl;
+ SWIFT_LOG(debug) << "Initialized Hunspell with dic,aff files " << dictionaries[language].dicPath << " , " << dictionaries[language].affPath;
speller_ = std::unique_ptr<Hunspell>(new Hunspell(dictionaries[language].affPath.c_str(), dictionaries[language].dicPath.c_str()));
activeLangauge_ = language;
}
else {
- SWIFT_LOG(warning) << "Unsupported language '" << language << "'" << std::endl;
+ SWIFT_LOG(warning) << "Unsupported language '" << language << "'";
}
}
diff --git a/SwifTools/Notifier/NotificationCenterNotifier.mm b/SwifTools/Notifier/NotificationCenterNotifier.mm
index 1538186..e6fdfb6 100644
--- a/SwifTools/Notifier/NotificationCenterNotifier.mm
+++ b/SwifTools/Notifier/NotificationCenterNotifier.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.
*/
@@ -88,7 +88,7 @@ void NotificationCenterNotifier::handleUserNotificationActivated(const std::stri
}
}
else {
- SWIFT_LOG(warning) << "Missing callback entry for activated notification. The activate notification may come from another instance." << std::endl;
+ SWIFT_LOG(warning) << "Missing callback entry for activated notification. The activate notification may come from another instance.";
}
}
diff --git a/Swift/Controllers/AccountController.cpp b/Swift/Controllers/AccountController.cpp
index 27655c0..a257cc4 100644
--- a/Swift/Controllers/AccountController.cpp
+++ b/Swift/Controllers/AccountController.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.
*/
@@ -781,10 +781,10 @@ void AccountController::enableMessageCarbons() {
auto enableCarbonsRequest = EnableCarbonsRequest::create(client_->getIQRouter());
enableCarbonsRequestHandlerConnection_ = enableCarbonsRequest->onResponse.connect([&](Payload::ref /*payload*/, ErrorPayload::ref error) {
if (error) {
- SWIFT_LOG(warning) << "Failed to enable carbons." << std::endl;
+ SWIFT_LOG(warning) << "Failed to enable carbons.";
}
else {
- SWIFT_LOG(debug) << "Successfully enabled carbons." << std::endl;
+ SWIFT_LOG(debug) << "Successfully enabled carbons.";
}
enableCarbonsRequestHandlerConnection_.disconnect();
});
@@ -840,18 +840,18 @@ void AccountController::handleQuitRequest() {
std::string AccountController::serializeClientOptions(const ClientOptions& options) {
std::string result;
- SERIALIZE_BOOL(useStreamCompression);
+ SERIALIZE_BOOL(useStreamCompression)
switch (options.useTLS) {
case ClientOptions::NeverUseTLS: result += "1";break;
case ClientOptions::UseTLSWhenAvailable: result += "2";break;
case ClientOptions::RequireTLS: result += "3";break;
}
result += ",";
- SERIALIZE_BOOL(allowPLAINWithoutTLS);
- SERIALIZE_BOOL(useStreamResumption);
- SERIALIZE_BOOL(useAcks);
- SERIALIZE_STRING(manualHostname);
- SERIALIZE_INT(manualPort);
+ SERIALIZE_BOOL(allowPLAINWithoutTLS)
+ SERIALIZE_BOOL(useStreamResumption)
+ SERIALIZE_BOOL(useAcks)
+ SERIALIZE_STRING(manualHostname)
+ SERIALIZE_INT(manualPort)
switch (options.proxyType) {
case ClientOptions::NoProxy: result += "1";break;
case ClientOptions::SystemConfiguredProxy: result += "2";break;
@@ -859,14 +859,14 @@ std::string AccountController::serializeClientOptions(const ClientOptions& optio
case ClientOptions::HTTPConnectProxy: result += "4";break;
}
result += ",";
- SERIALIZE_STRING(manualProxyHostname);
- SERIALIZE_INT(manualProxyPort);
- SERIALIZE_URL(boshURL);
- SERIALIZE_URL(boshHTTPConnectProxyURL);
- SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthID);
- SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthPassword);
- SERIALIZE_BOOL(tlsOptions.schannelTLS1_0Workaround);
- SERIALIZE_BOOL(singleSignOn);
+ SERIALIZE_STRING(manualProxyHostname)
+ SERIALIZE_INT(manualProxyPort)
+ SERIALIZE_URL(boshURL)
+ SERIALIZE_URL(boshHTTPConnectProxyURL)
+ SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthID)
+ SERIALIZE_SAFE_STRING(boshHTTPConnectProxyAuthPassword)
+ SERIALIZE_BOOL(tlsOptions.schannelTLS1_0Workaround)
+ SERIALIZE_BOOL(singleSignOn)
return result;
}
diff --git a/Swift/Controllers/Chat/ChatController.cpp b/Swift/Controllers/Chat/ChatController.cpp
index 5f441f8..debd83f 100644
--- a/Swift/Controllers/Chat/ChatController.cpp
+++ b/Swift/Controllers/Chat/ChatController.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.
*/
@@ -190,7 +190,7 @@ void ChatController::preHandleIncomingMessage(std::shared_ptr<MessageEvent> mess
// handle XEP-0184 Message Receipts
// incomming receipts
if (std::shared_ptr<DeliveryReceipt> receipt = message->getPayload<DeliveryReceipt>()) {
- SWIFT_LOG(debug) << "received receipt for id: " << receipt->getReceivedID() << std::endl;
+ SWIFT_LOG(debug) << "received receipt for id: " << receipt->getReceivedID();
if (requestedReceipts_.find(receipt->getReceivedID()) != requestedReceipts_.end()) {
chatWindow_->setMessageReceiptState(requestedReceipts_[receipt->getReceivedID()], ChatWindow::ReceiptReceived);
requestedReceipts_.erase(receipt->getReceivedID());
@@ -407,7 +407,7 @@ void ChatController::handleWhiteboardStateChange(const ChatWindow::WhiteboardSes
}
void ChatController::handleFileTransferCancel(std::string id) {
- SWIFT_LOG(debug) << "handleFileTransferCancel(" << id << ")" << std::endl;
+ SWIFT_LOG(debug) << "handleFileTransferCancel(" << id << ")";
if (ftControllers.find(id) != ftControllers.end()) {
ftControllers[id]->cancel();
} else {
@@ -416,7 +416,7 @@ void ChatController::handleFileTransferCancel(std::string id) {
}
void ChatController::handleFileTransferStart(std::string id, std::string description) {
- SWIFT_LOG(debug) << "handleFileTransferStart(" << id << ", " << description << ")" << std::endl;
+ SWIFT_LOG(debug) << "handleFileTransferStart(" << id << ", " << description << ")";
if (ftControllers.find(id) != ftControllers.end()) {
ftControllers[id]->start(description);
} else {
@@ -425,7 +425,7 @@ void ChatController::handleFileTransferStart(std::string id, std::string descrip
}
void ChatController::handleFileTransferAccept(std::string id, std::string filename) {
- SWIFT_LOG(debug) << "handleFileTransferAccept(" << id << ", " << filename << ")" << std::endl;
+ SWIFT_LOG(debug) << "handleFileTransferAccept(" << id << ", " << filename << ")";
if (ftControllers.find(id) != ftControllers.end()) {
ftControllers[id]->accept(filename);
} else {
@@ -434,7 +434,7 @@ void ChatController::handleFileTransferAccept(std::string id, std::string filena
}
void ChatController::handleSendFileRequest(std::string filename) {
- SWIFT_LOG(debug) << "ChatController::handleSendFileRequest(" << filename << ")" << std::endl;
+ SWIFT_LOG(debug) << "ChatController::handleSendFileRequest(" << filename << ")";
eventStream_->send(std::make_shared<SendFileUIEvent>(getToJID(), filename));
}
diff --git a/Swift/Controllers/Chat/ChatsManager.cpp b/Swift/Controllers/Chat/ChatsManager.cpp
index 6530a7e..193af7f 100644
--- a/Swift/Controllers/Chat/ChatsManager.cpp
+++ b/Swift/Controllers/Chat/ChatsManager.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.
*/
@@ -175,7 +175,7 @@ ChatsManager::~ChatsManager() {
roster_->onRosterCleared.disconnect(boost::bind(&ChatsManager::handleRosterCleared, this));
ftOverview_->onNewFileTransferController.disconnect(boost::bind(&ChatsManager::handleNewFileTransferController, this, _1));
delete joinMUCWindow_;
- SWIFT_LOG(debug) << "Destroying ChatsManager, containing " << chatControllers_.size() << " chats and " << mucControllers_.size() << " MUCs" << std::endl;
+ SWIFT_LOG(debug) << "Destroying ChatsManager, containing " << chatControllers_.size() << " chats and " << mucControllers_.size() << " MUCs";
for (JIDChatControllerPair controllerPair : chatControllers_) {
delete controllerPair.second;
}
@@ -311,7 +311,7 @@ void ChatsManager::loadRecents() {
boost::archive::text_iarchive ia(deserializeStream);
ia >> recentChats;
} catch (const boost::archive::archive_exception& e) {
- SWIFT_LOG(debug) << "Failed to load recents: " << e.what() << std::endl;
+ SWIFT_LOG(debug) << "Failed to load recents: " << e.what();
return;
}
recentChats.erase(std::remove(recentChats.begin(), recentChats.end(), ChatListWindow::Chat()), recentChats.end());
@@ -936,7 +936,7 @@ void ChatsManager::handleUserNicknameChanged(MUCController* mucController, const
JID oldMUCChatJID = mucController->getToJID().withResource(oldNickname);
JID newMUCChatJID = mucController->getToJID().withResource(newNickname);
- SWIFT_LOG(debug) << "nickname change in " << mucController->getToJID().toString() << " from " << oldNickname << " to " << newNickname << std::endl;
+ SWIFT_LOG(debug) << "nickname change in " << mucController->getToJID().toString() << " from " << oldNickname << " to " << newNickname;
// get current chat controller
ChatController *chatController = getChatControllerIfExists(oldMUCChatJID);
@@ -983,7 +983,7 @@ void ChatsManager::handleIncomingMessage(std::shared_ptr<Message> incomingMessag
controller->handleIncomingOwnMessage(forwardedMessage);
}
else {
- SWIFT_LOG(error) << "Carbons message ignored." << std::endl;
+ SWIFT_LOG(error) << "Carbons message ignored.";
}
return;
}
@@ -1141,7 +1141,7 @@ void ChatsManager::handleLocalServiceFound(const JID& service, std::shared_ptr<D
&& identity.getType() == "text")) {
localMUCServiceJID_ = service;
localMUCServiceFinderWalker_->endWalk();
- SWIFT_LOG(debug) << "Use following MUC service for impromptu chats: " << localMUCServiceJID_ << std::endl;
+ SWIFT_LOG(debug) << "Use following MUC service for impromptu chats: " << localMUCServiceJID_;
break;
}
}
diff --git a/Swift/Controllers/Chat/MUCSearchController.cpp b/Swift/Controllers/Chat/MUCSearchController.cpp
index 5db917a..0b54d25 100644
--- a/Swift/Controllers/Chat/MUCSearchController.cpp
+++ b/Swift/Controllers/Chat/MUCSearchController.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.
*/
@@ -92,7 +92,7 @@ void MUCSearchController::handleSearchService(const JID& jid) {
delete walker_;
}
- SWIFT_LOG(debug) << "Starting walking MUC services" << std::endl;
+ SWIFT_LOG(debug) << "Starting walking MUC services";
itemsInProgress_ = 0;
walker_ = new DiscoServiceWalker(jid, iqRouter_);
walker_->onServiceFound.connect(boost::bind(&MUCSearchController::handleDiscoServiceFound, this, _1, _2));
@@ -113,14 +113,14 @@ void MUCSearchController::handleDiscoServiceFound(const JID& jid, std::shared_pt
}
}
if (isMUC) {
- SWIFT_LOG(debug) << "MUC Service found: " << jid << std::endl;
+ SWIFT_LOG(debug) << "MUC Service found: " << jid;
services_.erase(std::remove(services_.begin(), services_.end(), jid), services_.end());
services_.push_back(jid);
serviceDetails_[jid].setName(name);
serviceDetails_[jid].setJID(jid);
serviceDetails_[jid].setComplete(false);
itemsInProgress_++;
- SWIFT_LOG(debug) << "Requesting items of " << jid << " (" << itemsInProgress_ << " item requests in progress)" << std::endl;
+ SWIFT_LOG(debug) << "Requesting items of " << jid << " (" << itemsInProgress_ << " item requests in progress)";
GetDiscoItemsRequest::ref discoItemsRequest = GetDiscoItemsRequest::create(jid, iqRouter_);
discoItemsRequest->onResponse.connect(boost::bind(&MUCSearchController::handleRoomsItemsResponse, this, _1, _2, jid));
discoItemsRequest->send();
@@ -132,7 +132,7 @@ void MUCSearchController::handleDiscoServiceFound(const JID& jid, std::shared_pt
}
void MUCSearchController::handleDiscoWalkFinished() {
- SWIFT_LOG(debug) << "MUC Walk finished" << std::endl;
+ SWIFT_LOG(debug) << "MUC Walk finished";
updateInProgressness();
}
@@ -144,7 +144,7 @@ void MUCSearchController::removeService(const JID& jid) {
void MUCSearchController::handleRoomsItemsResponse(std::shared_ptr<DiscoItems> items, ErrorPayload::ref error, const JID& jid) {
itemsInProgress_--;
- SWIFT_LOG(debug) << "Items received for " << jid << " (" << itemsInProgress_ << " item requests in progress)" << std::endl;
+ SWIFT_LOG(debug) << "Items received for " << jid << " (" << itemsInProgress_ << " item requests in progress)";
updateInProgressness();
if (error) {
handleDiscoError(jid, error);
diff --git a/Swift/Controllers/FileTransfer/FileTransferController.cpp b/Swift/Controllers/FileTransfer/FileTransferController.cpp
index 27e9dbf..5b86a7b 100644
--- a/Swift/Controllers/FileTransfer/FileTransferController.cpp
+++ b/Swift/Controllers/FileTransfer/FileTransferController.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2015-2017 Isode Limited.
+ * Copyright (c) 2015-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -82,7 +82,7 @@ boost::uintmax_t FileTransferController::getSize() const {
}
void FileTransferController::start(std::string& description) {
- SWIFT_LOG(debug) << "FileTransferController::start" << std::endl;
+ SWIFT_LOG(debug) << "FileTransferController::start";
fileReadStream = std::make_shared<FileReadBytestream>(boost::filesystem::path(filename));
OutgoingFileTransfer::ref outgoingTransfer = ftManager->createOutgoingFileTransfer(otherParty, boost::filesystem::path(filename), description, fileReadStream);
if (outgoingTransfer) {
@@ -98,7 +98,7 @@ void FileTransferController::start(std::string& description) {
}
void FileTransferController::accept(std::string& file) {
- SWIFT_LOG(debug) << "FileTransferController::accept" << std::endl;
+ SWIFT_LOG(debug) << "FileTransferController::accept";
IncomingFileTransfer::ref incomingTransfer = std::dynamic_pointer_cast<IncomingFileTransfer>(transfer);
if (incomingTransfer) {
fileWriteStream = std::make_shared<FileWriteBytestream>(boost::filesystem::path(file));
diff --git a/Swift/Controllers/Highlighting/HighlightManager.cpp b/Swift/Controllers/Highlighting/HighlightManager.cpp
index 2ca77e7..f09d94c 100644
--- a/Swift/Controllers/Highlighting/HighlightManager.cpp
+++ b/Swift/Controllers/Highlighting/HighlightManager.cpp
@@ -5,7 +5,7 @@
*/
/*
- * Copyright (c) 2014-2017 Isode Limited.
+ * Copyright (c) 2014-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -85,7 +85,7 @@ HighlightConfiguration HighlightManager::highlightConfigurationFromString(const
}
catch (boost::archive::archive_exception&) {
configuration = getDefaultConfig();
- SWIFT_LOG(warning) << "Failed to load highlight configuration. Will use default configuration instead." << std::endl;
+ SWIFT_LOG(warning) << "Failed to load highlight configuration. Will use default configuration instead.";
}
return configuration;
}
diff --git a/Swift/Controllers/Settings/XMLSettingsProvider.cpp b/Swift/Controllers/Settings/XMLSettingsProvider.cpp
index 2573af0..a316cef 100644
--- a/Swift/Controllers/Settings/XMLSettingsProvider.cpp
+++ b/Swift/Controllers/Settings/XMLSettingsProvider.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.
*/
@@ -18,16 +18,16 @@ namespace Swift {
XMLSettingsProvider::XMLSettingsProvider(const std::string& xmlConfig) : level_(0) {
if (!xmlConfig.empty()) {
PlatformXMLParserFactory factory;
- auto parser = factory.createXMLParser(this);
+ auto parser = factory.createXMLParser(this, true);
if (parser->parse(xmlConfig)) {
- SWIFT_LOG(debug) << "Found and parsed system config" << std::endl;
+ SWIFT_LOG(debug) << "Found and parsed system config";
}
else {
- SWIFT_LOG(debug) << "Found invalid system config" << std::endl;
+ SWIFT_LOG(debug) << "Found invalid system config";
}
}
else {
- SWIFT_LOG(debug) << "No system config found" << std::endl;
+ SWIFT_LOG(debug) << "No system config found";
}
}
@@ -68,7 +68,7 @@ int XMLSettingsProvider::getSetting(const Setting<int>& setting) {
if (values_.find(setting.getKey()) != values_.end()) {
std::string value = values_[setting.getKey()];
try {
- return value.empty() ? setting.getDefaultValue() : boost::lexical_cast<int>(value);;
+ return value.empty() ? setting.getDefaultValue() : boost::lexical_cast<int>(value);
}
catch(boost::bad_lexical_cast &) {}
}
@@ -110,7 +110,7 @@ void XMLSettingsProvider::handleStartElement(const std::string& element, const s
void XMLSettingsProvider::handleEndElement(const std::string& /*element*/, const std::string& /*ns*/) {
if (level_ == SettingLevel) {
values_[currentElement_] = currentText_;
- SWIFT_LOG(debug) << "Setting value of " << currentElement_ << " to " << currentText_ << std::endl;
+ SWIFT_LOG(debug) << "Setting value of " << currentElement_ << " to " << currentText_;
}
level_--;
}
@@ -123,7 +123,3 @@ void XMLSettingsProvider::handleCharacterData(const std::string& data) {
}
-
-
-
-
diff --git a/Swift/Controllers/StatusCache.cpp b/Swift/Controllers/StatusCache.cpp
index 3c6baed..f9196f6 100644
--- a/Swift/Controllers/StatusCache.cpp
+++ b/Swift/Controllers/StatusCache.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.
*/
@@ -76,13 +76,13 @@ void StatusCache::loadRecents() {
previousStatuses_.push_back(PreviousStatus(boost::trim_copy(bits[1]), type));
}
catch (const boost::bad_lexical_cast& e) {
- SWIFT_LOG(error) << "Failed to load recent status cache entry: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "Failed to load recent status cache entry: " << e.what();
}
}
}
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << "Failed to load recents: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "Failed to load recents: " << e.what();
}
}
@@ -100,7 +100,7 @@ void StatusCache::saveRecents() {
file.close();
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << "Failed to save recents: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "Failed to save recents: " << e.what();
}
}
diff --git a/Swift/Controllers/Storages/AvatarFileStorage.cpp b/Swift/Controllers/Storages/AvatarFileStorage.cpp
index 9d9b9ea..808c432 100644
--- a/Swift/Controllers/Storages/AvatarFileStorage.cpp
+++ b/Swift/Controllers/Storages/AvatarFileStorage.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.
*/
@@ -30,13 +30,13 @@ AvatarFileStorage::AvatarFileStorage(const boost::filesystem::path& avatarsDir,
jidAvatars.insert(std::make_pair(jid, r.first));
}
else if (!r.first.empty() || !r.second.empty()) {
- SWIFT_LOG(error) << "Invalid entry in avatars file: " << r.second << std::endl;
+ SWIFT_LOG(error) << "Invalid entry in avatars file: " << r.second;
}
}
}
}
catch (...) {
- SWIFT_LOG(error) << "Error reading avatars file" << std::endl;
+ SWIFT_LOG(error) << "Error reading avatars file";
}
}
}
@@ -54,7 +54,7 @@ void AvatarFileStorage::addAvatar(const std::string& hash, const ByteArray& avat
boost::filesystem::create_directories(avatarPath.parent_path());
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << "filesystem error: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "filesystem error: " << e.what();
}
}
@@ -63,7 +63,7 @@ void AvatarFileStorage::addAvatar(const std::string& hash, const ByteArray& avat
file.write(reinterpret_cast<const char*>(vecptr(avatar)), static_cast<std::streamsize>(avatar.size()));
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << "filesystem error: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "filesystem error: " << e.what();
}
}
@@ -77,7 +77,7 @@ ByteArray AvatarFileStorage::getAvatar(const std::string& hash) const {
readByteArrayFromFile(data, getAvatarPath(hash));
}
catch (const boost::filesystem::filesystem_error& e) {
- SWIFT_LOG(error) << "filesystem error: " << e.what() << std::endl;
+ SWIFT_LOG(error) << "filesystem error: " << e.what();
}
return data;
}
@@ -107,7 +107,7 @@ void AvatarFileStorage::saveJIDAvatars() {
file.close();
}
catch (...) {
- SWIFT_LOG(error) << "Error writing avatars file" << std::endl;
+ SWIFT_LOG(error) << "Error writing avatars file";
}
}
diff --git a/Swift/Controllers/Storages/CertificateFileStorage.cpp b/Swift/Controllers/Storages/CertificateFileStorage.cpp
index 2e1343f..a8661df 100644
--- a/Swift/Controllers/Storages/CertificateFileStorage.cpp
+++ b/Swift/Controllers/Storages/CertificateFileStorage.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.
*/
@@ -31,7 +31,7 @@ bool CertificateFileStorage::hasCertificate(Certificate::ref certificate) const
return true;
}
else {
- SWIFT_LOG(warning) << "Stored certificate does not match received certificate" << std::endl;
+ SWIFT_LOG(warning) << "Stored certificate does not match received certificate";
return false;
}
}
@@ -57,7 +57,7 @@ void CertificateFileStorage::addCertificate(Certificate::ref certificate) {
file.close();
}
catch (...) {
- SWIFT_LOG(warning) << "Failed to store certificate to " << certificatePath << std::endl;
+ SWIFT_LOG(warning) << "Failed to store certificate to " << certificatePath;
}
}
diff --git a/Swift/Packaging/Debian/Dockerfile.package.in b/Swift/Packaging/Debian/Dockerfile.package.in
index 38e493d..b53d477 100644
--- a/Swift/Packaging/Debian/Dockerfile.package.in
+++ b/Swift/Packaging/Debian/Dockerfile.package.in
@@ -3,6 +3,9 @@ MAINTAINER packages@swift.im
ENV DEBIAN_VERSION=__DEBIAN_VERSION__
+# Make sure nothing needs an interactive prompt
+ARG DEBIAN_FRONTEND=noninteractive
+
RUN \
apt-get -qq update && \
apt-get install -y lintian devscripts scons build-essential dh-make pkg-config libssl-dev qt5-default libqt5x11extras5-dev libqt5webkit5-dev qtmultimedia5-dev qttools5-dev-tools qt5-image-formats-plugins libqt5svg5-dev libminiupnpc-dev libnatpmp-dev libhunspell-dev libxml2-dev libxss-dev libboost-dev libboost-filesystem-dev libboost-program-options-dev libboost-regex-dev libboost-signals-dev libboost-system-dev libboost-thread-dev libboost-date-time-dev libidn11-dev docbook-xsl docbook-xml xsltproc libxml2-utils libsqlite3-dev zlib1g-dev help2man && \
diff --git a/Swift/QtUI/CAPICertificateSelector.cpp b/Swift/QtUI/CAPICertificateSelector.cpp
index e47121b..7e4bc0b 100644
--- a/Swift/QtUI/CAPICertificateSelector.cpp
+++ b/Swift/QtUI/CAPICertificateSelector.cpp
@@ -80,11 +80,11 @@ std::string selectCAPICertificate() {
if (titleLength == 0 || promptLength == 0) {
int error = GetLastError();
switch (error) {
- case ERROR_INSUFFICIENT_BUFFER: SWIFT_LOG(error) << "Insufficient buffer for rendering cert dialog" << std::endl;break;
- case ERROR_INVALID_FLAGS: SWIFT_LOG(error) << "Invalid flags for rendering cert dialog" << std::endl;break;
- case ERROR_INVALID_PARAMETER: SWIFT_LOG(error) << "Invalid parameter for rendering cert dialog" << std::endl;break;
- case ERROR_NO_UNICODE_TRANSLATION: SWIFT_LOG(error) << "Invalid unicode for rendering cert dialog" << std::endl;break;
- default: SWIFT_LOG(error) << "Unexpected multibyte conversion errorcode" << std::endl;
+ case ERROR_INSUFFICIENT_BUFFER: SWIFT_LOG(error) << "Insufficient buffer for rendering cert dialog"; break;
+ case ERROR_INVALID_FLAGS: SWIFT_LOG(error) << "Invalid flags for rendering cert dialog"; break;
+ case ERROR_INVALID_PARAMETER: SWIFT_LOG(error) << "Invalid parameter for rendering cert dialog"; break;
+ case ERROR_NO_UNICODE_TRANSLATION: SWIFT_LOG(error) << "Invalid unicode for rendering cert dialog"; break;
+ default: SWIFT_LOG(error) << "Unexpected multibyte conversion errorcode";
}
}
@@ -103,7 +103,7 @@ std::string selectCAPICertificate() {
if (hstore) {
if (CertCloseStore(hstore, 0) == FALSE) {
- SWIFT_LOG(debug) << "Failed to close the certificate store handle." << std::endl;
+ SWIFT_LOG(debug) << "Failed to close the certificate store handle.";
}
}
diff --git a/Swift/QtUI/QtAboutWidget.cpp b/Swift/QtUI/QtAboutWidget.cpp
index 2db0c9d..0a4e0ba 100644
--- a/Swift/QtUI/QtAboutWidget.cpp
+++ b/Swift/QtUI/QtAboutWidget.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.
*/
@@ -150,7 +150,7 @@ void QtAboutWidget::openPlainTextWindow(const QString& path) {
text->activateWindow();
}
else {
- SWIFT_LOG(error) << "Failed to open " << Q2PSTRING(path) << "." << std::endl;
+ SWIFT_LOG(error) << "Failed to open " << Q2PSTRING(path) << ".";
}
}
diff --git a/Swift/QtUI/QtScaledAvatarCache.cpp b/Swift/QtUI/QtScaledAvatarCache.cpp
index 37ea6a9..e3a28d6 100644
--- a/Swift/QtUI/QtScaledAvatarCache.cpp
+++ b/Swift/QtUI/QtScaledAvatarCache.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.
*/
@@ -53,8 +53,8 @@ QString QtScaledAvatarCache::getScaledAvatarPath(const QString& path) {
if (avatarFile.exists() && !avatarFile.absolutePath().startsWith(":/")) {
QString cacheSubPath = QString("ScaledAvatarCacheV%1/%2").arg(QString::number(QT_SCALED_AVATAR_CACHE_VERSION), QString::number(size));
if (!avatarFile.dir().mkpath(cacheSubPath)) {
- SWIFT_LOG(error) << "avatarFile.dir(): " << Q2PSTRING(avatarFile.dir().absolutePath()) << std::endl;
- SWIFT_LOG(error) << "Failed creating cache folder: " << Q2PSTRING(cacheSubPath) << std::endl;
+ SWIFT_LOG(error) << "avatarFile.dir(): " << Q2PSTRING(avatarFile.dir().absolutePath());
+ SWIFT_LOG(error) << "Failed creating cache folder: " << Q2PSTRING(cacheSubPath);
return path;
}
QDir targetDir(avatarFile.dir().absoluteFilePath(cacheSubPath));
@@ -75,7 +75,7 @@ QString QtScaledAvatarCache::getScaledAvatarPath(const QString& path) {
return path;
}
} else {
- SWIFT_LOG(warning) << "Failed to load " << Q2PSTRING(path) << std::endl;
+ SWIFT_LOG(warning) << "Failed to load " << Q2PSTRING(path);
}
}
return targetFile;
diff --git a/Swift/QtUI/QtSpellCheckerWindow.cpp b/Swift/QtUI/QtSpellCheckerWindow.cpp
index a8178c4..23b0963 100644
--- a/Swift/QtUI/QtSpellCheckerWindow.cpp
+++ b/Swift/QtUI/QtSpellCheckerWindow.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.
*/
@@ -64,7 +64,7 @@ void QtSpellCheckerWindow::setSupportedLanguages(const std::vector<std::string>&
}
void QtSpellCheckerWindow::setActiveLanguage(const std::string& language) {
- SWIFT_LOG_ASSERT(languageItems_.find(language) != languageItems_.end(), warning) << "Language '" << language << "' is not available." << std::endl;
+ SWIFT_LOG_ASSERT(languageItems_.find(language) != languageItems_.end(), warning) << "Language '" << language << "' is not available.";
if (languageItems_.find(language) != languageItems_.end()) {
languageItems_[language]->setSelected(true);
}
diff --git a/Swift/QtUI/QtSwift.cpp b/Swift/QtUI/QtSwift.cpp
index 8de5d70..73fd733 100644
--- a/Swift/QtUI/QtSwift.cpp
+++ b/Swift/QtUI/QtSwift.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.
*/
@@ -191,7 +191,7 @@ QtSwift::QtSwift(const po::variables_map& options) : networkFactories_(&clientMa
Log::setLogFile(fileName);
}
catch (...) {
- SWIFT_LOG(error) << "Error while retrieving the specified log file name from the command line" << std::endl;
+ SWIFT_LOG(error) << "Error while retrieving the specified log file name from the command line";
}
}
//TODO this old option can be purged
@@ -222,13 +222,13 @@ QtSwift::QtSwift(const po::variables_map& options) : networkFactories_(&clientMa
for (auto&& fontName : fontNames) {
std::string fontPath = std::string(":/") + fontName;
int error = QFontDatabase::addApplicationFont(P2QSTRING(fontPath));
- SWIFT_LOG_ASSERT(error != -1, error) << "Failed to load font " << fontPath << std::endl;
+ SWIFT_LOG_ASSERT(error != -1, error) << "Failed to load font " << fontPath;
}
#ifdef SWIFTEN_PLATFORM_LINUX
std::string fontPath = std::string(":/themes/Default/Noto/NotoColorEmoji.ttf");
int error = QFontDatabase::addApplicationFont(P2QSTRING(fontPath));
- SWIFT_LOG_ASSERT(error != -1, error) << "Failed to load font " << fontPath << std::endl;
+ SWIFT_LOG_ASSERT(error != -1, error) << "Failed to load font " << fontPath;
QFont::insertSubstitution(QApplication::font().family(),"NotoColorEmoji");
#endif
#ifdef SWIFTEN_PLATFORM_WINDOWS
@@ -446,34 +446,34 @@ ClientOptions QtSwift::parseClientOptions(const std::string& optionString) {
std::string stringVal;
std::vector<std::string> segments = String::split(optionString, ',');
- PARSE_BOOL(useStreamCompression, 1);
- PARSE_INT_RAW(-1);
+ PARSE_BOOL(useStreamCompression, 1)
+ PARSE_INT_RAW(-1)
switch (intVal) {
case 1: result.useTLS = ClientOptions::NeverUseTLS; break;
case 2: result.useTLS = ClientOptions::UseTLSWhenAvailable; break;
case 3: result.useTLS = ClientOptions::RequireTLS; break;
default:;
}
- PARSE_BOOL(allowPLAINWithoutTLS, 0);
- PARSE_BOOL(useStreamResumption, 0);
- PARSE_BOOL(useAcks, 1);
- PARSE_STRING(manualHostname);
- PARSE_INT(manualPort, -1);
- PARSE_INT_RAW(-1);
+ PARSE_BOOL(allowPLAINWithoutTLS, 0)
+ PARSE_BOOL(useStreamResumption, 0)
+ PARSE_BOOL(useAcks, 1)
+ PARSE_STRING(manualHostname)
+ PARSE_INT(manualPort, -1)
+ PARSE_INT_RAW(-1)
switch (intVal) {
case 1: result.proxyType = ClientOptions::NoProxy; break;
case 2: result.proxyType = ClientOptions::SystemConfiguredProxy; break;
case 3: result.proxyType = ClientOptions::SOCKS5Proxy; break;
case 4: result.proxyType = ClientOptions::HTTPConnectProxy; break;
}
- PARSE_STRING(manualProxyHostname);
- PARSE_INT(manualProxyPort, -1);
- PARSE_URL(boshURL);
- PARSE_URL(boshHTTPConnectProxyURL);
- PARSE_SAFE_STRING(boshHTTPConnectProxyAuthID);
- PARSE_SAFE_STRING(boshHTTPConnectProxyAuthPassword);
- PARSE_BOOL(tlsOptions.schannelTLS1_0Workaround, false);
- PARSE_BOOL(singleSignOn, false);
+ PARSE_STRING(manualProxyHostname)
+ PARSE_INT(manualProxyPort, -1)
+ PARSE_URL(boshURL)
+ PARSE_URL(boshHTTPConnectProxyURL)
+ PARSE_SAFE_STRING(boshHTTPConnectProxyAuthID)
+ PARSE_SAFE_STRING(boshHTTPConnectProxyAuthPassword)
+ PARSE_BOOL(tlsOptions.schannelTLS1_0Workaround, false)
+ PARSE_BOOL(singleSignOn, false)
return result;
}
diff --git a/Swift/QtUI/QtTextEdit.cpp b/Swift/QtUI/QtTextEdit.cpp
index e63cd4f..b3c57a7 100644
--- a/Swift/QtUI/QtTextEdit.cpp
+++ b/Swift/QtUI/QtTextEdit.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.
*/
@@ -240,7 +240,7 @@ void QtTextEdit::setUpSpellChecker() {
}
else {
// Spellchecking is not working, as we did not get a valid checker from the factory. Disable spellchecking.
- SWIFT_LOG(warning) << "Spellchecking is currently misconfigured in Swift (e.g. missing dictionary or broken dictionary file). Disable spellchecking." << std::endl;
+ SWIFT_LOG(warning) << "Spellchecking is currently misconfigured in Swift (e.g. missing dictionary or broken dictionary file). Disable spellchecking.";
settings_->storeSetting(QtUISettingConstants::SPELL_CHECKER, false);
}
diff --git a/Swift/QtUI/QtUIFactory.cpp b/Swift/QtUI/QtUIFactory.cpp
index 93fca5f..49f55dd 100644
--- a/Swift/QtUI/QtUIFactory.cpp
+++ b/Swift/QtUI/QtUIFactory.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,9 +49,9 @@ QtUIFactory::QtUIFactory(SettingsProviderHierachy* settings, QtSettingsProvider*
}
QtUIFactory::~QtUIFactory() {
- SWIFT_LOG(debug) << "Entering QtUIFactory destructor. chatWindows size:" << chatWindows_.size() << std::endl;
+ SWIFT_LOG(debug) << "Entering QtUIFactory destructor. chatWindows size:" << chatWindows_.size();
for (auto chat : chatWindows_) {
- SWIFT_LOG_ASSERT(chat.isNull(), debug) << "QtUIFactory has active chat windows and has not been reset properly" << std::endl;
+ SWIFT_LOG_ASSERT(chat.isNull(), debug) << "QtUIFactory has active chat windows and has not been reset properly";
}
delete chatWindowFactory_;
}
diff --git a/Swift/QtUI/QtWebKitChatView.cpp b/Swift/QtUI/QtWebKitChatView.cpp
index bca9e2e..75a23f8 100644
--- a/Swift/QtUI/QtWebKitChatView.cpp
+++ b/Swift/QtUI/QtWebKitChatView.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.
*/
@@ -141,7 +141,7 @@ void QtWebKitChatView::addMessageBottom(std::shared_ptr<ChatSnippet> snippet) {
void QtWebKitChatView::addMessageTop(std::shared_ptr<ChatSnippet> /* snippet */) {
// TODO: Implement this in a sensible manner later.
- SWIFT_LOG(error) << "Not yet implemented!" << std::endl;
+ SWIFT_LOG(error) << "Not yet implemented!";
}
void QtWebKitChatView::addToDOM(std::shared_ptr<ChatSnippet> snippet) {
@@ -384,7 +384,7 @@ void QtWebKitChatView::setFileTransferProgress(QString id, const int percentageD
rememberScrolledToBottom();
QWebElement ftElement = findElementWithID(document_, "div", id);
if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id!" << std::endl;
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id!";
return;
}
QWebElement progressBar = ftElement.findFirst("div.progressbar");
@@ -398,7 +398,7 @@ void QtWebKitChatView::setFileTransferStatus(QString id, const ChatWindow::FileT
rememberScrolledToBottom();
QWebElement ftElement = findElementWithID(document_, "div", id);
if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id);
return;
}
@@ -483,7 +483,7 @@ int QtWebKitChatView::getSnippetPositionByDate(const QDate& date) {
void QtWebKitChatView::resetTopInsertPoint() {
// TODO: Implement or refactor later.
- SWIFT_LOG(error) << "Not yet implemented!" << std::endl;
+ SWIFT_LOG(error) << "Not yet implemented!";
}
std::string QtWebKitChatView::addMessage(
@@ -624,7 +624,7 @@ void QtWebKitChatView::resizeEvent(QResizeEvent* event) {
}
std::string QtWebKitChatView::addFileTransfer(const std::string& senderName, const std::string& avatarPath, bool senderIsSelf, const std::string& filename, const boost::uintmax_t sizeInBytes, const std::string& description) {
- SWIFT_LOG(debug) << "addFileTransfer" << std::endl;
+ SWIFT_LOG(debug) << "addFileTransfer";
QString ft_id = QString("ft%1").arg(P2QSTRING(boost::lexical_cast<std::string>(idCounter_++)));
QString actionText;
@@ -726,7 +726,7 @@ static bool isFilePathWritable(const QString& path) {
void QtWebKitChatView::setFileTransferWarning(QString id, QString warningText) {
QWebElement ftElement = findElementWithID(document_, "div", id);
if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id);
return;
}
@@ -737,7 +737,7 @@ void QtWebKitChatView::setFileTransferWarning(QString id, QString warningText) {
void QtWebKitChatView::removeFileTransferWarning(QString id) {
QWebElement ftElement = findElementWithID(document_, "div", id);
if (ftElement.isNull()) {
- SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id) << std::endl;
+ SWIFT_LOG(debug) << "Tried to access FT UI via invalid id! id = " << Q2PSTRING(id);
return;
}
@@ -829,7 +829,7 @@ void QtWebKitChatView::handleHTMLButtonClicked(QString id, QString encodedArgume
window_->resendMessage(Q2PSTRING(chatID));
}
else {
- SWIFT_LOG(debug) << "Unknown HTML button! ( " << Q2PSTRING(id) << " )" << std::endl;
+ SWIFT_LOG(debug) << "Unknown HTML button! ( " << Q2PSTRING(id) << " )";
}
}
diff --git a/Swift/QtUI/Roster/QtFilterWidget.cpp b/Swift/QtUI/Roster/QtFilterWidget.cpp
index 2f561bd..c017d29 100644
--- a/Swift/QtUI/Roster/QtFilterWidget.cpp
+++ b/Swift/QtUI/Roster/QtFilterWidget.cpp
@@ -82,7 +82,7 @@ bool QtFilterWidget::eventFilter(QObject*, QEvent* event) {
} else if ((keyEvent->key() == Qt::Key_Alt && event->type() == QEvent::KeyRelease && isModifierSinglePressed_)
|| (keyEvent->key() == Qt::Key_Menu)) {
QPoint itemOffset(2,2);
- QPoint contextMenuPosition = treeView_->visualRect(treeView_->currentIndex()).topLeft() + itemOffset;;
+ QPoint contextMenuPosition = treeView_->visualRect(treeView_->currentIndex()).topLeft() + itemOffset;
QApplication::postEvent(treeView_, new QContextMenuEvent(QContextMenuEvent::Keyboard, contextMenuPosition, treeView_->mapToGlobal(contextMenuPosition)));
return true;
} else if (keyEvent->key() == Qt::Key_Return) {
diff --git a/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp b/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
index 2402529..53e2733 100644
--- a/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
+++ b/Swift/QtUI/Trellis/QtDynamicGridLayout.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014-2016 Isode Limited.
+ * Copyright (c) 2014-2019 Isode Limited.
* All rights reserved.
* See the COPYING file for more information.
*/
@@ -514,9 +514,9 @@ void QtDynamicGridLayout::updateTabPositions() {
void QtDynamicGridLayout::moveTab(QtTabWidget* tabWidget, int oldIndex, int newIndex) {
#if QT_VERSION >= 0x040500
- SWIFT_LOG_ASSERT(movingTab_ == nullptr, error) << std::endl;
+ SWIFT_LOG_ASSERT(movingTab_ == nullptr, error);
movingTab_ = qobject_cast<QtTabbable*>(tabWidget->widget(oldIndex));
- SWIFT_LOG_ASSERT(movingTab_ != nullptr, error) << std::endl;
+ SWIFT_LOG_ASSERT(movingTab_ != nullptr, error);
if (movingTab_) {
// Install event filter that filters out events issued during the internal movement of the
@@ -526,7 +526,7 @@ void QtDynamicGridLayout::moveTab(QtTabWidget* tabWidget, int oldIndex, int newI
tabWidget->tabBar()->moveTab(oldIndex, newIndex);
qApp->removeEventFilter(this);
- SWIFT_LOG_ASSERT(movingTab_ == tabWidget->widget(newIndex), error) << std::endl;
+ SWIFT_LOG_ASSERT(movingTab_ == tabWidget->widget(newIndex), error);
}
movingTab_ = nullptr;
tabWidget->widget(newIndex)->setFocus();
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());