refactor: cppcoreguidelines-init-variables pt. 11 (#2012)

* refactor: uninit vars in bandwidth.cc

* refactor: uninit vars in cache.cc

* refactor: uninit vars in fdlimit.cc

* refactor: uninit vars in inout.cc

* refactor: uninit vars in platform.cc

* refactor: uninit vars in log.cc

* refactor: uninit vars in tr-utp.cc

* refactor: uninit vars in stats.cc

* refactor: uninit vars in trevent.cc

* refactor: uninit vars in session-id.cc

* fixup! refactor: uninit vars in cache.cc

* refactor: uninit vars in upnp.cc

* refactor: uninit vars in file.cc

* refactor: uninit vars in tr-lpd.cc

* refactor: uninit vars in tr-udp.cc
This commit is contained in:
Charles Kerr
2021-10-23 10:43:15 -05:00
committed by GitHub
parent 4996f3356a
commit a127826d76
14 changed files with 120 additions and 180 deletions

View File

@@ -250,18 +250,14 @@ unsigned int Bandwidth::clamp(uint64_t now, tr_direction dir, unsigned int byte_
* clamp down harder on the bytes available */ * clamp down harder on the bytes available */
if (byte_count > 0) if (byte_count > 0)
{ {
double current;
double desired;
double r;
if (now == 0) if (now == 0)
{ {
now = tr_time_msec(); now = tr_time_msec();
} }
current = this->getRawSpeedBytesPerSecond(now, TR_DOWN); auto const current = this->getRawSpeedBytesPerSecond(now, TR_DOWN);
desired = this->getDesiredSpeedBytesPerSecond(TR_DOWN); auto const desired = this->getDesiredSpeedBytesPerSecond(TR_DOWN);
r = desired >= 1 ? current / desired : 0; auto const r = desired >= 1 ? double(current) / desired : 0;
if (r > 1.0) if (r > 1.0)
{ {

View File

@@ -128,6 +128,7 @@ enum
* - Stale runs, runs sitting in cache for a long time or runs not growing, get priority. * - Stale runs, runs sitting in cache for a long time or runs not growing, get priority.
* Returns number of runs. * Returns number of runs.
*/ */
// TODO: return std::vector
static int calcRuns(tr_cache const* cache, struct run_info* runs) static int calcRuns(tr_cache const* cache, struct run_info* runs)
{ {
int const n = tr_ptrArraySize(&cache->blocks); int const n = tr_ptrArraySize(&cache->blocks);
@@ -403,13 +404,9 @@ int tr_cacheFlushDone(tr_cache* cache)
if (tr_ptrArraySize(&cache->blocks) > 0) if (tr_ptrArraySize(&cache->blocks) > 0)
{ {
int i; auto* const runs = tr_new(struct run_info, tr_ptrArraySize(&cache->blocks));
int n; int i = 0;
struct run_info* runs; int const n = calcRuns(cache, runs);
runs = tr_new(struct run_info, tr_ptrArraySize(&cache->blocks));
i = 0;
n = calcRuns(cache, runs);
while (i < n && (runs[i].is_piece_done || runs[i].is_multi_piece)) while (i < n && (runs[i].is_piece_done || runs[i].is_multi_piece))
{ {
@@ -425,16 +422,15 @@ int tr_cacheFlushDone(tr_cache* cache)
int tr_cacheFlushFile(tr_cache* cache, tr_torrent* torrent, tr_file_index_t i) int tr_cacheFlushFile(tr_cache* cache, tr_torrent* torrent, tr_file_index_t i)
{ {
int pos; auto first = tr_block_index_t{};
int err = 0; auto last = tr_block_index_t{};
tr_block_index_t first;
tr_block_index_t last;
tr_torGetFileBlockRange(torrent, i, &first, &last); tr_torGetFileBlockRange(torrent, i, &first, &last);
pos = findBlockPos(cache, torrent, first);
int pos = findBlockPos(cache, torrent, first);
dbgmsg("flushing file %d from cache to disk: blocks [%zu...%zu]", (int)i, (size_t)first, (size_t)last); dbgmsg("flushing file %d from cache to disk: blocks [%zu...%zu]", (int)i, (size_t)first, (size_t)last);
/* flush out all the blocks in that file */ /* flush out all the blocks in that file */
int err = 0;
while (err == 0 && pos < tr_ptrArraySize(&cache->blocks)) while (err == 0 && pos < tr_ptrArraySize(&cache->blocks))
{ {
auto const* b = static_cast<struct cache_block const*>(tr_ptrArrayNth(&cache->blocks, pos)); auto const* b = static_cast<struct cache_block const*>(tr_ptrArrayNth(&cache->blocks, pos));

View File

@@ -92,7 +92,7 @@ static bool preallocate_file_full(tr_sys_file_t fd, uint64_t length, tr_error**
while (success && length > 0) while (success && length > 0)
{ {
uint64_t const thisPass = std::min(length, uint64_t{ sizeof(buf) }); uint64_t const thisPass = std::min(length, uint64_t{ sizeof(buf) });
uint64_t bytes_written; uint64_t bytes_written = 0;
success = tr_sys_file_write(fd, buf, thisPass, &bytes_written, &my_error); success = tr_sys_file_write(fd, buf, thisPass, &bytes_written, &my_error);
length -= bytes_written; length -= bytes_written;
} }
@@ -147,6 +147,7 @@ static void cached_file_close(struct tr_cached_file* o)
* errno values include ENOENT if the parent folder doesn't exist, * errno values include ENOENT if the parent folder doesn't exist,
* plus the errno values set by tr_sys_dir_create () and tr_sys_file_open (). * plus the errno values set by tr_sys_dir_create () and tr_sys_file_open ().
*/ */
// TODO: remove goto
static int cached_file_open( static int cached_file_open(
struct tr_cached_file* o, struct tr_cached_file* o,
char const* filename, char const* filename,
@@ -154,10 +155,10 @@ static int cached_file_open(
tr_preallocation_mode allocation, tr_preallocation_mode allocation,
uint64_t file_size) uint64_t file_size)
{ {
int flags; int flags = 0;
tr_sys_path_info info; tr_sys_path_info info = {};
bool already_existed; bool already_existed = false;
bool resize_needed; bool resize_needed = false;
tr_sys_file_t fd = TR_BAD_SYS_FILE; tr_sys_file_t fd = TR_BAD_SYS_FILE;
tr_error* error = nullptr; tr_error* error = nullptr;
@@ -380,11 +381,10 @@ static void ensureSessionFdInfoExists(tr_session* session)
if (session->fdInfo == nullptr) if (session->fdInfo == nullptr)
{ {
struct tr_fdInfo* i;
int const FILE_CACHE_SIZE = 32; int const FILE_CACHE_SIZE = 32;
/* Create the local file cache */ /* Create the local file cache */
i = tr_new0(struct tr_fdInfo, 1); auto* const i = tr_new0(struct tr_fdInfo, 1);
fileset_construct(&i->fileset, FILE_CACHE_SIZE); fileset_construct(&i->fileset, FILE_CACHE_SIZE);
session->fdInfo = i; session->fdInfo = i;
} }
@@ -418,9 +418,8 @@ static struct tr_fileset* get_fileset(tr_session* session)
void tr_fdFileClose(tr_session* s, tr_torrent const* tor, tr_file_index_t i) void tr_fdFileClose(tr_session* s, tr_torrent const* tor, tr_file_index_t i)
{ {
struct tr_cached_file* o; tr_cached_file* const o = fileset_lookup(get_fileset(s), tr_torrentId(tor), i);
if (o != nullptr)
if ((o = fileset_lookup(get_fileset(s), tr_torrentId(tor), i)) != nullptr)
{ {
/* flush writable files so that their mtimes will be /* flush writable files so that their mtimes will be
* up-to-date when this function returns to the caller... */ * up-to-date when this function returns to the caller... */
@@ -521,10 +520,9 @@ tr_socket_t tr_fdSocketCreate(tr_session* session, int domain, int type)
TR_ASSERT(tr_isSession(session)); TR_ASSERT(tr_isSession(session));
tr_socket_t s = TR_BAD_SOCKET; tr_socket_t s = TR_BAD_SOCKET;
struct tr_fdInfo* gFd;
ensureSessionFdInfoExists(session); ensureSessionFdInfoExists(session);
gFd = session->fdInfo; tr_fdInfo* gFd = session->fdInfo;
if (gFd->peerCount < session->peerLimit) if (gFd->peerCount < session->peerLimit)
{ {
@@ -579,16 +577,12 @@ tr_socket_t tr_fdSocketAccept(tr_session* s, tr_socket_t sockfd, tr_address* add
TR_ASSERT(addr != nullptr); TR_ASSERT(addr != nullptr);
TR_ASSERT(port != nullptr); TR_ASSERT(port != nullptr);
tr_socket_t fd;
socklen_t len;
struct tr_fdInfo* gFd;
struct sockaddr_storage sock;
ensureSessionFdInfoExists(s); ensureSessionFdInfoExists(s);
gFd = s->fdInfo; tr_fdInfo* const gFd = s->fdInfo;
len = sizeof(struct sockaddr_storage); struct sockaddr_storage sock;
fd = accept(sockfd, (struct sockaddr*)&sock, &len); socklen_t len = sizeof(struct sockaddr_storage);
tr_socket_t fd = accept(sockfd, (struct sockaddr*)&sock, &len);
if (fd != TR_BAD_SOCKET) if (fd != TR_BAD_SOCKET)
{ {

View File

@@ -21,14 +21,13 @@ bool tr_sys_file_read_line(tr_sys_file_t handle, char* buffer, size_t buffer_siz
TR_ASSERT(buffer != nullptr); TR_ASSERT(buffer != nullptr);
TR_ASSERT(buffer_size > 0); TR_ASSERT(buffer_size > 0);
bool ret = false; auto ret = bool{};
size_t offset = 0; auto offset = size_t{};
uint64_t bytes_read;
while (buffer_size > 0) while (buffer_size > 0)
{ {
size_t const bytes_needed = std::min(buffer_size, size_t{ 1024 }); size_t const bytes_needed = std::min(buffer_size, size_t{ 1024 });
auto bytes_read = uint64_t{};
ret = tr_sys_file_read(handle, buffer + offset, bytes_needed, &bytes_read, error); ret = tr_sys_file_read(handle, buffer + offset, bytes_needed, &bytes_read, error);
if (!ret || (offset == 0 && bytes_read == 0)) if (!ret || (offset == 0 && bytes_read == 0))
@@ -103,11 +102,10 @@ bool tr_sys_file_write_fmt(tr_sys_file_t handle, char const* format, tr_error**
TR_ASSERT(format != nullptr); TR_ASSERT(format != nullptr);
bool ret = false; bool ret = false;
char* buffer;
va_list args; va_list args;
va_start(args, error); va_start(args, error);
buffer = tr_strdup_vprintf(format, args); char* const buffer = tr_strdup_vprintf(format, args);
va_end(args); va_end(args);
if (buffer != nullptr) if (buffer != nullptr)

View File

@@ -47,7 +47,6 @@ static int readOrWriteBytes(
void* buf, void* buf,
size_t buflen) size_t buflen)
{ {
tr_sys_file_t fd;
int err = 0; int err = 0;
bool const doWrite = ioMode >= TR_IO_WRITE; bool const doWrite = ioMode >= TR_IO_WRITE;
tr_info const* const info = &tor->info; tr_info const* const info = &tor->info;
@@ -66,15 +65,13 @@ static int readOrWriteBytes(
**** Find the fd **** Find the fd
***/ ***/
fd = tr_fdFileGetCached(session, tr_torrentId(tor), fileIndex, doWrite); tr_sys_file_t fd = tr_fdFileGetCached(session, tr_torrentId(tor), fileIndex, doWrite);
if (fd == TR_BAD_SYS_FILE) if (fd == TR_BAD_SYS_FILE) /* it's not cached, so open/create it now */
{ {
/* it's not cached, so open/create it now */
char* subpath;
char const* base;
/* see if the file exists... */ /* see if the file exists... */
char const* base = nullptr;
char* subpath = nullptr;
if (!tr_torrentFindFile2(tor, fileIndex, &base, &subpath, nullptr)) if (!tr_torrentFindFile2(tor, fileIndex, &base, &subpath, nullptr))
{ {
/* we can't read a file that doesn't exist... */ /* we can't read a file that doesn't exist... */
@@ -96,8 +93,8 @@ static int readOrWriteBytes(
tr_preallocation_mode const prealloc = (file->dnd || !doWrite) ? TR_PREALLOCATE_NONE : tr_preallocation_mode const prealloc = (file->dnd || !doWrite) ? TR_PREALLOCATE_NONE :
tor->session->preallocationMode; tor->session->preallocationMode;
if ((fd = tr_fdFileCheckout(session, tor->uniqueId, fileIndex, filename, doWrite, prealloc, file->length)) == fd = tr_fdFileCheckout(session, tor->uniqueId, fileIndex, filename, doWrite, prealloc, file->length);
TR_BAD_SYS_FILE) if (fd == TR_BAD_SYS_FILE)
{ {
err = errno; err = errno;
tr_logAddTorErr(tor, "tr_fdFileCheckout failed for \"%s\": %s", filename, tr_strerror(err)); tr_logAddTorErr(tor, "tr_fdFileCheckout failed for \"%s\": %s", filename, tr_strerror(err));
@@ -204,8 +201,6 @@ static int readOrWritePiece(
size_t buflen) size_t buflen)
{ {
int err = 0; int err = 0;
tr_file_index_t fileIndex;
uint64_t fileOffset;
tr_info const* info = &tor->info; tr_info const* info = &tor->info;
if (pieceIndex >= tor->info.pieceCount) if (pieceIndex >= tor->info.pieceCount)
@@ -213,6 +208,8 @@ static int readOrWritePiece(
return EINVAL; return EINVAL;
} }
auto fileIndex = tr_file_index_t{};
auto fileOffset = uint64_t{};
tr_ioFindFileLocation(tor, pieceIndex, pieceOffset, &fileIndex, &fileOffset); tr_ioFindFileLocation(tor, pieceIndex, pieceOffset, &fileIndex, &fileOffset);
while (buflen != 0 && err == 0) while (buflen != 0 && err == 0)
@@ -262,18 +259,16 @@ static bool recalculateHash(tr_torrent* tor, tr_piece_index_t pieceIndex, uint8_
TR_ASSERT(pieceIndex < tor->info.pieceCount); TR_ASSERT(pieceIndex < tor->info.pieceCount);
TR_ASSERT(setme != nullptr); TR_ASSERT(setme != nullptr);
size_t bytesLeft;
uint32_t offset = 0; uint32_t offset = 0;
bool success = true; bool success = true;
size_t const buflen = tor->blockSize; size_t const buflen = tor->blockSize;
void* const buffer = tr_malloc(buflen); void* const buffer = tr_malloc(buflen);
tr_sha1_ctx_t sha;
TR_ASSERT(buffer != nullptr); TR_ASSERT(buffer != nullptr);
TR_ASSERT(buflen > 0); TR_ASSERT(buflen > 0);
sha = tr_sha1_init(); tr_sha1_ctx_t sha = tr_sha1_init();
bytesLeft = tr_torPieceCountBytes(tor, pieceIndex); size_t bytesLeft = tr_torPieceCountBytes(tor, pieceIndex);
tr_ioPrefetch(tor, pieceIndex, offset, bytesLeft); tr_ioPrefetch(tor, pieceIndex, offset, bytesLeft);

View File

@@ -103,10 +103,9 @@ bool tr_logGetQueueEnabled(void)
tr_log_message* tr_logGetQueue(void) tr_log_message* tr_logGetQueue(void)
{ {
tr_log_message* ret;
tr_lockLock(getMessageLock()); tr_lockLock(getMessageLock());
ret = myQueue; auto* const ret = myQueue;
myQueue = nullptr; myQueue = nullptr;
myQueueTail = &myQueue; myQueueTail = &myQueue;
myQueueLength = 0; myQueueLength = 0;
@@ -117,11 +116,9 @@ tr_log_message* tr_logGetQueue(void)
void tr_logFreeQueue(tr_log_message* list) void tr_logFreeQueue(tr_log_message* list)
{ {
tr_log_message* next;
while (list != nullptr) while (list != nullptr)
{ {
next = list->next; tr_log_message* next = list->next;
tr_free(list->message); tr_free(list->message);
tr_free(list->name); tr_free(list->name);
tr_free(list); tr_free(list);
@@ -211,14 +208,13 @@ void tr_logAddMessage(char const* file, int line, tr_log_level level, char const
{ {
int const err = errno; /* message logging shouldn't affect errno */ int const err = errno; /* message logging shouldn't affect errno */
char buf[1024]; char buf[1024];
int buf_len;
va_list ap; va_list ap;
tr_lockLock(getMessageLock()); tr_lockLock(getMessageLock());
/* build the text message */ /* build the text message */
*buf = '\0'; *buf = '\0';
va_start(ap, fmt); va_start(ap, fmt);
buf_len = evutil_vsnprintf(buf, sizeof(buf), fmt, ap); int const buf_len = evutil_vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap); va_end(ap);
if (buf_len < 0) if (buf_len < 0)
@@ -247,8 +243,7 @@ void tr_logAddMessage(char const* file, int line, tr_log_level level, char const
{ {
if (tr_logGetQueueEnabled()) if (tr_logGetQueueEnabled())
{ {
tr_log_message* newmsg; auto* const newmsg = tr_new0(tr_log_message, 1);
newmsg = tr_new0(tr_log_message, 1);
newmsg->level = level; newmsg->level = level;
newmsg->when = tr_time(); newmsg->when = tr_time();
newmsg->message = tr_strdup(buf); newmsg->message = tr_strdup(buf);
@@ -272,10 +267,9 @@ void tr_logAddMessage(char const* file, int line, tr_log_level level, char const
} }
else else
{ {
tr_sys_file_t fp;
char timestr[64]; char timestr[64];
fp = tr_logGetFile(); tr_sys_file_t fp = tr_logGetFile();
if (fp == TR_BAD_SYS_FILE) if (fp == TR_BAD_SYS_FILE)
{ {

View File

@@ -302,11 +302,9 @@ static char const* getHomeDir(void)
void tr_setConfigDir(tr_session* session, char const* configDir) void tr_setConfigDir(tr_session* session, char const* configDir)
{ {
char* path;
session->configDir = tr_strdup(configDir); session->configDir = tr_strdup(configDir);
path = tr_buildPath(configDir, RESUME_SUBDIR, nullptr); char* path = tr_buildPath(configDir, RESUME_SUBDIR, nullptr);
tr_sys_dir_create(path, TR_SYS_DIR_CREATE_PARENTS, 0777, nullptr); tr_sys_dir_create(path, TR_SYS_DIR_CREATE_PARENTS, 0777, nullptr);
session->resumeDir = path; session->resumeDir = path;
@@ -388,27 +386,18 @@ char const* tr_getDefaultDownloadDir(void)
if (user_dir == nullptr) if (user_dir == nullptr)
{ {
char* config_home;
char* config_file;
char* content;
size_t content_len;
/* figure out where to look for user-dirs.dirs */ /* figure out where to look for user-dirs.dirs */
config_home = tr_env_get_string("XDG_CONFIG_HOME", nullptr); char* const config_home = tr_env_get_string("XDG_CONFIG_HOME", nullptr);
if (!tr_str_is_empty(config_home)) char* const config_file = !tr_str_is_empty(config_home) ?
{ tr_buildPath(config_home, "user-dirs.dirs", nullptr) :
config_file = tr_buildPath(config_home, "user-dirs.dirs", nullptr); tr_buildPath(getHomeDir(), ".config", "user-dirs.dirs", nullptr);
}
else
{
config_file = tr_buildPath(getHomeDir(), ".config", "user-dirs.dirs", nullptr);
}
tr_free(config_home); tr_free(config_home);
/* read in user-dirs.dirs and look for the download dir entry */ /* read in user-dirs.dirs and look for the download dir entry */
content = (char*)tr_loadFile(config_file, &content_len, nullptr); size_t content_len = 0;
char* const content = (char*)tr_loadFile(config_file, &content_len, nullptr);
if (content != nullptr && content_len > 0) if (content != nullptr && content_len > 0)
{ {

View File

@@ -70,10 +70,8 @@ static tr_sys_file_t create_session_id_lock_file(char const* session_id)
} }
char* lock_file_path = get_session_id_lock_file_path(session_id); char* lock_file_path = get_session_id_lock_file_path(session_id);
tr_sys_file_t lock_file;
tr_error* error = nullptr; tr_error* error = nullptr;
auto lock_file = tr_sys_file_open(lock_file_path, TR_SYS_FILE_READ | TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE, 0600, &error);
lock_file = tr_sys_file_open(lock_file_path, TR_SYS_FILE_READ | TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE, 0600, &error);
if (lock_file != TR_BAD_SYS_FILE) if (lock_file != TR_BAD_SYS_FILE)
{ {
@@ -170,10 +168,8 @@ bool tr_session_id_is_local(char const* session_id)
if (session_id != nullptr) if (session_id != nullptr)
{ {
char* lock_file_path = get_session_id_lock_file_path(session_id); char* lock_file_path = get_session_id_lock_file_path(session_id);
tr_sys_file_t lock_file;
tr_error* error = nullptr; tr_error* error = nullptr;
auto lock_file = tr_sys_file_open(lock_file_path, TR_SYS_FILE_READ, 0, &error);
lock_file = tr_sys_file_open(lock_file_path, TR_SYS_FILE_READ, 0, &error);
if (lock_file == TR_BAD_SYS_FILE) if (lock_file == TR_BAD_SYS_FILE)
{ {

View File

@@ -39,12 +39,10 @@ static char* getFilename(tr_session const* session)
static void loadCumulativeStats(tr_session const* session, tr_session_stats* setme) static void loadCumulativeStats(tr_session const* session, tr_session_stats* setme)
{ {
tr_variant top; auto top = tr_variant{};
char* filename;
bool loaded = false;
filename = getFilename(session); char* filename = getFilename(session);
loaded = tr_variantFromFile(&top, TR_VARIANT_FMT_JSON, filename, nullptr); bool loaded = tr_variantFromFile(&top, TR_VARIANT_FMT_JSON, filename, nullptr);
tr_free(filename); tr_free(filename);
if (!loaded) if (!loaded)
@@ -56,7 +54,7 @@ static void loadCumulativeStats(tr_session const* session, tr_session_stats* set
if (loaded) if (loaded)
{ {
int64_t i; auto i = int64_t{};
if (tr_variantDictFindInt(&top, TR_KEY_downloaded_bytes, &i)) if (tr_variantDictFindInt(&top, TR_KEY_downloaded_bytes, &i))
{ {
@@ -89,9 +87,7 @@ static void loadCumulativeStats(tr_session const* session, tr_session_stats* set
static void saveCumulativeStats(tr_session const* session, tr_session_stats const* s) static void saveCumulativeStats(tr_session const* session, tr_session_stats const* s)
{ {
char* filename; auto top = tr_variant{};
tr_variant top;
tr_variantInitDict(&top, 5); tr_variantInitDict(&top, 5);
tr_variantDictAddInt(&top, TR_KEY_downloaded_bytes, s->downloadedBytes); tr_variantDictAddInt(&top, TR_KEY_downloaded_bytes, s->downloadedBytes);
tr_variantDictAddInt(&top, TR_KEY_files_added, s->filesAdded); tr_variantDictAddInt(&top, TR_KEY_files_added, s->filesAdded);
@@ -99,7 +95,7 @@ static void saveCumulativeStats(tr_session const* session, tr_session_stats cons
tr_variantDictAddInt(&top, TR_KEY_session_count, s->sessionCount); tr_variantDictAddInt(&top, TR_KEY_session_count, s->sessionCount);
tr_variantDictAddInt(&top, TR_KEY_uploaded_bytes, s->uploadedBytes); tr_variantDictAddInt(&top, TR_KEY_uploaded_bytes, s->uploadedBytes);
filename = getFilename(session); char* const filename = getFilename(session);
if (tr_logGetDeepEnabled()) if (tr_logGetDeepEnabled())
{ {
tr_logAddDeep(__FILE__, __LINE__, nullptr, "Saving stats to \"%s\"", filename); tr_logAddDeep(__FILE__, __LINE__, nullptr, "Saving stats to \"%s\"", filename);
@@ -125,14 +121,14 @@ void tr_statsInit(tr_session* session)
session->sessionStats = stats; session->sessionStats = stats;
} }
static struct tr_stats_handle* getStats(tr_session const* session) static tr_stats_handle* getStats(tr_session const* session)
{ {
return session != nullptr ? session->sessionStats : nullptr; return session != nullptr ? session->sessionStats : nullptr;
} }
void tr_statsSaveDirty(tr_session* session) void tr_statsSaveDirty(tr_session* session)
{ {
struct tr_stats_handle* h = getStats(session); auto* const h = getStats(session);
if (h != nullptr && h->isDirty) if (h != nullptr && h->isDirty)
{ {
@@ -216,9 +212,9 @@ void tr_sessionClearStats(tr_session* session)
void tr_statsAddUploaded(tr_session* session, uint32_t bytes) void tr_statsAddUploaded(tr_session* session, uint32_t bytes)
{ {
struct tr_stats_handle* s; auto* const s = getStats(session);
if ((s = getStats(session)) != nullptr) if (s != nullptr)
{ {
s->single.uploadedBytes += bytes; s->single.uploadedBytes += bytes;
s->isDirty = true; s->isDirty = true;
@@ -227,9 +223,9 @@ void tr_statsAddUploaded(tr_session* session, uint32_t bytes)
void tr_statsAddDownloaded(tr_session* session, uint32_t bytes) void tr_statsAddDownloaded(tr_session* session, uint32_t bytes)
{ {
struct tr_stats_handle* s; auto* const s = getStats(session);
if ((s = getStats(session)) != nullptr) if (s != nullptr)
{ {
s->single.downloadedBytes += bytes; s->single.downloadedBytes += bytes;
s->isDirty = true; s->isDirty = true;
@@ -238,9 +234,9 @@ void tr_statsAddDownloaded(tr_session* session, uint32_t bytes)
void tr_statsFileCreated(tr_session* session) void tr_statsFileCreated(tr_session* session)
{ {
struct tr_stats_handle* s; auto* const s = getStats(session);
if ((s = getStats(session)) != nullptr) if (s != nullptr)
{ {
s->single.filesAdded++; s->single.filesAdded++;
} }

View File

@@ -212,6 +212,7 @@ static char const* lpd_extractHeader(char const* s, struct lpd_protocolVersion*
* - assemble search string "\r\nName: " and locate position * - assemble search string "\r\nName: " and locate position
* - copy back value from end to next "\r\n" * - copy back value from end to next "\r\n"
*/ */
// TODO: string_view
static bool lpd_extractParam(char const* const str, char const* const name, int n, char* const val) static bool lpd_extractParam(char const* const str, char const* const name, int n, char* const val)
{ {
TR_ASSERT(str != nullptr); TR_ASSERT(str != nullptr);
@@ -222,7 +223,6 @@ static bool lpd_extractParam(char const* const str, char const* const name, int
auto constexpr MaxLength = int{ 30 }; auto constexpr MaxLength = int{ 30 };
char sstr[MaxLength] = { 0 }; char sstr[MaxLength] = { 0 };
char const* pos;
if (strlen(name) > MaxLength - strlen(CRLF ": ")) if (strlen(name) > MaxLength - strlen(CRLF ": "))
{ {
@@ -232,8 +232,7 @@ static bool lpd_extractParam(char const* const str, char const* const name, int
/* compose the string token to search for */ /* compose the string token to search for */
tr_snprintf(sstr, MaxLength, CRLF "%s: ", name); tr_snprintf(sstr, MaxLength, CRLF "%s: ", name);
pos = strstr(str, sstr); char const* const pos = strstr(str, sstr);
if (pos == nullptr) if (pos == nullptr)
{ {
return false; /* search was not successful */ return false; /* search was not successful */

View File

@@ -53,16 +53,14 @@ THE SOFTWARE.
static void set_socket_buffers(tr_socket_t fd, bool large) static void set_socket_buffers(tr_socket_t fd, bool large)
{ {
int size; int rbuf = 0;
int rbuf; int sbuf = 0;
int sbuf;
int rc;
socklen_t rbuf_len = sizeof(rbuf); socklen_t rbuf_len = sizeof(rbuf);
socklen_t sbuf_len = sizeof(sbuf); socklen_t sbuf_len = sizeof(sbuf);
char err_buf[512]; char err_buf[512];
size = large ? RECV_BUFFER_SIZE : SMALL_BUFFER_SIZE; int size = large ? RECV_BUFFER_SIZE : SMALL_BUFFER_SIZE;
rc = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<char const*>(&size), sizeof(size)); int rc = setsockopt(fd, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<char const*>(&size), sizeof(size));
if (rc < 0) if (rc < 0)
{ {
@@ -128,15 +126,15 @@ void tr_udpSetSocketBuffers(tr_session* session)
/* BEP-32 has a rather nice explanation of why we need to bind to one /* BEP-32 has a rather nice explanation of why we need to bind to one
IPv6 address, if I may say so myself. */ IPv6 address, if I may say so myself. */
// TODO: remove goto, it prevents reducing scope of local variables
static void rebind_ipv6(tr_session* ss, bool force) static void rebind_ipv6(tr_session* ss, bool force)
{ {
bool is_default; bool is_default = false;
struct tr_address const* public_addr; tr_address const* public_addr = nullptr;
struct sockaddr_in6 sin6; struct sockaddr_in6 sin6;
unsigned char const* ipv6 = tr_globalIPv6(); unsigned char const* ipv6 = tr_globalIPv6();
tr_socket_t s = TR_BAD_SOCKET; tr_socket_t s = TR_BAD_SOCKET;
int rc; int rc = -1;
int one = 1; int one = 1;
/* We currently have no way to enable or disable IPv6 after initialisation. /* We currently have no way to enable or disable IPv6 after initialisation.
@@ -244,14 +242,12 @@ static void event_callback(evutil_socket_t s, [[maybe_unused]] short type, void*
TR_ASSERT(tr_isSession(static_cast<tr_session*>(vsession))); TR_ASSERT(tr_isSession(static_cast<tr_session*>(vsession)));
TR_ASSERT(type == EV_READ); TR_ASSERT(type == EV_READ);
int rc;
socklen_t fromlen;
unsigned char buf[4096]; unsigned char buf[4096];
struct sockaddr_storage from; struct sockaddr_storage from;
auto* session = static_cast<tr_session*>(vsession); auto* session = static_cast<tr_session*>(vsession);
fromlen = sizeof(from); socklen_t fromlen = sizeof(from);
rc = recvfrom(s, reinterpret_cast<char*>(buf), 4096 - 1, 0, (struct sockaddr*)&from, &fromlen); int rc = recvfrom(s, reinterpret_cast<char*>(buf), 4096 - 1, 0, (struct sockaddr*)&from, &fromlen);
/* Since most packets we receive here are µTP, make quick inline /* Since most packets we receive here are µTP, make quick inline
checks for the other protocols. The logic is as follows: checks for the other protocols. The logic is as follows:
@@ -299,11 +295,6 @@ void tr_udpInit(tr_session* ss)
TR_ASSERT(ss->udp_socket == TR_BAD_SOCKET); TR_ASSERT(ss->udp_socket == TR_BAD_SOCKET);
TR_ASSERT(ss->udp6_socket == TR_BAD_SOCKET); TR_ASSERT(ss->udp6_socket == TR_BAD_SOCKET);
bool is_default;
struct tr_address const* public_addr;
struct sockaddr_in sin;
int rc;
ss->udp_port = tr_sessionGetPeerPort(ss); ss->udp_port = tr_sessionGetPeerPort(ss);
if (ss->udp_port <= 0) if (ss->udp_port <= 0)
@@ -316,37 +307,41 @@ void tr_udpInit(tr_session* ss)
if (ss->udp_socket == TR_BAD_SOCKET) if (ss->udp_socket == TR_BAD_SOCKET)
{ {
tr_logAddNamedError("UDP", "Couldn't create IPv4 socket"); tr_logAddNamedError("UDP", "Couldn't create IPv4 socket");
goto IPV6;
} }
else
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
public_addr = tr_sessionGetPublicAddress(ss, TR_AF_INET, &is_default);
if (public_addr != nullptr && !is_default)
{ {
memcpy(&sin.sin_addr, &public_addr->addr.addr4, sizeof(struct in_addr)); auto is_default = bool{};
tr_address const* public_addr = tr_sessionGetPublicAddress(ss, TR_AF_INET, &is_default);
auto sin = sockaddr_in{};
sin.sin_family = AF_INET;
if (public_addr != nullptr && !is_default)
{
memcpy(&sin.sin_addr, &public_addr->addr.addr4, sizeof(struct in_addr));
}
sin.sin_port = htons(ss->udp_port);
int const rc = bind(ss->udp_socket, (struct sockaddr*)&sin, sizeof(sin));
if (rc == -1)
{
tr_logAddNamedError("UDP", "Couldn't bind IPv4 socket");
tr_netCloseSocket(ss->udp_socket);
ss->udp_socket = TR_BAD_SOCKET;
}
else
{
ss->udp_event = event_new(ss->event_base, ss->udp_socket, EV_READ | EV_PERSIST, event_callback, ss);
if (ss->udp_event == nullptr)
{
tr_logAddNamedError("UDP", "Couldn't allocate IPv4 event");
}
}
} }
sin.sin_port = htons(ss->udp_port); // IPV6
rc = bind(ss->udp_socket, (struct sockaddr*)&sin, sizeof(sin));
if (rc == -1)
{
tr_logAddNamedError("UDP", "Couldn't bind IPv4 socket");
tr_netCloseSocket(ss->udp_socket);
ss->udp_socket = TR_BAD_SOCKET;
goto IPV6;
}
ss->udp_event = event_new(ss->event_base, ss->udp_socket, EV_READ | EV_PERSIST, event_callback, ss);
if (ss->udp_event == nullptr)
{
tr_logAddNamedError("UDP", "Couldn't allocate IPv4 event");
}
IPV6:
if (tr_globalIPv6() != nullptr) if (tr_globalIPv6() != nullptr)
{ {
rebind_ipv6(ss, true); rebind_ipv6(ss, true);

View File

@@ -108,7 +108,7 @@ static void incoming(void* vsession, struct UTPSocket* s)
struct sockaddr* from = (struct sockaddr*)&from_storage; struct sockaddr* from = (struct sockaddr*)&from_storage;
socklen_t fromlen = sizeof(from_storage); socklen_t fromlen = sizeof(from_storage);
tr_address addr; tr_address addr;
tr_port port; tr_port port = 0;
if (!tr_sessionIsUTPEnabled(session)) if (!tr_sessionIsUTPEnabled(session))
{ {
@@ -144,8 +144,8 @@ void tr_utpSendTo(void* closure, unsigned char const* buf, size_t buflen, struct
static void reset_timer(tr_session* ss) static void reset_timer(tr_session* ss)
{ {
int sec; int sec = 0;
int usec; int usec = 0;
if (tr_sessionIsUTPEnabled(ss)) if (tr_sessionIsUTPEnabled(ss))
{ {

View File

@@ -176,7 +176,7 @@ static void readFromPipe(evutil_socket_t fd, short eventType, void* veh)
/* read the command type */ /* read the command type */
char ch = '\0'; char ch = '\0';
int ret; int ret = 0;
do do
{ {
ret = piperead(fd, &ch, 1); ret = piperead(fd, &ch, 1);
@@ -269,11 +269,9 @@ static void libeventThreadFunc(void* veh)
void tr_eventInit(tr_session* session) void tr_eventInit(tr_session* session)
{ {
tr_event_handle* eh;
session->events = nullptr; session->events = nullptr;
eh = tr_new0(tr_event_handle, 1); auto* const eh = tr_new0(tr_event_handle, 1);
eh->lock = tr_lockNew(); eh->lock = tr_lockNew();
if (pipe(eh->fds) == -1) if (pipe(eh->fds) == -1)
@@ -336,22 +334,18 @@ void tr_runInEventThread(tr_session* session, void (*func)(void*), void* user_da
} }
else else
{ {
tr_pipe_end_t fd;
char ch;
ev_ssize_t res_1;
ev_ssize_t res_2;
tr_event_handle* e = session->events; tr_event_handle* e = session->events;
struct tr_run_data data; struct tr_run_data data;
tr_lockLock(e->lock); tr_lockLock(e->lock);
fd = e->fds[1]; tr_pipe_end_t const fd = e->fds[1];
ch = 'r'; char ch = 'r';
res_1 = pipewrite(fd, &ch, 1); ev_ssize_t const res_1 = pipewrite(fd, &ch, 1);
data.func = func; data.func = func;
data.user_data = user_data; data.user_data = user_data;
res_2 = pipewrite(fd, &data, sizeof(data)); ev_ssize_t const res_2 = pipewrite(fd, &data, sizeof(data));
tr_lockUnlock(e->lock); tr_lockUnlock(e->lock);

View File

@@ -225,9 +225,7 @@ tr_port_forwarding tr_upnpPulse(tr_upnp* handle, tr_port port, bool isEnabled, b
{ {
if (isEnabled && handle->state == TR_UPNP_DISCOVER) if (isEnabled && handle->state == TR_UPNP_DISCOVER)
{ {
struct UPNPDev* devlist; auto* const devlist = tr_upnpDiscover(2000);
devlist = tr_upnpDiscover(2000);
errno = 0; errno = 0;