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