refactor: use fmt (#2758)

* deps: use fmt (8.1.1 tag) to build log strings

Co-authored-by: Mike Gelfand <mikedld@mikedld.com>
This commit is contained in:
Charles Kerr 2022-03-13 23:43:35 -05:00 committed by GitHub
parent 2bd42f8225
commit a942c67199
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
44 changed files with 674 additions and 342 deletions

3
.gitmodules vendored
View File

@ -39,3 +39,6 @@
path = third-party/libpsl
url = https://github.com/transmission/libpsl.git
branch = post-3.0.0-transmission
[submodule "third-party/fmt"]
path = third-party/fmt
url = https://github.com/transmission/fmt.git

View File

@ -146,6 +146,7 @@ if(WIN32)
endforeach()
endif()
find_package(Fmt)
find_package(UtfCpp)
find_package(Threads)
find_package(PkgConfig QUIET)
@ -342,6 +343,8 @@ if(NOT USE_SYSTEM_NATPMP)
set(NATPMP_DEFINITIONS -DNATPMP_STATICLIB)
endif()
set(LIBFMT_DEFINITIONS -DFMT_HEADER_ONLY)
tr_add_external_auto_library(MINIUPNPC miniupnpc miniupnpc
CMAKE_ARGS
-DUPNPC_BUILD_STATIC=ON
@ -603,6 +606,8 @@ if(ENABLE_NLS)
if(HAVE_LIBINTL)
set(LIBINTL_LIBRARY intl)
endif()
check_function_exists(gettext "libintl.h" HAVE_GETTEXT)
check_function_exists(ngettext "libintl.h" HAVE_NGETTEXT)
endif()
check_library_exists(m sqrt "" HAVE_LIBM)

View File

@ -3392,12 +3392,14 @@
"third-party/libevent/include",
"third-party/libutp",
"third-party/utfcpp/source",
"third-party/fmt/include",
"third-party/libdeflate",
"third-party/libpsl/include",
);
OTHER_CFLAGS = (
"$(inherited)",
"-DWITH_UTP",
"-DFMT_HEADER_ONLY",
"-D__TRANSMISSION__",
"-DHAVE_FLOCK",
"-DHAVE_STRLCPY",
@ -3458,9 +3460,11 @@
"$(inherited)",
.,
"third-party/libevent/include",
"third-party/fmt/include",
);
OTHER_CFLAGS = (
"$(inherited)",
"-DFMT_HEADER_ONLY",
"-DHAVE_DAEMON",
);
OTHER_LDFLAGS = "-lc++";
@ -3478,6 +3482,11 @@
"$(inherited)",
.,
"third-party/libevent/include",
"third-party/fmt/include",
);
OTHER_CFLAGS = (
"$(inherited)",
"-DFMT_HEADER_ONLY",
);
OTHER_LDFLAGS = "-lc++";
PRODUCT_NAME = "transmission-remote";
@ -3586,12 +3595,14 @@
"third-party/libevent/include",
"third-party/libutp",
"third-party/utfcpp/source",
"third-party/fmt/include",
"third-party/libdeflate",
"third-party/libpsl/include",
);
OTHER_CFLAGS = (
"$(inherited)",
"-DWITH_UTP",
"-DFMT_HEADER_ONLY",
"-D__TRANSMISSION__",
"-DHAVE_FLOCK",
"-DHAVE_STRLCPY",
@ -3837,12 +3848,14 @@
"third-party/libevent/include",
"third-party/libutp",
"third-party/utfcpp/source",
"third-party/fmt/include",
"third-party/libdeflate",
"third-party/libpsl/include",
);
OTHER_CFLAGS = (
"$(inherited)",
"-DWITH_UTP",
"-DFMT_HEADER_ONLY",
"-D__TRANSMISSION__",
"-DHAVE_FLOCK",
"-DHAVE_STRLCPY",
@ -3866,10 +3879,12 @@
"$(inherited)",
.,
"third-party/libevent/include",
"third-party/fmt/include",
);
OTHER_CFLAGS = (
"$(inherited)",
"-DHAVE_DAEMON",
"-DFMT_HEADER_ONLY",
);
OTHER_LDFLAGS = "-lc++";
PRODUCT_NAME = "transmission-daemon";
@ -3886,8 +3901,13 @@
"$(inherited)",
.,
"third-party/libevent/include",
"third-party/fmt/include",
);
OTHER_LDFLAGS = "-lc++";
OTHER_CFLAGS = (
"$(inherited)",
"-DFMT_HEADER_ONLY",
);
PRODUCT_NAME = "transmission-remote";
};
name = "Release - Debug";
@ -4033,9 +4053,11 @@
"$(inherited)",
.,
"third-party/libevent/include",
"third-party/fmt/include",
);
OTHER_CFLAGS = (
"$(inherited)",
"-DFMT_HEADER_ONLY",
"-DHAVE_DAEMON",
);
OTHER_LDFLAGS = "-lc++";
@ -4053,8 +4075,13 @@
"$(inherited)",
.,
"third-party/libevent/include",
"third-party/fmt/include",
);
OTHER_LDFLAGS = "-lc++";
OTHER_CFLAGS = (
"$(inherited)",
"-DFMT_HEADER_ONLY",
);
PRODUCT_NAME = "transmission-remote";
};
name = Release;

1
cmake/FindFmt.cmake Normal file
View File

@ -0,0 +1 @@
set(LIBFMT_INCLUDE_DIRS ${CMAKE_SOURCE_DIR}/third-party/fmt/include)

View File

@ -13,6 +13,11 @@ include_directories(
SYSTEM
${CURL_INCLUDE_DIRS}
${EVENT2_INCLUDE_DIRS}
${LIBFMT_INCLUDE_DIRS}
)
add_definitions(
${LIBFMT_DEFINITIONS}
)
set(${PROJECT_NAME}_SOURCES

View File

@ -7,6 +7,8 @@
#include <windows.h>
#include <fmt/core.h>
#include <libtransmission/transmission.h>
#include <libtransmission/error.h>
#include <libtransmission/log.h>
@ -52,7 +54,12 @@ static void set_system_error(tr_error** error, DWORD code, char const* message)
static void do_log_system_error(char const* file, int line, tr_log_level level, DWORD code, char const* message)
{
char* const system_message = tr_win32_format_message(code);
tr_logAddMessage(file, line, level, "[dtr_daemon] %s (0x%08lx): %s", message, code, system_message);
tr_logAddMessage(
file,
line,
level,
"dtr_daemon",
fmt::format("[dtr_daemon] {} ({:#x}): {}", message, code, system_message));
tr_free(system_message);
}

View File

@ -21,6 +21,8 @@
#include <event2/event.h>
#include <fmt/core.h>
#include <libtransmission/transmission.h>
#include <libtransmission/error.h>
#include <libtransmission/file.h>
@ -255,24 +257,26 @@ static auto onFileAdded(tr_watchdir_t dir, char const* name, void* vsession)
if (tr_torrentNew(ctor, nullptr) == nullptr)
{
tr_logAddError("Unable to add .torrent file \"%s\"", name);
tr_logAddError(fmt::format(_("Couldn't add .torrent file '{path}'"), fmt::arg("path", name)));
}
else
{
bool trash = false;
bool const test = tr_ctorGetDeleteSource(ctor, &trash);
tr_logAddInfo("Parsing .torrent file successful \"%s\"", name);
if (test && trash)
{
tr_error* error = nullptr;
tr_logAddInfo("Deleting input .torrent file \"%s\"", name);
tr_logAddInfo(fmt::format(_("Removing .torrent file '{path}'"), fmt::arg("path", name)));
if (!tr_sys_path_remove(filename.c_str(), &error))
{
tr_logAddError("Error deleting .torrent file: %s", error->message);
tr_logAddError(fmt::format(
_("Couldn't remove '{path}': {errmsg} ({errcode})"),
fmt::arg("path", name),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
}
}
@ -636,7 +640,7 @@ static void daemon_reconfigure(void* /*arg*/)
{
if (mySession == nullptr)
{
tr_logAddInfo("Deferring reload until session is fully started.");
tr_logAddInfo(_("Deferring reload until session is fully started."));
seenHUP = true;
}
else
@ -651,7 +655,7 @@ static void daemon_reconfigure(void* /*arg*/)
}
configDir = tr_sessionGetConfigDir(mySession);
tr_logAddInfo("Reloading settings from \"%s\"", configDir);
tr_logAddInfo(fmt::format(_("Reloading settings from '{path}'"), fmt::arg("path", configDir)));
tr_variantInitDict(&settings, 0);
tr_variantDictAddBool(&settings, TR_KEY_rpc_enabled, true);
tr_sessionLoadSettings(&settings, configDir, MyName);
@ -689,7 +693,7 @@ static int daemon_start(void* varg, [[maybe_unused]] bool foreground)
if (ev_base == nullptr)
{
char buf[256];
tr_snprintf(buf, sizeof(buf), "Failed to init daemon event state: %s", tr_strerror(errno));
tr_snprintf(buf, sizeof(buf), "Couldn't initialize daemon event state: %s", tr_strerror(errno));
printMessage(logfile, TR_LOG_ERROR, MyName, buf, __FILE__, __LINE__);
return 1;
}
@ -700,7 +704,7 @@ static int daemon_start(void* varg, [[maybe_unused]] bool foreground)
tr_formatter_speed_init(SpeedK, SpeedKStr, SpeedMStr, SpeedGStr, SpeedTStr);
session = tr_sessionInit(configDir, true, settings);
tr_sessionSetRPCCallback(session, on_rpc_callback, nullptr);
tr_logAddNamedInfo(MyName, "Using settings from \"%s\"", configDir);
tr_logAddNamedInfo(MyName, fmt::format(_("Loading settings from '{path}'"), fmt::arg("path", configDir)));
tr_sessionSaveSettings(session, configDir, settings);
auto sv = std::string_view{};
@ -720,19 +724,23 @@ static int daemon_start(void* varg, [[maybe_unused]] bool foreground)
auto const out = std::to_string(getpid());
tr_sys_file_write(fp, std::data(out), std::size(out), nullptr, nullptr);
tr_sys_file_close(fp, nullptr);
tr_logAddInfo("Saved pidfile \"%s\"", sz_pid_filename.c_str());
tr_logAddInfo(fmt::format(_("Saved pidfile '{path}'"), fmt::arg("path", sz_pid_filename)));
pidfile_created = true;
}
else
{
tr_logAddError("Unable to save pidfile \"%s\": %s", sz_pid_filename.c_str(), error->message);
tr_logAddError(fmt::format(
_("Couldn't save '{path}': {errmsg} ({errcode})"),
fmt::arg("path", sz_pid_filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
}
}
if (tr_variantDictFindBool(settings, TR_KEY_rpc_authentication_required, &boolVal) && boolVal)
{
tr_logAddNamedInfo(MyName, "requiring authentication");
tr_logAddNamedInfo(MyName, _("Requiring authentication"));
}
mySession = session;
@ -753,7 +761,7 @@ static int daemon_start(void* varg, [[maybe_unused]] bool foreground)
(void)tr_variantDictFindStrView(settings, TR_KEY_watch_dir, &dir);
if (!std::empty(dir))
{
tr_logAddInfo("Watching \"%" TR_PRIsv "\" for new .torrent files", TR_PRIsv_ARG(dir));
tr_logAddInfo(fmt::format(_("Watching '{path}' for new .torrent files"), fmt::arg("path", dir)));
watchdir = tr_watchdir_new(dir, &onFileAdded, mySession, ev_base, force_generic);
if (watchdir == nullptr)
@ -794,13 +802,21 @@ static int daemon_start(void* varg, [[maybe_unused]] bool foreground)
if (status_ev == nullptr)
{
tr_logAddError("Failed to create status event %s", tr_strerror(errno));
auto const errcode = errno;
tr_logAddError(fmt::format(
_("Couldn't create status event: {errmsg} ({errcode})"),
fmt::arg("errmsg", tr_strerror(errcode)),
fmt::arg("errcode", errcode)));
goto CLEANUP;
}
if (event_add(status_ev, &one_sec) == -1)
{
tr_logAddError("Failed to add status event %s", tr_strerror(errno));
auto const errcode = errno;
tr_logAddError(fmt::format(
_("Couldn't add status event: {errmsg} ({errcode})"),
fmt::arg("errmsg", tr_strerror(errcode)),
fmt::arg("errcode", errcode)));
goto CLEANUP;
}
}
@ -810,7 +826,11 @@ static int daemon_start(void* varg, [[maybe_unused]] bool foreground)
/* Run daemon event loop */
if (event_base_dispatch(ev_base) == -1)
{
tr_logAddError("Failed to launch daemon event loop: %s", tr_strerror(errno));
auto const errcode = errno;
tr_logAddError(fmt::format(
_("Couldn't launch daemon event loop: {errmsg} ({errcode})"),
fmt::arg("errmsg", tr_strerror(errcode)),
fmt::arg("errcode", errcode)));
goto CLEANUP;
}
@ -922,7 +942,7 @@ int tr_main(int argc, char* argv[])
if (tr_error* error = nullptr; !dtr_daemon(&cb, &data, foreground, &ret, &error))
{
printMessage(logfile, TR_LOG_ERROR, MyName, tr_strvJoin("Failed to daemonize: ", error->message), __FILE__, __LINE__);
printMessage(logfile, TR_LOG_ERROR, MyName, tr_strvJoin("Couldn't daemonize: ", error->message), __FILE__, __LINE__);
tr_error_free(error);
}

View File

@ -130,6 +130,7 @@ include_directories(
)
include_directories(
SYSTEM
${LIBFMT_INCLUDE_DIRS}
${LIBAPPINDICATOR_INCLUDE_DIRS}
${GTK_INCLUDE_DIRS}
${CURL_INCLUDE_DIRS}
@ -158,6 +159,7 @@ add_definitions(
-DPANGOMM_DISABLE_DEPRECATED
-DSIGCXX_DISABLE_DEPRECATED
${GTK_CFLAGS_OTHER}
${LIBFMT_DEFINITIONS}
)
tr_win32_app_info(${PROJECT_NAME}_WIN32_RC_FILE

View File

@ -15,6 +15,8 @@
#include <event2/buffer.h>
#include <fmt/core.h>
#include <libtransmission/transmission.h>
#include <libtransmission/log.h>
@ -1107,7 +1109,8 @@ void Session::Impl::add_file_async_callback(
{
if (!file->load_contents_finish(result, contents, length))
{
g_message(_("Couldn't read \"%s\""), file->get_parse_name().c_str());
auto const errmsg = fmt::format(_("Couldn't read '{path}'"), fmt::arg("path", file->get_parse_name().raw()));
g_message("%s", errmsg.c_str());
}
else if (tr_ctorSetMetainfo(ctor, contents, length, nullptr))
{
@ -1120,7 +1123,12 @@ void Session::Impl::add_file_async_callback(
}
catch (Glib::Error const& e)
{
g_message(_("Couldn't read \"%s\": %s"), file->get_parse_name().c_str(), e.what().c_str());
auto const errmsg = fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", file->get_parse_name().raw()),
fmt::arg("errmsg", e.what().raw()),
fmt::arg("errmsg", e.code()));
g_message("%s", errmsg.c_str());
}
dec_busy();
@ -1437,13 +1445,13 @@ bool gtr_inhibit_hibernation(guint32& cookie)
cookie = Glib::VariantBase::cast_dynamic<Glib::Variant<guint32>>(response.get_child(0)).get();
/* logging */
tr_logAddInfo("%s", _("Inhibiting desktop hibernation"));
tr_logAddInfo(_("Inhibiting desktop hibernation"));
success = true;
}
catch (Glib::Error const& e)
{
tr_logAddError(_("Couldn't inhibit desktop hibernation: %s"), e.what().c_str());
tr_logAddError(fmt::format(_("Couldn't inhibit desktop hibernation: {errmsg}"), fmt::arg("errmsg", e.what().raw())));
}
return success;
@ -1464,11 +1472,11 @@ void gtr_uninhibit_hibernation(guint inhibit_cookie)
1000);
/* logging */
tr_logAddInfo("%s", _("Allowing desktop hibernation"));
tr_logAddInfo(_("Allowing desktop hibernation"));
}
catch (Glib::Error const& e)
{
g_warning("Couldn't uninhibit desktop hibernation: %s.", e.what().c_str());
tr_logAddError(fmt::format(_("Couldn't inhibit desktop hibernation: {errmsg}"), fmt::arg("errmsg", e.what().raw())));
}
}

View File

@ -216,6 +216,7 @@ endif()
add_definitions(
-D__TRANSMISSION__
"-DPACKAGE_DATA_DIR=\"${CMAKE_INSTALL_FULL_DATAROOTDIR}\""
${LIBFMT_DEFINITIONS}
${NATPMP_DEFINITIONS}
${MINIUPNPC_DEFINITIONS}
)
@ -256,6 +257,7 @@ include_directories(
include_directories(
SYSTEM
${LIBFMT_INCLUDE_DIRS}
${UTFCPP_INCLUDE_DIRS}
${DEFLATE_INCLUDE_DIRS}
${CRYPTO_INCLUDE_DIRS}

View File

@ -14,6 +14,8 @@
#include <event2/buffer.h>
#include <event2/http.h> /* for HTTP_OK */
#include <fmt/core.h>
#define LIBTRANSMISSION_ANNOUNCER_MODULE
#include "transmission.h"
@ -271,7 +273,11 @@ void tr_announcerParseHttpAnnounceResponse(tr_announce_response& response, std::
transmission::benc::parse(benc, stack, handler, nullptr, &error);
if (error != nullptr)
{
tr_logAddMessage(__FILE__, __LINE__, TR_LOG_WARN, log_name, "%s (%d)", error->message, error->code);
auto const errmsg = fmt::format(
_("Couldn't parse announce response: {errmsg} ({errcode})"),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code));
tr_logAddMessage(__FILE__, __LINE__, TR_LOG_WARN, log_name, errmsg);
tr_error_clear(&error);
}
}
@ -443,7 +449,11 @@ void tr_announcerParseHttpScrapeResponse(tr_scrape_response& response, std::stri
transmission::benc::parse(benc, stack, handler, nullptr, &error);
if (error != nullptr)
{
tr_logAddMessage(__FILE__, __LINE__, TR_LOG_WARN, log_name, "scrape response: %s (%d)", error->message, error->code);
auto const errmsg = fmt::format(
_("Couldn't parse scrape response: {errmsg} ({errcode})"),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code));
tr_logAddMessage(__FILE__, __LINE__, TR_LOG_WARN, log_name, errmsg);
tr_error_clear(&error);
}
}

View File

@ -20,6 +20,8 @@
#include <event2/buffer.h>
#include <event2/event.h> /* evtimer */
#include <fmt/core.h>
#define LIBTRANSMISSION_ANNOUNCER_MODULE
#include "transmission.h"
@ -654,7 +656,7 @@ static void publishPeerCounts(tr_tier* tier, int seeders, int leechers)
e.messageType = TR_TRACKER_COUNTS;
e.seeders = seeders;
e.leechers = leechers;
tr_logAddDebugTier(tier, "peer counts: %d seeders, %d leechers.", seeders, leechers);
tr_logAddDebugTier(tier, fmt::format("peer counts: {} seeders, {} leechers.", seeders, leechers));
(*tier->tor->torrent_announcer->callback)(tier->tor, &e, nullptr);
}
@ -671,10 +673,11 @@ static void publishPeersPex(tr_tier* tier, int seeders, int leechers, std::vecto
e.pex = pex;
tr_logAddDebugTier(
tier,
"tracker knows of %d seeders and %d leechers and gave a list of %zu peers.",
seeders,
leechers,
std::size(pex));
fmt::format(
"tracker knows of {} seeders and {} leechers and gave a list of {} peers.",
seeders,
leechers,
std::size(pex)));
(*tier->tor->torrent_announcer->callback)(tier->tor, &e, nullptr);
}
@ -737,7 +740,7 @@ static void tr_logAddTrace_tier_announce_queue(tr_tier const* tier)
}
auto const str = evbuffer_free_to_str(buf);
tr_logAddTraceTier(tier, "%s", str.c_str());
tr_logAddTraceTier(tier, str);
}
// higher priorities go to the front of the announce queue
@ -768,7 +771,7 @@ static void tier_announce_event_push(tr_tier* tier, tr_announce_event e, time_t
TR_ASSERT(tier != nullptr);
tr_logAddTrace_tier_announce_queue(tier);
tr_logAddTraceTier(tier, "queued \"%s\"", tr_announce_event_get_string(e));
tr_logAddTraceTier(tier, fmt::format("queued '{}'", tr_announce_event_get_string(e)));
auto& events = tier->announce_events;
if (!std::empty(events))
@ -798,7 +801,7 @@ static void tier_announce_event_push(tr_tier* tier, tr_announce_event e, time_t
tier_update_announce_priority(tier);
tr_logAddTrace_tier_announce_queue(tier);
tr_logAddTraceTier(tier, "announcing in %d seconds", (int)difftime(announceAt, tr_time()));
tr_logAddTraceTier(tier, fmt::format("announcing in {} seconds", difftime(announceAt, tr_time())));
}
static auto tier_announce_event_pull(tr_tier* tier)
@ -956,13 +959,21 @@ static void on_announce_error(tr_tier* tier, char const* err, tr_announce_event
if (isUnregistered(err))
{
tr_logAddErrorTier(tier, "announce error: %s", err);
tr_logAddErrorTier(tier, fmt::format(_("Announce error: {errmsg}"), fmt::arg("errmsg", err)));
}
else
{
/* schedule a reannounce */
int const interval = current_tracker->getRetryInterval();
tr_logAddWarnTier(tier, "announce error: %s (Retrying in %d seconds)", err, interval);
tr_logAddWarnTier(
tier,
fmt::format(
ngettext_(
"Announce error: {errmsg} (Retrying in {count} second)",
"Announce error: {errmsg} (Retrying in {count} seconds)",
interval),
fmt::arg("errmsg", err),
fmt::arg("count", interval)));
tier_announce_event_push(tier, e, tr_time() + interval);
}
}
@ -980,31 +991,32 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
{
tr_logAddTraceTier(
tier,
"Got announce response: "
"connected:%d "
"timeout:%d "
"seeders:%d "
"leechers:%d "
"downloads:%d "
"interval:%d "
"min_interval:%d "
"tracker_id_str:%s "
"pex:%zu "
"pex6:%zu "
"err:%s "
"warn:%s",
(int)response->did_connect,
(int)response->did_timeout,
response->seeders,
response->leechers,
response->downloads,
response->interval,
response->min_interval,
(!std::empty(response->tracker_id) ? response->tracker_id.c_str() : "none"),
std::size(response->pex),
std::size(response->pex6),
(!std::empty(response->errmsg) ? response->errmsg.c_str() : "none"),
(!std::empty(response->warning) ? response->warning.c_str() : "none"));
fmt::format(
"Got announce response: "
"connected:{} "
"timeout:{} "
"seeders:{} "
"leechers:{} "
"downloads:{} "
"interval:{} "
"min_interval:{} "
"tracker_id_str:{} "
"pex:{} "
"pex6:{} "
"err:{} "
"warn:{}",
response->did_connect,
response->did_timeout,
response->seeders,
response->leechers,
response->downloads,
response->interval,
response->min_interval,
(!std::empty(response->tracker_id) ? response->tracker_id.c_str() : "none"),
std::size(response->pex),
std::size(response->pex6),
(!std::empty(response->errmsg) ? response->errmsg.c_str() : "none"),
(!std::empty(response->warning) ? response->warning.c_str() : "none")));
tier->lastAnnounceTime = now;
tier->lastAnnounceTimedOut = response->did_timeout;
@ -1079,7 +1091,7 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
if (auto const& warning = response->warning; !std::empty(warning))
{
tier->last_announce_str = warning;
tr_logAddTraceTier(tier, "tracker gave \"%s\"", warning.c_str());
tr_logAddTraceTier(tier, fmt::format("tracker gave '{}'", warning));
publishWarning(tier, warning);
}
else
@ -1117,8 +1129,9 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
{
tr_logAddTraceTier(
tier,
"Announce response has scrape info; bumping next scrape to %d seconds from now.",
tier->scrapeIntervalSec);
fmt::format(
"Announce response has scrape info; bumping next scrape to {} seconds from now.",
tier->scrapeIntervalSec));
tier->scheduleNextScrape();
tier->lastScrapeTime = now;
tier->lastScrapeSucceeded = true;
@ -1145,7 +1158,7 @@ static void on_announce_done(tr_announce_response const* response, void* vdata)
{
/* the queue is empty, so enqueue a perodic update */
int const i = tier->announceIntervalSec;
tr_logAddTraceTier(tier, "Sending periodic reannounce in %d seconds", i);
tr_logAddTraceTier(tier, fmt::format("Sending periodic reannounce in {} seconds", i));
tier_announce_event_push(tier, TR_ANNOUNCE_EVENT_NONE, now + i);
}
}
@ -1183,7 +1196,7 @@ static void announce_request_delegate(
}
else
{
tr_logAddWarn("Unsupported url: %" TR_PRIsv, TR_PRIsv_ARG(announce_sv));
tr_logAddWarn(fmt::format("Unsupported url: {}", announce_sv));
delete callback_data;
}
@ -1250,7 +1263,9 @@ static void on_scrape_error(tr_session const* /*session*/, tr_tier* tier, char c
// schedule a rescrape
auto const interval = current_tracker->getRetryInterval();
auto const* const host_cstr = current_tracker->host.c_str();
tr_logAddDebugTier(tier, "Tracker '%s' scrape error: %s (Retrying in %zu seconds)", host_cstr, errmsg, (size_t)interval);
tr_logAddDebugTier(
tier,
fmt::format("Tracker '{}' scrape error: {} (Retrying in {} seconds)", host_cstr, errmsg, interval));
tier->lastScrapeSucceeded = false;
tier->scheduleNextScrape(interval);
}
@ -1286,7 +1301,7 @@ static void checkMultiscrapeMax(tr_announcer* announcer, tr_scrape_response cons
auto const parsed = *tr_urlParse(url.sv());
auto clean_url = std::string{};
tr_buildBuf(clean_url, parsed.scheme, "://"sv, parsed.host, ":"sv, parsed.portstr);
tr_logAddNamedInfo(clean_url.c_str(), "Reducing multiscrape max to %d", n);
tr_logAddNamedInfo(clean_url.c_str(), fmt::format(_("Reducing multiscrape max to {}"), n));
multiscrape_max = n;
}
}
@ -1315,25 +1330,26 @@ static void on_scrape_done(tr_scrape_response const* response, void* vsession)
tr_logAddTraceTier(
tier,
"scraped url:%" TR_PRIsv
" -- "
"did_connect:%d "
"did_timeout:%d "
"seeders:%d "
"leechers:%d "
"downloads:%d "
"downloaders:%d "
"min_request_interval:%d "
"err:%s ",
TR_PRIsv_ARG(scrape_url_sv),
(int)response->did_connect,
(int)response->did_timeout,
row.seeders,
row.leechers,
row.downloads,
row.downloaders,
response->min_request_interval,
std::empty(response->errmsg) ? "none" : response->errmsg.c_str());
fmt::format(
"scraped url:{} "
" -- "
"did_connect:{} "
"did_timeout:{} "
"seeders:{} "
"leechers:{} "
"downloads:{} "
"downloaders:{} "
"min_request_interval:{} "
"err:{} ",
scrape_url_sv,
response->did_connect,
response->did_timeout,
row.seeders,
row.leechers,
row.downloads,
row.downloaders,
response->min_request_interval,
std::empty(response->errmsg) ? "none"sv : response->errmsg));
tier->isScraping = false;
tier->lastScrapeTime = now;
@ -1357,7 +1373,7 @@ static void on_scrape_done(tr_scrape_response const* response, void* vsession)
tier->lastScrapeSucceeded = true;
tier->scrapeIntervalSec = std::max(int{ DefaultScrapeIntervalSec }, response->min_request_interval);
tier->scheduleNextScrape();
tr_logAddTraceTier(tier, "Scrape successful. Rescraping in %d seconds.", tier->scrapeIntervalSec);
tr_logAddTraceTier(tier, fmt::format("Scrape successful. Rescraping in {} seconds.", tier->scrapeIntervalSec));
if (tr_tracker* const tracker = tier->currentTracker(); tracker != nullptr)
{
@ -1411,7 +1427,7 @@ static void scrape_request_delegate(
}
else
{
tr_logAddError("Unsupported url: %" TR_PRIsv, TR_PRIsv_ARG(scrape_sv));
tr_logAddError(fmt::format(_("Unsupported URL: {url}"), fmt::arg("url", scrape_sv)));
}
}
@ -1566,7 +1582,7 @@ static void scrapeAndAnnounceMore(tr_announcer* announcer)
for (auto*& tier : announce_me)
{
tr_logAddTraceTier(tier, "%s", "Announcing to tracker");
tr_logAddTraceTier(tier, "Announcing to tracker");
tierAnnounce(announcer, tier);
}
}

View File

@ -8,6 +8,8 @@
#include <cstdlib> /* bsearch(), qsort() */
#include <cstring>
#include <fmt/core.h>
#include "transmission.h"
#include "blocklist.h"
@ -53,9 +55,6 @@ static void blocklistClose(tr_blocklistFile* b)
static void blocklistLoad(tr_blocklistFile* b)
{
tr_error* error = nullptr;
char const* err_fmt = _("Couldn't read \"%1$s\": %2$s");
blocklistClose(b);
auto info = tr_sys_path_info{};
@ -70,10 +69,15 @@ static void blocklistLoad(tr_blocklistFile* b)
return;
}
tr_error* error = nullptr;
auto const fd = tr_sys_file_open(b->filename, TR_SYS_FILE_READ, 0, &error);
if (fd == TR_BAD_SYS_FILE)
{
tr_logAddWarn(err_fmt, b->filename, error->message);
tr_logAddWarn(fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", b->filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
return;
}
@ -81,7 +85,11 @@ static void blocklistLoad(tr_blocklistFile* b)
b->rules = static_cast<struct tr_ipv4_range*>(tr_sys_file_map_for_reading(fd, 0, byteCount, &error));
if (b->rules == nullptr)
{
tr_logAddWarn(err_fmt, b->filename, error->message);
tr_logAddWarn(fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", b->filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_sys_file_close(fd, nullptr);
tr_error_free(error);
return;
@ -92,7 +100,10 @@ static void blocklistLoad(tr_blocklistFile* b)
b->ruleCount = byteCount / sizeof(struct tr_ipv4_range);
char* const base = tr_sys_path_basename(b->filename, nullptr);
tr_logAddInfo(_("Blocklist \"%s\" contains %zu entries"), base, b->ruleCount);
tr_logAddInfo(fmt::format(
ngettext_("Blocklist '{path}' has {count} entry", "Blocklist '{path}' has {count} entries", b->ruleCount),
fmt::arg("path", base),
fmt::arg("count", b->ruleCount)));
tr_free(base);
}
@ -355,7 +366,6 @@ int tr_blocklistFileSetContent(tr_blocklistFile* b, char const* filename)
{
int inCount = 0;
char line[2048];
char const* err_fmt = _("Couldn't read \"%1$s\": %2$s");
// TODO: should be a vector
struct tr_ipv4_range* ranges = nullptr;
size_t ranges_alloc = 0;
@ -371,7 +381,11 @@ int tr_blocklistFileSetContent(tr_blocklistFile* b, char const* filename)
auto const in = tr_sys_file_open(filename, TR_SYS_FILE_READ, 0, &error);
if (in == TR_BAD_SYS_FILE)
{
tr_logAddWarn(err_fmt, filename, error->message);
tr_logAddWarn(fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
return 0;
}
@ -381,7 +395,11 @@ int tr_blocklistFileSetContent(tr_blocklistFile* b, char const* filename)
auto const out = tr_sys_file_open(b->filename, TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE, 0666, &error);
if (out == TR_BAD_SYS_FILE)
{
tr_logAddWarn(err_fmt, b->filename, error->message);
tr_logAddWarn(fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", b->filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
tr_sys_file_close(in, nullptr);
return 0;
@ -397,7 +415,7 @@ int tr_blocklistFileSetContent(tr_blocklistFile* b, char const* filename)
if (!parseLine(line, &range))
{
/* don't try to display the actual lines - it causes issues */
tr_logAddWarn(_("blocklist skipped invalid address at line %d"), inCount);
tr_logAddWarn(fmt::format(_("Couldn't parse line: '{line}'"), fmt::arg("line", inCount)));
continue;
}
@ -454,13 +472,23 @@ int tr_blocklistFileSetContent(tr_blocklistFile* b, char const* filename)
if (!tr_sys_file_write(out, ranges, sizeof(struct tr_ipv4_range) * ranges_count, nullptr, &error))
{
tr_logAddWarn(_("Couldn't save file \"%1$s\": %2$s"), b->filename, error->message);
tr_logAddWarn(fmt::format(
_("Couldn't save '{path}': {errmsg} ({errcode})"),
fmt::arg("path", b->filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
}
else
{
char* base = tr_sys_path_basename(b->filename, nullptr);
tr_logAddInfo(_("Blocklist \"%s\" updated with %zu entries"), base, ranges_count);
tr_logAddInfo(fmt::format(
ngettext_(
"Blocklist '{path}' updated with {count} entry",
"Blocklist '{path}' updated with {count} entries",
ranges_count),
fmt::arg("path", base),
fmt::arg("count", ranges_count)));
tr_free(base);
}

View File

@ -12,7 +12,10 @@
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonRandom.h>
#include <fmt/core.h>
#include "transmission.h"
#include "crypto-utils.h"
#include "log.h"
#include "tr-assert.h"
@ -93,14 +96,12 @@ void log_ccrypto_error(CCCryptorStatus error_code, char const* file, int line)
{
if (tr_logLevelIsActive(TR_LOG_ERROR))
{
tr_logAddMessage(
file,
line,
TR_LOG_ERROR,
MyName,
"CCrypto error (%d): %s",
error_code,
ccrypto_error_to_str(error_code));
auto const errmsg = fmt::format(
_("{crypto_library} error: {errmsg} ({errcode})"),
fmt::arg("crypto_library", "CCrypto"),
fmt::arg("errmsg", ccrypto_error_to_str(error_code)),
fmt::arg("errcode", error_code));
tr_logAddMessage(file, line, TR_LOG_ERROR, MyName, errmsg);
}
}

View File

@ -24,6 +24,8 @@
#include API_HEADER_CRYPT(sha.h)
#include API_HEADER(version.h)
#include <fmt/core.h>
#include "transmission.h"
#include "crypto-utils.h"
#include "log.h"
@ -61,7 +63,12 @@ static void log_cyassl_error(int error_code, char const* file, int line)
CTaoCryptErrorString(error_code, error_message);
#endif
tr_logAddMessage(file, line, TR_LOG_ERROR, MyName, "CyaSSL error: %s", error_message);
auto const errmsg = fmt::format(
_("{crypto_library} error: {errmsg} ({errcode})"),
fmt::arg("crypto_library", "CyaSSL"),
fmt::arg("errmsg", error_message),
fmt::arg("errcode", error_code));
tr_logAddMessage(file, line, TR_LOG_ERROR, MyName, errmsg);
}
}

View File

@ -18,6 +18,8 @@
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <fmt/core.h>
#include "transmission.h"
#include "crypto-utils.h"
#include "log.h"
@ -59,7 +61,12 @@ static void log_openssl_error(char const* file, int line)
#endif
ERR_error_string_n(error_code, buf, sizeof(buf));
tr_logAddMessage(file, line, TR_LOG_ERROR, MyName, "OpenSSL error: %s", buf);
auto const errmsg = fmt::format(
_("{crypto_library} error: {errmsg} ({errcode})"),
fmt::arg("crypto_library", "OpenSSL"),
fmt::arg("errmsg", buf),
fmt::arg("errcode", error_code));
tr_logAddMessage(file, line, TR_LOG_ERROR, MyName, errmsg);
}
}

View File

@ -22,6 +22,8 @@
#include API_HEADER(sha1.h)
#include API_HEADER(version.h)
#include <fmt/core.h>
#include "transmission.h"
#include "crypto-utils.h"
#include "log.h"
@ -56,7 +58,12 @@ static void log_polarssl_error(int error_code, char const* file, int line)
error_strerror(error_code, error_message, sizeof(error_message));
#endif
tr_logAddMessage(file, line, TR_LOG_ERROR, MyName, "PolarSSL error: %s", error_message);
auto const errmsg = fmt::format(
_("{crypto_library} error: {errmsg} ({errcode})"),
fmt::arg("crypto_library", "PolarSSL"),
fmt::arg("errmsg", error_message),
fmt::arg("errcode", error_code));
tr_logAddMessage(file, line, TR_LOG_ERROR, MyName, errmsg);
}
}

View File

@ -9,6 +9,8 @@
#include <cinttypes>
#include <ctime>
#include <fmt/core.h>
#include "transmission.h"
#include "error-types.h"
@ -41,7 +43,7 @@ static bool preallocate_file_sparse(tr_sys_file_t fd, uint64_t length, tr_error*
return true;
}
tr_logAddDebug("Preallocating (sparse, normal) failed (%d): %s", my_error->code, my_error->message);
tr_logAddDebug(fmt::format("Fast preallocation failed: {} ({})", my_error->message, my_error->code));
if (!TR_ERROR_IS_ENOSPC(my_error->code))
{
@ -55,7 +57,7 @@ static bool preallocate_file_sparse(tr_sys_file_t fd, uint64_t length, tr_error*
return true;
}
tr_logAddDebug("Preallocating (sparse, fallback) failed (%d): %s", my_error->code, my_error->message);
tr_logAddDebug(fmt::format("Fast prellocation fallback failed: {} ({})", my_error->message, my_error->code));
}
tr_error_propagate(error, &my_error);
@ -76,7 +78,7 @@ static bool preallocate_file_full(tr_sys_file_t fd, uint64_t length, tr_error**
return true;
}
tr_logAddDebug("Preallocating (full, normal) failed (%d): %s", my_error->code, my_error->message);
tr_logAddDebug(fmt::format("Full preallocation failed: {} ({})", my_error->message, my_error->code));
if (!TR_ERROR_IS_ENOSPC(my_error->code))
{
@ -99,7 +101,7 @@ static bool preallocate_file_full(tr_sys_file_t fd, uint64_t length, tr_error**
return true;
}
tr_logAddDebug("Preallocating (full, fallback) failed (%d): %s", my_error->code, my_error->message);
tr_logAddDebug(fmt::format("Full preallocation fallback failed: {} ({})", my_error->message, my_error->code));
}
tr_error_propagate(error, &my_error);
@ -166,13 +168,21 @@ static int cached_file_open(
if (dir == nullptr)
{
tr_logAddError(_("Couldn't get directory for \"%1$s\": %2$s"), filename, error->message);
tr_logAddError(fmt::format(
_("Couldn't create '{path}': {errmsg} ({errcode})"),
fmt::arg("path", filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
goto FAIL;
}
if (!tr_sys_dir_create(dir, TR_SYS_DIR_CREATE_PARENTS, 0777, &error))
{
tr_logAddError(_("Couldn't create \"%1$s\": %2$s"), dir, error->message);
tr_logAddError(fmt::format(
_("Couldn't create '{path}': {errmsg} ({errcode})"),
fmt::arg("path", dir),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_free(dir);
goto FAIL;
}
@ -193,7 +203,11 @@ static int cached_file_open(
if (fd == TR_BAD_SYS_FILE)
{
tr_logAddError(_("Couldn't open \"%1$s\": %2$s"), filename, error->message);
tr_logAddError(fmt::format(
_("Couldn't open '{path}': {errmsg} ({errcode})"),
fmt::arg("path", filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
goto FAIL;
}
@ -217,16 +231,15 @@ static int cached_file_open(
if (!success)
{
tr_logAddWarn(
_("Couldn't preallocate file \"%1$s\" (%2$s, size: %3$" PRIu64 "): %4$s"),
filename,
type,
file_size,
error->message);
tr_logAddError(fmt::format(
_("Couldn't preallocate '{path}': {errmsg} ({errcode})"),
fmt::arg("path", filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
goto FAIL;
}
tr_logAddDebug(_("Preallocated file \"%1$s\" (%2$s, size: %3$" PRIu64 ")"), filename, type, file_size);
tr_logAddDebug(fmt::format("Preallocated file '{}' ({}, size: {})", filename, type, file_size));
}
/* If the file already exists and it's too large, truncate it.
@ -237,7 +250,11 @@ static int cached_file_open(
*/
if (resize_needed && !tr_sys_file_truncate(fd, file_size, &error))
{
tr_logAddWarn(_("Couldn't truncate \"%1$s\": %2$s"), filename, error->message);
tr_logAddWarn(fmt::format(
_("Couldn't truncate '{path}': {errmsg} ({errcode})"),
fmt::arg("path", filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
goto FAIL;
}
@ -477,11 +494,11 @@ tr_sys_file_t tr_fdFileCheckout(
return TR_BAD_SYS_FILE;
}
tr_logAddTrace("opened '%s' writable %c", filename, writable ? 'y' : 'n');
tr_logAddTrace(fmt::format("opened '{}' writable {}", filename, writable ? 'y' : 'n'));
o->is_writable = writable;
}
tr_logAddTrace("checking out '%s'", filename);
tr_logAddTrace(fmt::format("checking out '{}'", filename));
o->torrent_id = torrent_id;
o->file_index = i;
o->used_at = tr_time();
@ -509,7 +526,10 @@ tr_socket_t tr_fdSocketCreate(tr_session* session, int domain, int type)
if ((s == TR_BAD_SOCKET) && (sockerrno != EAFNOSUPPORT))
{
tr_logAddWarn(_("Couldn't create socket: %s"), tr_net_strerror(sockerrno).c_str());
tr_logAddWarn(fmt::format(
_("Couldn't create socket: {errmsg} ({errcode})"),
fmt::arg("errmsg", tr_net_strerror(sockerrno)),
fmt::arg("errcode", sockerrno)));
}
}
@ -531,7 +551,7 @@ tr_socket_t tr_fdSocketCreate(tr_session* session, int domain, int type)
if (getsockopt(s, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<char*>(&i), &size) != -1)
{
tr_logAddTrace("SO_SNDBUF size is %d", i);
tr_logAddTrace(fmt::format("SO_SNDBUF size is {}", i));
}
i = 0;
@ -539,7 +559,7 @@ tr_socket_t tr_fdSocketCreate(tr_session* session, int domain, int type)
if (getsockopt(s, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<char*>(&i), &size) != -1)
{
tr_logAddTrace("SO_RCVBUF size is %d", i);
tr_logAddTrace(fmt::format("SO_RCVBUF size is {}", i));
}
buf_logged = true;

View File

@ -51,6 +51,8 @@
#define USE_COPY_FILE_RANGE
#endif /* __linux__ */
#include <fmt/core.h>
#include "transmission.h"
#include "error.h"
#include "file.h"
@ -265,7 +267,11 @@ FAILURE:
TR_ASSERT(!ret);
TR_ASSERT(my_error != nullptr);
tr_logAddError(_("Couldn't create \"%1$s\": %2$s"), path, my_error->message);
tr_logAddError(fmt::format(
_("Couldn't create '{path}': {errmsg} ({errcode})"),
fmt::arg("path", path),
fmt::arg("errmsg", my_error->message),
fmt::arg("errcode", my_error->code)));
tr_error_propagate(error, &my_error);
CLEANUP:

View File

@ -12,6 +12,8 @@
#include <event2/buffer.h>
#include <event2/event.h>
#include <fmt/core.h>
#include "transmission.h"
#include "clients.h"
#include "crypto-utils.h"
@ -155,7 +157,7 @@ static char const* getStateName(handshake_state_t const state)
static void setState(tr_handshake* handshake, handshake_state_t state)
{
tr_logAddTraceHand(handshake, "setting to state [%s]", getStateName(state));
tr_logAddTraceHand(handshake, fmt::format("setting to state [{}]", getStateName(state)));
handshake->state = state;
}
@ -214,7 +216,7 @@ static handshake_parse_err_t parseHandshake(tr_handshake* handshake, struct evbu
uint8_t name[HANDSHAKE_NAME_LEN];
uint8_t reserved[HANDSHAKE_FLAGS_LEN];
tr_logAddTraceHand(handshake, "payload: need %d, got %zu", HANDSHAKE_SIZE, evbuffer_get_length(inbuf));
tr_logAddTraceHand(handshake, fmt::format("payload: need {}, got {}", HANDSHAKE_SIZE, evbuffer_get_length(inbuf)));
if (evbuffer_get_length(inbuf) < HANDSHAKE_SIZE)
{
@ -247,7 +249,8 @@ static handshake_parse_err_t parseHandshake(tr_handshake* handshake, struct evbu
handshake->peer_id = peer_id;
/* peer id */
tr_logAddTraceHand(handshake, "peer-id is [%" TR_PRIsv "]", TR_PRIsv_ARG(peer_id));
auto const peer_id_sv = std::string_view{ std::data(peer_id), std::size(peer_id) };
tr_logAddTraceHand(handshake, fmt::format("peer-id is '{}'", peer_id_sv));
if (auto* const tor = handshake->session->torrents().get(hash); peer_id == tr_torrentGetPeerId(tor))
{
@ -375,7 +378,7 @@ static ReadState readYb(tr_handshake* handshake, struct evbuffer* inbuf)
}
}
tr_logAddTraceHand(handshake, "got an %s handshake", (isEncrypted ? "encrypted" : "plain"));
tr_logAddTraceHand(handshake, isEncrypted ? "got an encrypted handshake" : "got a plain handshake");
tr_peerIoSetEncryption(handshake->io, isEncrypted ? PEER_ENCRYPTION_RC4 : PEER_ENCRYPTION_NONE);
@ -516,7 +519,7 @@ static ReadState readCryptoSelect(tr_handshake* handshake, struct evbuffer* inbu
uint32_t crypto_select = 0;
tr_peerIoReadUint32(handshake->io, inbuf, &crypto_select);
handshake->crypto_select = crypto_select;
tr_logAddTraceHand(handshake, "crypto select is %d", (int)crypto_select);
tr_logAddTraceHand(handshake, fmt::format("crypto select is {}", crypto_select));
if ((crypto_select & getCryptoProvide(handshake)) == 0)
{
@ -526,7 +529,7 @@ static ReadState readCryptoSelect(tr_handshake* handshake, struct evbuffer* inbu
uint16_t pad_d_len = 0;
tr_peerIoReadUint16(handshake->io, inbuf, &pad_d_len);
tr_logAddTraceHand(handshake, "pad_d_len is %d", (int)pad_d_len);
tr_logAddTraceHand(handshake, fmt::format("pad_d_len is {}", pad_d_len));
if (pad_d_len > 512)
{
@ -544,7 +547,7 @@ static ReadState readPadD(tr_handshake* handshake, struct evbuffer* inbuf)
{
size_t const needlen = handshake->pad_d_len;
tr_logAddTraceHand(handshake, "pad d: need %zu, got %zu", needlen, evbuffer_get_length(inbuf));
tr_logAddTraceHand(handshake, fmt::format("pad d: need {}, got {}", needlen, evbuffer_get_length(inbuf)));
if (evbuffer_get_length(inbuf) < needlen)
{
@ -567,7 +570,7 @@ static ReadState readPadD(tr_handshake* handshake, struct evbuffer* inbuf)
static ReadState readHandshake(tr_handshake* handshake, struct evbuffer* inbuf)
{
tr_logAddTraceHand(handshake, "payload: need %d, got %zu", INCOMING_HANDSHAKE_LEN, evbuffer_get_length(inbuf));
tr_logAddTraceHand(handshake, fmt::format("payload: need {}, got {}", INCOMING_HANDSHAKE_LEN, evbuffer_get_length(inbuf)));
if (evbuffer_get_length(inbuf) < INCOMING_HANDSHAKE_LEN)
{
@ -691,7 +694,9 @@ static ReadState readPeerId(tr_handshake* handshake, struct evbuffer* inbuf)
char client[128] = {};
tr_clientForId(client, sizeof(client), peer_id);
tr_logAddTraceHand(handshake, "peer-id is [%s] ... isIncoming is %d", client, tr_peerIoIsIncoming(handshake->io));
tr_logAddTraceHand(
handshake,
fmt::format("peer-id is '{}' ... isIncoming is {}", client, tr_peerIoIsIncoming(handshake->io)));
// if we've somehow connected to ourselves, don't keep the connection
auto const hash = tr_peerIoGetTorrentHash(handshake->io);
@ -703,7 +708,7 @@ static ReadState readPeerId(tr_handshake* handshake, struct evbuffer* inbuf)
static ReadState readYa(tr_handshake* handshake, struct evbuffer* inbuf)
{
tr_logAddTraceHand(handshake, "in readYa... need %d, have %zu", KEY_LEN, evbuffer_get_length(inbuf));
tr_logAddTraceHand(handshake, fmt::format("in readYa... need {}, have {}", KEY_LEN, evbuffer_get_length(inbuf)));
if (evbuffer_get_length(inbuf) < KEY_LEN)
{
@ -811,7 +816,9 @@ static ReadState readCryptoProvide(tr_handshake* handshake, struct evbuffer* inb
{
bool const clientIsSeed = tor->isDone();
bool const peerIsSeed = tr_peerMgrPeerIsSeed(tor, tr_peerIoGetAddress(handshake->io, nullptr));
tr_logAddTraceHand(handshake, "got INCOMING connection's encrypted handshake for torrent [%s]", tr_torrentName(tor));
tr_logAddTraceHand(
handshake,
fmt::format("got INCOMING connection's encrypted handshake for torrent [{}]", tor->name()));
tr_peerIoSetTorrentHash(handshake->io, tor->infoHash());
if (clientIsSeed && peerIsSeed)
@ -834,10 +841,10 @@ static ReadState readCryptoProvide(tr_handshake* handshake, struct evbuffer* inb
tr_peerIoReadUint32(handshake->io, inbuf, &crypto_provide);
handshake->crypto_provide = crypto_provide;
tr_logAddTraceHand(handshake, "crypto_provide is %d", (int)crypto_provide);
tr_logAddTraceHand(handshake, fmt::format("crypto_provide is {}", crypto_provide));
tr_peerIoReadUint16(handshake->io, inbuf, &padc_len);
tr_logAddTraceHand(handshake, "padc is %d", (int)padc_len);
tr_logAddTraceHand(handshake, fmt::format("padc is {}", padc_len));
handshake->pad_c_len = padc_len;
setState(handshake, AWAITING_PAD_C);
return READ_NOW;
@ -859,7 +866,7 @@ static ReadState readPadC(tr_handshake* handshake, struct evbuffer* inbuf)
/* read ia_len */
tr_peerIoReadUint16(handshake->io, inbuf, &ia_len);
tr_logAddTraceHand(handshake, "ia_len is %d", (int)ia_len);
tr_logAddTraceHand(handshake, fmt::format("ia_len is {}", ia_len));
handshake->ia_len = ia_len;
setState(handshake, AWAITING_IA);
return READ_NOW;
@ -869,7 +876,7 @@ static ReadState readIA(tr_handshake* handshake, struct evbuffer const* inbuf)
{
size_t const needlen = handshake->ia_len;
tr_logAddTraceHand(handshake, "reading IA... have %zu, need %zu", evbuffer_get_length(inbuf), needlen);
tr_logAddTraceHand(handshake, fmt::format("reading IA... have {}, need {}", evbuffer_get_length(inbuf), needlen));
if (evbuffer_get_length(inbuf) < needlen)
{
@ -896,7 +903,7 @@ static ReadState readIA(tr_handshake* handshake, struct evbuffer const* inbuf)
if (crypto_select != 0)
{
tr_logAddTraceHand(handshake, "selecting crypto mode '%d'", (int)crypto_select);
tr_logAddTraceHand(handshake, fmt::format("selecting crypto mode '{}'", crypto_select));
evbuffer_add_uint32(outbuf, crypto_select);
}
else
@ -951,7 +958,9 @@ static ReadState readPayloadStream(tr_handshake* handshake, struct evbuffer* inb
{
size_t const needlen = HANDSHAKE_SIZE;
tr_logAddTraceHand(handshake, "reading payload stream... have %zu, need %zu", evbuffer_get_length(inbuf), needlen);
tr_logAddTraceHand(
handshake,
fmt::format("reading payload stream... have {}, need {}", evbuffer_get_length(inbuf), needlen));
if (evbuffer_get_length(inbuf) < needlen)
{
@ -960,7 +969,7 @@ static ReadState readPayloadStream(tr_handshake* handshake, struct evbuffer* inb
/* parse the handshake ... */
handshake_parse_err_t const i = parseHandshake(handshake, inbuf);
tr_logAddTraceHand(handshake, "parseHandshake returned %d", i);
tr_logAddTraceHand(handshake, fmt::format("parseHandshake returned {}", i));
if (i != HANDSHAKE_OK)
{
@ -989,7 +998,7 @@ static ReadState canRead(tr_peerIo* io, void* vhandshake, size_t* piece)
/* no piece data in handshake */
*piece = 0;
tr_logAddTraceHand(handshake, "handling canRead; state is [%s]", getStateName(handshake->state));
tr_logAddTraceHand(handshake, fmt::format("handling canRead; state is [{}]", getStateName(handshake->state)));
ReadState ret = READ_NOW;
while (readyForMore)
@ -1100,7 +1109,7 @@ static void tr_handshakeFree(tr_handshake* handshake)
static ReadState tr_handshakeDone(tr_handshake* handshake, bool isOK)
{
tr_logAddTraceHand(handshake, "handshakeDone: %s", isOK ? "connected" : "aborting");
tr_logAddTraceHand(handshake, isOK ? "handshakeDone: connected" : "handshakeDone: aborting");
tr_peerIoSetIOFuncs(handshake->io, nullptr, nullptr, nullptr, nullptr);
bool const success = fireDoneFunc(handshake, isOK);
@ -1162,10 +1171,7 @@ static void gotError(tr_peerIo* io, short what, void* vhandshake)
{
tr_logAddTraceHand(
handshake,
"libevent got an error what==%d, errno=%d (%s)",
(int)what,
errcode,
tr_strerror(errcode));
fmt::format("libevent got an error what=={}, errno={} ({})", what, errcode, tr_strerror(errcode)));
tr_handshakeDone(handshake, false);
}
}

View File

@ -8,6 +8,8 @@
#include <optional>
#include <vector>
#include <fmt/core.h>
#include "transmission.h"
#include "cache.h" /* tr_cacheReadBlock() */
@ -131,7 +133,13 @@ int readOrWriteBytes(
if (fd == TR_BAD_SYS_FILE)
{
err = errno;
tr_logAddErrorTor(tor, "tr_fdFileCheckout failed for \"%s\": %s", filename.c_str(), tr_strerror(err));
tr_logAddErrorTor(
tor,
fmt::format(
_("Couldn't get '{path}': {errmsg} ({errcode})"),
fmt::arg("path", filename),
fmt::arg("errmsg", tr_strerror(err)),
fmt::arg("errcode", err)));
}
else if (doWrite)
{
@ -160,7 +168,13 @@ int readOrWriteBytes(
if (!readEntireBuf(fd, file_offset, buf, buflen, &error))
{
err = error->code;
tr_logAddErrorTor(tor, "read failed for \"%s\": %s", tor->fileSubpath(file_index).c_str(), error->message);
tr_logAddErrorTor(
tor,
fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", tor->fileSubpath(file_index)),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
}
break;
@ -169,7 +183,13 @@ int readOrWriteBytes(
if (!writeEntireBuf(fd, file_offset, buf, buflen, &error))
{
err = error->code;
tr_logAddErrorTor(tor, "write failed for \"%s\": %s", tor->fileSubpath(file_index).c_str(), error->message);
tr_logAddErrorTor(
tor,
fmt::format(
_("Couldn't save '{path}': {errmsg} ({errcode})"),
fmt::arg("path", tor->fileSubpath(file_index)),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
}
break;

View File

@ -231,13 +231,7 @@ void logAddImpl(
#endif
}
void tr_logAddMessage(
[[maybe_unused]] char const* file,
[[maybe_unused]] int line,
tr_log_level level,
[[maybe_unused]] std::string_view name,
char const* fmt,
...)
void tr_logAddMessage(char const* file, int line, tr_log_level level, std::string_view name, std::string_view msg)
{
// message logging shouldn't affect errno
int const err = errno;
@ -269,6 +263,27 @@ void tr_logAddMessage(
}
}
// log the messages
logAddImpl(file, line, level, name, msg);
if (last_one)
{
logAddImpl(file, line, level, "", _("Too many messages like this! I won't log this message anymore this session."));
}
errno = err;
}
void tr_logAddMessage(
[[maybe_unused]] char const* file,
[[maybe_unused]] int line,
tr_log_level level,
[[maybe_unused]] std::string_view name,
char const* fmt,
...)
{
// message logging shouldn't affect errno
int const err = errno;
// build the message
auto buf = std::array<char, 2048>{};
va_list ap;
@ -281,12 +296,5 @@ void tr_logAddMessage(
return;
}
// log the messages
logAddImpl(file, line, level, name, std::data(buf));
if (last_one)
{
logAddImpl(file, line, level, "", _("Too many messages like this! I won't log this message anymore this session."));
}
errno = err;
tr_logAddMessage(file, line, level, name, std::string_view{ std::data(buf) });
}

View File

@ -18,6 +18,8 @@
return tr_logGetLevel() >= level;
}
void tr_logAddMessage(char const* file, int line, tr_log_level level, std::string_view name, std::string_view msg);
void tr_logAddMessage(char const* file, int line, tr_log_level level, std::string_view name, char const* fmt, ...)
TR_GNUC_PRINTF(5, 6);

View File

@ -14,6 +14,8 @@
#include <event2/util.h> /* evutil_ascii_strcasecmp() */
#include <fmt/core.h>
#include "transmission.h"
#include "crypto-utils.h"
@ -55,7 +57,11 @@ static struct FileList* getFiles(char const* dir, char const* base, struct FileL
tr_sys_path_info info;
if (tr_error* error = nullptr; !tr_sys_path_get_info(buf.c_str(), 0, &info, &error))
{
tr_logAddWarn(_("Torrent Creator is skipping file \"%s\": %s"), buf.c_str(), error->message);
tr_logAddWarn(fmt::format(
_("Skipping '{path}': {errmsg} ({errcode})"),
fmt::arg("path", buf),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
return list;
}
@ -200,10 +206,10 @@ bool tr_metaInfoBuilderSetPieceSize(tr_metainfo_builder* b, uint32_t bytes)
{
if (!isValidPieceSize(bytes))
{
tr_logAddWarn(
_("Failed to set piece size to %s, leaving it at %s"),
tr_formatter_mem_B(bytes).c_str(),
tr_formatter_mem_B(b->pieceSize).c_str());
tr_logAddWarn(fmt::format(
_("Couldn't use invalid piece size {size_requested}; using {size_used} instead"),
fmt::arg("size_requested", tr_formatter_mem_B(bytes)),
fmt::arg("size_used", tr_formatter_mem_B(b->pieceSize))));
return false;
}

View File

@ -10,6 +10,8 @@
#include <event2/util.h> /* evutil_inet_ntop() */
#include <fmt/core.h>
#define ENABLE_STRNATPMPERR
#include "natpmp.h"
@ -38,18 +40,19 @@ static void logVal(char const* func, int ret)
if (ret >= 0)
{
tr_logAddNamedInfo(CodeName, _("%s succeeded (%d)"), func, ret);
tr_logAddNamedDebug(CodeName, fmt::format("{} succeeded ({})", func, ret));
}
else
{
tr_logAddNamedDebug(
CodeName,
"%s failed. Natpmp returned %d (%s); errno is %d (%s)",
func,
ret,
strnatpmperr(ret),
errno,
tr_strerror(errno));
fmt::format(
"{} failed. Natpmp returned {} ({}); errno is {} ({})",
func,
ret,
strnatpmperr(ret),
errno,
tr_strerror(errno)));
}
}
@ -110,7 +113,7 @@ tr_port_forwarding tr_natpmpPulse(
{
char str[128];
evutil_inet_ntop(AF_INET, &response.pnu.publicaddress.addr, str, sizeof(str));
tr_logAddNamedInfo(CodeName, _("Found public address \"%s\""), str);
tr_logAddNamedInfo(CodeName, fmt::format(_("Found public address '{address}'"), fmt::arg("address", str)));
nat->state = TR_NATPMP_IDLE;
}
else if (val != NATPMP_TRYAGAIN)
@ -143,7 +146,7 @@ tr_port_forwarding tr_natpmpPulse(
{
int const unmapped_port = resp.pnu.newportmapping.privateport;
tr_logAddNamedInfo(CodeName, _("no longer forwarding port %d"), unmapped_port);
tr_logAddNamedInfo(CodeName, fmt::format(_("Port {port} is no longer forwarded"), fmt::arg("port", unmapped_port)));
if (nat->private_port == unmapped_port)
{
@ -192,7 +195,9 @@ tr_port_forwarding tr_natpmpPulse(
nat->renew_time = tr_time() + (resp.pnu.newportmapping.lifetime / 2);
nat->private_port = resp.pnu.newportmapping.privateport;
nat->public_port = resp.pnu.newportmapping.mappedpublicport;
tr_logAddNamedInfo(CodeName, _("Port %d forwarded successfully"), nat->private_port);
tr_logAddNamedInfo(
CodeName,
fmt::format(_("Port {port} forwarded successfully"), fmt::arg("port", nat->private_port)));
}
else if (val != NATPMP_TRYAGAIN)
{

View File

@ -15,6 +15,9 @@
#include <libutp/utp.h>
#include <fmt/core.h>
#include <fmt/format.h> // fmt::ptr
#include "transmission.h"
#include "session.h"
#include "bandwidth.h"
@ -302,7 +305,9 @@ static void event_read_cb(evutil_socket_t fd, short /*event*/, void* vio)
what |= BEV_EVENT_ERROR;
}
tr_logAddDebugIo(io, "event_read_cb err: res:%d, what:%hd, errno:%d (%s)", res, what, e, tr_net_strerror(e).c_str());
tr_logAddDebugIo(
io,
fmt::format("event_read_cb err: res:{}, what:{}, errno:{} ({})", res, what, e, tr_net_strerror(e)));
if (io->gotError != nullptr)
{
@ -316,7 +321,7 @@ static int tr_evbuffer_write(tr_peerIo* io, int fd, size_t howmuch)
EVUTIL_SET_SOCKET_ERROR(0);
int const n = evbuffer_write_atmost(io->outbuf, fd, howmuch);
int const e = EVUTIL_SOCKET_ERROR();
tr_logAddTraceIo(io, "wrote %d to peer (%s)", n, (n == -1 ? tr_net_strerror(e).c_str() : ""));
tr_logAddTraceIo(io, fmt::format("wrote {} to peer ({})", n, (n == -1 ? tr_net_strerror(e).c_str() : "")));
return n;
}
@ -390,7 +395,7 @@ RESCHEDULE:
FAIL:
auto const errmsg = tr_net_strerror(e);
tr_logAddDebugIo(io, "event_write_cb got an err. res:%d, what:%hd, errno:%d (%s)", res, what, e, errmsg.c_str());
tr_logAddDebugIo(io, fmt::format("event_write_cb got an err. res:{}, what:{}, errno:{} ({})", res, what, e, errmsg));
if (io->gotError != nullptr)
{
@ -420,7 +425,7 @@ static void utp_on_read(void* vio, unsigned char const* buf, size_t buflen)
TR_ASSERT(tr_isPeerIo(io));
int rc = evbuffer_add(io->inbuf, buf, buflen);
tr_logAddTraceIo(io, "utp_on_read got %zu bytes", buflen);
tr_logAddTraceIo(io, fmt::format("utp_on_read got {} bytes", buflen));
if (rc < 0)
{
@ -439,12 +444,16 @@ static void utp_on_write(void* vio, unsigned char* buf, size_t buflen)
TR_ASSERT(tr_isPeerIo(io));
int rc = evbuffer_remove(io->outbuf, buf, buflen);
tr_logAddTraceIo(io, "utp_on_write sending %zu bytes... evbuffer_remove returned %d", buflen, rc);
tr_logAddTraceIo(io, fmt::format("utp_on_write sending {} bytes... evbuffer_remove returned {}", buflen, rc));
TR_ASSERT(rc == (int)buflen); /* if this fails, we've corrupted our bookkeeping somewhere */
if (rc < (long)buflen)
{
tr_logAddWarnIo(io, "Short write: %d < %ld", rc, (long)buflen);
auto const errmsg = fmt::format(
_("Couldn't write {expected_size} bytes to peer; wrote {actual_size}"),
fmt::arg("expected_size", buflen),
fmt::arg("actual_size", rc));
tr_logAddWarnIo(io, errmsg);
}
didWriteWrapper(io, buflen);
@ -458,7 +467,7 @@ static size_t utp_get_rb_size(void* vio)
size_t bytes = io->bandwidth->clamp(TR_DOWN, UTP_READ_BUFFER_SIZE);
tr_logAddTraceIo(io, "utp_get_rb_size is saying it's ready to read %zu bytes", bytes);
tr_logAddTraceIo(io, fmt::format("utp_get_rb_size is saying it's ready to read {} bytes", bytes));
return UTP_READ_BUFFER_SIZE - bytes;
}
@ -506,7 +515,7 @@ static void utp_on_state_change(void* vio, int state)
}
else
{
tr_logAddErrorIo(io, "Unknown state %d", state);
tr_logAddErrorIo(io, fmt::format(_("Unknown state: {state}"), fmt::arg("state", state)));
}
}
@ -516,7 +525,7 @@ static void utp_on_error(void* vio, int errcode)
TR_ASSERT(tr_isPeerIo(io));
tr_logAddDebugIo(io, "utp_on_error -- errcode is %d", errcode);
tr_logAddDebugIo(io, fmt::format("utp_on_error -- errcode is {}", errcode));
if (io->gotError != nullptr)
{
@ -531,7 +540,7 @@ static void utp_on_overhead(void* vio, bool send, size_t count, int /*type*/)
TR_ASSERT(tr_isPeerIo(io));
tr_logAddTraceIo(io, "utp_on_overhead -- count is %zu", count);
tr_logAddTraceIo(io, fmt::format("utp_on_overhead -- count is {}", count));
io->bandwidth->notifyBandwidthConsumed(send ? TR_UP : TR_DOWN, count, false, tr_time_msec());
}
@ -612,12 +621,12 @@ static tr_peerIo* tr_peerIoNew(
io->socket = socket;
io->bandwidth = new Bandwidth(parent);
io->bandwidth->setPeer(io);
tr_logAddTraceIo(io, "bandwidth is %p; its parent is %p", (void*)&io->bandwidth, (void*)parent);
tr_logAddTraceIo(io, fmt::format("bandwidth is {}; its parent is {}", fmt::ptr(&io->bandwidth), fmt::ptr(parent)));
switch (socket.type)
{
case TR_PEER_SOCKET_TYPE_TCP:
tr_logAddTraceIo(io, "socket (tcp) is %" PRIdMAX, (intmax_t)socket.handle.tcp);
tr_logAddTraceIo(io, fmt::format("socket (tcp) is {}", socket.handle.tcp));
io->event_read = event_new(session->event_base, socket.handle.tcp, EV_READ, event_read_cb, io);
io->event_write = event_new(session->event_base, socket.handle.tcp, EV_WRITE, event_write_cb, io);
break;
@ -625,14 +634,14 @@ static tr_peerIo* tr_peerIoNew(
#ifdef WITH_UTP
case TR_PEER_SOCKET_TYPE_UTP:
tr_logAddTraceIo(io, "socket (utp) is %p", (void*)socket.handle.utp);
tr_logAddTraceIo(io, fmt::format("socket (utp) is {}", fmt::ptr(socket.handle.utp)));
UTP_SetSockopt(socket.handle.utp, SO_RCVBUF, UTP_READ_BUFFER_SIZE);
tr_logAddTraceIo(io, "%s", "calling UTP_SetCallbacks &utp_function_table");
tr_logAddTraceIo(io, "calling UTP_SetCallbacks &utp_function_table");
UTP_SetCallbacks(socket.handle.utp, &utp_function_table, io);
if (!is_incoming)
{
tr_logAddTraceIo(io, "%s", "calling UTP_Connect");
tr_logAddTraceIo(io, "calling UTP_Connect");
UTP_Connect(socket.handle.utp);
}
@ -684,9 +693,9 @@ tr_peerIo* tr_peerIoNewOutgoing(
if (socket.type == TR_PEER_SOCKET_TYPE_NONE)
{
socket = tr_netOpenPeerSocket(session, addr, port, is_seed);
tr_logAddDebug(
"tr_netOpenPeerSocket returned fd %" PRIdMAX,
(intmax_t)(socket.type != TR_PEER_SOCKET_TYPE_NONE ? socket.handle.tcp : TR_BAD_SOCKET));
tr_logAddDebug(fmt::format(
"tr_netOpenPeerSocket returned {}",
socket.type != TR_PEER_SOCKET_TYPE_NONE ? socket.handle.tcp : TR_BAD_SOCKET));
}
if (socket.type == TR_PEER_SOCKET_TYPE_NONE)
@ -823,7 +832,7 @@ static void io_close_socket(tr_peerIo* io)
#endif
default:
tr_logAddDebugIo(io, "unsupported peer socket type %d", io->socket.type);
tr_logAddDebugIo(io, fmt::format("unsupported peer socket type {}", io->socket.type));
}
io->socket = {};
@ -877,7 +886,9 @@ void tr_peerIoRefImpl(char const* file, int line, tr_peerIo* io)
{
TR_ASSERT(tr_isPeerIo(io));
tr_logAddTraceIo(io, "%s:%d is incrementing the IO's refcount from %d to %d", file, line, io->refCount, io->refCount + 1);
tr_logAddTraceIo(
io,
fmt::format("{}:{} incrementing the IO's refcount from {} to {}", file, line, io->refCount, io->refCount + 1));
++io->refCount;
}
@ -886,7 +897,9 @@ void tr_peerIoUnrefImpl(char const* file, int line, tr_peerIo* io)
{
TR_ASSERT(tr_isPeerIo(io));
tr_logAddTraceIo(io, "%s:%d is decrementing the IO's refcount from %d to %d", file, line, io->refCount, io->refCount - 1);
tr_logAddTraceIo(
io,
fmt::format("{}:{} decrementing the IO's refcount from {} to {}", file, line, io->refCount, io->refCount - 1));
if (--io->refCount == 0)
{
@ -1242,7 +1255,7 @@ static int tr_peerIoTryRead(tr_peerIo* io, size_t howmuch)
res = evbuffer_read(io->inbuf, io->socket.handle.tcp, (int)howmuch);
int const e = EVUTIL_SOCKET_ERROR();
tr_logAddTraceIo(io, "read %d from peer (%s)", res, res == -1 ? tr_net_strerror(e).c_str() : "");
tr_logAddTraceIo(io, fmt::format("read {} from peer ({})", res, res == -1 ? tr_net_strerror(e).c_str() : ""));
if (evbuffer_get_length(io->inbuf) != 0)
{
@ -1260,11 +1273,7 @@ static int tr_peerIoTryRead(tr_peerIo* io, size_t howmuch)
tr_logAddTraceIo(
io,
"tr_peerIoTryRead err: res:%d what:%hd, errno:%d (%s)",
res,
what,
e,
tr_net_strerror(e).c_str());
fmt::format("tr_peerIoTryRead err: res:{} what:{}, errno:{} ({})", res, what, e, tr_net_strerror(e)));
io->gotError(io, what, io->userData);
}
@ -1273,7 +1282,7 @@ static int tr_peerIoTryRead(tr_peerIo* io, size_t howmuch)
}
default:
tr_logAddDebugIo(io, "unsupported peer socket type %d", io->socket.type);
tr_logAddDebugIo(io, fmt::format("unsupported peer socket type {}", io->socket.type));
}
return res;
@ -1283,7 +1292,7 @@ static int tr_peerIoTryWrite(tr_peerIo* io, size_t howmuch)
{
auto const old_len = size_t{ evbuffer_get_length(io->outbuf) };
tr_logAddTraceIo(io, "in tr_peerIoTryWrite %zu", howmuch);
tr_logAddTraceIo(io, fmt::format("in tr_peerIoTryWrite {}", howmuch));
howmuch = std::min(howmuch, old_len);
howmuch = io->bandwidth->clamp(TR_UP, howmuch);
if (howmuch == 0)
@ -1316,11 +1325,7 @@ static int tr_peerIoTryWrite(tr_peerIo* io, size_t howmuch)
tr_logAddTraceIo(
io,
"tr_peerIoTryWrite err: res:%d, what:%hd, errno:%d (%s)",
n,
what,
e,
tr_net_strerror(e).c_str());
fmt::format("tr_peerIoTryWrite err: res:{}, what:{}, errno:{} ({})", n, what, e, tr_net_strerror(e)));
io->gotError(io, what, io->userData);
}
@ -1328,7 +1333,7 @@ static int tr_peerIoTryWrite(tr_peerIo* io, size_t howmuch)
}
default:
tr_logAddDebugIo(io, "unsupported peer socket type %d", io->socket.type);
tr_logAddDebugIo(io, fmt::format("unsupported peer socket type {}", io->socket.type));
}
return n;
@ -1340,7 +1345,7 @@ int tr_peerIoFlush(tr_peerIo* io, tr_direction dir, size_t limit)
TR_ASSERT(tr_isDirection(dir));
int const bytes_used = dir == TR_DOWN ? tr_peerIoTryRead(io, limit) : tr_peerIoTryWrite(io, limit);
tr_logAddTraceIo(io, "flushing peer-io, direction:%d, limit:%zu, byte_used:%d", (int)dir, limit, bytes_used);
tr_logAddTraceIo(io, fmt::format("flushing peer-io, direction:{}, limit:{}, byte_used:{}", dir, limit, bytes_used));
return bytes_used;
}

View File

@ -16,6 +16,8 @@
#include <event2/event.h>
#include <fmt/core.h>
#define LIBTRANSMISSION_PEER_MODULE
#include "transmission.h"
@ -446,7 +448,7 @@ static constexpr bool atomIsSeed(struct peer_atom const* atom)
static void atomSetSeed(tr_swarm* s, struct peer_atom* atom)
{
tr_logAddTraceSwarm(s, "marking peer %s as a seed", tr_atomAddrStr(atom));
tr_logAddTraceSwarm(s, fmt::format("marking peer {} as a seed", tr_atomAddrStr(atom)));
atom->flags |= ADDED_F_SEED_FLAG;
s->poolIsAllSeedsDirty = true;
}
@ -664,14 +666,14 @@ static void refillUpkeep(evutil_socket_t /*fd*/, short /*what*/, void* vmgr)
static void addStrike(tr_swarm* s, tr_peer* peer)
{
tr_logAddTraceSwarm(s, "increasing peer %s strike count to %d", tr_atomAddrStr(peer->atom), peer->strikes + 1);
tr_logAddTraceSwarm(s, fmt::format("increasing peer {} strike count to {}", tr_atomAddrStr(peer->atom), peer->strikes + 1));
if (++peer->strikes >= MaxBadPiecesPerPeer)
{
struct peer_atom* atom = peer->atom;
atom->flags2 |= MyflagBanned;
peer->doPurge = true;
tr_logAddTraceSwarm(s, "banning peer %s", tr_atomAddrStr(atom));
tr_logAddTraceSwarm(s, fmt::format("banning peer {}", tr_atomAddrStr(atom)));
}
}
@ -849,18 +851,19 @@ static void peerCallbackFunc(tr_peer* peer, tr_peer_event const* e, void* vs)
peer->doPurge = true;
tr_logAddDebugSwarm(
s,
"setting %s doPurge flag because we got an ERANGE, EMSGSIZE, or ENOTCONN error",
tr_atomAddrStr(peer->atom));
fmt::format(
"setting {} doPurge flag because we got an ERANGE, EMSGSIZE, or ENOTCONN error",
tr_atomAddrStr(peer->atom)));
}
else
{
tr_logAddDebugSwarm(s, "unhandled error: %s", tr_strerror(e->err));
tr_logAddDebugSwarm(s, fmt::format("unhandled error: {}", tr_strerror(e->err)));
}
break;
default:
TR_ASSERT_MSG(false, "unhandled peer event type %d", int(e->eventType));
TR_ASSERT_MSG(false, "%s", fmt::format("unhandled peer event type {}", e->eventType).c_str());
}
}
@ -921,7 +924,7 @@ static struct peer_atom* ensureAtomExists(
a->blocklisted = -1;
tr_ptrArrayInsertSorted(&s->pool, a, compareAtomsByAddress);
tr_logAddTraceSwarm(s, "got a new atom: %s", tr_atomAddrStr(a));
tr_logAddTraceSwarm(s, fmt::format("got a new atom: {}", tr_atomAddrStr(a)));
}
else
{
@ -1013,9 +1016,7 @@ static bool on_handshake_done(tr_handshake_result const& result)
{
tr_logAddTraceSwarm(
s,
"marking peer %s as unreachable... numFails is %d",
tr_atomAddrStr(atom),
int(atom->numFails));
fmt::format("marking peer {} as unreachable... numFails is {}", tr_atomAddrStr(atom), atom->numFails));
atom->flags2 |= MyflagUnreachable;
}
}
@ -1044,7 +1045,7 @@ static bool on_handshake_done(tr_handshake_result const& result)
if ((atom->flags2 & MyflagBanned) != 0)
{
tr_logAddTraceSwarm(s, "banned peer %s tried to reconnect", tr_atomAddrStr(atom));
tr_logAddTraceSwarm(s, fmt::format("banned peer {} tried to reconnect", tr_atomAddrStr(atom)));
}
else if (tr_peerIoIsIncoming(result.io) && getPeerCount(s) >= getMaxPeerCount(s->tor))
{
@ -1090,7 +1091,7 @@ void tr_peerMgrAddIncoming(tr_peerMgr* manager, tr_address const* addr, tr_port
if (tr_sessionIsAddressBlocked(session, addr))
{
tr_logAddTrace("Banned IP address \"%s\" tried to connect to us", tr_address_to_string(addr));
tr_logAddTrace(fmt::format("Banned IP address '{}' tried to connect to us", tr_address_to_string(addr)));
tr_netClosePeerSocket(session, socket);
}
else if (manager->incoming_handshakes.count(*addr) > 0)
@ -1207,10 +1208,11 @@ void tr_peerMgrGotBadPiece(tr_torrent* tor, tr_piece_index_t pieceIndex)
{
tr_logAddTraceSwarm(
s,
"peer %s contributed to corrupt piece (%d); now has %d strikes",
tr_atomAddrStr(peer->atom),
pieceIndex,
int(peer->strikes + 1));
fmt::format(
"peer {} contributed to corrupt piece ({}); now has {} strikes",
tr_atomAddrStr(peer->atom),
pieceIndex,
peer->strikes + 1));
addStrike(s, peer);
}
}
@ -1907,9 +1909,10 @@ static void rechokeDownloads(tr_swarm* s)
maxPeers = s->interestedCount * mult;
tr_logAddTraceSwarm(
s,
"cancel rate is %.3f -- reducing the number of peers we're interested in by %.0f percent",
cancelRate,
mult * 100);
fmt::format(
"cancel rate is {} -- reducing the number of peers we're interested in by {} percent",
cancelRate,
mult * 100));
s->lastCancel = now;
}
@ -1924,9 +1927,10 @@ static void rechokeDownloads(tr_swarm* s)
maxPeers = s->maxPeers + inc;
tr_logAddTraceSwarm(
s,
"time since last cancel is %jd -- increasing the number of peers we're interested in by %d",
(intmax_t)timeSinceCancel,
inc);
fmt::format(
"time since last cancel is {} -- increasing the number of peers we're interested in by {}",
timeSinceCancel,
inc));
}
}
@ -2258,7 +2262,7 @@ static bool shouldPeerBeClosed(tr_swarm const* s, tr_peer const* peer, int peerC
/* if it's marked for purging, close it */
if (peer->doPurge)
{
tr_logAddTraceSwarm(s, "purging peer %s because its doPurge flag is set", tr_atomAddrStr(atom));
tr_logAddTraceSwarm(s, fmt::format("purging peer {} because its doPurge flag is set", tr_atomAddrStr(atom)));
return true;
}
@ -2285,9 +2289,10 @@ static bool shouldPeerBeClosed(tr_swarm const* s, tr_peer const* peer, int peerC
{
tr_logAddTraceSwarm(
s,
"purging peer %s because it's been %d secs since we shared anything",
tr_atomAddrStr(atom),
idleTime);
fmt::format(
"purging peer {} because it's been {} secs since we shared anything",
tr_atomAddrStr(atom),
idleTime));
return true;
}
}
@ -2351,7 +2356,7 @@ static int getReconnectIntervalSecs(struct peer_atom const* atom, time_t const n
}
}
tr_logAddTrace("reconnect interval for %s is %d seconds", tr_atomAddrStr(atom), sec);
tr_logAddTrace(fmt::format("reconnect interval for {} is {} seconds", tr_atomAddrStr(atom), sec));
return sec;
}
@ -2385,16 +2390,16 @@ static void closePeer(tr_peer* peer)
to them fruitlessly, so mark it as another fail */
if (auto* const atom = peer->atom; atom->piece_data_time != 0)
{
tr_logAddTraceSwarm(s, "resetting atom %s numFails to 0", tr_atomAddrStr(atom));
tr_logAddTraceSwarm(s, fmt::format("resetting atom {} numFails to 0", tr_atomAddrStr(atom)));
atom->numFails = 0;
}
else
{
++atom->numFails;
tr_logAddTraceSwarm(s, "incremented atom %s numFails to %d", tr_atomAddrStr(atom), int(atom->numFails));
tr_logAddTraceSwarm(s, fmt::format("incremented atom {} numFails to {}", tr_atomAddrStr(atom), atom->numFails));
}
tr_logAddTraceSwarm(s, "removing bad peer %s", tr_atomAddrStr(peer->atom));
tr_logAddTraceSwarm(s, fmt::format("removing bad peer {}", tr_atomAddrStr(peer->atom)));
removePeer(peer);
}
@ -2759,7 +2764,9 @@ static void atomPulse(evutil_socket_t /*fd*/, short /*what*/, void* vmgr)
tr_ptrArrayAppend(&s->pool, keep[i]);
}
tr_logAddTraceSwarm(s, "max atom count is %d... pruned from %d to %d\n", maxAtomCount, atomCount, keepCount);
tr_logAddTraceSwarm(
s,
fmt::format("max atom count is {}... pruned from {} to {}", maxAtomCount, atomCount, keepCount));
/* cleanup */
tr_free(test);
@ -3013,7 +3020,9 @@ static void initiateConnection(tr_peerMgr* mgr, tr_swarm* s, struct peer_atom* a
utp = utp && (atom->flags & ADDED_F_UTP_FLAGS) != 0;
}
tr_logAddTraceSwarm(s, "Starting an OUTGOING%s connection with %s", utp ? " µTP" : "", tr_atomAddrStr(atom));
tr_logAddTraceSwarm(
s,
fmt::format("Starting an OUTGOING {} connection with {}", utp ? " µTP" : "TCP", tr_atomAddrStr(atom)));
tr_peerIo* const io = tr_peerIoNewOutgoing(
mgr->session,
@ -3027,7 +3036,7 @@ static void initiateConnection(tr_peerMgr* mgr, tr_swarm* s, struct peer_atom* a
if (io == nullptr)
{
tr_logAddTraceSwarm(s, "peerIo not created; marking peer %s as unreachable", tr_atomAddrStr(atom));
tr_logAddTraceSwarm(s, fmt::format("peerIo not created; marking peer {} as unreachable", tr_atomAddrStr(atom)));
atom->flags2 |= MyflagUnreachable;
atom->numFails++;
}

View File

@ -672,7 +672,7 @@ static void myDebug(char const* file, int line, tr_log_level level, tr_peerMsgsI
evbuffer_add_vprintf(buf, fmt, args);
va_end(args);
auto const message = evbuffer_free_to_str(buf);
tr_logAddMessage(file, line, level, tr_torrentName(msgs->torrent), "%s", message.c_str());
tr_logAddMessage(file, line, level, tr_torrentName(msgs->torrent), message);
}
#define logdbg(msgs, ...) myDebug(__FILE__, __LINE__, TR_LOG_DEBUG, msgs, __VA_ARGS__)

View File

@ -32,6 +32,8 @@
#include <FindDirectory.h>
#endif
#include <fmt/core.h>
#include "transmission.h"
#include "file.h"
@ -316,8 +318,7 @@ static bool isWebClientDir(std::string_view path)
{
auto tmp = tr_strvPath(path, "index.html");
bool const ret = tr_sys_path_exists(tmp.c_str(), nullptr);
tr_logAddTrace("Searching for web interface file \"%s\"", tmp.c_str());
tr_logAddTrace(fmt::format("Searching for web interface file '{}'", tmp));
return ret;
}

View File

@ -9,6 +9,9 @@
#include <string_view>
#include <vector>
#include <fmt/core.h>
#include <fmt/format.h> // fmt::ptr
#include "transmission.h"
#include "error.h"
@ -77,14 +80,14 @@ static auto loadPeers(tr_variant* dict, tr_torrent* tor)
if (tr_variantDictFindRaw(dict, TR_KEY_peers2, &str, &len))
{
size_t const numAdded = addPeers(tor, str, len);
tr_logAddTraceTor(tor, "Loaded %zu IPv4 peers from resume file", numAdded);
tr_logAddTraceTor(tor, fmt::format("Loaded {} IPv4 peers from resume file", numAdded));
ret = tr_resume::Peers;
}
if (tr_variantDictFindRaw(dict, TR_KEY_peers2_6, &str, &len))
{
size_t const numAdded = addPeers(tor, str, len);
tr_logAddTraceTor(tor, "Loaded %zu IPv6 peers from resume file", numAdded);
tr_logAddTraceTor(tor, fmt::format("Loaded {} IPv6 peers from resume file", numAdded));
ret = tr_resume::Peers;
}
@ -176,11 +179,11 @@ static auto loadDND(tr_variant* dict, tr_torrent* tor)
{
tr_logAddDebugTor(
tor,
"Couldn't load DND flags. DND list (%p) has %zu"
" children; torrent has %d files",
(void*)list,
tr_variantListSize(list),
(int)n);
fmt::format(
"Couldn't load DND flags. DND list {} has {} children; torrent has {} files",
fmt::ptr(list),
tr_variantListSize(list),
n));
}
return ret;
@ -564,7 +567,7 @@ static auto loadProgress(tr_variant* dict, tr_torrent* tor)
if (std::size(mtimes) != n_files)
{
tr_logAddWarnTor(tor, "got %zu mtimes; expected %zu", std::size(mtimes), size_t(n_files));
tr_logAddWarnTor(tor, fmt::format("got {} mtimes; expected {}", std::size(mtimes), n_files));
// if resizing grows the vector, we'll get 0 mtimes for the
// new items which is exactly what we want since the pieces
// in an unknown state should be treated as untested
@ -613,7 +616,7 @@ static auto loadProgress(tr_variant* dict, tr_torrent* tor)
if (err != nullptr)
{
tr_logAddDebugTor(tor, "Torrent needs to be verified - %s", err);
tr_logAddDebugTor(tor, fmt::format("Torrent needs to be verified - {}", err));
}
else
{
@ -659,12 +662,12 @@ static auto loadFromFile(tr_torrent* tor, tr_resume::fields_t fieldsToLoad, bool
nullptr,
&error))
{
tr_logAddDebugTor(tor, "Couldn't read \"%s\": %s", filename.c_str(), error->message);
tr_logAddDebugTor(tor, fmt::format("Couldn't read '{}': {}", filename, error->message));
tr_error_clear(&error);
return fields_loaded;
}
tr_logAddDebugTor(tor, "Read resume file \"%s\"", filename.c_str());
tr_logAddDebugTor(tor, fmt::format("Read resume file '{}'", filename));
auto boolVal = false;
auto i = int64_t{};

View File

@ -10,6 +10,8 @@
#include <sys/stat.h>
#endif
#include <fmt/core.h>
#include "transmission.h"
#include "crypto-utils.h"
#include "error.h"
@ -91,7 +93,11 @@ static tr_sys_file_t create_session_id_lock_file(char const* session_id)
if (error != nullptr)
{
tr_logAddWarn("Unable to create session lock file (%d): %s", error->code, error->message);
tr_logAddWarn(fmt::format(
_("Couldn't create '{path}': {errmsg} ({errcode})"),
fmt::arg("path", lock_file_path),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
}
@ -194,7 +200,11 @@ bool tr_session_id_is_local(char const* session_id)
if (error != nullptr)
{
tr_logAddWarn("Unable to open session lock file (%d): %s", error->code, error->message);
tr_logAddWarn(fmt::format(
_("Couldn't open session lock file '{path}': {errmsg} ({errcode})"),
fmt::arg("path", lock_file_path),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error);
}
}

View File

@ -27,6 +27,9 @@
#include <event2/event.h>
#include <fmt/core.h>
#include <fmt/format.h> // fmt::ptr
#include "transmission.h"
#include "announcer.h"
@ -229,7 +232,7 @@ static void accept_incoming_peer(evutil_socket_t fd, short /*what*/, void* vsess
{
char addrstr[TR_ADDRSTRLEN];
tr_address_and_port_to_string(addrstr, sizeof(addrstr), &clientAddr, clientPort);
tr_logAddTrace("new incoming connection %" PRIdMAX " (%s)", (intmax_t)clientSocket, addrstr);
tr_logAddTrace(fmt::format("new incoming connection {} ({})", clientSocket, addrstr));
tr_peerMgrAddIncoming(session->peerMgr, &clientAddr, clientPort, tr_peer_socket_tcp_create(clientSocket));
}
@ -691,7 +694,8 @@ static void tr_sessionInitImpl(init_data* data)
TR_ASSERT(tr_amInEventThread(session));
TR_ASSERT(tr_variantIsDict(clientSettings));
tr_logAddTrace("tr_sessionInit: the session's top-level bandwidth object is %p", (void*)&session->bandwidth);
tr_logAddTrace(
fmt::format("tr_sessionInit: the session's top-level bandwidth object is {}", fmt::ptr(&session->bandwidth)));
tr_variant settings;
@ -733,9 +737,7 @@ static void tr_sessionInitImpl(init_data* data)
tr_announcerInit(session);
/* first %s is the application name
second %s is the version number */
tr_logAddInfo(_("%s %s started"), TR_NAME, LONG_VERSION_STRING);
tr_logAddInfo(fmt::format(_("Transmission version {version} starting"), fmt::arg("version", LONG_VERSION_STRING)));
tr_statsInit(session);
@ -1478,7 +1480,7 @@ static void turtleCheckClock(tr_session* s, struct tr_turtle_info* t)
if (!alreadySwitched)
{
tr_logAddInfo("Time to turn %s turtle mode!", enabled ? "on" : "off");
tr_logAddInfo(enabled ? _("Time to turn on turtle mode") : _("Time to turn off turtle mode"));
t->autoTurtleState = newAutoTurtleState;
useAltSpeed(s, t, enabled, false);
}
@ -1925,8 +1927,8 @@ void tr_sessionClose(tr_session* session)
time_t const deadline = time(nullptr) + ShutdownMaxSeconds;
tr_logAddInfo("Shutting down transmission session %p", (void*)session);
tr_logAddDebug("now is %zu, deadline is %zu", (size_t)time(nullptr), (size_t)deadline);
tr_logAddInfo(fmt::format(_("Transmission version {version} shutting down"), fmt::arg("version", LONG_VERSION_STRING)));
tr_logAddDebug(fmt::format("now is {}, deadline is {}", time(nullptr), deadline));
/* close the session */
tr_runInEventThread(session, sessionCloseImpl, session);
@ -1945,12 +1947,12 @@ void tr_sessionClose(tr_session* session)
session->announcer_udp != nullptr) &&
!deadlineReached(deadline))
{
tr_logAddTrace(
"waiting on port unmap (%p) or announcer (%p)... now %zu deadline %zu",
(void*)session->shared,
(void*)session->announcer,
(size_t)time(nullptr),
(size_t)deadline);
tr_logAddTrace(fmt::format(
"waiting on port unmap ({}) or announcer ({})... now {} deadline {}",
fmt::ptr(session->shared),
fmt::ptr(session->announcer),
time(nullptr),
deadline));
tr_wait_msec(50);
}
@ -1963,9 +1965,7 @@ void tr_sessionClose(tr_session* session)
{
static bool forced = false;
tr_logAddTrace(
"waiting for libtransmission thread to finish... now %zu deadline %zu",
(size_t)time(nullptr),
(size_t)deadline);
fmt::format("waiting for libtransmission thread to finish... now {} deadline {}", time(nullptr), deadline));
tr_wait_msec(10);
if (deadlineReached(deadline) && !forced)
@ -1977,7 +1977,7 @@ void tr_sessionClose(tr_session* session)
if (deadlineReached(deadline + 3))
{
tr_logAddTrace("deadline+3 reached... calling break...\n");
tr_logAddTrace("deadline+3 reached... calling break...");
break;
}
}
@ -2052,7 +2052,7 @@ static void sessionLoadTorrents(struct sessionLoadTorrentsData* const data)
if (n != 0)
{
tr_logAddInfo(_("Loaded %d torrents"), n);
tr_logAddInfo(fmt::format(ngettext_("Loaded {count} torrent", "Loaded {count} torrents", n), fmt::arg("count", n)));
}
if (data->setmeCount != nullptr)

View File

@ -12,6 +12,8 @@
#include <string_view>
#include <vector>
#include <fmt/core.h>
#include "transmission.h"
#include "crypto-utils.h"
@ -537,8 +539,12 @@ bool tr_torrent_metainfo::migrateFile(
if (old_filename_exists && tr_sys_path_rename(old_filename.c_str(), new_filename.c_str(), nullptr))
{
auto const name_sz = std::string{ name };
tr_logAddNamedError(name_sz, "Migrated torrent file from \"%s\" to \"%s\"", old_filename.c_str(), new_filename.c_str());
tr_logAddNamedError(
name,
fmt::format(
_("Migrated torrent file from '{oldpath}' to '{path}'"),
fmt::arg("oldpath", old_filename),
fmt::arg("path", new_filename)));
return true;
}

View File

@ -8,6 +8,8 @@
#include <mutex>
#include <thread>
#include <fmt/core.h>
#ifdef SYSTEM_MINIUPNP
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/upnpcommands.h>
@ -141,7 +143,7 @@ static struct UPNPDev* tr_upnpDiscover(int msec, char const* bindaddr)
if (have_err)
{
tr_logAddDebug("upnpDiscover failed (errno %d - %s)", errno, tr_strerror(errno));
tr_logAddDebug(fmt::format("upnpDiscover failed: {} ({})", tr_strerror(errno), errno));
}
return ret;
@ -227,7 +229,7 @@ static int tr_upnpAddPortMapping(tr_upnp const* handle, char const* proto, tr_po
if (err != 0)
{
tr_logAddDebug("%s Port forwarding failed with error %d (errno %d - %s)", proto, err, errno, tr_strerror(errno));
tr_logAddDebug(fmt::format("{} Port forwarding failed with error {}: {} ({})", proto, err, tr_strerror(errno), errno));
}
errno = old_errno;
@ -291,15 +293,15 @@ tr_port_forwarding tr_upnpPulse(tr_upnp* handle, tr_port port, bool isEnabled, b
if (UPNP_GetValidIGD(devlist, &handle->urls, &handle->data, handle->lanaddr, sizeof(handle->lanaddr)) ==
UPNP_IGD_VALID_CONNECTED)
{
tr_logAddInfo(_("Found Internet Gateway Device \"%s\""), handle->urls.controlURL);
tr_logAddInfo(_("Local Address is \"%s\""), handle->lanaddr);
tr_logAddInfo(fmt::format(_("Found Internet Gateway Device '{url}'"), fmt::arg("url", handle->urls.controlURL)));
tr_logAddInfo(fmt::format(_("Local Address is '{address}')"), fmt::arg("address", handle->lanaddr)));
handle->state = UpnpState::IDLE;
handle->hasDiscovered = true;
}
else
{
handle->state = UpnpState::FAILED;
tr_logAddDebug("UPNP_GetValidIGD failed (errno %d - %s)", errno, tr_strerror(errno));
tr_logAddDebug(fmt::format("UPNP_GetValidIGD failed: {} ({})", tr_strerror(errno), errno));
tr_logAddDebug("If your router supports UPnP, please make sure UPnP is enabled!");
}
@ -315,7 +317,7 @@ tr_port_forwarding tr_upnpPulse(tr_upnp* handle, tr_port port, bool isEnabled, b
((tr_upnpGetSpecificPortMappingEntry(handle, "TCP") != UPNPCOMMAND_SUCCESS) ||
(tr_upnpGetSpecificPortMappingEntry(handle, "UDP") != UPNPCOMMAND_SUCCESS)))
{
tr_logAddInfo(_("Port %d isn't forwarded"), handle->port);
tr_logAddInfo(fmt::format(_("Port {port} is not forwarded"), fmt::arg("port", handle->port)));
handle->isMapped = false;
}
@ -324,10 +326,10 @@ tr_port_forwarding tr_upnpPulse(tr_upnp* handle, tr_port port, bool isEnabled, b
tr_upnpDeletePortMapping(handle, "TCP", handle->port);
tr_upnpDeletePortMapping(handle, "UDP", handle->port);
tr_logAddInfo(
_("Stopping port forwarding through \"%s\", service \"%s\""),
handle->urls.controlURL,
handle->data.first.servicetype);
tr_logAddInfo(fmt::format(
_("Stopping port forwarding through '{url}', service '{type}'"),
fmt::arg("url", handle->urls.controlURL),
fmt::arg("type", handle->data.first.servicetype)));
handle->isMapped = false;
handle->state = UpnpState::IDLE;
@ -358,22 +360,22 @@ tr_port_forwarding tr_upnpPulse(tr_upnp* handle, tr_port port, bool isEnabled, b
handle->isMapped = err_tcp == 0 || err_udp == 0;
}
tr_logAddInfo(
_("Port forwarding through \"%s\", service \"%s\". (local address: %s:%d)"),
handle->urls.controlURL,
handle->data.first.servicetype,
handle->lanaddr,
port);
tr_logAddInfo(fmt::format(
_("Port forwarding through '{url}', service '{type}'. (local address: {address}:{port})"),
fmt::arg("url", handle->urls.controlURL),
fmt::arg("type", handle->data.first.servicetype),
fmt::arg("address", handle->lanaddr),
fmt::arg("port", port)));
if (handle->isMapped)
{
tr_logAddInfo("%s", _("Port forwarding successful!"));
tr_logAddInfo(_("Port forwarding successful!"));
handle->port = port;
handle->state = UpnpState::IDLE;
}
else
{
tr_logAddInfo("%s", _("If your router supports UPnP, please make sure UPnP is enabled!"));
tr_logAddInfo(_("If your router supports UPnP, please make sure UPnP is enabled!"));
handle->port = -1;
handle->state = UpnpState::FAILED;
}

View File

@ -37,6 +37,8 @@
#include <event2/buffer.h>
#include <event2/event.h>
#include <fmt/core.h>
#include "transmission.h"
#include "error-types.h"
@ -231,14 +233,18 @@ uint8_t* tr_loadFile(char const* path, size_t* size, tr_error** error)
tr_error* my_error = nullptr;
if (!tr_sys_path_get_info(path, 0, &info, &my_error))
{
tr_logAddError("Couldn't read \"%1$s\": %2$s", path, my_error->message);
tr_logAddError(fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", path),
fmt::arg("errmsg", my_error->message),
fmt::arg("errcode", my_error->code)));
tr_error_propagate(error, &my_error);
return nullptr;
}
if (info.type != TR_SYS_PATH_IS_FILE)
{
tr_logAddError("Couldn't read \"%1$s\": Not a regular file", path);
tr_logAddError(fmt::format(_("Couldn't read '{path}': Not a regular file"), fmt::arg("path", path)));
tr_error_set(error, TR_ERROR_EISDIR, "Not a regular file"sv);
return nullptr;
}
@ -253,7 +259,11 @@ uint8_t* tr_loadFile(char const* path, size_t* size, tr_error** error)
auto const fd = tr_sys_file_open(path, TR_SYS_FILE_READ | TR_SYS_FILE_SEQUENTIAL, 0, &my_error);
if (fd == TR_BAD_SYS_FILE)
{
tr_logAddError("Couldn't read \"%1$s\": %2$s", path, my_error->message);
tr_logAddError(fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", path),
fmt::arg("errmsg", my_error->message),
fmt::arg("errcode", my_error->code)));
tr_error_propagate(error, &my_error);
return nullptr;
}
@ -261,7 +271,11 @@ uint8_t* tr_loadFile(char const* path, size_t* size, tr_error** error)
auto* buf = static_cast<uint8_t*>(tr_malloc(info.size + 1));
if (!tr_sys_file_read(fd, buf, info.size, nullptr, &my_error))
{
tr_logAddError("Couldn't read \"%1$s\": %2$s", path, my_error->message);
tr_logAddError(fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", path),
fmt::arg("errmsg", my_error->message),
fmt::arg("errcode", my_error->code)));
tr_sys_file_close(fd, nullptr);
tr_free(buf);
tr_error_propagate(error, &my_error);
@ -283,14 +297,18 @@ bool tr_loadFile(std::vector<char>& setme, std::string const& path, tr_error** e
tr_error* my_error = nullptr;
if (!tr_sys_path_get_info(path_sz, 0, &info, &my_error))
{
tr_logAddError(_("Couldn't read \"%1$s\": %2$s"), path_sz, my_error->message);
tr_logAddError(fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", path),
fmt::arg("errmsg", my_error->message),
fmt::arg("errcode", my_error->code)));
tr_error_propagate(error, &my_error);
return false;
}
if (info.type != TR_SYS_PATH_IS_FILE)
{
tr_logAddError(_("Couldn't read \"%1$s\": Not a regular file"), path_sz);
tr_logAddError(fmt::format(_("Couldn't read '{path}': Not a regular file"), fmt::arg("path", path)));
tr_error_set(error, TR_ERROR_EISDIR, "Not a regular file"sv);
return false;
}
@ -299,7 +317,11 @@ bool tr_loadFile(std::vector<char>& setme, std::string const& path, tr_error** e
auto const fd = tr_sys_file_open(path_sz, TR_SYS_FILE_READ | TR_SYS_FILE_SEQUENTIAL, 0, &my_error);
if (fd == TR_BAD_SYS_FILE)
{
tr_logAddError(_("Couldn't read \"%1$s\": %2$s"), path_sz, my_error->message);
tr_logAddError(fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", path),
fmt::arg("errmsg", my_error->message),
fmt::arg("errcode", my_error->code)));
tr_error_propagate(error, &my_error);
return false;
}
@ -307,7 +329,11 @@ bool tr_loadFile(std::vector<char>& setme, std::string const& path, tr_error** e
setme.resize(info.size);
if (!tr_sys_file_read(fd, std::data(setme), info.size, nullptr, &my_error))
{
tr_logAddError(_("Couldn't read \"%1$s\": %2$s"), path_sz, my_error->message);
tr_logAddError(fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", path),
fmt::arg("errmsg", my_error->message),
fmt::arg("errcode", my_error->code)));
tr_sys_file_close(fd, nullptr);
tr_error_propagate(error, &my_error);
return false;
@ -360,7 +386,7 @@ bool tr_saveFile(std::string const& filename, std::string_view contents, tr_erro
return false;
}
tr_logAddTrace("Saved \"%s\"", filename.c_str());
tr_logAddTrace(fmt::format("Saved '{}'", filename));
return true;
}
@ -1134,7 +1160,11 @@ bool tr_moveFile(char const* oldpath, char const* newpath, tr_error** error)
if (!tr_sys_path_remove(oldpath, &my_error))
{
tr_logAddError("Unable to remove file at old path: %s", my_error->message);
tr_logAddError(fmt::format(
_("Couldn't remove '{path}': {errmsg} ({errcode})"),
fmt::arg("path", oldpath),
fmt::arg("errmsg", my_error->message),
fmt::arg("errcode", my_error->code)));
tr_error_free(my_error);
}
}

View File

@ -36,7 +36,7 @@ struct tr_error;
char const* tr_strip_positional_args(char const* fmt);
#if !defined(_)
#if defined(HAVE_LIBINTL_H) && !defined(__APPLE__)
#if defined(HAVE_GETTEXT) && !defined(__APPLE__)
#include <libintl.h>
#define _(a) gettext(a)
#else
@ -44,6 +44,15 @@ char const* tr_strip_positional_args(char const* fmt);
#endif
#endif
#if !defined(ngettext_)
#if defined(HAVE_NGETTEXT) && !defined(__APPLE__)
#include <libintl.h>
#define ngettext_(singular, plural, count) ngettext(singular, plural, count)
#else
#define ngettext_(singular, plural, count) ((count) == 1 ? (singular) : (plural))
#endif
#endif
/* #define DISABLE_GETTEXT */
#ifndef DISABLE_GETTEXT
#if defined(_WIN32) || defined(TR_LIGHTWEIGHT)
@ -52,7 +61,9 @@ char const* tr_strip_positional_args(char const* fmt);
#endif
#ifdef DISABLE_GETTEXT
#undef _
#undef ngettext_
#define _(a) tr_strip_positional_args(a)
#define ngettext_(singular, plural, count) tr_strip_positional_args((count) == 1 ? (singular) : (plural))
#endif
/****

View File

@ -16,6 +16,8 @@
#include <event2/buffer.h>
#include <fmt/core.h>
#define LIBTRANSMISSION_VARIANT_MODULE
#include "transmission.h"
@ -79,7 +81,12 @@ static void error_handler(jsonsl_t jsn, jsonsl_error_t error, jsonsl_state_st* /
{
auto* data = static_cast<struct json_wrapper_data*>(jsn->data);
tr_logAddError("JSON parse failed at pos %zu: %s -- remaining text \"%.16s\"", jsn->pos, jsonsl_strerror(error), buf);
tr_logAddError(fmt::format(
_("JSON parse failed at pos {pos} '{text:16s}': {errmsg} ({errcode})"),
fmt::arg("pos", jsn->pos),
fmt::arg("text", buf),
fmt::arg("errmsg", jsonsl_strerror(error)),
fmt::arg("errcode", error)));
data->error = EILSEQ;
}

View File

@ -33,6 +33,8 @@
#include <event2/buffer.h>
#include <fmt/core.h>
#define LIBTRANSMISSION_VARIANT_MODULE
#include "transmission.h"
@ -968,7 +970,7 @@ void tr_variantWalk(tr_variant const* v_in, struct VariantWalkFuncs const* walkF
default:
/* did caller give us an uninitialized val? */
tr_logAddError("%s", _("Invalid metadata"));
tr_logAddError(_("Invalid metadata"));
break;
}
}
@ -1056,7 +1058,7 @@ static void tr_variantListCopy(tr_variant* target, tr_variant const* src)
}
else
{
tr_logAddError("tr_variantListCopy skipping item");
tr_logAddWarn("tr_variantListCopy skipping item");
}
++i;
@ -1159,7 +1161,7 @@ void tr_variantMergeDicts(tr_variant* target, tr_variant const* source)
}
else
{
tr_logAddDebug("tr_variantMergeDicts skipping \"%s\"", tr_quark_get_string(key));
tr_logAddDebug(fmt::format("tr_variantMergeDicts skipping '{}'", tr_quark_get_string(key)));
}
}
}
@ -1213,7 +1215,11 @@ int tr_variantToFile(tr_variant const* v, tr_variant_fmt fmt, std::string const&
tr_saveFile(filename, { std::data(contents), std::size(contents) }, &error);
if (error != nullptr)
{
tr_logAddError(_("Error saving \"%" TR_PRIsv "\": %s (%d)"), TR_PRIsv_ARG(filename), error->message, error->code);
tr_logAddError(fmt::format(
_("Couldn't save '{path}': {errmsg} ({errcode})"),
fmt::arg("path", filename),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
error_code = error->code;
tr_error_clear(&error);
}

View File

@ -11,6 +11,8 @@
#include <thread>
#include <vector>
#include <fmt/core.h>
#include "transmission.h"
#include "completion.h"
#include "crypto-utils.h"
@ -43,7 +45,7 @@ static bool verifyTorrent(tr_torrent* tor, bool const* stopFlag)
auto buffer = std::vector<std::byte>(1024 * 256);
auto sha = tr_sha1_init();
tr_logAddDebugTor(tor, "%s", "verifying torrent...");
tr_logAddDebugTor(tor, "verifying torrent...");
tor->verify_progress = 0;
while (!*stopFlag && piece < tor->pieceCount())
@ -146,10 +148,11 @@ static bool verifyTorrent(tr_torrent* tor, bool const* stopFlag)
time_t const end = tr_time();
tr_logAddDebugTor(
tor,
"Verification is done. It took %d seconds to verify %" PRIu64 " bytes (%" PRIu64 " bytes per second)",
(int)(end - begin),
tor->totalSize(),
(uint64_t)(tor->totalSize() / (1 + (end - begin))));
fmt::format(
"Verification is done. It took {} seconds to verify {} bytes ({} bytes per second)",
end - begin,
tor->totalSize(),
tor->totalSize() / (1 + (end - begin))));
return changed;
}
@ -225,7 +228,7 @@ static void verifyThreadFunc()
}
tr_torrent* tor = currentNode.torrent;
tr_logAddTraceTor(tor, "%s", _("Verifying torrent"));
tr_logAddTraceTor(tor, "Verifying torrent");
tor->setVerifyState(TR_VERIFY_NOW);
auto const changed = verifyTorrent(tor, &stopCurrent);
tor->setVerifyState(TR_VERIFY_NONE);
@ -246,7 +249,7 @@ static void verifyThreadFunc()
void tr_verifyAdd(tr_torrent* tor, tr_verify_done_func callback_func, void* callback_data)
{
TR_ASSERT(tr_isTorrent(tor));
tr_logAddTraceTor(tor, "%s", _("Queued for verification"));
tr_logAddTraceTor(tor, "Queued for verification");
auto node = verify_node{};
node.torrent = tor;

View File

@ -1,4 +1,5 @@
include_directories(SYSTEM
${LIBFMT_INCLUDE_DIRS}
${THIRD_PARTY_DIR}/googletest/googletest/include
${THIRD_PARTY_DIR}/googletest/googletest)

View File

@ -38,6 +38,7 @@ add_executable(libtransmission-test
target_compile_definitions(libtransmission-test
PRIVATE
${LIBFMT_DEFINITIONS}
-DLIBTRANSMISSION_TEST_ASSETS_DIR="${CMAKE_CURRENT_SOURCE_DIR}/assets"
__TRANSMISSION__)

1
third-party/fmt vendored Submodule

@ -0,0 +1 @@
Subproject commit b6f4ceaed0a0a24ccf575fab6c56dd50ccf6f1a9

View File

@ -2,6 +2,10 @@ project(trutils)
add_compile_options(${CXX_WARNING_FLAGS})
add_definitions(
${LIBFMT_DEFINITIONS}
)
include_directories(
${CMAKE_SOURCE_DIR}
)
@ -9,6 +13,7 @@ include_directories(
SYSTEM
${EVENT2_INCLUDE_DIRS}
${CURL_INCLUDE_DIRS}
${LIBFMT_INCLUDE_DIRS}
)
foreach(P create edit remote show)

View File

@ -14,10 +14,12 @@
#include <string>
#include <string_view>
#include <curl/curl.h>
#include <event2/buffer.h>
#include <event2/util.h>
#include <curl/curl.h>
#include <fmt/core.h>
#include <libtransmission/transmission.h>
#include <libtransmission/crypto-utils.h>
@ -2000,7 +2002,7 @@ static int processResponse(char const* rpcurl, std::string_view response)
if (!tr_variantFromBuf(&top, TR_VARIANT_PARSE_JSON | TR_VARIANT_PARSE_INPLACE, response))
{
tr_logAddNamedWarn(MyName, "Unable to parse response \"%" TR_PRIsv "\"", TR_PRIsv_ARG(response));
tr_logAddNamedWarn(MyName, fmt::format("Unable to parse response '{}'", response));
status |= EXIT_FAILURE;
}
else
@ -2172,7 +2174,7 @@ static int flush(char const* rpcurl, tr_variant** benc)
auto const res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
tr_logAddNamedWarn(MyName, " (%s) %s", rpcurl_http.c_str(), curl_easy_strerror(res));
tr_logAddNamedWarn(MyName, fmt::format(" ({}) {}", rpcurl_http, curl_easy_strerror(res)));
status |= EXIT_FAILURE;
}
else