refactor: clang-tidy in libtransmission (#2578)

* chore: enable cppcoreguidelines-slicing warning

* chore: enable readability-named-parameter warning

* chore: enable bugprone-reserved-identifier check

* chore: enable bugprone-not-null-terminated-result check

* chore: enable bugprone-sizeof-expression check

* chore: enable bugprone-incorrect-roundings check

* chore: enable misc-misplaced-const check

* chore: enable bugprone-suspicious-include check

* chore: enable bugprone-signed-char-misuse check

* chore: enable modernize-raw-string-literal check

* chore: enable readability-static-accessed-through-instance check

* chore: enable readability-implicit-bool-conversion check

* fixup! Merge branch 'main' into refactor/clang-tidy
This commit is contained in:
Charles Kerr 2022-02-06 22:28:36 -06:00 committed by GitHub
parent f9d068d7a0
commit ecef0feb0c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
40 changed files with 143 additions and 161 deletions

View File

@ -5,17 +5,9 @@ Checks: >
-bugprone-branch-clone,
-bugprone-easily-swappable-parameters,
-bugprone-implicit-widening-of-multiplication-result,
-bugprone-incorrect-roundings,
-bugprone-narrowing-conversions,
-bugprone-not-null-terminated-result,
-bugprone-reserved-identifier,
-bugprone-signed-char-misuse,
-bugprone-sizeof-expression,
-bugprone-suspicious-include,
cert-*,
-cert-dcl37-c,
-cert-dcl50-cpp,
-cert-dcl51-cpp,
-cert-err33-c,
-cert-err34-c,
-cert-err58-cpp,
@ -26,23 +18,19 @@ Checks: >
clang-analyzer-valist.*,
cppcoreguidelines-init-variables,
cppcoreguidelines-prefer-member-initializer,
cppcoreguidelines-slicing,
cppcoreguidelines-virtual-class-destructor,
misc-*,
-misc-misplaced-const,
-misc-no-recursion,
-misc-non-private-member-variables-in-classes,
modernize-*,
-modernize-avoid-c-arrays,
-modernize-raw-string-literal,
-modernize-use-trailing-return-type,
performance-*,
readability-*,
-readability-function-cognitive-complexity,
-readability-identifier-length,
-readability-implicit-bool-conversion,
-readability-inconsistent-declaration-parameter-name,
-readability-magic-numbers,
-readability-named-parameter,
-readability-qualified-auto,
-readability-redundant-access-specifiers,
-readability-static-accessed-through-instance,

View File

@ -71,7 +71,7 @@ static std::string announce_url_new(tr_session const* session, tr_announce_reque
"&compact=1"
"&supportcrypto=1",
TR_PRIsv_ARG(announce_sv),
announce_sv.find('?') == announce_sv.npos ? '?' : '&',
announce_sv.find('?') == std::string_view::npos ? '?' : '&',
std::data(escaped_info_hash),
TR_PRIsv_ARG(req->peer_id),
req->port,
@ -154,13 +154,13 @@ static void verboseLog(std::string_view description, tr_direction direction, std
out << description << std::endl << "[raw]"sv << direction_sv;
for (unsigned char ch : message)
{
if (isprint(ch))
if (isprint(ch) != 0)
{
out << ch;
}
else
{
out << "\\x"sv << std::hex << std::setw(2) << std::setfill('0') << unsigned(ch) << std::dec << std::setw(1)
out << R"(\x)" << std::hex << std::setw(2) << std::setfill('0') << unsigned(ch) << std::dec << std::setw(1)
<< std::setfill(' ');
}
}

View File

@ -450,7 +450,7 @@ struct tau_tracker
}
};
static void tau_tracker_upkeep(struct tau_tracker*);
static void tau_tracker_upkeep(struct tau_tracker* /*tracker*/);
static void tau_tracker_on_dns(int errcode, struct evutil_addrinfo* addr, void* vtracker)
{

View File

@ -761,7 +761,7 @@ static void tier_announce_event_push(tr_tier* tier, tr_announce_event e, time_t
* dump everything leading up to it except "completed" */
if (e == TR_ANNOUNCE_EVENT_STOPPED)
{
bool has_completed = std::count(std::begin(events), std::end(events), TR_ANNOUNCE_EVENT_COMPLETED);
bool has_completed = std::count(std::begin(events), std::end(events), TR_ANNOUNCE_EVENT_COMPLETED) != 0;
events.clear();
if (has_completed)
{
@ -885,7 +885,7 @@ void tr_announcerRemoveTorrent(tr_announcer* announcer, tr_torrent* tor)
auto const e = TR_ANNOUNCE_EVENT_STOPPED;
auto* req = announce_request_new(announcer, tor, &tier, e);
if (announcer->stops.count(req))
if (announcer->stops.count(req) != 0U)
{
delete req;
}
@ -1593,8 +1593,8 @@ static tr_tracker_view trackerView(tr_torrent const& tor, int tier_index, tr_tie
}
else
{
view.hasScraped = tier.lastScrapeTime;
if (view.hasScraped != 0)
view.hasScraped = tier.lastScrapeTime != 0;
if (view.hasScraped)
{
view.lastScrapeTime = tier.lastScrapeTime;
view.lastScrapeSucceeded = tier.lastScrapeSucceeded;
@ -1622,8 +1622,8 @@ static tr_tracker_view trackerView(tr_torrent const& tor, int tier_index, tr_tie
view.lastAnnounceStartTime = tier.lastAnnounceStartTime;
view.hasAnnounced = tier.lastAnnounceTime;
if (view.hasAnnounced != 0)
view.hasAnnounced = tier.lastAnnounceTime != 0;
if (view.hasAnnounced)
{
view.lastAnnounceTime = tier.lastAnnounceTime;
view.lastAnnounceSucceeded = tier.lastAnnounceSucceeded;

View File

@ -46,10 +46,10 @@ void tr_block_info::initSizes(uint64_t total_size_in, uint64_t piece_size_in)
n_pieces = (total_size + piece_size - 1) / piece_size;
auto remainder = total_size % piece_size;
final_piece_size = remainder ? remainder : piece_size;
final_piece_size = remainder != 0U ? remainder : piece_size;
remainder = total_size % block_size;
final_block_size = remainder ? remainder : block_size;
final_block_size = remainder != 0U ? remainder : block_size;
if (block_size != 0)
{

View File

@ -235,8 +235,8 @@ bool decodeBitCometClient(char* buf, size_t buflen, std::string_view peer_id)
bool const is_bitlord = std::string_view(std::data(peer_id) + 6, 4) == "LORD"sv;
auto const name = is_bitlord ? "BitLord"sv : "BitComet"sv;
int const major = peer_id[4];
int const minor = peer_id[5];
int const major = uint8_t(peer_id[4]);
int const minor = uint8_t(peer_id[5]);
std::tie(buf, buflen) = buf_append(buf, buflen, name, ' ', mod, major, '.');
tr_snprintf(buf, buflen, "%02d", minor);
@ -683,7 +683,7 @@ char* tr_clientForId(char* buf, size_t buflen, tr_peer_id_t peer_id)
{
char const c = peer_id[i];
if (isprint((unsigned char)c))
if (isprint((unsigned char)c) != 0)
{
*walk++ = c;
}

View File

@ -20,7 +20,7 @@
#define TR_CRYPTO_DH_SECRET_FALLBACK
#define TR_CRYPTO_X509_FALLBACK
#include "crypto-utils-fallback.cc"
#include "crypto-utils-fallback.cc" // NOLINT(bugprone-suspicious-include)
/***
****

View File

@ -32,7 +32,7 @@
#define TR_CRYPTO_DH_SECRET_FALLBACK
#define TR_CRYPTO_X509_FALLBACK
#include "crypto-utils-fallback.cc"
#include "crypto-utils-fallback.cc" // NOLINT(bugprone-suspicious-include)
struct tr_dh_ctx
{

View File

@ -25,7 +25,7 @@
#include "utils.h"
#define TR_CRYPTO_DH_SECRET_FALLBACK
#include "crypto-utils-fallback.cc"
#include "crypto-utils-fallback.cc" // NOLINT(bugprone-suspicious-include)
/***
****

View File

@ -30,7 +30,7 @@
#define TR_CRYPTO_DH_SECRET_FALLBACK
#define TR_CRYPTO_X509_FALLBACK
#include "crypto-utils-fallback.cc"
#include "crypto-utils-fallback.cc" // NOLINT(bugprone-suspicious-include)
/***
****

View File

@ -4,7 +4,7 @@
// License text can be found in the licenses/ folder.
#undef _GNU_SOURCE
#define _GNU_SOURCE
#define _GNU_SOURCE // NOLINT
#include <algorithm>
#include <array>
@ -14,17 +14,17 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string_view>
#include <vector>
#include <dirent.h>
#include <fcntl.h> /* O_LARGEFILE, posix_fadvise(), [posix_]fallocate(), fcntl() */
#include <libgen.h> /* basename(), dirname() */
#include <string_view>
#include <unistd.h> /* lseek(), write(), ftruncate(), pread(), pwrite(), pathconf(), etc */
#include <vector>
#include <sys/file.h> /* flock() */
#include <sys/mman.h> /* mmap(), munmap() */
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h> /* lseek(), write(), ftruncate(), pread(), pwrite(), pathconf(), etc */
#ifdef HAVE_XFS_XFS_H
#include <xfs/xfs.h>

View File

@ -22,8 +22,7 @@
using namespace std::literals;
tr_log_level __tr_message_level = TR_LOG_ERROR;
static tr_log_level tr_message_level = TR_LOG_ERROR;
static bool myQueueEnabled = false;
static tr_log_message* myQueue = nullptr;
static tr_log_message** myQueueTail = &myQueue;
@ -45,7 +44,7 @@ static inline bool IsDebuggerPresent()
tr_log_level tr_logGetLevel()
{
return __tr_message_level;
return tr_message_level;
}
/***
@ -84,7 +83,7 @@ tr_sys_file_t tr_logGetFile()
void tr_logSetLevel(tr_log_level level)
{
__tr_message_level = level;
tr_message_level = level;
}
void tr_logSetQueueEnabled(bool isEnabled)

View File

@ -151,7 +151,7 @@ std::vector<tr_block_index_t> ActiveRequests::remove(tr_peer const* peer)
auto const key = peer_at{ const_cast<tr_peer*>(peer), 0 };
for (auto const& [block, peers_at] : impl_->blocks_)
{
if (peers_at.count(key))
if (peers_at.count(key) != 0U)
{
removed.push_back(block);
}
@ -194,7 +194,7 @@ std::vector<tr_peer*> ActiveRequests::remove(tr_block_index_t block)
bool ActiveRequests::has(tr_block_index_t block, tr_peer const* peer) const
{
auto const it = impl_->blocks_.find(block);
return it != std::end(impl_->blocks_) && it->second.count(peer_at{ const_cast<tr_peer*>(peer), 0 });
return it != std::end(impl_->blocks_) && (it->second.count(peer_at{ const_cast<tr_peer*>(peer), 0 }) != 0U);
}
// count how many peers we're asking for `block`

View File

@ -6,6 +6,7 @@
#include <algorithm>
#include <cerrno> /* error codes ERANGE, ... */
#include <climits> /* INT_MAX */
#include <cmath>
#include <cstdlib> /* qsort */
#include <ctime> // time_t
#include <iterator> // std::back_inserter
@ -339,7 +340,7 @@ static void swarmFree(tr_swarm* s)
delete s;
}
static void peerCallbackFunc(tr_peer*, tr_peer_event const*, void*);
static void peerCallbackFunc(tr_peer* /*peer*/, tr_peer_event const* /*e*/, void* /*vs*/);
static void rebuildWebseedArray(tr_swarm* s, tr_torrent* tor)
{
@ -681,7 +682,7 @@ static void addStrike(tr_swarm* s, tr_peer* peer)
}
}
static void peerSuggestedPiece(tr_swarm* /*s*/, tr_peer* /*peer*/, tr_piece_index_t /*pieceIndex*/, int /*isFastAllowed*/)
static void peerSuggestedPiece(tr_swarm* /*s*/, tr_peer* /*peer*/, tr_piece_index_t /*pieceIndex*/, bool /*isFastAllowed*/)
{
#if 0
@ -1399,10 +1400,10 @@ int tr_peerMgrGetPeers(tr_torrent const* tor, tr_pex** setme_pex, uint8_t af, ui
return count;
}
static void atomPulse(evutil_socket_t, short, void*);
static void bandwidthPulse(evutil_socket_t, short, void*);
static void rechokePulse(evutil_socket_t, short, void*);
static void reconnectPulse(evutil_socket_t, short, void*);
static void atomPulse(evutil_socket_t, short /*unused*/, void* /*vmgr*/);
static void bandwidthPulse(evutil_socket_t, short /*unused*/, void* /*vmgr*/);
static void rechokePulse(evutil_socket_t, short /*unused*/, void* /*vmgr*/);
static void reconnectPulse(evutil_socket_t, short /*unused*/, void* /*vmgr*/);
static struct event* createTimer(tr_session* session, int msec, event_callback_fn callback, void* cbdata)
{
@ -1450,7 +1451,7 @@ void tr_peerMgrStartTorrent(tr_torrent* tor)
tr_timerAddMsec(s->manager->rechokeTimer, 100);
}
static void removeAllPeers(tr_swarm*);
static void removeAllPeers(tr_swarm* /*swarm*/);
static void stopSwarm(tr_swarm* swarm)
{
@ -2297,7 +2298,7 @@ static bool shouldPeerBeClosed(tr_swarm const* s, tr_peer const* peer, int peerC
/* disconnect if it's been too long since piece data has been transferred.
* this is on a sliding scale based on number of available peers... */
{
auto const relaxStrictnessIfFewerThanN = int(getMaxPeerCount(tor) * 0.9 + 0.5);
auto const relaxStrictnessIfFewerThanN = std::lround(getMaxPeerCount(tor) * 0.9);
/* if we have >= relaxIfFewerThan, strictness is 100%.
* if we have zero connections, strictness is 0% */
float const strictness = peerCount >= relaxStrictnessIfFewerThanN ? 1.0 :

View File

@ -1408,7 +1408,7 @@ static ReadState readBtLength(tr_peerMsgsImpl* msgs, struct evbuffer* inbuf, siz
return READ_NOW;
}
static ReadState readBtMessage(tr_peerMsgsImpl*, struct evbuffer*, size_t);
static ReadState readBtMessage(tr_peerMsgsImpl* /*msgs*/, struct evbuffer* /*inbuf*/, size_t /*inlen*/);
static ReadState readBtId(tr_peerMsgsImpl* msgs, struct evbuffer* inbuf, size_t inlen)
{

View File

@ -220,7 +220,7 @@ static std::string getblkdev(std::string_view path)
}
auto const pos = path.rfind('/');
if (pos == path.npos)
if (pos == std::string_view::npos)
{
return {};
}
@ -459,7 +459,7 @@ static struct tr_disk_space getDiskSpace(char const* path)
#elif defined(HAVE_STATVFS)
struct statvfs buf;
return statvfs(path, &buf) ?
return statvfs(path, &buf) != 0 ?
(struct tr_disk_space){ -1, -1 } :
(struct tr_disk_space){ (int64_t)buf.f_bavail * (int64_t)buf.f_frsize, (int64_t)buf.f_blocks * (int64_t)buf.f_frsize };
@ -479,7 +479,7 @@ tr_device_info tr_device_info_create(std::string_view path)
#ifndef _WIN32
out.device = getblkdev(out.path);
auto const* const fstype = getfstype(out.path.c_str());
out.fstype = fstype ? fstype : "";
out.fstype = fstype != nullptr ? fstype : "";
#endif
return out;
}

View File

@ -253,7 +253,7 @@ static std::string getXdgEntryFromUserDirs(std::string_view key)
}
// search for key="val" and extract val
auto const search = tr_strvJoin(key, "=\""sv);
auto const search = tr_strvJoin(key, R"(=")");
auto begin = std::search(std::begin(content), std::end(content), std::begin(search), std::end(search));
if (begin == std::end(content))
{

View File

@ -415,7 +415,7 @@ static uint64_t loadFilenames(tr_variant* dict, tr_torrent* tor)
static void bitfieldToRaw(tr_bitfield const& b, tr_variant* benc)
{
if (b.hasNone() || std::empty(b))
if (b.hasNone() || (std::empty(b) != 0U))
{
tr_variantInitStr(benc, "none"sv);
}

View File

@ -724,9 +724,9 @@ static auto parseWhitelist(std::string_view whitelist)
auto const pos = whitelist.find_first_of(" ,;"sv);
auto const token = tr_strvStrip(whitelist.substr(0, pos));
list.emplace_back(token);
whitelist = pos == whitelist.npos ? ""sv : whitelist.substr(pos + 1);
whitelist = pos == std::string_view::npos ? ""sv : whitelist.substr(pos + 1);
if (token.find_first_of("+-"sv) != token.npos)
if (token.find_first_of("+-"sv) != std::string_view::npos)
{
tr_logAddNamedInfo(
MyName,

View File

@ -812,7 +812,7 @@ static void initField(tr_torrent const* const tor, tr_stat const* const st, tr_v
tr_variantInitList(initme, n);
for (tr_file_index_t i = 0; i < n; ++i)
{
tr_variantListAddInt(initme, tr_torrentFile(tor, i).wanted);
tr_variantListAddBool(initme, tr_torrentFile(tor, i).wanted);
}
}
break;

View File

@ -572,7 +572,7 @@ static void onSaveTimer(evutil_socket_t /*fd*/, short /*what*/, void* vsession)
****
***/
static void tr_sessionInitImpl(void*);
static void tr_sessionInitImpl(void* /*vdata*/);
struct init_data
{
@ -757,7 +757,7 @@ static void tr_sessionInitImpl(void* vdata)
data->done = true;
}
static void turtleBootstrap(tr_session*, struct tr_turtle_info*);
static void turtleBootstrap(tr_session* /*session*/, struct tr_turtle_info* /*turtle*/);
static void setPeerPort(tr_session* session, tr_port port);
static void sessionSetImpl(void* vdata)
@ -1142,7 +1142,7 @@ void tr_sessionSetDownloadDir(tr_session* session, char const* dir)
{
TR_ASSERT(tr_isSession(session));
session->setDownloadDir(dir ? dir : "");
session->setDownloadDir(dir != nullptr ? dir : "");
}
char const* tr_sessionGetDownloadDir(tr_session const* session)
@ -1178,7 +1178,7 @@ void tr_sessionSetIncompleteDir(tr_session* session, char const* dir)
{
TR_ASSERT(tr_isSession(session));
session->setIncompleteDir(dir ? dir : "");
session->setIncompleteDir(dir != nullptr ? dir : "");
}
char const* tr_sessionGetIncompleteDir(tr_session const* session)
@ -1801,7 +1801,7 @@ std::vector<tr_torrent*> tr_sessionGetTorrents(tr_session* session)
return torrents;
}
static void closeBlocklists(tr_session*);
static void closeBlocklists(tr_session* /*session*/);
static void sessionCloseImplWaitForIdleUdp(evutil_socket_t fd, short what, void* vsession);
@ -2042,7 +2042,7 @@ static void sessionLoadTorrents(void* vdata)
}
int const n = std::size(torrents);
data->torrents = tr_new(tr_torrent*, n);
data->torrents = tr_new(tr_torrent*, n); // NOLINT(bugprone-sizeof-expression)
std::copy(std::begin(torrents), std::end(torrents), data->torrents);
if (n != 0)
@ -2454,7 +2454,7 @@ bool tr_sessionIsAddressBlocked(tr_session const* session, tr_address const* add
void tr_blocklistSetURL(tr_session* session, char const* url)
{
session->setBlocklistUrl(url ? url : "");
session->setBlocklistUrl(url != nullptr ? url : "");
}
char const* tr_blocklistGetURL(tr_session const* session)
@ -2518,7 +2518,7 @@ void tr_sessionSetRPCUrl(tr_session* session, char const* url)
{
TR_ASSERT(tr_isSession(session));
tr_rpcSetUrl(session->rpc_server_.get(), url ? url : "");
tr_rpcSetUrl(session->rpc_server_.get(), url != nullptr ? url : "");
}
char const* tr_sessionGetRPCUrl(tr_session const* session)
@ -2540,7 +2540,7 @@ void tr_sessionSetRPCWhitelist(tr_session* session, char const* whitelist)
{
TR_ASSERT(tr_isSession(session));
session->setRpcWhitelist(whitelist ? whitelist : "");
session->setRpcWhitelist(whitelist != nullptr ? whitelist : "");
}
char const* tr_sessionGetRPCWhitelist(tr_session const* session)
@ -2568,7 +2568,7 @@ void tr_sessionSetRPCPassword(tr_session* session, char const* password)
{
TR_ASSERT(tr_isSession(session));
tr_rpcSetPassword(session->rpc_server_.get(), password ? password : "");
tr_rpcSetPassword(session->rpc_server_.get(), password != nullptr ? password : "");
}
char const* tr_sessionGetRPCPassword(tr_session const* session)
@ -2582,7 +2582,7 @@ void tr_sessionSetRPCUsername(tr_session* session, char const* username)
{
TR_ASSERT(tr_isSession(session));
tr_rpcSetUsername(session->rpc_server_.get(), username ? username : "");
tr_rpcSetUsername(session->rpc_server_.get(), username != nullptr ? username : "");
}
char const* tr_sessionGetRPCUsername(tr_session const* session)
@ -2638,7 +2638,7 @@ void tr_sessionSetScript(tr_session* session, TrScript type, char const* script)
TR_ASSERT(tr_isSession(session));
TR_ASSERT(type < TR_SCRIPT_N_TYPES);
session->setScript(type, script ? script : "");
session->setScript(type, script != nullptr ? script : "");
}
char const* tr_sessionGetScript(tr_session const* session, TrScript type)

View File

@ -78,7 +78,7 @@ static bool tr_spawn_async_in_child(
return true;
FAIL:
(void)!write(pipe_fd, &errno, sizeof(errno));
(void)write(pipe_fd, &errno, sizeof(errno));
return false;
}

View File

@ -86,7 +86,7 @@ bool tr_ctorSetMetainfoFromFile(tr_ctor* ctor, std::string const& filename, tr_e
bool tr_ctorSetMetainfoFromFile(tr_ctor* ctor, char const* filename, tr_error** error)
{
return tr_ctorSetMetainfoFromFile(ctor, std::string{ filename ? filename : "" }, error);
return tr_ctorSetMetainfoFromFile(ctor, std::string{ filename != nullptr ? filename : "" }, error);
}
bool tr_ctorSetMetainfo(tr_ctor* ctor, char const* metainfo, size_t len, tr_error** error)
@ -100,7 +100,7 @@ bool tr_ctorSetMetainfo(tr_ctor* ctor, char const* metainfo, size_t len, tr_erro
bool tr_ctorSetMetainfoFromMagnetLink(tr_ctor* ctor, char const* magnet_link, tr_error** error)
{
ctor->torrent_filename.clear();
return ctor->metainfo.parseMagnet(magnet_link ? magnet_link : "", error);
return ctor->metainfo.parseMagnet(magnet_link != nullptr ? magnet_link : "", error);
}
std::string_view tr_ctorGetContents(tr_ctor const* ctor)
@ -218,12 +218,12 @@ void tr_ctorSetDownloadDir(tr_ctor* ctor, tr_ctorMode mode, char const* director
TR_ASSERT(ctor != nullptr);
TR_ASSERT(mode == TR_FALLBACK || mode == TR_FORCE);
ctor->optional_args[mode].download_dir.assign(directory ? directory : "");
ctor->optional_args[mode].download_dir.assign(directory != nullptr ? directory : "");
}
void tr_ctorSetIncompleteDir(tr_ctor* ctor, char const* directory)
{
ctor->incomplete_dir.assign(directory ? directory : "");
ctor->incomplete_dir.assign(directory != nullptr ? directory : "");
}
bool tr_ctorGetPeerLimit(tr_ctor const* ctor, tr_ctorMode mode, uint16_t* setme)

View File

@ -196,7 +196,7 @@ static bool appendSanitizedComponent(std::string& out, std::string_view in, bool
// remove trailing spaces and '.'
auto constexpr trailing_test = [](unsigned char ch)
{
return isspace(ch) || ch == '.';
return (isspace(ch) != 0) || ch == '.';
};
auto const rit = std::find_if_not(std::rbegin(in), std::rend(in), trailing_test);
in.remove_suffix(std::distance(std::rbegin(in), rit));

View File

@ -111,7 +111,7 @@ tr_torrent* tr_torrentFindFromMetainfo(tr_session* session, tr_torrent_metainfo
tr_torrent* tr_torrentFindFromMagnetLink(tr_session* session, char const* magnet_link)
{
auto mm = tr_magnet_metainfo{};
return mm.parseMagnet(magnet_link ? magnet_link : "") ? session->getTorrent(mm.infoHash()) : nullptr;
return mm.parseMagnet(magnet_link != nullptr ? magnet_link : "") ? session->getTorrent(mm.infoHash()) : nullptr;
}
tr_torrent* tr_torrentFindFromObfuscatedHash(tr_session* session, tr_sha1_digest_t const& obfuscated_hash)
@ -1216,7 +1216,7 @@ static void tr_torrentResetTransferStats(tr_torrent* tor)
***/
#ifdef TR_ENABLE_ASSERTS
static bool queueIsSequenced(tr_session*);
static bool queueIsSequenced(tr_session* /*session*/);
#endif
static void freeTorrent(tr_torrent* tor)
@ -1570,7 +1570,7 @@ struct remove_data
tr_fileFunc deleteFunc;
};
static void tr_torrentDeleteLocalData(tr_torrent*, tr_fileFunc);
static void tr_torrentDeleteLocalData(tr_torrent* /*tor*/, tr_fileFunc /*func*/);
static void removeTorrent(void* vdata)
{
@ -2010,7 +2010,7 @@ bool tr_torrentSetAnnounceList(tr_torrent* tor, char const* const* announce_urls
auto const lock = tor->unique_lock();
auto announce_list = tr_announce_list();
if (!announce_list.set(announce_urls, tiers, n) || !announce_list.save(tor->torrentFile()))
if ((announce_list.set(announce_urls, tiers, n) == 0U) || !announce_list.save(tor->torrentFile()))
{
return false;
}
@ -2443,7 +2443,7 @@ void tr_torrentSetLocation(
TR_ASSERT(tr_isTorrent(tor));
TR_ASSERT(!tr_str_is_empty(location));
return tor->setLocation(location ? location : "", move_from_old_location, setme_progress, setme_state);
return tor->setLocation(location != nullptr ? location : "", move_from_old_location, setme_progress, setme_state);
}
std::string_view tr_torrent::primaryMimeType() const

View File

@ -9,6 +9,9 @@
#include <cstdlib> /* atoi() */
#include <cstring> /* memcpy(), memset(), memchr(), strlen() */
#include <ctime>
#include <fstream>
#include <sstream>
#include <string>
#include <string_view>
#include <thread>
@ -129,6 +132,42 @@ static void bootstrap_from_name(char const* name, tr_port port, int af)
freeaddrinfo(info);
}
static void dht_boostrap_from_file(tr_session* session)
{
if (bootstrap_done(session, 0))
{
return;
}
// check for a manual bootstrap file.
auto const bootstrap_file = tr_strvPath(session->config_dir, "dht.bootstrap");
auto in = std::ifstream{ bootstrap_file };
if (!in.is_open())
{
return;
}
// format is each line has address, a space char, and port number
tr_logAddNamedInfo("DHT", "Attempting manual bootstrap");
auto line = std::string{};
while (!bootstrap_done(session, 0) && std::getline(in, line))
{
auto line_stream = std::istringstream{ line };
auto addrstr = std::string{};
auto port = tr_port{};
line_stream >> addrstr >> port;
if (line_stream.bad() || std::empty(addrstr) || port <= 0)
{
tr_logAddNamedError("DHT", "Couldn't parse line: \"%s\"", line.c_str());
}
else
{
bootstrap_from_name(addrstr.c_str(), port, bootstrap_af(session_));
}
}
}
static void dht_bootstrap(void* closure)
{
auto* cl = static_cast<struct bootstrap_closure*>(closure);
@ -198,48 +237,7 @@ static void dht_bootstrap(void* closure)
if (!bootstrap_done(cl->session, 0))
{
auto const bootstrap_file = tr_strvPath(cl->session->config_dir, "dht.bootstrap");
tr_sys_file_t const f = tr_sys_file_open(bootstrap_file.c_str(), TR_SYS_FILE_READ, 0, nullptr);
if (f != TR_BAD_SYS_FILE)
{
tr_logAddNamedInfo("DHT", "Attempting manual bootstrap");
for (;;)
{
char buf[201];
if (!tr_sys_file_read_line(f, buf, 200, nullptr))
{
break;
}
auto* p = static_cast<char*>(memchr(buf, ' ', strlen(buf)));
int port = 0;
if (p != nullptr)
{
port = atoi(p + 1);
}
if (p == nullptr || port <= 0 || port >= 0x10000)
{
tr_logAddNamedError("DHT", "Couldn't parse %s", buf);
continue;
}
*p = '\0';
bootstrap_from_name(buf, port, bootstrap_af(session_));
if (bootstrap_done(cl->session, 0))
{
break;
}
}
tr_sys_file_close(f, nullptr);
}
dht_boostrap_from_file(cl->session);
}
if (!bootstrap_done(cl->session, 0))

View File

@ -46,7 +46,7 @@ static auto constexpr SIZEOF_HASH_STRING = TR_SHA1_DIGEST_STRLEN;
*
*/
static void event_callback(evutil_socket_t, short, void*);
static void event_callback(evutil_socket_t, short /*type*/, void* /*unused*/);
static auto constexpr UpkeepIntervalSecs = int{ 5 };
@ -239,7 +239,7 @@ static bool lpd_extractParam(char const* const str, char const* const name, int
/**
* @} */
static void on_upkeep_timer(evutil_socket_t, short, void*);
static void on_upkeep_timer(evutil_socket_t, short /*unused*/, void* /*unused*/);
/**
* @brief Initializes Local Peer Discovery for this node

View File

@ -109,7 +109,7 @@ void tr_udpSetSocketTOS(tr_session* session)
{
auto const tos = session->peerSocketTos();
if (tos)
if (tos != 0)
{
return;
}
@ -261,9 +261,7 @@ static void event_callback(evutil_socket_t s, [[maybe_unused]] short type, void*
}
else if (rc >= 8 && buf[0] == 0 && buf[1] == 0 && buf[2] == 0 && buf[3] <= 3)
{
rc = tau_handle_message(session, buf, rc);
if (rc == 0)
if (!tau_handle_message(session, buf, rc))
{
tr_logAddNamedDbg("UDP", "Couldn't parse UDP tracker packet.");
}
@ -272,9 +270,7 @@ static void event_callback(evutil_socket_t s, [[maybe_unused]] short type, void*
{
if (tr_sessionIsUTPEnabled(session))
{
rc = tr_utpPacket(buf, rc, (struct sockaddr*)&from, fromlen, session);
if (rc == 0)
if (!tr_utpPacket(buf, rc, (struct sockaddr*)&from, fromlen, session))
{
tr_logAddNamedDbg("UDP", "Unexpected UDP packet");
}

View File

@ -42,14 +42,14 @@ bool UTP_Write(struct UTPSocket* socket, size_t count)
return false;
}
int tr_utpPacket(
bool tr_utpPacket(
unsigned char const* /*buf*/,
size_t /*buflen*/,
sockaddr const* /*from*/,
socklen_t /*fromlen*/,
tr_session* /*ss*/)
{
return -1;
return false;
}
struct UTPSocket* UTP_Create(
@ -152,7 +152,7 @@ static void timer_callback(evutil_socket_t /*s*/, short /*type*/, void* vsession
reset_timer(session);
}
int tr_utpPacket(unsigned char const* buf, size_t buflen, struct sockaddr const* from, socklen_t fromlen, tr_session* ss)
bool tr_utpPacket(unsigned char const* buf, size_t buflen, struct sockaddr const* from, socklen_t fromlen, tr_session* ss)
{
if (!ss->isClosed && ss->utp_timer == nullptr)
{
@ -160,7 +160,7 @@ int tr_utpPacket(unsigned char const* buf, size_t buflen, struct sockaddr const*
if (ss->utp_timer == nullptr)
{
return -1;
return false;
}
reset_timer(ss);

View File

@ -10,7 +10,7 @@
#include <cstddef> // size_t
int tr_utpPacket(unsigned char const* buf, size_t buflen, struct sockaddr const* from, socklen_t fromlen, tr_session* ss);
bool tr_utpPacket(unsigned char const* buf, size_t buflen, struct sockaddr const* from, socklen_t fromlen, tr_session* ss);
void tr_utpClose(tr_session*);

View File

@ -51,7 +51,7 @@ void lock_free(void* lock_, unsigned /*locktype*/)
int lock_lock(unsigned mode, void* lock_)
{
auto* lock = static_cast<std::recursive_mutex*>(lock_);
if (mode & EVTHREAD_TRY)
if ((mode & EVTHREAD_TRY) != 0U)
{
auto const success = lock->try_lock();
return success ? 0 : -1;
@ -79,7 +79,7 @@ void cond_free(void* cond_)
int cond_signal(void* cond_, int broadcast)
{
auto* cond = static_cast<std::condition_variable_any*>(cond_);
if (broadcast)
if (broadcast != 0)
{
cond->notify_all();
}
@ -206,7 +206,7 @@ static void libeventThreadFunc(tr_event_handle* events)
events->base = base;
events->work_queue_event = event_new(base, -1, 0, onWorkAvailable, events->session);
events->session->event_base = base;
events->session->evdns_base = evdns_base_new(base, true);
events->session->evdns_base = evdns_base_new(base, EVDNS_BASE_INITIALIZE_NAMESERVERS);
events->session->events = events;
// loop until `tr_eventClose()` kills the loop

View File

@ -164,15 +164,15 @@ char const* tr_strip_positional_args(char const* str)
char const* in = str;
size_t pos = 0;
for (; str && *str && pos + 1 < std::size(buf); ++str)
for (; (str != nullptr) && (*str != 0) && pos + 1 < std::size(buf); ++str)
{
buf[pos++] = *str;
if (*str == '%' && isdigit(str[1]))
if (*str == '%' && (isdigit(str[1]) != 0))
{
char const* tmp = str + 1;
while (isdigit(*tmp))
while (isdigit(*tmp) != 0)
{
++tmp;
}
@ -191,7 +191,7 @@ char const* tr_strip_positional_args(char const* str)
buf[pos] = '\0';
return in && !strcmp(buf.data(), in) ? in : buf.data();
return (in != nullptr) && (strcmp(buf.data(), in) == 0) ? in : buf.data();
}
/**
@ -743,7 +743,7 @@ std::string& tr_strvUtf8Clean(std::string_view cleanme, std::string& setme)
else
{
auto* const tmp = to_utf8(cleanme);
setme.assign(tmp ? tmp : "");
setme.assign(tmp != nullptr ? tmp : "");
tr_free(tmp);
}

View File

@ -66,7 +66,7 @@ std::optional<int64_t> ParseInt(std::string_view* benc)
}
// leading zeroes are not allowed
if ((walk[0] == '0' && isdigit(walk[1])) || (walk[0] == '-' && walk[1] == '0' && isdigit(walk[2])))
if ((walk[0] == '0' && (isdigit(walk[1]) != 0)) || (walk[0] == '-' && walk[1] == '0' && (isdigit(walk[2]) != 0)))
{
return {};
}

View File

@ -571,7 +571,7 @@ static void jsonStringFunc(tr_variant const* val, void* vdata)
break;
default:
if (isprint((unsigned char)sv.front()))
if (isprint((unsigned char)sv.front()) != 0)
{
*outwalk++ = sv.front();
}

View File

@ -5,7 +5,7 @@
#if defined(HAVE_USELOCALE) && (!defined(_XOPEN_SOURCE) || _XOPEN_SOURCE < 700)
#undef _XOPEN_SOURCE
#define _XOPEN_SOURCE 700
#define XOPEN_SOURCE 700 // NOLINT
#endif
#if defined(HAVE_USELOCALE) && !defined(_GNU_SOURCE)
@ -479,7 +479,7 @@ void tr_variantInitStrView(tr_variant* v, std::string_view str)
void tr_variantInitBool(tr_variant* v, bool value)
{
tr_variantInit(v, TR_VARIANT_TYPE_BOOL);
v->val.b = value != 0;
v->val.b = value;
}
void tr_variantInitReal(tr_variant* v, double value)
@ -1105,7 +1105,7 @@ void tr_variantMergeDicts(tr_variant* target, tr_variant const* source)
// if types differ, ensure that target will overwrite source
auto const* const target_child = tr_variantDictFind(target, key);
if (target_child && !tr_variantIsType(target_child, val->type))
if ((target_child != nullptr) && !tr_variantIsType(target_child, val->type))
{
tr_variantDictRemove(target, key);
}
@ -1237,7 +1237,7 @@ bool tr_variantFromBuf(tr_variant* setme, int opts, std::string_view buf, char c
use_numeric_locale(&locale_ctx, "C");
auto success = bool{};
if (opts & TR_VARIANT_PARSE_BENC)
if ((opts & TR_VARIANT_PARSE_BENC) != 0)
{
success = tr_variantParseBenc(*setme, opts, buf, setme_end, error);
}
@ -1245,7 +1245,7 @@ bool tr_variantFromBuf(tr_variant* setme, int opts, std::string_view buf, char c
{
// TODO: tr_variantParseJson() should take a tr_error* same as ParseBenc
auto err = tr_variantParseJson(*setme, opts, buf, setme_end);
if (err)
if (err != 0)
{
tr_error_set(error, EILSEQ, "error parsing encoded data"sv);
}

View File

@ -38,7 +38,7 @@ static bool verifyTorrent(tr_torrent* tor, bool const* stopFlag)
time_t lastSleptAt = 0;
uint32_t piecePos = 0;
tr_file_index_t fileIndex = 0;
tr_file_index_t prevFileIndex = !fileIndex;
tr_file_index_t prevFileIndex = ~0;
tr_piece_index_t piece = 0;
auto buffer = std::vector<std::byte>(1024 * 256);
auto sha = tr_sha1_init();

View File

@ -144,7 +144,7 @@ static void tr_watchdir_on_retry_timer(evutil_socket_t /*fd*/, short /*type*/, v
TR_ASSERT(context != nullptr);
auto* const retry = static_cast<tr_watchdir_retry*>(context);
tr_watchdir_t const handle = retry->handle;
auto const handle = retry->handle;
if (tr_watchdir_process_impl(handle, retry->name) == TR_WATCHDIR_RETRY)
{
@ -325,7 +325,7 @@ void tr_watchdir_scan(tr_watchdir_t handle, std::unordered_set<std::string>* dir
auto new_dir_entries = std::unordered_set<std::string>{};
tr_error* error = nullptr;
tr_sys_dir_t const dir = tr_sys_dir_open(handle->path, &error);
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);

View File

@ -414,7 +414,7 @@ std::string tr_urlPercentDecode(std::string_view in)
}
in.remove_prefix(pos);
if (std::size(in) >= 3 && in[0] == '%' && std::isxdigit(in[1]) && std::isxdigit(in[2]))
if (std::size(in) >= 3 && in[0] == '%' && (std::isxdigit(in[1]) != 0) && (std::isxdigit(in[2]) != 0))
{
auto hexstr = std::array<char, 3>{ in[1], in[2], '\0' };
auto const hex = strtoul(std::data(hexstr), nullptr, 16);

View File

@ -150,7 +150,7 @@ static int sockoptfunction(void* vtask, curl_socket_t fd, curlsocktype /*purpose
static CURLcode ssl_context_func(CURL* /*curl*/, void* ssl_ctx, void* /*user_data*/)
{
tr_x509_store_t const cert_store = tr_ssl_get_x509_store(ssl_ctx);
auto const cert_store = tr_ssl_get_x509_store(ssl_ctx);
if (cert_store == nullptr)
{
return CURLE_OK;
@ -490,7 +490,7 @@ static void tr_webThreadFunc(void* vsession)
auto numfds = int{};
curl_multi_wait(multi, nullptr, 0, msec, &numfds);
if (!numfds)
if (numfds == 0)
{
repeats++;
if (repeats > 1)

View File

@ -309,7 +309,7 @@ static void on_content_changed(struct evbuffer* buf, struct evbuffer_cb_info con
session,
connection_succeeded,
new connection_succeeded_data{ w,
real_url ? real_url : "",
real_url != nullptr ? real_url : "",
task->piece_index,
task->piece_offset + task->blocks_done * task->block_size + len - 1 });
}