aboutsummaryrefslogtreecommitdiffstats
path: root/liblfjail/fileutils.hh
blob: 0824796af6302c4b53a8b01141fc853d0b7ca1a4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
 * This source code is released into the public domain.
 */

#ifndef	LFJAIL_READ_FILE_HH
#define	LFJAIL_READ_FILE_HH

#include <array>
#include <iterator>
#include <ranges>
#include <span>
#include <string>
#include <vector>

#include <fcntl.h>
#include <unistd.h>

#include "context.hh"
#include "io_error.hh"
#include "guard.hh"

namespace lfjail {

void ensure_dir(context const &ctx, std::string_view dir);

/*
 * Load the contents of a file into an output iterator.  Throws io_error
 * on failure.
 */

void read_file(std::string filename,
	       std::output_iterator<char> auto &&iter)
{
	constexpr std::size_t bufsize = 1024;
	std::array<char, bufsize> buffer;
	int fd, err;

	if ((fd = ::open(filename.c_str(), O_RDONLY)) == -1)
		throw io_error(filename, errno);

	auto fd_guard = guard([fd] { ::close(fd); });

	while ((err = ::read(fd, &buffer[0], buffer.size())) > 0) {
		auto data = std::span(buffer).subspan(0, err);
		std::ranges::copy(data, iter);
	}

	if (err == -1)
		throw io_error(filename, errno);
}


/*
 * Write the contents of a range to a file.  Throws io_error on error.
 */

void write_file(std::string filename, std::ranges::range auto &&range) {
	// Convert the range into an array.
	std::vector<char> chars;
	std::ranges::copy(range, std::back_inserter(chars));

	// Open the output file.
	int fd;

	if ((fd = ::open(filename.c_str(), O_CREAT|O_WRONLY, 0777)) == -1)
		throw io_error(filename, errno);

	auto fd_guard = guard([fd] { ::close(fd); });

	// Write the data.
	if (int err = ::write(fd, chars.data(), chars.size()); err < 0)
		throw io_error(filename, errno);
}

/*
 * Write the contents of a range to a file safely.  The data will be written
 * to "<filename>.tmp", and if the write succeeds, the temporary file will be
 * renamed to the target filename.  If an error occurs, the target file will
 * not be modified.
 */
void safe_write_file(std::string filename, std::ranges::range auto &&range) {
	auto tmpfile = filename + ".tmp";
	auto tmpfile_guard = guard([tmpfile] { ::unlink(tmpfile.c_str()); });

	write_file(tmpfile, range);
	int err = ::rename(tmpfile.c_str(), filename.c_str());
	if (err != 0)
		throw io_error(filename, errno);
}

} // namespace lfjail

#endif	// !LFJAIL_FILEUTILS_HH