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