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