diff options
193 files changed, 1699 insertions, 1216 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 © ); 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/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/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 8415209..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. */ @@ -20,14 +20,14 @@ XMLSettingsProvider::XMLSettingsProvider(const std::string& xmlConfig) : level_( PlatformXMLParserFactory factory; 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/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 a584b79..eb72014 100644 --- a/Swiften/JID/JID.cpp +++ b/Swiften/JID/JID.cpp @@ -72,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; diff --git a/Swiften/JID/JID.h b/Swiften/JID/JID.h index e98b796..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. */ 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/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/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 b8d941c..32b91a1 100644 --- a/Swiften/Parser/LibXMLParser.cpp +++ b/Swiften/Parser/LibXMLParser.cpp @@ -34,7 +34,7 @@ static void handleStartElement(void* parser, const xmlChar* name, const xmlChar* 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 attributeName = asString(attributes[i]); @@ -100,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, bool allowComments) : XMLParser(client, allowComments), p(new Private()) { // Initialize libXML for multithreaded applications if (!initialized) { xmlInitParser(); + xmlSetGenericErrorFunc(nullptr, handleGenericError); + xmlSetStructuredErrorFunc(nullptr, handleStructuredError); initialized = true; } @@ -136,12 +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; } if (stopped_) return false; - xmlError* error = xmlCtxtGetLastError(p->context_); - if (error->code == XML_WAR_NS_URI || error->code == XML_WAR_NS_URI_RELATIVE) { + if (error == XML_WAR_NS_URI || error == XML_WAR_NS_URI_RELATIVE) { xmlCtxtResetLastError(p->context_); p->context_->errNo = XML_ERR_OK; return true; 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/XMLParserTest.cpp b/Swiften/Parser/UnitTest/XMLParserTest.cpp index d38c1cc..89229c9 100644 --- a/Swiften/Parser/UnitTest/XMLParserTest.cpp +++ b/Swiften/Parser/UnitTest/XMLParserTest.cpp @@ -45,6 +45,7 @@ class XMLParserTest : public CppUnit::TestFixture { CPPUNIT_TEST(testParse_Doctype); CPPUNIT_TEST(testParse_ProcessingInstructions); CPPUNIT_TEST(testParse_ProcessingPrefixedElement); + CPPUNIT_TEST(testParse_InvalidlyEncodedInput); CPPUNIT_TEST_SUITE_END(); public: @@ -410,6 +411,20 @@ class XMLParserTest : public CppUnit::TestFixture { 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: diff --git a/Swiften/QA/TLSTest/CertificateTest.cpp b/Swiften/QA/TLSTest/CertificateTest.cpp index 624d953..463ef9e 100644 --- a/Swiften/QA/TLSTest/CertificateTest.cpp +++ b/Swiften/QA/TLSTest/CertificateTest.cpp @@ -35,6 +35,7 @@ class CertificateTest : public CppUnit::TestFixture { CPPUNIT_TEST(testGetXMPPAddresses); CPPUNIT_TEST(testCreateCertificateChain); CPPUNIT_TEST(testCreateTlsContext); + CPPUNIT_TEST(testCreateTlsContextDisableSystemTAs); CPPUNIT_TEST_SUITE_END(); public: @@ -130,6 +131,29 @@ class CertificateTest : public CppUnit::TestFixture { 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; 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/OpenSSL/OpenSSLCertificate.cpp b/Swiften/TLS/OpenSSL/OpenSSLCertificate.cpp index bb51428..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,7 +32,7 @@ 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(); } diff --git a/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp b/Swiften/TLS/OpenSSL/OpenSSLCertificateFactory.cpp index fd94ec8..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 { @@ -44,6 +45,11 @@ std::vector<std::shared_ptr<Certificate>> OpenSSLCertificateFactory::createCerti } } + // 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/OpenSSLContext.cpp b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp index 6dd75d6..86b0504 100644 --- a/Swiften/TLS/OpenSSL/OpenSSLContext.cpp +++ b/Swiften/TLS/OpenSSL/OpenSSLContext.cpp @@ -121,52 +121,57 @@ OpenSSLContext::OpenSSLContext(const TLSOptions& options, Mode mode) : mode_(mod // 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 = 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()); + 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); } @@ -202,7 +207,7 @@ static int certVerifyCallback(X509_STORE_CTX* store_ctx, void* arg) if (cb != nullptr) { ret = cb(static_cast<const OpenSSLContext*>(context)); } else { - SWIFT_LOG(warning) << "certVerifyCallback called but context.verifyCertCallback is unset" << std::endl; + SWIFT_LOG(debug) << "certVerifyCallback called but context.verifyCertCallback is unset"; ret = 0; } @@ -245,12 +250,12 @@ static int verifyCallback(int preverifyOk, X509_STORE_CTX* 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(error) << "verifyCallback: internal error" << std::endl; + SWIFT_LOG(debug) << "verifyCallback: internal error"; return preverifyOk; } if (SSL_CTX_get_verify_mode(sslctx) == SSL_VERIFY_NONE) { - SWIFT_LOG(info) << "verifyCallback: no verification required" << std::endl; + SWIFT_LOG(debug) << "verifyCallback: no verification required"; // No verification requested return 1; } @@ -281,14 +286,18 @@ static int verifyCallback(int preverifyOk, X509_STORE_CTX* ctx) X509_NAME* issuerName = X509_get_issuer_name(errCert); issuerString = X509_NAME_to_text(issuerName); } - SWIFT_LOG(error) << "verifyCallback: verification error" << - X509_verify_cert_error_string(err) << " depth: " << - depth << " issuer: " << ((issuerString.length() > 0) ? issuerString : "<unknown>") << std::endl; - } else { - SWIFT_LOG(info) << "verifyCallback: SSL depth: " << depth << " Subject: " << - ((subjectString.length() > 0) ? subjectString : "<>") << std::endl; - } - return preverifyOk; + 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) @@ -296,7 +305,7 @@ 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(error) << "Failed to set cipher-suites" << std::endl; + SWIFT_LOG(debug) << "Failed to set cipher-suites"; return false; } } @@ -307,7 +316,7 @@ bool OpenSSLContext::configure(const TLSOptions &options) if (SSL_CTX_set_session_id_context(context_.get(), reinterpret_cast<const unsigned char *>(contextId.c_str()), contextId.length()) != 1) { - SWIFT_LOG(error) << "Failed to set context-id" << std::endl; + SWIFT_LOG(debug) << "Failed to set context-id"; return false; } } @@ -315,12 +324,12 @@ bool OpenSSLContext::configure(const TLSOptions &options) if (options.sessionCacheTimeout) { int scto = *options.sessionCacheTimeout; if (scto <= 0) { - SWIFT_LOG(error) << "Invalid value for session-cache-timeout" << std::endl; + 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(error) << "Failed to set session-cache-timeout" << std::endl; + SWIFT_LOG(debug) << "Failed to set session-cache-timeout"; return false; } } @@ -362,7 +371,7 @@ bool OpenSSLContext::configure(const TLSOptions &options) if (options.verifyDepth) { int depth = *options.verifyDepth; if (depth <= 0) { - SWIFT_LOG(error) << "Invalid value for verify-depth" << std::endl; + SWIFT_LOG(debug) << "Invalid value for verify-depth"; return false; } @@ -584,7 +593,7 @@ void OpenSSLContext::sendPendingDataToApplication() { 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; } @@ -607,7 +616,7 @@ bool OpenSSLContext::setCertificateChain(const std::vector<std::shared_ptr<Certi } 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; } // Have to manually increment reference count as SSL_CTX_add_extra_chain_cert does not do so @@ -746,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/OpenSSLContextFactory.cpp b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp index 12445fd..e332ca8 100644 --- a/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp +++ b/Swiften/TLS/OpenSSL/OpenSSLContextFactory.cpp @@ -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/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/TLSOptions.h b/Swiften/TLS/TLSOptions.h index 4109096..e3faaf9 100644 --- a/Swiften/TLS/TLSOptions.h +++ b/Swiften/TLS/TLSOptions.h @@ -68,5 +68,10 @@ namespace Swift { * 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()); |