From ed94a2147dd8c7533e75ca7f050683014bed8588 Mon Sep 17 00:00:00 2001 From: anonimal Date: Wed, 15 Jun 2016 15:25:02 +0000 Subject: [PATCH 01/11] Log: finish pimpl refactor. Refs #33. Also: * Style refactor * Remove unused code * Document remaining code / add important notes --- src/core/CMakeLists.txt | 6 +- src/core/util/Log.cpp | 340 --------------------------- src/core/util/Log.h | 369 +++++++++--------------------- src/core/util/pimpl/Log.cpp | 443 ++++++++++++++++++++++++++++++++++++ 4 files changed, 551 insertions(+), 607 deletions(-) delete mode 100644 src/core/util/Log.cpp create mode 100644 src/core/util/pimpl/Log.cpp diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 4a1e7168..d42f8dd3 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -27,11 +27,11 @@ set(CORE_SRC "tunnel/TunnelGateway.cpp" "tunnel/TunnelPool.cpp" "util/Base64.cpp" + "util/Filesystem.cpp" "util/HTTP.cpp" - "util/Log.cpp" "util/MTU.cpp" - "util/Filesystem.cpp" - "util/ZIP.cpp") + "util/ZIP.cpp" + "util/pimpl/Log.cpp") if(CMAKE_SYSTEM_NAME STREQUAL "Windows") list(APPEND CORE_SRC "util/I2PEndian.cpp") diff --git a/src/core/util/Log.cpp b/src/core/util/Log.cpp deleted file mode 100644 index 19dd8e5a..00000000 --- a/src/core/util/Log.cpp +++ /dev/null @@ -1,340 +0,0 @@ -/** - * Copyright (c) 2013-2016, The Kovri I2P Router Project - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other - * materials provided with the distribution. - * - * 3. Neither the name of the copyright holder nor the names of its contributors may be - * used to endorse or promote products derived from this software without specific - * prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL - * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF - * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * Parts of the project are originally copyright (c) 2013-2015 The PurpleI2P Project - */ - -#include "Log.h" - -#include -#include - -namespace i2p { -namespace util { -namespace log { - -static std::shared_ptr g_Log = nullptr; -sink_ptr g_LogSink; - -// -// LogStreamImpl <- LogStream -// -LogStreamImpl::LogStreamImpl( - std::mutex& mtx, - log_t& l, - LogLevel level) - : m_Str(std::make_unique()), - m_Access(mtx), - m_Log(l), - m_Level(level), - m_Enable(true) { - // m_Log.add_global_attribute("Logger", m_ParentName); -} - -LogStreamImpl::~LogStreamImpl() {} - -void LogStreamImpl::WaitForReady() { - { - std::lock_guard lock(m_Access); - } -} - -LogStreamImpl::int_type LogStreamImpl::overflow( - int_type ch) { - return std::streambuf::overflow(ch); -} - -int LogStreamImpl::sync() { - int ret = 0; - ret = m_Str->pubsync(); - Flush(); - m_Access.unlock(); - return ret; -} - -// not thread safe -std::streamsize LogStreamImpl::xsputn( - const LogStreamImpl::char_type* s, - std::streamsize count) { - return m_Str->sputn(s, count); -} - -// not thread safe -void LogStreamImpl::Flush() { - if (g_Log->Silent()) { - // don't log if we are silent - return; - } - BOOST_LOG_SEV(m_Log, m_Level) << m_Str.get(); - m_Str = std::make_unique(); - g_LogSink->flush(); -} - -// -// LogStream -// -LogStream::LogStream( - LogStreamImpl* impl) - : std::ostream(impl), - m_Impl(impl) {} - -LogStream::~LogStream() { - delete m_Impl; -} - -LogStream& LogStream::Flush() { - g_LogSink->flush(); - return *this; -} - -bool LogStream::IsEnabled() { - return m_Impl->IsEnabled(); -} - -void LogStream::Disable() { - m_Impl->Disable(); -} - -void LogStream::Enable() { - m_Impl->Enable(); -} - -/** - * TODO(unassigned): implement - * LogStream& LogStream::Meta( - * const std::string& key, - * std::string value) { - * //TODO(unassigned): this doesn't do anything yet - * m_Impl->MetaImpl(key, value); - * return *this; - * } -*/ - -// -// LoggerImpl <- Logger -// -LoggerImpl::LoggerImpl( - const std::string& name, - const std::string& channel) - : log(boost::log::keywords::channel = channel), - m_Debug(new LogStreamImpl(m_DebugMtx, log, eLogDebug)), - m_Info(new LogStreamImpl(m_InfoMtx, log, eLogInfo)), - m_Warn(new LogStreamImpl(m_WarnMtx, log, eLogWarning)), - m_Error(new LogStreamImpl(m_ErrorMtx, log, eLogError)) { - log.add_attribute( - "LogName", - boost::log::attributes::constant< std::string >(name)); -} - -LoggerImpl::LoggerImpl() - : LoggerImpl("default", "default") {} - -LogStream& LoggerImpl::Debug() { - return GetLogger(m_Debug, m_DebugMtx); -} - -LogStream& LoggerImpl::Info() { - return GetLogger(m_Info, m_InfoMtx); -} - -LogStream& LoggerImpl::Warning() { - return GetLogger(m_Warn, m_WarnMtx); -} - -LogStream& LoggerImpl::Error() { - return GetLogger(m_Error, m_ErrorMtx); -} - -LogStream& LoggerImpl::GetLogger( - LogStream& l, - std::mutex & mtx) { - mtx.lock(); - return l; -} - -// -// Logger -// -Logger::Logger( - LoggerImpl* impl) - : m_Impl(impl) {} - -Logger::~Logger() { - delete m_Impl; -} - -LogStream& Logger::Error() { - return m_Impl->Error(); -} - -LogStream& Logger::Warning() { - return m_Impl->Warning(); -} - -LogStream& Logger::Info() { - return m_Impl->Info(); -} - -LogStream& Logger::Debug() { - return m_Impl->Debug(); -} - -void Logger::Flush() { - g_LogSink->flush(); -} - -// -// LogImpl <- Log -// -LogImpl::LogImpl( - LogLevel minlev, - std::ostream* out) { - m_Silent = false; - m_LogCore = boost::log::core::get(); - m_LogBackend = boost::make_shared(); - m_LogBackend->add_stream( - boost::shared_ptr( - out, - boost::null_deleter())); - g_LogSink = boost::shared_ptr( - new sink_t( - m_LogBackend)); - g_LogSink->set_filter( - boost::log::expressions::attr( - "Severity") >= minlev); - g_LogSink->set_formatter(&LogImpl::Format); - m_LogCore->add_sink(g_LogSink); - m_LogCore->add_global_attribute( - "Timestamp", - boost::log::attributes::local_clock()); -} - -void LogImpl::Format( - boost::log::record_view const& rec, - boost::log::formatting_ostream &s) { - // const boost::log::attribute_value_set& attrs = rec.attribute_values(); - static std::locale loc( - std::clog.getloc(), - new boost::posix_time::time_facet("%Y:%m:%d|%T.%f")); - std::stringstream ss; - ss.imbue(loc); - ss << boost::log::extract("Timestamp", rec) << ' '; - s << ss.str(); - s << boost::log::extract("Channel", rec) << ":"; - s << boost::log::extract("LogName", rec) << "\t\t"; - s << boost::log::extract("Severity", rec) << "\t\t"; - s << rec[boost::log::expressions::smessage]; -} - -void LogImpl::Flush() { - g_LogSink->flush(); -} - -void LogImpl::Stop() { - m_Silent = true; -} - -bool LogImpl::IsSilent() { - return m_Silent; -} - -// -// Log -// -Log::Log( - LogLevel minlev, - std::ostream* out) { - m_LogImpl = std::make_shared(minlev, out); - m_DefaultLogger = std::make_shared(new LoggerImpl); -} - -std::shared_ptr Log::Get() { - // make default logger if we don't have a logger - if (g_Log == nullptr) - g_Log = std::make_shared(eLogDebug, &std::clog); - return g_Log; -} - -std::shared_ptr Log::Default() { - return m_DefaultLogger; -} - -std::unique_ptr Log::New( - const std::string& name, - const std::string& channel) { - return std::unique_ptr( - new Logger( - new LoggerImpl( - name, - channel))); -} - -void Log::Stop() { - m_LogImpl->Stop(); -} - -bool Log::Silent() { - return m_LogImpl->IsSilent(); -} - -std::ostream& operator<<( - std::ostream& out, - LogLevel lev) { - static const char* levels[] = { - "DBG", // debug - "NFO", // info - "WRN", // warning - "ERR" // error - }; - if (static_cast(lev) < sizeof(levels) / sizeof(*levels)) { - out << levels[lev]; - } else { - out << "?" << static_cast(lev) << "?"; - } - return out; -} - -} // namespace log -} // namespace util -} // namespace i2p - -// -// Deprecated -// -void DeprecatedStartLog( - const std::string& fullFilePath) { - std::cerr << "Not opening log file: " << fullFilePath << std::endl; -} - -void DeprecatedStartLog( - std::ostream* s) { - *s << "Deprecated Logging not implemented" << std::endl; -} - -void DeprecatedStopLog() {} diff --git a/src/core/util/Log.h b/src/core/util/Log.h index 089c02af..6d3e2a25 100644 --- a/src/core/util/Log.h +++ b/src/core/util/Log.h @@ -33,52 +33,33 @@ #ifndef SRC_CORE_UTIL_LOG_H_ #define SRC_CORE_UTIL_LOG_H_ -#include - -#if BOOST_VERSION >= 105600 -#include -#else -// defines null_deleter here if we don't have the right boost version -#include -namespace boost { -struct null_deleter { - typedef void result_type; - template void operator() (T*) const {} -}; -} -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - #include #include -#include #include -#include - -// TODO(unassigned): remove these when removing deprecated logger -#define eLogDebug i2p::util::log::eLogLevelDebug -#define eLogInfo i2p::util::log::eLogLevelInfo -#define eLogWarning i2p::util::log::eLogLevelWarning -#define eLogError i2p::util::log::eLogLevelError namespace i2p { namespace util { namespace log { +/** + * + * Our flow is as follows (see Boost.Log): + * + * Kovri -> LogStream -> Logger -> Log -> UI + * + * ========================================= + * + * TODO(unassigned): + * Our current logging implementation is overwritten and convoluted. + * Our flow pattern is sound but a pimpl design for LogStream, Logger, + * and Log, serves no useful purpose (though *may* in the future). + * It should also be noted that to effectively remove deprecations, + * a design rewrite is necessary. + * + * Referencing #33. + * + */ + enum LogLevel { eLogLevelDebug, eLogLevelInfo, @@ -86,237 +67,97 @@ enum LogLevel { eLogLevelError }; -// core -typedef boost::log::core_ptr core_ptr; -// backend -typedef boost::log::sinks::text_ostream_backend backend_t; -typedef boost::shared_ptr backend_ptr; -// sink -typedef boost::log::sinks::asynchronous_sink sink_t; -typedef boost::shared_ptr sink_ptr; -// level -typedef boost::log::sources::severity_channel_logger_mt log_t; - -// -// LogStreamImpl <- LogStream -// -class LogStreamImpl : public std::streambuf { - public: - LogStreamImpl( - std::mutex& access, - log_t& l, - LogLevel levelno); - ~LogStreamImpl(); - - void MetaImpl( - const std::string& key, - std::string value); - - bool IsEnabled() { - return m_Enable; - } - - void Disable() { - m_Enable = false; - } - - void Enable() { - m_Enable = true; - } - - std::streambuf::int_type overflow( - std::streambuf::int_type ch); - - void WaitForReady(); - - protected: - int sync(); - std::streamsize xsputn( - const std::streambuf::char_type* s, - std::streamsize count); - - private: - void Flush(); - std::unique_ptr m_Str; - std::mutex& m_Access; - log_t& m_Log; - LogLevel m_Level; - bool m_Enable; -}; +#define eLogDebug i2p::util::log::eLogLevelDebug +#define eLogInfo i2p::util::log::eLogLevelInfo +#define eLogWarning i2p::util::log::eLogLevelWarning +#define eLogError i2p::util::log::eLogLevelError +class LogStreamImpl; class LogStream : public std::ostream { public: - explicit LogStream( - LogStreamImpl* impl); + LogStream(); ~LogStream(); - // TODO(unassigned): implement (currently unfinished) - // // attach metadata to the current logger's next entries until flushed - // LogStream& Meta( - // const std::string& key, - // std::string value); - - // flush this log stream - LogStream& Flush(); - - // check if this stream is enabled - // return true if it is - bool IsEnabled(); - - // disable logging on this stream - void Disable(); + LogStream( + LogStreamImpl* impl); - // enable logging on this stream + /// @brief Enable logging on this stream void Enable(); - private: - LogStreamImpl* m_Impl; -}; - -// // TODO(unassigned): implement (currently unfinished) -// class BoostEventStream : public EventStream { -// public: -// virtual EventStream& Flush() const {} -// virtual EventStream& operator <<( -// const std::vector& strs) const {} -// }; - -// -// LoggerImpl <- Logger -// -class LoggerImpl { - public: - // Construct default Logger - LoggerImpl(); - // Construct logger with a name that belongs in 1 log channel - LoggerImpl( - const std::string& name, - const std::string& channel); - - LogStream& Debug(); - LogStream& Info(); - LogStream& Warning(); - LogStream& Error(); + /// @brief Disable logging on this stream + void Disable(); - // TODO(unassigned): implement (currently unfinished) - // EventStream& UI() { - // return m_Events; - //} + /// @brief Flush this log stream + LogStream& Flush(); - log_t log; + /// @brief Check if this stream is enabled + /// @return True if stream is enabled + bool IsEnabled(); private: - LogStream& GetLogger( - LogStream& log, - std::mutex& mtx); - - std::mutex m_DebugMtx, - m_InfoMtx, - m_WarnMtx, - m_ErrorMtx; - - LogStream m_Debug, - m_Info, - m_Warn, - m_Error; - - // TODO(unassigned): implement (currently unfinished) - // BoostEventStream m_Events; + std::unique_ptr m_LogStreamPimpl; }; +class LoggerImpl; class Logger { public: + Logger(); + ~Logger(); + Logger( LoggerImpl* impl); - ~Logger(); - LogStream& Error(); - LogStream& Warning(); + /// @return Reference to info level log stream LogStream& Info(); - LogStream& Debug(); - - // TODO(unassigned): implement (currently unfinished) - // get EventStream to send events to UI - // EventStream& UI(); - // flush pending log events - void Flush(); + /// @return Reference to warning level log stream + LogStream& Warning(); - private: - LoggerImpl* m_Impl; -}; + /// @return Reference to error level log stream + LogStream& Error(); -// -// LogImpl <- Log -// -class LogImpl { - public: - LogImpl( - LogLevel minLevel, - std::ostream* out); - LogImpl() - : LogImpl( - eLogDebug, - &std::clog) {} + /// @return Reference to debug level log stream + LogStream& Debug(); + /// @brief Flush pending log events void Flush(); - void Stop(); - - bool IsSilent(); - private: - bool m_Silent; - backend_ptr m_LogBackend; - core_ptr m_LogCore; - static void Format( - boost::log::record_view const& rec, - boost::log::formatting_ostream &s); + std::unique_ptr m_LoggerPimpl; }; -/** - * // TODO(unassigned): implement (currently unfinished) - * // Stream for sending events to live UI - * class EventStream { - * public: - * // flush events - * virtual EventStream& Flush() const = 0; - * // operator overload for << - * // queue an event - * virtual EventStream& operator <<( - * const std::vector & strs) const = 0; - * }; - */ - +class LogImpl; class Log { public: + Log(); + ~Log(); + Log( - LogLevel minLev, - std::ostream* out); - Log() - : Log( - eLogLevelWarning, - &std::clog) {} - - // Get global log engine + LogLevel min_level, + std::ostream* out_stream); + + /// @brief Get global log engine static std::shared_ptr Get(); - // Get default logger + /// @brief Get default logger std::shared_ptr Default(); - // Create a logger's given name - std::unique_ptr New( - const std::string& name, - const std::string& channel); + // TODO(unassigned): + // Uncomment when this becomes useful + /// @brief Create a logger's given name + //std::unique_ptr New( + //const std::string& name, + //const std::string& channel); - // turn off logging forever + /// @brief Turn off logging forever void Stop(); - // is logging silent right now? + /// @brief Is logging silent right now? + /// @return True if silent bool Silent(); private: - std::shared_ptr m_LogImpl; + std::shared_ptr m_LogPimpl; std::shared_ptr m_DefaultLogger; }; @@ -324,76 +165,76 @@ class Log { } // namespace util } // namespace i2p -// -// Deprecated Logger -// - -#include +/** + * + * Deprecated Logger + * + */ void DeprecatedStartLog( - const std::string& fullFilePath); + const std::string& full_file_path); void DeprecatedStartLog( - std::ostream* s); + std::ostream* stream); void DeprecatedStopLog(); -template +template void DeprecatedLog( - std::ostream& s, - TValue arg) { - s << arg; + std::ostream& stream, + Arg arg) { + stream << arg; } -template +template void DeprecatedLog( - std::ostream& s, - TValue arg, - TArgs... args) { - DeprecatedLog(s, arg); - DeprecatedLog(s, args...); + std::ostream& stream, + Value arg, + Args... args) { + DeprecatedLog(stream, arg); + DeprecatedLog(stream, args...); } -template +template void DeprecatedLogPrint( i2p::util::log::LogLevel level, - TArgs... args) { - auto l = i2p::util::log::Log::Get(); - if (l == nullptr) { + Args... args) { + auto logger = i2p::util::log::Log::Get(); + if (logger == nullptr) { // fallback logging to std::clog std::clog << "!!! "; DeprecatedLog(std::clog, args...); std::clog << std::endl; } else { - auto log = l->Default(); + auto log = logger->Default(); if (level == eLogDebug) { - auto& s = log->Debug(); - DeprecatedLog(s, args...); - s << std::flush; + auto& stream = log->Debug(); + DeprecatedLog(stream, args...); + stream << std::flush; } else if (level == eLogInfo) { - auto& s = log->Info(); - DeprecatedLog(s, args...); - s << std::flush; + auto& stream = log->Info(); + DeprecatedLog(stream, args...); + stream << std::flush; } else if (level == eLogWarning) { - auto& s = log->Warning(); - DeprecatedLog(s, args...); - s << std::flush; + auto& stream = log->Warning(); + DeprecatedLog(stream, args...); + stream << std::flush; } else { - auto& s = log->Error(); - DeprecatedLog(s, args...); - s << std::flush; + auto& stream = log->Error(); + DeprecatedLog(stream, args...); + stream << std::flush; } } } -template +template void DeprecatedLogPrint( - TArgs... args) { + Args... args) { DeprecatedLogPrint(eLogInfo, args...); } -#define StopLog DeprecatedStopLog #define StartLog DeprecatedStartLog #define LogPrint DeprecatedLogPrint +#define StopLog DeprecatedStopLog #endif // SRC_CORE_UTIL_LOG_H_ diff --git a/src/core/util/pimpl/Log.cpp b/src/core/util/pimpl/Log.cpp new file mode 100644 index 00000000..2ef50d3c --- /dev/null +++ b/src/core/util/pimpl/Log.cpp @@ -0,0 +1,443 @@ +/** + * Copyright (c) 2013-2016, The Kovri I2P Router Project + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other + * materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors may be + * used to endorse or promote products derived from this software without specific + * prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Parts of the project are originally copyright (c) 2013-2015 The PurpleI2P Project + */ + +#include "core/util/Log.h" + +#include + +#if BOOST_VERSION >= 105600 +#include +#else +// defines null_deleter here if we don't have the right boost version +#include +namespace boost { +struct null_deleter { + typedef void result_type; + template void operator() (T*) const {} +}; +} +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace i2p { +namespace util { +namespace log { + +/// @typedef core_ptr +/// @brief Boost.Log core pointer +typedef boost::log::core_ptr core_ptr; + +/// @typedef backend_t +/// @brief Boost.Log text ostream backend sink +typedef boost::log::sinks::text_ostream_backend backend_t; + +/// @typedef backend_ptr +/// @brief Shared pointer to backend sink +typedef boost::shared_ptr backend_ptr; + +/// @typedef sink_t +/// @brief Boost.Log asynchronous sink +typedef boost::log::sinks::asynchronous_sink sink_t; + +/// @typedef sink_ptr +/// @brief Shared pointer to sink +typedef boost::shared_ptr sink_ptr; + +/// @var g_LogSink +/// @brief sink pointer to global log sink +sink_ptr g_LogSink; + +/// @var g_Log +/// @brief Shared pointer to global log +static std::shared_ptr g_Log = nullptr; + +/// @typedef log_t +/// @brief Log level/severity channel +typedef boost::log::sources::severity_channel_logger_mt log_t; + +/** + * + * LogStream implementation and definitions + * + */ + +/// @class LogStreamImpl +class LogStreamImpl : public std::streambuf { + public: + LogStreamImpl( + std::mutex& mtx, + log_t& log, + LogLevel level) + : m_Str(std::make_unique()), + m_Access(mtx), + m_Log(log), + m_Level(level), + m_Enabled(true) {} + + ~LogStreamImpl() {} + + void Enable() { + m_Enabled = true; + } + + void Disable() { + m_Enabled = false; + } + + /// @note Not thread safe + void Flush() { + if (g_Log->Silent()) { + // Don't log if we are silent + return; + } + BOOST_LOG_SEV(m_Log, m_Level) << m_Str.get(); + m_Str = std::make_unique(); + g_LogSink->flush(); + } + + bool IsEnabled() { + return m_Enabled; + } + + void WaitForReady() { + { + std::lock_guard lock(m_Access); + } + } + + std::streambuf::int_type overflow( + int_type ch) { + return std::streambuf::overflow(ch); + } + + protected: + int sync() { + int ret = 0; + ret = m_Str->pubsync(); + Flush(); + m_Access.unlock(); + return ret; + } + + /// @note Not thread safe + std::streamsize xsputn( + const std::streambuf::char_type* s, + std::streamsize count) { + return m_Str->sputn(s, count); + } + + private: + std::unique_ptr m_Str; + std::mutex& m_Access; + log_t& m_Log; + LogLevel m_Level; + bool m_Enabled; +}; + +LogStream::LogStream() {} +LogStream::~LogStream() {} + +LogStream::LogStream( + LogStreamImpl* impl) + : std::ostream(impl), + m_LogStreamPimpl(impl) {} + +void LogStream::Enable() { + m_LogStreamPimpl->Enable(); +} + +void LogStream::Disable() { + m_LogStreamPimpl->Disable(); +} + +LogStream& LogStream::Flush() { + m_LogStreamPimpl->Flush(); + return *this; +} + +bool LogStream::IsEnabled() { + return m_LogStreamPimpl->IsEnabled(); +} + +/** + * + * Logger implementation and definitions + * + */ + +/// @class LoggerImpl +class LoggerImpl { + public: + /// @brief Construct default Logger + LoggerImpl() + : LoggerImpl("default", "default") {} + + ~LoggerImpl() {} + + /// @brief Construct logger with a name that belongs in 1 log channel + LoggerImpl( + const std::string& name, + const std::string& channel) + : m_Log(boost::log::keywords::channel = channel), + m_Info(new LogStreamImpl(m_InfoMtx, m_Log, eLogInfo)), + m_Warn(new LogStreamImpl(m_WarnMtx, m_Log, eLogWarning)), + m_Error(new LogStreamImpl(m_ErrorMtx, m_Log, eLogError)), + m_Debug(new LogStreamImpl(m_DebugMtx, m_Log, eLogDebug)) { + m_Log.add_attribute( + "LogName", + boost::log::attributes::constant(name)); + } + + LogStream& Error() { + return GetLogger(m_Error, m_ErrorMtx); + } + + LogStream& Warning() { + return GetLogger(m_Warn, m_WarnMtx); + } + + LogStream& Info() { + return GetLogger(m_Info, m_InfoMtx); + } + + LogStream& Debug() { + return GetLogger(m_Debug, m_DebugMtx); + } + + void Flush() { + g_LogSink->flush(); + } + + private: + /// @brief Lock mutex and return log stream + /// @return Reference to LogStream + LogStream& GetLogger( + LogStream& stream, + std::mutex& mtx) { + mtx.lock(); + return stream; + } + + private: + log_t m_Log; + LogStream m_Info, m_Warn, m_Error, m_Debug; + std::mutex m_InfoMtx, m_WarnMtx, m_ErrorMtx, m_DebugMtx; +}; + +Logger::Logger() {} +Logger::~Logger() {} + +Logger::Logger( + LoggerImpl* impl) + : m_LoggerPimpl(impl) {} + +LogStream& Logger::Error() { + return m_LoggerPimpl->Error(); +} + +LogStream& Logger::Warning() { + return m_LoggerPimpl->Warning(); +} + +LogStream& Logger::Info() { + return m_LoggerPimpl->Info(); +} + +LogStream& Logger::Debug() { + return m_LoggerPimpl->Debug(); +} + +void Logger::Flush() { + m_LoggerPimpl->Flush(); +} + +/** + * + * Log implementation and definitions + * + */ + +/// @class LogImpl +class LogImpl { + public: + LogImpl() : LogImpl(eLogDebug, &std::clog) {} + + ~LogImpl() {} + + LogImpl( + LogLevel min_level, + std::ostream* out_stream) { + // Running + m_Silent = false; + // Backend + m_LogBackend = boost::make_shared(); + m_LogBackend->add_stream(boost::shared_ptr(out_stream, boost::null_deleter())); + // Sink + g_LogSink = boost::shared_ptr(new sink_t(m_LogBackend)); + g_LogSink->set_filter(boost::log::expressions::attr("Severity") >= min_level); + g_LogSink->set_formatter(&LogImpl::Format); + // Core + m_LogCore = boost::log::core::get(); + m_LogCore->add_sink(g_LogSink); + m_LogCore->add_global_attribute("Timestamp", boost::log::attributes::local_clock()); + } + + void Flush() { + g_LogSink->flush(); + } + + void Stop() { + m_Silent = true; + } + + bool IsSilent() { + return m_Silent; + } + + private: + static void Format( + boost::log::record_view const& rec, + boost::log::formatting_ostream &stream) { + // const boost::log::attribute_value_set& attrs = rec.attribute_values(); + static std::locale loc( + std::clog.getloc(), + new boost::posix_time::time_facet("%Y:%m:%d|%T.%f")); + std::stringstream ss; + ss.imbue(loc); + ss << boost::log::extract("Timestamp", rec); + stream << ss.str(); + stream << boost::log::extract("Channel", rec) << ":"; + stream << boost::log::extract("LogName", rec) << "\t\t"; + stream << boost::log::extract("Severity", rec) << "\t\t"; + stream << rec[boost::log::expressions::smessage]; + } + + private: + backend_ptr m_LogBackend; + core_ptr m_LogCore; + bool m_Silent; +}; + +Log::Log() : Log(eLogDebug, &std::clog) {} +Log::~Log() {} + +Log::Log( + LogLevel min_level, + std::ostream* out_stream) { + m_LogPimpl = std::make_shared(min_level, out_stream); + m_DefaultLogger = std::make_shared(new LoggerImpl); +} + +void Log::Stop() { + m_LogPimpl->Stop(); +} + +bool Log::Silent() { + return m_LogPimpl->IsSilent(); +} + +std::shared_ptr Log::Get() { + // Make default logger if we don't have a logger + if (g_Log == nullptr) + g_Log = std::make_shared(eLogDebug, &std::clog); + return g_Log; +} + +std::shared_ptr Log::Default() { + return m_DefaultLogger; +} + +// TODO(unassigned): +// Uncomment when this becomes useful +//std::unique_ptr Log::New( + //const std::string& name, + //const std::string& channel) { + //return std::unique_ptr(new Logger(new LoggerImpl(name, channel))); +//} + +std::ostream& operator<<( + std::ostream& out_stream, + LogLevel log_level) { + static const char* levels[] = { + "DBG", // debug + "NFO", // info + "WRN", // warning + "ERR" // error + }; + if (static_cast(log_level) < sizeof(levels) / sizeof(*levels)) { + out_stream << levels[log_level]; + } else { + out_stream << "Invalid log level: " << static_cast(log_level); + } + return out_stream; +} + +} // namespace log +} // namespace util +} // namespace i2p + +/** + * + * Deprecated Logger + * + */ + +void DeprecatedStartLog( + const std::string& full_file_path) { + std::cerr << "Not opening log file: " << full_file_path << std::endl; +} + +void DeprecatedStartLog( + std::ostream* stream) { + *stream << "Deprecated Logging not implemented" << std::endl; +} + +void DeprecatedStopLog() {} From 093dd656e073f4d534abfc9fee983056864b2b4c Mon Sep 17 00:00:00 2001 From: anonimal Date: Wed, 15 Jun 2016 15:29:55 +0000 Subject: [PATCH 02/11] Log: s/GetLogger/GetLogStream/ in LoggerImpl. --- src/core/util/pimpl/Log.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/core/util/pimpl/Log.cpp b/src/core/util/pimpl/Log.cpp index 2ef50d3c..c16274d7 100644 --- a/src/core/util/pimpl/Log.cpp +++ b/src/core/util/pimpl/Log.cpp @@ -237,19 +237,19 @@ class LoggerImpl { } LogStream& Error() { - return GetLogger(m_Error, m_ErrorMtx); + return GetLogStream(m_Error, m_ErrorMtx); } LogStream& Warning() { - return GetLogger(m_Warn, m_WarnMtx); + return GetLogStream(m_Warn, m_WarnMtx); } LogStream& Info() { - return GetLogger(m_Info, m_InfoMtx); + return GetLogStream(m_Info, m_InfoMtx); } LogStream& Debug() { - return GetLogger(m_Debug, m_DebugMtx); + return GetLogStream(m_Debug, m_DebugMtx); } void Flush() { @@ -259,7 +259,7 @@ class LoggerImpl { private: /// @brief Lock mutex and return log stream /// @return Reference to LogStream - LogStream& GetLogger( + LogStream& GetLogStream( LogStream& stream, std::mutex& mtx) { mtx.lock(); From 833412450e51bb974d40766afb3f5fc6cf4c651a Mon Sep 17 00:00:00 2001 From: anonimal Date: Wed, 15 Jun 2016 15:39:21 +0000 Subject: [PATCH 03/11] Log: C++11/14 refactor of ostream operator<< --- src/core/util/pimpl/Log.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/core/util/pimpl/Log.cpp b/src/core/util/pimpl/Log.cpp index c16274d7..413c672e 100644 --- a/src/core/util/pimpl/Log.cpp +++ b/src/core/util/pimpl/Log.cpp @@ -406,14 +406,14 @@ std::shared_ptr Log::Default() { std::ostream& operator<<( std::ostream& out_stream, LogLevel log_level) { - static const char* levels[] = { + static std::array levels { "DBG", // debug "NFO", // info "WRN", // warning "ERR" // error }; - if (static_cast(log_level) < sizeof(levels) / sizeof(*levels)) { - out_stream << levels[log_level]; + if (static_cast(log_level) < levels.size()) { + out_stream << levels.at(log_level); } else { out_stream << "Invalid log level: " << static_cast(log_level); } From ba5fc9e6abb4b70c47e0be54c3b7eaae662b9d9a Mon Sep 17 00:00:00 2001 From: anonimal Date: Wed, 15 Jun 2016 15:46:52 +0000 Subject: [PATCH 04/11] Log: improve/cleanup stream formatting. --- src/core/util/pimpl/Log.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/core/util/pimpl/Log.cpp b/src/core/util/pimpl/Log.cpp index 413c672e..a42a09e6 100644 --- a/src/core/util/pimpl/Log.cpp +++ b/src/core/util/pimpl/Log.cpp @@ -346,7 +346,6 @@ class LogImpl { static void Format( boost::log::record_view const& rec, boost::log::formatting_ostream &stream) { - // const boost::log::attribute_value_set& attrs = rec.attribute_values(); static std::locale loc( std::clog.getloc(), new boost::posix_time::time_facet("%Y:%m:%d|%T.%f")); @@ -354,9 +353,11 @@ class LogImpl { ss.imbue(loc); ss << boost::log::extract("Timestamp", rec); stream << ss.str(); - stream << boost::log::extract("Channel", rec) << ":"; - stream << boost::log::extract("LogName", rec) << "\t\t"; - stream << boost::log::extract("Severity", rec) << "\t\t"; + // TODO(unassigned): + // When these become useful, uncomment and tweak + //stream << "|" << boost::log::extract("Channel", rec) << ":"; + //stream << boost::log::extract("LogName", rec); + stream << "|" << boost::log::extract("Severity", rec) << " "; stream << rec[boost::log::expressions::smessage]; } From 7906dfc90c84bb67afaba4be6a29a3da352b21aa Mon Sep 17 00:00:00 2001 From: anonimal Date: Wed, 15 Jun 2016 15:59:36 +0000 Subject: [PATCH 05/11] Daemon: minor log member style refactor. --- src/app/Daemon.cpp | 4 ++-- src/app/Daemon.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/app/Daemon.cpp b/src/app/Daemon.cpp index 495b7fa0..ca3cf2d3 100644 --- a/src/app/Daemon.cpp +++ b/src/app/Daemon.cpp @@ -59,7 +59,7 @@ namespace util { Daemon_Singleton::Daemon_Singleton() : m_IsRunning(true), - m_log(i2p::util::log::Log::Get()) {} + m_Log(i2p::util::log::Log::Get()) {} Daemon_Singleton::~Daemon_Singleton() {} bool Daemon_Singleton::IsService() const { @@ -123,7 +123,7 @@ bool Daemon_Singleton::Start() { StartLog(""); // write to stdout } } else { - m_log->Stop(); + m_Log->Stop(); } try { LogPrint(eLogInfo, "Daemon_Singleton: starting NetDb"); diff --git a/src/app/Daemon.h b/src/app/Daemon.h index 2f4f3f78..4837146d 100644 --- a/src/app/Daemon.h +++ b/src/app/Daemon.h @@ -67,7 +67,7 @@ class Daemon_Singleton { Daemon_Singleton(); virtual ~Daemon_Singleton(); bool IsService() const; - std::shared_ptr m_log; + std::shared_ptr m_Log; }; #ifdef _WIN32 From 20b4f27dfb11bb3320c6f9013bb080b67ab858e7 Mon Sep 17 00:00:00 2001 From: anonimal Date: Sat, 18 Jun 2016 05:59:09 +0000 Subject: [PATCH 06/11] Log: implement log-levels runtime capability. * Resolves #183 --- src/app/util/Config.cpp | 50 +++++++++++++++++++++++++++++- src/app/util/Config.h | 4 +++ src/core/util/Log.h | 61 +++++++++++++++++++++++++++++-------- src/core/util/pimpl/Log.cpp | 31 +++++++++++++++++++ 4 files changed, 132 insertions(+), 14 deletions(-) diff --git a/src/app/util/Config.cpp b/src/app/util/Config.cpp index 308d48b5..0daf2711 100644 --- a/src/app/util/Config.cpp +++ b/src/app/util/Config.cpp @@ -31,8 +31,10 @@ #include "Config.h" #include +#include -#include +#include "core/util/Log.h" +#include "crypto/Rand.h" namespace i2p { namespace util { @@ -104,6 +106,17 @@ bool ParseArgs( "Enable or disable logging to file\n" "1 = enabled, 0 = disabled\n") + ("log-levels", bpo::value>()-> + // Note: we set a default value during validation and + // leave blank here to prevent bad_any_cast exception. + default_value(std::vector(), "")->multitoken(), + "Log levels to report.\n" + "Options: info warn error debug\n" + "Examples:\n" + "./kovri --log-levels info # produces info only\n" + "./kovri --log-levels warn error # warn/error only\n" + "Default: all levels [info warn error debug]\n") + ("daemon,d", bpo::value()->default_value(0), "Enable or disable daemon mode\n" "1 = enabled, 0 = disabled\n") @@ -220,6 +233,9 @@ bool ParseArgs( bpo::notify(var_map); // Parse config after mapping cli ParseConfigFile(kovri_config, config_options, var_map); + // Validate user input where possible + if (!ValidateUserInput()) + return false; /* * Display --help and --help-with */ @@ -271,6 +287,38 @@ void ParseConfigFile( } } +bool ValidateUserInput() { + /** + * TODO(unassigned): write custom validator for log-levels + * so we can set values via config file. + */ + // Test for valid log-levels input + auto arg_levels = var_map["log-levels"].as>(); + auto global_levels = i2p::util::log::GetGlobalLogLevels(); + if (arg_levels.size()) { + if (arg_levels.size() > global_levels.size()) { + std::cout << "Invalid number of log levels. Maximum allowed: " + << global_levels.size() << std::endl; + return false; + } + // Verify validity of log levels + for (auto& level : arg_levels) { + auto result = global_levels.find(level); + if (result == global_levels.end()) { + std::cout << "Invalid log-level(s). See help for options" << std::endl; + return false; + } + } + } else { + // Set default log-levels if none present + for (auto& level : global_levels) + arg_levels.push_back(level.first); + } + // Set new global log-levels + i2p::util::log::SetGlobalLogLevels(arg_levels); + return true; +} + } // namespace config } // namespace util } // namespace i2p diff --git a/src/app/util/Config.h b/src/app/util/Config.h index cf546594..36333ed7 100644 --- a/src/app/util/Config.h +++ b/src/app/util/Config.h @@ -84,6 +84,10 @@ void ParseConfigFile( boost::program_options::options_description& config_options, boost::program_options::variables_map& var_map); +/// @brief Validates user input where possible +/// @return False on failure +bool ValidateUserInput(); + } // namespace config } // namespace util } // namespace i2p diff --git a/src/core/util/Log.h b/src/core/util/Log.h index 6d3e2a25..2a3af111 100644 --- a/src/core/util/Log.h +++ b/src/core/util/Log.h @@ -36,6 +36,8 @@ #include #include #include +#include +#include namespace i2p { namespace util { @@ -72,6 +74,18 @@ enum LogLevel { #define eLogWarning i2p::util::log::eLogLevelWarning #define eLogError i2p::util::log::eLogLevelError +/// @typedef LogLevelsMap +/// @brief Map of log levels +typedef std::unordered_map LogLevelsMap; + +/// @brief Set log levels/severity +void SetGlobalLogLevels( + const std::vector& levels); + +/// @brief Get log levels/severity +/// @return Log levels/severity +const LogLevelsMap& GetGlobalLogLevels(); + class LogStreamImpl; class LogStream : public std::ostream { public: @@ -195,6 +209,7 @@ void DeprecatedLog( DeprecatedLog(stream, args...); } +// TODO(unassigned): more efficient way to execute this function. template void DeprecatedLogPrint( i2p::util::log::LogLevel level, @@ -206,23 +221,43 @@ void DeprecatedLogPrint( DeprecatedLog(std::clog, args...); std::clog << std::endl; } else { + // Set log implementation auto log = logger->Default(); + // Get global log levels + auto global_levels = i2p::util::log::GetGlobalLogLevels(); + // Print log after testing arg level against global levels if (level == eLogDebug) { - auto& stream = log->Debug(); - DeprecatedLog(stream, args...); - stream << std::flush; + for (auto& current_level : global_levels) { + if (current_level.second == eLogDebug) { + auto& stream = log->Debug(); + DeprecatedLog(stream, args...); + stream << std::flush; + } + } } else if (level == eLogInfo) { - auto& stream = log->Info(); - DeprecatedLog(stream, args...); - stream << std::flush; + for (auto& current_level : global_levels) { + if (current_level.second == eLogInfo) { + auto& stream = log->Info(); + DeprecatedLog(stream, args...); + stream << std::flush; + } + } } else if (level == eLogWarning) { - auto& stream = log->Warning(); - DeprecatedLog(stream, args...); - stream << std::flush; - } else { - auto& stream = log->Error(); - DeprecatedLog(stream, args...); - stream << std::flush; + for (auto& current_level : global_levels) { + if (current_level.second == eLogWarning) { + auto& stream = log->Warning(); + DeprecatedLog(stream, args...); + stream << std::flush; + } + } + } else if (level == eLogError) { + for (auto& current_level : global_levels) { + if (current_level.second == eLogError) { + auto& stream = log->Error(); + DeprecatedLog(stream, args...); + stream << std::flush; + } + } } } } diff --git a/src/core/util/pimpl/Log.cpp b/src/core/util/pimpl/Log.cpp index a42a09e6..0ac27691 100644 --- a/src/core/util/pimpl/Log.cpp +++ b/src/core/util/pimpl/Log.cpp @@ -66,11 +66,42 @@ struct null_deleter { #include #include #include +#include namespace i2p { namespace util { namespace log { +/// @var g_LogLevels +/// @brief Maps string global levels to enumerated global levels +LogLevelsMap g_LogLevels { + { "info", eLogInfo }, + { "warn", eLogWarning }, + { "error", eLogError }, + { "debug", eLogDebug }, +}; + +/// @brief Sets global log levels with sanitized user input +/// @param levels String vector of user-supplied log levels +void SetGlobalLogLevels( + const std::vector& levels) { + // Create temporary map for new global levels + LogLevelsMap new_levels; + // Iterate and insert into new global map + for (auto& v : levels) { + auto key = g_LogLevels.find(v); + if (key != g_LogLevels.end()) + new_levels.insert({v, g_LogLevels[v]}); + } + // Set new global map + g_LogLevels.swap(new_levels); +} + +/// @brief Returns current state of global lob levels +const LogLevelsMap& GetGlobalLogLevels() { + return g_LogLevels; +} + /// @typedef core_ptr /// @brief Boost.Log core pointer typedef boost::log::core_ptr core_ptr; From 456d7182491ccd8655caf5aeb5f687ef32f04416 Mon Sep 17 00:00:00 2001 From: anonimal Date: Sat, 18 Jun 2016 06:11:05 +0000 Subject: [PATCH 07/11] Kovri: s/Warning/Warn/g for consistency with Log. --- src/app/Daemon.cpp | 6 +++--- src/client/AddressBook.cpp | 6 +++--- src/client/ClientContext.cpp | 2 +- src/client/Datagram.cpp | 10 +++++----- src/client/Destination.cpp | 10 +++++----- src/client/I2PControl/I2PControl.cpp | 4 ++-- src/client/I2PService.cpp | 2 +- src/client/I2PTunnel/HTTPProxy.cpp | 2 +- src/client/I2PTunnel/I2PTunnel.cpp | 4 ++-- src/client/I2PTunnel/SOCKS.cpp | 6 +++--- src/client/Streaming.cpp | 22 +++++++++++----------- src/core/Garlic.cpp | 10 +++++----- src/core/I2NPProtocol.cpp | 6 +++--- src/core/Identity.cpp | 8 ++++---- src/core/LeaseSet.cpp | 2 +- src/core/NetDbRequests.cpp | 8 ++++---- src/core/NetworkDatabase.cpp | 10 +++++----- src/core/Profiling.cpp | 4 ++-- src/core/RouterInfo.cpp | 2 +- src/core/transport/NTCPSession.cpp | 8 ++++---- src/core/transport/SSU.cpp | 4 ++-- src/core/transport/SSUData.cpp | 14 +++++++------- src/core/transport/SSUSession.cpp | 14 +++++++------- src/core/tunnel/Tunnel.cpp | 4 ++-- src/core/tunnel/TunnelPool.cpp | 6 +++--- src/core/util/Log.h | 12 ++++++------ src/core/util/MTU.cpp | 2 +- src/core/util/ZIP.cpp | 4 ++-- src/core/util/pimpl/Log.cpp | 12 ++++++------ 29 files changed, 102 insertions(+), 102 deletions(-) diff --git a/src/app/Daemon.cpp b/src/app/Daemon.cpp index ca3cf2d3..195a8c07 100644 --- a/src/app/Daemon.cpp +++ b/src/app/Daemon.cpp @@ -206,7 +206,7 @@ void Daemon_Singleton::SetupTunnels() { try { boost::property_tree::read_ini(path_tunnels_config_file, pt); } catch(const std::exception& ex) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Daemon_Singleton: can't read ", path_tunnels_config_file, ": ", ex.what()); return; @@ -287,7 +287,7 @@ void Daemon_Singleton::SetupTunnels() { local_destination->GetIdentHash()), " already exists"); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Daemon_Singleton: unknown section type=", type, " of ", name, " in ", path_tunnels_config_file); } @@ -309,7 +309,7 @@ void Daemon_Singleton::ReloadTunnels() { try { boost::property_tree::read_ini(tunnels_config_file, pt); } catch (const std::exception& ex) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Daemon_Singleton: can't read ", tunnels_config_file, ": ", ex.what()); return; diff --git a/src/client/AddressBook.cpp b/src/client/AddressBook.cpp index e0d933f5..22427086 100644 --- a/src/client/AddressBook.cpp +++ b/src/client/AddressBook.cpp @@ -162,7 +162,7 @@ int AddressBookFilesystemStorage::Load( LogPrint(eLogInfo, "AddressBookFilesystemStorage: ", num, " addresses loaded"); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "AddressBookFilesystemStorage: ", filename, " not found"); } return num; @@ -390,7 +390,7 @@ void AddressBook::LoadSubscriptions() { LogPrint(eLogInfo, "AddressBook: ", m_Subscriptions.size(), " subscriptions loaded"); } else { - LogPrint(eLogWarning, "AddressBook: subscriptions.txt not found"); + LogPrint(eLogWarn, "AddressBook: subscriptions.txt not found"); } } else { LogPrint(eLogError, "AddressBook: subscriptions already loaded"); @@ -602,7 +602,7 @@ void AddressBookSubscription::Request() { LogPrint(eLogInfo, "AddressBookSubscription: no updates from ", m_Link); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "AddressBookSubscription: HTTP response ", status); } } else { diff --git a/src/client/ClientContext.cpp b/src/client/ClientContext.cpp index 1d9fc85b..7fe8499c 100644 --- a/src/client/ClientContext.cpp +++ b/src/client/ClientContext.cpp @@ -171,7 +171,7 @@ std::shared_ptr ClientContext::LoadLocalDestination( std::unique_lock l(m_DestinationsMutex); auto it = m_Destinations.find(keys.GetPublic().GetIdentHash()); if (it != m_Destinations.end()) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "ClientContext: local destination ", m_AddressBook.ToAddress(keys.GetPublic().GetIdentHash()), " already exists"); diff --git a/src/client/Datagram.cpp b/src/client/Datagram.cpp index eb46f95c..e8d40684 100644 --- a/src/client/Datagram.cpp +++ b/src/client/Datagram.cpp @@ -116,10 +116,10 @@ void DatagramDestination::SendMsg( outboundTunnel->SendTunnelDataMsg(msgs); } else { if (outboundTunnel) - LogPrint(eLogWarning, + LogPrint(eLogWarn, "DatagramDestination: failed to send datagram: all leases expired"); else - LogPrint(eLogWarning, + LogPrint(eLogWarn, "DatagramDestination: failed to send datagram: no outbound tunnels"); DeleteI2NPMessage(msg); } @@ -152,10 +152,10 @@ void DatagramDestination::HandleDatagram( m_Receiver( identity, fromPort, toPort, buf + headerLen, len - headerLen); else - LogPrint(eLogWarning, + LogPrint(eLogWarn, "DatagramDestination: receiver for datagram is not set"); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "DatagramDestination: datagram signature verification failed"); } } @@ -174,7 +174,7 @@ void DatagramDestination::HandleDataMessagePayload( decompressor.Get(uncompressed, uncompressedLen); HandleDatagram(fromPort, toPort, uncompressed, uncompressedLen); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "DatagramDestination: the received datagram size ", uncompressedLen, " exceeds max size"); } diff --git a/src/client/Destination.cpp b/src/client/Destination.cpp index 2953a8cf..0c5353b8 100644 --- a/src/client/Destination.cpp +++ b/src/client/Destination.cpp @@ -411,7 +411,7 @@ void ClientDestination::HandleDatabaseSearchReplyMessage( m_LeaseSetRequests.erase(key); } } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "ClientDestination: request for ", key.ToBase64(), " not found"); } } @@ -488,7 +488,7 @@ void ClientDestination::HandlePublishConfirmationTimer( const boost::system::error_code& ecode) { if (ecode != boost::asio::error::operation_aborted) { if (m_PublishReplyToken) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "ClientDestination: publish confirmation was not received in ", PUBLISH_CONFIRMATION_TIMEOUT, "seconds. Try again"); m_PublishReplyToken = 0; @@ -512,7 +512,7 @@ void ClientDestination::HandleDataMessage( if (dest) dest->HandleDataMessagePayload(buf, length); else - LogPrint(eLogWarning, + LogPrint(eLogWarn, "ClientDestination: missing streaming destination"); } break; @@ -525,11 +525,11 @@ void ClientDestination::HandleDataMessage( buf, length); else - LogPrint(eLogWarning, + LogPrint(eLogWarn, "ClientDestination: missing streaming destination"); break; default: - LogPrint(eLogWarning, + LogPrint(eLogWarn, "ClientDestination: HandleDataMessage(): unexpected protocol ", buf[9]); } } diff --git a/src/client/I2PControl/I2PControl.cpp b/src/client/I2PControl/I2PControl.cpp index 9b462205..9865b027 100644 --- a/src/client/I2PControl/I2PControl.cpp +++ b/src/client/I2PControl/I2PControl.cpp @@ -303,7 +303,7 @@ I2PControlSession::Response I2PControlSession::HandleRequest( std::string method = pt.get(constants::PROPERTY_METHOD); auto it = m_MethodHandlers.find(method); if (it == m_MethodHandlers.end()) { // Not found - LogPrint(eLogWarning, + LogPrint(eLogWarn, "I2PControlSession: unknown I2PControl method ", method); response.SetError(ErrorCode::e_MethodNotFound); return response; @@ -311,7 +311,7 @@ I2PControlSession::Response I2PControlSession::HandleRequest( ptree params = pt.get_child(constants::PROPERTY_PARAMS); if (method != constants::METHOD_AUTHENTICATE && !Authenticate(params, response)) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "I2PControlSession: invalid token presented"); return response; } diff --git a/src/client/I2PService.cpp b/src/client/I2PService.cpp index 020acb39..1b11e727 100644 --- a/src/client/I2PService.cpp +++ b/src/client/I2PService.cpp @@ -70,7 +70,7 @@ void I2PService::CreateStream( identHash, port); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "I2PService: remote destination ", dest, " not found"); streamRequestComplete(nullptr); } diff --git a/src/client/I2PTunnel/HTTPProxy.cpp b/src/client/I2PTunnel/HTTPProxy.cpp index d0982a15..4c73015b 100644 --- a/src/client/I2PTunnel/HTTPProxy.cpp +++ b/src/client/I2PTunnel/HTTPProxy.cpp @@ -101,7 +101,7 @@ void HTTPProxyHandler::HandleSockRecv( std::size_t len) { LogPrint(eLogDebug, "HTTPProxyHandler: sock recv: ", len); if (ecode) { - LogPrint(eLogWarning, "HTTPProxyHandler: sock recv got error: ", ecode); + LogPrint(eLogWarn, "HTTPProxyHandler: sock recv got error: ", ecode); Terminate(); return; } diff --git a/src/client/I2PTunnel/I2PTunnel.cpp b/src/client/I2PTunnel/I2PTunnel.cpp index 4fbb9293..2bbb3ca8 100644 --- a/src/client/I2PTunnel/I2PTunnel.cpp +++ b/src/client/I2PTunnel/I2PTunnel.cpp @@ -378,7 +378,7 @@ std::unique_ptr I2PClientTunnel::GetIdentHash() { if (i2p::client::context.GetAddressBook().GetIdentHash(m_Destination, identHash)) m_DestinationIdentHash = std::make_unique(identHash); else - LogPrint(eLogWarning, + LogPrint(eLogWarn, "I2PClientTunnel: remote destination ", m_Destination, " not found"); } return std::move(m_DestinationIdentHash); @@ -558,7 +558,7 @@ void I2PServerTunnel::HandleAccept( if (stream) { if (m_IsAccessList) { if (!m_AccessList.count(stream->GetRemoteIdentity().GetIdentHash())) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "I2PServerTunnel: address ", stream->GetRemoteIdentity().GetIdentHash().ToBase32(), " is not in white list, incoming connection dropped"); diff --git a/src/client/I2PTunnel/SOCKS.cpp b/src/client/I2PTunnel/SOCKS.cpp index 15280ad1..b82caefd 100644 --- a/src/client/I2PTunnel/SOCKS.cpp +++ b/src/client/I2PTunnel/SOCKS.cpp @@ -288,7 +288,7 @@ bool SOCKSHandler::Socks5ChooseAuth() { m_response[1] = m_authchosen; // Response code boost::asio::const_buffers_1 response(m_response, 2); if (m_authchosen == AUTH_UNACCEPTABLE) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SOCKSHandler: SOCKS5 authentication negotiation failed"); boost::asio::async_write( *m_sock, @@ -319,7 +319,7 @@ void SOCKSHandler::SocksRequestFailed( assert(error != SOCKS4_OK && error != SOCKS5_OK); switch (m_socksv) { case SOCKS4: - LogPrint(eLogWarning, "SOCKSHandler: SOCKS4 failed: ", error); + LogPrint(eLogWarn, "SOCKSHandler: SOCKS4 failed: ", error); // Transparently map SOCKS5 errors if (error < SOCKS4_OK) error = SOCKS4_FAIL; response = GenerateSOCKS4Response( @@ -328,7 +328,7 @@ void SOCKSHandler::SocksRequestFailed( m_port); break; case SOCKS5: - LogPrint(eLogWarning, "SOCKSHandler: SOCKS5 failed: ", error); + LogPrint(eLogWarn, "SOCKSHandler: SOCKS5 failed: ", error); response = GenerateSOCKS5Response( error, m_addrtype, diff --git a/src/client/Streaming.cpp b/src/client/Streaming.cpp index 90a873b9..8023d0c3 100644 --- a/src/client/Streaming.cpp +++ b/src/client/Streaming.cpp @@ -176,12 +176,12 @@ void Stream::HandleNextPacket( } else { if (receivedSeqn <= m_LastReceivedSequenceNumber) { // we have received duplicate - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Stream: duplicate message ", receivedSeqn, " received"); SendQuickAck(); // resend ack for previous message again delete packet; // packet dropped } else { - LogPrint(eLogWarning, "Stream: missing messages from ", + LogPrint(eLogWarn, "Stream: missing messages from ", m_LastReceivedSequenceNumber + 1, " to ", receivedSeqn - 1); // save message and wait for missing message again SavePacket(packet); @@ -549,7 +549,7 @@ void Stream::Close() { m_LocalDestination.DeleteStream(shared_from_this()); break; default: - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Stream: unexpected stream status ", static_cast(m_Status)); } @@ -676,7 +676,7 @@ void Stream::SendPackets( } m_CurrentOutboundTunnel->SendTunnelDataMsg(msgs); } else { - LogPrint(eLogWarning, "Stream: all leases are expired"); + LogPrint(eLogWarn, "Stream: all leases are expired"); } } @@ -697,7 +697,7 @@ void Stream::HandleResendTimer( if (ecode != boost::asio::error::operation_aborted) { // check for resend attempts if (m_NumResendAttempts >= MAX_NUM_RESEND_ATTEMPTS) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Stream: packet was not ACKed after ", MAX_NUM_RESEND_ATTEMPTS, " attempts. Terminate"); m_Status = eStreamStatusReset; @@ -729,7 +729,7 @@ void Stream::HandleResendTimer( // no break here case 4: UpdateCurrentRemoteLease(); // pick another lease - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Stream: another remote lease has been selected for stream"); break; case 3: @@ -737,7 +737,7 @@ void Stream::HandleResendTimer( m_CurrentOutboundTunnel = m_LocalDestination.GetOwner().GetTunnelPool()->GetNextOutboundTunnel( m_CurrentOutboundTunnel); - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Stream: another outbound tunnel has been selected for stream"); break; default: {} @@ -752,7 +752,7 @@ void Stream::HandleAckSendTimer( const boost::system::error_code&) { if (m_IsAckSendScheduled) { if (m_LastReceivedSequenceNumber < 0) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Stream: SYN has not been received after ", ACK_SEND_TIMEOUT, " milliseconds after follow on, terminating"); m_Status = eStreamStatusReset; @@ -871,7 +871,7 @@ void StreamingDestination::HandleNextPacket( it->second->HandleNextPacket( packet); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "StreamingDestination: unknown stream ", sendStreamID); delete packet; } @@ -882,7 +882,7 @@ void StreamingDestination::HandleNextPacket( if (m_Acceptor != nullptr) { m_Acceptor(incomingStream); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "StreamingDestination: acceptor for incoming stream is not set"); DeleteStream(incomingStream); } @@ -895,7 +895,7 @@ void StreamingDestination::HandleNextPacket( return; } // TODO(unassigned): should queue it up - LogPrint(eLogWarning, + LogPrint(eLogWarn, "StreamingDestination: Unknown stream ", receiveStreamID); delete packet; } diff --git a/src/core/Garlic.cpp b/src/core/Garlic.cpp index 72d43483..b9a0113a 100644 --- a/src/core/Garlic.cpp +++ b/src/core/Garlic.cpp @@ -172,10 +172,10 @@ std::shared_ptr GarlicRoutingSession::WrapSingleMessage( } // create message if (!tag_found) { // new session - LogPrint(eLogWarning, + LogPrint(eLogWarn, "GarlicRoutingSession: no garlic tags available, using ElGamal"); if (!m_Destination) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "GarlicRoutingSession: can't use ElGamal for unknown destination"); return nullptr; } @@ -275,7 +275,7 @@ std::size_t GarlicRoutingSession::CreateGarlicPayload( m_UnconfirmedTagsMsgs[msg_ID] = new_tags; m_Owner->DeliveryStatusSent(shared_from_this(), msg_ID); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "GarlicRoutingSession: DeliveryStatus clove was not created"); } } @@ -376,7 +376,7 @@ std::size_t GarlicRoutingSession::CreateDeliveryStatusClove( "GarlicRoutingSession: no inbound tunnels in the pool for DeliveryStatus"); } } else { - LogPrint(eLogWarning, "GarlicRoutingSession: missing local LeaseSet"); + LogPrint(eLogWarn, "GarlicRoutingSession: missing local LeaseSet"); } return size; } @@ -569,7 +569,7 @@ void GarlicDestination::HandleGarlicPayload( break; } case eGarlicDeliveryTypeRouter: - LogPrint(eLogWarning, + LogPrint(eLogWarn, "GarlicDestination: Garlic type router not supported"); buf += 32; break; diff --git a/src/core/I2NPProtocol.cpp b/src/core/I2NPProtocol.cpp index 581bb70a..47103f6a 100644 --- a/src/core/I2NPProtocol.cpp +++ b/src/core/I2NPProtocol.cpp @@ -541,12 +541,12 @@ void HandleVariableTunnelBuildReplyMsg( tunnel->SetState(i2p::tunnel::e_TunnelStateEstablished); i2p::tunnel::tunnels.AddOutboundTunnel(tunnel); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "I2NPMessage: outbound tunnel ", tunnel->GetTunnelID(), " has been declined"); tunnel->SetState(i2p::tunnel::e_TunnelStateBuildFailed); } } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "I2NPMessage: pending tunnel for message ", replyMsgID, " not found"); } } @@ -670,7 +670,7 @@ void HandleI2NPMessage( // TODO(unassigned): ??? break; default: - LogPrint(eLogWarning, + LogPrint(eLogWarn, "I2NPMessage: unexpected message ", static_cast(typeID)); } } diff --git a/src/core/Identity.cpp b/src/core/Identity.cpp index 7fa4b358..10a0594f 100644 --- a/src/core/Identity.cpp +++ b/src/core/Identity.cpp @@ -155,7 +155,7 @@ IdentityEx::IdentityEx( break; } default: - LogPrint(eLogWarning, + LogPrint(eLogWarn, "IdentityEx: signing key type ", static_cast(type), " is not supported"); } @@ -394,7 +394,7 @@ void IdentityEx::CreateVerifier() const { break; } default: - LogPrint(eLogWarning, + LogPrint(eLogWarn, "IdentityEx: signing key type ", static_cast(keyType), " is not supported"); } @@ -520,7 +520,7 @@ void PrivateKeys::CreateSigner() { m_Signer = std::make_unique(m_SigningPrivateKey); break; default: - LogPrint(eLogWarning, + LogPrint(eLogWarn, "IdentityEx: Signing key type ", static_cast(m_Public.GetSigningKeyType()), " is not supported"); } @@ -566,7 +566,7 @@ PrivateKeys PrivateKeys::CreateRandomKeys(SigningKeyType type) { signingPublicKey); break; default: - LogPrint(eLogWarning, + LogPrint(eLogWarn, "IdentityEx: Signing key type ", static_cast(type), " is not supported, creating DSA-SHA1"); return PrivateKeys(i2p::data::CreateRandomKeys()); // DSA-SHA1 diff --git a/src/core/LeaseSet.cpp b/src/core/LeaseSet.cpp index 67d87b6a..15815c76 100644 --- a/src/core/LeaseSet.cpp +++ b/src/core/LeaseSet.cpp @@ -153,7 +153,7 @@ void LeaseSet::ReadFromBuffer() { } // verify if (!m_Identity.Verify(m_Buffer.get(), leases - m_Buffer.get(), leases)) { - LogPrint(eLogWarning, "LeaseSet: verification failed"); + LogPrint(eLogWarn, "LeaseSet: verification failed"); m_IsValid = false; } } diff --git a/src/core/NetDbRequests.cpp b/src/core/NetDbRequests.cpp index ffdfc2cd..107c0d6b 100644 --- a/src/core/NetDbRequests.cpp +++ b/src/core/NetDbRequests.cpp @@ -162,15 +162,15 @@ void NetDbRequests::ManageRequests() { } else { done = true; if (!inbound) - LogPrint(eLogWarning, "NetDbRequests: no inbound tunnels"); + LogPrint(eLogWarn, "NetDbRequests: no inbound tunnels"); if (!outbound) - LogPrint(eLogWarning, "NetDbRequests: no outbound tunnels"); + LogPrint(eLogWarn, "NetDbRequests: no outbound tunnels"); if (!nextFloodfill) - LogPrint(eLogWarning, "NetDbRequests: no more floodfills"); + LogPrint(eLogWarn, "NetDbRequests: no more floodfills"); } } else { if (!dest->IsExploratory()) - LogPrint(eLogWarning, + LogPrint(eLogWarn, "NetDbRequests: ", dest->GetDestination().ToBase64(), " not found after ", attempts, " attempts"); done = true; diff --git a/src/core/NetworkDatabase.cpp b/src/core/NetworkDatabase.cpp index 4b1784f3..f19a06de 100644 --- a/src/core/NetworkDatabase.cpp +++ b/src/core/NetworkDatabase.cpp @@ -450,7 +450,7 @@ void NetDb::RequestDestination( false, request_complete); // non-exploratory if (!dest) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "NetDb: destination ", destination.ToBase64(), " was already requested"); return; } @@ -599,7 +599,7 @@ void NetDb::HandleDatabaseSearchReplyMsg( delete_dest = false; } } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "NetDb: ", key, " was not found in ", max_ff, "floodfills"); } if (msgs.size() > 0) @@ -614,7 +614,7 @@ void NetDb::HandleDatabaseSearchReplyMsg( m_Requests.RequestComplete(ident, nullptr); } } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "NetDb: requested destination for ", key, " not found"); } // try responses @@ -663,7 +663,7 @@ void NetDb::HandleDatabaseLookupMsg( uint16_t num_excluded = bufbe16toh(excluded); excluded += 2; if (num_excluded > 512) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "NetDb: number of excluded peers", num_excluded, " exceeds 512"); num_excluded = 0; // TODO(unassigned): ??? } @@ -770,7 +770,7 @@ void NetDb::Explore( i2p::crypto::RandBytes(randomHash, 32); auto dest = m_Requests.CreateRequest(randomHash, true); // exploratory if (!dest) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "NetDb: exploratory destination was already requested"); return; } diff --git a/src/core/Profiling.cpp b/src/core/Profiling.cpp index 5b7866e3..7e1574d5 100644 --- a/src/core/Profiling.cpp +++ b/src/core/Profiling.cpp @@ -154,7 +154,7 @@ void RouterProfile::Load() { PEER_PROFILE_PARTICIPATION_NON_REPLIED, 0); } catch (boost::property_tree::ptree_bad_path& ex) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "RouterProfile: Missing section ", PEER_PROFILE_SECTION_PARTICIPATION); } @@ -164,7 +164,7 @@ void RouterProfile::Load() { m_NumTimesTaken = usage.get(PEER_PROFILE_USAGE_TAKEN, 0); m_NumTimesRejected = usage.get(PEER_PROFILE_USAGE_REJECTED, 0); } catch (boost::property_tree::ptree_bad_path& ex) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "RouterProfile: missing section ", PEER_PROFILE_SECTION_USAGE); } } else { diff --git a/src/core/RouterInfo.cpp b/src/core/RouterInfo.cpp index e10cbb45..a32f11eb 100644 --- a/src/core/RouterInfo.cpp +++ b/src/core/RouterInfo.cpp @@ -190,7 +190,7 @@ void RouterInfo::ReadFromStream( address.address_string = value; } else { // TODO(unassigned): resolve address for SSU - LogPrint(eLogWarning, "RouterInfo: unexpected SSU address ", value); + LogPrint(eLogWarn, "RouterInfo: unexpected SSU address ", value); is_valid_address = false; } } else { diff --git a/src/core/transport/NTCPSession.cpp b/src/core/transport/NTCPSession.cpp index 8f78e515..4e05aded 100644 --- a/src/core/transport/NTCPSession.cpp +++ b/src/core/transport/NTCPSession.cpp @@ -412,7 +412,7 @@ void NTCPSession::CreateAESKey( non_zero++; if (non_zero - shared_key.data() > static_cast(NTCPSize::pub_key)) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "NTCPSession:", GetFormattedSessionInfo(), "*** first 32 bytes of shared key is all zeros. Ignored"); return; @@ -691,7 +691,7 @@ void NTCPSession::HandlePhase4Sent( const boost::system::error_code& ecode, std::size_t /*bytes_transferred*/) { if (ecode) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "NTCPSession:", GetFormattedSessionInfo(), "!!! couldn't send Phase4 '", ecode.message(), "'"); if (ecode != boost::asio::error::operation_aborted) @@ -923,7 +923,7 @@ bool NTCPSession::DecryptNextBlock( m_NextMessageOffset - static_cast(NTCPSize::adler32))) m_Handler.PutNextMessage(m_NextMessage); else - LogPrint(eLogWarning, + LogPrint(eLogWarn, "NTCPSession:", GetFormattedSessionInfo(), "!!! incorrect Adler checksum of NTCP message, dropped"); m_NextMessage = nullptr; @@ -1021,7 +1021,7 @@ void NTCPSession::HandleSentPayload( std::vector> /*msgs*/) { m_IsSending = false; if (ecode) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "NTCPSession:", GetFormattedSessionInfo(), "!!! couldn't send I2NP messages, error '", ecode.message(), "'"); // TODO(unassigned): diff --git a/src/core/transport/SSU.cpp b/src/core/transport/SSU.cpp index 17a2c954..53b6579f 100644 --- a/src/core/transport/SSU.cpp +++ b/src/core/transport/SSU.cpp @@ -472,7 +472,7 @@ std::shared_ptr SSUServer::GetSession( } introducerSession->Introduce(introducer->tag, introducer->key); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUServer: can't connect to unreachable router." "No introducers presented"); std::unique_lock l(m_SessionsMutex); @@ -482,7 +482,7 @@ std::shared_ptr SSUServer::GetSession( } } } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUServer: router ", router->GetIdentHashAbbreviation(), " doesn't have SSU address"); } diff --git a/src/core/transport/SSUData.cpp b/src/core/transport/SSUData.cpp index aeee2f00..dbe9a788 100644 --- a/src/core/transport/SSUData.cpp +++ b/src/core/transport/SSUData.cpp @@ -114,7 +114,7 @@ void SSUData::AdjustPacketSize( "SSUData:", m_Session.GetFormattedSessionInfo(), "MTU=", ssuAddress->mtu, " packet size=", m_PacketSize); } else { - LogPrint(eLogWarning, "SSUData: unexpected MTU ", ssuAddress->mtu); + LogPrint(eLogWarn, "SSUData: unexpected MTU ", ssuAddress->mtu); m_PacketSize = m_MaxPacketSize; } } @@ -257,13 +257,13 @@ void SSUData::ProcessFragments( } else { if (fragmentNum < incompleteMessage->nextFragmentNum) { // duplicate fragment - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUData:", m_Session.GetFormattedSessionInfo(), " ignoring duplicate fragment ", static_cast(fragmentNum), " of message ", msgID); } else { // missing fragment - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUData:", m_Session.GetFormattedSessionInfo(), " missing fragments from ", static_cast(incompleteMessage->nextFragmentNum), @@ -275,7 +275,7 @@ void SSUData::ProcessFragments( incompleteMessage->lastFragmentInsertTime = i2p::util::GetSecondsSinceEpoch(); else - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUData:", m_Session.GetFormattedSessionInfo(), "fragment ", static_cast(fragmentNum), " of message ", msgID, " is already saved"); @@ -299,7 +299,7 @@ void SSUData::ProcessFragments( m_ReceivedMessages.insert(msgID); m_Handler.PutNextMessage(msg); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUData:", m_Session.GetFormattedSessionInfo(), "SSU message ", msgID, " already received"); } @@ -373,7 +373,7 @@ void SSUData::Send( "sending message"); uint32_t msgID = msg->ToSSU(); if (m_SentMessages.count(msgID) > 0) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUData:", m_Session.GetFormattedSessionInfo(), "message ", msgID, " was already sent"); return; @@ -468,7 +468,7 @@ void SSUData::SendFragmentAck( "SSUData:", m_Session.GetFormattedSessionInfo(), "sending fragment ACK"); if (fragmentNum > 64) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUData:", m_Session.GetFormattedSessionInfo(), "fragment number ", fragmentNum, " exceeds 64"); return; diff --git a/src/core/transport/SSUSession.cpp b/src/core/transport/SSUSession.cpp index c8375e3c..9d1f4c29 100644 --- a/src/core/transport/SSUSession.cpp +++ b/src/core/transport/SSUSession.cpp @@ -193,7 +193,7 @@ void SSUSession::CreateAESandMacKey( while (!*nonZero) { nonZero++; if (nonZero - sharedKey > 32) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUSession:", GetFormattedSessionInfo(), "first 32 bytes of shared key is all zeros. Ignored"); return; @@ -322,7 +322,7 @@ void SSUSession::ProcessDecryptedMessage( ProcessRelayIntro(pkt); break; default: - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUSession: unexpected payload type: ", static_cast(payload_type)); } @@ -419,7 +419,7 @@ void SSUSession::SendSessionRequest() { void SSUSession::ProcessSessionCreated( SSUSessionPacket& pkt) { if (!m_RemoteRouter || !m_DHKeysPair) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUSession:", GetFormattedSessionInfo(), "unsolicited SessionCreated message"); return; @@ -900,7 +900,7 @@ void SSUSession::ProcessRelayIntro( address, port)); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUSession:", GetFormattedSessionInfo(), "ProcessRelayIntro(): address size ", static_cast(size), " is not supported"); @@ -982,7 +982,7 @@ void SSUSession::ProcessPeerTest( uint16_t port = buf16toh(buf + size + 5); // big endian, 2 bytes const uint8_t* introKey = buf + size + 7; if (port && !address) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUSession:", GetFormattedSessionInfo(), "address of ", static_cast(size), " bytes not supported"); return; @@ -1372,7 +1372,7 @@ void SSUSession::Connect() { void SSUSession::WaitForConnect() { if (IsOutbound()) - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUSession:", GetFormattedSessionInfo(), "WaitForConnect() for outgoing session"); else @@ -1535,7 +1535,7 @@ void SSUSession::Send( if (paddingSize > 0) msgSize += (16 - paddingSize); if (msgSize > SSU_MTU_V4) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "SSUSession:", GetFormattedSessionInfo(), "<-- payload size ", msgSize, " exceeds MTU"); return; diff --git a/src/core/tunnel/Tunnel.cpp b/src/core/tunnel/Tunnel.cpp index be0d028c..a09a8435 100644 --- a/src/core/tunnel/Tunnel.cpp +++ b/src/core/tunnel/Tunnel.cpp @@ -146,7 +146,7 @@ bool Tunnel::HandleTunnelBuildResponse( decryption.SetIV(hop->replyIV); decryption.Decrypt(record, TUNNEL_BUILD_RECORD_SIZE, record); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Tunnel: hop index ", idx, " is out of range"); } hop1 = hop1->prev; @@ -434,7 +434,7 @@ void Tunnels::Run() { else // tunnel gateway assumed HandleTunnelGatewayMsg(tunnel, msg); } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "Tunnels: tunnel ", tunnelID, " not found"); } break; diff --git a/src/core/tunnel/TunnelPool.cpp b/src/core/tunnel/TunnelPool.cpp index 860807bf..6e38645a 100644 --- a/src/core/tunnel/TunnelPool.cpp +++ b/src/core/tunnel/TunnelPool.cpp @@ -242,7 +242,7 @@ void TunnelPool::CreateTunnels() { void TunnelPool::TestTunnels() { for (auto it : m_Tests) { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "TunnelPool: tunnel test ", static_cast(it.first), " failed"); // if test failed again with another tunnel we consider it failed if (it.second.first) { @@ -300,7 +300,7 @@ void TunnelPool::ProcessGarlicMessage( if (m_LocalDestination) m_LocalDestination->ProcessGarlicMessage(msg); else - LogPrint(eLogWarning, + LogPrint(eLogWarn, "TunnelPool: local destination doesn't exist, dropped"); } @@ -326,7 +326,7 @@ void TunnelPool::ProcessDeliveryStatus( if (m_LocalDestination) m_LocalDestination->ProcessDeliveryStatusMessage(msg); else - LogPrint(eLogWarning, "TunnelPool: local destination doesn't exist, dropped"); + LogPrint(eLogWarn, "TunnelPool: local destination doesn't exist, dropped"); } } diff --git a/src/core/util/Log.h b/src/core/util/Log.h index 2a3af111..413e99c7 100644 --- a/src/core/util/Log.h +++ b/src/core/util/Log.h @@ -65,13 +65,13 @@ namespace log { enum LogLevel { eLogLevelDebug, eLogLevelInfo, - eLogLevelWarning, + eLogLevelWarn, eLogLevelError }; #define eLogDebug i2p::util::log::eLogLevelDebug #define eLogInfo i2p::util::log::eLogLevelInfo -#define eLogWarning i2p::util::log::eLogLevelWarning +#define eLogWarn i2p::util::log::eLogLevelWarn #define eLogError i2p::util::log::eLogLevelError /// @typedef LogLevelsMap @@ -125,7 +125,7 @@ class Logger { LogStream& Info(); /// @return Reference to warning level log stream - LogStream& Warning(); + LogStream& Warn(); /// @return Reference to error level log stream LogStream& Error(); @@ -242,10 +242,10 @@ void DeprecatedLogPrint( stream << std::flush; } } - } else if (level == eLogWarning) { + } else if (level == eLogWarn) { for (auto& current_level : global_levels) { - if (current_level.second == eLogWarning) { - auto& stream = log->Warning(); + if (current_level.second == eLogWarn) { + auto& stream = log->Warn(); DeprecatedLog(stream, args...); stream << std::flush; } diff --git a/src/core/util/MTU.cpp b/src/core/util/MTU.cpp index 42fa14f2..b6c926de 100644 --- a/src/core/util/MTU.cpp +++ b/src/core/util/MTU.cpp @@ -132,7 +132,7 @@ int GetMTUUnix( LogPrint(eLogError, "MTU: failed to create datagram socket"); } } else { - LogPrint(eLogWarning, + LogPrint(eLogWarn, "MTU: interface for local address", localAddress.to_string(), " not found"); } diff --git a/src/core/util/ZIP.cpp b/src/core/util/ZIP.cpp index 77f7c7bf..cf9c1ea2 100644 --- a/src/core/util/ZIP.cpp +++ b/src/core/util/ZIP.cpp @@ -111,14 +111,14 @@ bool ZIP::PrepareLocalFile() { // Get CRC-32 checksum m_Stream.Read(*m_Data->crc_32.data(), Size::crc_32); if (!m_Data->crc_32.data()) { - LogPrint(eLogWarning, "ZIP: CRC-32 checksum was null"); + LogPrint(eLogWarn, "ZIP: CRC-32 checksum was null"); return false; } // Prepare compressed file size m_Stream.Read(m_Data->compressed_size, Size::compressed_size); m_Data->compressed_size = le32toh(m_Data->compressed_size); if (!m_Data->compressed_size) - LogPrint(eLogWarning, "ZIP: compressed file size was null"); + LogPrint(eLogWarn, "ZIP: compressed file size was null"); // Prepare uncompressed file size m_Stream.Read(m_Data->uncompressed_size, Size::uncompressed_size); m_Data->uncompressed_size = le32toh(m_Data->uncompressed_size); diff --git a/src/core/util/pimpl/Log.cpp b/src/core/util/pimpl/Log.cpp index 0ac27691..b41d89e9 100644 --- a/src/core/util/pimpl/Log.cpp +++ b/src/core/util/pimpl/Log.cpp @@ -76,7 +76,7 @@ namespace log { /// @brief Maps string global levels to enumerated global levels LogLevelsMap g_LogLevels { { "info", eLogInfo }, - { "warn", eLogWarning }, + { "warn", eLogWarn }, { "error", eLogError }, { "debug", eLogDebug }, }; @@ -259,7 +259,7 @@ class LoggerImpl { const std::string& channel) : m_Log(boost::log::keywords::channel = channel), m_Info(new LogStreamImpl(m_InfoMtx, m_Log, eLogInfo)), - m_Warn(new LogStreamImpl(m_WarnMtx, m_Log, eLogWarning)), + m_Warn(new LogStreamImpl(m_WarnMtx, m_Log, eLogWarn)), m_Error(new LogStreamImpl(m_ErrorMtx, m_Log, eLogError)), m_Debug(new LogStreamImpl(m_DebugMtx, m_Log, eLogDebug)) { m_Log.add_attribute( @@ -271,7 +271,7 @@ class LoggerImpl { return GetLogStream(m_Error, m_ErrorMtx); } - LogStream& Warning() { + LogStream& Warn() { return GetLogStream(m_Warn, m_WarnMtx); } @@ -314,8 +314,8 @@ LogStream& Logger::Error() { return m_LoggerPimpl->Error(); } -LogStream& Logger::Warning() { - return m_LoggerPimpl->Warning(); +LogStream& Logger::Warn() { + return m_LoggerPimpl->Warn(); } LogStream& Logger::Info() { @@ -441,7 +441,7 @@ std::ostream& operator<<( static std::array levels { "DBG", // debug "NFO", // info - "WRN", // warning + "WRN", // warn "ERR" // error }; if (static_cast(log_level) < levels.size()) { From 4151d774e8514fb96fc88db004da9cb1c52ccb36 Mon Sep 17 00:00:00 2001 From: anonimal Date: Sat, 18 Jun 2016 06:37:43 +0000 Subject: [PATCH 08/11] Log: fix trivial typo. --- src/core/util/pimpl/Log.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/util/pimpl/Log.cpp b/src/core/util/pimpl/Log.cpp index b41d89e9..ad6d71b7 100644 --- a/src/core/util/pimpl/Log.cpp +++ b/src/core/util/pimpl/Log.cpp @@ -97,7 +97,7 @@ void SetGlobalLogLevels( g_LogLevels.swap(new_levels); } -/// @brief Returns current state of global lob levels +/// @brief Returns current state of global log levels const LogLevelsMap& GetGlobalLogLevels() { return g_LogLevels; } From 48e33bccfd3c8521026692945f67ae514c98752a Mon Sep 17 00:00:00 2001 From: anonimal Date: Sat, 18 Jun 2016 19:08:47 +0000 Subject: [PATCH 09/11] Travis: attempt to fix Coverity. Refs #199. --- .travis.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.travis.yml b/.travis.yml index a69d4797..87f46109 100644 --- a/.travis.yml +++ b/.travis.yml @@ -20,14 +20,14 @@ addons: - doxygen sources: - ubuntu-toolchain-r-test -coverity_scan: - project: - name: monero-project/kovri - description: The Kovri I2P Router Project - notification_email: anonimal@i2pmail.org - build_command_prepend: export CC=gcc-${GCC_VERSION} CXX=g++-${GCC_VERSION} && cd build && cmake -DWITH_TESTS=ON -DWITH_BENCHMARKS=ON -DWITH_UPNP=ON -DWITH_DOXYGEN=ON ../ - build_command: make -j2 - branch_pattern: coverity_scan + coverity_scan: + project: + name: monero-project/kovri + description: The Kovri I2P Router Project + notification_email: anonimal@i2pmail.org + build_command_prepend: export CC=gcc-${GCC_VERSION} CXX=g++-${GCC_VERSION} && cd build && cmake -DWITH_TESTS=ON -DWITH_BENCHMARKS=ON -DWITH_UPNP=ON -DWITH_DOXYGEN=ON ../ + build_command: make -j2 + branch_pattern: coverity_scan before_script: export CC=gcc-${GCC_VERSION} CXX=g++-${GCC_VERSION} script: if [ "${COVERITY_SCAN_BRANCH}" != 1 ]; then cd build && cmake -DWITH_TESTS=ON -DWITH_BENCHMARKS=ON -DWITH_UPNP=ON -DWITH_DOXYGEN=ON ../ && make doc && make -j2 ; fi notifications: From 18e76665a9be5211e549ea42f2c1ac898dd86bff Mon Sep 17 00:00:00 2001 From: anonimal Date: Sat, 18 Jun 2016 20:21:32 +0000 Subject: [PATCH 10/11] Travis: add certs. Refs travis-ci/travis-ci#6142 --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 87f46109..de061d84 100644 --- a/.travis.yml +++ b/.travis.yml @@ -10,6 +10,7 @@ compiler: addons: apt: packages: + - ca-certificates - gcc-5 - g++-5 - libboost-all-dev From 73912f3bcd74277360b9da0bff30166f3be06da2 Mon Sep 17 00:00:00 2001 From: anonimal Date: Sat, 18 Jun 2016 20:45:06 +0000 Subject: [PATCH 11/11] Travis: grab Coverity cert manually. Refs travis-ci/travis-ci#6142 --- .travis.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.travis.yml b/.travis.yml index de061d84..8ec75240 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,6 +4,8 @@ env: - secure: J4o/q57D7PAqV+hG5VUhwGJLH4ryFWy8YGVAlAOyrRVv9UxfbiihhyE5Yh68tjukdFqLt3WcHB3hoPz0VfbxWGdLQ9OR0r7xxYPetA0qVYcttpumcVSBra17CCRBYOcyRCfbgUY/LVRbKlr8zgkubRUW0skUcAgELyZJA6k/k+3pd1oDjdBLMLp+TeQvQnUtekw7eEzBl31bgpku3vHQEiYxMRY6FhBC0vojNJSjT56pqYzA/bOVrPNDATxHqDAxuEWfNiNQym4P2T+LmkC2utCWlwLBSqTauy54z4nKM6+0xEmRq2hmBWZeSv1tYuKJi8rmtAH5OozyVGSaXpuelcaWE4YrNCGEXOJZQvuD+IEuFVSkqXItoUIjlE1kP/zIDAZERMaISzXkp2xpPQFes8NLE3lNdcvMYYUjVfyUpYN0qE5/XX6Opii6Y8Sj6wQaz1Y5n3g1Lp5TMlQIVmmTUPAWoCq3U2BTPn+Ub8O8Z7Y/9Zr1xdz3gBEJaYv1CuxrSb3z3lQ9BjodBL1u+l5me+16dBe4RbpPwoWvLramJAvKEuDHMx93UnYU+PWs9B9UyIwEh/FxpvRyu8iyI6pfNWIsrc1jJ2nzf1YrnXOHb0C0CdwHH6p6Nzy/bOfaBOihiwc6o9r80AHq0RBbkH7euPOGFAo4iUgYTaS7R9Pw6Rk= sudo: required dist: trusty +before_install: +- echo -n | openssl s_client -connect scan.coverity.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | sudo tee -a /etc/ssl/certs/ca-certificates.crt language: cpp compiler: - gcc