refactor: fmt pt 4 (#2774)

Co-authored-by: Mike Gelfand <mikedld@mikedld.com>
This commit is contained in:
Charles Kerr 2022-03-16 19:23:44 -05:00 committed by GitHub
parent 4f2472cd93
commit 54ef7341a2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 294 additions and 150 deletions

View File

@ -60,7 +60,7 @@ using namespace std::literals;
****
***/
static auto constexpr CodeName = "daemon"sv;
static auto constexpr LogName = "daemon"sv;
#undef tr_logAddError
#undef tr_logAddWarn
@ -68,11 +68,11 @@ static auto constexpr CodeName = "daemon"sv;
#undef tr_logAddDebug
#undef tr_logAddTrace
#define tr_logAddError(...) tr_logAddNamedError(CodeName, __VA_ARGS__)
#define tr_logAddWarn(...) tr_logAddNamedWarn(CodeName, __VA_ARGS__)
#define tr_logAddInfo(...) tr_logAddNamedInfo(CodeName, __VA_ARGS__)
#define tr_logAddDebug(...) tr_logAddNamedDebug(CodeName, __VA_ARGS__)
#define tr_logAddTrace(...) tr_logAddNamedTrace(CodeName, __VA_ARGS__)
#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__)
/***
****
@ -804,7 +804,7 @@ static int daemon_start(void* varg, [[maybe_unused]] bool foreground)
{
auto const error_code = errno;
tr_logAddError(fmt::format(
_("Couldn't create status event: {error} ({error_code})"),
_("Couldn't create event: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto CLEANUP;
@ -814,7 +814,7 @@ static int daemon_start(void* varg, [[maybe_unused]] bool foreground)
{
auto const error_code = errno;
tr_logAddError(fmt::format(
_("Couldn't add status event: {error} ({error_code})"),
_("Couldn't add event: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto CLEANUP;

View File

@ -1457,7 +1457,10 @@ bool gtr_inhibit_hibernation(guint32& cookie)
}
catch (Glib::Error const& e)
{
tr_logAddError(fmt::format(_("Couldn't inhibit desktop hibernation: {error}"), fmt::arg("error", e.what().raw())));
tr_logAddError(fmt::format(
_("Couldn't inhibit desktop hibernation: {error} ({error_code})"),
fmt::arg("error", e.what().raw()),
fmt::arg("error_code", e.code())));
}
return success;
@ -1482,7 +1485,10 @@ void gtr_uninhibit_hibernation(guint inhibit_cookie)
}
catch (Glib::Error const& e)
{
tr_logAddError(fmt::format(_("Couldn't inhibit desktop hibernation: {error}"), fmt::arg("error", e.what().raw())));
tr_logAddError(fmt::format(
_("Couldn't inhibit desktop hibernation: {error} ({error_code})"),
fmt::arg("error", e.what().raw()),
fmt::arg("error_code", e.code())));
}
}

View File

@ -708,7 +708,7 @@ static bool bindUnixSocket(
if (chmod(addr.sun_path, (mode_t)socket_mode) != 0)
{
tr_logAddWarn(
fmt::format(_("Could not set RPC socket mode to {mode:#o}, defaulting to 0755"), fmt::arg("mode", socket_mode)));
fmt::format(_("Couldn't set RPC socket mode to {mode:#o}, defaulting to 0755"), fmt::arg("mode", socket_mode)));
}
return evhttp_bind_listener(httpd, lev) != nullptr;

View File

@ -58,16 +58,6 @@
#include "version.h"
#include "web-utils.h"
/***
****
***/
#define logerr(tor, ...) tr_logAddNamed(TR_LOG_ERROR, tr_torrentName(tor), __VA_ARGS__)
#define logwarn(tor, ...) tr_logAddNamed(TR_LOG_WARN, tr_torrentName(tor), __VA_ARGS__)
#define loginfo(tor, ...) tr_logAddNamed(TR_LOG_INFO, tr_torrentName(tor), __VA_ARGS__)
#define logdbg(tor, ...) tr_logAddNamed(TR_LOG_DEBUG, tr_torrentName(tor), __VA_ARGS__)
#define logtrace(tor, ...) tr_logAddNamed(TR_LOG_TRACE, tr_torrentName(tor), __VA_ARGS__)
using namespace std::literals;
/***
@ -478,7 +468,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, "Seed ratio reached; pausing torrent");
tr_logAddInfoTor(tor, _("Seed ratio reached; pausing torrent"));
tor->isStopping = true;
@ -491,7 +481,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, "Seeding idle limit reached; pausing torrent");
tr_logAddInfoTor(tor, _("Seeding idle limit reached; pausing torrent"));
tor->isStopping = true;
tor->finishedSeedingByIdle = true;
@ -525,7 +515,7 @@ static void onTrackerResponse(tr_torrent* tor, tr_tracker_event const* event, vo
switch (event->messageType)
{
case TR_TRACKER_PEERS:
logtrace(tor, "Got %zu peers from tracker", size_t(std::size(event->pex)));
tr_logAddTraceTor(tor, fmt::format("Got {} peers from tracker", std::size(event->pex)));
tr_peerMgrAddPex(tor, TR_PEER_FROM_TRACKER, std::data(event->pex), std::size(event->pex));
break;
@ -538,7 +528,7 @@ static void onTrackerResponse(tr_torrent* tor, tr_tracker_event const* event, vo
break;
case TR_TRACKER_WARNING:
logwarn(tor, _("Tracker warning: \"%" TR_PRIsv "\""), TR_PRIsv_ARG(event->text));
tr_logAddWarnTor(tor, fmt::format(_("Tracker warning: '{warning}'"), fmt::arg("warning", event->text)));
tor->error = TR_STAT_TRACKER_WARNING;
tor->error_announce_url = event->announce_url;
tor->error_string = event->text;
@ -580,7 +570,7 @@ static void torrentInitFromInfoDict(tr_torrent* tor)
else
{
// lookups by obfuscated hash will fail for this torrent
logerr(tor, "error computing obfuscated info hash");
tr_logAddErrorTor(tor, _("Couldn't compute obfuscated info hash"));
tor->obfuscated_hash = tr_sha1_digest_t{};
}
@ -622,7 +612,7 @@ static bool setLocalErrorIfFilesDisappeared(tr_torrent* tor)
if (disappeared)
{
logtrace(tor, "[LAZY] uh oh, the files disappeared");
tr_logAddTraceTor(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."));
}
@ -1403,7 +1393,7 @@ static void torrentStart(tr_torrent* tor, bool bypass_queue)
/* allow finished torrents to be resumed */
if (tr_torrentIsSeedRatioDone(tor))
{
loginfo(tor, _("Restarted manually -- disabling its seed ratio"));
tr_logAddInfoTor(tor, _("Restarted manually -- disabling its seed ratio"));
tr_torrentSetRatioMode(tor, TR_RATIOLIMIT_UNLIMITED);
}
@ -1517,7 +1507,7 @@ static void stopTorrent(tr_torrent* const tor)
if (!tor->session->isClosing())
{
loginfo(tor, _("Pausing"));
tr_logAddInfoTor(tor, _("Pausing torrent"));
}
tr_verifyRemove(tor);
@ -1537,7 +1527,7 @@ static void stopTorrent(tr_torrent* const tor)
if (tor->magnetVerify)
{
tor->magnetVerify = false;
logtrace(tor, "Magnet Verify");
tr_logAddTraceTor(tor, "Magnet Verify");
refreshCurrentDir(tor);
tr_torrentVerify(tor);
@ -1570,7 +1560,7 @@ static void closeTorrent(tr_torrent* const tor)
if (!tor->session->isClosing())
{
loginfo(tor, _("Removing torrent"));
tr_logAddInfoTor(tor, _("Removing torrent"));
}
tor->magnetVerify = false;
@ -1780,13 +1770,13 @@ static void torrentCallScript(tr_torrent const* tor, char const* script)
{ "TR_TORRENT_TRACKERS"sv, trackers_str },
};
loginfo(tor, fmt::format(_("Calling script '{path}'"), script));
tr_logAddInfoTor(tor, fmt::format(_("Calling script '{path}'"), fmt::arg("path", script)));
tr_error* error = nullptr;
if (!tr_spawn_async(std::data(cmd), env, TR_IF_WIN32("\\", "/"), &error))
{
logwarn(
tr_logAddWarnTor(
tor,
fmt::format(
_("Couldn't call script '{path}': {error} ({error_code})"),
@ -1811,7 +1801,7 @@ void tr_torrent::recheckCompleteness()
if (recentChange)
{
logtrace(
tr_logAddTraceTor(
this,
fmt::format(
"State changed from {} to {}",
@ -1988,13 +1978,7 @@ bool tr_torrentReqIsValid(tr_torrent const* tor, tr_piece_index_t index, uint32_
if (err != 0)
{
logtrace(
tor,
"index %lu offset %lu length %lu err %d\n",
(unsigned long)index,
(unsigned long)offset,
(unsigned long)length,
err);
tr_logAddTraceTor(tor, fmt::format("index {} offset {} length {} err {}", index, offset, length, err));
}
return err == 0;
@ -2024,7 +2008,7 @@ tr_block_span_t tr_torGetFileBlockSpan(tr_torrent const* tor, tr_file_index_t i)
bool tr_torrent::checkPiece(tr_piece_index_t piece)
{
bool const pass = tr_ioTestPiece(this, piece);
logtrace(this, "[LAZY] tr_torrent.checkPiece tested piece %zu, pass==%d", size_t(piece), int(pass));
tr_logAddTraceTor(this, fmt::format("[LAZY] tr_torrent.checkPiece tested piece {}, pass=={}", piece, pass));
return pass;
}
@ -2357,7 +2341,7 @@ static void setLocationImpl(struct LocationData* const data)
auto const& location = data->location;
double bytesHandled = 0;
logtrace(
tr_logAddTraceTor(
tor,
fmt::format("Moving '{}' location from currentDir '{}' to '{}'", tor->name(), tor->currentDir().sv(), location));
@ -2382,18 +2366,18 @@ static void setLocationImpl(struct LocationData* const data)
auto const oldpath = tr_strvPath(oldbase, sub);
auto const newpath = tr_strvPath(location, sub);
logtrace(tor, fmt::format("Found file #{}: {}", i, oldpath));
tr_logAddTraceTor(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, fmt::format("moving '{}' to '{}'", oldpath, newpath));
tr_logAddTraceTor(tor, fmt::format("moving '{}' to '{}'", oldpath, newpath));
if (!tr_moveFile(oldpath.c_str(), newpath.c_str(), &error))
{
err = true;
logerr(
tr_logAddErrorTor(
tor,
fmt::format(
_("Couldn't move '{old_path}' to '{path}': {error} ({error_code})"),
@ -2539,7 +2523,7 @@ 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(
tr_logAddErrorTor(
tor,
fmt::format(
_("Couldn't move '{old_path}' to '{path}': {error} ({error_code})"),
@ -2593,7 +2577,7 @@ void tr_torrentGotBlock(tr_torrent* tor, tr_block_index_t block)
else
{
uint32_t const n = tor->pieceSize(piece);
logdbg(tor, fmt::format("Piece {}, which was just downloaded, failed its checksum test", piece));
tr_logAddDebugTor(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);
@ -2604,7 +2588,7 @@ void tr_torrentGotBlock(tr_torrent* tor, tr_block_index_t block)
{
uint32_t const n = tor->blockSize(block);
tor->downloadedCur -= std::min(tor->downloadedCur, uint64_t{ n });
logdbg(tor, "we have this block already...");
tr_logAddDebugTor(tor, "we have this block already...");
}
}

View File

@ -50,7 +50,7 @@ static void set_socket_buffers(tr_socket_t fd, bool large)
if (rc < 0)
{
logdbg(fmt::format("Failed to set receive buffer: {}", tr_net_strerror(sockerrno)));
logdbg(fmt::format("Couldn't set receive buffer: {}", tr_net_strerror(sockerrno)));
}
size = large ? SEND_BUFFER_SIZE : SMALL_BUFFER_SIZE;
@ -58,7 +58,7 @@ static void set_socket_buffers(tr_socket_t fd, bool large)
if (rc < 0)
{
logdbg(fmt::format("Failed to set send buffer: {}", tr_net_strerror(sockerrno)));
logdbg(fmt::format("Couldn't set send buffer: {}", tr_net_strerror(sockerrno)));
}
if (large)
@ -79,7 +79,7 @@ static void set_socket_buffers(tr_socket_t fd, bool large)
if (rbuf < RECV_BUFFER_SIZE)
{
logdbg(fmt::format("Failed to set receive buffer: requested {}, got {}", RECV_BUFFER_SIZE, rbuf));
logdbg(fmt::format("Couldn't set receive buffer: requested {}, got {}", RECV_BUFFER_SIZE, rbuf));
#ifdef __linux__
logdbg(fmt::format("Please add the line 'net.core.rmem_max = {}' to /etc/sysctl.conf", RECV_BUFFER_SIZE));
#endif
@ -87,7 +87,7 @@ static void set_socket_buffers(tr_socket_t fd, bool large)
if (sbuf < SEND_BUFFER_SIZE)
{
logdbg(fmt::format("Failed to set send buffer: requested {}, got {}", SEND_BUFFER_SIZE, sbuf));
logdbg(fmt::format("Couldn't set send buffer: requested {}, got {}", SEND_BUFFER_SIZE, sbuf));
#ifdef __linux__
logdbg(fmt::format("Please add the line 'net.core.wmem_max = {}' to /etc/sysctl.conf", SEND_BUFFER_SIZE));
#endif
@ -207,7 +207,14 @@ 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"));
auto const error_code = errno;
auto ipv6_readable = std::array<char, INET6_ADDRSTRLEN>{};
evutil_inet_ntop(AF_INET6, ipv6, std::data(ipv6_readable), std::size(ipv6_readable));
logwarn(fmt::format(
_("Couldn't rebind IPv6 socket {address}: {error} ({error_code})"),
fmt::arg("address", std::data(ipv6_readable)),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
if (s != TR_BAD_SOCKET)
{
@ -305,7 +312,12 @@ void tr_udpInit(tr_session* ss)
if (rc == -1)
{
logwarn(_("Couldn't bind IPv4 socket"));
auto const error_code = errno;
logwarn(fmt::format(
_("Couldn't bind IPv4 socket {address}: {error} ({error_code})"),
fmt::arg("address", public_addr->to_string(ss->udp_port)),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
tr_netCloseSocket(ss->udp_socket);
ss->udp_socket = TR_BAD_SOCKET;
}

View File

@ -2,39 +2,44 @@
// It may be used under the MIT (SPDX: MIT) license.
// License text can be found in the licenses/ folder.
#include <cstdint>
#include <string_view>
#include <event2/event.h>
#include <cstdint>
#include <fmt/core.h>
#include <fmt/format.h>
#include <libutp/utp.h>
#include "transmission.h"
#include "crypto-utils.h" /* tr_rand_int_weak() */
#include "log.h"
#include "net.h"
#include "session.h"
#include "crypto-utils.h" /* tr_rand_int_weak() */
#include "peer-mgr.h"
#include "peer-socket.h"
#include "session.h"
#include "tr-utp.h"
#include "utils.h"
#define logwarn(...) tr_logAddNamed(TR_LOG_WARN, "utp", __VA_ARGS__)
#define logtrace(...) tr_logAddNamed(TR_LOG_TRACE, "utp", __VA_ARGS__)
static auto constexpr LogName = std::string_view{ "utp" };
#ifndef WITH_UTP
void UTP_Close(struct UTPSocket* socket)
{
logtrace("UTP_Close(%p) was called.", socket);
tr_logAddNamedTrace(LogName, fmt::format("UTP_Close({}) was called.", fmt::ptr(socket)));
}
void UTP_RBDrained(struct UTPSocket* socket)
{
logtrace("UTP_RBDrained(%p) was called.", socket);
tr_logAddNamedTrace(LogName, fmt::format("UTP_RBDrained({}) was called.", fmt::ptr(socket)));
}
bool UTP_Write(struct UTPSocket* socket, size_t count)
{
logtrace("UTP_RBDrained(%p, %zu) was called.", socket, count);
tr_logAddNamedTrace(LogName, fmt::format("UTP_Write({}, {}) was called.", fmt::ptr(socket), count));
return false;
}
@ -95,7 +100,7 @@ static void incoming(void* vsession, struct UTPSocket* s)
if (!tr_address_from_sockaddr_storage(&addr, &port, &from_storage))
{
logwarn("Unknown socket family");
tr_logAddNamedWarn(LogName, _("Unknown socket family"));
UTP_Close(s);
return;
}

View File

@ -82,8 +82,8 @@ static void error_handler(jsonsl_t jsn, jsonsl_error_t error, jsonsl_state_st* /
auto* data = static_cast<struct json_wrapper_data*>(jsn->data);
tr_logAddError(fmt::format(
_("JSON parse failed at pos {pos} '{text:16s}': {error} ({error_code})"),
fmt::arg("pos", jsn->pos),
_("Couldn't parse JSON at position {position} '{text:16s}': {error} ({error_code})"),
fmt::arg("position", jsn->pos),
fmt::arg("text", buf),
fmt::arg("error", jsonsl_strerror(error)),
fmt::arg("error_code", error)));

View File

@ -5,10 +5,13 @@
#include <cerrno>
#include <string>
#include <string_view>
#include <unordered_set>
#include <event2/event.h>
#include <fmt/core.h>
#define LIBTRANSMISSION_WATCHDIR_MODULE
#include "transmission.h"
@ -18,13 +21,7 @@
#include "watchdir.h"
#include "watchdir-common.h"
/***
****
***/
#define log_error(...) \
(!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \
tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:generic", __VA_ARGS__))
static auto constexpr LogName = std::string_view{ "watchdir:generic" };
/***
****
@ -84,13 +81,25 @@ tr_watchdir_backend* tr_watchdir_generic_new(tr_watchdir_t handle)
->event = event_new(tr_watchdir_get_event_base(handle), -1, EV_PERSIST, &tr_watchdir_generic_on_event, handle)) ==
nullptr)
{
log_error("Failed to create event: %s", tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't create event: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto FAIL;
}
if (event_add(backend->event, &tr_watchdir_generic_interval) == -1)
{
log_error("Failed to add event: %s", tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't add event: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto FAIL;
}

View File

@ -5,6 +5,7 @@
#include <cerrno>
#include <climits> /* NAME_MAX */
#include <string_view>
#include <unistd.h> /* close() */
@ -13,6 +14,8 @@
#include <event2/bufferevent.h>
#include <event2/event.h>
#include <fmt/core.h>
#define LIBTRANSMISSION_WATCHDIR_MODULE
#include "transmission.h"
@ -22,13 +25,7 @@
#include "watchdir.h"
#include "watchdir-common.h"
/***
****
***/
#define log_error(...) \
(!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \
tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:inotify", __VA_ARGS__))
static auto constexpr LogName = std::string_view{ "watchdir:inotify" };
/***
****
@ -77,13 +74,24 @@ static void tr_watchdir_inotify_on_event(struct bufferevent* event, void* contex
{
if (nread == (size_t)-1)
{
log_error("Failed to read inotify event: %s", tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't read event: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
break;
}
if (nread != sizeof(ev))
{
log_error("Failed to read inotify event: expected %zu, got %zu bytes.", sizeof(ev), nread);
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't read event: expected {expected_size}, got {actual_size}"),
fmt::arg("expected_size", sizeof(ev)),
fmt::arg("actual_size", nread)));
break;
}
@ -100,13 +108,24 @@ static void tr_watchdir_inotify_on_event(struct bufferevent* event, void* contex
/* Consume entire name into buffer */
if ((nread = bufferevent_read(event, name, ev.len)) == (size_t)-1)
{
log_error("Failed to read inotify name: %s", tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't read filename: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
break;
}
if (nread != ev.len)
{
log_error("Failed to read inotify name: expected %" PRIu32 ", got %zu bytes.", ev.len, nread);
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't read filename: expected {expected_size}, got {actual_size}"),
fmt::arg("expected_size", sizeof(ev)),
fmt::arg("actual_size", nread)));
break;
}
@ -152,24 +171,46 @@ tr_watchdir_backend* tr_watchdir_inotify_new(tr_watchdir_t handle)
auto* const backend = tr_new0(tr_watchdir_inotify, 1);
backend->base.free_func = &tr_watchdir_inotify_free;
backend->infd = -1;
backend->inwd = -1;
if ((backend->infd = inotify_init()) == -1)
backend->infd = inotify_init();
if (backend->infd == -1)
{
log_error("Unable to inotify_init: %s", tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't watch '{path}': {error} ({error_code})"),
fmt::arg("path", path),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto FAIL;
}
if ((backend->inwd = inotify_add_watch(backend->infd, path, INOTIFY_WATCH_MASK | IN_ONLYDIR)) == -1)
backend->inwd = inotify_add_watch(backend->infd, path, INOTIFY_WATCH_MASK | IN_ONLYDIR);
if (backend->inwd == -1)
{
log_error("Failed to setup watchdir \"%s\": %s (%d)", path, tr_strerror(errno), errno);
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't watch '{path}': {error} ({error_code})"),
fmt::arg("path", path),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto FAIL;
}
if ((backend->event = bufferevent_socket_new(tr_watchdir_get_event_base(handle), backend->infd, 0)) == nullptr)
backend->event = bufferevent_socket_new(tr_watchdir_get_event_base(handle), backend->infd, 0);
if (backend->event == nullptr)
{
log_error("Failed to create event buffer: %s", tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't watch '{path}': {error} ({error_code})"),
fmt::arg("path", path),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto FAIL;
}
@ -188,7 +229,14 @@ tr_watchdir_backend* tr_watchdir_inotify_new(tr_watchdir_t handle)
handle,
nullptr) == -1)
{
log_error("Failed to perform initial scan: %s", tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedWarn(
LogName,
fmt::format(
_("Couldn't scan '{path}': {error} ({error_code})"),
fmt::arg("path", path),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
}
return BACKEND_DOWNCAST(backend);

View File

@ -5,6 +5,7 @@
#include <cerrno> /* errno */
#include <string>
#include <string_view>
#include <unordered_set>
#include <fcntl.h> /* open() */
@ -19,22 +20,18 @@
#include <event2/event.h>
#define LIBTRANSMISSION_WATCHDIR_MODULE
#include <fmt/core.h>
#define LIBTRANSMISSION_WATCHDIR_MODULE
#include "transmission.h"
#include "log.h"
#include "tr-assert.h"
#include "utils.h"
#include "watchdir.h"
#include "watchdir-common.h"
/***
****
***/
#define log_error(...) \
(!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \
tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:kqueue", __VA_ARGS__))
static auto constexpr LogName = std::string_view{ "watchdir:kqueue" };
/***
****
@ -61,13 +58,19 @@ struct tr_watchdir_kqueue
static void tr_watchdir_kqueue_on_event(evutil_socket_t /*fd*/, short /*type*/, void* context)
{
auto const handle = static_cast<tr_watchdir_t>(context);
tr_watchdir_kqueue* const backend = BACKEND_UPCAST(tr_watchdir_get_backend(handle));
auto* const backend = BACKEND_UPCAST(tr_watchdir_get_backend(handle));
struct kevent ke;
auto ts = timespec{};
if (kevent(backend->kq, nullptr, 0, &ke, 1, &ts) == -1)
{
log_error("Failed to fetch kevent: %s", tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't read event: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
return;
}
@ -112,19 +115,34 @@ tr_watchdir_backend* tr_watchdir_kqueue_new(tr_watchdir_t handle)
auto* backend = new tr_watchdir_kqueue{};
backend->base.free_func = &tr_watchdir_kqueue_free;
backend->kq = -1;
backend->dirfd = -1;
if ((backend->kq = kqueue()) == -1)
backend->kq = kqueue();
if (backend->kq == -1)
{
log_error("Failed to start kqueue");
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't watch '{path}': {error} ({error_code})"),
fmt::arg("path", path),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto fail;
}
/* Open fd for watching */
if ((backend->dirfd = open(path, O_RDONLY | O_EVTONLY)) == -1)
backend->dirfd = open(path, O_RDONLY | O_EVTONLY);
if (backend->dirfd == -1)
{
log_error("Failed to passively watch directory \"%s\": %s", path, tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't watch '{path}': {error} ({error_code})"),
fmt::arg("path", path),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto fail;
}
@ -133,7 +151,14 @@ tr_watchdir_backend* tr_watchdir_kqueue_new(tr_watchdir_t handle)
if (kevent(backend->kq, &ke, 1, nullptr, 0, nullptr) == -1)
{
log_error("Failed to set directory event filter with fd %d: %s", backend->kq, tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't watch '{path}': {error} ({error_code})"),
fmt::arg("path", path),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto fail;
}
@ -145,13 +170,25 @@ tr_watchdir_backend* tr_watchdir_kqueue_new(tr_watchdir_t handle)
&tr_watchdir_kqueue_on_event,
handle)) == nullptr)
{
log_error("Failed to create event: %s", tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't create event: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto fail;
}
if (event_add(backend->event, nullptr) == -1)
{
log_error("Failed to add event: %s", tr_strerror(errno));
auto const error_code = errno;
tr_logAddNamedError(
LogName,
fmt::format(
_("Couldn't add event: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto fail;
}

View File

@ -3,9 +3,10 @@
// or any future license endorsed by Mnemosyne LLC.
// License text can be found in the licenses/ folder.
#include <cstddef> /* offsetof */
#include <cstdlib> /* realloc() */
#include <errno.h>
#include <stddef.h> /* offsetof */
#include <stdlib.h> /* realloc() */
#include <string_view>
#include <process.h> /* _beginthreadex() */
@ -15,6 +16,8 @@
#include <event2/event.h>
#include <event2/util.h>
#include <fmt/core.h>
#define LIBTRANSMISSION_WATCHDIR_MODULE
#include "transmission.h"
@ -29,9 +32,9 @@
****
***/
#define log_error(...) \
(!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : \
tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir:win32", __VA_ARGS__))
static auto constexpr LogName = std::string_view{ "watchdir:win32" };
#define log_error(...) tr_logAddNamedError(LogName, __VA_ARGS__)
/***
****
@ -127,14 +130,14 @@ static unsigned int __stdcall tr_watchdir_win32_thread(void* context)
&backend->overlapped,
nullptr))
{
log_error("Failed to read directory changes");
log_error(_("Couldn't read directory changes"));
return 0;
}
}
if (GetLastError() != ERROR_OPERATION_ABORTED)
{
log_error("Failed to wait for directory changes");
log_error(_("Couldn't wait for directory changes"));
}
return 0;
@ -162,13 +165,20 @@ static void tr_watchdir_win32_on_event(struct bufferevent* event, void* context)
{
if (nread == (size_t)-1)
{
log_error("Failed to read event: %s", tr_strerror(errno));
auto const error_code = errno;
log_error(fmt::format(
_("Couldn't read event: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
break;
}
if (nread != header_size)
{
log_error("Failed to read event: expected %zu, got %zu bytes.", header_size, nread);
log_error(fmt::format(
_("Couldn't read event: expected {expected_size}, got {actual_size}"),
fmt::arg("expected_size", header_size),
fmt::arg("actual_size", nread)));
break;
}
@ -188,13 +198,20 @@ static void tr_watchdir_win32_on_event(struct bufferevent* event, void* context)
/* Consume entire name into buffer */
if ((nread = bufferevent_read(event, buffer + header_size, nleft)) == (size_t)-1)
{
log_error("Failed to read name: %s", tr_strerror(errno));
auto const error_code = errno;
log_error(fmt::format(
_("Couldn't read filename: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
break;
}
if (nread != nleft)
{
log_error("Failed to read name: expected %zu, got %zu bytes.", nleft, nread);
log_error(fmt::format(
_("Couldn't read filename: expected {expected_size}, got {actual_size}"),
fmt::arg("expected_size", nleft),
fmt::arg("actual_size", nread)));
break;
}
@ -261,17 +278,16 @@ static void tr_watchdir_win32_free(tr_watchdir_backend* backend_base)
tr_watchdir_backend* tr_watchdir_win32_new(tr_watchdir_t handle)
{
char const* const path = tr_watchdir_get_path(handle);
wchar_t* wide_path;
tr_watchdir_win32* backend;
backend = tr_new0(tr_watchdir_win32, 1);
auto* const backend = tr_new0(tr_watchdir_win32, 1);
backend->base.free_func = &tr_watchdir_win32_free;
backend->fd = INVALID_HANDLE_VALUE;
backend->notify_pipe[0] = backend->notify_pipe[1] = TR_BAD_SOCKET;
if ((wide_path = tr_win32_utf8_to_native(path, -1)) == nullptr)
wchar_t* wide_path = tr_win32_utf8_to_native(path, -1);
if (wide_path == nullptr)
{
log_error("Failed to convert \"%s\" to native path", path);
log_error(fmt::format(_("Couldn't convert '{path}' to native path"), fmt::arg("path", path)));
goto fail;
}
@ -284,7 +300,7 @@ tr_watchdir_backend* tr_watchdir_win32_new(tr_watchdir_t handle)
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
nullptr)) == INVALID_HANDLE_VALUE)
{
log_error("Failed to open directory \"%s\"", path);
log_error(fmt::format(_("Couldn't read '{path}'"), fmt::arg("path", path)));
goto fail;
}
@ -303,19 +319,27 @@ tr_watchdir_backend* tr_watchdir_win32_new(tr_watchdir_t handle)
&backend->overlapped,
nullptr))
{
log_error("Failed to read directory changes");
log_error(fmt::format(_("Couldn't read '{path}'"), fmt::arg("path", path)));
goto fail;
}
if (evutil_socketpair(AF_INET, SOCK_STREAM, 0, backend->notify_pipe) == -1)
{
log_error("Failed to create notify pipe: %s", tr_strerror(errno));
auto const error_code = errno;
log_error(fmt::format(
_("Couldn't create pipe: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto fail;
}
if ((backend->event = bufferevent_socket_new(tr_watchdir_get_event_base(handle), backend->notify_pipe[0], 0)) == nullptr)
{
log_error("Failed to create event buffer: %s", tr_strerror(errno));
auto const error_code = errno;
log_error(fmt::format(
_("Couldn't create event: {error} ({error_code})"),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
goto fail;
}
@ -325,7 +349,7 @@ tr_watchdir_backend* tr_watchdir_win32_new(tr_watchdir_t handle)
if ((backend->thread = (HANDLE)_beginthreadex(nullptr, 0, &tr_watchdir_win32_thread, handle, 0, nullptr)) == nullptr)
{
log_error("Failed to create thread");
log_error(_("Couldn't create thread"));
goto fail;
}
@ -338,7 +362,12 @@ tr_watchdir_backend* tr_watchdir_win32_new(tr_watchdir_t handle)
handle,
nullptr) == -1)
{
log_error("Failed to perform initial scan: %s", tr_strerror(errno));
auto const error_code = errno;
log_error(fmt::format(
_("Couldn't scan '{path}': {error} ({error_code})"),
fmt::arg("path", path),
fmt::arg("error", tr_strerror(error_code)),
fmt::arg("error_code", error_code)));
}
return BACKEND_DOWNCAST(backend);

View File

@ -11,6 +11,8 @@
#include <event2/event.h>
#include <event2/util.h>
#include <fmt/core.h>
#define LIBTRANSMISSION_WATCHDIR_MODULE
#include "transmission.h"
@ -24,15 +26,7 @@
#include "watchdir.h"
#include "watchdir-common.h"
/***
****
***/
#define log_debug(...) \
(!tr_logLevelIsActive(TR_LOG_DEBUG) ? (void)0 : tr_logAddMessage(__FILE__, __LINE__, TR_LOG_DEBUG, "watchdir", __VA_ARGS__))
#define log_error(...) \
(!tr_logLevelIsActive(TR_LOG_ERROR) ? (void)0 : tr_logAddMessage(__FILE__, __LINE__, TR_LOG_ERROR, "watchdir", __VA_ARGS__))
static auto constexpr LogName = std::string_view{ "watchdir" };
/***
****
@ -64,7 +58,13 @@ static bool is_regular_file(char const* dir, char const* name)
{
if (!TR_ERROR_IS_ENOENT(error->code))
{
log_error("Failed to get type of \"%s\" (%d): %s", path.c_str(), error->code, error->message);
tr_logAddNamedWarn(
LogName,
fmt::format(
_("Couldn't read '{path}': {error} ({error_code})"),
fmt::arg("path", path),
fmt::arg("error", error->message),
fmt::arg("error_code", error->code)));
}
tr_error_free(error);
@ -103,7 +103,7 @@ static tr_watchdir_status tr_watchdir_process_impl(tr_watchdir_t handle, char co
TR_ASSERT(ret == TR_WATCHDIR_ACCEPT || ret == TR_WATCHDIR_IGNORE || ret == TR_WATCHDIR_RETRY);
log_debug("Callback decided to %s file \"%s\"", watchdir_status_to_string(ret), name);
tr_logAddNamedDebug(LogName, fmt::format("Callback decided to {} file '{}'", watchdir_status_to_string(ret), name));
return ret;
}
@ -162,7 +162,7 @@ static void tr_watchdir_on_retry_timer(evutil_socket_t /*fd*/, short /*type*/, v
return;
}
log_error("Failed to add (corrupted?) torrent file: %s", retry->name);
tr_logAddNamedWarn(LogName, fmt::format(_("Couldn't add .torrent file '{path}'"), fmt::arg("path", retry->name)));
}
tr_watchdir_retries_remove(&handle->active_retries, retry);
@ -328,7 +328,13 @@ void tr_watchdir_scan(tr_watchdir_t handle, std::unordered_set<std::string>* dir
auto const dir = tr_sys_dir_open(handle->path, &error);
if (dir == TR_BAD_SYS_DIR)
{
log_error("Failed to open directory \"%s\" (%d): %s", handle->path, error->code, error->message);
tr_logAddNamedWarn(
LogName,
fmt::format(
_("Couldn't open '{path}': {error} ({error_code})"),
fmt::arg("path", handle->path),
fmt::arg("error", error->message),
fmt::arg("error_code", error->code)));
tr_error_free(error);
return;
}
@ -357,7 +363,13 @@ void tr_watchdir_scan(tr_watchdir_t handle, std::unordered_set<std::string>* dir
if (error != nullptr)
{
log_error("Failed to read directory \"%s\" (%d): %s", handle->path, error->code, error->message);
tr_logAddNamedWarn(
LogName,
fmt::format(
_("Couldn't read '{path}': {error} ({error_code})"),
fmt::arg("path", handle->path),
fmt::arg("error", error->message),
fmt::arg("error_code", error->code)));
tr_error_free(error);
}

View File

@ -11,6 +11,8 @@
#include <atomic> /* atomic, atomic_fetch_add_explicit, memory_order_relaxed */
#include <libtransmission/transmission.h>
#include <libtransmission/log.h>
#include <libtransmission/torrent-metainfo.h>
#include <libtransmission/utils.h>
#include <libtransmission/variant.h>