#ifdef UNSAFE_BUFFERS_BUILD
#pragma allow_unsafe_buffers
#endif
#include "net/base/file_stream.h"
#include <string>
#include <utility>
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/path_service.h"
#include "base/run_loop.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/current_thread.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/gtest_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "base/unguessable_token.h"
#include "build/build_config.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/log/test_net_log.h"
#include "net/test/gtest_util.h"
#include "net/test/test_with_task_environment.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
IsError;
IsOk;
#if BUILDFLAG(IS_ANDROID)
#include "base/test/test_file_util.h"
#endif
namespace net {
namespace {
constexpr char kTestData[] = …;
constexpr int kTestDataSize = …;
scoped_refptr<IOBufferWithSize> CreateTestDataBuffer() { … }
}
class FileStreamTest : public PlatformTest, public WithTaskEnvironment { … };
namespace {
TEST_F(FileStreamTest, OpenExplicitClose) { … }
TEST_F(FileStreamTest, OpenExplicitCloseOrphaned) { … }
TEST_F(FileStreamTest, UseFileHandle) { … }
TEST_F(FileStreamTest, UseClosedStream) { … }
TEST_F(FileStreamTest, Read) { … }
TEST_F(FileStreamTest, Read_EarlyDelete) { … }
TEST_F(FileStreamTest, Read_FromOffset) { … }
TEST_F(FileStreamTest, Write) { … }
TEST_F(FileStreamTest, Write_EarlyDelete) { … }
TEST_F(FileStreamTest, Write_FromOffset) { … }
TEST_F(FileStreamTest, BasicReadWrite) { … }
TEST_F(FileStreamTest, BasicWriteRead) { … }
class TestWriteReadCompletionCallback { … };
TEST_F(FileStreamTest, WriteRead) { … }
class TestWriteCloseCompletionCallback { … };
TEST_F(FileStreamTest, WriteClose) { … }
TEST_F(FileStreamTest, OpenAndDelete) { … }
TEST_F(FileStreamTest, WriteError) { … }
TEST_F(FileStreamTest, ReadError) { … }
#if BUILDFLAG(IS_WIN)
TEST_F(FileStreamTest, AsyncFlagMismatch) {
uint32_t flags = base::File::FLAG_OPEN | base::File::FLAG_READ;
base::File file(temp_file_path(), flags);
base::File lying_file(file.TakePlatformFile(), true);
ASSERT_TRUE(lying_file.IsValid());
FileStream stream(std::move(lying_file),
base::SingleThreadTaskRunner::GetCurrentDefault());
ASSERT_FALSE(stream.IsOpen());
TestCompletionCallback callback;
scoped_refptr<IOBufferWithSize> buf =
base::MakeRefCounted<IOBufferWithSize>(4);
int rv = stream.Read(buf.get(), buf->size(), callback.callback());
EXPECT_THAT(callback.GetResult(rv), IsError(ERR_UNEXPECTED));
}
#endif
#if BUILDFLAG(IS_ANDROID)
TEST_F(FileStreamTest, DISABLED_ContentUriRead) {
base::FilePath test_dir;
base::PathService::Get(base::DIR_SRC_TEST_DATA_ROOT, &test_dir);
test_dir = test_dir.AppendASCII("net");
test_dir = test_dir.AppendASCII("data");
test_dir = test_dir.AppendASCII("file_stream_unittest");
ASSERT_TRUE(base::PathExists(test_dir));
base::FilePath image_file = test_dir.Append(FILE_PATH_LITERAL("red.png"));
base::FilePath path = base::InsertImageIntoMediaStore(image_file);
EXPECT_TRUE(path.IsContentUri());
EXPECT_TRUE(base::PathExists(path));
int64_t file_size;
EXPECT_TRUE(base::GetFileSize(path, &file_size));
EXPECT_LT(0, file_size);
FileStream stream(base::SingleThreadTaskRunner::GetCurrentDefault());
int flags = base::File::FLAG_OPEN | base::File::FLAG_READ |
base::File::FLAG_ASYNC;
TestCompletionCallback callback;
int rv = stream.Open(path, flags, callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
EXPECT_THAT(callback.WaitForResult(), IsOk());
int total_bytes_read = 0;
std::string data_read;
for (;;) {
scoped_refptr<IOBufferWithSize> buf =
base::MakeRefCounted<IOBufferWithSize>(4);
rv = stream.Read(buf.get(), buf->size(), callback.callback());
if (rv == ERR_IO_PENDING)
rv = callback.WaitForResult();
EXPECT_LE(0, rv);
if (rv <= 0)
break;
total_bytes_read += rv;
data_read.append(buf->data(), rv);
}
EXPECT_EQ(file_size, total_bytes_read);
}
#endif
#if BUILDFLAG(IS_WIN)
class FileStreamPipeTest : public PlatformTest, public WithTaskEnvironment {
protected:
FileStreamPipeTest() = default;
base::File CreatePipe() {
base::win::ScopedHandle pipe(::CreateNamedPipeW(
pipe_name_.c_str(),
PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE |
FILE_FLAG_OVERLAPPED,
PIPE_TYPE_BYTE, 1,
0, 0, 0,
nullptr));
if (pipe.IsValid()) {
return base::File(std::move(pipe), true);
}
return base::File(base::File::GetLastFileError());
}
base::File OpenPipe() {
base::win::ScopedHandle pipe(
::CreateFileW(pipe_name_.c_str(), GENERIC_READ | GENERIC_WRITE,
0, nullptr,
OPEN_EXISTING, 0,
nullptr));
if (!pipe.IsValid()) {
return base::File(base::File::GetLastFileError());
}
return base::File(std::move(pipe));
}
private:
const std::wstring pipe_name_{base::StrCat(
{L"\\\\.\\pipe\\chromium.test.",
base::ASCIIToWide(base::UnguessableToken::Create().ToString())})};
};
TEST_F(FileStreamPipeTest, ConnectNamedPipeAfterClient) {
base::File pipe(CreatePipe());
ASSERT_TRUE(pipe.IsValid())
<< base::File::ErrorToString(pipe.error_details());
FileStream pipe_stream(std::move(pipe),
base::SingleThreadTaskRunner::GetCurrentDefault());
ASSERT_TRUE(pipe_stream.IsOpen());
base::File client(OpenPipe());
ASSERT_TRUE(client.IsValid())
<< base::File::ErrorToString(client.error_details());
TestCompletionCallback callback;
ASSERT_THAT(
callback.GetResult(pipe_stream.ConnectNamedPipe(callback.callback())),
IsOk());
scoped_refptr<IOBufferWithSize> write_io_buffer = CreateTestDataBuffer();
int result = pipe_stream.Write(write_io_buffer.get(), write_io_buffer->size(),
callback.callback());
auto buffer = base::HeapArray<uint8_t>::WithSize(write_io_buffer->size());
ASSERT_EQ(client.ReadAtCurrentPos(buffer.as_span()), write_io_buffer->size());
ASSERT_THAT(callback.GetResult(result), write_io_buffer->size());
ASSERT_EQ(buffer.as_span(), base::as_bytes(write_io_buffer->span()));
}
TEST_F(FileStreamPipeTest, ConnectNamedPipeBeforeClient) {
base::File pipe(CreatePipe());
ASSERT_TRUE(pipe.IsValid())
<< base::File::ErrorToString(pipe.error_details());
FileStream pipe_stream(std::move(pipe),
base::SingleThreadTaskRunner::GetCurrentDefault());
ASSERT_TRUE(pipe_stream.IsOpen());
TestCompletionCallback callback;
ASSERT_THAT(pipe_stream.ConnectNamedPipe(callback.callback()),
IsError(ERR_IO_PENDING));
base::File client(OpenPipe());
ASSERT_TRUE(client.IsValid())
<< base::File::ErrorToString(client.error_details());
ASSERT_THAT(callback.WaitForResult(), IsOk());
}
TEST_F(FileStreamPipeTest, CloseBeforeConnect) {
{
base::File pipe(CreatePipe());
ASSERT_TRUE(pipe.IsValid())
<< base::File::ErrorToString(pipe.error_details());
FileStream pipe_stream(std::move(pipe),
base::SingleThreadTaskRunner::GetCurrentDefault());
ASSERT_TRUE(pipe_stream.IsOpen());
ASSERT_THAT(pipe_stream.ConnectNamedPipe(base::BindLambdaForTesting(
[loop_quitter = base::ScopedClosureRunner(QuitClosure())](
int error) { FAIL(); })),
IsError(ERR_IO_PENDING));
}
RunUntilQuit();
RunUntilIdle();
}
using FileStreamPipeDeathTest = FileStreamPipeTest;
TEST_F(FileStreamPipeDeathTest, CannotConnectFile) {
const base::FilePath exe_path(base::PathService::CheckedGet(base::FILE_EXE));
base::File exe_file(exe_path, base::File::FLAG_OPEN | base::File::FLAG_READ |
base::File::FLAG_ASYNC |
base::File::FLAG_WIN_SHARE_DELETE);
ASSERT_TRUE(exe_file.IsValid())
<< base::File::ErrorToString(exe_file.error_details());
FileStream file_stream(std::move(exe_file),
base::SingleThreadTaskRunner::GetCurrentDefault());
ASSERT_TRUE(file_stream.IsOpen());
ASSERT_CHECK_DEATH(
{ file_stream.ConnectNamedPipe(CompletionOnceCallback()); });
}
#endif
}
}