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