1 //! Tools and utilities
3 //! This is a collection of small and useful tools.
8 use lazy_static
::lazy_static
;
10 use std
::fs
::{File, OpenOptions}
;
14 use std
::io
::ErrorKind
;
15 use std
::time
::Duration
;
18 use std
::os
::unix
::io
::{AsRawFd, FromRawFd, IntoRawFd, RawFd}
;
20 use std
::collections
::HashMap
;
22 use serde_json
::Value
;
26 pub mod wrapped_reader_stream
;
42 pub use process_locker
::*;
46 pub use file_logger
::*;
49 pub use broadcast_future
::*;
51 /// Macro to write error-handling blocks (like perl eval {})
55 /// # #[macro_use] extern crate proxmox_backup;
57 /// # let some_condition = false;
58 /// let result = try_block!({
59 /// if (some_condition) {
60 /// bail!("some error");
64 /// .map_err(|e| format_err!("my try block returned an error - {}", e));
68 macro_rules
! try_block
{
69 { $($token:tt)* }
=> {{ (|| -> Result<_,_> { $($token)* }
)() }}
73 /// The `BufferedRead` trait provides a single function
74 /// `buffered_read`. It returns a reference to an internal buffer. The
75 /// purpose of this traid is to avoid unnecessary data copies.
76 pub trait BufferedRead
{
77 /// This functions tries to fill the internal buffers, then
78 /// returns a reference to the available data. It returns an empty
79 /// buffer if `offset` points to the end of the file.
80 fn buffered_read(&mut self, offset
: u64) -> Result
<&[u8], Error
>;
83 /// Directly map a type into a binary buffer. This is mostly useful
84 /// for reading structured data from a byte stream (file). You need to
85 /// make sure that the buffer location does not change, so please
86 /// avoid vec resize while you use such map.
88 /// This function panics if the buffer is not large enough.
89 pub fn map_struct
<T
>(buffer
: &[u8]) -> Result
<&T
, Error
> {
90 if buffer
.len() < ::std
::mem
::size_of
::<T
>() {
91 bail
!("unable to map struct - buffer too small");
93 Ok(unsafe { & * (buffer.as_ptr() as *const T) }
)
96 /// Directly map a type into a mutable binary buffer. This is mostly
97 /// useful for writing structured data into a byte stream (file). You
98 /// need to make sure that the buffer location does not change, so
99 /// please avoid vec resize while you use such map.
101 /// This function panics if the buffer is not large enough.
102 pub fn map_struct_mut
<T
>(buffer
: &mut [u8]) -> Result
<&mut T
, Error
> {
103 if buffer
.len() < ::std
::mem
::size_of
::<T
>() {
104 bail
!("unable to map struct - buffer too small");
106 Ok(unsafe { &mut * (buffer.as_ptr() as *mut T) }
)
109 pub fn file_read_firstline
<P
: AsRef
<Path
>>(path
: P
) -> Result
<String
, Error
> {
111 let path
= path
.as_ref();
114 let file
= std
::fs
::File
::open(path
)?
;
116 use std
::io
::{BufRead, BufReader}
;
118 let mut reader
= BufReader
::new(file
);
120 let mut line
= String
::new();
122 let _
= reader
.read_line(&mut line
)?
;
125 }).map_err(|err
: Error
| format_err
!("unable to read {:?} - {}", path
, err
))
128 pub fn file_get_contents
<P
: AsRef
<Path
>>(path
: P
) -> Result
<Vec
<u8>, Error
> {
130 let path
= path
.as_ref();
134 }).map_err(|err
| format_err
!("unable to read {:?} - {}", path
, err
))
137 pub fn file_get_json
<P
: AsRef
<Path
>>(path
: P
, default: Option
<Value
>) -> Result
<Value
, Error
> {
139 let path
= path
.as_ref();
141 let raw
= match std
::fs
::read(path
) {
144 if err
.kind() == std
::io
::ErrorKind
::NotFound
{
145 if let Some(v
) = default {
149 bail
!("unable to read json {:?} - {}", path
, err
);
154 let data
= String
::from_utf8(raw
)?
;
155 let json
= serde_json
::from_str(&data
)?
;
157 }).map_err(|err
: Error
| format_err
!("unable to parse json from {:?} - {}", path
, err
))
160 /// Atomically write a file
162 /// We first create a temporary file, which is then renamed.
163 pub fn file_set_contents
<P
: AsRef
<Path
>>(
166 perm
: Option
<stat
::Mode
>,
167 ) -> Result
<(), Error
> {
168 file_set_contents_full(path
, data
, perm
, None
, None
)
171 /// Atomically write a file with owner and group
172 pub fn file_set_contents_full
<P
: AsRef
<Path
>>(
175 perm
: Option
<stat
::Mode
>,
176 owner
: Option
<unistd
::Uid
>,
177 group
: Option
<unistd
::Gid
>,
178 ) -> Result
<(), Error
> {
180 let path
= path
.as_ref();
182 // Note: we use mkstemp heŕe, because this worka with different
183 // processes, threads, and even tokio tasks.
184 let mut template
= path
.to_owned();
185 template
.set_extension("tmp_XXXXXX");
186 let (fd
, tmp_path
) = match unistd
::mkstemp(&template
) {
187 Ok((fd
, path
)) => (fd
, path
),
188 Err(err
) => bail
!("mkstemp {:?} failed: {}", template
, err
),
191 let tmp_path
= tmp_path
.as_path();
193 let mode
: stat
::Mode
= perm
.unwrap_or(stat
::Mode
::from(
194 stat
::Mode
::S_IRUSR
| stat
::Mode
::S_IWUSR
|
195 stat
::Mode
::S_IRGRP
| stat
::Mode
::S_IROTH
198 if let Err(err
) = stat
::fchmod(fd
, mode
) {
199 let _
= unistd
::unlink(tmp_path
);
200 bail
!("fchmod {:?} failed: {}", tmp_path
, err
);
203 if owner
!= None
|| group
!= None
{
204 if let Err(err
) = fchown(fd
, owner
, group
) {
205 let _
= unistd
::unlink(tmp_path
);
206 bail
!("fchown {:?} failed: {}", tmp_path
, err
);
210 use std
::os
::unix
::io
::FromRawFd
;
211 let mut file
= unsafe { File::from_raw_fd(fd) }
;
213 if let Err(err
) = file
.write_all(data
) {
214 let _
= unistd
::unlink(tmp_path
);
215 bail
!("write failed: {}", err
);
218 if let Err(err
) = std
::fs
::rename(tmp_path
, path
) {
219 let _
= unistd
::unlink(tmp_path
);
220 bail
!("Atomic rename failed for file {:?} - {}", path
, err
);
226 /// Create a file lock using fntl. This function allows you to specify
227 /// a timeout if you want to avoid infinite blocking.
228 pub fn lock_file
<F
: AsRawFd
>(
231 timeout
: Option
<Duration
>,
232 ) -> Result
<(), Error
> {
235 nix
::fcntl
::FlockArg
::LockExclusive
237 nix
::fcntl
::FlockArg
::LockShared
240 let timeout
= match timeout
{
242 nix
::fcntl
::flock(file
.as_raw_fd(), lockarg
)?
;
248 // unblock the timeout signal temporarily
249 let _sigblock_guard
= timer
::unblock_timeout_signal();
251 // setup a timeout timer
252 let mut timer
= timer
::Timer
::create(
253 timer
::Clock
::Realtime
,
254 timer
::TimerEvent
::ThisThreadSignal(timer
::SIGTIMEOUT
))?
;
256 timer
.arm(timer
::TimerSpec
::new()
257 .value(Some(timeout
))
258 .interval(Some(Duration
::from_millis(10))))?
;
260 nix
::fcntl
::flock(file
.as_raw_fd(), lockarg
)?
;
264 /// Open or create a lock file (append mode). Then try to
265 /// aquire a lock using `lock_file()`.
266 pub fn open_file_locked
<P
: AsRef
<Path
>>(path
: P
, timeout
: Duration
)
267 -> Result
<File
, Error
>
269 let path
= path
.as_ref();
271 match OpenOptions
::new()
277 Err(err
) => bail
!("Unable to open lock {:?} - {}",
280 match lock_file(&mut file
, true, Some(timeout
)) {
282 Err(err
) => bail
!("Unable to aquire lock {:?} - {}",
287 /// Split a file into equal sized chunks. The last chunk may be
288 /// smaller. Note: We cannot implement an `Iterator`, because iterators
289 /// cannot return a borrowed buffer ref (we want zero-copy)
290 pub fn file_chunker
<C
, R
>(
294 ) -> Result
<(), Error
>
295 where C
: FnMut(usize, &[u8]) -> Result
<bool
, Error
>,
299 const READ_BUFFER_SIZE
: usize = 4*1024*1024; // 4M
301 if chunk_size
> READ_BUFFER_SIZE { bail!("chunk size too large!"); }
303 let mut buf
= vec
![0u8; READ_BUFFER_SIZE
];
306 let mut file_pos
= 0;
309 let mut tmp
= &mut buf
[..];
310 // try to read large portions, at least chunk_size
311 while pos
< chunk_size
{
312 match file
.read(tmp
) {
313 Ok(0) => { eof = true; break; }
,
316 if pos
> chunk_size { break; }
319 Err(ref e
) if e
.kind() == ErrorKind
::Interrupted
=> { /* try again */ }
320 Err(e
) => bail
!("read chunk failed - {}", e
.to_string()),
324 while start
+ chunk_size
<= pos
{
325 if !(chunk_cb
)(file_pos
, &buf
[start
..start
+chunk_size
])? { break; }
326 file_pos
+= chunk_size
;
331 (chunk_cb
)(file_pos
, &buf
[start
..pos
])?
;
332 //file_pos += pos - start;
336 let rest
= pos
- start
;
338 let ptr
= buf
.as_mut_ptr();
339 unsafe { std::ptr::copy_nonoverlapping(ptr.add(start), ptr, rest); }
350 /// Returns the Unix uid/gid for the sepcified system user.
351 pub fn getpwnam_ugid(username
: &str) -> Result
<(libc
::uid_t
,libc
::gid_t
), Error
> {
352 let info
= unsafe { libc::getpwnam(std::ffi::CString::new(username).unwrap().as_ptr()) }
;
353 if info
== std
::ptr
::null_mut() {
354 bail
!("getwpnam '{}' failed", username
);
357 let info
= unsafe { *info }
;
359 Ok((info
.pw_uid
, info
.pw_gid
))
362 /// Creates directory at the provided path with specified ownership
364 /// Simply returns if the directory already exists.
365 pub fn create_dir_chown
<P
: AsRef
<Path
>>(
367 perm
: Option
<stat
::Mode
>,
368 owner
: Option
<unistd
::Uid
>,
369 group
: Option
<unistd
::Gid
>,
370 ) -> Result
<(), nix
::Error
>
372 let mode
: stat
::Mode
= perm
.unwrap_or(stat
::Mode
::from_bits_truncate(0o770));
374 let path
= path
.as_ref();
376 match nix
::unistd
::mkdir(path
, mode
) {
378 Err(nix
::Error
::Sys(nix
::errno
::Errno
::EEXIST
)) => {
384 unistd
::chown(path
, owner
, group
)?
;
389 /// Change ownership of an open file handle
392 owner
: Option
<nix
::unistd
::Uid
>,
393 group
: Option
<nix
::unistd
::Gid
>
394 ) -> Result
<(), Error
> {
396 // According to the POSIX specification, -1 is used to indicate that owner and group
397 // are not to be changed. Since uid_t and gid_t are unsigned types, we have to wrap
398 // around to get -1 (copied fron nix crate).
399 let uid
= owner
.map(Into
::into
).unwrap_or((0 as libc
::uid_t
).wrapping_sub(1));
400 let gid
= group
.map(Into
::into
).unwrap_or((0 as libc
::gid_t
).wrapping_sub(1));
402 let res
= unsafe { libc::fchown(fd, uid, gid) }
;
403 nix
::errno
::Errno
::result(res
)?
;
408 // Returns the hosts node name (UTS node name)
409 pub fn nodename() -> &'
static str {
412 static ref NODENAME
: String
= {
414 nix
::sys
::utsname
::uname()
426 pub fn json_object_to_query(data
: Value
) -> Result
<String
, Error
> {
428 let mut query
= url
::form_urlencoded
::Serializer
::new(String
::new());
430 let object
= data
.as_object().ok_or_else(|| {
431 format_err
!("json_object_to_query: got wrong data type (expected object).")
434 for (key
, value
) in object
{
436 Value
::Bool(b
) => { query.append_pair(key, &b.to_string()); }
437 Value
::Number(n
) => { query.append_pair(key, &n.to_string()); }
438 Value
::String(s
) => { query.append_pair(key, &s); }
439 Value
::Array(arr
) => {
442 Value
::Bool(b
) => { query.append_pair(key, &b.to_string()); }
443 Value
::Number(n
) => { query.append_pair(key, &n.to_string()); }
444 Value
::String(s
) => { query.append_pair(key, &s); }
445 _
=> bail
!("json_object_to_query: unable to handle complex array data types."),
449 _
=> bail
!("json_object_to_query: unable to handle complex data types."),
456 pub fn required_string_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<&'a
str, Error
> {
457 match param
[name
].as_str() {
459 None
=> bail
!("missing parameter '{}'", name
),
463 pub fn required_integer_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<i64, Error
> {
464 match param
[name
].as_i64() {
466 None
=> bail
!("missing parameter '{}'", name
),
470 pub fn required_array_param
<'a
>(param
: &'a Value
, name
: &str) -> Result
<Vec
<Value
>, Error
> {
471 match param
[name
].as_array() {
472 Some(s
) => Ok(s
.to_vec()),
473 None
=> bail
!("missing parameter '{}'", name
),
477 pub fn complete_file_name(arg
: &str, _param
: &HashMap
<String
, String
>) -> Vec
<String
> {
479 let mut result
= vec
![];
481 use nix
::fcntl
::OFlag
;
482 use nix
::sys
::stat
::Mode
;
483 use nix
::fcntl
::AtFlags
;
485 let mut dirname
= std
::path
::PathBuf
::from(if arg
.len() == 0 { "./" }
else { arg }
);
487 let is_dir
= match nix
::sys
::stat
::fstatat(libc
::AT_FDCWD
, &dirname
, AtFlags
::empty()) {
488 Ok(stat
) => (stat
.st_mode
& libc
::S_IFMT
) == libc
::S_IFDIR
,
493 if let Some(parent
) = dirname
.parent() {
494 dirname
= parent
.to_owned();
498 let mut dir
= match nix
::dir
::Dir
::openat(libc
::AT_FDCWD
, &dirname
, OFlag
::O_DIRECTORY
, Mode
::empty()) {
500 Err(_
) => return result
,
503 for item
in dir
.iter() {
504 if let Ok(entry
) = item
{
505 if let Ok(name
) = entry
.file_name().to_str() {
506 if name
== "." || name
== ".." { continue; }
507 let mut newpath
= dirname
.clone();
510 if let Ok(stat
) = nix
::sys
::stat
::fstatat(libc
::AT_FDCWD
, &newpath
, AtFlags
::empty()) {
511 if (stat
.st_mode
& libc
::S_IFMT
) == libc
::S_IFDIR
{
513 if let Some(newpath
) = newpath
.to_str() {
514 result
.push(newpath
.to_owned());
519 if let Some(newpath
) = newpath
.to_str() {
520 result
.push(newpath
.to_owned());
530 /// Scan directory for matching file names.
532 /// Scan through all directory entries and call `callback()` function
533 /// if the entry name matches the regular expression. This function
534 /// used unix `openat()`, so you can pass absolute or relative file
535 /// names. This function simply skips non-UTF8 encoded names.
536 pub fn scandir
<P
, F
>(
539 regex
: ®ex
::Regex
,
541 ) -> Result
<(), Error
>
542 where F
: FnMut(RawFd
, &str, nix
::dir
::Type
) -> Result
<(), Error
>,
543 P
: ?Sized
+ nix
::NixPath
,
545 for entry
in self::fs
::scan_subdir(dirfd
, path
, regex
)?
{
547 let file_type
= match entry
.file_type() {
548 Some(file_type
) => file_type
,
549 None
=> bail
!("unable to detect file type"),
552 callback(entry
.parent_fd(), unsafe { entry.file_name_utf8_unchecked() }
, file_type
)?
;
557 pub fn get_hardware_address() -> Result
<String
, Error
> {
559 static FILENAME
: &str = "/etc/ssh/ssh_host_rsa_key.pub";
561 let contents
= file_get_contents(FILENAME
)?
;
562 let digest
= md5
::compute(contents
);
564 Ok(format
!("{:0x}", digest
))
567 const HEX_CHARS
: &'
static [u8; 16] = b
"0123456789abcdef";
569 pub fn digest_to_hex(digest
: &[u8]) -> String
{
570 let mut buf
= Vec
::<u8>::with_capacity(digest
.len()*2);
572 for i
in 0..digest
.len() {
573 buf
.push(HEX_CHARS
[(digest
[i
] >> 4) as usize]);
574 buf
.push(HEX_CHARS
[(digest
[i
] & 0xf) as usize]);
577 unsafe { String::from_utf8_unchecked(buf) }
580 pub fn hex_to_digest(hex
: &str) -> Result
<[u8; 32], Error
> {
581 let mut digest
= [0u8; 32];
583 let bytes
= hex
.as_bytes();
585 if bytes
.len() != 64 { bail!("got wrong digest length."); }
588 if c
>= b'
0'
&& c
<= b'
9' { return Ok(c - b'0'); }
589 if c
>= b'a'
&& c
<= b'f' { return Ok(c - b'a' + 10); }
590 if c
>= b'A'
&& c
<= b'F' { return Ok(c - b'A' + 10); }
591 bail
!("found illegal hex character.");
595 for pair
in bytes
.chunks(2) {
596 if pos
>= digest
.len() { bail!("hex digest too long."); }
597 let h
= val(pair
[0])?
;
598 let l
= val(pair
[1])?
;
599 digest
[pos
] = (h
<<4)|l
;
603 if pos
!= digest
.len() { bail!("hex digest too short."); }
608 pub fn assert_if_modified(digest1
: &str, digest2
: &str) -> Result
<(), Error
> {
609 if digest1
!= digest2
{
610 bail
!("detected modified configuration - file changed by other user? Try again.");
615 /// Extract authentication cookie from cookie header.
616 /// We assume cookie_name is already url encoded.
617 pub fn extract_auth_cookie(cookie
: &str, cookie_name
: &str) -> Option
<String
> {
619 for pair
in cookie
.split('
;'
) {
621 let (name
, value
) = match pair
.find('
='
) {
622 Some(i
) => (pair
[..i
].trim(), pair
[(i
+ 1)..].trim()),
623 None
=> return None
, // Cookie format error
626 if name
== cookie_name
{
627 use url
::percent_encoding
::percent_decode
;
628 if let Ok(value
) = percent_decode(value
.as_bytes()).decode_utf8() {
629 return Some(value
.into());
631 return None
; // Cookie format error
639 pub fn join(data
: &Vec
<String
>, sep
: char) -> String
{
641 let mut list
= String
::new();
644 if list
.len() != 0 { list.push(sep); }
651 /// normalize uri path
653 /// Do not allow ".", "..", or hidden files ".XXXX"
654 /// Also remove empty path components
655 pub fn normalize_uri_path(path
: &str) -> Result
<(String
, Vec
<&str>), Error
> {
657 let items
= path
.split('
/'
);
659 let mut path
= String
::new();
660 let mut components
= vec
![];
663 if name
.is_empty() { continue; }
664 if name
.starts_with(".") {
665 bail
!("Path contains illegal components.");
669 components
.push(name
);
672 Ok((path
, components
))
675 pub fn fd_change_cloexec(fd
: RawFd
, on
: bool
) -> Result
<(), Error
> {
676 use nix
::fcntl
::{fcntl, F_GETFD, F_SETFD, FdFlag}
;
677 let mut flags
= FdFlag
::from_bits(fcntl(fd
, F_GETFD
)?
)
678 .ok_or_else(|| format_err
!("unhandled file flags"))?
; // nix crate is stupid this way...
679 flags
.set(FdFlag
::FD_CLOEXEC
, on
);
680 fcntl(fd
, F_SETFD(flags
))?
;
685 static mut SHUTDOWN_REQUESTED
: bool
= false;
687 pub fn request_shutdown() {
688 unsafe { SHUTDOWN_REQUESTED = true; }
689 crate::server
::server_shutdown();
693 pub fn shutdown_requested() -> bool
{
694 unsafe { SHUTDOWN_REQUESTED }
697 pub fn fail_on_shutdown() -> Result
<(), Error
> {
698 if shutdown_requested() {
699 bail
!("Server shutdown requested - aborting task");
704 /// Guard a raw file descriptor with a drop handler. This is mostly useful when access to an owned
705 /// `RawFd` is required without the corresponding handler object (such as when only the file
706 /// descriptor number is required in a closure which may be dropped instead of being executed).
707 pub struct Fd(pub RawFd
);
719 impl AsRawFd
for Fd
{
720 fn as_raw_fd(&self) -> RawFd
{
725 impl IntoRawFd
for Fd
{
726 fn into_raw_fd(mut self) -> RawFd
{
733 impl FromRawFd
for Fd
{
734 unsafe fn from_raw_fd(fd
: RawFd
) -> Self {
739 // wrap nix::unistd::pipe2 + O_CLOEXEC into something returning guarded file descriptors
740 pub fn pipe() -> Result
<(Fd
, Fd
), Error
> {
741 let (pin
, pout
) = nix
::unistd
::pipe2(nix
::fcntl
::OFlag
::O_CLOEXEC
)?
;
742 Ok((Fd(pin
), Fd(pout
)))
745 /// An easy way to convert types to Any
747 /// Mostly useful to downcast trait objects (see RpcEnvironment).
749 fn as_any(&self) -> &Any
;
752 impl<T
: Any
> AsAny
for T
{
753 fn as_any(&self) -> &Any { self }