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