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