From 72a67054ea9c6ef07d4aee55f45522243d60cb09 Mon Sep 17 00:00:00 2001 From: Charles Kerr Date: Tue, 15 Mar 2022 09:52:16 -0500 Subject: [PATCH] refactor: fmt part 2 (#2771) --- CMakeLists.txt | 19 +++--- gtk/Application.cc | 11 +++- gtk/FileList.cc | 9 ++- gtk/MakeDialog.cc | 22 +++++-- gtk/MessageLogWindow.cc | 73 +++++++++++------------ gtk/PrefsDialog.cc | 42 +++++++++----- gtk/Session.cc | 8 ++- gtk/Utils.cc | 6 +- libtransmission/announcer-udp.cc | 10 +++- libtransmission/announcer.cc | 6 +- libtransmission/bandwidth.cc | 9 +-- libtransmission/blocklist.cc | 9 +-- libtransmission/cache.cc | 20 +++---- libtransmission/fdlimit.cc | 4 +- libtransmission/net.cc | 82 +++++++++++++++----------- libtransmission/port-forwarding.cc | 7 ++- libtransmission/rpc-server.cc | 93 ++++++++++++++++++------------ libtransmission/session.cc | 2 +- libtransmission/torrent-magnet.cc | 4 +- libtransmission/torrent.cc | 66 +++++++++++++-------- libtransmission/tr-udp.cc | 28 ++++----- libtransmission/upnp.cc | 14 ++--- libtransmission/utils.h | 13 ++--- libtransmission/web.cc | 14 +++-- 24 files changed, 338 insertions(+), 233 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c11126340..6c5ade1b0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -542,6 +542,14 @@ set(NEEDED_HEADERS xlocale.h) 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) endif() @@ -562,12 +570,14 @@ set(NEEDED_FUNCTIONS fallocate64 flock getmntent + gettext gmtime_r gmtime_s htonll localtime_r localtime_s mkdtemp + ngettext ntohll posix_fadvise posix_fallocate @@ -601,15 +611,6 @@ 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) if(HAVE_LIBM) set(LIBM_LIBRARY m) diff --git a/gtk/Application.cc b/gtk/Application.cc index f8cc011f6..e795d20b1 100644 --- a/gtk/Application.cc +++ b/gtk/Application.cc @@ -14,6 +14,8 @@ #include #include +#include + #include #include #include @@ -344,7 +346,12 @@ void register_magnet_link_handler() } 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); auto* top_label = Gtk::make_managed(); - top_label->set_markup(_("Closing Connections")); + top_label->set_markup(fmt::format("{}", _("Closing Connections…"))); top_label->set_halign(Gtk::ALIGN_START); top_label->set_valign(Gtk::ALIGN_CENTER); p->attach(*top_label, 1, 0, 1, 1); diff --git a/gtk/FileList.cc b/gtk/FileList.cc index 5f8c55212..52d1457cc 100644 --- a/gtk/FileList.cc +++ b/gtk/FileList.cc @@ -11,6 +11,8 @@ #include #include +#include + #include #include @@ -741,7 +743,12 @@ bool FileList::Impl::on_rename_done_idle(Glib::ustring const& path_string, Glib: { Gtk::MessageDialog w( *static_cast(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, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, diff --git a/gtk/MakeDialog.cc b/gtk/MakeDialog.cc index 0b926074b..f44ec2b50 100644 --- a/gtk/MakeDialog.cc +++ b/gtk/MakeDialog.cc @@ -9,6 +9,8 @@ #include #include +#include + #include #include #include /* tr_formatter_mem_B() */ @@ -121,15 +123,23 @@ bool MakeProgressDialog::onProgressDialogRefresh() } 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) { - 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) { - 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 { @@ -146,7 +156,9 @@ bool MakeProgressDialog::onProgressDialogRefresh() else { /* 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); @@ -468,7 +480,7 @@ MakeDialog::Impl::Impl(MakeDialog& dialog, Glib::RefPtr const& core) t->add_row_w(row, *file_radio_, *file_chooser_); pieces_lb_ = Gtk::make_managed(); - pieces_lb_->set_markup(_("No source selected")); + pieces_lb_->set_markup(fmt::format("{}", _("No source selected"))); t->add_row(row, {}, *pieces_lb_); t->add_section_divider(row); diff --git a/gtk/MessageLogWindow.cc b/gtk/MessageLogWindow.cc index 624f78289..4eeb51e7f 100644 --- a/gtk/MessageLogWindow.cc +++ b/gtk/MessageLogWindow.cc @@ -5,10 +5,13 @@ #include #include +#include #include #include +#include + #include #include @@ -59,6 +62,7 @@ private: void scroll_to_bottom(); void level_combo_changed_cb(Gtk::ComboBox* combo_box); + Gtk::ComboBox* level_combo_new() const; bool is_pinned_to_new() const; bool isRowVisible(Gtk::TreeModel::const_iterator const& iter) const; @@ -74,6 +78,7 @@ private: tr_log_level maxLevel_ = TR_LOG_INFO; bool isPaused_ = false; sigc::connection refresh_tag_; + std::map const level_names_; }; namespace @@ -133,6 +138,18 @@ void MessageLogWindow::Impl::scroll_to_bottom() ***** ****/ +Gtk::ComboBox* MessageLogWindow::Impl::level_combo_new() const +{ + auto items = std::vector>{}; + 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) { auto const level = static_cast(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) { + auto const errcode = errno; auto w = std::make_shared( 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, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE); @@ -180,39 +202,17 @@ void MessageLogWindow::Impl::doSave(Gtk::Window& parent, Glib::ustring const& fi { for (auto const& row : store_->children()) { - char const* levelStr; auto const* const node = row.get_value(message_log_cols.tr_msg); - auto const date = gtr_asctime(node->when); - switch (node->level) - { - 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; - } + auto const it = level_names_.find(node->level); + auto const* const level_str = it != std::end(level_names_) ? it->second : "???"; fprintf( fp, "%s\t%s\t%s\t%s\n", date.c_str(), - levelStr, + level_str, node->name != nullptr ? node->name : "", node->message != nullptr ? node->message : ""); } @@ -420,19 +420,6 @@ bool MessageLogWindow::Impl::onRefresh() 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 /** @@ -456,6 +443,12 @@ MessageLogWindow::~MessageLogWindow() = default; MessageLogWindow::Impl::Impl(MessageLogWindow& window, Glib::RefPtr const& core) : window_(window) , 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_default_size(560, 350); @@ -516,7 +509,7 @@ MessageLogWindow::Impl::Impl(MessageLogWindow& window, Glib::RefPtr con } { - auto* w = debug_level_combo_new(); + auto* w = level_combo_new(); w->signal_changed().connect([this, w]() { level_combo_changed_cb(w); }); auto* item = Gtk::make_managed(); item->add(*w); diff --git a/gtk/PrefsDialog.cc b/gtk/PrefsDialog.cc index dc994e6b9..9b75f62ad 100644 --- a/gtk/PrefsDialog.cc +++ b/gtk/PrefsDialog.cc @@ -10,6 +10,8 @@ #include #include +#include + #include #include #include @@ -410,8 +412,10 @@ struct blocklist_data void updateBlocklistText(Gtk::Label* w, Glib::RefPtr const& core) { int const n = tr_blocklistGetRuleCount(core->get_session()); - w->set_markup( - gtr_sprintf("%s", gtr_sprintf(ngettext("Blocklist contains %'d rule", "Blocklist contains %'d rules", n), n))); + auto const msg = fmt::format( + ngettext("Blocklist has {count} entry", "Blocklist has {count} entries", n), + fmt::arg("count", n)); + w->set_markup(gtr_sprintf("%s", msg.c_str())); } /* prefs dialog is being destroyed, so stop listening to blocklist updates */ @@ -436,10 +440,14 @@ void onBlocklistUpdated(Glib::RefPtr const& core, int n, blocklist_data { bool const success = n >= 0; 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->updateBlocklistDialog->set_message(success ? _("Update succeeded!") : _("Unable to update."), true); - data->updateBlocklistDialog->set_secondary_text( - gtr_sprintf(ngettext("Blocklist has %'d rule.", "Blocklist has %'d rules.", count), count)); + data->updateBlocklistDialog->set_message( + fmt::format("{}", success ? _("Blocklist updated!") : _("Couldn't update blocklist")), + true); + data->updateBlocklistDialog->set_secondary_text(msg); updateBlocklistText(data->label, core); } @@ -841,19 +849,27 @@ Gtk::ComboBox* new_time_combo(Glib::RefPtr const& core, tr_quark const 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 const& core, tr_quark const key) { auto* w = gtr_combo_box_new_enum({ { _("Every Day"), TR_SCHED_ALL }, { _("Weekdays"), TR_SCHED_WEEKDAY }, { _("Weekends"), TR_SCHED_WEEKEND }, - { _("Sunday"), TR_SCHED_SUN }, - { _("Monday"), TR_SCHED_MON }, - { _("Tuesday"), TR_SCHED_TUES }, - { _("Wednesday"), TR_SCHED_WED }, - { _("Thursday"), TR_SCHED_THURS }, - { _("Friday"), TR_SCHED_FRI }, - { _("Saturday"), TR_SCHED_SAT }, + { get_weekday_string(Glib::Date::MONDAY), TR_SCHED_MON }, + { get_weekday_string(Glib::Date::TUESDAY), TR_SCHED_TUES }, + { get_weekday_string(Glib::Date::WEDNESDAY), TR_SCHED_WED }, + { get_weekday_string(Glib::Date::THURSDAY), TR_SCHED_THURS }, + { get_weekday_string(Glib::Date::FRIDAY), TR_SCHED_FRI }, + { get_weekday_string(Glib::Date::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)); w->signal_changed().connect([w, key, core]() { onIntComboChanged(w, key, core); }); @@ -999,7 +1015,7 @@ void onPortTest(std::shared_ptr const& data) { data->portButton->set_sensitive(false); data->portSpin->set_sensitive(false); - data->portLabel->set_markup(_("Testing TCP port…")); + data->portLabel->set_markup(fmt::format("{}", _("Testing TCP port…"))); if (!data->portTag.connected()) { diff --git a/gtk/Session.cc b/gtk/Session.cc index 36f5c6bc7..694452da8 100644 --- a/gtk/Session.cc +++ b/gtk/Session.cc @@ -615,7 +615,13 @@ void rename_torrent(Glib::RefPtr const& file) } 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()); } } } diff --git a/gtk/Utils.cc b/gtk/Utils.cc index 42f7e61a6..076a2005e 100644 --- a/gtk/Utils.cc +++ b/gtk/Utils.cc @@ -12,6 +12,8 @@ #include /* g_file_trash() */ #include +#include + #include /* TR_RATIO_NA, TR_RATIO_INF */ #include @@ -164,7 +166,7 @@ void gtr_add_torrent_error_dialog(Gtk::Widget& child, tr_torrent* duplicate_torr auto w = std::make_shared( *win, - _("Error opening torrent"), + _("Couldn't open torrent"), false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE); @@ -450,7 +452,7 @@ void gtr_unrecognized_url_dialog(Gtk::Widget& parent, Glib::ustring const& url) auto w = std::make_shared( *window, - _("Unrecognized URL"), + fmt::format(_("Unsupported URL: '{url}'"), fmt::arg("url", url.raw())), false /*use markup*/, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, diff --git a/libtransmission/announcer-udp.cc b/libtransmission/announcer-udp.cc index 7b3966eed..cc8c3c0a3 100644 --- a/libtransmission/announcer-udp.cc +++ b/libtransmission/announcer-udp.cc @@ -14,6 +14,8 @@ #include #include +#include + #define LIBTRANSMISSION_ANNOUNCER_MODULE #include "transmission.h" @@ -462,8 +464,12 @@ static void tau_tracker_on_dns(int errcode, struct evutil_addrinfo* addr, void* if (errcode != 0) { - auto const errmsg = tr_strvJoin("DNS Lookup failed: "sv, evutil_gai_strerror(errcode)); - logwarn(tracker->key, "%s", errmsg.c_str()); + auto const errmsg = fmt::format( + _("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()); } else diff --git a/libtransmission/announcer.cc b/libtransmission/announcer.cc index 899e039dd..f635d7f62 100644 --- a/libtransmission/announcer.cc +++ b/libtransmission/announcer.cc @@ -968,7 +968,7 @@ static void on_announce_error(tr_tier* tier, char const* err, tr_announce_event tr_logAddWarnTier( tier, fmt::format( - ngettext_( + ngettext( "Announce error: {errmsg} (Retrying in {count} second)", "Announce error: {errmsg} (Retrying in {count} seconds)", interval), @@ -1301,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(), fmt::format(_("Reducing multiscrape max to {}"), n)); + tr_logAddNamedDebug(clean_url.c_str(), fmt::format("Reducing multiscrape max to {}", n)); multiscrape_max = n; } } @@ -1427,7 +1427,7 @@ static void scrape_request_delegate( } 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))); } } diff --git a/libtransmission/bandwidth.cc b/libtransmission/bandwidth.cc index 341466d19..90632caf0 100644 --- a/libtransmission/bandwidth.cc +++ b/libtransmission/bandwidth.cc @@ -6,7 +6,10 @@ #include #include +#include + #include "transmission.h" + #include "bandwidth.h" #include "crypto-utils.h" /* tr_rand_int_weak() */ #include "log.h" @@ -14,8 +17,6 @@ #include "tr-assert.h" #include "utils.h" -#define logtrace(...) tr_logAddMessage(__FILE__, __LINE__, TR_LOG_TRACE, "", __VA_ARGS__) - /*** **** ***/ @@ -166,7 +167,7 @@ void Bandwidth::phaseOne(std::vector& peerArray, tr_direction dir) * peers from starving the others. Loop through the peers, giving each a * small chunk of bandwidth. Keep looping until we run out of bandwidth * 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(); while (n > 0) @@ -180,7 +181,7 @@ void Bandwidth::phaseOne(std::vector& peerArray, tr_direction dir) 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)) { diff --git a/libtransmission/blocklist.cc b/libtransmission/blocklist.cc index 31d777971..ac3616c9c 100644 --- a/libtransmission/blocklist.cc +++ b/libtransmission/blocklist.cc @@ -101,7 +101,7 @@ static void blocklistLoad(tr_blocklistFile* b) char* const base = tr_sys_path_basename(b->filename, nullptr); 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("count", b->ruleCount))); 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); tr_logAddInfo(fmt::format( - ngettext_( - "Blocklist '{path}' updated with {count} entry", - "Blocklist '{path}' updated with {count} entries", - ranges_count), + ngettext("Blocklist '{path}' has {count} entry", "Blocklist '{path}' has {count} entries", b->ruleCount), fmt::arg("path", base), - fmt::arg("count", ranges_count))); + fmt::arg("count", b->ruleCount))); tr_free(base); } diff --git a/libtransmission/cache.cc b/libtransmission/cache.cc index 50f05249b..6e33e04ca 100644 --- a/libtransmission/cache.cc +++ b/libtransmission/cache.cc @@ -8,6 +8,8 @@ #include +#include + #include "transmission.h" #include "cache.h" #include "inout.h" @@ -18,7 +20,7 @@ #include "trevent.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); tr_logAddNamedDebug( - CodeName, - "Maximum cache size set to %s (%d blocks)", - tr_formatter_mem_B(cache->max_bytes).c_str(), - cache->max_blocks); + LogName, + fmt::format("Maximum cache size set to {} ({} blocks)", tr_formatter_mem_B(cache->max_bytes), cache->max_blocks)); 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); - int pos = findBlockPos(cache, torrent, torrent->blockLoc(begin)); - tr_logAddNamedTrace( - CodeName, - "flushing file %d from cache to disk: blocks [%zu...%zu)", - (int)i, - (size_t)begin, - (size_t)end); + int const pos = findBlockPos(cache, torrent, torrent->blockLoc(begin)); + + tr_logAddNamedTrace(LogName, fmt::format("flushing file {} from cache to disk: blocks [{}...{})", i, begin, end)); /* flush out all the blocks in that file */ int err = 0; diff --git a/libtransmission/fdlimit.cc b/libtransmission/fdlimit.cc index cbd3fab8a..a871d15a2 100644 --- a/libtransmission/fdlimit.cc +++ b/libtransmission/fdlimit.cc @@ -219,12 +219,12 @@ static int cached_file_open( if (allocation == TR_PREALLOCATE_FULL) { success = preallocate_file_full(fd, file_size, &error); - type = _("full"); + type = "full"; } else if (allocation == TR_PREALLOCATE_SPARSE) { success = preallocate_file_sparse(fd, file_size, &error); - type = _("sparse"); + type = "sparse"; } TR_ASSERT(type != nullptr); diff --git a/libtransmission/net.cc b/libtransmission/net.cc index 921fd0760..159663bb3 100644 --- a/libtransmission/net.cc +++ b/libtransmission/net.cc @@ -21,6 +21,8 @@ #include +#include + #include #include @@ -34,21 +36,31 @@ #include "tr-assert.h" #include "tr-macros.h" #include "tr-utp.h" /* tr_utpSendTo() */ -#include "utils.h" /* tr_time(), tr_logAddDebug() */ +#include "utils.h" /* tr_time() */ #ifndef IN_MULTICAST #define IN_MULTICAST(a) (((a)&0xf0000000) == 0xe0000000) #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_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) { #ifdef _WIN32 @@ -148,10 +160,7 @@ std::string tr_address::to_string(tr_port port) const { auto addrbuf = std::array{}; tr_address_to_string_with_buf(this, std::data(addrbuf), std::size(addrbuf)); - - auto buf = std::array{}; - tr_snprintf(std::data(buf), std::size(buf), "[%s]:%u", std::data(addrbuf), ntohs(port)); - return std::data(buf); + return fmt::format("[{}]:{}", std::data(addrbuf), ntohs(port)); } 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) { - 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 } @@ -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 (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 } else { /* 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) { - 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 @@ -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(&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) { - logwarn( - _("Couldn't set source address %s on %" PRIdMAX ": %s"), - tr_address_to_string(source_addr), - (intmax_t)s, - tr_net_strerror(sockerrno).c_str()); + tr_logAddWarn(fmt::format( + _("Couldn't set source address {address} on {socket}: {errmsg} ({errcode})"), + fmt::arg("address", source_addr->to_string()), + fmt::arg("socket", s), + fmt::arg("errmsg", tr_net_strerror(sockerrno)), + fmt::arg("errcode", sockerrno))); tr_netClose(session, s); 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) { - logwarn( - _("Couldn't connect socket %" PRIdMAX " to %s, port %d (errno %d - %s)"), - (intmax_t)s, - tr_address_to_string(addr), - (int)ntohs(port), - tmperrno, - tr_net_strerror(tmperrno).c_str()); + tr_logAddWarn(fmt::format( + _("Couldn't connect socket {socket} to {address}:{port}: {errmsg} ({errcode})"), + fmt::arg("socket", s), + fmt::arg("address", addr->to_string()), + fmt::arg("port", ntohs(port)), + fmt::arg("errmsg", tr_net_strerror(tmperrno)), + fmt::arg("errcode", tmperrno))); } tr_netClose(session, s); @@ -419,7 +429,7 @@ struct tr_peer_socket tr_netOpenPeerSocket(tr_session* session, tr_address const char addrstr[TR_ADDRSTRLEN]; 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; } @@ -511,12 +521,14 @@ static tr_socket_t tr_netBindTCPImpl(tr_address const* addr, tr_port port, bool if (!suppressMsgs) { - char const* const hint = err == EADDRINUSE ? _("Is another copy of Transmission already running?") : nullptr; - - char const* const fmt = hint == nullptr ? _("Couldn't bind port %d on %s: %s") : - _("Couldn't bind port %d on %s: %s (%s)"); - - logerr(fmt, port, tr_address_to_string(addr), tr_net_strerror(err).c_str(), hint); + tr_logAddError(fmt::format( + err == EADDRINUSE ? + _("Couldn't bind port {port} on {address}: {errmsg} ({errcode}) -- Is another copy of Transmission already running?") : + _("Couldn't bind port {port} on {address}: {errmsg} ({errcode})"), + fmt::arg("address", addr->to_string()), + fmt::arg("port", port), + fmt::arg("errmsg", tr_net_strerror(err)), + fmt::arg("errcode", err))); } tr_netCloseSocket(fd); @@ -526,7 +538,7 @@ static tr_socket_t tr_netBindTCPImpl(tr_address const* addr, tr_port port, bool 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 diff --git a/libtransmission/port-forwarding.cc b/libtransmission/port-forwarding.cc index 1ac8f6401..5ef167f2f 100644 --- a/libtransmission/port-forwarding.cc +++ b/libtransmission/port-forwarding.cc @@ -8,6 +8,8 @@ #include +#include + #include "transmission.h" #include "natpmp_local.h" #include "log.h" @@ -104,7 +106,10 @@ static void natPulse(tr_shared* s, bool do_check) 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)))); } } diff --git a/libtransmission/rpc-server.cc b/libtransmission/rpc-server.cc index 3a1469f60..cadd7b0f6 100644 --- a/libtransmission/rpc-server.cc +++ b/libtransmission/rpc-server.cc @@ -12,8 +12,6 @@ #include #include -#include - #ifndef _WIN32 #include #include @@ -26,6 +24,10 @@ #include /* TODO: eventually remove this */ #include +#include + +#include + #include "transmission.h" #include "crypto-utils.h" /* tr_rand_buffer() */ @@ -49,6 +51,23 @@ 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. * Don't disable this feature unless you really know what you're doing! * http://en.wikipedia.org/wiki/Cross-site_request_forgery @@ -94,11 +113,6 @@ struct tr_rpc_address #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 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) { - logerr( - _("Unix socket path must be fewer than %zu characters (including \"%" TR_PRIsv "\" prefix)"), - TrUnixAddrStrLen - 1, - TR_PRIsv_ARG(TrUnixSocketPrefix)); + tr_logAddError(fmt::format( + _("Unix socket path must be fewer than {count} characters (including '{prefix}' prefix)"), + fmt::arg("count", TrUnixAddrStrLen - 1), + fmt::arg("prefix", TrUnixSocketPrefix))); return false; } @@ -668,9 +682,9 @@ static bool bindUnixSocket( [[maybe_unused]] int socket_mode) { #ifdef _WIN32 - logerr( - _("Unix sockets are not supported on Windows. Please change \"%s\" in your configuration file."), - tr_quark_get_string(TR_KEY_rpc_bind_address)); + tr_logAddError(fmt::format( + _("Unix sockets are not supported on Windows. Please change '{key}' in your configuration file."), + fmt::arg("key", tr_quark_get_string(TR_KEY_rpc_bind_address)))); return false; #else struct sockaddr_un addr; @@ -695,7 +709,8 @@ static bool bindUnixSocket( 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; @@ -766,18 +781,24 @@ static void startServer(tr_rpc_server* 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; } - 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 { evhttp_set_gencb(httpd, handle_request, server); 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); @@ -806,7 +827,7 @@ static void stopServer(tr_rpc_server* server) 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) @@ -865,7 +886,7 @@ tr_port tr_rpcGetPort(tr_rpc_server const* server) void tr_rpcSetUrl(tr_rpc_server* server, std::string_view 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) @@ -886,13 +907,13 @@ static auto parseWhitelist(std::string_view whitelist) if (token.find_first_of("+-"sv) != std::string_view::npos) { - logwarn( - "Adding address to whitelist: %" TR_PRIsv " (And it has a '+' or '-'! Are you using an old ACL by mistake?)", - TR_PRIsv_ARG(token)); + tr_logAddWarn(fmt::format( + _("Adding entry to whitelist: {entry} (And it has a '+' or '-'! Are you using an old ACL by mistake?)"), + fmt::arg("entry", token))); } 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) { 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) @@ -964,7 +985,7 @@ void tr_rpcSetPassword(tr_rpc_server* server, std::string_view 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) @@ -975,7 +996,7 @@ std::string const& tr_rpcGetPassword(tr_rpc_server const* server) void tr_rpcSetPasswordEnabled(tr_rpc_server* server, bool 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) @@ -1019,7 +1040,7 @@ void tr_rpcSetAntiBruteForceThreshold(tr_rpc_server* server, int badRequests) 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) @@ -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)) { - logwarn( - _("%" TR_PRIsv - " 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."), - TR_PRIsv_ARG(sv)); + tr_logAddWarn(fmt::format( + _("{key} value ({address}) must be an IPv4 or IPv6 address or a unix socket path. Using default value '0.0.0.0'"), + fmt::format("key", tr_quark_get_string(key)), + fmt::format("address", sv))); bindAddress->set_inaddr_any(); } @@ -1203,24 +1224,24 @@ tr_rpc_server::tr_rpc_server(tr_session* session_in, tr_variant* settings) if (this->isEnabled) { 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); if (this->isWhitelistEnabled) { - loginfo("%s", _("Whitelist enabled")); + tr_logAddInfo(_("Whitelist enabled")); } if (this->isPasswordEnabled) { - loginfo("%s", _("Password required")); + tr_logAddInfo(_("Password required")); } } char const* webClientDir = tr_getWebClientDir(this->session); 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))); } } diff --git a/libtransmission/session.cc b/libtransmission/session.cc index 0e6f62c8f..736d09cbe 100644 --- a/libtransmission/session.cc +++ b/libtransmission/session.cc @@ -2052,7 +2052,7 @@ static void sessionLoadTorrents(struct sessionLoadTorrentsData* const data) 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) diff --git a/libtransmission/torrent-magnet.cc b/libtransmission/torrent-magnet.cc index 7ebb41284..9c58f00d8 100644 --- a/libtransmission/torrent-magnet.cc +++ b/libtransmission/torrent-magnet.cc @@ -11,6 +11,8 @@ #include +#include + #include "transmission.h" #include "crypto-utils.h" /* tr_sha1() */ @@ -311,7 +313,7 @@ static void onHaveAllMetainfo(tr_torrent* tor, tr_incomplete_metadata* m) m->piecesNeededCount = n; 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); } } diff --git a/libtransmission/torrent.cc b/libtransmission/torrent.cc index 6b02dc437..d68a33528 100644 --- a/libtransmission/torrent.cc +++ b/libtransmission/torrent.cc @@ -28,6 +28,8 @@ #include /* evutil_vsnprintf() */ +#include + #include "transmission.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 (tr_torrentIsSeedRatioDone(tor)) { - loginfo(tor, "%s", "Seed ratio reached; pausing torrent"); + loginfo(tor, "Seed ratio reached; pausing torrent"); 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 */ 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->finishedSeedingByIdle = true; @@ -620,7 +622,7 @@ static bool setLocalErrorIfFilesDisappeared(tr_torrent* tor) if (disappeared) { - logtrace(tor, "%s", "[LAZY] uh oh, the files disappeared"); + logtrace(tor, "[LAZY] uh oh, the files disappeared"); tor->setLocalError(_( "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 */ 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); } @@ -1535,7 +1537,7 @@ static void stopTorrent(tr_torrent* const tor) if (tor->magnetVerify) { tor->magnetVerify = false; - logtrace(tor, "%s", "Magnet Verify"); + logtrace(tor, "Magnet Verify"); refreshCurrentDir(tor); tr_torrentVerify(tor); @@ -1568,7 +1570,7 @@ static void closeTorrent(tr_torrent* const tor) if (!tor->session->isClosing()) { - loginfo(tor, "%s", _("Removing torrent")); + loginfo(tor, _("Removing torrent")); } tor->magnetVerify = false; @@ -1650,13 +1652,13 @@ static char const* getCompletionString(int type) "Complete" means we've downloaded every file in the torrent. "Done" means we're done downloading the files we wanted, but NOT all that exist */ - return _("Done"); + return "Done"; case TR_SEED: - return _("Complete"); + return "Complete"; 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 }, }; - loginfo(tor, "Calling script \"%s\"", script); + loginfo(tor, fmt::format(_("Calling script '{path}'"), script)); tr_error* error = nullptr; 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); } } @@ -1805,9 +1813,10 @@ void tr_torrent::recheckCompleteness() { logtrace( this, - _("State changed from \"%1$s\" to \"%2$s\""), - getCompletionString(this->completeness), - getCompletionString(completeness)); + fmt::format( + "State changed from {} to {}", + getCompletionString(this->completeness), + getCompletionString(completeness))); } this->completeness = new_completeness; @@ -2350,10 +2359,7 @@ static void setLocationImpl(struct LocationData* const data) logtrace( tor, - "Moving \"%s\" location from currentDir \"%s\" to \"%s\"", - tr_torrentName(tor), - tor->currentDir().c_str(), - location.c_str()); + fmt::format("Moving '{}' location from currentDir '{}' to '{}'", tor->name(), tor->currentDir().sv(), location)); 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 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)) { 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)) { 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); } } @@ -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)) { - 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); } } @@ -2573,7 +2593,7 @@ void tr_torrentGotBlock(tr_torrent* tor, tr_block_index_t block) else { 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->downloadedCur -= std::min(tor->downloadedCur, uint64_t{ n }); tr_peerMgrGotBadPiece(tor, piece); diff --git a/libtransmission/tr-udp.cc b/libtransmission/tr-udp.cc index 4b0e7030c..29675a72b 100644 --- a/libtransmission/tr-udp.cc +++ b/libtransmission/tr-udp.cc @@ -2,6 +2,7 @@ // It may be used under the MIT (SPDX: MIT) license. // License text can be found in the licenses/ folder. +#include #include /* memcmp(), memcpy(), memset() */ #include /* malloc(), free() */ @@ -13,7 +14,7 @@ #include -#include +#include #include "transmission.h" #include "log.h" @@ -23,6 +24,7 @@ #include "tr-dht.h" #include "tr-utp.h" #include "tr-udp.h" +#include "utils.h" #define logwarn(...) tr_logAddNamed(TR_LOG_WARN, "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) { - 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; @@ -56,7 +58,7 @@ static void set_socket_buffers(tr_socket_t fd, bool large) 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) @@ -77,17 +79,17 @@ static void set_socket_buffers(tr_socket_t fd, bool large) 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__ - 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 } 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__ - 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 } } @@ -205,7 +207,7 @@ static void rebind_ipv6(tr_session* ss, bool force) FAIL: /* Something went wrong. It's difficult to recover, so let's simply 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) { @@ -232,7 +234,7 @@ static void event_callback(evutil_socket_t s, [[maybe_unused]] short type, void* int rc = recvfrom(s, reinterpret_cast(buf), 4096 - 1, 0, (struct sockaddr*)&from, &fromlen); /* 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 UDP tracker packets start with a 32-bit (!) "action", which is between 0 and 3 @@ -284,7 +286,7 @@ void tr_udpInit(tr_session* ss) if (ss->udp_socket == TR_BAD_SOCKET) { - logwarn("Couldn't create IPv4 socket"); + logwarn(_("Couldn't create IPv4 socket")); } else { @@ -303,7 +305,7 @@ void tr_udpInit(tr_session* ss) if (rc == -1) { - logwarn("Couldn't bind IPv4 socket"); + logwarn(_("Couldn't bind IPv4 socket")); tr_netCloseSocket(ss->udp_socket); ss->udp_socket = TR_BAD_SOCKET; } @@ -313,7 +315,7 @@ void tr_udpInit(tr_session* ss) 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) { - logwarn("Couldn't allocate IPv6 event"); + logwarn(_("Couldn't allocate IPv6 event")); } } diff --git a/libtransmission/upnp.cc b/libtransmission/upnp.cc index 1a7806f40..30f90cfe9 100644 --- a/libtransmission/upnp.cc +++ b/libtransmission/upnp.cc @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -29,19 +30,18 @@ namespace { -char constexpr Key[] = "Port Forwarding (UPnP)"; - #undef tr_logAddError #undef tr_logAddWarn #undef tr_logAddInfo #undef tr_logAddDebug #undef tr_logAddTrace -#define tr_logAddError(...) tr_logAddNamedError(Key, __VA_ARGS__) -#define tr_logAddWarn(...) tr_logAddNamedWarn(Key, __VA_ARGS__) -#define tr_logAddInfo(...) tr_logAddNamedInfo(Key, __VA_ARGS__) -#define tr_logAddDebug(...) tr_logAddNamedDebug(Key, __VA_ARGS__) -#define tr_logAddTrace(...) tr_logAddNamedTrace(Key, __VA_ARGS__) +auto constexpr LogName = std::string_view{ "Port Forwarding (UPnP)" }; +#define tr_logAddError(...) tr_logAddNamedError(LogName, __VA_ARGS__) +#define tr_logAddWarn(...) tr_logAddNamedWarn(LogName, __VA_ARGS__) +#define tr_logAddInfo(...) tr_logAddNamedInfo(LogName, __VA_ARGS__) +#define tr_logAddDebug(...) tr_logAddNamedDebug(LogName, __VA_ARGS__) +#define tr_logAddTrace(...) tr_logAddNamedTrace(LogName, __VA_ARGS__) enum class UpnpState { diff --git a/libtransmission/utils.h b/libtransmission/utils.h index 4e867be3a..845473797 100644 --- a/libtransmission/utils.h +++ b/libtransmission/utils.h @@ -44,13 +44,8 @@ char const* tr_strip_positional_args(char const* fmt); #endif #endif -#if !defined(ngettext_) -#if defined(HAVE_NGETTEXT) && !defined(__APPLE__) -#include -#define ngettext_(singular, plural, count) ngettext(singular, plural, count) -#else -#define ngettext_(singular, plural, count) ((count) == 1 ? (singular) : (plural)) -#endif +#if !defined(HAVE_NGETTEXT) +#define ngettext(singular, plural, count) ((count) == 1 ? (singular) : (plural)) #endif /* #define DISABLE_GETTEXT */ @@ -61,9 +56,9 @@ char const* tr_strip_positional_args(char const* fmt); #endif #ifdef DISABLE_GETTEXT #undef _ -#undef ngettext_ +#undef ngettext #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 /**** diff --git a/libtransmission/web.cc b/libtransmission/web.cc index eeffa7669..32e5455b6 100644 --- a/libtransmission/web.cc +++ b/libtransmission/web.cc @@ -22,6 +22,9 @@ #include +#include +#include + #include "crypto-utils.h" #include "log.h" #include "tr-assert.h" @@ -119,9 +122,10 @@ public: if (curl_ssl_verify) { 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("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"); + loginfo( + fmt::format(_("Will verify tracker certs using envvar CURL_CA_BUNDLE: {bundle}"), fmt::arg("bundle", bundle))); + 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) @@ -291,7 +295,7 @@ private: } 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; } @@ -457,7 +461,7 @@ private: // add 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); curl_multi_add_handle(multi.get(), task->easy()); }