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