~nabijaczleweli/klapki

ref: 1fee319d55dfd63d66122d036e426fb691f60ad2 klapki/src/context_commit.cpp -rw-r--r-- 7.5 KiB
1fee319dнаб https://twitter.com/nabijaczleweli/status/1307513189064740864 1 year, 1 month ago
                                                                                
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// The MIT License (MIT)

// Copyright (c) 2020 наб <nabijaczleweli@nabijaczleweli.xyz>

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


#include "config.hpp"
#include "context.hpp"
#include "quickscope_wrapper.hpp"
#include <algorithm>
#include <fcntl.h>
#include <set>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>


#define TRY_OPT(...)              \
	if(auto err = __VA_ARGS__; err) \
		return err;


/// https://stackoverflow.com/a/2180157/2851815 says FreeBSD and Darwin have fcopyfile(3),
/// but the only reference I could find was (a) copies of that answer and (b) Apple documentation, which wasn't helpful.
///
/// Plus, I've no idea if libefivar even works on Berkeley distros; it's got separate linux*.c implementations, but.
///
/// Just use sendfile(2) here and potentially ifdef for non-Linux later.
static std::optional<std::string> copy_file(int srcdir, int destdir, const char * basename) {
	auto srcfd = openat(srcdir, basename, O_RDONLY);
	if(srcfd < 0)
		return fmt::format("Couldn't open {} for reading: {}\n", basename, strerror(errno));
	klapki::quickscope_wrapper srcfd_deleter{[&] { close(srcfd); }};

	struct stat src_sb;
	if(fstat(srcfd, &src_sb) < 0)
		return fmt::format("Couldn't stat() source {}: {}\n", basename, strerror(errno));

	auto destfd = openat(destdir, basename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
	if(destfd < 0)
		return fmt::format("Couldn't open {} for writing: {}\n", basename, strerror(errno));
	klapki::quickscope_wrapper destfd_deleter{[&] {
		if(close(destfd))
			fmt::print(stderr, "Warning: destination {} errored on close: {}", basename, strerror(errno));
	}};

	off_t offset = 0;
	for(ssize_t res = 0; res < src_sb.st_size; res = sendfile(destfd, srcfd, &offset, src_sb.st_size)) {
		if(res < 0)
			return fmt::format("Couldn't copy to {} (offset {}): {}\n", basename, offset, strerror(errno));

		src_sb.st_size -= res;
	}

	return {};
}


std::optional<std::string> klapki::context::context::commit(const config & cfg, const state::state & state) {
	// TODO: parallelise the copying somehow?

	std::map<std::string_view, int> esp_dirs;
	quickscope_wrapper esp_dirs_deleter{[&] {
		for(auto && [dir, fd] : esp_dirs)
			close(fd);
	}};
	{
		auto esp_fd = open(cfg.esp.second, O_RDONLY | O_DIRECTORY | O_PATH);
		if(esp_fd < 0)
			return fmt::format("Couldn't open ESP ({}): {}\n", cfg.esp.second, strerror(errno));
		quickscope_wrapper esp_fd_deleter{[&] { close(esp_fd); }};

		for(auto && kern : this->our_kernels)
			if(esp_dirs.find(kern.second.image_path.first) == std::end(esp_dirs)) {
				auto dir = kern.second.image_path.first;
				std::transform(std::begin(dir), std::end(dir), std::begin(dir), [](auto c) { return c == '\\' ? '/' : c; });
				dir.erase(std::remove_if(std::begin(dir), std::end(dir),
				                         [prev = '\0'](auto c) mutable {
					                         if(prev == '/' && c == '/')
						                         return true;
					                         else {
						                         prev = c;
						                         return false;
					                         }
				                         }),
				          std::end(dir));
				if(dir.back() == '/')
					dir.pop_back();
				dir.erase(0, dir.find_first_not_of('/'));

				for(auto slash_idx = dir.find('/'); slash_idx != std::string::npos; slash_idx = dir.find('/', slash_idx + 1)) {
					dir[slash_idx] = '\0';
					if(mkdirat(esp_fd, dir.c_str(), 0755) < 0 && errno != EEXIST)
						return fmt::format("Couldn't create {} under ESP ({}): {}\n", dir.c_str(), cfg.esp.second, strerror(errno));
					dir[slash_idx] = '/';
				}
				if(mkdirat(esp_fd, dir.c_str(), 0755) < 0 && errno != EEXIST)
					return fmt::format("Couldn't create {} under ESP ({}): {}\n", dir, cfg.esp.second, strerror(errno));

				auto fd = openat(esp_fd, dir.c_str(), O_RDONLY | O_DIRECTORY | O_PATH);
				if(fd < 0)
					return fmt::format("Couldn't open {} under ESP ({}): {}\n", dir, cfg.esp.second, strerror(errno));
				esp_dirs.emplace(kern.second.image_path.first, fd);
			}
	}


	std::map<detail::bad_cow, int> source_dir_fds;
	quickscope_wrapper dir_fds_deleter{[&] {
		for(auto && [dir, fd] : source_dir_fds)
			if(fd >= 0)
				close(fd);  // No error checking, just directories
	}};

	// TODO: maybe, just maybe, deduplicate these?
	for(auto && skern : state.statecfg.wanted_entries) {
		source_dir_fds[detail::bad_cow{skern.kernel_dirname}] = -1;
		for(auto && initrd_dirname : skern.initrd_dirnames)
			if(initrd_dirname)
				source_dir_fds[detail::bad_cow{*initrd_dirname}] = -1;
	}

	for(auto && [path, fd] : source_dir_fds) {
		fd = open(path.get().data(), O_RDONLY | O_DIRECTORY | O_PATH);
		if(fd < 0)
			return fmt::format("Couldn't open {}: {}\n", path.get(), strerror(errno));
	}


	std::set<std::pair<int, std::string_view>> already_copied;
	auto do_copy = [&](auto bootnum, auto && srcdir, auto && destdir, auto && basename) -> std::optional<std::string> {
		auto destfd = esp_dirs.find(destdir);
		if(destfd == std::end(esp_dirs))
			return fmt::format("ESP dir {} not in cache?", destdir);

		if(already_copied.count(std::pair{destfd->second, basename})) {
			if(cfg.verbose)
				fmt::print("Entry {:04X}: already copied {} from {} to {}\n", bootnum, basename, srcdir, destdir);
			return {};
		}

		auto srcfd = source_dir_fds.find(detail::bad_cow{srcdir});
		if(srcfd == std::end(source_dir_fds))
			return fmt::format("Source dir {} not in cache?", srcdir);

		if(cfg.verbose)
			fmt::print("Entry {:04X}: copying {} from {} to {}\n", bootnum, basename, srcdir, destdir);
		TRY_OPT(copy_file(srcfd->second, destfd->second, basename.c_str()));
		already_copied.emplace(destfd->second, basename);
		return {};
	};

	for(auto && [bootnum, kern] : this->our_kernels) {
		auto skern = std::find_if(std::begin(state.statecfg.wanted_entries), std::end(state.statecfg.wanted_entries),
		                          [bn = bootnum](auto && skern) { return skern.bootnum_hint == bn; });
		if(skern == std::end(state.statecfg.wanted_entries))
			throw __func__;

		TRY_OPT(do_copy(bootnum, skern->kernel_dirname, kern.image_path.first, kern.image_path.second));

		if(skern->initrd_dirnames.size() != kern.initrd_paths.size())
			throw __func__;

		std::string_view sprev = skern->kernel_dirname;
		std::string_view dprev = kern.image_path.first;
		for(std::size_t i = 0; i < skern->initrd_dirnames.size(); ++i) {
			auto && [didir, dibase] = kern.initrd_paths[i];

			if(skern->initrd_dirnames[i])
				sprev = *skern->initrd_dirnames[i];
			if(didir)
				dprev = *didir;
			TRY_OPT(do_copy(bootnum, sprev, dprev, dibase));
		}
	}


	// TODO: delete old files from delkernel here


	return {};
}