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