Repository navigation
Expand file tree
/
Copy pathtool_bundle_install.rs
More file actions
268 lines (268 loc) · 9.21 KB
/
Copy pathtool_bundle_install.rs
File metadata and controls
268 lines (268 loc) · 9.21 KB
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
//! 完整工具树的有界私有暂存与不覆盖原子目录发布。
use crate::bundle_cache_fs::{budget, children, name, open_dir, parent, private};
use crate::bundle_install_stage::BundleInstallStage;
use crate::{InstalledBundle, UnpackedArchive, verify_unpacked_bundle_tree};
use std::collections::BTreeMap;
use std::fs::{File, OpenOptions, Permissions};
use std::io::{Read, Write};
use std::os::fd::{AsRawFd, FromRawFd};
use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};
use std::path::Path;
use std::sync::atomic::AtomicBool;
use std::time::Instant;
/// 将完整已匹配工具树发布为单个内容寻址目录,失败不覆盖已有目录。
/// 参数为已存在缓存、冻结树、预期摘要及共享预算;返回经重验的相对定位。
/// 不下载/执行/批准来源,调用方必须独立绑定清单、平台和工具准备。
pub fn publish_tool_bundle(
cache_root: &Path,
tree: &UnpackedArchive,
expected: &str,
deadline: Instant,
cancelled: &AtomicBool,
) -> Result<InstalledBundle, &'static str> {
budget(deadline, cancelled)?;
if !cache_root.is_absolute() {
return Err("bundle_install_cache_invalid");
}
verify_unpacked_bundle_tree(tree, expected, deadline, cancelled)?;
let cache = OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW | libc::O_DIRECTORY | libc::O_CLOEXEC)
.open(cache_root)
.map_err(|_| "bundle_install_cache_invalid")?;
let m = cache
.metadata()
.map_err(|_| "bundle_install_cache_invalid")?;
if !m.is_dir() || m.uid() != unsafe { libc::geteuid() } || m.mode() & 0o022 != 0 {
return Err("bundle_install_cache_permissions_invalid");
}
let relative_path = format!("{expected}.bundle");
let destination = name(&relative_path)?;
let byte_len = tree.files.iter().map(|f| f.bytes.len() as u64).sum();
if exists(&cache, &relative_path, tree, deadline, cancelled)? {
return Ok(InstalledBundle {
relative_path,
newly_published: false,
byte_len,
});
}
let mut stage = BundleInstallStage::create(&cache)?;
stage
.directory
.set_permissions(Permissions::from_mode(0o700))
.map_err(|_| "bundle_install_stage_write_failed")?;
let mut dirs: Vec<_> = tree.directories.iter().collect();
dirs.sort();
for path in dirs {
budget(deadline, cancelled)?;
let (fd, leaf) = parent(&stage.directory, path)?;
if unsafe { libc::mkdirat(fd.as_raw_fd(), leaf.as_ptr(), 0o700) } != 0 {
return Err("bundle_install_stage_write_failed");
}
stage.directories.push(path.clone());
open_dir(
&fd,
leaf.to_str().map_err(|_| "bundle_install_path_invalid")?,
)?
.set_permissions(Permissions::from_mode(0o700))
.map_err(|_| "bundle_install_stage_write_failed")?;
}
for input in &tree.files {
budget(deadline, cancelled)?;
let (fd, leaf) = parent(&stage.directory, &input.relative_path)?;
let raw = unsafe {
libc::openat(
fd.as_raw_fd(),
leaf.as_ptr(),
libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_WRONLY,
0o700,
)
};
if raw < 0 {
return Err("bundle_install_stage_write_failed");
}
let mut file = unsafe { File::from_raw_fd(raw) };
stage.files.push(input.relative_path.clone());
file.set_permissions(Permissions::from_mode(0o700))
.map_err(|_| "bundle_install_stage_write_failed")?;
for chunk in input.bytes.chunks(128 * 1024) {
budget(deadline, cancelled)?;
file.write_all(chunk)
.map_err(|_| "bundle_install_stage_write_failed")?;
}
file.sync_all()
.map_err(|_| "bundle_install_stage_sync_failed")?;
}
for path in stage.directories.iter().rev() {
let (fd, leaf) = parent(&stage.directory, path)?;
open_dir(
&fd,
leaf.to_str().map_err(|_| "bundle_install_path_invalid")?,
)?
.sync_all()
.map_err(|_| "bundle_install_stage_sync_failed")?;
}
stage
.directory
.sync_all()
.map_err(|_| "bundle_install_stage_sync_failed")?;
verify(&stage.directory, tree, deadline, cancelled)?;
budget(deadline, cancelled)?;
// 两个平台均使用原生独占重命名;不退回可能覆盖目录的普通 rename。
#[cfg(target_os = "macos")]
let renamed = unsafe {
libc::renameatx_np(
cache.as_raw_fd(),
stage.name.as_ptr(),
cache.as_raw_fd(),
destination.as_ptr(),
libc::RENAME_EXCL,
)
};
#[cfg(target_os = "linux")]
let renamed = unsafe {
libc::renameat2(
cache.as_raw_fd(),
stage.name.as_ptr(),
cache.as_raw_fd(),
destination.as_ptr(),
libc::RENAME_NOREPLACE,
)
};
let newly_published = renamed == 0;
if newly_published {
stage.published = true;
} else if std::io::Error::last_os_error().raw_os_error() != Some(libc::EEXIST) {
return Err("bundle_install_publish_failed");
}
drop(stage);
cache
.sync_all()
.map_err(|_| "bundle_install_cache_sync_failed")?;
if !exists(&cache, &relative_path, tree, deadline, cancelled)? {
return Err("bundle_installed_tree_invalid");
}
budget(deadline, cancelled)?;
Ok(InstalledBundle {
relative_path,
newly_published,
byte_len,
})
}
fn exists(
cache: &File,
value: &str,
tree: &UnpackedArchive,
deadline: Instant,
cancelled: &AtomicBool,
) -> Result<bool, &'static str> {
let leaf = name(value)?;
let raw = unsafe {
libc::openat(
cache.as_raw_fd(),
leaf.as_ptr(),
libc::O_RDONLY
| libc::O_DIRECTORY
| libc::O_NOFOLLOW
| libc::O_CLOEXEC
| libc::O_NONBLOCK,
)
};
if raw < 0 {
return if std::io::Error::last_os_error().raw_os_error() == Some(libc::ENOENT) {
Ok(false)
} else {
Err("bundle_installed_tree_invalid")
};
}
let directory = unsafe { File::from_raw_fd(raw) };
verify(&directory, tree, deadline, cancelled)?;
Ok(true)
}
fn verify(
root: &File,
tree: &UnpackedArchive,
deadline: Instant,
cancelled: &AtomicBool,
) -> Result<(), &'static str> {
budget(deadline, cancelled)?;
private(root, true)?;
let mut members: BTreeMap<String, Vec<String>> = BTreeMap::new();
members.insert(String::new(), Vec::new());
for path in &tree.directories {
members.entry(path.clone()).or_default();
}
for path in tree
.directories
.iter()
.map(String::as_str)
.chain(tree.files.iter().map(|f| f.relative_path.as_str()))
{
let (parent, leaf) = path.rsplit_once('/').unwrap_or(("", path));
members
.get_mut(parent)
.ok_or("bundle_installed_tree_invalid")?
.push(leaf.to_owned());
}
for (path, mut expected) in members {
budget(deadline, cancelled)?;
let directory = if path.is_empty() {
root.try_clone()
.map_err(|_| "bundle_installed_tree_invalid")?
} else {
let (fd, leaf) = parent(root, &path)?;
open_dir(
&fd,
leaf.to_str().map_err(|_| "bundle_install_path_invalid")?,
)?
};
private(&directory, true)?;
expected.sort();
if children(&directory, deadline, cancelled)? != expected {
return Err("bundle_installed_tree_invalid");
}
}
for input in &tree.files {
budget(deadline, cancelled)?;
let (fd, leaf) = parent(root, &input.relative_path)?;
let raw = unsafe {
libc::openat(
fd.as_raw_fd(),
leaf.as_ptr(),
libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK,
)
};
if raw < 0 {
return Err("bundle_installed_tree_invalid");
}
let mut file = unsafe { File::from_raw_fd(raw) };
private(&file, false)?;
if file
.metadata()
.map_err(|_| "bundle_installed_tree_invalid")?
.len()
!= input.bytes.len() as u64
{
return Err("bundle_installed_tree_invalid");
}
let mut buffer = vec![0; 128 * 1024];
for chunk in input.bytes.chunks(buffer.len()) {
budget(deadline, cancelled)?;
file.read_exact(&mut buffer[..chunk.len()])
.map_err(|_| "bundle_installed_tree_invalid")?;
if buffer[..chunk.len()] != *chunk {
return Err("bundle_installed_tree_invalid");
}
}
let mut tail = [0];
if file
.read(&mut tail)
.map_err(|_| "bundle_installed_tree_invalid")?
!= 0
{
return Err("bundle_installed_tree_invalid");
}
private(&file, false)?;
}
budget(deadline, cancelled)
}