Debian Codegraph @

src/checkout/entry.rs

raw symbols SCIP
1 use std::{
2 borrow::Cow,
3 io::Write,
4 path::{Path, PathBuf},
5 };
6
7 use bstr::BStr;
8 use gix_filter::{driver::apply::MaybeDelayed, pipeline::convert::ToWorktreeOutcome};
9 use gix_index::{entry::Stat, Entry};
10 use gix_object::FindExt;
11 use gix_worktree::Stack;
12 use io_close::Close;
13
14 pub struct Context<'a, Find> {
15 pub objects: &'a mut Find,
16 pub path_cache: &'a mut Stack,
17 pub filters: &'a mut gix_filter::Pipeline,
18 pub buf: &'a mut Vec<u8>,
19 }
20
21 /// A delayed result of a long-running filter process, which is made available as stream.
22 pub struct DelayedFilteredStream<'a> {
23 /// The key identifying the driver program
24 pub key: gix_filter::driver::Key,
25 /// If the file is going to be an executable.
26 pub needs_executable_bit: bool,
27 /// The validated path on disk at which the file should be placed.
28 pub validated_file_path: PathBuf,
29 /// The entry to adjust with the file we will write.
30 pub entry: &'a mut gix_index::Entry,
31 /// The relative path at which the entry resides (for use when querying the delayed entry).
32 pub entry_path: &'a BStr,
33 }
34
35 pub enum Outcome<'a> {
36 /// The file was written.
37 Written {
38 /// The amount of written bytes.
39 bytes: usize,
40 },
41 /// The will be ready later.
42 Delayed(DelayedFilteredStream<'a>),
43 }
44
45 impl Outcome<'_> {
46 /// Return ourselves as (in-memory) bytes if possible.
47 pub fn as_bytes(&self) -> Option<usize> {
48 match self {
49 Outcome::Written { bytes } => Some(*bytes),
50 Outcome::Delayed { .. } => None,
51 }
52 }
53 }
54
55 #[cfg_attr(not(unix), allow(unused_variables))]
56 pub fn checkout<'entry, Find>(
57 entry: &'entry mut Entry,
58 entry_path: &'entry BStr,
59 Context {
60 objects,
61 filters,
62 path_cache,
63 buf,
64 }: Context<'_, Find>,
65 crate::checkout::chunk::Options {
66 fs: gix_fs::Capabilities {
67 symlink,
68 executable_bit,
69 ..
70 },
71 destination_is_initially_empty,
72 overwrite_existing,
73 filter_process_delay,
74 ..
75 }: crate::checkout::chunk::Options,
76 ) -> Result<Outcome<'entry>, crate::checkout::Error>
77 where
78 Find: gix_object::Find,
79 {
80 let dest_relative = gix_path::try_from_bstr(entry_path).map_err(|_| crate::checkout::Error::IllformedUtf8 {
81 path: entry_path.to_owned(),
82 })?;
83 let path_cache = path_cache.at_path(dest_relative.as_ref(), Some(entry.mode), &*objects)?;
84 let dest = path_cache.path();
85
86 let object_size = match entry.mode {
87 gix_index::entry::Mode::FILE | gix_index::entry::Mode::FILE_EXECUTABLE => {
88 let obj = (*objects)
89 .find_blob(&entry.id, buf)
90 .map_err(|err| crate::checkout::Error::Find {
91 err,
92 path: dest.to_path_buf(),
93 })?;
94
95 let filtered = filters.convert_to_worktree(
96 obj.data,
97 entry_path,
98 &mut |_, attrs| {
99 path_cache.matching_attributes(attrs);
100 },
101 filter_process_delay,
102 )?;
103 let (num_bytes, file, set_executable_after_creation) = match filtered {
104 ToWorktreeOutcome::Unchanged(buf) | ToWorktreeOutcome::Buffer(buf) => {
105 let (mut file, flag) = open_file(
106 dest,
107 destination_is_initially_empty,
108 overwrite_existing,
109 executable_bit,
110 entry.mode,
111 )?;
112 file.write_all(buf)?;
113 (buf.len(), file, flag)
114 }
115 ToWorktreeOutcome::Process(MaybeDelayed::Immediate(mut filtered)) => {
116 let (mut file, flag) = open_file(
117 dest,
118 destination_is_initially_empty,
119 overwrite_existing,
120 executable_bit,
121 entry.mode,
122 )?;
123 let num_bytes = std::io::copy(&mut filtered, &mut file)? as usize;
124 (num_bytes, file, flag)
125 }
126 ToWorktreeOutcome::Process(MaybeDelayed::Delayed(key)) => {
127 return Ok(Outcome::Delayed(DelayedFilteredStream {
128 key,
129 needs_executable_bit: false,
130 validated_file_path: dest.to_owned(),
131 entry,
132 entry_path,
133 }))
134 }
135 };
136
137 // For possibly existing, overwritten files, we must change the file mode explicitly.
138 finalize_entry(entry, file, num_bytes as u64, set_executable_after_creation)?;
139 num_bytes
140 }
141 gix_index::entry::Mode::SYMLINK => {
142 let obj = (*objects)
143 .find_blob(&entry.id, buf)
144 .map_err(|err| crate::checkout::Error::Find {
145 err,
146 path: dest.to_path_buf(),
147 })?;
148 if symlink {
149 #[cfg_attr(not(windows), allow(unused_mut))]
150 let mut symlink_destination = Cow::Borrowed(
151 gix_path::try_from_byte_slice(obj.data)
152 .map_err(|_| crate::checkout::Error::IllformedUtf8 { path: obj.data.into() })?,
153 );
154 #[cfg(windows)]
155 {
156 symlink_destination = gix_path::to_native_path_on_windows(gix_path::into_bstr(symlink_destination))
157 }
158
159 try_op_or_unlink(dest, overwrite_existing, |p| {
160 gix_fs::symlink::create(symlink_destination.as_ref(), p)
161 })?;
162 } else {
163 let mut file = try_op_or_unlink(dest, overwrite_existing, |p| {
164 open_options(p, destination_is_initially_empty, overwrite_existing).open(dest)
165 })?;
166 file.write_all(obj.data)?;
167 file.close()?;
168 }
169
170 entry.stat = Stat::from_fs(&gix_index::fs::Metadata::from_path_no_follow(dest)?)?;
171 obj.data.len()
172 }
173 gix_index::entry::Mode::DIR => {
174 gix_features::trace::warn!(
175 "Skipped sparse directory at '{entry_path}' ({id}) as it cannot yet be handled",
176 id = entry.id
177 );
178 0
179 }
180 gix_index::entry::Mode::COMMIT => {
181 gix_features::trace::warn!(
182 "Skipped submodule at '{entry_path}' ({id}) as it cannot yet be handled",
183 id = entry.id
184 );
185 0
186 }
187 _ => unreachable!(),
188 };
189 Ok(Outcome::Written { bytes: object_size })
190 }
191
192 /// Note that this works only because we assume to not race ourselves when symlinks are involved, and we do this by
193 /// delaying symlink creation to the end and will always do that sequentially.
194 /// It's still possible to fall for a race if other actors create symlinks in our path, but that's nothing to defend against.
195 fn try_op_or_unlink<T>(
196 path: &Path,
197 overwrite_existing: bool,
198 op: impl Fn(&Path) -> std::io::Result<T>,
199 ) -> std::io::Result<T> {
200 if overwrite_existing {
201 match op(path) {
202 Ok(res) => Ok(res),
203 Err(err) if gix_fs::symlink::is_collision_error(&err) => {
204 try_unlink_path_recursively(path, &std::fs::symlink_metadata(path)?)?;
205 op(path)
206 }
207 Err(err) => Err(err),
208 }
209 } else {
210 op(path)
211 }
212 }
213
214 fn try_unlink_path_recursively(path: &Path, path_meta: &std::fs::Metadata) -> std::io::Result<()> {
215 if path_meta.is_dir() {
216 std::fs::remove_dir_all(path)
217 } else if path_meta.file_type().is_symlink() {
218 gix_fs::symlink::remove(path)
219 } else {
220 std::fs::remove_file(path)
221 }
222 }
223
224 #[cfg(not(debug_assertions))]
225 fn debug_assert_dest_is_no_symlink(_path: &Path) {}
226
227 /// This is a debug assertion as we expect the machinery calling this to prevent this possibility in the first place
228 #[cfg(debug_assertions)]
229 fn debug_assert_dest_is_no_symlink(path: &Path) {
230 if let Ok(meta) = path.metadata() {
231 debug_assert!(
232 !meta.file_type().is_symlink(),
233 "BUG: should not ever allow to overwrite/write-into the target of a symbolic link: {}",
234 path.display()
235 );
236 }
237 }
238
239 fn open_options(path: &Path, destination_is_initially_empty: bool, overwrite_existing: bool) -> std::fs::OpenOptions {
240 if overwrite_existing || !destination_is_initially_empty {
241 debug_assert_dest_is_no_symlink(path);
242 }
243 let mut options = gix_features::fs::open_options_no_follow();
244 options
245 .create_new(destination_is_initially_empty && !overwrite_existing)
246 .create(!destination_is_initially_empty || overwrite_existing)
247 .write(true)
248 .truncate(true);
249 options
250 }
251
252 pub(crate) fn open_file(
253 path: &Path,
254 destination_is_initially_empty: bool,
255 overwrite_existing: bool,
256 fs_supports_executable_bit: bool,
257 entry_mode: gix_index::entry::Mode,
258 ) -> std::io::Result<(std::fs::File, bool)> {
259 #[cfg_attr(windows, allow(unused_mut))]
260 let mut options = open_options(path, destination_is_initially_empty, overwrite_existing);
261 let needs_executable_bit = fs_supports_executable_bit && entry_mode == gix_index::entry::Mode::FILE_EXECUTABLE;
262 #[cfg(unix)]
263 let set_executable_after_creation = if needs_executable_bit && destination_is_initially_empty {
264 use std::os::unix::fs::OpenOptionsExt;
265 // Note that these only work if the file was newly created, but won't if it's already
266 // existing, possibly without the executable bit set. Thus we do this only if the file is new.
267 options.mode(0o777);
268 false
269 } else {
270 needs_executable_bit
271 };
272 // not supported on windows
273 #[cfg(windows)]
274 let set_executable_after_creation = needs_executable_bit;
275 try_op_or_unlink(path, overwrite_existing, |p| options.open(p)).map(|f| (f, set_executable_after_creation))
276 }
277
278 /// Close `file` and store its stats in `entry`, possibly setting `file` executable.
279 ///
280 /// `desired_bytes` is the amount of bytes Git thinks the file should have after writing.
281 pub(crate) fn finalize_entry(
282 entry: &mut gix_index::Entry,
283 file: std::fs::File,
284 desired_bytes: u64,
285 #[cfg_attr(windows, allow(unused_variables))] set_executable_after_creation: bool,
286 ) -> Result<(), crate::checkout::Error> {
287 // For possibly existing, overwritten files, we must change the file mode explicitly.
288 #[cfg(unix)]
289 if set_executable_after_creation {
290 set_executable(&file)?;
291 }
292
293 let md = &gix_index::fs::Metadata::from_file(&file)?;
294 // A last sanity check: if the file wasn't truncated upon opening, which is good in case something
295 // goes wrong during writing, not everything is lost, then after writing the file is smaller than it was
296 // before, it needs truncation. We do that here.
297 let needs_truncation = md.len() > desired_bytes;
298 if needs_truncation {
299 file.set_len(desired_bytes)?;
300 }
301 // NOTE: we don't call `file.sync_all()` here knowing that some filesystems don't handle this well.
302 // revisit this once there is a bug to fix.
303 entry.stat = Stat::from_fs(md)?;
304 file.close()?;
305 Ok(())
306 }
307
308 /// Use `fstat` and `fchmod` on a file descriptor to make a regular file executable.
309 ///
310 /// See `let_readers_execute` for the exact details of how the mode is transformed.
311 #[cfg(unix)]
312 fn set_executable(file: &std::fs::File) -> Result<(), std::io::Error> {
313 use std::os::unix::fs::{MetadataExt, PermissionsExt};
314 let old_mode = file.metadata()?.mode();
315 let new_mode = let_readers_execute(old_mode);
316 file.set_permissions(std::fs::Permissions::from_mode(new_mode))?;
317 Ok(())
318 }
319
320 /// Given the st_mode of a regular file, compute the mode with executable bits safely added.
321 ///
322 /// Currently this adds executable bits for whoever has read bits already. It doesn't use the umask.
323 /// Set-user-ID and set-group-ID bits are unset for safety. The sticky bit is also unset.
324 ///
325 /// This returns only mode bits, not file type. The return value can be used in chmod or fchmod.
326 #[cfg(any(unix, test))]
327 fn let_readers_execute(mut mode: u32) -> u32 {
328 assert_eq!(mode & 0o170000, 0o100000, "bug in caller if not from a regular file");
329 mode &= 0o777; // Clear type, non-rwx mode bits (setuid, setgid, sticky).
330 mode |= (mode & 0o444) >> 2; // Let readers also execute.
331 mode
332 }
333
334 #[cfg(test)]
335 mod tests {
336 #[test]
337 fn let_readers_execute() {
338 let cases = [
339 // Common cases:
340 (0o100755, 0o755),
341 (0o100644, 0o755),
342 (0o100750, 0o750),
343 (0o100640, 0o750),
344 (0o100700, 0o700),
345 (0o100600, 0o700),
346 (0o100775, 0o775),
347 (0o100664, 0o775),
348 (0o100770, 0o770),
349 (0o100660, 0o770),
350 (0o100764, 0o775),
351 (0o100760, 0o770),
352 // Less common:
353 (0o100674, 0o775),
354 (0o100670, 0o770),
355 (0o100000, 0o000),
356 (0o100400, 0o500),
357 (0o100440, 0o550),
358 (0o100444, 0o555),
359 (0o100462, 0o572),
360 (0o100242, 0o252),
361 (0o100167, 0o177),
362 // With set-user-ID, set-group-ID, and sticky bits:
363 (0o104755, 0o755),
364 (0o104644, 0o755),
365 (0o102755, 0o755),
366 (0o102644, 0o755),
367 (0o101755, 0o755),
368 (0o101644, 0o755),
369 (0o106755, 0o755),
370 (0o106644, 0o755),
371 (0o104750, 0o750),
372 (0o104640, 0o750),
373 (0o102750, 0o750),
374 (0o102640, 0o750),
375 (0o101750, 0o750),
376 (0o101640, 0o750),
377 (0o106750, 0o750),
378 (0o106640, 0o750),
379 (0o107644, 0o755),
380 (0o107000, 0o000),
381 (0o106400, 0o500),
382 (0o102462, 0o572),
383 ];
384 for (st_mode, expected) in cases {
385 let actual = super::let_readers_execute(st_mode);
386 assert_eq!(
387 actual, expected,
388 "{st_mode:06o} should become {expected:04o}, became {actual:04o}"
389 );
390 }
391 }
392
393 #[test]
394 #[should_panic]
395 fn let_readers_execute_panics_on_directory() {
396 super::let_readers_execute(0o040644);
397 }
398
399 #[test]
400 #[should_panic]
401 fn let_readers_execute_should_panic_on_symlink() {
402 super::let_readers_execute(0o120644);
403 }
404 }