refactor: fmt part 2 (#2771)

This commit is contained in:
Charles Kerr 2022-03-15 09:52:16 -05:00 committed by GitHub
parent a942c67199
commit 72a67054ea
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 338 additions and 233 deletions

View File

@ -542,6 +542,14 @@ set(NEEDED_HEADERS
xlocale.h) xlocale.h)
if(ENABLE_NLS) if(ENABLE_NLS)
check_library_exists(intl libintl_gettext "" HAVE_LIBINTL)
if(HAVE_LIBINTL)
set(LIBINTL_LIBRARY intl)
# check_function_exists() below may need this
# when looking for gettext() and ngettext()
list(APPEND CMAKE_REQUIRED_LIBRARIES intl)
endif()
list(APPEND NEEDED_HEADERS libintl.h) list(APPEND NEEDED_HEADERS libintl.h)
endif() endif()
@ -562,12 +570,14 @@ set(NEEDED_FUNCTIONS
fallocate64 fallocate64
flock flock
getmntent getmntent
gettext
gmtime_r gmtime_r
gmtime_s gmtime_s
htonll htonll
localtime_r localtime_r
localtime_s localtime_s
mkdtemp mkdtemp
ngettext
ntohll ntohll
posix_fadvise posix_fadvise
posix_fallocate posix_fallocate
@ -601,15 +611,6 @@ endif()
# endif() # endif()
# endif() # endif()
if(ENABLE_NLS)
check_library_exists(intl libintl_gettext "" HAVE_LIBINTL)
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) check_library_exists(m sqrt "" HAVE_LIBM)
if(HAVE_LIBM) if(HAVE_LIBM)
set(LIBM_LIBRARY m) set(LIBM_LIBRARY m)

View File

@ -14,6 +14,8 @@
#include <locale.h> #include <locale.h>
#include <signal.h> #include <signal.h>
#include <fmt/core.h>
#include <giomm.h> #include <giomm.h>
#include <glib/gmessages.h> #include <glib/gmessages.h>
#include <glibmm/i18n.h> #include <glibmm/i18n.h>
@ -344,7 +346,12 @@ void register_magnet_link_handler()
} }
catch (Gio::Error const& e) catch (Gio::Error const& e)
{ {
g_warning(_("Error registering Transmission as a %s handler: %s"), content_type.c_str(), e.what().c_str()); auto const msg = fmt::format(
_("Couldn't register Transmission as a {content_type} handler: {errmsg} ({errcode})"),
fmt::arg("content_type", content_type),
fmt::arg("errmsg", e.what().raw()),
fmt::arg("errcode", e.code()));
g_warning("%s", msg.c_str());
} }
} }
@ -889,7 +896,7 @@ void Application::Impl::on_app_exit()
p->attach(*icon, 0, 0, 1, 2); p->attach(*icon, 0, 0, 1, 2);
auto* top_label = Gtk::make_managed<Gtk::Label>(); auto* top_label = Gtk::make_managed<Gtk::Label>();
top_label->set_markup(_("<b>Closing Connections</b>")); top_label->set_markup(fmt::format("<b>{}</b>", _("Closing Connections…")));
top_label->set_halign(Gtk::ALIGN_START); top_label->set_halign(Gtk::ALIGN_START);
top_label->set_valign(Gtk::ALIGN_CENTER); top_label->set_valign(Gtk::ALIGN_CENTER);
p->attach(*top_label, 1, 0, 1, 1); p->attach(*top_label, 1, 0, 1, 1);

View File

@ -11,6 +11,8 @@
#include <glibmm.h> #include <glibmm.h>
#include <glibmm/i18n.h> #include <glibmm/i18n.h>
#include <fmt/core.h>
#include <libtransmission/transmission.h> #include <libtransmission/transmission.h>
#include <libtransmission/utils.h> #include <libtransmission/utils.h>
@ -741,7 +743,12 @@ bool FileList::Impl::on_rename_done_idle(Glib::ustring const& path_string, Glib:
{ {
Gtk::MessageDialog w( Gtk::MessageDialog w(
*static_cast<Gtk::Window*>(widget_.get_toplevel()), *static_cast<Gtk::Window*>(widget_.get_toplevel()),
gtr_sprintf(_("Unable to rename file as \"%s\": %s"), newname, tr_strerror(error)), fmt::format(
_("Couldn't rename '{oldpath}' as '{path}': {errmsg} ({errcode})"),
fmt::arg("oldpath", path_string.raw()),
fmt::arg("path", newname.raw()),
fmt::arg("errmsg", tr_strerror(error)),
fmt::arg("errcode", error)),
false, false,
Gtk::MESSAGE_ERROR, Gtk::MESSAGE_ERROR,
Gtk::BUTTONS_CLOSE, Gtk::BUTTONS_CLOSE,

View File

@ -9,6 +9,8 @@
#include <glibmm.h> #include <glibmm.h>
#include <glibmm/i18n.h> #include <glibmm/i18n.h>
#include <fmt/core.h>
#include <libtransmission/transmission.h> #include <libtransmission/transmission.h>
#include <libtransmission/makemeta.h> #include <libtransmission/makemeta.h>
#include <libtransmission/utils.h> /* tr_formatter_mem_B() */ #include <libtransmission/utils.h> /* tr_formatter_mem_B() */
@ -121,15 +123,23 @@ bool MakeProgressDialog::onProgressDialogRefresh()
} }
else if (builder_.result == TrMakemetaResult::ERR_URL) else if (builder_.result == TrMakemetaResult::ERR_URL)
{ {
str = gtr_sprintf(_("Error: invalid announce URL \"%s\""), builder_.errfile); str = fmt::format(_("Unsupported URL: '{url}'"), fmt::arg("url", builder_.errfile));
} }
else if (builder_.result == TrMakemetaResult::ERR_IO_READ) else if (builder_.result == TrMakemetaResult::ERR_IO_READ)
{ {
str = gtr_sprintf(_("Error reading \"%s\": %s"), builder_.errfile, Glib::strerror(builder_.my_errno)); str = fmt::format(
_("Couldn't read '{path}': {errmsg} ({errcode})"),
fmt::arg("path", builder_.errfile),
fmt::arg("errmsg", Glib::strerror(builder_.my_errno).raw()),
fmt::arg("errcode", builder_.my_errno));
} }
else if (builder_.result == TrMakemetaResult::ERR_IO_WRITE) else if (builder_.result == TrMakemetaResult::ERR_IO_WRITE)
{ {
str = gtr_sprintf(_("Error writing \"%s\": %s"), builder_.errfile, Glib::strerror(builder_.my_errno)); str = fmt::format(
_("Couldn't save '{path}': {errmsg} ({errcode})"),
fmt::arg("path", builder_.errfile),
fmt::arg("errmsg", Glib::strerror(builder_.my_errno).raw()),
fmt::arg("errcode", builder_.my_errno));
} }
else else
{ {
@ -146,7 +156,9 @@ bool MakeProgressDialog::onProgressDialogRefresh()
else else
{ {
/* how much data we've scanned through to generate checksums */ /* how much data we've scanned through to generate checksums */
str = gtr_sprintf(_("Scanned %s"), tr_strlsize((uint64_t)builder_.pieceIndex * (uint64_t)builder_.pieceSize)); str = fmt::format(
_("Scanned {file_size}"),
fmt::arg("file_size", tr_strlsize((uint64_t)builder_.pieceIndex * (uint64_t)builder_.pieceSize).raw()));
} }
progress_bar_->set_fraction(fraction); progress_bar_->set_fraction(fraction);
@ -468,7 +480,7 @@ MakeDialog::Impl::Impl(MakeDialog& dialog, Glib::RefPtr<Session> const& core)
t->add_row_w(row, *file_radio_, *file_chooser_); t->add_row_w(row, *file_radio_, *file_chooser_);
pieces_lb_ = Gtk::make_managed<Gtk::Label>(); pieces_lb_ = Gtk::make_managed<Gtk::Label>();
pieces_lb_->set_markup(_("<i>No source selected</i>")); pieces_lb_->set_markup(fmt::format("<i>{}</i>", _("No source selected")));
t->add_row(row, {}, *pieces_lb_); t->add_row(row, {}, *pieces_lb_);
t->add_section_divider(row); t->add_section_divider(row);

View File

@ -5,10 +5,13 @@
#include <errno.h> #include <errno.h>
#include <stdio.h> #include <stdio.h>
#include <map>
#include <glibmm.h> #include <glibmm.h>
#include <glibmm/i18n.h> #include <glibmm/i18n.h>
#include <fmt/core.h>
#include <libtransmission/transmission.h> #include <libtransmission/transmission.h>
#include <libtransmission/log.h> #include <libtransmission/log.h>
@ -59,6 +62,7 @@ private:
void scroll_to_bottom(); void scroll_to_bottom();
void level_combo_changed_cb(Gtk::ComboBox* combo_box); void level_combo_changed_cb(Gtk::ComboBox* combo_box);
Gtk::ComboBox* level_combo_new() const;
bool is_pinned_to_new() const; bool is_pinned_to_new() const;
bool isRowVisible(Gtk::TreeModel::const_iterator const& iter) const; bool isRowVisible(Gtk::TreeModel::const_iterator const& iter) const;
@ -74,6 +78,7 @@ private:
tr_log_level maxLevel_ = TR_LOG_INFO; tr_log_level maxLevel_ = TR_LOG_INFO;
bool isPaused_ = false; bool isPaused_ = false;
sigc::connection refresh_tag_; sigc::connection refresh_tag_;
std::map<tr_log_level, char const*> const level_names_;
}; };
namespace namespace
@ -133,6 +138,18 @@ void MessageLogWindow::Impl::scroll_to_bottom()
***** *****
****/ ****/
Gtk::ComboBox* MessageLogWindow::Impl::level_combo_new() const
{
auto items = std::vector<std::pair<Glib::ustring, int>>{};
for (auto const& [level, name] : level_names_)
{
items.emplace_back(name, level);
}
auto* w = gtr_combo_box_new_enum(items);
gtr_combo_box_set_active_enum(*w, gtr_pref_int_get(TR_KEY_message_level));
return w;
}
void MessageLogWindow::Impl::level_combo_changed_cb(Gtk::ComboBox* combo_box) void MessageLogWindow::Impl::level_combo_changed_cb(Gtk::ComboBox* combo_box)
{ {
auto const level = static_cast<tr_log_level>(gtr_combo_box_get_active_enum(*combo_box)); auto const level = static_cast<tr_log_level>(gtr_combo_box_get_active_enum(*combo_box));
@ -166,9 +183,14 @@ void MessageLogWindow::Impl::doSave(Gtk::Window& parent, Glib::ustring const& fi
if (fp == nullptr) if (fp == nullptr)
{ {
auto const errcode = errno;
auto w = std::make_shared<Gtk::MessageDialog>( auto w = std::make_shared<Gtk::MessageDialog>(
parent, parent,
gtr_sprintf(_("Couldn't save \"%s\""), filename), fmt::format(
_("Couldn't save '{path}': {errmsg} ({errcode})"),
fmt::arg("path", filename.raw()),
fmt::arg("errmsg", g_strerror(errcode)),
fmt::arg("errcode", errcode)),
false, false,
Gtk::MESSAGE_ERROR, Gtk::MESSAGE_ERROR,
Gtk::BUTTONS_CLOSE); Gtk::BUTTONS_CLOSE);
@ -180,39 +202,17 @@ void MessageLogWindow::Impl::doSave(Gtk::Window& parent, Glib::ustring const& fi
{ {
for (auto const& row : store_->children()) for (auto const& row : store_->children())
{ {
char const* levelStr;
auto const* const node = row.get_value(message_log_cols.tr_msg); auto const* const node = row.get_value(message_log_cols.tr_msg);
auto const date = gtr_asctime(node->when); auto const date = gtr_asctime(node->when);
switch (node->level) auto const it = level_names_.find(node->level);
{ auto const* const level_str = it != std::end(level_names_) ? it->second : "???";
case TR_LOG_TRACE:
levelStr = _("trace");
break;
case TR_LOG_DEBUG:
levelStr = _("debug");
break;
case TR_LOG_WARN:
levelStr = _("warn");
break;
case TR_LOG_ERROR:
levelStr = _("error");
break;
default:
levelStr = _("info");
break;
}
fprintf( fprintf(
fp, fp,
"%s\t%s\t%s\t%s\n", "%s\t%s\t%s\t%s\n",
date.c_str(), date.c_str(),
levelStr, level_str,
node->name != nullptr ? node->name : "", node->name != nullptr ? node->name : "",
node->message != nullptr ? node->message : ""); node->message != nullptr ? node->message : "");
} }
@ -420,19 +420,6 @@ bool MessageLogWindow::Impl::onRefresh()
namespace namespace
{ {
Gtk::ComboBox* debug_level_combo_new()
{
auto* w = gtr_combo_box_new_enum({
{ _("Error"), TR_LOG_ERROR },
{ _("Warnings"), TR_LOG_WARN },
{ _("Information"), TR_LOG_INFO },
{ _("Debug"), TR_LOG_DEBUG },
{ _("Trace"), TR_LOG_TRACE },
});
gtr_combo_box_set_active_enum(*w, gtr_pref_int_get(TR_KEY_message_level));
return w;
}
} // namespace } // namespace
/** /**
@ -456,6 +443,12 @@ MessageLogWindow::~MessageLogWindow() = default;
MessageLogWindow::Impl::Impl(MessageLogWindow& window, Glib::RefPtr<Session> const& core) MessageLogWindow::Impl::Impl(MessageLogWindow& window, Glib::RefPtr<Session> const& core)
: window_(window) : window_(window)
, core_(core) , core_(core)
, level_names_{ { { TR_LOG_CRITICAL, _("Critical") },
{ TR_LOG_ERROR, _("Error") },
{ TR_LOG_WARN, _("Warning") },
{ TR_LOG_INFO, _("Information") },
{ TR_LOG_DEBUG, _("Debug") },
{ TR_LOG_TRACE, _("Trace") } } }
{ {
window_.set_title(_("Message Log")); window_.set_title(_("Message Log"));
window_.set_default_size(560, 350); window_.set_default_size(560, 350);
@ -516,7 +509,7 @@ MessageLogWindow::Impl::Impl(MessageLogWindow& window, Glib::RefPtr<Session> con
} }
{ {
auto* w = debug_level_combo_new(); auto* w = level_combo_new();
w->signal_changed().connect([this, w]() { level_combo_changed_cb(w); }); w->signal_changed().connect([this, w]() { level_combo_changed_cb(w); });
auto* item = Gtk::make_managed<Gtk::ToolItem>(); auto* item = Gtk::make_managed<Gtk::ToolItem>();
item->add(*w); item->add(*w);

View File

@ -10,6 +10,8 @@
#include <glibmm.h> #include <glibmm.h>
#include <glibmm/i18n.h> #include <glibmm/i18n.h>
#include <fmt/core.h>
#include <libtransmission/transmission.h> #include <libtransmission/transmission.h>
#include <libtransmission/utils.h> #include <libtransmission/utils.h>
#include <libtransmission/version.h> #include <libtransmission/version.h>
@ -410,8 +412,10 @@ struct blocklist_data
void updateBlocklistText(Gtk::Label* w, Glib::RefPtr<Session> const& core) void updateBlocklistText(Gtk::Label* w, Glib::RefPtr<Session> const& core)
{ {
int const n = tr_blocklistGetRuleCount(core->get_session()); int const n = tr_blocklistGetRuleCount(core->get_session());
w->set_markup( auto const msg = fmt::format(
gtr_sprintf("<i>%s</i>", gtr_sprintf(ngettext("Blocklist contains %'d rule", "Blocklist contains %'d rules", n), n))); ngettext("Blocklist has {count} entry", "Blocklist has {count} entries", n),
fmt::arg("count", n));
w->set_markup(gtr_sprintf("<i>%s</i>", msg.c_str()));
} }
/* prefs dialog is being destroyed, so stop listening to blocklist updates */ /* prefs dialog is being destroyed, so stop listening to blocklist updates */
@ -436,10 +440,14 @@ void onBlocklistUpdated(Glib::RefPtr<Session> const& core, int n, blocklist_data
{ {
bool const success = n >= 0; bool const success = n >= 0;
int const count = n >= 0 ? n : tr_blocklistGetRuleCount(core->get_session()); int const count = n >= 0 ? n : tr_blocklistGetRuleCount(core->get_session());
auto const msg = fmt::format(
ngettext("Blocklist has {count} entry", "Blocklist has {count} entries", count),
fmt::arg("count", count));
data->updateBlocklistButton->set_sensitive(true); data->updateBlocklistButton->set_sensitive(true);
data->updateBlocklistDialog->set_message(success ? _("<b>Update succeeded!</b>") : _("<b>Unable to update.</b>"), true); data->updateBlocklistDialog->set_message(
data->updateBlocklistDialog->set_secondary_text( fmt::format("<b>{}</b>", success ? _("Blocklist updated!") : _("Couldn't update blocklist")),
gtr_sprintf(ngettext("Blocklist has %'d rule.", "Blocklist has %'d rules.", count), count)); true);
data->updateBlocklistDialog->set_secondary_text(msg);
updateBlocklistText(data->label, core); updateBlocklistText(data->label, core);
} }
@ -841,19 +849,27 @@ Gtk::ComboBox* new_time_combo(Glib::RefPtr<Session> const& core, tr_quark const
return w; return w;
} }
static auto get_weekday_string(Glib::Date::Weekday weekday)
{
auto date = Glib::Date{};
date.set_time_current();
date.add_days(weekday - date.get_weekday());
return date.format_string("%A");
}
Gtk::ComboBox* new_week_combo(Glib::RefPtr<Session> const& core, tr_quark const key) Gtk::ComboBox* new_week_combo(Glib::RefPtr<Session> const& core, tr_quark const key)
{ {
auto* w = gtr_combo_box_new_enum({ auto* w = gtr_combo_box_new_enum({
{ _("Every Day"), TR_SCHED_ALL }, { _("Every Day"), TR_SCHED_ALL },
{ _("Weekdays"), TR_SCHED_WEEKDAY }, { _("Weekdays"), TR_SCHED_WEEKDAY },
{ _("Weekends"), TR_SCHED_WEEKEND }, { _("Weekends"), TR_SCHED_WEEKEND },
{ _("Sunday"), TR_SCHED_SUN }, { get_weekday_string(Glib::Date::MONDAY), TR_SCHED_MON },
{ _("Monday"), TR_SCHED_MON }, { get_weekday_string(Glib::Date::TUESDAY), TR_SCHED_TUES },
{ _("Tuesday"), TR_SCHED_TUES }, { get_weekday_string(Glib::Date::WEDNESDAY), TR_SCHED_WED },
{ _("Wednesday"), TR_SCHED_WED }, { get_weekday_string(Glib::Date::THURSDAY), TR_SCHED_THURS },
{ _("Thursday"), TR_SCHED_THURS }, { get_weekday_string(Glib::Date::FRIDAY), TR_SCHED_FRI },
{ _("Friday"), TR_SCHED_FRI }, { get_weekday_string(Glib::Date::SATURDAY), TR_SCHED_SAT },
{ _("Saturday"), TR_SCHED_SAT }, { get_weekday_string(Glib::Date::SUNDAY), TR_SCHED_SUN },
}); });
gtr_combo_box_set_active_enum(*w, gtr_pref_int_get(key)); gtr_combo_box_set_active_enum(*w, gtr_pref_int_get(key));
w->signal_changed().connect([w, key, core]() { onIntComboChanged(w, key, core); }); w->signal_changed().connect([w, key, core]() { onIntComboChanged(w, key, core); });
@ -999,7 +1015,7 @@ void onPortTest(std::shared_ptr<network_page_data> const& data)
{ {
data->portButton->set_sensitive(false); data->portButton->set_sensitive(false);
data->portSpin->set_sensitive(false); data->portSpin->set_sensitive(false);
data->portLabel->set_markup(_("<i>Testing TCP port…</i>")); data->portLabel->set_markup(fmt::format("<i>{}</i>", _("Testing TCP port…")));
if (!data->portTag.connected()) if (!data->portTag.connected())
{ {

View File

@ -615,7 +615,13 @@ void rename_torrent(Glib::RefPtr<Gio::File> const& file)
} }
catch (Glib::Error const& e) catch (Glib::Error const& e)
{ {
g_message("Unable to rename \"%s\" as \"%s\": %s", old_name.c_str(), new_name.c_str(), e.what().c_str()); auto const errmsg = fmt::format(
_("Couldn't rename '{oldpath}' as '{path}': {errmsg} ({errcode})"),
fmt::arg("oldpath", old_name.raw()),
fmt::arg("path", new_name.raw()),
fmt::arg("errmsg", e.what().raw()),
fmt::arg("errcode", e.code()));
g_message("%s", errmsg.c_str());
} }
} }
} }

View File

@ -12,6 +12,8 @@
#include <giomm.h> /* g_file_trash() */ #include <giomm.h> /* g_file_trash() */
#include <glibmm/i18n.h> #include <glibmm/i18n.h>
#include <fmt/core.h>
#include <libtransmission/transmission.h> /* TR_RATIO_NA, TR_RATIO_INF */ #include <libtransmission/transmission.h> /* TR_RATIO_NA, TR_RATIO_INF */
#include <libtransmission/error.h> #include <libtransmission/error.h>
@ -164,7 +166,7 @@ void gtr_add_torrent_error_dialog(Gtk::Widget& child, tr_torrent* duplicate_torr
auto w = std::make_shared<Gtk::MessageDialog>( auto w = std::make_shared<Gtk::MessageDialog>(
*win, *win,
_("Error opening torrent"), _("Couldn't open torrent"),
false, false,
Gtk::MESSAGE_ERROR, Gtk::MESSAGE_ERROR,
Gtk::BUTTONS_CLOSE); Gtk::BUTTONS_CLOSE);
@ -450,7 +452,7 @@ void gtr_unrecognized_url_dialog(Gtk::Widget& parent, Glib::ustring const& url)
auto w = std::make_shared<Gtk::MessageDialog>( auto w = std::make_shared<Gtk::MessageDialog>(
*window, *window,
_("Unrecognized URL"), fmt::format(_("Unsupported URL: '{url}'"), fmt::arg("url", url.raw())),
false /*use markup*/, false /*use markup*/,
Gtk::MESSAGE_ERROR, Gtk::MESSAGE_ERROR,
Gtk::BUTTONS_CLOSE, Gtk::BUTTONS_CLOSE,

View File

@ -14,6 +14,8 @@
#include <event2/dns.h> #include <event2/dns.h>
#include <event2/util.h> #include <event2/util.h>
#include <fmt/core.h>
#define LIBTRANSMISSION_ANNOUNCER_MODULE #define LIBTRANSMISSION_ANNOUNCER_MODULE
#include "transmission.h" #include "transmission.h"
@ -462,8 +464,12 @@ static void tau_tracker_on_dns(int errcode, struct evutil_addrinfo* addr, void*
if (errcode != 0) if (errcode != 0)
{ {
auto const errmsg = tr_strvJoin("DNS Lookup failed: "sv, evutil_gai_strerror(errcode)); auto const errmsg = fmt::format(
logwarn(tracker->key, "%s", errmsg.c_str()); _("Couldn't find address of tracker '{host}': {errmsg} ({errcode})"),
fmt::arg("host", tracker->host.sv()),
fmt::arg("errmsg", evutil_gai_strerror(errcode)),
fmt::arg("errcode", errcode));
logwarn(tracker->key, errmsg);
tracker->failAll(false, false, errmsg.c_str()); tracker->failAll(false, false, errmsg.c_str());
} }
else else

View File

@ -968,7 +968,7 @@ static void on_announce_error(tr_tier* tier, char const* err, tr_announce_event
tr_logAddWarnTier( tr_logAddWarnTier(
tier, tier,
fmt::format( fmt::format(
ngettext_( ngettext(
"Announce error: {errmsg} (Retrying in {count} second)", "Announce error: {errmsg} (Retrying in {count} second)",
"Announce error: {errmsg} (Retrying in {count} seconds)", "Announce error: {errmsg} (Retrying in {count} seconds)",
interval), interval),
@ -1301,7 +1301,7 @@ static void checkMultiscrapeMax(tr_announcer* announcer, tr_scrape_response cons
auto const parsed = *tr_urlParse(url.sv()); auto const parsed = *tr_urlParse(url.sv());
auto clean_url = std::string{}; auto clean_url = std::string{};
tr_buildBuf(clean_url, parsed.scheme, "://"sv, parsed.host, ":"sv, parsed.portstr); tr_buildBuf(clean_url, parsed.scheme, "://"sv, parsed.host, ":"sv, parsed.portstr);
tr_logAddNamedInfo(clean_url.c_str(), fmt::format(_("Reducing multiscrape max to {}"), n)); tr_logAddNamedDebug(clean_url.c_str(), fmt::format("Reducing multiscrape max to {}", n));
multiscrape_max = n; multiscrape_max = n;
} }
} }
@ -1427,7 +1427,7 @@ static void scrape_request_delegate(
} }
else else
{ {
tr_logAddError(fmt::format(_("Unsupported URL: {url}"), fmt::arg("url", scrape_sv))); tr_logAddError(fmt::format(_("Unsupported URL: '{url}'"), fmt::arg("url", scrape_sv)));
} }
} }

View File

@ -6,7 +6,10 @@
#include <algorithm> #include <algorithm>
#include <vector> #include <vector>
#include <fmt/core.h>
#include "transmission.h" #include "transmission.h"
#include "bandwidth.h" #include "bandwidth.h"
#include "crypto-utils.h" /* tr_rand_int_weak() */ #include "crypto-utils.h" /* tr_rand_int_weak() */
#include "log.h" #include "log.h"
@ -14,8 +17,6 @@
#include "tr-assert.h" #include "tr-assert.h"
#include "utils.h" #include "utils.h"
#define logtrace(...) tr_logAddMessage(__FILE__, __LINE__, TR_LOG_TRACE, "", __VA_ARGS__)
/*** /***
**** ****
***/ ***/
@ -166,7 +167,7 @@ void Bandwidth::phaseOne(std::vector<tr_peerIo*>& peerArray, tr_direction dir)
* peers from starving the others. Loop through the peers, giving each a * peers from starving the others. Loop through the peers, giving each a
* small chunk of bandwidth. Keep looping until we run out of bandwidth * small chunk of bandwidth. Keep looping until we run out of bandwidth
* and/or peers that can use it */ * and/or peers that can use it */
logtrace("%lu peers to go round-robin for %s", peerArray.size(), dir == TR_UP ? "upload" : "download"); tr_logAddTrace(fmt::format("{} peers to go round-robin for {}", peerArray.size(), dir == TR_UP ? "upload" : "download"));
size_t n = peerArray.size(); size_t n = peerArray.size();
while (n > 0) while (n > 0)
@ -180,7 +181,7 @@ void Bandwidth::phaseOne(std::vector<tr_peerIo*>& peerArray, tr_direction dir)
int const bytes_used = tr_peerIoFlush(peerArray[i], dir, increment); int const bytes_used = tr_peerIoFlush(peerArray[i], dir, increment);
logtrace("peer #%d of %zu used %d bytes in this pass", i, n, bytes_used); tr_logAddTrace(fmt::format("peer #{} of {} used {} bytes in this pass", i, n, bytes_used));
if (bytes_used != int(increment)) if (bytes_used != int(increment))
{ {

View File

@ -101,7 +101,7 @@ static void blocklistLoad(tr_blocklistFile* b)
char* const base = tr_sys_path_basename(b->filename, nullptr); char* const base = tr_sys_path_basename(b->filename, nullptr);
tr_logAddInfo(fmt::format( tr_logAddInfo(fmt::format(
ngettext_("Blocklist '{path}' has {count} entry", "Blocklist '{path}' has {count} entries", b->ruleCount), ngettext("Blocklist '{path}' has {count} entry", "Blocklist '{path}' has {count} entries", b->ruleCount),
fmt::arg("path", base), fmt::arg("path", base),
fmt::arg("count", b->ruleCount))); fmt::arg("count", b->ruleCount)));
tr_free(base); tr_free(base);
@ -483,12 +483,9 @@ int tr_blocklistFileSetContent(tr_blocklistFile* b, char const* filename)
{ {
char* base = tr_sys_path_basename(b->filename, nullptr); char* base = tr_sys_path_basename(b->filename, nullptr);
tr_logAddInfo(fmt::format( tr_logAddInfo(fmt::format(
ngettext_( ngettext("Blocklist '{path}' has {count} entry", "Blocklist '{path}' has {count} entries", b->ruleCount),
"Blocklist '{path}' updated with {count} entry",
"Blocklist '{path}' updated with {count} entries",
ranges_count),
fmt::arg("path", base), fmt::arg("path", base),
fmt::arg("count", ranges_count))); fmt::arg("count", b->ruleCount)));
tr_free(base); tr_free(base);
} }

View File

@ -8,6 +8,8 @@
#include <event2/buffer.h> #include <event2/buffer.h>
#include <fmt/core.h>
#include "transmission.h" #include "transmission.h"
#include "cache.h" #include "cache.h"
#include "inout.h" #include "inout.h"
@ -18,7 +20,7 @@
#include "trevent.h" #include "trevent.h"
#include "utils.h" #include "utils.h"
auto constexpr CodeName = std::string_view{ "cache" }; auto constexpr LogName = std::string_view{ "cache" };
/**** /****
***** *****
@ -243,10 +245,8 @@ int tr_cacheSetLimit(tr_cache* cache, int64_t max_bytes)
cache->max_blocks = getMaxBlocks(max_bytes); cache->max_blocks = getMaxBlocks(max_bytes);
tr_logAddNamedDebug( tr_logAddNamedDebug(
CodeName, LogName,
"Maximum cache size set to %s (%d blocks)", fmt::format("Maximum cache size set to {} ({} blocks)", tr_formatter_mem_B(cache->max_bytes), cache->max_blocks));
tr_formatter_mem_B(cache->max_bytes).c_str(),
cache->max_blocks);
return cacheTrim(cache); return cacheTrim(cache);
} }
@ -406,13 +406,9 @@ int tr_cacheFlushFile(tr_cache* cache, tr_torrent* torrent, tr_file_index_t i)
{ {
auto const [begin, end] = tr_torGetFileBlockSpan(torrent, i); auto const [begin, end] = tr_torGetFileBlockSpan(torrent, i);
int pos = findBlockPos(cache, torrent, torrent->blockLoc(begin)); int const pos = findBlockPos(cache, torrent, torrent->blockLoc(begin));
tr_logAddNamedTrace(
CodeName, tr_logAddNamedTrace(LogName, fmt::format("flushing file {} from cache to disk: blocks [{}...{})", i, begin, end));
"flushing file %d from cache to disk: blocks [%zu...%zu)",
(int)i,
(size_t)begin,
(size_t)end);
/* flush out all the blocks in that file */ /* flush out all the blocks in that file */
int err = 0; int err = 0;

View File

@ -219,12 +219,12 @@ static int cached_file_open(
if (allocation == TR_PREALLOCATE_FULL) if (allocation == TR_PREALLOCATE_FULL)
{ {
success = preallocate_file_full(fd, file_size, &error); success = preallocate_file_full(fd, file_size, &error);
type = _("full"); type = "full";
} }
else if (allocation == TR_PREALLOCATE_SPARSE) else if (allocation == TR_PREALLOCATE_SPARSE)
{ {
success = preallocate_file_sparse(fd, file_size, &error); success = preallocate_file_sparse(fd, file_size, &error);
type = _("sparse"); type = "sparse";
} }
TR_ASSERT(type != nullptr); TR_ASSERT(type != nullptr);

View File

@ -21,6 +21,8 @@
#include <event2/util.h> #include <event2/util.h>
#include <fmt/core.h>
#include <cstdint> #include <cstdint>
#include <libutp/utp.h> #include <libutp/utp.h>
@ -34,21 +36,31 @@
#include "tr-assert.h" #include "tr-assert.h"
#include "tr-macros.h" #include "tr-macros.h"
#include "tr-utp.h" /* tr_utpSendTo() */ #include "tr-utp.h" /* tr_utpSendTo() */
#include "utils.h" /* tr_time(), tr_logAddDebug() */ #include "utils.h" /* tr_time() */
#ifndef IN_MULTICAST #ifndef IN_MULTICAST
#define IN_MULTICAST(a) (((a)&0xf0000000) == 0xe0000000) #define IN_MULTICAST(a) (((a)&0xf0000000) == 0xe0000000)
#endif #endif
#undef tr_logAddCritical
#undef tr_logAddError
#undef tr_logAddWarn
#undef tr_logAddInfo
#undef tr_logAddDebug
#undef tr_logAddTrace
auto constexpr LogName = std::string_view{ "net" };
#define tr_logAddCritical(...) tr_logAddNamed(TR_LOG_CRITICAL, LogName, __VA_ARGS__)
#define tr_logAddError(...) tr_logAddNamed(TR_LOG_ERROR, LogName, __VA_ARGS__)
#define tr_logAddWarn(...) tr_logAddNamed(TR_LOG_WARN, LogName, __VA_ARGS__)
#define tr_logAddInfo(...) tr_logAddNamed(TR_LOG_INFO, LogName, __VA_ARGS__)
#define tr_logAddDebug(...) tr_logAddNamed(TR_LOG_DEBUG, LogName, __VA_ARGS__)
#define tr_logAddTrace(...) tr_logAddNamed(TR_LOG_TRACE, LogName, __VA_ARGS__)
tr_address const tr_in6addr_any = { TR_AF_INET6, { IN6ADDR_ANY_INIT } }; tr_address const tr_in6addr_any = { TR_AF_INET6, { IN6ADDR_ANY_INIT } };
tr_address const tr_inaddr_any = { TR_AF_INET, { { { { INADDR_ANY } } } } }; tr_address const tr_inaddr_any = { TR_AF_INET, { { { { INADDR_ANY } } } } };
#define logerr(...) tr_logAddNamed(TR_LOG_ERROR, "net", __VA_ARGS__)
#define logwarn(...) tr_logAddNamed(TR_LOG_WARN, "net", __VA_ARGS__)
#define logdbg(...) tr_logAddNamed(TR_LOG_DEBUG, "net", __VA_ARGS__)
#define logtrace(...) tr_logAddNamed(TR_LOG_TRACE, "net", __VA_ARGS__)
std::string tr_net_strerror(int err) std::string tr_net_strerror(int err)
{ {
#ifdef _WIN32 #ifdef _WIN32
@ -148,10 +160,7 @@ std::string tr_address::to_string(tr_port port) const
{ {
auto addrbuf = std::array<char, TR_ADDRSTRLEN>{}; auto addrbuf = std::array<char, TR_ADDRSTRLEN>{};
tr_address_to_string_with_buf(this, std::data(addrbuf), std::size(addrbuf)); tr_address_to_string_with_buf(this, std::data(addrbuf), std::size(addrbuf));
return fmt::format("[{}]:{}", std::data(addrbuf), ntohs(port));
auto buf = std::array<char, TR_ADDRSTRLEN>{};
tr_snprintf(std::data(buf), std::size(buf), "[%s]:%u", std::data(addrbuf), ntohs(port));
return std::data(buf);
} }
tr_address tr_address::from_4byte_ipv4(std::string_view in) tr_address tr_address::from_4byte_ipv4(std::string_view in)
@ -257,7 +266,7 @@ void tr_netSetTOS([[maybe_unused]] tr_socket_t s, [[maybe_unused]] int tos, tr_a
if (setsockopt(s, IPPROTO_IP, IP_TOS, (void const*)&tos, sizeof(tos)) == -1) if (setsockopt(s, IPPROTO_IP, IP_TOS, (void const*)&tos, sizeof(tos)) == -1)
{ {
logwarn("Can't set TOS '%d': %s", tos, tr_net_strerror(sockerrno).c_str()); tr_logAddDebug(fmt::format("Can't set TOS '{}': {}", tos, tr_net_strerror(sockerrno)));
} }
#endif #endif
} }
@ -266,14 +275,14 @@ void tr_netSetTOS([[maybe_unused]] tr_socket_t s, [[maybe_unused]] int tos, tr_a
#if defined(IPV6_TCLASS) && !defined(_WIN32) #if defined(IPV6_TCLASS) && !defined(_WIN32)
if (setsockopt(s, IPPROTO_IPV6, IPV6_TCLASS, (void const*)&tos, sizeof(tos)) == -1) if (setsockopt(s, IPPROTO_IPV6, IPV6_TCLASS, (void const*)&tos, sizeof(tos)) == -1)
{ {
logwarn("Can't set IPv6 QoS '%d': %s", tos, tr_net_strerror(sockerrno).c_str()); tr_logAddDebug(fmt::format("Can't set IPv6 QoS '{}': {}", tos, tr_net_strerror(sockerrno)));
} }
#endif #endif
} }
else else
{ {
/* program should never reach here! */ /* program should never reach here! */
logdbg("Something goes wrong while setting TOS/Traffic-Class"); tr_logAddDebug("Something goes wrong while setting TOS/Traffic-Class");
} }
} }
@ -283,7 +292,7 @@ void tr_netSetCongestionControl([[maybe_unused]] tr_socket_t s, [[maybe_unused]]
if (setsockopt(s, IPPROTO_TCP, TCP_CONGESTION, (void const*)algorithm, strlen(algorithm) + 1) == -1) if (setsockopt(s, IPPROTO_TCP, TCP_CONGESTION, (void const*)algorithm, strlen(algorithm) + 1) == -1)
{ {
logwarn("Can't set congestion control algorithm '%s': %s", algorithm, tr_net_strerror(sockerrno).c_str()); tr_logAddDebug(fmt::format("Can't set congestion control algorithm '{}': {}", algorithm, tr_net_strerror(sockerrno)));
} }
#endif #endif
@ -363,7 +372,7 @@ struct tr_peer_socket tr_netOpenPeerSocket(tr_session* session, tr_address const
if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<char const*>(&n), sizeof(n)) == -1) if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<char const*>(&n), sizeof(n)) == -1)
{ {
logwarn("Unable to set SO_RCVBUF on socket %" PRIdMAX ": %s", (intmax_t)s, tr_net_strerror(sockerrno).c_str()); tr_logAddDebug(fmt::format("Unable to set SO_RCVBUF on socket {}: {}", s, tr_net_strerror(sockerrno)));
} }
} }
@ -382,11 +391,12 @@ struct tr_peer_socket tr_netOpenPeerSocket(tr_session* session, tr_address const
if (bind(s, (struct sockaddr*)&source_sock, sourcelen) == -1) if (bind(s, (struct sockaddr*)&source_sock, sourcelen) == -1)
{ {
logwarn( tr_logAddWarn(fmt::format(
_("Couldn't set source address %s on %" PRIdMAX ": %s"), _("Couldn't set source address {address} on {socket}: {errmsg} ({errcode})"),
tr_address_to_string(source_addr), fmt::arg("address", source_addr->to_string()),
(intmax_t)s, fmt::arg("socket", s),
tr_net_strerror(sockerrno).c_str()); fmt::arg("errmsg", tr_net_strerror(sockerrno)),
fmt::arg("errcode", sockerrno)));
tr_netClose(session, s); tr_netClose(session, s);
return ret; return ret;
} }
@ -401,13 +411,13 @@ struct tr_peer_socket tr_netOpenPeerSocket(tr_session* session, tr_address const
if ((tmperrno != ENETUNREACH && tmperrno != EHOSTUNREACH) || addr->type == TR_AF_INET) if ((tmperrno != ENETUNREACH && tmperrno != EHOSTUNREACH) || addr->type == TR_AF_INET)
{ {
logwarn( tr_logAddWarn(fmt::format(
_("Couldn't connect socket %" PRIdMAX " to %s, port %d (errno %d - %s)"), _("Couldn't connect socket {socket} to {address}:{port}: {errmsg} ({errcode})"),
(intmax_t)s, fmt::arg("socket", s),
tr_address_to_string(addr), fmt::arg("address", addr->to_string()),
(int)ntohs(port), fmt::arg("port", ntohs(port)),
tmperrno, fmt::arg("errmsg", tr_net_strerror(tmperrno)),
tr_net_strerror(tmperrno).c_str()); fmt::arg("errcode", tmperrno)));
} }
tr_netClose(session, s); tr_netClose(session, s);
@ -419,7 +429,7 @@ struct tr_peer_socket tr_netOpenPeerSocket(tr_session* session, tr_address const
char addrstr[TR_ADDRSTRLEN]; char addrstr[TR_ADDRSTRLEN];
tr_address_and_port_to_string(addrstr, sizeof(addrstr), addr, port); tr_address_and_port_to_string(addrstr, sizeof(addrstr), addr, port);
logtrace("New OUTGOING connection %" PRIdMAX " (%s)", (intmax_t)s, addrstr); tr_logAddTrace(fmt::format("New OUTGOING connection {} ({})", s, addrstr));
return ret; return ret;
} }
@ -511,12 +521,14 @@ static tr_socket_t tr_netBindTCPImpl(tr_address const* addr, tr_port port, bool
if (!suppressMsgs) if (!suppressMsgs)
{ {
char const* const hint = err == EADDRINUSE ? _("Is another copy of Transmission already running?") : nullptr; tr_logAddError(fmt::format(
err == EADDRINUSE ?
char const* const fmt = hint == nullptr ? _("Couldn't bind port %d on %s: %s") : _("Couldn't bind port {port} on {address}: {errmsg} ({errcode}) -- Is another copy of Transmission already running?") :
_("Couldn't bind port %d on %s: %s (%s)"); _("Couldn't bind port {port} on {address}: {errmsg} ({errcode})"),
fmt::arg("address", addr->to_string()),
logerr(fmt, port, tr_address_to_string(addr), tr_net_strerror(err).c_str(), hint); fmt::arg("port", port),
fmt::arg("errmsg", tr_net_strerror(err)),
fmt::arg("errcode", err)));
} }
tr_netCloseSocket(fd); tr_netCloseSocket(fd);
@ -526,7 +538,7 @@ static tr_socket_t tr_netBindTCPImpl(tr_address const* addr, tr_port port, bool
if (!suppressMsgs) if (!suppressMsgs)
{ {
logdbg("Bound socket %" PRIdMAX " to port %d on %s", (intmax_t)fd, port, tr_address_to_string(addr)); tr_logAddDebug(fmt::format("Bound socket {} to port {} on {}", fd, port, addr->to_string()));
} }
#ifdef TCP_FASTOPEN #ifdef TCP_FASTOPEN

View File

@ -8,6 +8,8 @@
#include <event2/event.h> #include <event2/event.h>
#include <fmt/core.h>
#include "transmission.h" #include "transmission.h"
#include "natpmp_local.h" #include "natpmp_local.h"
#include "log.h" #include "log.h"
@ -104,7 +106,10 @@ static void natPulse(tr_shared* s, bool do_check)
if (new_status != old_status) if (new_status != old_status)
{ {
loginfo(_("State changed from \"%1$s\" to \"%2$s\""), getNatStateStr(old_status), getNatStateStr(new_status)); loginfo(fmt::format(
_("State changed from '{oldstate}' to '{state}"),
fmt::arg("oldstate", getNatStateStr(old_status)),
fmt::arg("state", getNatStateStr(new_status))));
} }
} }

View File

@ -12,8 +12,6 @@
#include <string_view> #include <string_view>
#include <vector> #include <vector>
#include <libdeflate.h>
#ifndef _WIN32 #ifndef _WIN32
#include <sys/un.h> #include <sys/un.h>
#include <sys/stat.h> #include <sys/stat.h>
@ -26,6 +24,10 @@
#include <event2/http_struct.h> /* TODO: eventually remove this */ #include <event2/http_struct.h> /* TODO: eventually remove this */
#include <event2/listener.h> #include <event2/listener.h>
#include <fmt/core.h>
#include <libdeflate.h>
#include "transmission.h" #include "transmission.h"
#include "crypto-utils.h" /* tr_rand_buffer() */ #include "crypto-utils.h" /* tr_rand_buffer() */
@ -49,6 +51,23 @@
using namespace std::literals; using namespace std::literals;
#undef tr_logAddCritical
#undef tr_logAddError
#undef tr_logAddWarn
#undef tr_logAddInfo
#undef tr_logAddDebug
#undef tr_logAddTrace
auto constexpr LogName = "rpc"sv;
#define tr_logAddCritical(...) tr_logAddNamed(TR_LOG_CRITICAL, LogName, __VA_ARGS__)
#define tr_logAddError(...) tr_logAddNamed(TR_LOG_ERROR, LogName, __VA_ARGS__)
#define tr_logAddWarn(...) tr_logAddNamed(TR_LOG_WARN, LogName, __VA_ARGS__)
#define tr_logAddInfo(...) tr_logAddNamed(TR_LOG_INFO, LogName, __VA_ARGS__)
#define tr_logAddDebug(...) tr_logAddNamed(TR_LOG_DEBUG, LogName, __VA_ARGS__)
#define tr_logAddTrace(...) tr_logAddNamed(TR_LOG_TRACE, LogName, __VA_ARGS__)
///
/* session-id is used to make cross-site request forgery attacks difficult. /* session-id is used to make cross-site request forgery attacks difficult.
* Don't disable this feature unless you really know what you're doing! * Don't disable this feature unless you really know what you're doing!
* http://en.wikipedia.org/wiki/Cross-site_request_forgery * http://en.wikipedia.org/wiki/Cross-site_request_forgery
@ -94,11 +113,6 @@ struct tr_rpc_address
#define MY_REALM "Transmission" #define MY_REALM "Transmission"
#define logerr(...) tr_logAddNamed(TR_LOG_ERROR, "rpc", __VA_ARGS__)
#define logwarn(...) tr_logAddNamed(TR_LOG_WARN, "rpc", __VA_ARGS__)
#define loginfo(...) tr_logAddNamed(TR_LOG_INFO, "rpc", __VA_ARGS__)
#define logdbg(...) tr_logAddNamed(TR_LOG_DEBUG, "rpc", __VA_ARGS__)
static int constexpr DeflateLevel = 6; // medium / default static int constexpr DeflateLevel = 6; // medium / default
static bool constexpr tr_rpc_address_is_valid(tr_rpc_address const& a) static bool constexpr tr_rpc_address_is_valid(tr_rpc_address const& a)
@ -634,10 +648,10 @@ static bool tr_rpc_address_from_string(tr_rpc_address& dst, std::string_view src
{ {
if (std::size(src) >= TrUnixAddrStrLen) if (std::size(src) >= TrUnixAddrStrLen)
{ {
logerr( tr_logAddError(fmt::format(
_("Unix socket path must be fewer than %zu characters (including \"%" TR_PRIsv "\" prefix)"), _("Unix socket path must be fewer than {count} characters (including '{prefix}' prefix)"),
TrUnixAddrStrLen - 1, fmt::arg("count", TrUnixAddrStrLen - 1),
TR_PRIsv_ARG(TrUnixSocketPrefix)); fmt::arg("prefix", TrUnixSocketPrefix)));
return false; return false;
} }
@ -668,9 +682,9 @@ static bool bindUnixSocket(
[[maybe_unused]] int socket_mode) [[maybe_unused]] int socket_mode)
{ {
#ifdef _WIN32 #ifdef _WIN32
logerr( tr_logAddError(fmt::format(
_("Unix sockets are not supported on Windows. Please change \"%s\" in your configuration file."), _("Unix sockets are not supported on Windows. Please change '{key}' in your configuration file."),
tr_quark_get_string(TR_KEY_rpc_bind_address)); fmt::arg("key", tr_quark_get_string(TR_KEY_rpc_bind_address))));
return false; return false;
#else #else
struct sockaddr_un addr; struct sockaddr_un addr;
@ -695,7 +709,8 @@ static bool bindUnixSocket(
if (chmod(addr.sun_path, (mode_t)socket_mode) != 0) if (chmod(addr.sun_path, (mode_t)socket_mode) != 0)
{ {
logwarn(_("Could not set RPC socket mode to %o, defaulting to 755"), socket_mode); tr_logAddWarn(
fmt::format(_("Could not set RPC socket mode to {mode:o}, defaulting to 755"), fmt::arg("mode", socket_mode)));
} }
return evhttp_bind_listener(httpd, lev) != nullptr; return evhttp_bind_listener(httpd, lev) != nullptr;
@ -766,18 +781,24 @@ static void startServer(tr_rpc_server* server)
{ {
int const retry_delay = rpc_server_start_retry(server); int const retry_delay = rpc_server_start_retry(server);
logdbg("Unable to bind to %s, retrying in %d seconds", addr_port_str.c_str(), retry_delay); tr_logAddDebug(fmt::format("Couldn't bind to {}, retrying in {} seconds", addr_port_str, retry_delay));
return; return;
} }
logerr("Unable to bind to %s after %d attempts, giving up", addr_port_str.c_str(), ServerStartRetryCount); tr_logAddError(fmt::format(
ngettext(
"Couldn't bind to {address} after {count} attempt, giving up",
"Couldn't bind to {address} after {count} attempts, giving up",
ServerStartRetryCount),
fmt::arg("address", addr_port_str),
fmt::arg("count", ServerStartRetryCount)));
} }
else else
{ {
evhttp_set_gencb(httpd, handle_request, server); evhttp_set_gencb(httpd, handle_request, server);
server->httpd = httpd; server->httpd = httpd;
loginfo("Started listening on %s", addr_port_str.c_str()); tr_logAddInfo(fmt::format(_("Started listening on {address}"), fmt::arg("address", addr_port_str)));
} }
rpc_server_start_retry_cancel(server); rpc_server_start_retry_cancel(server);
@ -806,7 +827,7 @@ static void stopServer(tr_rpc_server* server)
unlink(address + std::size(TrUnixSocketPrefix)); unlink(address + std::size(TrUnixSocketPrefix));
} }
loginfo("Stopped listening on %s", tr_rpc_address_with_port(server).c_str()); tr_logAddInfo(fmt::format(_("Stopped listening on {address}"), fmt::arg("address", tr_rpc_address_with_port(server))));
} }
static void onEnabledChanged(tr_rpc_server* const server) static void onEnabledChanged(tr_rpc_server* const server)
@ -865,7 +886,7 @@ tr_port tr_rpcGetPort(tr_rpc_server const* server)
void tr_rpcSetUrl(tr_rpc_server* server, std::string_view url) void tr_rpcSetUrl(tr_rpc_server* server, std::string_view url)
{ {
server->url = url; server->url = url;
logdbg("setting our URL to [%s]", server->url.c_str()); tr_logAddDebug(fmt::format("setting our URL to '{}'", server->url));
} }
std::string const& tr_rpcGetUrl(tr_rpc_server const* server) std::string const& tr_rpcGetUrl(tr_rpc_server const* server)
@ -886,13 +907,13 @@ static auto parseWhitelist(std::string_view whitelist)
if (token.find_first_of("+-"sv) != std::string_view::npos) if (token.find_first_of("+-"sv) != std::string_view::npos)
{ {
logwarn( tr_logAddWarn(fmt::format(
"Adding address to whitelist: %" TR_PRIsv " (And it has a '+' or '-'! Are you using an old ACL by mistake?)", _("Adding entry to whitelist: {entry} (And it has a '+' or '-'! Are you using an old ACL by mistake?)"),
TR_PRIsv_ARG(token)); fmt::arg("entry", token)));
} }
else else
{ {
loginfo("Adding address to whitelist: %" TR_PRIsv, TR_PRIsv_ARG(token)); tr_logAddInfo(fmt::format(_("Adding entry to whitelist: {entry}"), fmt::arg("entry", token)));
} }
} }
@ -947,7 +968,7 @@ static void tr_rpcSetRPCSocketMode(tr_rpc_server* server, int socket_mode)
void tr_rpcSetUsername(tr_rpc_server* server, std::string_view username) void tr_rpcSetUsername(tr_rpc_server* server, std::string_view username)
{ {
server->username = username; server->username = username;
logdbg("setting our Username to [%s]", server->username.c_str()); tr_logAddDebug(fmt::format("setting our username to '{}'", server->username));
} }
std::string const& tr_rpcGetUsername(tr_rpc_server const* server) std::string const& tr_rpcGetUsername(tr_rpc_server const* server)
@ -964,7 +985,7 @@ void tr_rpcSetPassword(tr_rpc_server* server, std::string_view password)
{ {
server->salted_password = isSalted(password) ? password : tr_ssha1(password); server->salted_password = isSalted(password) ? password : tr_ssha1(password);
logdbg("setting our salted password to [%s]", server->salted_password.c_str()); tr_logAddDebug(fmt::format("setting our salted password to '{}'", server->salted_password));
} }
std::string const& tr_rpcGetPassword(tr_rpc_server const* server) std::string const& tr_rpcGetPassword(tr_rpc_server const* server)
@ -975,7 +996,7 @@ std::string const& tr_rpcGetPassword(tr_rpc_server const* server)
void tr_rpcSetPasswordEnabled(tr_rpc_server* server, bool isEnabled) void tr_rpcSetPasswordEnabled(tr_rpc_server* server, bool isEnabled)
{ {
server->isPasswordEnabled = isEnabled; server->isPasswordEnabled = isEnabled;
logdbg("setting 'password enabled' to %d", (int)isEnabled); tr_logAddDebug(fmt::format("setting password-enabled to '{}'", isEnabled));
} }
bool tr_rpcIsPasswordEnabled(tr_rpc_server const* server) bool tr_rpcIsPasswordEnabled(tr_rpc_server const* server)
@ -1019,7 +1040,7 @@ void tr_rpcSetAntiBruteForceThreshold(tr_rpc_server* server, int badRequests)
static void missing_settings_key(tr_quark const q) static void missing_settings_key(tr_quark const q)
{ {
logdbg(_("Couldn't find settings key \"%s\""), tr_quark_get_string(q)); tr_logAddDebug(fmt::format("Couldn't find settings key '{}'", tr_quark_get_string(q)));
} }
tr_rpc_server::tr_rpc_server(tr_session* session_in, tr_variant* settings) tr_rpc_server::tr_rpc_server(tr_session* session_in, tr_variant* settings)
@ -1187,10 +1208,10 @@ tr_rpc_server::tr_rpc_server(tr_session* session_in, tr_variant* settings)
} }
else if (!tr_rpc_address_from_string(*bindAddress, sv)) else if (!tr_rpc_address_from_string(*bindAddress, sv))
{ {
logwarn( tr_logAddWarn(fmt::format(
_("%" TR_PRIsv _("{key} value ({address}) must be an IPv4 or IPv6 address or a unix socket path. Using default value '0.0.0.0'"),
" is not an IPv4 address, an IPv6 address, or a unix socket path. RPC listeners must be one of the previously mentioned types. Falling back to 0.0.0.0."), fmt::format("key", tr_quark_get_string(key)),
TR_PRIsv_ARG(sv)); fmt::format("address", sv)));
bindAddress->set_inaddr_any(); bindAddress->set_inaddr_any();
} }
@ -1203,24 +1224,24 @@ tr_rpc_server::tr_rpc_server(tr_session* session_in, tr_variant* settings)
if (this->isEnabled) if (this->isEnabled)
{ {
auto const rpc_uri = tr_rpc_address_with_port(this) + this->url; auto const rpc_uri = tr_rpc_address_with_port(this) + this->url;
loginfo(_("Serving RPC and Web requests on %s"), rpc_uri.c_str()); tr_logAddInfo(fmt::format(_("Serving RPC and Web requests on {address}"), fmt::arg("address", rpc_uri)));
tr_runInEventThread(session, startServer, this); tr_runInEventThread(session, startServer, this);
if (this->isWhitelistEnabled) if (this->isWhitelistEnabled)
{ {
loginfo("%s", _("Whitelist enabled")); tr_logAddInfo(_("Whitelist enabled"));
} }
if (this->isPasswordEnabled) if (this->isPasswordEnabled)
{ {
loginfo("%s", _("Password required")); tr_logAddInfo(_("Password required"));
} }
} }
char const* webClientDir = tr_getWebClientDir(this->session); char const* webClientDir = tr_getWebClientDir(this->session);
if (!tr_str_is_empty(webClientDir)) if (!tr_str_is_empty(webClientDir))
{ {
loginfo(_("Serving RPC and Web requests from directory '%s'"), webClientDir); tr_logAddInfo(fmt::format(_("Serving RPC and Web requests from '{path}'"), fmt::arg("path", webClientDir)));
} }
} }

View File

@ -2052,7 +2052,7 @@ static void sessionLoadTorrents(struct sessionLoadTorrentsData* const data)
if (n != 0) if (n != 0)
{ {
tr_logAddInfo(fmt::format(ngettext_("Loaded {count} torrent", "Loaded {count} torrents", n), fmt::arg("count", n))); tr_logAddInfo(fmt::format(ngettext("Loaded {count} torrent", "Loaded {count} torrents", n), fmt::arg("count", n)));
} }
if (data->setmeCount != nullptr) if (data->setmeCount != nullptr)

View File

@ -11,6 +11,8 @@
#include <event2/buffer.h> #include <event2/buffer.h>
#include <fmt/core.h>
#include "transmission.h" #include "transmission.h"
#include "crypto-utils.h" /* tr_sha1() */ #include "crypto-utils.h" /* tr_sha1() */
@ -311,7 +313,7 @@ static void onHaveAllMetainfo(tr_torrent* tor, tr_incomplete_metadata* m)
m->piecesNeededCount = n; m->piecesNeededCount = n;
char const* const msg = error != nullptr && error->message != nullptr ? error->message : "unknown error"; char const* const msg = error != nullptr && error->message != nullptr ? error->message : "unknown error";
logdbg(tor, "metadata error: %s. (trying again; %d pieces left)", msg, n); logdbg(tor, fmt::format("metadata error: {}. (trying again; {} pieces left)", msg, n));
tr_error_clear(&error); tr_error_clear(&error);
} }
} }

View File

@ -28,6 +28,8 @@
#include <event2/util.h> /* evutil_vsnprintf() */ #include <event2/util.h> /* evutil_vsnprintf() */
#include <fmt/core.h>
#include "transmission.h" #include "transmission.h"
#include "announcer.h" #include "announcer.h"
@ -476,7 +478,7 @@ void tr_torrentCheckSeedLimit(tr_torrent* tor)
/* if we're seeding and reach our seed ratio limit, stop the torrent */ /* if we're seeding and reach our seed ratio limit, stop the torrent */
if (tr_torrentIsSeedRatioDone(tor)) if (tr_torrentIsSeedRatioDone(tor))
{ {
loginfo(tor, "%s", "Seed ratio reached; pausing torrent"); loginfo(tor, "Seed ratio reached; pausing torrent");
tor->isStopping = true; tor->isStopping = true;
@ -489,7 +491,7 @@ void tr_torrentCheckSeedLimit(tr_torrent* tor)
/* if we're seeding and reach our inactivity limit, stop the torrent */ /* if we're seeding and reach our inactivity limit, stop the torrent */
else if (tr_torrentIsSeedIdleLimitDone(tor)) else if (tr_torrentIsSeedIdleLimitDone(tor))
{ {
loginfo(tor, "%s", "Seeding idle limit reached; pausing torrent"); loginfo(tor, "Seeding idle limit reached; pausing torrent");
tor->isStopping = true; tor->isStopping = true;
tor->finishedSeedingByIdle = true; tor->finishedSeedingByIdle = true;
@ -620,7 +622,7 @@ static bool setLocalErrorIfFilesDisappeared(tr_torrent* tor)
if (disappeared) if (disappeared)
{ {
logtrace(tor, "%s", "[LAZY] uh oh, the files disappeared"); logtrace(tor, "[LAZY] uh oh, the files disappeared");
tor->setLocalError(_( tor->setLocalError(_(
"No data found! Ensure your drives are connected or use \"Set Location\". To re-download, remove the torrent and re-add it.")); "No data found! Ensure your drives are connected or use \"Set Location\". To re-download, remove the torrent and re-add it."));
} }
@ -1401,7 +1403,7 @@ static void torrentStart(tr_torrent* tor, bool bypass_queue)
/* allow finished torrents to be resumed */ /* allow finished torrents to be resumed */
if (tr_torrentIsSeedRatioDone(tor)) if (tr_torrentIsSeedRatioDone(tor))
{ {
loginfo(tor, "%s", _("Restarted manually -- disabling its seed ratio")); loginfo(tor, _("Restarted manually -- disabling its seed ratio"));
tr_torrentSetRatioMode(tor, TR_RATIOLIMIT_UNLIMITED); tr_torrentSetRatioMode(tor, TR_RATIOLIMIT_UNLIMITED);
} }
@ -1535,7 +1537,7 @@ static void stopTorrent(tr_torrent* const tor)
if (tor->magnetVerify) if (tor->magnetVerify)
{ {
tor->magnetVerify = false; tor->magnetVerify = false;
logtrace(tor, "%s", "Magnet Verify"); logtrace(tor, "Magnet Verify");
refreshCurrentDir(tor); refreshCurrentDir(tor);
tr_torrentVerify(tor); tr_torrentVerify(tor);
@ -1568,7 +1570,7 @@ static void closeTorrent(tr_torrent* const tor)
if (!tor->session->isClosing()) if (!tor->session->isClosing())
{ {
loginfo(tor, "%s", _("Removing torrent")); loginfo(tor, _("Removing torrent"));
} }
tor->magnetVerify = false; tor->magnetVerify = false;
@ -1650,13 +1652,13 @@ static char const* getCompletionString(int type)
"Complete" means we've downloaded every file in the torrent. "Complete" means we've downloaded every file in the torrent.
"Done" means we're done downloading the files we wanted, but NOT all "Done" means we're done downloading the files we wanted, but NOT all
that exist */ that exist */
return _("Done"); return "Done";
case TR_SEED: case TR_SEED:
return _("Complete"); return "Complete";
default: default:
return _("Incomplete"); return "Incomplete";
} }
} }
@ -1778,13 +1780,19 @@ static void torrentCallScript(tr_torrent const* tor, char const* script)
{ "TR_TORRENT_TRACKERS"sv, trackers_str }, { "TR_TORRENT_TRACKERS"sv, trackers_str },
}; };
loginfo(tor, "Calling script \"%s\"", script); loginfo(tor, fmt::format(_("Calling script '{path}'"), script));
tr_error* error = nullptr; tr_error* error = nullptr;
if (!tr_spawn_async(std::data(cmd), env, TR_IF_WIN32("\\", "/"), &error)) if (!tr_spawn_async(std::data(cmd), env, TR_IF_WIN32("\\", "/"), &error))
{ {
logwarn(tor, "Error executing script \"%s\" (%d): %s", script, error->code, error->message); logwarn(
tor,
fmt::format(
_("Couldn't call script '{path}': {errmsg} ({errcode})"),
fmt::arg("path", script),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error); tr_error_free(error);
} }
} }
@ -1805,9 +1813,10 @@ void tr_torrent::recheckCompleteness()
{ {
logtrace( logtrace(
this, this,
_("State changed from \"%1$s\" to \"%2$s\""), fmt::format(
getCompletionString(this->completeness), "State changed from {} to {}",
getCompletionString(completeness)); getCompletionString(this->completeness),
getCompletionString(completeness)));
} }
this->completeness = new_completeness; this->completeness = new_completeness;
@ -2350,10 +2359,7 @@ static void setLocationImpl(struct LocationData* const data)
logtrace( logtrace(
tor, tor,
"Moving \"%s\" location from currentDir \"%s\" to \"%s\"", fmt::format("Moving '{}' location from currentDir '{}' to '{}'", tor->name(), tor->currentDir().sv(), location));
tr_torrentName(tor),
tor->currentDir().c_str(),
location.c_str());
tr_sys_dir_create(location.c_str(), TR_SYS_DIR_CREATE_PARENTS, 0777, nullptr); tr_sys_dir_create(location.c_str(), TR_SYS_DIR_CREATE_PARENTS, 0777, nullptr);
@ -2376,18 +2382,25 @@ static void setLocationImpl(struct LocationData* const data)
auto const oldpath = tr_strvPath(oldbase, sub); auto const oldpath = tr_strvPath(oldbase, sub);
auto const newpath = tr_strvPath(location, sub); auto const newpath = tr_strvPath(location, sub);
logtrace(tor, "Found file #%d: %s", (int)i, oldpath.c_str()); logtrace(tor, fmt::format("Found file #{}: {}", i, oldpath));
if (do_move && !tr_sys_path_is_same(oldpath.c_str(), newpath.c_str(), nullptr)) if (do_move && !tr_sys_path_is_same(oldpath.c_str(), newpath.c_str(), nullptr))
{ {
tr_error* error = nullptr; tr_error* error = nullptr;
logtrace(tor, "moving \"%s\" to \"%s\"", oldpath.c_str(), newpath.c_str()); logtrace(tor, fmt::format("moving '{}' to '{}'", oldpath, newpath));
if (!tr_moveFile(oldpath.c_str(), newpath.c_str(), &error)) if (!tr_moveFile(oldpath.c_str(), newpath.c_str(), &error))
{ {
err = true; err = true;
logerr(tor, "error moving \"%s\" to \"%s\": %s", oldpath.c_str(), newpath.c_str(), error->message); logerr(
tor,
fmt::format(
_("Couldn't move '{oldpath}' to '{path}': {errmsg} ({errcode})"),
fmt::arg("oldpath", oldpath),
fmt::arg("path", newpath),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error); tr_error_free(error);
} }
} }
@ -2526,7 +2539,14 @@ static void tr_torrentFileCompleted(tr_torrent* tor, tr_file_index_t i)
if (!tr_sys_path_rename(oldpath.c_str(), newpath.c_str(), &error)) if (!tr_sys_path_rename(oldpath.c_str(), newpath.c_str(), &error))
{ {
logerr(tor, "Error moving \"%s\" to \"%s\": %s", oldpath.c_str(), newpath.c_str(), error->message); logerr(
tor,
fmt::format(
_("Couldn't move '{oldpath}' to '{path}': {errmsg} ({errcode})"),
fmt::arg("oldpath", oldpath),
fmt::arg("path", newpath),
fmt::arg("errmsg", error->message),
fmt::arg("errcode", error->code)));
tr_error_free(error); tr_error_free(error);
} }
} }
@ -2573,7 +2593,7 @@ void tr_torrentGotBlock(tr_torrent* tor, tr_block_index_t block)
else else
{ {
uint32_t const n = tor->pieceSize(piece); uint32_t const n = tor->pieceSize(piece);
logdbg(tor, _("Piece %" PRIu32 ", which was just downloaded, failed its checksum test"), piece); logdbg(tor, fmt::format("Piece {}, which was just downloaded, failed its checksum test", piece));
tor->corruptCur += n; tor->corruptCur += n;
tor->downloadedCur -= std::min(tor->downloadedCur, uint64_t{ n }); tor->downloadedCur -= std::min(tor->downloadedCur, uint64_t{ n });
tr_peerMgrGotBadPiece(tor, piece); tr_peerMgrGotBadPiece(tor, piece);

View File

@ -2,6 +2,7 @@
// It may be used under the MIT (SPDX: MIT) license. // It may be used under the MIT (SPDX: MIT) license.
// License text can be found in the licenses/ folder. // License text can be found in the licenses/ folder.
#include <cstdint>
#include <cstring> /* memcmp(), memcpy(), memset() */ #include <cstring> /* memcmp(), memcpy(), memset() */
#include <cstdlib> /* malloc(), free() */ #include <cstdlib> /* malloc(), free() */
@ -13,7 +14,7 @@
#include <event2/event.h> #include <event2/event.h>
#include <cstdint> #include <fmt/core.h>
#include "transmission.h" #include "transmission.h"
#include "log.h" #include "log.h"
@ -23,6 +24,7 @@
#include "tr-dht.h" #include "tr-dht.h"
#include "tr-utp.h" #include "tr-utp.h"
#include "tr-udp.h" #include "tr-udp.h"
#include "utils.h"
#define logwarn(...) tr_logAddNamed(TR_LOG_WARN, "udp", __VA_ARGS__) #define logwarn(...) tr_logAddNamed(TR_LOG_WARN, "udp", __VA_ARGS__)
#define loginfo(...) tr_logAddNamed(TR_LOG_INFO, "udp", __VA_ARGS__) #define loginfo(...) tr_logAddNamed(TR_LOG_INFO, "udp", __VA_ARGS__)
@ -48,7 +50,7 @@ static void set_socket_buffers(tr_socket_t fd, bool large)
if (rc < 0) if (rc < 0)
{ {
logdbg("Failed to set receive buffer: %s", tr_net_strerror(sockerrno).c_str()); logdbg(fmt::format("Failed to set receive buffer: {}", tr_net_strerror(sockerrno)));
} }
size = large ? SEND_BUFFER_SIZE : SMALL_BUFFER_SIZE; size = large ? SEND_BUFFER_SIZE : SMALL_BUFFER_SIZE;
@ -56,7 +58,7 @@ static void set_socket_buffers(tr_socket_t fd, bool large)
if (rc < 0) if (rc < 0)
{ {
logdbg("Failed to set send buffer: %s", tr_net_strerror(sockerrno).c_str()); logdbg(fmt::format("Failed to set send buffer: {}", tr_net_strerror(sockerrno)));
} }
if (large) if (large)
@ -77,17 +79,17 @@ static void set_socket_buffers(tr_socket_t fd, bool large)
if (rbuf < RECV_BUFFER_SIZE) if (rbuf < RECV_BUFFER_SIZE)
{ {
loginfo("Failed to set receive buffer: requested %d, got %d", RECV_BUFFER_SIZE, rbuf); logdbg(fmt::format("Failed to set receive buffer: requested {}, got {}", RECV_BUFFER_SIZE, rbuf));
#ifdef __linux__ #ifdef __linux__
loginfo("Please add the line \"net.core.rmem_max = %d\" to /etc/sysctl.conf", RECV_BUFFER_SIZE); logdbg(fmt::format("Please add the line 'net.core.rmem_max = {}' to /etc/sysctl.conf", RECV_BUFFER_SIZE));
#endif #endif
} }
if (sbuf < SEND_BUFFER_SIZE) if (sbuf < SEND_BUFFER_SIZE)
{ {
loginfo("Failed to set send buffer: requested %d, got %d", SEND_BUFFER_SIZE, sbuf); logdbg(fmt::format("Failed to set send buffer: requested {}, got {}", SEND_BUFFER_SIZE, sbuf));
#ifdef __linux__ #ifdef __linux__
loginfo("Please add the line \"net.core.wmem_max = %d\" to /etc/sysctl.conf", SEND_BUFFER_SIZE); logdbg(fmt::format("Please add the line 'net.core.wmem_max = {}' to /etc/sysctl.conf", SEND_BUFFER_SIZE));
#endif #endif
} }
} }
@ -205,7 +207,7 @@ static void rebind_ipv6(tr_session* ss, bool force)
FAIL: FAIL:
/* Something went wrong. It's difficult to recover, so let's simply /* Something went wrong. It's difficult to recover, so let's simply
set things up so that we try again next time. */ set things up so that we try again next time. */
logwarn("Couldn't rebind IPv6 socket"); logwarn(_("Couldn't rebind IPv6 socket"));
if (s != TR_BAD_SOCKET) if (s != TR_BAD_SOCKET)
{ {
@ -232,7 +234,7 @@ static void event_callback(evutil_socket_t s, [[maybe_unused]] short type, void*
int rc = recvfrom(s, reinterpret_cast<char*>(buf), 4096 - 1, 0, (struct sockaddr*)&from, &fromlen); int rc = recvfrom(s, reinterpret_cast<char*>(buf), 4096 - 1, 0, (struct sockaddr*)&from, &fromlen);
/* Since most packets we receive here are µTP, make quick inline /* Since most packets we receive here are µTP, make quick inline
checks for the other protocols. The logic is as follows: checks for the other protocols. The logic is as follows:
- all DHT packets start with 'd' - all DHT packets start with 'd'
- all UDP tracker packets start with a 32-bit (!) "action", which - all UDP tracker packets start with a 32-bit (!) "action", which
is between 0 and 3 is between 0 and 3
@ -284,7 +286,7 @@ void tr_udpInit(tr_session* ss)
if (ss->udp_socket == TR_BAD_SOCKET) if (ss->udp_socket == TR_BAD_SOCKET)
{ {
logwarn("Couldn't create IPv4 socket"); logwarn(_("Couldn't create IPv4 socket"));
} }
else else
{ {
@ -303,7 +305,7 @@ void tr_udpInit(tr_session* ss)
if (rc == -1) if (rc == -1)
{ {
logwarn("Couldn't bind IPv4 socket"); logwarn(_("Couldn't bind IPv4 socket"));
tr_netCloseSocket(ss->udp_socket); tr_netCloseSocket(ss->udp_socket);
ss->udp_socket = TR_BAD_SOCKET; ss->udp_socket = TR_BAD_SOCKET;
} }
@ -313,7 +315,7 @@ void tr_udpInit(tr_session* ss)
if (ss->udp_event == nullptr) if (ss->udp_event == nullptr)
{ {
logwarn("Couldn't allocate IPv4 event"); logwarn(_("Couldn't allocate IPv4 event"));
} }
} }
} }
@ -331,7 +333,7 @@ void tr_udpInit(tr_session* ss)
if (ss->udp6_event == nullptr) if (ss->udp6_event == nullptr)
{ {
logwarn("Couldn't allocate IPv6 event"); logwarn(_("Couldn't allocate IPv6 event"));
} }
} }

View File

@ -6,6 +6,7 @@
#include <cerrno> #include <cerrno>
#include <future> #include <future>
#include <mutex> #include <mutex>
#include <string_view>
#include <thread> #include <thread>
#include <fmt/core.h> #include <fmt/core.h>
@ -29,19 +30,18 @@
namespace namespace
{ {
char constexpr Key[] = "Port Forwarding (UPnP)";
#undef tr_logAddError #undef tr_logAddError
#undef tr_logAddWarn #undef tr_logAddWarn
#undef tr_logAddInfo #undef tr_logAddInfo
#undef tr_logAddDebug #undef tr_logAddDebug
#undef tr_logAddTrace #undef tr_logAddTrace
#define tr_logAddError(...) tr_logAddNamedError(Key, __VA_ARGS__) auto constexpr LogName = std::string_view{ "Port Forwarding (UPnP)" };
#define tr_logAddWarn(...) tr_logAddNamedWarn(Key, __VA_ARGS__) #define tr_logAddError(...) tr_logAddNamedError(LogName, __VA_ARGS__)
#define tr_logAddInfo(...) tr_logAddNamedInfo(Key, __VA_ARGS__) #define tr_logAddWarn(...) tr_logAddNamedWarn(LogName, __VA_ARGS__)
#define tr_logAddDebug(...) tr_logAddNamedDebug(Key, __VA_ARGS__) #define tr_logAddInfo(...) tr_logAddNamedInfo(LogName, __VA_ARGS__)
#define tr_logAddTrace(...) tr_logAddNamedTrace(Key, __VA_ARGS__) #define tr_logAddDebug(...) tr_logAddNamedDebug(LogName, __VA_ARGS__)
#define tr_logAddTrace(...) tr_logAddNamedTrace(LogName, __VA_ARGS__)
enum class UpnpState enum class UpnpState
{ {

View File

@ -44,13 +44,8 @@ char const* tr_strip_positional_args(char const* fmt);
#endif #endif
#endif #endif
#if !defined(ngettext_) #if !defined(HAVE_NGETTEXT)
#if defined(HAVE_NGETTEXT) && !defined(__APPLE__) #define ngettext(singular, plural, count) ((count) == 1 ? (singular) : (plural))
#include <libintl.h>
#define ngettext_(singular, plural, count) ngettext(singular, plural, count)
#else
#define ngettext_(singular, plural, count) ((count) == 1 ? (singular) : (plural))
#endif
#endif #endif
/* #define DISABLE_GETTEXT */ /* #define DISABLE_GETTEXT */
@ -61,9 +56,9 @@ char const* tr_strip_positional_args(char const* fmt);
#endif #endif
#ifdef DISABLE_GETTEXT #ifdef DISABLE_GETTEXT
#undef _ #undef _
#undef ngettext_ #undef ngettext
#define _(a) tr_strip_positional_args(a) #define _(a) tr_strip_positional_args(a)
#define ngettext_(singular, plural, count) tr_strip_positional_args((count) == 1 ? (singular) : (plural)) #define ngettext(singular, plural, count) tr_strip_positional_args((count) == 1 ? (singular) : (plural))
#endif #endif
/**** /****

View File

@ -22,6 +22,9 @@
#include <event2/buffer.h> #include <event2/buffer.h>
#include <fmt/core.h>
#include <fmt/format.h>
#include "crypto-utils.h" #include "crypto-utils.h"
#include "log.h" #include "log.h"
#include "tr-assert.h" #include "tr-assert.h"
@ -119,9 +122,10 @@ public:
if (curl_ssl_verify) if (curl_ssl_verify)
{ {
auto const* bundle = std::empty(curl_ca_bundle) ? "none" : curl_ca_bundle.c_str(); auto const* bundle = std::empty(curl_ca_bundle) ? "none" : curl_ca_bundle.c_str();
loginfo("will verify tracker certs using envvar CURL_CA_BUNDLE: %s", bundle); loginfo(
loginfo("NB: this only works if you built against libcurl with openssl or gnutls, NOT nss"); fmt::format(_("Will verify tracker certs using envvar CURL_CA_BUNDLE: {bundle}"), fmt::arg("bundle", bundle)));
loginfo("NB: Invalid certs will appear as 'Could not connect to tracker' like many other errors"); loginfo(_("NB: this only works if you built against libcurl with openssl or gnutls, NOT nss"));
loginfo(_("NB: Invalid certs will appear as 'Could not connect to tracker' like many other errors"));
} }
if (auto const& file = mediator.cookieFile(); file) if (auto const& file = mediator.cookieFile(); file)
@ -291,7 +295,7 @@ private:
} }
evbuffer_add(task->body(), data, bytes_used); evbuffer_add(task->body(), data, bytes_used);
logtrace("wrote %zu bytes to task %p's buffer", bytes_used, (void*)task); logtrace(fmt::format("wrote {} bytes to task {}'s buffer", bytes_used, fmt::ptr(task)));
return bytes_used; return bytes_used;
} }
@ -457,7 +461,7 @@ private:
// add queued tasks // add queued tasks
for (auto* task : impl->queued_tasks) for (auto* task : impl->queued_tasks)
{ {
logtrace("adding task to curl: [%s]", task->url().c_str()); logtrace(fmt::format("adding task to curl: '{}'", task->url()));
initEasy(impl, task); initEasy(impl, task);
curl_multi_add_handle(multi.get(), task->easy()); curl_multi_add_handle(multi.get(), task->easy());
} }