refactor: modernize-avoid-c-arrays pt. 1 (#3702)

This commit is contained in:
Charles Kerr 2022-08-24 20:19:21 -05:00 committed by GitHub
parent e8686095ed
commit e191407dee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 181 additions and 145 deletions

View File

@ -4,6 +4,7 @@
// License text can be found in the licenses/ folder.
#include <algorithm>
#include <array>
#include <cstdio>
#include <cstdlib> // bsearch()
#include <string_view>
@ -227,11 +228,12 @@ bool BlocklistFile::parseLine2(std::string_view line, struct IPv4Range* range)
*/
bool BlocklistFile::parseLine3(char const* line, IPv4Range* range)
{
unsigned int ip[4];
auto ip = std::array<unsigned int, 4>{};
unsigned int pflen = 0;
uint32_t ip_u = 0;
uint32_t mask = 0xffffffff;
// NOLINTNEXTLINE readability-container-data-pointer
if (sscanf(line, "%u.%u.%u.%u/%u", TR_ARG_TUPLE(&ip[0], &ip[1], &ip[2], &ip[3]), &pflen) != 5)
{
return false;
@ -266,7 +268,7 @@ bool BlocklistFile::compareAddressRangesByFirstAddress(IPv4Range const& a, IPv4R
size_t BlocklistFile::setContent(char const* filename)
{
int inCount = 0;
char line[2048];
auto line = std::array<char, 2048>{};
tr_error* error = nullptr;
if (filename == nullptr)
@ -307,13 +309,13 @@ size_t BlocklistFile::setContent(char const* filename)
/* load the rules into memory */
std::vector<IPv4Range> ranges;
while (tr_sys_file_read_line(in, line, sizeof(line)))
while (tr_sys_file_read_line(in, std::data(line), std::size(line)))
{
IPv4Range range = {};
++inCount;
if (!parseLine(line, &range))
if (!parseLine(std::data(line), &range))
{
/* don't try to display the actual lines - it causes issues */
tr_logAddWarn(fmt::format(_("Couldn't parse line: '{line}'"), fmt::arg("line", inCount)));

View File

@ -37,8 +37,6 @@ static void log_openssl_error(char const* file, int line)
if (tr_logLevelIsActive(TR_LOG_ERROR))
{
char buf[512];
#ifndef TR_LIGHTWEIGHT
static bool strings_loaded = false;
@ -56,7 +54,8 @@ static void log_openssl_error(char const* file, int line)
#endif
ERR_error_string_n(error_code, buf, sizeof(buf));
auto buf = std::array<char, 512>{};
ERR_error_string_n(error_code, std::data(buf), std::size(buf));
tr_logAddMessage(
file,
line,
@ -64,7 +63,7 @@ static void log_openssl_error(char const* file, int line)
fmt::format(
_("{crypto_library} error: {error} ({error_code})"),
fmt::arg("crypto_library", "OpenSSL"),
fmt::arg("error", buf),
fmt::arg("error", std::data(buf)),
fmt::arg("error_code", error_code)));
}
}

View File

@ -6,7 +6,6 @@
#include <algorithm>
#include <array>
#include <cctype>
#include <cstring> // memmove(), memset()
#include <iterator>
#include <random>
#include <string>
@ -63,6 +62,8 @@ int tr_rand_int_weak(int upper_bound)
namespace
{
namespace ssha1_impl
{
auto constexpr DigestStringSize = TR_SHA1_DIGEST_STRLEN;
auto constexpr SaltedPrefix = "{"sv;
@ -79,10 +80,13 @@ std::string tr_salt(std::string_view plaintext, std::string_view salt)
return fmt::format(FMT_STRING("{:s}{:s}{:s}"), SaltedPrefix, tr_sha1_to_string(digest), salt);
}
} // namespace ssha1_impl
} // namespace
std::string tr_ssha1(std::string_view plaintext)
{
using namespace ssha1_impl;
// build an array of random Salter chars
auto constexpr Salter = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ./"sv;
static_assert(std::size(Salter) == 64);
@ -100,11 +104,15 @@ std::string tr_ssha1(std::string_view plaintext)
bool tr_ssha1_test(std::string_view text)
{
using namespace ssha1_impl;
return tr_strvStartsWith(text, SaltedPrefix) && std::size(text) >= std::size(SaltedPrefix) + DigestStringSize;
}
bool tr_ssha1_matches(std::string_view ssha1, std::string_view plaintext)
{
using namespace ssha1_impl;
if (!tr_ssha1_test(ssha1))
{
return false;
@ -118,7 +126,12 @@ bool tr_ssha1_matches(std::string_view ssha1, std::string_view plaintext)
****
***/
static size_t base64_alloc_size(std::string_view input)
namespace
{
namespace base64_impl
{
constexpr size_t base64AllocSize(std::string_view input)
{
size_t ret_length = 4 * ((std::size(input) + 2) / 3); // NOLINT misc-const-correctness
#ifdef USE_SYSTEM_B64
@ -128,9 +141,14 @@ static size_t base64_alloc_size(std::string_view input)
return ret_length * 8;
}
} // namespace base64_impl
} // namespace
std::string tr_base64_encode(std::string_view input)
{
auto buf = std::vector<char>(base64_alloc_size(input));
using namespace base64_impl;
auto buf = std::vector<char>(base64AllocSize(input));
auto state = base64_encodestate{};
base64_init_encodestate(&state);
size_t len = base64_encode_block(std::data(input), std::size(input), std::data(buf), &state);
@ -157,9 +175,14 @@ std::string tr_base64_decode(std::string_view input)
****
***/
static void tr_binary_to_hex(void const* vinput, void* voutput, size_t byte_length)
namespace
{
static char constexpr Hex[] = "0123456789abcdef";
namespace hex_impl
{
constexpr void tr_binary_to_hex(void const* vinput, void* voutput, size_t byte_length)
{
auto constexpr Hex = "0123456789abcdef"sv;
auto const* input = static_cast<uint8_t const*>(vinput);
auto* output = static_cast<char*>(voutput);
@ -178,8 +201,27 @@ static void tr_binary_to_hex(void const* vinput, void* voutput, size_t byte_leng
}
}
constexpr void tr_hex_to_binary(char const* input, void* voutput, size_t byte_length)
{
auto constexpr Hex = "0123456789abcdef"sv;
auto* output = static_cast<uint8_t*>(voutput);
for (size_t i = 0; i < byte_length; ++i)
{
auto const upper_nibble = Hex.find(std::tolower(*input++));
auto const lower_nibble = Hex.find(std::tolower(*input++));
*output++ = (uint8_t)((upper_nibble << 4) | lower_nibble);
}
}
} // namespace hex_impl
} // namespace
std::string tr_sha1_to_string(tr_sha1_digest_t const& digest)
{
using namespace hex_impl;
auto str = std::string(std::size(digest) * 2, '?');
tr_binary_to_hex(std::data(digest), std::data(str), std::size(digest));
return str;
@ -187,27 +229,17 @@ std::string tr_sha1_to_string(tr_sha1_digest_t const& digest)
std::string tr_sha256_to_string(tr_sha256_digest_t const& digest)
{
using namespace hex_impl;
auto str = std::string(std::size(digest) * 2, '?');
tr_binary_to_hex(std::data(digest), std::data(str), std::size(digest));
return str;
}
static void tr_hex_to_binary(char const* input, void* voutput, size_t byte_length)
{
static char constexpr Hex[] = "0123456789abcdef";
auto* output = static_cast<uint8_t*>(voutput);
for (size_t i = 0; i < byte_length; ++i)
{
int const hi = strchr(Hex, tolower(*input++)) - Hex;
int const lo = strchr(Hex, tolower(*input++)) - Hex;
*output++ = (uint8_t)((hi << 4) | lo);
}
}
std::optional<tr_sha1_digest_t> tr_sha1_from_string(std::string_view hex)
{
using namespace hex_impl;
if (std::size(hex) != TR_SHA1_DIGEST_STRLEN)
{
return {};
@ -225,6 +257,8 @@ std::optional<tr_sha1_digest_t> tr_sha1_from_string(std::string_view hex)
std::optional<tr_sha256_digest_t> tr_sha256_from_string(std::string_view hex)
{
using namespace hex_impl;
if (std::size(hex) != TR_SHA256_DIGEST_STRLEN)
{
return {};

View File

@ -166,24 +166,24 @@ struct tr_handshake
#define tr_logAddTraceHand(handshake, msg) tr_logAddTrace(msg, (handshake)->io->addrStr())
static char const* getStateName(handshake_state_t const state)
static constexpr std::string_view getStateName(handshake_state_t const state)
{
static char const* const state_strings[N_STATES] = {
"awaiting handshake", /* AWAITING_HANDSHAKE */
"awaiting peer id", /* AWAITING_PEER_ID */
"awaiting ya", /* AWAITING_YA */
"awaiting pad a", /* AWAITING_PAD_A */
"awaiting crypto_provide", /* AWAITING_CRYPTO_PROVIDE */
"awaiting pad c", /* AWAITING_PAD_C */
"awaiting ia", /* AWAITING_IA */
"awaiting payload stream", /* AWAITING_PAYLOAD_STREAM */
"awaiting yb", /* AWAITING_YB */
"awaiting vc", /* AWAITING_VC */
"awaiting crypto select", /* AWAITING_CRYPTO_SELECT */
"awaiting pad d" /* AWAITING_PAD_D */
auto StateStrings = std::array<std::string_view, N_STATES>{
"awaiting handshake"sv, /* AWAITING_HANDSHAKE */
"awaiting peer id"sv, /* AWAITING_PEER_ID */
"awaiting ya"sv, /* AWAITING_YA */
"awaiting pad a"sv, /* AWAITING_PAD_A */
"awaiting crypto_provide"sv, /* AWAITING_CRYPTO_PROVIDE */
"awaiting pad c"sv, /* AWAITING_PAD_C */
"awaiting ia"sv, /* AWAITING_IA */
"awaiting payload stream"sv, /* AWAITING_PAYLOAD_STREAM */
"awaiting yb"sv, /* AWAITING_YB */
"awaiting vc"sv, /* AWAITING_VC */
"awaiting crypto select"sv, /* AWAITING_CRYPTO_SELECT */
"awaiting pad d"sv /* AWAITING_PAD_D */
};
return state < N_STATES ? state_strings[state] : "unknown state";
return state < N_STATES ? StateStrings[state] : "unknown state"sv;
}
static void setState(tr_handshake* handshake, handshake_state_t state)
@ -241,9 +241,6 @@ enum handshake_parse_err_t
static handshake_parse_err_t parseHandshake(tr_handshake* handshake, struct evbuffer* inbuf)
{
uint8_t name[HANDSHAKE_NAME_LEN];
uint8_t reserved[HANDSHAKE_FLAGS_LEN];
tr_logAddTraceHand(handshake, fmt::format("payload: need {}, got {}", HANDSHAKE_SIZE, evbuffer_get_length(inbuf)));
if (evbuffer_get_length(inbuf) < HANDSHAKE_SIZE)
@ -252,15 +249,16 @@ static handshake_parse_err_t parseHandshake(tr_handshake* handshake, struct evbu
}
/* confirm the protocol */
tr_peerIoReadBytes(handshake->io, inbuf, name, HANDSHAKE_NAME_LEN);
if (memcmp(name, HANDSHAKE_NAME, HANDSHAKE_NAME_LEN) != 0)
auto name = std::array<uint8_t, HANDSHAKE_NAME_LEN>{};
tr_peerIoReadBytes(handshake->io, inbuf, std::data(name), std::size(name));
if (memcmp(std::data(name), HANDSHAKE_NAME, std::size(name)) != 0)
{
return HANDSHAKE_ENCRYPTION_WRONG;
}
/* read the reserved bytes */
tr_peerIoReadBytes(handshake->io, inbuf, reserved, HANDSHAKE_FLAGS_LEN);
auto reserved = std::array<uint8_t, HANDSHAKE_FLAGS_LEN>{};
tr_peerIoReadBytes(handshake->io, inbuf, std::data(reserved), std::size(reserved));
/* torrent hash */
auto hash = tr_sha1_digest_t{};
@ -341,33 +339,33 @@ static uint32_t getCryptoProvide(tr_handshake const* handshake)
return provide;
}
static uint32_t getCryptoSelect(tr_handshake const* handshake, uint32_t crypto_provide)
static constexpr uint32_t getCryptoSelect(tr_encryption_mode encryption_mode, uint32_t crypto_provide)
{
uint32_t choices[2];
int nChoices = 0;
auto choices = std::array<uint32_t, 2>{};
int n_choices = 0;
switch (handshake->encryption_mode)
switch (encryption_mode)
{
case TR_ENCRYPTION_REQUIRED:
choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
choices[n_choices++] = CRYPTO_PROVIDE_CRYPTO;
break;
case TR_ENCRYPTION_PREFERRED:
choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
choices[nChoices++] = CRYPTO_PROVIDE_PLAINTEXT;
choices[n_choices++] = CRYPTO_PROVIDE_CRYPTO;
choices[n_choices++] = CRYPTO_PROVIDE_PLAINTEXT;
break;
case TR_CLEAR_PREFERRED:
choices[nChoices++] = CRYPTO_PROVIDE_PLAINTEXT;
choices[nChoices++] = CRYPTO_PROVIDE_CRYPTO;
choices[n_choices++] = CRYPTO_PROVIDE_PLAINTEXT;
choices[n_choices++] = CRYPTO_PROVIDE_CRYPTO;
break;
}
for (int i = 0; i < nChoices; ++i)
for (auto const& choice : choices)
{
if ((crypto_provide & choices[i]) != 0)
if ((crypto_provide & choice) != 0)
{
return choices[i];
return choice;
}
}
@ -448,10 +446,10 @@ static ReadState readYb(tr_handshake* handshake, struct evbuffer* inbuf)
evbuffer_add_uint16(outbuf, 0);
/* ENCRYPT len(IA)), ENCRYPT(IA) */
if (uint8_t msg[HANDSHAKE_SIZE]; buildHandshakeMessage(handshake, msg))
if (auto msg = std::array<uint8_t, HANDSHAKE_SIZE>{}; buildHandshakeMessage(handshake, std::data(msg)))
{
evbuffer_add_uint16(outbuf, sizeof(msg));
evbuffer_add(outbuf, msg, sizeof(msg));
evbuffer_add_uint16(outbuf, std::size(msg));
evbuffer_add(outbuf, std::data(msg), std::size(msg));
handshake->haveSentBitTorrentHandshake = true;
}
else
@ -607,18 +605,18 @@ static ReadState readHandshake(tr_handshake* handshake, struct evbuffer* inbuf)
/* pstr (BitTorrent) */
TR_ASSERT(pstrlen == 19);
uint8_t pstr[20];
tr_peerIoReadBytes(handshake->io, inbuf, pstr, pstrlen);
auto pstr = std::array<uint8_t, 20>{};
tr_peerIoReadBytes(handshake->io, inbuf, std::data(pstr), pstrlen);
pstr[pstrlen] = '\0';
if (strncmp((char const*)pstr, "BitTorrent protocol", 19) != 0)
if (strncmp(reinterpret_cast<char const*>(std::data(pstr)), "BitTorrent protocol", 19) != 0)
{
return tr_handshakeDone(handshake, false);
}
/* reserved bytes */
uint8_t reserved[HANDSHAKE_FLAGS_LEN];
tr_peerIoReadBytes(handshake->io, inbuf, reserved, sizeof(reserved));
auto reserved = std::array<uint8_t, HANDSHAKE_FLAGS_LEN>{};
tr_peerIoReadBytes(handshake->io, inbuf, std::data(reserved), std::size(reserved));
/**
*** Extensions
@ -659,14 +657,14 @@ static ReadState readHandshake(tr_handshake* handshake, struct evbuffer* inbuf)
if (!handshake->haveSentBitTorrentHandshake)
{
uint8_t msg[HANDSHAKE_SIZE];
auto msg = std::array<uint8_t, HANDSHAKE_SIZE>{};
if (!buildHandshakeMessage(handshake, msg))
if (!buildHandshakeMessage(handshake, std::data(msg)))
{
return tr_handshakeDone(handshake, false);
}
tr_peerIoWriteBytes(handshake->io, msg, sizeof(msg), false);
tr_peerIoWriteBytes(handshake->io, std::data(msg), std::size(msg), false);
handshake->haveSentBitTorrentHandshake = true;
}
@ -685,9 +683,11 @@ static ReadState readPeerId(tr_handshake* handshake, struct evbuffer* inbuf)
tr_peerIoReadBytes(handshake->io, inbuf, std::data(peer_id), std::size(peer_id));
handshake->peer_id = peer_id;
char client[128] = {};
tr_clientForId(client, sizeof(client), peer_id);
tr_logAddTraceHand(handshake, fmt::format("peer-id is '{}' ... isIncoming is {}", client, handshake->isIncoming()));
auto client = std::array<char, 128>{};
tr_clientForId(std::data(client), std::size(client), peer_id);
tr_logAddTraceHand(
handshake,
fmt::format("peer-id is '{}' ... isIncoming is {}", std::data(client), handshake->isIncoming()));
// if we've somehow connected to ourselves, don't keep the connection
auto const hash = handshake->io->torrentHash();
@ -865,7 +865,7 @@ static ReadState readIA(tr_handshake* handshake, struct evbuffer const* inbuf)
evbuffer_add(outbuf, std::data(VC), std::size(VC));
/* send crypto_select */
uint32_t const crypto_select = getCryptoSelect(handshake, handshake->crypto_provide);
uint32_t const crypto_select = getCryptoSelect(handshake->encryption_mode, handshake->crypto_provide);
if (crypto_select != 0)
{
@ -898,9 +898,9 @@ static ReadState readIA(tr_handshake* handshake, struct evbuffer const* inbuf)
tr_logAddTraceHand(handshake, "sending handshake");
/* send our handshake */
if (uint8_t msg[HANDSHAKE_SIZE]; buildHandshakeMessage(handshake, msg))
if (auto msg = std::array<uint8_t, HANDSHAKE_SIZE>{}; buildHandshakeMessage(handshake, std::data(msg)))
{
evbuffer_add(outbuf, msg, sizeof(msg));
evbuffer_add(outbuf, std::data(msg), std::size(msg));
handshake->haveSentBitTorrentHandshake = true;
}
else
@ -1097,11 +1097,11 @@ static void gotError(tr_peerIo* io, short what, void* vhandshake)
if (tr_peerIoReconnect(handshake->io) == 0)
{
uint8_t msg[HANDSHAKE_SIZE];
buildHandshakeMessage(handshake, msg);
auto msg = std::array<uint8_t, HANDSHAKE_SIZE>{};
buildHandshakeMessage(handshake, std::data(msg));
handshake->haveSentBitTorrentHandshake = true;
setReadState(handshake, AWAITING_HANDSHAKE);
tr_peerIoWriteBytes(handshake->io, msg, sizeof(msg), false);
tr_peerIoWriteBytes(handshake->io, std::data(msg), std::size(msg), false);
}
}
@ -1111,13 +1111,12 @@ static void gotError(tr_peerIo* io, short what, void* vhandshake)
if ((handshake->state == AWAITING_YB || handshake->state == AWAITING_VC) &&
handshake->encryption_mode != TR_ENCRYPTION_REQUIRED && tr_peerIoReconnect(handshake->io) == 0)
{
uint8_t msg[HANDSHAKE_SIZE];
auto msg = std::array<uint8_t, HANDSHAKE_SIZE>{};
tr_logAddTraceHand(handshake, "handshake failed, trying plaintext...");
buildHandshakeMessage(handshake, msg);
buildHandshakeMessage(handshake, std::data(msg));
handshake->haveSentBitTorrentHandshake = true;
setReadState(handshake, AWAITING_HANDSHAKE);
tr_peerIoWriteBytes(handshake->io, msg, sizeof(msg), false);
tr_peerIoWriteBytes(handshake->io, std::data(msg), std::size(msg), false);
}
else
{
@ -1160,12 +1159,12 @@ tr_handshake* tr_handshakeNew(
}
else
{
uint8_t msg[HANDSHAKE_SIZE];
buildHandshakeMessage(handshake, msg);
auto msg = std::array<uint8_t, HANDSHAKE_SIZE>{};
buildHandshakeMessage(handshake, std::data(msg));
handshake->haveSentBitTorrentHandshake = true;
setReadState(handshake, AWAITING_HANDSHAKE);
tr_peerIoWriteBytes(handshake->io, msg, sizeof(msg), false);
tr_peerIoWriteBytes(handshake->io, std::data(msg), std::size(msg), false);
}
return handshake;

View File

@ -157,8 +157,6 @@ void logAddImpl(
}
else
{
char timestr[64];
tr_sys_file_t fp = tr_logGetFile();
if (fp == TR_BAD_SYS_FILE)
@ -166,12 +164,12 @@ void logAddImpl(
fp = tr_sys_file_get_std(TR_STD_SYS_FILE_ERR);
}
tr_logGetTimeStr(timestr, sizeof(timestr));
auto timestr = std::array<char, 64>{};
tr_logGetTimeStr(std::data(timestr), std::size(timestr));
tr_sys_file_write_line(
fp,
!std::empty(name) ? fmt::format(FMT_STRING("[{:s}] {:s}: {:s}"), timestr, name, msg) :
fmt::format(FMT_STRING("[{:s}] {:s}"), timestr, msg));
!std::empty(name) ? fmt::format(FMT_STRING("[{:s}] {:s}: {:s}"), std::data(timestr), name, msg) :
fmt::format(FMT_STRING("[{:s}] {:s}"), std::data(timestr), msg));
tr_sys_file_flush(fp);
}
#endif

View File

@ -3,9 +3,10 @@
// or any future license endorsed by Mnemosyne LLC.
// License text can be found in the licenses/ folder.
#include <array>
#include <cerrno>
#include <ctime>
#include <cstdint> // uint32_t
#include <ctime>
#include <event2/util.h> /* evutil_inet_ntop() */
@ -75,9 +76,9 @@ tr_port_forwarding tr_natpmp::pulse(tr_port private_port, bool is_enabled, tr_po
if (val >= 0)
{
char str[128];
evutil_inet_ntop(AF_INET, &response.pnu.publicaddress.addr, str, sizeof(str));
tr_logAddInfo(fmt::format(_("Found public address '{address}'"), fmt::arg("address", str)));
auto str = std::array<char, 128>{};
evutil_inet_ntop(AF_INET, &response.pnu.publicaddress.addr, std::data(str), std::size(str));
tr_logAddInfo(fmt::format(_("Found public address '{address}'"), fmt::arg("address", std::data(str))));
state_ = TR_NATPMP_IDLE;
}
else if (val != NATPMP_TRYAGAIN)

View File

@ -414,10 +414,10 @@ static tr_socket_t tr_netBindTCPImpl(tr_address const* addr, tr_port port, bool
{
TR_ASSERT(tr_address_is_valid(addr));
static int const domains[NUM_TR_AF_INET_TYPES] = { AF_INET, AF_INET6 };
static auto constexpr Domains = std::array<int, NUM_TR_AF_INET_TYPES>{ AF_INET, AF_INET6 };
struct sockaddr_storage sock;
auto const fd = socket(domains[addr->type], SOCK_STREAM, 0);
auto const fd = socket(Domains[addr->type], SOCK_STREAM, 0);
if (fd == TR_BAD_SOCKET)
{
*errOut = sockerrno;
@ -706,7 +706,7 @@ static int tr_globalAddress(int af, void* addr, int* addr_len)
/* Return our global IPv6 address, with caching. */
unsigned char const* tr_globalIPv6(tr_session const* session)
{
static unsigned char ipv6[16];
static auto ipv6 = std::array<unsigned char, 16>{};
static time_t last_time = 0;
static bool have_ipv6 = false;
@ -714,7 +714,7 @@ unsigned char const* tr_globalIPv6(tr_session const* session)
if (auto const now = tr_time(); last_time < now - 1800)
{
int addrlen = 16;
int const rc = tr_globalAddress(AF_INET6, ipv6, &addrlen);
int const rc = tr_globalAddress(AF_INET6, std::data(ipv6), &addrlen);
have_ipv6 = rc >= 0 && addrlen == 16;
last_time = now;
}
@ -724,11 +724,11 @@ unsigned char const* tr_globalIPv6(tr_session const* session)
return nullptr; /* No IPv6 address at all. */
}
/* Return the default address. This is useful for checking
for connectivity in general. */
/* Return the default address.
* This is useful for checking for connectivity in general. */
if (session == nullptr)
{
return ipv6;
return std::data(ipv6);
}
/* We have some sort of address, now make sure that we return
@ -738,10 +738,10 @@ unsigned char const* tr_globalIPv6(tr_session const* session)
if (!is_default)
{
/* Explicitly bound. Return that address. */
memcpy(ipv6, ipv6_bindaddr.addr.addr6.s6_addr, 16);
memcpy(std::data(ipv6), ipv6_bindaddr.addr.addr6.s6_addr, 16);
}
return ipv6;
return std::data(ipv6);
}
/***

View File

@ -4,6 +4,7 @@
// License text can be found in the licenses/ folder.
#include <algorithm>
#include <array>
#include <cerrno>
#include <cstdint>
#include <cstring>
@ -1004,16 +1005,15 @@ void tr_peerIoReadUint32(tr_peerIo* io, struct evbuffer* inbuf, uint32_t* setme)
*setme = ntohl(tmp);
}
void tr_peerIoDrain(tr_peerIo* io, struct evbuffer* inbuf, size_t byteCount)
void tr_peerIoDrain(tr_peerIo* io, struct evbuffer* inbuf, size_t byte_count)
{
char buf[4096];
size_t const buflen = sizeof(buf);
auto buf = std::array<char, 4096>{};
while (byteCount > 0)
while (byte_count > 0)
{
size_t const thisPass = std::min(byteCount, buflen);
tr_peerIoReadBytes(io, inbuf, buf, thisPass);
byteCount -= thisPass;
size_t const this_pass = std::min(byte_count, std::size(buf));
tr_peerIoReadBytes(io, inbuf, std::data(buf), this_pass);
byte_count -= this_pass;
}
}

View File

@ -398,7 +398,7 @@ void tr_peerIoReadUint16(tr_peerIo* io, struct evbuffer* inbuf, uint16_t* setme)
void tr_peerIoReadUint32(tr_peerIo* io, struct evbuffer* inbuf, uint32_t* setme);
void tr_peerIoDrain(tr_peerIo* io, struct evbuffer* inbuf, size_t byteCount);
void tr_peerIoDrain(tr_peerIo* io, struct evbuffer* inbuf, size_t byte_count);
/**
***

View File

@ -4,6 +4,7 @@
// License text can be found in the licenses/ folder.
#include <algorithm>
#include <array>
#include <cerrno> /* error codes ERANGE, ... */
#include <chrono>
#include <climits> /* INT_MAX */
@ -1221,9 +1222,9 @@ static bool on_handshake_done(tr_handshake_result const& result)
auto client = tr_quark{ TR_KEY_NONE };
if (result.peer_id)
{
char buf[128] = {};
tr_clientForId(buf, sizeof(buf), *result.peer_id);
client = tr_quark_new(buf);
auto buf = std::array<char, 128>{};
tr_clientForId(std::data(buf), sizeof(buf), *result.peer_id);
client = tr_quark_new(std::data(buf));
}
/* this steals its refcount too, which is balanced by our unref in peerDelete() */

View File

@ -88,8 +88,8 @@ static std::string getHomeDir()
struct passwd pwent;
struct passwd* pw = nullptr;
char buf[4096];
getpwuid_r(getuid(), &pwent, buf, sizeof buf, &pw);
auto buf = std::array<char, 4096>{};
getpwuid_r(getuid(), &pwent, std::data(buf), std::size(buf), &pw);
if (pw != nullptr)
{
return pw->pw_dir;

View File

@ -57,9 +57,9 @@ static size_t addPeers(tr_torrent* tor, uint8_t const* buf, size_t buflen)
size_t const n_in = buflen / sizeof(tr_pex);
size_t const n_pex = std::min(n_in, size_t{ MAX_REMEMBERED_PEERS });
tr_pex pex[MAX_REMEMBERED_PEERS];
memcpy(pex, buf, sizeof(tr_pex) * n_pex);
return tr_peerMgrAddPex(tor, TR_PEER_FROM_RESUME, pex, n_pex);
auto pex = std::array<tr_pex, MAX_REMEMBERED_PEERS>{};
memcpy(std::data(pex), buf, sizeof(tr_pex) * n_pex);
return tr_peerMgrAddPex(tor, TR_PEER_FROM_RESUME, std::data(pex), n_pex);
}
static auto loadPeers(tr_variant* dict, tr_torrent* tor)

View File

@ -170,27 +170,27 @@ static evbuffer* make_response(struct evhttp_request* req, tr_rpc_server* server
{
auto const max_compressed_len = libdeflate_deflate_compress_bound(server->compressor.get(), std::size(content));
struct evbuffer_iovec iovec[1];
evbuffer_reserve_space(out, std::max(std::size(content), max_compressed_len), iovec, 1);
struct evbuffer_iovec iovec;
evbuffer_reserve_space(out, std::max(std::size(content), max_compressed_len), &iovec, 1);
auto const compressed_len = libdeflate_gzip_compress(
server->compressor.get(),
std::data(content),
std::size(content),
iovec[0].iov_base,
iovec[0].iov_len);
iovec.iov_base,
iovec.iov_len);
if (0 < compressed_len && compressed_len < std::size(content))
{
iovec[0].iov_len = compressed_len;
iovec.iov_len = compressed_len;
evhttp_add_header(req->output_headers, "Content-Encoding", "gzip");
}
else
{
std::copy(std::begin(content), std::end(content), static_cast<char*>(iovec[0].iov_base));
iovec[0].iov_len = std::size(content);
std::copy(std::begin(content), std::end(content), static_cast<char*>(iovec.iov_base));
iovec.iov_len = std::size(content);
}
evbuffer_commit_space(out, iovec, 1);
evbuffer_commit_space(out, &iovec, 1);
}
return out;
@ -565,10 +565,10 @@ static char const* tr_rpc_address_to_string(tr_rpc_address const& addr, char* bu
static std::string tr_rpc_address_with_port(tr_rpc_server const* server)
{
char addr_buf[TrUnixAddrStrLen];
tr_rpc_address_to_string(*server->bindAddress, addr_buf, sizeof(addr_buf));
auto addr_buf = std::array<char, TrUnixAddrStrLen>{};
tr_rpc_address_to_string(*server->bindAddress, std::data(addr_buf), std::size(addr_buf));
std::string addr_port_str{ addr_buf };
std::string addr_port_str = std::data(addr_buf);
if (server->bindAddress->type != TR_RPC_AF_UNIX)
{
addr_port_str.append(":" + std::to_string(server->port().host()));

View File

@ -41,9 +41,9 @@ struct tr_ctor
tr_priority_t priority = TR_PRI_NORMAL;
tr_torrent::labels_t labels = {};
tr_torrent::labels_t labels{};
struct optional_args optional_args[2];
std::array<struct optional_args, 2> optional_args{};
std::string incomplete_dir;
std::string torrent_filename;

View File

@ -2,6 +2,7 @@
// It may be used under the MIT (SPDX: MIT) license.
// License text can be found in the licenses/ folder.
#include <array>
#include <cerrno>
#include <cstdint>
#include <cstring> /* memcmp(), memcpy(), memset() */
@ -228,12 +229,13 @@ static void event_callback(evutil_socket_t s, [[maybe_unused]] short type, void*
TR_ASSERT(vsession != nullptr);
TR_ASSERT(type == EV_READ);
unsigned char buf[4096];
auto buf = std::array<unsigned char, 4096>{};
struct sockaddr_storage from;
auto* session = static_cast<tr_session*>(vsession);
socklen_t fromlen = sizeof(from);
int const rc = recvfrom(s, reinterpret_cast<char*>(buf), 4096 - 1, 0, (struct sockaddr*)&from, &fromlen);
int const
rc = recvfrom(s, reinterpret_cast<char*>(std::data(buf)), std::size(buf) - 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:
@ -249,12 +251,12 @@ static void event_callback(evutil_socket_t s, [[maybe_unused]] short type, void*
if (session->allowsDHT())
{
buf[rc] = '\0'; /* required by the DHT code */
tr_dhtCallback(buf, rc, (struct sockaddr*)&from, fromlen, vsession);
tr_dhtCallback(std::data(buf), rc, (struct sockaddr*)&from, fromlen, vsession);
}
}
else if (rc >= 8 && buf[0] == 0 && buf[1] == 0 && buf[2] == 0 && buf[3] <= 3)
{
if (!tau_handle_message(session, buf, rc))
if (!tau_handle_message(session, std::data(buf), rc))
{
tr_logAddTrace("Couldn't parse UDP tracker packet.");
}
@ -263,7 +265,7 @@ static void event_callback(evutil_socket_t s, [[maybe_unused]] short type, void*
{
if (session->allowsUTP())
{
if (!tr_utpPacket(buf, rc, (struct sockaddr*)&from, fromlen, session))
if (!tr_utpPacket(std::data(buf), rc, (struct sockaddr*)&from, fromlen, session))
{
tr_logAddTrace("Unexpected UDP packet");
}

View File

@ -421,17 +421,17 @@ struct jsonWalk
static void jsonIndent(struct jsonWalk* data)
{
static char buf[1024] = { '\0' };
static auto buf = std::array<char, 1024>{};
if (*buf == '\0')
if (buf.front() == '\0')
{
memset(buf, ' ', sizeof(buf));
memset(std::data(buf), ' ', std::size(buf));
buf[0] = '\n';
}
if (data->doIndent)
{
evbuffer_add(data->out, buf, std::size(data->parents) * 4 + 1);
evbuffer_add(data->out, std::data(buf), std::size(data->parents) * 4 + 1);
}
}