ziperu 0.2.3 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +190 -0
  3. data/Cargo.lock +2 -1
  4. data/README.md +35 -7
  5. data/ext/ziperu/Cargo.toml +9 -1
  6. data/ext/ziperu/src/archive.rs +246 -144
  7. data/ext/ziperu/src/entry_options.rs +1 -1
  8. data/ext/ziperu/src/errors.rs +39 -11
  9. data/ext/ziperu/src/extract.rs +332 -104
  10. data/ext/ziperu/src/gvl.rs +45 -26
  11. data/ext/ziperu/src/lib.rs +17 -0
  12. data/ext/ziperu/src/place.rs +379 -0
  13. data/ext/ziperu/src/rb.rs +14 -1
  14. data/ext/ziperu/src/reader.rs +100 -29
  15. data/ext/ziperu/src/sink.rs +2 -7
  16. data/ext/ziperu/src/source.rs +4 -7
  17. data/ext/ziperu/src/stream.rs +89 -11
  18. data/ext/ziperu/src/test_rng.rs +37 -0
  19. data/ext/ziperu/src/writer.rs +71 -25
  20. data/ext/ziperu/src/zipcrypto.rs +40 -12
  21. data/lib/zip.rb +3 -3
  22. data/lib/ziperu/central_directory.rb +4 -8
  23. data/lib/ziperu/constants.rb +8 -0
  24. data/lib/ziperu/crypto.rb +10 -2
  25. data/lib/ziperu/dos_time.rb +1 -1
  26. data/lib/ziperu/entry/source.rb +41 -6
  27. data/lib/ziperu/entry.rb +252 -112
  28. data/lib/ziperu/entry_set.rb +0 -5
  29. data/lib/ziperu/errors.rb +4 -2
  30. data/lib/ziperu/extra_field/zip64.rb +1 -3
  31. data/lib/ziperu/extra_field.rb +10 -10
  32. data/lib/ziperu/file/commit.rb +255 -0
  33. data/lib/ziperu/file/extraction.rb +285 -0
  34. data/lib/ziperu/file.rb +77 -405
  35. data/lib/ziperu/file_split.rb +1 -3
  36. data/lib/ziperu/filesystem/dir.rb +3 -9
  37. data/lib/ziperu/filesystem/file.rb +2 -6
  38. data/lib/ziperu/filesystem/zip_file_name_mapper.rb +2 -2
  39. data/lib/ziperu/input_stream.rb +30 -32
  40. data/lib/ziperu/ioextras/abstract_input_stream.rb +83 -31
  41. data/lib/ziperu/ioextras/abstract_output_stream.rb +1 -3
  42. data/lib/ziperu/ioextras/fake_io.rb +1 -3
  43. data/lib/ziperu/ioextras.rb +6 -0
  44. data/lib/ziperu/limits.rb +48 -0
  45. data/lib/ziperu/null_input_stream.rb +1 -1
  46. data/lib/ziperu/output_stream.rb +118 -31
  47. data/lib/ziperu/pass_thru_decompressor.rb +1 -3
  48. data/lib/ziperu/rails_streaming.rb +5 -5
  49. data/lib/ziperu/remote_io.rb +181 -32
  50. data/lib/ziperu/size_estimator.rb +27 -19
  51. data/lib/ziperu/verify_report.rb +62 -0
  52. data/lib/ziperu/version.rb +2 -2
  53. data/lib/ziperu.rb +19 -17
  54. metadata +8 -1
@@ -29,15 +29,23 @@ use std::thread::Result as ThreadResult;
29
29
  /// `with_token`.
30
30
  pub type Token = Option<Arc<AtomicBool>>;
31
31
 
32
- // The initializer is already `const`; the lint misreads the macro.
32
+ // The initializers are already `const`; the lint misreads the macro.
33
33
  #[allow(clippy::missing_const_for_thread_local)]
34
- mod token_slot {
34
+ mod slots {
35
35
  use super::{RefCell, Token};
36
36
  thread_local! {
37
37
  pub(super) static TOKEN: RefCell<Token> = const { RefCell::new(None) };
38
+ /// An exception that handling routine interrupts raised, for
39
+ /// `errors::interrupted` to raise in its place. It is the thread's
40
+ /// `$!` meanwhile, which keeps it alive.
41
+ pub(super) static RAISED: RefCell<Option<magnus::Error>> = const { RefCell::new(None) };
38
42
  }
39
43
  }
40
- use token_slot::TOKEN;
44
+ use slots::{RAISED, TOKEN};
45
+
46
+ /// How often Ruby may decline to release the GVL (see `without_gvl`)
47
+ /// before the work is run with it held.
48
+ const MAX_REFUSALS: u32 = 3;
41
49
 
42
50
  /// The error a loop returns when its call has been asked to stop.
43
51
  #[derive(Debug)]
@@ -147,19 +155,17 @@ pub fn without_gvl<F: FnOnce() -> R, R>(f: F) -> R {
147
155
  f: Some(run),
148
156
  out: None,
149
157
  };
150
- // SAFETY: `call` and `flag` live for the whole blocking call; the
151
- // unblock function only stores to the flag. The `2` variant matters:
152
- // plain `rb_thread_call_without_gvl` checks for pending interrupts on
158
+ // The `2` variant matters: plain `rb_thread_call_without_gvl` checks for pending interrupts on
153
159
  // the way out and raises them with a longjmp straight through these
154
160
  // Rust frames, skipping their destructors (a `RefCell` borrow left
155
161
  // held, a buffer leaked). This one leaves that to the caller, and the
156
162
  // `Cancelled` error our loops return gets the interrupt raised the
157
163
  // safe way (`errors::interrupted`), or Ruby raises it at its next
158
164
  // check once we are back in Ruby code.
159
- // SAFETY (each call): `call` and `flag` outlive it, and the unblock
160
- // function only stores to the flag.
161
165
  let mut refusals = 0;
162
166
  loop {
167
+ // SAFETY: `call` and `flag` outlive the blocking call, and the
168
+ // unblock function only stores to the flag.
163
169
  unsafe {
164
170
  rb_sys::rb_thread_call_without_gvl2(
165
171
  Some(trampoline_for(&call)),
@@ -183,7 +189,7 @@ pub fn without_gvl<F: FnOnce() -> R, R>(f: F) -> R {
183
189
  return run();
184
190
  }
185
191
  refusals += 1;
186
- if refusals > 3 {
192
+ if refusals > MAX_REFUSALS {
187
193
  // Refused again and again: run it here, as it always could.
188
194
  return run();
189
195
  }
@@ -201,14 +207,28 @@ pub fn without_gvl<F: FnOnce() -> R, R>(f: F) -> R {
201
207
 
202
208
  /// Whether an exception is queued for this thread, waiting for its next
203
209
  /// interrupt check: `Thread#pending_interrupt?`, which leaves it queued.
210
+ ///
211
+ /// Calling a method is itself an interrupt check, so the exception can be
212
+ /// raised by this very call. It is then no longer queued anywhere: it is
213
+ /// kept for `errors::interrupted` to raise, and this says it is pending.
214
+ /// Dropping it, as this once did, lost the exception for good: a
215
+ /// `Timeout` that fired at that moment never fired again, and the work it
216
+ /// guarded ran on.
204
217
  fn exception_pending() -> bool {
205
218
  use magnus::prelude::*;
206
219
  let Ok(ruby) = magnus::Ruby::get() else {
207
220
  return false;
208
221
  };
209
- ruby.thread_current()
222
+ match ruby
223
+ .thread_current()
210
224
  .funcall::<_, _, bool>("pending_interrupt?", ())
211
- .unwrap_or(false)
225
+ {
226
+ Ok(pending) => pending,
227
+ Err(raised) => {
228
+ RAISED.with(|r| *r.borrow_mut() = Some(raised));
229
+ true
230
+ }
231
+ }
212
232
  }
213
233
 
214
234
  /// Lets Ruby handle the interrupts it has pending for this thread, none of
@@ -220,16 +240,8 @@ fn handle_routine_interrupts() -> bool {
220
240
  let Ok(ruby) = magnus::Ruby::get() else {
221
241
  return false;
222
242
  };
223
- use magnus::rb_sys::AsRawValue;
224
- let nil = ruby.qnil().as_raw();
225
- // SAFETY: the GVL is held; `protect` turns what `rb_thread_check_ints`
226
- // raises into an `Err` rather than a longjmp through Rust frames.
227
- let result = magnus::rb_sys::protect(|| {
228
- unsafe { rb_sys::rb_thread_check_ints() };
229
- nil
230
- });
231
- match result {
232
- Ok(_) => true,
243
+ match check_ints(&ruby) {
244
+ Ok(()) => true,
233
245
  Err(e) => {
234
246
  RAISED.with(|r| *r.borrow_mut() = Some(e));
235
247
  false
@@ -237,11 +249,18 @@ fn handle_routine_interrupts() -> bool {
237
249
  }
238
250
  }
239
251
 
240
- thread_local! {
241
- /// An exception that handling routine interrupts raised, for
242
- /// `errors::interrupted` to raise in its place. It is the thread's
243
- /// `$!` meanwhile, which keeps it alive.
244
- static RAISED: RefCell<Option<magnus::Error>> = const { RefCell::new(None) };
252
+ /// Has Ruby handle this thread's pending interrupts now. An exception
253
+ /// among them comes back as the error instead of being raised.
254
+ pub fn check_ints(ruby: &magnus::Ruby) -> Result<(), magnus::Error> {
255
+ use magnus::rb_sys::AsRawValue;
256
+ let nil = ruby.qnil().as_raw();
257
+ magnus::rb_sys::protect(|| {
258
+ // SAFETY: the GVL is held, and `protect` turns what this raises
259
+ // into an `Err` rather than a longjmp through Rust frames.
260
+ unsafe { rb_sys::rb_thread_check_ints() };
261
+ nil
262
+ })
263
+ .map(|_| ())
245
264
  }
246
265
 
247
266
  /// The exception `handle_routine_interrupts` caught, if any; taken.
@@ -9,12 +9,15 @@ mod entry_options;
9
9
  mod errors;
10
10
  mod extract;
11
11
  mod gvl;
12
+ mod place;
12
13
  mod rb;
13
14
  mod reader;
14
15
  mod sink;
15
16
  mod source;
16
17
  mod stream;
17
18
  mod stream_stats;
19
+ #[cfg(test)]
20
+ mod test_rng;
18
21
  mod writer;
19
22
  mod zipcrypto;
20
23
 
@@ -26,12 +29,25 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
26
29
  let native = zip.define_module("Native")?;
27
30
 
28
31
  let archive = native.define_class("Archive", ruby.class_object())?;
32
+ // What each position of an `each_entry_row` row holds, and the keys of
33
+ // the Hashes; `Entry::ROW_FIELDS` is checked against it.
34
+ let row_fields = ruby.ary_from_iter(archive::ROW_FIELDS.iter().map(|f| ruby.to_symbol(f)));
35
+ row_fields.freeze();
36
+ archive.const_set("ROW_FIELDS", row_fields)?;
29
37
  archive.define_singleton_method("open_path", function!(archive::Archive::open_path, 1))?;
30
38
  archive.define_singleton_method("open_bytes", function!(archive::Archive::open_bytes, 1))?;
31
39
  archive.define_singleton_method("open_io", function!(archive::Archive::open_io, 1))?;
32
40
  archive.define_method("entry_count", method!(archive::Archive::entry_count, 0))?;
33
41
  archive.define_method("entries", method!(archive::Archive::entries, 0))?;
34
42
  archive.define_method("each_entry", method!(archive::Archive::each_entry, 0))?;
43
+ archive.define_method(
44
+ "each_entry_row",
45
+ method!(archive::Archive::each_entry_row, 0),
46
+ )?;
47
+ archive.define_method(
48
+ "indices_with_extra_fields",
49
+ method!(archive::Archive::indices_with_extra_fields, 2),
50
+ )?;
35
51
  archive.define_method("entry_meta", method!(archive::Archive::entry_meta, 1))?;
36
52
  archive.define_method("entry_metas", method!(archive::Archive::entry_metas, 2))?;
37
53
  archive.define_method("local_extra", method!(archive::Archive::local_extra, 1))?;
@@ -95,6 +111,7 @@ fn init(ruby: &Ruby) -> Result<(), Error> {
95
111
  writer.define_method("write", method!(writer::Writer::write, 1))?;
96
112
  writer.define_method("write_file", method!(writer::Writer::write_file, 1))?;
97
113
  writer.define_method("raw_copy", method!(writer::Writer::raw_copy, 4))?;
114
+ writer.define_method("raw_copy_many", method!(writer::Writer::raw_copy_many, 2))?;
98
115
  writer.define_method("copy_zipcrypto", method!(writer::Writer::copy_zipcrypto, 4))?;
99
116
  writer.define_method("comment=", method!(writer::Writer::set_comment, 1))?;
100
117
  writer.define_method("rollback_entry", method!(writer::Writer::rollback_entry, 0))?;
@@ -0,0 +1,379 @@
1
+ //! Where extraction creates things, without going through a link.
2
+ //!
3
+ //! `extract.rs` first walks each path with `lstat` and refuses links, which
4
+ //! is enough unless someone swaps a directory for a link in between. On
5
+ //! Linux 5.6 and later this module closes that gap: the destination is
6
+ //! opened once, and every directory a file goes into is opened from it with
7
+ //! `openat2(RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS)`, so the kernel refuses a
8
+ //! link anywhere on the way (`ELOOP`) or a path that leaves the destination
9
+ //! (`EXDEV`). The file is then created, renamed and removed relative to
10
+ //! that directory handle, with `O_NOFOLLOW` at the leaf.
11
+ //!
12
+ //! Elsewhere (Windows, macOS, an older kernel, or a sandbox that refuses
13
+ //! the system call) the same operations go by path, and only the `lstat`
14
+ //! walk stands between a write and a link.
15
+
16
+ use std::fs::{self, File, OpenOptions};
17
+ use std::io;
18
+ use std::path::{Path, PathBuf};
19
+ use std::sync::atomic::{AtomicU64, Ordering};
20
+
21
+ /// The destination, opened when the OS can resolve paths beneath it.
22
+ pub(crate) struct Beneath {
23
+ #[cfg(target_os = "linux")]
24
+ root: Option<std::os::fd::OwnedFd>,
25
+ }
26
+
27
+ /// A directory to create things in: `path` always, and on Linux a handle
28
+ /// on it opened beneath the destination.
29
+ #[derive(Debug)]
30
+ pub(crate) struct Place {
31
+ path: PathBuf,
32
+ #[cfg(target_os = "linux")]
33
+ fd: Option<std::os::fd::OwnedFd>,
34
+ }
35
+
36
+ /// Whether `e` says a link stood in the way: what `openat2` and
37
+ /// `O_NOFOLLOW` fail with.
38
+ pub(crate) fn is_link_error(e: &io::Error) -> bool {
39
+ #[cfg(target_os = "linux")]
40
+ {
41
+ matches!(e.raw_os_error(), Some(libc::ELOOP | libc::EXDEV))
42
+ }
43
+ #[cfg(all(unix, not(target_os = "linux")))]
44
+ {
45
+ e.raw_os_error() == Some(libc::ELOOP)
46
+ }
47
+ #[cfg(not(unix))]
48
+ {
49
+ let _ = e;
50
+ false
51
+ }
52
+ }
53
+
54
+ impl Beneath {
55
+ /// Opens the destination `root` (an existing directory, taken as
56
+ /// given even when it is itself a link).
57
+ pub(crate) fn new(root: &Path) -> Self {
58
+ #[cfg(target_os = "linux")]
59
+ {
60
+ Self {
61
+ root: linux::open_root(root),
62
+ }
63
+ }
64
+ #[cfg(not(target_os = "linux"))]
65
+ {
66
+ let _ = root;
67
+ Self {}
68
+ }
69
+ }
70
+
71
+ /// Whether paths are resolved by the kernel beneath the destination.
72
+ #[cfg(all(test, target_os = "linux"))]
73
+ pub(crate) fn is_race_free(&self) -> bool {
74
+ self.root.is_some()
75
+ }
76
+
77
+ /// The directory `path`, which is `below` (relative, `/`-separated,
78
+ /// empty for the destination itself) under the destination.
79
+ pub(crate) fn place(&self, path: &Path, below: &str) -> io::Result<Place> {
80
+ #[cfg(target_os = "linux")]
81
+ {
82
+ let fd = match &self.root {
83
+ Some(root) => Some(linux::open_beneath(
84
+ root,
85
+ below,
86
+ libc::O_PATH | libc::O_DIRECTORY,
87
+ )?),
88
+ None => None,
89
+ };
90
+ Ok(Place {
91
+ path: path.to_path_buf(),
92
+ fd,
93
+ })
94
+ }
95
+ #[cfg(not(target_os = "linux"))]
96
+ {
97
+ let _ = below;
98
+ Ok(Place {
99
+ path: path.to_path_buf(),
100
+ })
101
+ }
102
+ }
103
+
104
+ /// A handle on the directory `path` (`below` under the destination)
105
+ /// to set its times and mode through.
106
+ pub(crate) fn directory_handle(&self, path: &Path, below: &str) -> io::Result<File> {
107
+ #[cfg(target_os = "linux")]
108
+ if let Some(root) = &self.root {
109
+ return linux::open_beneath(root, below, libc::O_RDONLY | libc::O_DIRECTORY)
110
+ .map(File::from);
111
+ }
112
+ let _ = below;
113
+ open_directory(path)
114
+ }
115
+ }
116
+
117
+ impl Place {
118
+ /// Creates `leaf`, which must not exist yet.
119
+ pub(crate) fn create_new(&self, leaf: &str) -> io::Result<File> {
120
+ #[cfg(target_os = "linux")]
121
+ if let Some(dir) = &self.fd {
122
+ return linux::create_new(dir, leaf);
123
+ }
124
+ let mut options = OpenOptions::new();
125
+ options.write(true).create_new(true);
126
+ no_follow(&mut options);
127
+ options.open(self.path.join(leaf))
128
+ }
129
+
130
+ /// A new hidden file beside `leaf` to write its replacement into;
131
+ /// returns its name and the file.
132
+ pub(crate) fn staging(&self, leaf: &str) -> io::Result<(String, File)> {
133
+ static COUNTER: AtomicU64 = AtomicU64::new(0);
134
+ loop {
135
+ let n = COUNTER.fetch_add(1, Ordering::Relaxed);
136
+ let staged = format!(".{leaf}.ziperu-{}-{n}", std::process::id());
137
+ match self.create_new(&staged) {
138
+ Ok(file) => return Ok((staged, file)),
139
+ Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
140
+ Err(e) => return Err(e),
141
+ }
142
+ }
143
+ }
144
+
145
+ /// Renames `from` over `to`, both in this directory.
146
+ pub(crate) fn rename(&self, from: &str, to: &str) -> io::Result<()> {
147
+ #[cfg(target_os = "linux")]
148
+ if let Some(dir) = &self.fd {
149
+ return linux::rename(dir, from, to);
150
+ }
151
+ fs::rename(self.path.join(from), self.path.join(to))
152
+ }
153
+
154
+ /// Removes the file `leaf` from this directory.
155
+ pub(crate) fn remove(&self, leaf: &str) -> io::Result<()> {
156
+ #[cfg(target_os = "linux")]
157
+ if let Some(dir) = &self.fd {
158
+ return linux::unlink(dir, leaf);
159
+ }
160
+ fs::remove_file(self.path.join(leaf))
161
+ }
162
+ }
163
+
164
+ /// Opens without following a link at the path itself, where the OS can.
165
+ #[cfg(unix)]
166
+ pub(crate) fn no_follow(options: &mut OpenOptions) {
167
+ use std::os::unix::fs::OpenOptionsExt;
168
+ options.custom_flags(libc::O_NOFOLLOW);
169
+ }
170
+
171
+ #[cfg(not(unix))]
172
+ pub(crate) fn no_follow(_options: &mut OpenOptions) {}
173
+
174
+ /// A directory handle that `set_times` accepts: on Windows that means
175
+ /// backup semantics and write-attributes access, which a plain `open`
176
+ /// does not ask for.
177
+ #[cfg(windows)]
178
+ pub(crate) fn open_directory(path: &Path) -> io::Result<File> {
179
+ use std::os::windows::fs::OpenOptionsExt;
180
+ const FILE_WRITE_ATTRIBUTES: u32 = 0x0100;
181
+ const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
182
+ OpenOptions::new()
183
+ .access_mode(FILE_WRITE_ATTRIBUTES)
184
+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS)
185
+ .open(path)
186
+ }
187
+
188
+ #[cfg(not(windows))]
189
+ pub(crate) fn open_directory(path: &Path) -> io::Result<File> {
190
+ File::open(path)
191
+ }
192
+
193
+ #[cfg(target_os = "linux")]
194
+ mod linux {
195
+ use std::ffi::CString;
196
+ use std::fs::File;
197
+ use std::io;
198
+ use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
199
+ use std::os::unix::ffi::OsStrExt;
200
+ use std::path::Path;
201
+
202
+ const RESOLVE: u64 =
203
+ libc::RESOLVE_BENEATH | libc::RESOLVE_NO_SYMLINKS | libc::RESOLVE_NO_MAGICLINKS;
204
+
205
+ fn c_string(s: &[u8]) -> io::Result<CString> {
206
+ CString::new(s).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))
207
+ }
208
+
209
+ /// The destination as a handle, when `openat2` works here: None on a
210
+ /// kernel without it (ENOSYS) or where a sandbox refuses it (EPERM),
211
+ /// and then everything goes by path.
212
+ pub(super) fn open_root(root: &Path) -> Option<OwnedFd> {
213
+ let path = c_string(root.as_os_str().as_bytes()).ok()?;
214
+ // SAFETY: `path` is a valid NUL-terminated string for the call.
215
+ let fd = unsafe {
216
+ libc::open(
217
+ path.as_ptr(),
218
+ libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC,
219
+ )
220
+ };
221
+ if fd < 0 {
222
+ return None;
223
+ }
224
+ // SAFETY: `fd` was just returned by open and is owned by no one else.
225
+ let root = unsafe { OwnedFd::from_raw_fd(fd) };
226
+ // A probe of the destination itself tells whether openat2 is
227
+ // there at all.
228
+ match open_beneath(&root, "", libc::O_PATH | libc::O_DIRECTORY) {
229
+ Ok(_) => Some(root),
230
+ Err(_) => None,
231
+ }
232
+ }
233
+
234
+ /// `openat2(dir, below, flags, RESOLVE)`; `below` empty is `dir` itself.
235
+ /// Retried on EAGAIN, which the kernel returns when a rename elsewhere
236
+ /// raced the lookup.
237
+ pub(super) fn open_beneath(dir: &OwnedFd, below: &str, flags: i32) -> io::Result<OwnedFd> {
238
+ let below = if below.is_empty() { "." } else { below };
239
+ let path = c_string(below.as_bytes())?;
240
+ // SAFETY: open_how is plain integers, so all-zero is a valid value;
241
+ // the fields the kernel reads are set below.
242
+ let mut how: libc::open_how = unsafe { std::mem::zeroed() };
243
+ how.flags = (flags | libc::O_CLOEXEC) as u64;
244
+ how.resolve = RESOLVE;
245
+ for _ in 0..16 {
246
+ // SAFETY: `path` is NUL-terminated, `how` is a valid open_how
247
+ // whose size is passed with it, and `dir` is an open handle.
248
+ let fd = unsafe {
249
+ libc::syscall(
250
+ libc::SYS_openat2,
251
+ dir.as_raw_fd(),
252
+ path.as_ptr(),
253
+ &how as *const libc::open_how,
254
+ std::mem::size_of::<libc::open_how>(),
255
+ )
256
+ };
257
+ if fd >= 0 {
258
+ // SAFETY: the kernel returned a new descriptor we now own.
259
+ return Ok(unsafe { OwnedFd::from_raw_fd(fd as i32) });
260
+ }
261
+ let err = io::Error::last_os_error();
262
+ if err.raw_os_error() != Some(libc::EAGAIN) {
263
+ return Err(err);
264
+ }
265
+ }
266
+ Err(io::Error::from_raw_os_error(libc::EAGAIN))
267
+ }
268
+
269
+ pub(super) fn create_new(dir: &OwnedFd, leaf: &str) -> io::Result<File> {
270
+ let name = c_string(leaf.as_bytes())?;
271
+ // SAFETY: `name` is NUL-terminated and `dir` is an open handle.
272
+ let fd = unsafe {
273
+ libc::openat(
274
+ dir.as_raw_fd(),
275
+ name.as_ptr(),
276
+ libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC,
277
+ 0o666 as libc::c_uint,
278
+ )
279
+ };
280
+ if fd < 0 {
281
+ return Err(io::Error::last_os_error());
282
+ }
283
+ // SAFETY: the descriptor was just returned by openat and is ours.
284
+ Ok(File::from(unsafe { OwnedFd::from_raw_fd(fd) }))
285
+ }
286
+
287
+ pub(super) fn rename(dir: &OwnedFd, from: &str, to: &str) -> io::Result<()> {
288
+ let (from, to) = (c_string(from.as_bytes())?, c_string(to.as_bytes())?);
289
+ // SAFETY: both names are NUL-terminated and `dir` is an open handle.
290
+ let r =
291
+ unsafe { libc::renameat(dir.as_raw_fd(), from.as_ptr(), dir.as_raw_fd(), to.as_ptr()) };
292
+ if r == 0 {
293
+ Ok(())
294
+ } else {
295
+ Err(io::Error::last_os_error())
296
+ }
297
+ }
298
+
299
+ pub(super) fn unlink(dir: &OwnedFd, leaf: &str) -> io::Result<()> {
300
+ let name = c_string(leaf.as_bytes())?;
301
+ // SAFETY: `name` is NUL-terminated and `dir` is an open handle.
302
+ let r = unsafe { libc::unlinkat(dir.as_raw_fd(), name.as_ptr(), 0) };
303
+ if r == 0 {
304
+ Ok(())
305
+ } else {
306
+ Err(io::Error::last_os_error())
307
+ }
308
+ }
309
+ }
310
+
311
+ #[cfg(all(test, target_os = "linux"))]
312
+ mod tests {
313
+ use super::*;
314
+ use std::io::Write;
315
+ use std::os::unix::fs::symlink;
316
+
317
+ fn scratch(name: &str) -> PathBuf {
318
+ let dir = std::env::temp_dir().join(format!("ziperu-place-{name}-{}", std::process::id()));
319
+ let _ = fs::remove_dir_all(&dir);
320
+ fs::create_dir_all(dir.join("dest/a")).expect("scratch dirs");
321
+ fs::create_dir_all(dir.join("outside")).expect("scratch dirs");
322
+ dir
323
+ }
324
+
325
+ #[test]
326
+ fn a_link_on_the_way_is_refused_by_the_kernel() {
327
+ let dir = scratch("link");
328
+ let dest = dir.join("dest");
329
+ symlink(dir.join("outside"), dest.join("a/l")).expect("symlink");
330
+ let beneath = Beneath::new(&dest);
331
+ if !beneath.is_race_free() {
332
+ eprintln!("openat2 unavailable here; skipping");
333
+ return;
334
+ }
335
+ let err = beneath
336
+ .place(&dest.join("a/l"), "a/l")
337
+ .expect_err("refused");
338
+ assert!(is_link_error(&err), "{err}");
339
+ let err = beneath
340
+ .directory_handle(&dest.join("a/l"), "a/l")
341
+ .expect_err("refused");
342
+ assert!(is_link_error(&err), "{err}");
343
+ // `..` cannot climb out either.
344
+ let err = beneath.place(&dir, "a/../..").expect_err("refused");
345
+ assert!(is_link_error(&err), "{err}");
346
+ let _ = fs::remove_dir_all(&dir);
347
+ }
348
+
349
+ #[test]
350
+ fn a_directory_swapped_for_a_link_after_the_check_is_not_followed() {
351
+ let dir = scratch("swap");
352
+ let dest = dir.join("dest");
353
+ let beneath = Beneath::new(&dest);
354
+ if !beneath.is_race_free() {
355
+ eprintln!("openat2 unavailable here; skipping");
356
+ return;
357
+ }
358
+ // The directory is checked and opened, then swapped for a link.
359
+ let place = beneath
360
+ .place(&dest.join("a"), "a")
361
+ .expect("a real directory");
362
+ fs::rename(dest.join("a"), dest.join("moved")).expect("move aside");
363
+ symlink(dir.join("outside"), dest.join("a")).expect("symlink");
364
+ let mut file = place.create_new("x.txt").expect("created");
365
+ file.write_all(b"data").expect("written");
366
+ let (staged, _) = place.staging("x.txt").expect("staged");
367
+ place.rename(&staged, "x.txt").expect("renamed");
368
+ // Everything landed in the directory that was checked.
369
+ assert!(dest.join("moved/x.txt").exists());
370
+ assert!(fs::read_dir(dir.join("outside"))
371
+ .expect("outside")
372
+ .next()
373
+ .is_none());
374
+ // A fresh lookup refuses the link.
375
+ let err = beneath.place(&dest.join("a"), "a").expect_err("refused");
376
+ assert!(is_link_error(&err), "{err}");
377
+ let _ = fs::remove_dir_all(&dir);
378
+ }
379
+ }
data/ext/ziperu/src/rb.rs CHANGED
@@ -73,7 +73,7 @@ pub(crate) fn fill_new_string<R: io::Read, T>(
73
73
  if out.capacity() < size {
74
74
  return (out, Err(io::Error::other("could not allocate the String")));
75
75
  }
76
- // The String is new and unshared, with room for `size` bytes.
76
+ // SAFETY: the String is new and unshared, with room for `size` bytes.
77
77
  let base = unsafe { rb_sys::RSTRING_PTR(out.as_raw()) as usize };
78
78
  let mut filled = 0usize;
79
79
  let result = crate::gvl::maybe_without_gvl(needs_gvl, || -> io::Result<Option<T>> {
@@ -113,6 +113,19 @@ pub(crate) fn fill_new_string<R: io::Read, T>(
113
113
  (std::hint::black_box(out), result.map(|t| (filled, t)))
114
114
  }
115
115
 
116
+ /// What a Ruby `read(buf.len())` returned, copied into `buf`: the number
117
+ /// of bytes, 0 for nil (the end of the input).
118
+ pub fn copy_chunk(chunk: Option<RString>, buf: &mut [u8]) -> usize {
119
+ let Some(chunk) = chunk else {
120
+ return 0;
121
+ };
122
+ // SAFETY: the slice is copied out before any other Ruby call.
123
+ let bytes = unsafe { chunk.as_slice() };
124
+ let n = bytes.len().min(buf.len());
125
+ buf[..n].copy_from_slice(&bytes[..n]);
126
+ n
127
+ }
128
+
116
129
  /// Reads `reader` to its end into a new binary String, the first `size`
117
130
  /// bytes (the declared size) straight into its buffer (`fill_new_string`)
118
131
  /// and anything past them appended once the GVL is back.