]> git.proxmox.com Git - proxmox-backup.git/blame - src/tools.rs
garbage_collect: call fail_on_abort to abort GV when requested.
[proxmox-backup.git] / src / tools.rs
CommitLineData
51b499db
DM
1//! Tools and utilities
2//!
3//! This is a collection of small and useful tools.
6100071f
WB
4use std::any::Any;
5use std::collections::HashMap;
62ee2eb4 6use std::hash::BuildHasher;
365bb90f 7use std::fs::{File, OpenOptions};
43eeef28 8use std::io::ErrorKind;
6100071f 9use std::io::Read;
00ec8d16 10use std::os::unix::io::{AsRawFd, RawFd};
6100071f
WB
11use std::path::Path;
12use std::time::Duration;
365bb90f 13
f7d4e4b5 14use anyhow::{bail, format_err, Error};
af926291 15use serde_json::Value;
c5946faf 16use openssl::hash::{hash, DigestBytes, MessageDigest};
8a1028e0 17use percent_encoding::AsciiSet;
0fe5d605 18
f35197f4
WB
19use proxmox::tools::vec;
20
00ec8d16
WB
21pub use proxmox::tools::fd::Fd;
22
6100071f 23pub mod acl;
556eb70e 24pub mod async_io;
6ed25cbe 25pub mod borrow;
6100071f 26pub mod daemon;
b4d5787d 27pub mod fs;
4939255f 28pub mod format;
1685c2e3 29pub mod lru_cache;
daef93f4 30pub mod runtime;
6100071f
WB
31pub mod ticket;
32pub mod timer;
f1d99e3f
DM
33
34mod wrapped_reader_stream;
35pub use wrapped_reader_stream::*;
dcd033a5
DM
36
37mod std_channel_writer;
38pub use std_channel_writer::*;
39
2dcdd3b4 40pub mod xattr;
8cf6e764 41
a650f503
DM
42mod process_locker;
43pub use process_locker::*;
44
3b151414
DM
45mod file_logger;
46pub use file_logger::*;
47
490be29e
DM
48mod broadcast_future;
49pub use broadcast_future::*;
50
fded74d0 51/// The `BufferedRead` trait provides a single function
0a72e267
DM
52/// `buffered_read`. It returns a reference to an internal buffer. The
53/// purpose of this traid is to avoid unnecessary data copies.
fded74d0 54pub trait BufferedRead {
318564ac
DM
55 /// This functions tries to fill the internal buffers, then
56 /// returns a reference to the available data. It returns an empty
57 /// buffer if `offset` points to the end of the file.
0a72e267
DM
58 fn buffered_read(&mut self, offset: u64) -> Result<&[u8], Error>;
59}
60
51b499db
DM
61/// Directly map a type into a binary buffer. This is mostly useful
62/// for reading structured data from a byte stream (file). You need to
63/// make sure that the buffer location does not change, so please
64/// avoid vec resize while you use such map.
65///
66/// This function panics if the buffer is not large enough.
50ea4396 67pub fn map_struct<T>(buffer: &[u8]) -> Result<&T, Error> {
dc3de618
DM
68 if buffer.len() < ::std::mem::size_of::<T>() {
69 bail!("unable to map struct - buffer too small");
70 }
6100071f 71 Ok(unsafe { &*(buffer.as_ptr() as *const T) })
dc3de618
DM
72}
73
51b499db
DM
74/// Directly map a type into a mutable binary buffer. This is mostly
75/// useful for writing structured data into a byte stream (file). You
76/// need to make sure that the buffer location does not change, so
77/// please avoid vec resize while you use such map.
78///
79/// This function panics if the buffer is not large enough.
50ea4396 80pub fn map_struct_mut<T>(buffer: &mut [u8]) -> Result<&mut T, Error> {
dc3de618
DM
81 if buffer.len() < ::std::mem::size_of::<T>() {
82 bail!("unable to map struct - buffer too small");
83 }
6100071f 84 Ok(unsafe { &mut *(buffer.as_ptr() as *mut T) })
dc3de618
DM
85}
86
51b499db
DM
87/// Create a file lock using fntl. This function allows you to specify
88/// a timeout if you want to avoid infinite blocking.
1628a4c7
WB
89pub fn lock_file<F: AsRawFd>(
90 file: &mut F,
91 exclusive: bool,
92 timeout: Option<Duration>,
eb90c9e3 93) -> Result<(), Error> {
6100071f
WB
94 let lockarg = if exclusive {
95 nix::fcntl::FlockArg::LockExclusive
96 } else {
97 nix::fcntl::FlockArg::LockShared
98 };
1628a4c7
WB
99
100 let timeout = match timeout {
101 None => {
102 nix::fcntl::flock(file.as_raw_fd(), lockarg)?;
103 return Ok(());
104 }
105 Some(t) => t,
106 };
107
108 // unblock the timeout signal temporarily
109 let _sigblock_guard = timer::unblock_timeout_signal();
110
111 // setup a timeout timer
112 let mut timer = timer::Timer::create(
113 timer::Clock::Realtime,
6100071f
WB
114 timer::TimerEvent::ThisThreadSignal(timer::SIGTIMEOUT),
115 )?;
1628a4c7 116
6100071f
WB
117 timer.arm(
118 timer::TimerSpec::new()
119 .value(Some(timeout))
120 .interval(Some(Duration::from_millis(10))),
121 )?;
1628a4c7
WB
122
123 nix::fcntl::flock(file.as_raw_fd(), lockarg)?;
124 Ok(())
125}
365bb90f 126
51b499db
DM
127/// Open or create a lock file (append mode). Then try to
128/// aquire a lock using `lock_file()`.
6100071f 129pub fn open_file_locked<P: AsRef<Path>>(path: P, timeout: Duration) -> Result<File, Error> {
1628a4c7 130 let path = path.as_ref();
6100071f
WB
131 let mut file = match OpenOptions::new().create(true).append(true).open(path) {
132 Ok(file) => file,
133 Err(err) => bail!("Unable to open lock {:?} - {}", path, err),
134 };
28b96b56
DM
135 match lock_file(&mut file, true, Some(timeout)) {
136 Ok(_) => Ok(file),
6100071f 137 Err(err) => bail!("Unable to aquire lock {:?} - {}", path, err),
28b96b56 138 }
365bb90f
DM
139}
140
51b499db
DM
141/// Split a file into equal sized chunks. The last chunk may be
142/// smaller. Note: We cannot implement an `Iterator`, because iterators
143/// cannot return a borrowed buffer ref (we want zero-copy)
6100071f
WB
144pub fn file_chunker<C, R>(mut file: R, chunk_size: usize, mut chunk_cb: C) -> Result<(), Error>
145where
146 C: FnMut(usize, &[u8]) -> Result<bool, Error>,
147 R: Read,
43eeef28 148{
6100071f 149 const READ_BUFFER_SIZE: usize = 4 * 1024 * 1024; // 4M
43eeef28 150
6100071f
WB
151 if chunk_size > READ_BUFFER_SIZE {
152 bail!("chunk size too large!");
153 }
43eeef28 154
8ea3b1d1 155 let mut buf = vec::undefined(READ_BUFFER_SIZE);
43eeef28
DM
156
157 let mut pos = 0;
158 let mut file_pos = 0;
159 loop {
160 let mut eof = false;
161 let mut tmp = &mut buf[..];
6100071f 162 // try to read large portions, at least chunk_size
43eeef28
DM
163 while pos < chunk_size {
164 match file.read(tmp) {
6100071f
WB
165 Ok(0) => {
166 eof = true;
167 break;
168 }
43eeef28
DM
169 Ok(n) => {
170 pos += n;
6100071f
WB
171 if pos > chunk_size {
172 break;
173 }
43eeef28
DM
174 tmp = &mut tmp[n..];
175 }
176 Err(ref e) if e.kind() == ErrorKind::Interrupted => { /* try again */ }
5f0c2d56 177 Err(e) => bail!("read chunk failed - {}", e.to_string()),
43eeef28
DM
178 }
179 }
43eeef28
DM
180 let mut start = 0;
181 while start + chunk_size <= pos {
6100071f
WB
182 if !(chunk_cb)(file_pos, &buf[start..start + chunk_size])? {
183 break;
184 }
43eeef28
DM
185 file_pos += chunk_size;
186 start += chunk_size;
187 }
188 if eof {
189 if start < pos {
190 (chunk_cb)(file_pos, &buf[start..pos])?;
191 //file_pos += pos - start;
192 }
193 break;
194 } else {
195 let rest = pos - start;
196 if rest > 0 {
197 let ptr = buf.as_mut_ptr();
6100071f
WB
198 unsafe {
199 std::ptr::copy_nonoverlapping(ptr.add(start), ptr, rest);
200 }
43eeef28
DM
201 pos = rest;
202 } else {
203 pos = 0;
204 }
205 }
206 }
207
208 Ok(())
43eeef28 209}
0fe5d605 210
f5f13ebc 211pub fn json_object_to_query(data: Value) -> Result<String, Error> {
f5f13ebc
DM
212 let mut query = url::form_urlencoded::Serializer::new(String::new());
213
214 let object = data.as_object().ok_or_else(|| {
215 format_err!("json_object_to_query: got wrong data type (expected object).")
216 })?;
217
218 for (key, value) in object {
219 match value {
6100071f
WB
220 Value::Bool(b) => {
221 query.append_pair(key, &b.to_string());
222 }
223 Value::Number(n) => {
224 query.append_pair(key, &n.to_string());
225 }
226 Value::String(s) => {
227 query.append_pair(key, &s);
228 }
f5f13ebc
DM
229 Value::Array(arr) => {
230 for element in arr {
231 match element {
6100071f
WB
232 Value::Bool(b) => {
233 query.append_pair(key, &b.to_string());
234 }
235 Value::Number(n) => {
236 query.append_pair(key, &n.to_string());
237 }
238 Value::String(s) => {
239 query.append_pair(key, &s);
240 }
241 _ => bail!(
242 "json_object_to_query: unable to handle complex array data types."
243 ),
f5f13ebc
DM
244 }
245 }
246 }
247 _ => bail!("json_object_to_query: unable to handle complex data types."),
248 }
249 }
250
251 Ok(query.finish())
252}
253
0fe5d605 254pub fn required_string_param<'a>(param: &'a Value, name: &str) -> Result<&'a str, Error> {
6100071f 255 match param[name].as_str() {
0fe5d605
DM
256 Some(s) => Ok(s),
257 None => bail!("missing parameter '{}'", name),
258 }
259}
0d38dcb4 260
e17d5d86
DM
261pub fn required_string_property<'a>(param: &'a Value, name: &str) -> Result<&'a str, Error> {
262 match param[name].as_str() {
263 Some(s) => Ok(s),
264 None => bail!("missing property '{}'", name),
265 }
266}
267
0d38dcb4 268pub fn required_integer_param<'a>(param: &'a Value, name: &str) -> Result<i64, Error> {
6100071f 269 match param[name].as_i64() {
0d38dcb4
DM
270 Some(s) => Ok(s),
271 None => bail!("missing parameter '{}'", name),
f8dfbb45
DM
272 }
273}
274
e17d5d86
DM
275pub fn required_integer_property<'a>(param: &'a Value, name: &str) -> Result<i64, Error> {
276 match param[name].as_i64() {
277 Some(s) => Ok(s),
278 None => bail!("missing property '{}'", name),
279 }
280}
281
f8dfbb45 282pub fn required_array_param<'a>(param: &'a Value, name: &str) -> Result<Vec<Value>, Error> {
6100071f 283 match param[name].as_array() {
f8dfbb45
DM
284 Some(s) => Ok(s.to_vec()),
285 None => bail!("missing parameter '{}'", name),
0d38dcb4
DM
286 }
287}
383e8577 288
e17d5d86
DM
289pub fn required_array_property<'a>(param: &'a Value, name: &str) -> Result<Vec<Value>, Error> {
290 match param[name].as_array() {
291 Some(s) => Ok(s.to_vec()),
292 None => bail!("missing property '{}'", name),
293 }
294}
295
62ee2eb4 296pub fn complete_file_name<S: BuildHasher>(arg: &str, _param: &HashMap<String, String, S>) -> Vec<String> {
383e8577
DM
297 let mut result = vec![];
298
6100071f 299 use nix::fcntl::AtFlags;
383e8577
DM
300 use nix::fcntl::OFlag;
301 use nix::sys::stat::Mode;
383e8577 302
62ee2eb4 303 let mut dirname = std::path::PathBuf::from(if arg.is_empty() { "./" } else { arg });
383e8577
DM
304
305 let is_dir = match nix::sys::stat::fstatat(libc::AT_FDCWD, &dirname, AtFlags::empty()) {
306 Ok(stat) => (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR,
307 Err(_) => false,
308 };
309
310 if !is_dir {
311 if let Some(parent) = dirname.parent() {
312 dirname = parent.to_owned();
313 }
314 }
315
6100071f
WB
316 let mut dir =
317 match nix::dir::Dir::openat(libc::AT_FDCWD, &dirname, OFlag::O_DIRECTORY, Mode::empty()) {
318 Ok(d) => d,
319 Err(_) => return result,
320 };
383e8577
DM
321
322 for item in dir.iter() {
323 if let Ok(entry) = item {
324 if let Ok(name) = entry.file_name().to_str() {
6100071f
WB
325 if name == "." || name == ".." {
326 continue;
327 }
383e8577
DM
328 let mut newpath = dirname.clone();
329 newpath.push(name);
330
6100071f
WB
331 if let Ok(stat) =
332 nix::sys::stat::fstatat(libc::AT_FDCWD, &newpath, AtFlags::empty())
333 {
383e8577
DM
334 if (stat.st_mode & libc::S_IFMT) == libc::S_IFDIR {
335 newpath.push("");
336 if let Some(newpath) = newpath.to_str() {
337 result.push(newpath.to_owned());
338 }
339 continue;
6100071f 340 }
383e8577
DM
341 }
342 if let Some(newpath) = newpath.to_str() {
343 result.push(newpath.to_owned());
344 }
6100071f 345 }
383e8577
DM
346 }
347 }
348
349 result
350}
443f3743
DM
351
352/// Scan directory for matching file names.
353///
354/// Scan through all directory entries and call `callback()` function
355/// if the entry name matches the regular expression. This function
356/// used unix `openat()`, so you can pass absolute or relative file
357/// names. This function simply skips non-UTF8 encoded names.
358pub fn scandir<P, F>(
359 dirfd: RawFd,
121f18ef 360 path: &P,
443f3743 361 regex: &regex::Regex,
6100071f 362 mut callback: F,
443f3743 363) -> Result<(), Error>
6100071f
WB
364where
365 F: FnMut(RawFd, &str, nix::dir::Type) -> Result<(), Error>,
366 P: ?Sized + nix::NixPath,
443f3743 367{
121f18ef 368 for entry in self::fs::scan_subdir(dirfd, path, regex)? {
443f3743
DM
369 let entry = entry?;
370 let file_type = match entry.file_type() {
371 Some(file_type) => file_type,
372 None => bail!("unable to detect file type"),
373 };
443f3743 374
6100071f
WB
375 callback(
376 entry.parent_fd(),
377 unsafe { entry.file_name_utf8_unchecked() },
378 file_type,
379 )?;
443f3743
DM
380 }
381 Ok(())
382}
7e13b2d6 383
c5946faf
WB
384/// Shortcut for md5 sums.
385pub fn md5sum(data: &[u8]) -> Result<DigestBytes, Error> {
386 hash(MessageDigest::md5(), data).map_err(Error::from)
387}
388
7e13b2d6 389pub fn get_hardware_address() -> Result<String, Error> {
1631c54f 390 static FILENAME: &str = "/etc/ssh/ssh_host_rsa_key.pub";
7e13b2d6 391
e18a6c9e 392 let contents = proxmox::tools::fs::file_get_contents(FILENAME)?;
c5946faf 393 let digest = md5sum(&contents)?;
7e13b2d6 394
c5946faf 395 Ok(proxmox::tools::bin_to_hex(&digest))
7e13b2d6 396}
22968600 397
af2fddea
DM
398pub fn assert_if_modified(digest1: &str, digest2: &str) -> Result<(), Error> {
399 if digest1 != digest2 {
6100071f 400 bail!("detected modified configuration - file changed by other user? Try again.");
af2fddea
DM
401 }
402 Ok(())
403}
b9903d63
DM
404
405/// Extract authentication cookie from cookie header.
406/// We assume cookie_name is already url encoded.
407pub fn extract_auth_cookie(cookie: &str, cookie_name: &str) -> Option<String> {
b9903d63 408 for pair in cookie.split(';') {
b9903d63
DM
409 let (name, value) = match pair.find('=') {
410 Some(i) => (pair[..i].trim(), pair[(i + 1)..].trim()),
411 None => return None, // Cookie format error
412 };
413
414 if name == cookie_name {
8a1028e0 415 use percent_encoding::percent_decode;
b9903d63
DM
416 if let Ok(value) = percent_decode(value.as_bytes()).decode_utf8() {
417 return Some(value.into());
418 } else {
419 return None; // Cookie format error
420 }
421 }
422 }
423
424 None
425}
af53186e
DM
426
427pub fn join(data: &Vec<String>, sep: char) -> String {
af53186e
DM
428 let mut list = String::new();
429
430 for item in data {
62ee2eb4 431 if !list.is_empty() {
6100071f
WB
432 list.push(sep);
433 }
af53186e
DM
434 list.push_str(item);
435 }
436
437 list
438}
ff7049d4 439
002a191a
DM
440/// Detect modified configuration files
441///
442/// This function fails with a resonable error message if checksums do not match.
443pub fn detect_modified_configuration_file(digest1: &[u8;32], digest2: &[u8;32]) -> Result<(), Error> {
444 if digest1 != digest2 {
445 bail!("detected modified configuration - file changed by other user? Try again.");
446 }
447 Ok(())
448}
449
3578d99f
DM
450/// normalize uri path
451///
452/// Do not allow ".", "..", or hidden files ".XXXX"
453/// Also remove empty path components
454pub fn normalize_uri_path(path: &str) -> Result<(String, Vec<&str>), Error> {
3578d99f
DM
455 let items = path.split('/');
456
457 let mut path = String::new();
458 let mut components = vec![];
459
460 for name in items {
6100071f
WB
461 if name.is_empty() {
462 continue;
463 }
62ee2eb4 464 if name.starts_with('.') {
3578d99f
DM
465 bail!("Path contains illegal components.");
466 }
467 path.push('/');
468 path.push_str(name);
469 components.push(name);
470 }
471
472 Ok((path, components))
473}
474
ff7049d4 475pub fn fd_change_cloexec(fd: RawFd, on: bool) -> Result<(), Error> {
6100071f 476 use nix::fcntl::{fcntl, FdFlag, F_GETFD, F_SETFD};
ff7049d4
WB
477 let mut flags = FdFlag::from_bits(fcntl(fd, F_GETFD)?)
478 .ok_or_else(|| format_err!("unhandled file flags"))?; // nix crate is stupid this way...
479 flags.set(FdFlag::FD_CLOEXEC, on);
480 fcntl(fd, F_SETFD(flags))?;
481 Ok(())
482}
9136f857 483
9136f857
DM
484static mut SHUTDOWN_REQUESTED: bool = false;
485
486pub fn request_shutdown() {
6100071f
WB
487 unsafe {
488 SHUTDOWN_REQUESTED = true;
489 }
7a630df7 490 crate::server::server_shutdown();
9136f857
DM
491}
492
493#[inline(always)]
494pub fn shutdown_requested() -> bool {
495 unsafe { SHUTDOWN_REQUESTED }
496}
92da93b2
DM
497
498pub fn fail_on_shutdown() -> Result<(), Error> {
499 if shutdown_requested() {
500 bail!("Server shutdown requested - aborting task");
501 }
502 Ok(())
503}
d96bb7f1 504
efd1536e
WB
505// wrap nix::unistd::pipe2 + O_CLOEXEC into something returning guarded file descriptors
506pub fn pipe() -> Result<(Fd, Fd), Error> {
507 let (pin, pout) = nix::unistd::pipe2(nix::fcntl::OFlag::O_CLOEXEC)?;
508 Ok((Fd(pin), Fd(pout)))
509}
2edc341b
DM
510
511/// An easy way to convert types to Any
512///
513/// Mostly useful to downcast trait objects (see RpcEnvironment).
514pub trait AsAny {
dd5495d6 515 fn as_any(&self) -> &dyn Any;
2edc341b
DM
516}
517
518impl<T: Any> AsAny for T {
6100071f
WB
519 fn as_any(&self) -> &dyn Any {
520 self
521 }
2edc341b 522}
8a1028e0
WB
523
524/// This used to be: `SIMPLE_ENCODE_SET` plus space, `"`, `#`, `<`, `>`, backtick, `?`, `{`, `}`
525pub const DEFAULT_ENCODE_SET: &AsciiSet = &percent_encoding::CONTROLS // 0..1f and 7e
526 // The SIMPLE_ENCODE_SET adds space and anything >= 0x7e (7e itself is already included above)
527 .add(0x20)
528 .add(0x7f)
529 // the DEFAULT_ENCODE_SET added:
530 .add(b' ')
531 .add(b'"')
532 .add(b'#')
533 .add(b'<')
534 .add(b'>')
535 .add(b'`')
536 .add(b'?')
537 .add(b'{')
538 .add(b'}');