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