fix: potential out-of-range error in io's readOrWritePiece() (#2413)

This commit is contained in:
Charles Kerr 2022-01-16 12:02:47 -06:00 committed by GitHub
parent 2c09e99515
commit 6b440af32f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 36 additions and 18 deletions

View File

@ -50,9 +50,10 @@ static int readOrWriteBytes(
void* buf,
size_t buflen)
{
TR_ASSERT(file_index < tor->fileCount());
int err = 0;
bool const doWrite = ioMode >= TR_IO_WRITE;
auto const file_size = tor->fileSize(file_index);
TR_ASSERT(file_size == 0 || file_offset < file_size);
TR_ASSERT(file_offset + buflen <= file_size);
@ -174,14 +175,15 @@ static int readOrWritePiece(
err = readOrWriteBytes(tor->session, tor, ioMode, file_index, file_offset, buf, bytes_this_pass);
buf += bytes_this_pass;
buflen -= bytes_this_pass;
++file_index;
file_offset = 0;
if (err != 0 && ioMode == TR_IO_WRITE && tor->error != TR_STAT_LOCAL_ERROR)
{
auto const path = tr_strvPath(tor->downloadDir().sv(), tor->fileSubpath(file_index));
tor->setLocalError(tr_strvJoin(tr_strerror(err), " ("sv, path, ")"sv));
}
++file_index;
file_offset = 0;
}
return err;

View File

@ -25,6 +25,7 @@
#include "log.h"
#include "quark.h"
#include "torrent-metainfo.h"
#include "tr-assert.h"
#include "utils.h"
#include "variant.h"
#include "web-utils.h"
@ -596,3 +597,24 @@ bool tr_torrent_metainfo::migrateFile(
new_filename.c_str());
return true;
}
std::string const& tr_torrent_metainfo::fileSubpath(tr_file_index_t i) const
{
TR_ASSERT(i < fileCount());
return files_.at(i).path();
}
void tr_torrent_metainfo::setFileSubpath(tr_file_index_t i, std::string_view subpath)
{
TR_ASSERT(i < fileCount());
files_.at(i).setSubpath(subpath);
}
uint64_t tr_torrent_metainfo::fileSize(tr_file_index_t i) const
{
TR_ASSERT(i < fileCount());
return files_.at(i).size();
}

View File

@ -97,11 +97,11 @@ public:
return blockInfo().totalSize();
}
auto const& comment() const
[[nodiscard]] auto const& comment() const
{
return comment_;
}
auto const& creator() const
[[nodiscard]] auto const& creator() const
{
return creator_;
}
@ -110,22 +110,16 @@ public:
return source_;
}
auto fileCount() const
[[nodiscard]] auto fileCount() const
{
return std::size(files_);
}
std::string const& fileSubpath(tr_file_index_t i) const
{
return files_.at(i).path();
}
void setFileSubpath(tr_file_index_t i, std::string_view subpath)
{
files_.at(i).setSubpath(subpath);
}
auto fileSize(tr_file_index_t i) const
{
return files_.at(i).size();
}
[[nodiscard]] std::string const& fileSubpath(tr_file_index_t i) const;
void setFileSubpath(tr_file_index_t i, std::string_view subpath);
[[nodiscard]] uint64_t fileSize(tr_file_index_t i) const;
[[nodiscard]] auto const& isPrivate() const
{